Module: Embulk

Defined in:
lib/embulk/version.rb,
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/guess/csv.rb,
lib/embulk/file_input.rb,
lib/embulk/guess/gzip.rb,
lib/embulk/guess/json.rb,
lib/embulk/data_source.rb,
lib/embulk/file_output.rb,
lib/embulk/guess/bzip2.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/guess/csv_all_strings.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

Overview

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, OutputPlugin, PackageData, Page, PageBuilder, ParserPlugin, PluginLoadError, PluginManager, PluginRegistry, Schema, Slf4jAdapter, StandardLoggerAdapter, TextGuessPlugin

Constant Summary collapse

VERSION_INTERNAL =
'0.8.19'
DEPRECATED_MESSAGE =
'Embulk::VERSION in (J)Ruby is deprecated. Use org.embulk.EmbulkVersion::VERSION instead. If this message is from a plugin, please tell this to the author of the plugin!'
@@logger =

default logger

Logger.new(STDOUT)
@@warned =
false

Class Method Summary collapse

Class Method Details

.const_missing(name) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/embulk/version.rb', line 9

def self.const_missing(name)
  if name == :VERSION
    unless @@warned
      if Embulk.method_defined?(:logger)
        Embulk.logger.warn(DEPRECATED_MESSAGE)
        @@warned = true
      else
        STDERR.puts(DEPRECATED_MESSAGE)
      end
    end
    return VERSION_INTERNAL
  else
    super
  end
end

.default_gem_homeObject



280
281
282
283
284
285
286
287
288
289
# File 'lib/embulk/command/embulk_run.rb', line 280

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

.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

.new_bundle(path, bundle_path) ⇒ Object



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
# File 'lib/embulk/command/embulk_run.rb', line 307

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


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

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
# 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)

  require 'embulk/version'

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

  require 'java'
  require 'optparse'
  op = OptionParser.new
  op.version = org.embulk.EmbulkVersion::VERSION

  puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: Embulk v#{org.embulk.EmbulkVersion::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: embulk 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', '(deprecated)') do |path|
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: Run with -o option is deprecated. Please use -c option instead. For example,"
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: "
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}:   $ embulk run config.yml -c diff.yml"
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: "
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: This -c option stores only diff of the next configuration."
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: The diff will be merged to the original config.yml file."
      STDERR.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%3N %z")}: "
      options[:next_config_output_path] = path
    end
    op.on('-c', '--config-diff PATH', 'Path to a file to read & write the next configuration diff') do |path|
      options[:next_config_diff_path] = path
    end
    plugin_load_ops.call
    java_embed_ops.call
    args = 1..1

  when :cleanup
    op.banner = "Usage: embulk cleanup <config.yml>"
    op.separator "  Options:"
    op.on('-r', '--resume-state PATH', 'Path to a file to cleanup 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: embulk 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: embulk 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: embulk 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 <<-EOF

"mkbundle" creates a new a plugin bundle directory. You can install
plugins (gems) to the directory instead of ~/.embulk.

See generated <directory>/Gemfile to install plugins to the directory.
Use -b, --bundle BUNDLE_DIR option to use it:

  $ embulk mkbundle ./dir                # create bundle directory
  $ (cd dir && vi Gemfile && embulk bundle)   # update plugin list
  $ embulk guess -b ./dir ...            # guess using bundled plugins
  $ embulk run   -b ./dir ...            # run using bundled plugins

    EOF
    args = 1..1

  when :bundle
    if argv[0] == 'new'
      usage nil if argv.length != 2
      new_bundle(argv[1], nil)
      STDERR.puts "'embulk bundle new' is deprecated. This will be removed in future release. Please use 'embulk mkbundle' instead."
    else
      run_bundler(argv)
    end
    system_exit_success

  when :gem
    require 'rubygems/gem_runner'
    Gem::GemRunner.new.run argv
    system_exit_success

  when :new
    op.banner = "Usage: embulk 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 :migrate
    op.banner = "Usage: embulk migrate <directory>"
    args = 1..1

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

  when :example
    args = 0..1

  when :exec
    exec(*argv)
    exit 127

  when :irb
    require 'irb'
    IRB.start
    system_exit_success

  else
    usage "Unknown subcommand #{subcmd.to_s.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
  when :example
    (org.embulk.cli.EmbulkExample.new).createExample(ARGV[0] || "embulk-example")

  when :new
    (org.embulk.cli.EmbulkNew.new(ARGV[0], ARGV[1], org.embulk.EmbulkVersion::VERSION)).newPlugin()

  when :migrate
    (org.embulk.cli.EmbulkMigrate.new).migratePlugin(ARGV[0], org.embulk.EmbulkVersion::VERSION)

  when :selfupdate
    (org.embulk.cli.EmbulkSelfUpdate.new).updateSelf(org.embulk.EmbulkVersion::VERSION,
                                                     ARGV[0],
                                                     __FILE__,
                                                     options[:force])

  when :mkbundle
    new_bundle(argv[0], options[:bundle_path])

  else
    require 'json'

    # Gem::StubSpecification is an internal API that seems chainging often.
    # Gem::Specification.add_spec is deprecated also. Therefore, here makes
    # -L <path> option alias of -I <path>/lib by assuming that *.gemspec file
    # always has require_paths = ["lib"].
    load_paths = load_paths + plugin_paths.map {|path| File.join(path, "lib") }

    setup_load_paths(load_paths)
    setup_classpaths(classpaths)

    # call setup after setup_classpaths to allow users to overwrite
    # embulk classes
    Embulk.setup(options.delete(:system_config))

    begin
      case subcmd
      when :guess
        Embulk::Runner.guess(argv[0], options)
      when :preview
        Embulk::Runner.preview(argv[0], options)
      when :run
        Embulk::Runner.run(argv[0], options)
      end
    rescue => ex
      print_exception(ex)
      puts ""
      puts "Error: #{ex}"
      raise SystemExit.new(1, ex.to_s)
    end
  end
end

.run_bundler(argv) ⇒ Object



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

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

.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



301
302
303
304
305
# File 'lib/embulk/command/embulk_run.rb', line 301

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



293
294
295
296
297
298
299
# File 'lib/embulk/command/embulk_run.rb', line 293

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

.system_exit(message = nil) ⇒ Object

Raises:

  • (SystemExit)


410
411
412
413
# File 'lib/embulk/command/embulk_run.rb', line 410

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

.system_exit_successObject

Raises:

  • (SystemExit)


415
416
417
# File 'lib/embulk/command/embulk_run.rb', line 415

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

.usage(message) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/embulk/command/embulk_run.rb', line 363

def self.usage(message)
  STDERR.puts "Embulk v#{org.embulk.EmbulkVersion::VERSION}"
  STDERR.puts "Usage: embulk [-vm-options] <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 "   cleanup    <config.yml>                            # cleanup resume state."
  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 ""
  STDERR.puts "VM options:"
  STDERR.puts "   -J-O                             Disable JVM optimizations to speed up startup time (enabled by default if command is 'run')"
  STDERR.puts "   -J+O                             Enable JVM optimizations to speed up throughput"
  STDERR.puts "   -J...                            Set JVM options (use -J-help to see available options)"
  STDERR.puts "   -R...                            Set JRuby options (use -R--help to see available options)"
  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



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

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