Module: Embulk

Defined in:
lib/embulk.rb,
lib/embulk/exec.rb,
lib/embulk/page.rb,
lib/embulk/error.rb,
lib/embulk/buffer.rb,
lib/embulk/column.rb,
lib/embulk/logger.rb,
lib/embulk/plugin.rb,
lib/embulk/runner.rb,
lib/embulk/schema.rb,
lib/embulk/version.rb,
lib/embulk/guess/csv.rb,
lib/embulk/file_input.rb,
lib/embulk/guess/gzip.rb,
lib/embulk/data_source.rb,
lib/embulk/file_output.rb,
lib/embulk/java_plugin.rb,
lib/embulk/guess_plugin.rb,
lib/embulk/input_plugin.rb,
lib/embulk/page_builder.rb,
lib/embulk/filter_plugin.rb,
lib/embulk/guess/charset.rb,
lib/embulk/guess/newline.rb,
lib/embulk/output_plugin.rb,
lib/embulk/parser_plugin.rb,
lib/embulk/decoder_plugin.rb,
lib/embulk/encoder_plugin.rb,
lib/embulk/java/bootstrap.rb,
lib/embulk/executor_plugin.rb,
lib/embulk/plugin_registry.rb,
lib/embulk/formatter_plugin.rb,
lib/embulk/java/time_helper.rb,
lib/embulk/data/package_data.rb,
lib/embulk/file_input_plugin.rb,
lib/embulk/command/embulk_run.rb,
lib/embulk/file_output_plugin.rb,
lib/embulk/command/embulk_example.rb,
lib/embulk/command/embulk_new_plugin.rb,
lib/embulk/command/embulk_selfupdate.rb,
lib/embulk/command/embulk_generate_bin.rb,
lib/embulk/command/embulk_migrate_plugin.rb,
lib/embulk/data/bundle/embulk/input/example.rb,
lib/embulk/data/bundle/embulk/filter/example.rb,
lib/embulk/data/bundle/embulk/output/example.rb

Defined Under Namespace

Modules: Exec, Filter, Guess, Impl, Input, Java, Output, Plugin, Type Classes: Buffer, Column, ConfigError, DataError, DataSource, DecoderPlugin, EmbulkRunner, EncoderPlugin, ExecutorPlugin, FileInput, FileInputPlugin, FileOutput, FileOutputPlugin, FilterPlugin, FormatterPlugin, GuessPlugin, InputPlugin, JavaPlugin, LineGuessPlugin, Logger, Migrator, OutputPlugin, PackageData, Page, PageBuilder, ParserPlugin, PluginLoadError, PluginManager, PluginRegistry, Schema, Slf4jAdapter, StandardLoggerAdapter, TextGuessPlugin

Constant Summary collapse

VERSION =
'0.7.10'
@@logger =

default logger

Logger.new(STDOUT)

Class Method Summary collapse

Class Method Details

.b(s) ⇒ Object



59
60
61
# File 'lib/embulk/command/embulk_generate_bin.rb', line 59

def self.b(s)
  s.force_encoding('ASCII-8BIT')
end

.check_latest_versionObject



86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/embulk/command/embulk_selfupdate.rb', line 86

def self.check_latest_version
  start_bintray_http do |http|
    response = http.get('/embulk/maven/embulk/_latestVersion')
    if response.code != "302"
      raise "Expected response code 302 Found but got #{response.code}"
    end
    location = response["Location"].to_s
    m = /(\d+\.\d+[^\/]+)/.match(location)
    unless m
      raise "Cound not find version number in Location header '#{location}'"
    end
    return m[1]
  end
end

.check_target_version(version = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/embulk/command/embulk_selfupdate.rb', line 101

def self.check_target_version(version=nil)
  start_bintray_http do |http|
    response = http.get("/embulk/maven/embulk/#{version}")
    if response.code == "404"
      return nil
    elsif response.code != "200"
      raise "Unexpected response code: #{response.code}"
    else
      return version
    end
  end
end

.create_example(path) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/embulk/command/embulk_example.rb', line 2

def self.create_example(path)
  require 'fileutils'
  require 'zlib'

  puts "  Creating #{path}/"
  FileUtils.mkdir_p File.join(path, 'csv')
  puts "  Creating #{path}/csv/"

  puts "  Creating #{path}/csv/sample_01.csv.gz"
  Zlib::GzipWriter.open(File.join(path, 'csv', 'sample_01.csv.gz')) do |f|
    f.write "id,account,time,purchase,comment\n1,32864,2015-01-27 19:23:49,20150127,embulk\n2,14824,2015-01-27 19:01:23,20150127,embulk jruby\n3,27559,2015-01-28 02:20:02,20150128,\"Embulk \"\"csv\"\" parser plugin\"\n4,11270,2015-01-29 11:54:36,20150129,NULL\n"
  end

  puts "  Creating #{path}/example.yml"
  File.open(File.join(path, 'example.yml'), 'w') do |f|
    f.write "in:\ntype: file\npath_prefix: \"\#{File.expand_path File.join(path, 'csv', 'sample_')}\"\nout:\ntype: stdout\n"
  end
end

.default_gem_homeObject



307
308
309
310
311
312
313
314
315
316
# File 'lib/embulk/command/embulk_run.rb', line 307

def self.default_gem_home
  if RUBY_PLATFORM =~ /java/i
    user_home = java.lang.System.properties["user.home"]
  end
  user_home ||= ENV['HOME']
  unless user_home
    raise "HOME environment variable is not set."
  end
  File.expand_path File.join(user_home, '.embulk', Gem.ruby_engine, RbConfig::CONFIG['ruby_version'])
end

.fix_gem_ruby_pathObject



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/embulk/command/embulk_run.rb', line 320

def self.fix_gem_ruby_path
  # Oveerride Gem.ruby method so that rubygems can execute ruby command (as another process).
  # By default, Gem.ruby uses "java -jar jar_path" command. However, it doesn't work because
  # Main-Class is overwritten to org.embulk.cli.Main. Here fixes it to use
  # "java -cp jar_path org.jruby.main" instead.

  jar, resource = __FILE__.split("!", 2)
  jar_uri = URI.parse(jar).path rescue jar

  manifest = File.read("#{jar_uri}!/META-INF/MANIFEST.MF") rescue ""
  m = /Main-Class: ([^\r\n]+)/.match(manifest)
  if m && m[1] != "org.jruby.Main"
    # Main-Class is not jruby
    Gem.define_singleton_method(:ruby) do
      "java -cp #{jar_path(jar_uri)} org.jruby.Main"
    end
  end
end

.generate_bin(options = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
# File 'lib/embulk/command/embulk_generate_bin.rb', line 2

def self.generate_bin(options={})
  jruby_jar_path = org.jruby.Main.java_class.protection_domain.code_source.location.to_s
  if __FILE__ =~ /^(?:classpath|uri:classloader):/ || __FILE__.include?('!/')
    resource_class = org.embulk.command.Runner.java_class
    ruby_script_path = resource_class.resource("/embulk/command/embulk.rb").to_s
  else
    ruby_script_path = File.join(File.dirname(__FILE__), 'embulk.rb')
  end
  java_home = java.lang.System.properties['java.home']

  generate_bin_data(jruby_jar_path, ruby_script_path, options.merge(java_home: java_home))
end

.generate_bin_data(jruby_jar_path, ruby_script_path, options = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/embulk/command/embulk_generate_bin.rb', line 15

def self.generate_bin_data(jruby_jar_path, ruby_script_path, options={})
  if java_home = options[:java_home]
    java_home_script = %{export JAVA_HOME='#{java_home}'}
    java_path = %{"$JAVA_HOME"/bin/java}
  else
    java_home_script = %{}
    java_path = %{java}
  end

  # TODO parse -D options to set them to java
  shell_script = "#!/bin/sh\n=begin 2>/dev/null\n\#{java_home_script}\nexec \#{java_path} -classpath \"$0\" org.jruby.Main \"$0\" \"$@\"\nexit 127\n=end\n"

  if options[:bundle_path] == :here
    bundle_path_script = %{ENV['EMBULK_BUNDLE_PATH'] = File.expand_path('..', File.dirname(__FILE__))}
  elsif path = options[:bundle_path]
    bundle_path_script = %{ENV['EMBULK_BUNDLE_PATH'] = '#{path}'}
  else
    bundle_path_script = b ''
  end

  ruby_init_script = b "\#{bundle_path_script}\nENV.delete 'GEM_HOME'\nENV.delete 'GEM_PATH'\n"

  ruby_script = b(File.read(ruby_script_path))
  if i = ruby_script.index(b("\n__END__\n"))
    # delete contents after __END__
    ruby_script = ruby_script[0, i]
  end

  jruby_jar = b(File.read(jruby_jar_path))

  data = shell_script << ruby_init_script + ruby_script << b("\n__END__\n") << jruby_jar
end

.lib_path(path) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/embulk.rb', line 5

def self.lib_path(path)
  path = '' if path == '/'
  jar, resource = __FILE__.split("!", 2)
  if resource
    lib = resource.split("/")[0..-2].join("/")
    "#{jar}!#{lib}/#{path}"
  elsif __FILE__ =~ /^(?:classpath|uri:classloader):/
    lib = __FILE__.split("/")[0..-2].join("/")
    "#{lib}/#{path}"
  else
    lib = File.expand_path File.dirname(__FILE__)
    File.join(lib, *path.split("/"))
  end
end

.loggerObject



144
145
146
# File 'lib/embulk/logger.rb', line 144

def self.logger
  @@logger
end

.logger=(logger) ⇒ Object



148
149
150
# File 'lib/embulk/logger.rb', line 148

def self.logger=(logger)
  @@logger = logger
end

.migrate_java_plugin(migrator, from_ver) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/embulk/command/embulk_migrate_plugin.rb', line 38

def self.migrate_java_plugin(migrator, from_ver)
  if from_ver < version("0.7.0")
    # rename CommitReport to TaskReport
    migrator.replace("**/*.java", /(CommitReport)/, "TaskReport")
    migrator.replace("**/*.java", /(commitReport)/, "taskReport")
  end

  if migrator.match("gradle/wrapper/gradle-wrapper.properties", /gradle-2\.[12345]\W+/)
    # gradle < 2.6
    require 'embulk/data/package_data'
    data = PackageData.new("new", migrator.path)
    migrator.write "gradle/wrapper/gradle-wrapper.jar", data.bincontent("java/gradle/wrapper/gradle-wrapper.jar")
    migrator.write "gradle/wrapper/gradle-wrapper.properties", data.content("java/gradle/wrapper/gradle-wrapper.properties")
  end

  #
  # add rules...
  ##

  # update version at the end
  migrator.replace("**/build.gradle", /org\.embulk:embulk-(?:core|standards):([\d\.]+)?/, Embulk::VERSION)
end

.migrate_plugin(path) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/embulk/command/embulk_migrate_plugin.rb', line 2

def self.migrate_plugin(path)
  migrator = Migrator.new(path)

  if ms = migrator.match("**/build.gradle", /org\.embulk:embulk-core:([\d\.]+)?/)
    lang = :java
    from_ver = version(ms[0][1])
    puts "Detected Java plugin for Embulk #{from_ver}..."

  elsif ms = migrator.match("**/*.gemspec", /add_(?:development_)?dependency\s+\W+embulk\W+\s+([\d\.]+)\W+/)
    lang = :ruby
    from_ver = version(ms[0][1])
    puts "Detected Ruby plugin for Embulk #{from_ver}..."

  elsif ms = migrator.match("**/*.gemspec", /embulk-/)
    lang = :ruby
    from_ver = version("0.1.0")
    puts "Detected Ruby plugin for unknown Embulk version..."

  else
    raise "Failed to detect plugin language and dependency version"
  end

  case lang
  when :java
    migrate_java_plugin(migrator, from_ver)
  when :ruby
    migrate_ruby_plugin(migrator, from_ver)
  end

  if migrator.modified_files.empty?
    puts "Done. No files are modified."
  else
    puts "Done. Please check modifieid files."
  end
end

.migrate_ruby_plugin(migrator, from_ver) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/embulk/command/embulk_migrate_plugin.rb', line 61

def self.migrate_ruby_plugin(migrator, from_ver)
  #
  # add rules...
  ##

  migrator.write(".ruby-version", "jruby-9.0.0.0")

  # update version at the end
  if from_ver <= version("0.1.0")
    # add add_development_dependency
    migrator.insert_line("**/*.gemspec", /([ \t]*\w+)\.add_development_dependency/) {|m|
      "#{m[1]}.add_development_dependency 'embulk', ['~> #{Embulk::VERSION}']"
    }
  else
    migrator.replace("**/*.gemspec", /add_(?:development_)?dependency\s+\W+embulk\W+\s+([\d\.]+)\W+/, Embulk::VERSION)
  end
end

.new_bundle(path, bundle_path) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/embulk/command/embulk_run.rb', line 374

def self.new_bundle(path, bundle_path)
  require 'fileutils'
  require 'rubygems/gem_runner'

  if File.exists?(path)
    error = "'#{path}' already exists."
    STDERR.puts error
    raise SystemExit.new(1, error)
  end

  puts "Initializing #{path}..."
  FileUtils.mkdir_p path
  begin
    success = false

    # copy embulk/data/bundle/ contents
    require 'embulk/data/package_data'
    pkg = PackageData.new("bundle", path)
    %w[Gemfile .ruby-version .bundle/config embulk/input/example.rb embulk/output/example.rb embulk/filter/example.rb].each do |file|
      pkg.cp(file, file)
    end

    # run the first bundle-install
    Dir.chdir(path) do
      run_bundler(['install', '--path', bundle_path || "."])
    end

    success = true
  rescue Gem::SystemExitException => e
    raise e if e.exit_code != 0
    success = true
  ensure
    FileUtils.rm_rf path unless success
  end
end

.new_plugin(name, language, category) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/embulk/command/embulk_new_plugin.rb', line 2

def self.new_plugin(name, language, category)
  require 'embulk/data/package_data'
  require 'embulk/version'
  require 'fileutils'

  embulk_category = category
  embulk_category = :input if category == :file_input
  embulk_category = :output if category == :file_output

  name = name.gsub(/[^a-zA-Z0-9_]+/, '_')  # replace '-' to '_'

  full_project_name = "embulk-#{embulk_category}-#{name}"
  plugin_dir = "lib/embulk"
  plugin_path = "#{plugin_dir}/#{embulk_category}/#{name}.rb"

  if File.exist?(full_project_name)
    raise "./#{full_project_name} already exists. Please delete it first."
  end
  FileUtils.mkdir_p(full_project_name)

  puts "Creating #{full_project_name}/"

  success = false
  begin
    #
    # Generate gemspec
    #
    author = `git config user.name`.strip rescue ""
    author = "YOUR_NAME" if author.empty?
    email = `git config user.email`.strip rescue ""
    email = "YOUR_NAME" if email.empty?

    # variables used in erb templates
    ruby_class_name = name.split('_').map {|a| a.capitalize }.join
    java_iface_name = category.to_s.split('_').map {|a| a.capitalize }.join
    java_class_name = name.split('_').map {|a| a.capitalize }.join + java_iface_name + "Plugin"
    java_package_name = "org.embulk.#{embulk_category}.#{name}"
    display_name = name.split('_').map {|a| a.capitalize }.join(' ')
    display_category = category.to_s.gsub('_', ' ')

    extra_guess_erb = {}

    case category
    when :input
      description = %[Loads records from #{display_name}.]
    when :file_input
      description = %[Reads files stored on #{display_name}.]
    when :parser
      description = %[Parses #{display_name} files read by other file input plugins.]
      extra_guess_erb["ruby/parser_guess.rb.erb"] = "#{plugin_dir}/guess/#{name}.rb"
    when :decoder
      description = %[Decodes #{display_name}-encoded files read by other file input plugins.]
      extra_guess_erb["ruby/decoder_guess.rb.erb"] = "#{plugin_dir}/guess/#{name}.rb"
    when :output
      description = %[Dumps records to #{display_name}.]
    when :file_output
      description = %[Stores files on #{display_name}.]
    when :formatter
      description = %[Formats #{display_name} files for other file output plugins.]
    when :encoder
      description = %[Encodes files using #{display_name} for other file output plugins.]
    when :filter
      description = %[#{display_name}]
    end

    #
    # Generate project repository
    #
    pkg = Embulk::PackageData.new("new", full_project_name, binding())

    pkg.cp_erb("README.md.erb", "README.md")
    pkg.cp("LICENSE.txt", "LICENSE.txt")
    pkg.cp_erb("gitignore.erb", ".gitignore")

    case language
    when :ruby
      pkg.cp("ruby/Rakefile", "Rakefile")
      pkg.cp("ruby/Gemfile", "Gemfile")
      pkg.cp("ruby/.ruby-version", ".ruby-version")
      pkg.cp_erb("ruby/gemspec.erb", "#{full_project_name}.gemspec")
      pkg.cp_erb("ruby/#{category}.rb.erb", plugin_path)

    when :java
      pkg.cp("java/gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.jar")
      pkg.cp("java/gradle/wrapper/gradle-wrapper.properties", "gradle/wrapper/gradle-wrapper.properties")
      pkg.cp("java/gradlew.bat", "gradlew.bat")
      pkg.cp("java/gradlew", "gradlew")
      pkg.set_executable("gradlew")
      pkg.cp_erb("java/build.gradle.erb", "build.gradle")
      pkg.cp_erb("java/plugin_loader.rb.erb", plugin_path)
      pkg.cp_erb("java/#{category}.java.erb", "src/main/java/#{java_package_name.gsub(/\./, '/')}/#{java_class_name}.java")
      pkg.cp_erb("java/test.java.erb", "src/test/java/#{java_package_name.gsub(/\./, '/')}/Test#{java_class_name}.java")
    end

    extra_guess_erb.each_pair do |erb,dest|
      pkg.cp_erb(erb, dest)
    end

    puts ""
    puts "Plugin template is successfully generated."

    case language
    when :ruby
      puts "Next steps:"
      puts ""
      puts "  $ cd #{full_project_name}"
      puts "  $ bundle install                      # install one using rbenv & rbenv-build"
      puts "  $ bundle exec rake                    # build gem to be released"
      puts "  $ bundle exec embulk run config.yml   # you can run plugin using this command"
    when :java
      puts "Next steps:"
      puts ""
      puts "  $ cd #{full_project_name}"
      puts "  $ ./gradlew package"
    end

    success = true
    puts ""
  ensure
    FileUtils.rm_rf full_project_name unless success
  end
end


459
460
461
462
463
464
465
466
467
468
# File 'lib/embulk/command/embulk_run.rb', line 459

def self.print_exception(ex)
  if ex.respond_to?(:to_java) && ex.is_a?(java.lang.Throwable)
    ex.to_java.printStackTrace(java.lang.System.out)
  else
    puts "#{ex.to_s}"
    ex.backtrace.each do |bt|
      puts "    #{bt}"
    end
  end
end

.require_classpathObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/embulk.rb', line 20

def self.require_classpath
  if __FILE__.include?("!")
    # single jar. __FILE__ should point path/to/embulk.jar!/embulk.rb
    # which means that embulk.jar is already loaded in this JVM.

  elsif __FILE__ =~ /^(?:classpath|uri:classloader):/
    # already in classpath

  else
    # gem package. __FILE__ should point path/to/embulk/lib/embulk.rb
    # that requires here to load ../classpath/*.jar to start EmbulkEmbed.
    gem_root = File.expand_path('..', File.dirname(__FILE__))
    classpath_dir = File.join(gem_root, "classpath")
    jars = Dir.entries(classpath_dir).select{|f| f =~ /\.jar$/ }.sort
    jars.each do |jar|
      require File.join(classpath_dir, jar)
    end
  end
end

.run(argv) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/embulk/command/embulk_run.rb', line 4

def self.run(argv)
  # reset context class loader set by org.jruby.Main.main to nil. embulk manages
  # multiple classloaders. default classloader should be Plugin.class.getClassloader().
  java.lang.Thread.current_thread.set_context_class_loader(nil)

  # Gem.path is called when GemRunner installs a gem with native extension.
  # Running extconf.rb fails without this hack.
  fix_gem_ruby_path

  require 'embulk/version'

  i = argv.find_index {|arg| arg !~ /^\-/ }
  unless i
    if argv.include?('--version')
      puts "embulk #{Embulk::VERSION}"
      system_exit_success
    end
    usage nil
  end
  subcmd = argv.slice!(i).to_sym

  require 'java'
  require 'optparse'
  op = OptionParser.new
  op.version = Embulk::VERSION

  puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: Embulk v#{Embulk::VERSION}"

  plugin_paths = []
  load_paths = []
  classpaths = []
  classpath_separator = java.io.File.pathSeparator

  options = {
    system_config: {}
  }

  java_embed_ops = lambda do
    op.separator ""
    op.separator "  Other options:"
    op.on('-l', '--log PATH', 'Output log messages to a file (default: -)') do |path|
      options[:system_config][:log_path] = path
    end
    op.on('-l', '--log-level LEVEL', 'Log level (error, warn, info, debug or trace)') do |level|
      options[:system_config][:log_level] = level
    end
    op.on('-X KEY=VALUE', 'Add a performance system config') do |kv|
      k, v = kv.split('=', 2)
      v ||= "true"
      options[:system_config][k] = v
    end
  end

  plugin_load_ops = lambda do
    op.separator ""
    op.separator "  Plugin load options:"
    op.on('-L', '--load PATH', 'Add a local plugin path') do |plugin_path|
      plugin_paths << plugin_path
    end
    op.on('-I', '--load-path PATH', 'Add ruby script directory path ($LOAD_PATH)') do |load_path|
      load_paths << load_path
    end
    op.on('-C', '--classpath PATH', "Add java classpath separated by #{classpath_separator} (CLASSPATH)") do |classpath|
      classpaths.concat classpath.split(classpath_separator)
    end
    op.on('-b', '--bundle BUNDLE_DIR', 'Path to a Gemfile directory (create one using "embulk mkbundle" command)') do |path|
      # only for help message. implemented at lib/embulk/command/embulk_bundle.rb
    end
  end

  case subcmd
  when :run
    op.banner = "Usage: run <config.yml>"
    op.separator "  Options:"
    op.on('-r', '--resume-state PATH', 'Path to a file to write or read resume state') do |path|
      options[:resume_state_path] = path
    end
    op.on('-o', '--output PATH', 'Path to a file to write the next configuration') do |path|
      options[:next_config_output_path] = path
    end
    plugin_load_ops.call
    java_embed_ops.call
    args = 1..1

  when :cleanup
    op.banner = "Usage: cleanup <config.yml>"
    op.separator "  Options:"
    op.on('-r', '--resume-state PATH', 'Path to a file to write or read resume state') do |path|
      options[:resume_state_path] = path
    end
    plugin_load_ops.call
    java_embed_ops.call
    args = 1..1

  when :preview
    op.banner = "Usage: preview <config.yml>"
    op.separator "  Options:"
    op.on('-G', '--vertical', "Use vertical output format", TrueClass) do |b|
      options[:format] = "vertical"
    end
    plugin_load_ops.call
    java_embed_ops.call
    args = 1..1

  when :guess
    op.banner = "Usage: guess <partial-config.yml>"
    op.separator "  Options:"
    op.on('-o', '--output PATH', 'Path to a file to write the guessed configuration') do |path|
      options[:next_config_output_path] = path
    end
    op.on('-g', '--guess NAMES', "Comma-separated list of guess plugin names") do |names|
      (options[:system_config][:guess_plugins] ||= []).concat names.split(",")  # TODO
    end
    plugin_load_ops.call
    java_embed_ops.call
    args = 1..1

  when :mkbundle
    op.banner = "Usage: mkbundle <directory> [--path PATH]"
    op.separator "  Options:"
    op.on('--path PATH', 'Relative path from <directory> for the location to install gems to (e.g. --path shared/bundle).') do |path|
      options[:bundle_path] = path
    end
    op.separator "\n\"mkbundle\" creates a new a plugin bundle directory. You can install\nplugins (gems) to the directory instead of ~/.embulk.\n\nSee generated <directory>/Gemfile to install plugins to the directory.\nUse -b, --bundle BUNDLE_DIR option to use it:\n\n  $ embulk mkbundle ./dir                # create bundle directory\n  $ (cd dir && vi Gemfile && embulk bundle)   # update plugin list\n  $ embulk guess -b ./dir ...            # guess using bundled plugins\n  $ embulk run   -b ./dir ...            # run using bundled plugins\n\n    EOF\n    args = 1..1\n\n  when :bundle\n    if argv[0] == 'new'\n      usage nil if argv.length != 2\n      new_bundle(argv[1], nil)\n      STDERR.puts \"'embulk bundle new' is deprecated. This will be removed in future release. Please use 'embulk mkbundle' instead.\"\n    else\n      run_bundler(argv)\n    end\n    system_exit_success\n\n  when :gem\n    require 'rubygems/gem_runner'\n    Gem::GemRunner.new.run argv\n    system_exit_success\n\n  when :new\n    op.banner = \"Usage: new <category> <name>\" + %[\ncategories:\n  ruby-input                 Ruby record input plugin    (like \"mysql\")\n  ruby-output                Ruby record output plugin   (like \"mysql\")\n  ruby-filter                Ruby record filter plugin   (like \"add-hostname\")\n  #ruby-file-input           Ruby file input plugin      (like \"ftp\")          # not implemented yet [#21]\n  #ruby-file-output          Ruby file output plugin     (like \"ftp\")          # not implemented yet [#22]\n  ruby-parser                Ruby file parser plugin     (like \"csv\")\n  ruby-formatter             Ruby file formatter plugin  (like \"csv\")\n  #ruby-decoder              Ruby file decoder plugin    (like \"gzip\")         # not implemented yet [#31]\n  #ruby-encoder              Ruby file encoder plugin    (like \"gzip\")         # not implemented yet [#32]\n  java-input                 Java record input plugin    (like \"mysql\")\n  java-output                Java record output plugin   (like \"mysql\")\n  java-filter                Java record filter plugin   (like \"add-hostname\")\n  java-file-input            Java file input plugin      (like \"ftp\")\n  java-file-output           Java file output plugin     (like \"ftp\")\n  java-parser                Java file parser plugin     (like \"csv\")\n  java-formatter             Java file formatter plugin  (like \"csv\")\n  java-decoder               Java file decoder plugin    (like \"gzip\")\n  java-encoder               Java file encoder plugin    (like \"gzip\")\n\nexamples:\n  new ruby-output hbase\n  new ruby-filter int-to-string\n]\n    args = 2..2\n\n  when :migrate\n    op.banner = \"Usage: migrate <directory>\"\n    args = 1..1\n\n  when :selfupdate\n    op.on('-f', \"Skip corruption check\", TrueClass) do |b|\n      options[:force] = true\n    end\n    args = 0..1\n\n  when :example\n    args = 0..1\n\n  when :exec\n    exec(*argv)\n    exit 127\n\n  when :irb\n    require 'irb'\n    IRB.start\n    system_exit_success\n\n  else\n    usage \"Unknown subcommand \#{subcmd.to_s.dump}.\"\n  end\n\n  begin\n    op.parse!(argv)\n    unless args.include?(argv.length)\n      usage_op op, nil\n    end\n  rescue => e\n    usage_op op, e.to_s\n  end\n\n  case subcmd\n  when :example\n    require 'embulk/command/embulk_example'\n    path = ARGV[0] || \"embulk-example\"\n    puts \"Creating \#{path} directory...\"\n    Embulk.create_example(path)\n    puts \"\"\n    puts \"Run following subcommands to try embulk:\"\n    puts \"\"\n    puts \"   1. embulk guess \#{File.join(path, 'example.yml')} -o config.yml\"\n    puts \"   2. embulk preview config.yml\"\n    puts \"   3. embulk run config.yml\"\n    puts \"\"\n\n  when :new\n    lang_cate = ARGV[0]\n    name = ARGV[1]\n\n    language, category = case lang_cate\n      when \"java-input\"       then [:java, :input]\n      when \"java-output\"      then [:java, :output]\n      when \"java-filter\"      then [:java, :filter]\n      when \"java-file-input\"  then [:java, :file_input]\n      when \"java-file-output\" then [:java, :file_output]\n      when \"java-parser\"      then [:java, :parser]\n      when \"java-formatter\"   then [:java, :formatter]\n      when \"java-decoder\"     then [:java, :decoder]\n      when \"java-encoder\"     then [:java, :encoder]\n      when \"ruby-input\"       then [:ruby, :input]\n      when \"ruby-output\"      then [:ruby, :output]\n      when \"ruby-filter\"      then [:ruby, :filter]\n      when \"ruby-file-input\"  then raise \"ruby-file-input is not implemented yet. See #21 on github.\" #[:ruby, :file_input]\n      when \"ruby-file-output\" then raise \"ruby-file-output is not implemented yet. See #22 on github.\" #[:ruby, :file_output]\n      when \"ruby-parser\"      then [:ruby, :parser]\n      when \"ruby-formatter\"   then [:ruby, :formatter]\n      when \"ruby-decoder\"     then raise \"ruby-decoder is not implemented yet. See #31 on github.\" #[:ruby, :decoder]\n      when \"ruby-encoder\"     then raise \"ruby-decoder is not implemented yet. See #32 on github.\" #[:ruby, :encoder]\n      else\n        usage_op op, \"Unknown category '\#{lang_cate}'\"\n      end\n\n    require 'embulk/command/embulk_new_plugin'\n    Embulk.new_plugin(name, language, category)\n\n  when :migrate\n    path = ARGV[0]\n    require 'embulk/command/embulk_migrate_plugin'\n    Embulk.migrate_plugin(path)\n\n  when :selfupdate\n    require 'embulk/command/embulk_selfupdate'\n    options[:version] = ARGV[0]\n    Embulk.selfupdate(options)\n\n  when :mkbundle\n    new_bundle(argv[0], options[:bundle_path])\n\n  else\n    require 'json'\n\n    setup_plugin_paths(plugin_paths)\n    setup_load_paths(load_paths)\n    setup_classpaths(classpaths)\n\n    # call setup after setup_classpaths to allow users to overwrite\n    # embulk classes\n    Embulk.setup(options.delete(:system_config))\n\n    begin\n      case subcmd\n      when :guess\n        Embulk::Runner.guess(argv[0], options)\n      when :preview\n        Embulk::Runner.preview(argv[0], options)\n      when :run\n        Embulk::Runner.run(argv[0], options)\n      end\n    rescue => ex\n      print_exception(ex)\n      puts \"\"\n      puts \"Error: \#{ex}\"\n      raise SystemExit.new(1, ex.to_s)\n    end\n  end\nend\n"

.run_bundler(argv) ⇒ Object



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/embulk/command/embulk_run.rb', line 410

def self.run_bundler(argv)
  require 'bundler'  # bundler is included in embulk-core.jar

  # this hack is necessary to make --help working
  Bundler.define_singleton_method(:which_orig, Bundler.method(:which))
  Bundler.define_singleton_method(:which) do |executable|
    if executable == "man"
      false
    else
      which_orig(executable)
    end
  end

  require 'bundler/friendly_errors'
  require 'bundler/cli'
  Bundler.with_friendly_errors do
    Bundler::CLI.start(argv, debug: true)
  end
end

.selfupdate(options = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/embulk/command/embulk_selfupdate.rb', line 2

def self.selfupdate(options={})
  require 'uri'

  jar, resource = __FILE__.split("!", 2)
  jar_uri = URI.parse(jar).path rescue jar
  unless resource && File.file?(jar_uri)
    STDERR.puts ""
    STDERR.puts "Embulk is not installed by a single jar. Selfupdate is not supported."
    STDERR.puts "If you used gem to install embulk, please run: "
    STDERR.puts ""
    STDERR.puts "  $ gem install embulk"
    STDERR.puts ""
    raise SystemExit.new(1)
  end
  jar_path = jar_uri

  if version = options[:version]
    puts "Checking version #{version}..."
    target_version = check_target_version(version)

    unless target_version
      puts "Specified version does not exist: #{version}"
      raise SystemExit.new(1)
    end
    puts "Found version #{target_version}."

  else
    puts "Checking the latest version..."
    target_version = check_latest_version

    current_version = Gem::Version.new(Embulk::VERSION)
    if Gem::Version.new(target_version) <= current_version
      puts "Already up-to-date. #{current_version} is the latest version."
      return
    end

    puts "Found new version #{target_version}."
  end

  unless File.writable?(jar_path)
    STDERR.puts ""
    STDERR.puts "Installation path #{jar_path} is not writable."
    STDERR.puts "Dou you need to run with sudo?"
    STDERR.puts ""
    raise SystemExit.new(1)
  end

  url = "https://dl.bintray.com/embulk/maven/embulk-#{target_version}.jar"
  puts "Downloading #{url} ..."

  require 'open-uri'
  require 'tempfile'
  Tempfile.open(["embulk-selfupdate", ".jar"]) do |tmp|
    tmp.chmod(File.stat(jar_path).mode)
    OpenURI.open_uri(url) do |f|
      IO.copy_stream(f, tmp)
    end
    tmp.close(false)

    # check corruption
    unless options[:force]
      begin
        data = File.read("jar:#{java.io.File.new(tmp.path).toURI.toURL}!/embulk/version.rb")
        m = Module.new
        m.module_eval(data)
        unless m::Embulk::VERSION == target_version
          raise "Embulk::VERSION does not match with #{target_version}"
        end
      rescue => e
        STDERR.puts "Corruption checking failed (#{e})."
        STDERR.puts "This version might include incompatible changes."
        STDERR.puts "Please add '-f' argument to selfupdate command to skip checking."
        raise SystemExit.new(1, e.to_s)
      end
    end

    File.rename(tmp.path, jar_path)
  end

  puts "Updated to #{target_version}."
end

.setup(system_config = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/embulk.rb', line 40

def self.setup(system_config={})
  unless RUBY_PLATFORM =~ /java/i
    raise "Embulk.setup works only with JRuby."
  end

  require 'json'

  require_classpath

  systemConfigJson = system_config.merge({
    # use the global ruby runtime for all ScriptingContainer
    # injected by org.embulk.jruby.JRubyScriptingModule
    use_global_ruby_runtime: true
  }).to_json

  bootstrap = org.embulk.EmbulkEmbed::Bootstrap.new
  systemConfig = bootstrap.getSystemConfigLoader.fromJsonString(systemConfigJson)
  bootstrap.setSystemConfig(systemConfig)
  embed = bootstrap.java_method(:initialize).call  # see embulk-core/src/main/java/org/embulk/jruby/JRubyScriptingModule.

  # see also embulk/java/bootstrap.rb loaded by JRubyScriptingModule

  Embulk.const_set :Runner, EmbulkRunner.new(embed)
end

.setup_classpaths(classpaths) ⇒ Object



368
369
370
371
372
# File 'lib/embulk/command/embulk_run.rb', line 368

def self.setup_classpaths(classpaths)
  classpaths.each do |classpath|
    $CLASSPATH << classpath  # $CLASSPATH object doesn't have concat method
  end
end

.setup_load_paths(load_paths) ⇒ Object



360
361
362
363
364
365
366
# File 'lib/embulk/command/embulk_run.rb', line 360

def self.setup_load_paths(load_paths)
  # first $LOAD_PATH has highet priority. later load_paths should have highest priority.
  load_paths.each do |load_path|
    # ruby script directory (use unshift to make it highest priority)
    $LOAD_PATH.unshift File.expand_path(load_path)
  end
end

.setup_plugin_paths(plugin_paths) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/embulk/command/embulk_run.rb', line 339

def self.setup_plugin_paths(plugin_paths)
  plugin_paths.each do |path|
    unless File.directory?(path)
      raise "Path '#{path}' is not a directory"
    end
    specs = Dir[File.join(File.expand_path(path), "*.gemspec")]
    if specs.empty?
      raise "Path '#{path}' does not include *.gemspec file. Hint: Did you run './gradlew package' command?"
    end
    specs.each do |spec|
      gem_path = File.dirname(spec)
      Dir.chdir(path) do
        # cd to path because spec could include `git ...`
        stub = Gem::StubSpecification.new(spec)
        stub.define_singleton_method(:full_gem_path) { gem_path }
        Gem::Specification.add_spec(stub)
      end
    end
  end
end

.start_bintray_http(&block) ⇒ Object



114
115
116
117
118
119
120
# File 'lib/embulk/command/embulk_selfupdate.rb', line 114

def self.start_bintray_http(&block)
  require 'net/https'
  bintray = Net::HTTP.new('bintray.com', 443)
  bintray.use_ssl = true
  bintray.verify_mode = OpenSSL::SSL::VERIFY_NONE
  bintray.start(&block)
end

.system_exit(message = nil) ⇒ Object

Raises:

  • (SystemExit)


470
471
472
473
# File 'lib/embulk/command/embulk_run.rb', line 470

def self.system_exit(message=nil)
  STDERR.puts message if message
  raise SystemExit.new(1, message)
end

.system_exit_successObject

Raises:

  • (SystemExit)


475
476
477
# File 'lib/embulk/command/embulk_run.rb', line 475

def self.system_exit_success
  raise SystemExit.new(0)
end

.usage(message) ⇒ Object



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/embulk/command/embulk_run.rb', line 430

def self.usage(message)
  STDERR.puts "Embulk v#{Embulk::VERSION}"
  STDERR.puts "usage: <command> [--options]"
  STDERR.puts "commands:"
  STDERR.puts "   mkbundle   <directory>                             # create a new plugin bundle environment."
  STDERR.puts "   bundle     [directory]                             # update a plugin bundle environment."
  STDERR.puts "   run        <config.yml>                            # run a bulk load transaction."
  STDERR.puts "   preview    <config.yml>                            # dry-run the bulk load without output and show preview."
  STDERR.puts "   guess      <partial-config.yml> -o <output.yml>    # guess missing parameters to create a complete configuration file."
  STDERR.puts "   gem        <install | list | help>                 # install a plugin or show installed plugins."
  STDERR.puts "                                                      # plugin path is #{ENV['GEM_HOME']}"
  STDERR.puts "   new        <category> <name>                       # generates new plugin template"
  STDERR.puts "   migrate    <path>                                  # modify plugin code to use the latest Embulk plugin API"
  STDERR.puts "   example    [path]                                  # creates an example config file and csv file to try embulk."
  STDERR.puts "   selfupdate [version]                               # upgrades embulk to the latest released version or to the specified version."
  STDERR.puts ""
  if message
    system_exit "error: #{message}"
  else
    system_exit "Use \`<command> --help\` to see description of the commands."
  end
end

.usage_op(op, message) ⇒ Object



453
454
455
456
457
# File 'lib/embulk/command/embulk_run.rb', line 453

def self.usage_op(op, message)
  STDERR.puts op.help
  STDERR.puts
  system_exit message
end

.version(str) ⇒ Object



81
82
83
# File 'lib/embulk/command/embulk_migrate_plugin.rb', line 81

def self.version(str)
  Gem::Version.new(str)
end