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.25'
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

.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 #{Embulk::VERSION_INTERNAL}"
      system_exit_success
    end
    usage nil
  end
  subcmd = argv.slice!(i).to_sym

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

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

  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], Embulk::VERSION_INTERNAL)).newPlugin()

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

  when :selfupdate
    (org.embulk.cli.EmbulkSelfUpdate.new).updateSelf(Embulk::VERSION_INTERNAL,
                                                     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

.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