Module: Embulk

Defined in:
lib/embulk.rb,
lib/embulk/gems.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/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/java/liquid_helper.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/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: Filter, Guess, Impl, Input, Java, Output, Plugin, Type Classes: Buffer, Column, ConfigError, DataSource, DecoderPlugin, EncoderPlugin, ExecutorPlugin, FileInput, FileInputPlugin, FileOutput, FileOutputPlugin, FilterPlugin, FormatterPlugin, GuessPlugin, InputPlugin, JavaPlugin, LineGuessPlugin, Logger, OutputPlugin, PackageData, Page, PageBuilder, ParserPlugin, PluginLoadError, PluginManager, PluginRegistry, Schema, Slf4jAdapter, StandardLoggerAdapter, TextGuessPlugin

Constant Summary collapse

VERSION =
'0.6.23'
@@logger =

default logger

Logger.new(STDOUT)

Class Method Summary collapse

Class Method Details

.add_embedded_gem_pathObject



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
# File 'lib/embulk/gems.rb', line 2

def self.add_embedded_gem_path
  begin
    resource_class = org.embulk.command.Runner.java_class
  rescue NameError
    begin
      Embulk.require_classpath
      resource_class = org.embulk.command.Runner.java_class
    rescue NameError
      return nil
    end
  end

  gem_path = resource_class.resource("/embulk/gems").to_s.sub(/^jar:/, '')
  unless gem_path.empty?
    # GEM_PATH can't include ':'
    gem_path = gem_path.gsub(/\w{0,5}:(?:\/(?=\/))*/, "")
    orig = ENV['GEM_PATH'].to_s
    if orig.empty?
      ENV['GEM_PATH'] = gem_path
    elsif !orig.split(Gem.path_separator).include?(gem_path)
      ENV['GEM_PATH'] = "#{gem_path}:#{orig}"
    end
    Gem.clear_paths
    return ENV['GEM_PATH']
  end
  return nil
end

.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



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/embulk/command/embulk_selfupdate.rb', line 70

def self.check_latest_version
  require 'net/https'
  bintray = Net::HTTP.new('bintray.com', 443)
  bintray.use_ssl = true
  bintray.verify_mode = OpenSSL::SSL::VERIFY_NONE
  bintray.start do
    response = bintray.get('/embulk/maven/embulk/_latestVersion')
    raise "Expected response code 302 Found but got #{response.code}" if response.code != "302"
    location = response["Location"].to_s
    m = /(\d+\.\d+[^\/]+)/.match(location)
    raise "Cound not find version number in Location header '#{location}'" unless m
    return m[1]
  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 <<EOF
id,account,time,purchase,comment
1,32864,2015-01-27 19:23:49,20150127,embulk
2,14824,2015-01-27 19:01:23,20150127,embulk jruby
3,27559,2015-01-28 02:20:02,20150128,"Embulk ""csv"" parser plugin"
4,11270,2015-01-29 11:54:36,20150129,NULL
EOF
  end

  puts "  Creating #{path}/example.yml"
  File.open(File.join(path, 'example.yml'), 'w') do |f|
    f.write <<EOF
in:
type: file
path_prefix: "#{File.expand_path File.join(path, 'csv', 'sample_')}"
out:
type: stdout
EOF
  end
end

.default_gem_homeObject



399
400
401
402
403
404
405
406
407
408
# File 'lib/embulk/command/embulk_run.rb', line 399

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

.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:/ || __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 = <<EOF
#!/bin/sh
=begin 2>/dev/null
#{java_home_script}
exec #{java_path} -classpath "$0" org.jruby.Main "$0" "$@"
exit 127
=end
EOF

  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 <<EOF
#{bundle_path_script}
ENV.delete 'GEM_HOME'
ENV.delete 'GEM_PATH'
EOF

  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

.home(dir) ⇒ Object



380
381
382
383
384
385
386
387
388
389
# File 'lib/embulk/command/embulk_run.rb', line 380

def self.home(dir)
  jar, resource = __FILE__.split("!")
  if resource && jar =~ /^file:/
    home = resource.split("/")[0..-3].join("/")
    "#{jar}!#{home}/#{dir}"
  else
    home = File.expand_path('../../..', File.dirname(__FILE__))
    File.join(home, dir)
  end
end

.java?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/embulk.rb', line 3

def self.java?
  true
end

.loggerObject



142
143
144
# File 'lib/embulk/logger.rb', line 142

def self.logger
  @@logger
end

.logger=(logger) ⇒ Object



146
147
148
# File 'lib/embulk/logger.rb', line 146

def self.logger=(logger)
  @@logger = logger
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
# 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
    author = "YOUR_NAME" if author.empty?
    email = `git config user.email`.strip
    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_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 "  $ rake"
    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

.require_classpathObject



391
392
393
394
395
396
397
# File 'lib/embulk/command/embulk_run.rb', line 391

def self.require_classpath
  classpath_dir = Embulk.home("classpath")
  jars = Dir.entries(classpath_dir).select{|f| f =~ /\.jar$/ }.sort
  jars.each do |jar|
    require File.join(classpath_dir, jar)
  end
end

.run(argv) ⇒ 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/embulk/command/embulk_run.rb', line 2

def self.run(argv)
  # default_bundle_path
  default_bundle_path = nil
  gemfile_path = ENV['BUNDLE_GEMFILE'].to_s
  gemfile_path = nil if gemfile_path.empty?
  default_bundle_path = File.dirname(gemfile_path) if gemfile_path

  # default GEM_HOME is ~/.embulk/jruby/1.9/. If -b option is set,
  # GEM_HOME is already set by embulk/command/embulk.rb
  gem_home = ENV['GEM_HOME'].to_s
  if gem_home.empty?
    ENV['GEM_HOME'] = default_gem_home
    Gem.clear_paths  # force rubygems to reload GEM_HOME
  end

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

  # to make sure org.embulk.jruby.JRubyScriptingModule can require 'embulk/java/bootstrap'
  $LOAD_PATH << Embulk.home('lib')

  require 'embulk/version'

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

  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 = {
    # use the global ruby runtime (the jruby Runtime running this embulk_run.rb script) for all
    # ScriptingContainer injected by the org.embulk.command.Runner.
    useGlobalRubyRuntime: true,
    systemProperty: {},
  }

  op.on('-b', '--bundle BUNDLE_DIR', 'Path to a Gemfile directory') do |path|
    # only for help message. implemented at lib/embulk/command/embulk.rb
  end

  case subcmd.to_sym
  when :bundle
    op.remove  # remove --bundle
    if default_bundle_path
      op.banner = "Usage: bundle [directory=#{default_bundle_path}]"
      args = 0..1
    else
      op.banner = "Usage: bundle <directory>"
      args = 1..1
    end

  when :run
    op.banner = "Usage: run <config.yml>"
    op.on('-l', '--log-level LEVEL', 'Log level (error, warn, info, debug or trace)') do |level|
      options[:logLevel] = level
    end
    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('-o', '--output PATH', 'Path to a file to write the next configuration') do |path|
      options[:nextConfigOutputPath] = path
    end
    op.on('-r', '--resume-state PATH', 'Path to a file to write or read resume state') do |path|
      options[:resumeStatePath] = path
    end
    op.on('-X KEY=VALUE', 'Add a performance system config') do |kv|
      k, v = kv.split('=', 2)
      v ||= "true"
      options[:systemProperty][k] = v
    end
    args = 1..1

  when :cleanup
    op.banner = "Usage: cleanup <config.yml>"
    op.on('-l', '--log-level LEVEL', 'Log level (error, warn, info, debug or trace)') do |level|
      options[:logLevel] = level
    end
    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('-r', '--resume-state PATH', 'Path to a file to write or read resume state') do |path|
      options[:resumeStatePath] = path
    end
    op.on('-X KEY=VALUE', 'Add a performance system config') do |kv|
      k, v = kv.split('=', 2)
      v ||= "true"
      options[:systemProperty][k] = v
    end
    args = 1..1

  when :preview
    op.banner = "Usage: preview <config.yml>"
    op.on('-l', '--log-level LEVEL', 'Log level (error, warn, info, debug or trace)') do |level|
      options[:logLevel] = level
    end
    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('-G', '--vertical', "Use vertical output format", TrueClass) do |b|
      options[:previewOutputFormat] = "vertical"
    end
    op.on('-X KEY=VALUE', 'Add a performance system config') do |kv|
      k, v = kv.split('=', 2)
      v ||= "true"
      options[:systemProperty][k] = v
    end
    args = 1..1

  when :guess
    op.banner = "Usage: guess <partial-config.yml>"
    op.on('-l', '--log-level LEVEL', 'Log level (error, warn, info, debug or trace)') do |level|
      options[:logLevel] = level
    end
    op.on('-o', '--output PATH', 'Path to a file to write the guessed configuration') do |path|
      options[:nextConfigOutputPath] = path
    end
    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('-g', '--guess NAMES', "Comma-separated list of guess plugin names") do |names|
      (options[:guessPlugins] ||= []).concat names.split(",")
    end
    op.on('-X KEY=VALUE', 'Add a performance system config') do |kv|
      k, v = kv.split('=', 2)
      v ||= "true"
      options[:systemProperty][k] = v
    end
    args = 1..1

  when :new
    op.remove  # remove --bundle
    op.banner = "Usage: new <category> <name>" + %[
categories:
  ruby-input                 Ruby record input plugin    (like "mysql")
  ruby-output                Ruby record output plugin   (like "mysql")
  ruby-filter                Ruby record filter plugin   (like "add-hostname")
  #ruby-file-input           Ruby file input plugin      (like "ftp")          # not implemented yet [#21]
  #ruby-file-output          Ruby file output plugin     (like "ftp")          # not implemented yet [#22]
  ruby-parser                Ruby file parser plugin     (like "csv")
  ruby-formatter             Ruby file formatter plugin  (like "csv")
  #ruby-decoder              Ruby file decoder plugin    (like "gzip")         # not implemented yet [#31]
  #ruby-encoder              Ruby file encoder plugin    (like "gzip")         # not implemented yet [#32]
  java-input                 Java record input plugin    (like "mysql")
  java-output                Java record output plugin   (like "mysql")
  java-filter                Java record filter plugin   (like "add-hostname")
  java-file-input            Java file input plugin      (like "ftp")
  java-file-output           Java file output plugin     (like "ftp")
  java-parser                Java file parser plugin     (like "csv")
  java-formatter             Java file formatter plugin  (like "csv")
  java-decoder               Java file decoder plugin    (like "gzip")
  java-encoder               Java file encoder plugin    (like "gzip")

examples:
  new ruby-output hbase
  new ruby-filter int-to-string
]
    args = 2..2

  when :selfupdate
    op.remove  # remove --bundle
    op.on('-f', "Skip corruption check", TrueClass) do |b|
      options[:force] = true
    end
    args = 0..0

  when :gem
    require 'embulk/gems'
    Embulk.add_embedded_gem_path
    require 'rubygems/gem_runner'
    Gem::GemRunner.new.run argv
    exit 0

  when :example
    args = 0..1

  when :exec
    exec(*argv)
    exit 127

  when :irb
    require 'irb'
    IRB.start
    exit 0

  else
    usage "Unknown subcommand #{subcmd.dump}."
  end

  begin
    op.parse!(argv)
    unless args.include?(argv.length)
      usage_op op, nil
    end
  rescue => e
    usage_op op, e.to_s
  end

  case subcmd.to_sym
  when :bundle
    path = argv[0] || default_bundle_path

    require 'fileutils'
    require 'rubygems/gem_runner'
    setup_plugin_paths(plugin_paths)
    setup_load_paths(load_paths)
    setup_classpaths(classpaths)

    unless File.exists?(path)
      puts "Initializing #{path}..."
      FileUtils.mkdir_p File.dirname(path)
      begin
        success = false

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

        ## TODO this is disabled for now. enable this if you want to use
        ## create bin/embulk
        #bin_embulk_path = File.join(path, 'bin', 'embulk')
        #FileUtils.mkdir_p File.dirname(bin_embulk_path)
        #require 'embulk/command/embulk_generate_bin'  # defines Embulk.generate_bin
        #File.open(bin_embulk_path, 'wb', 0755) {|f| f.write Embulk.generate_bin(bundle_path: :here) }

        # install bundler
        setup_gem_paths(path)
        Gem::GemRunner.new.run %w[install bundler]

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

    ENV['BUNDLE_GEMFILE'] = File.expand_path File.join(path, "Gemfile")
    Dir.chdir(path) do
      begin
        require 'bundler'
      rescue LoadError
        require 'rubygems/gem_runner'
        begin
          puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: installing bundler..."
          Gem::GemRunner.new.run %w[install bundler]
        rescue Gem::SystemExitException => e
          raise e if e.exit_code != 0
        end
        Gem.clear_paths
        require 'bundler'
      end
      require 'bundler/friendly_errors'
      require 'bundler/cli'
      Bundler.with_friendly_errors do
        # run > bundle install
        Bundler::CLI.start(%w[install], debug: true)
      end
    end

  when :example
    require_relative 'embulk_example'
    path = ARGV[0] || "embulk-example"
    puts "Creating #{path} directory..."
    Embulk.create_example(path)
    puts ""
    puts "Run following subcommands to try embulk:"
    puts ""
    puts "   1. embulk guess #{File.join(path, 'example.yml')} -o config.yml"
    puts "   2. embulk preview config.yml"
    puts "   3. embulk run config.yml"
    puts ""

  when :new
    lang_cate = ARGV[0]
    name = ARGV[1]

    language, category = case lang_cate
      when "java-input"       then [:java, :input]
      when "java-output"      then [:java, :output]
      when "java-filter"      then [:java, :filter]
      when "java-file-input"  then [:java, :file_input]
      when "java-file-output" then [:java, :file_output]
      when "java-parser"      then [:java, :parser]
      when "java-formatter"   then [:java, :formatter]
      when "java-decoder"     then [:java, :decoder]
      when "java-encoder"     then [:java, :encoder]
      when "ruby-input"       then [:ruby, :input]
      when "ruby-output"      then [:ruby, :output]
      when "ruby-filter"      then [:ruby, :filter]
      when "ruby-file-input"  then raise "ruby-file-input is not implemented yet. See #21 on github." #[:ruby, :file_input]
      when "ruby-file-output" then raise "ruby-file-output is not implemented yet. See #22 on github." #[:ruby, :file_output]
      when "ruby-parser"      then [:ruby, :parser]
      when "ruby-formatter"   then [:ruby, :formatter]
      when "ruby-decoder"     then raise "ruby-decoder is not implemented yet. See #31 on github." #[:ruby, :decoder]
      when "ruby-encoder"     then raise "ruby-decoder is not implemented yet. See #32 on github." #[:ruby, :encoder]
      else
        usage_op op, "Unknown category '#{lang_cate}'"
      end

    require 'embulk/command/embulk_new_plugin'
    Embulk.new_plugin(name, language, category)

  when :selfupdate
    require 'embulk/command/embulk_selfupdate'
    Embulk.selfupdate(options)

  else
    require 'json'

    begin
      java.lang.Class.forName('org.embulk.command.Runner')
    rescue java.lang.ClassNotFoundException
      # load classpath
      Embulk.require_classpath
    end

    setup_plugin_paths(plugin_paths)
    setup_load_paths(load_paths)
    setup_classpaths(classpaths)

    begin
      org.embulk.command.Runner.new(options.to_json).main(subcmd, argv.to_java(:string))
    rescue => ex
      print_exception(ex)
      puts ""
      puts "Error: #{ex}"
      raise SystemExit.new(1, ex.to_s)
    end
  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
# File 'lib/embulk/command/embulk_selfupdate.rb', line 2

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

  jar, resource = __FILE__.split("!", 2)
  jar_path = URI.parse(jar).path rescue jar
  unless resource && File.file?(jar_path)
    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

  puts "Checking the latest version..."
  latest_version = check_latest_version

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

  puts "Found new version #{latest_version}."

  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-#{latest_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 == latest_version
          raise "Embulk::VERSION does not match with #{latest_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 #{latest_version}."
end