Module: Einhorn

Extended by:
Third::LittlePlugger
Defined in:
lib/einhorn.rb,
lib/einhorn/event.rb,
lib/einhorn/third.rb,
lib/einhorn/client.rb,
lib/einhorn/compat.rb,
lib/einhorn/worker.rb,
lib/einhorn/command.rb,
lib/einhorn/version.rb,
lib/einhorn/worker_pool.rb

Defined Under Namespace

Modules: AbstractState, Command, Compat, Event, Plugins, State, Third, TransientState, Worker, WorkerPool Classes: Client

Constant Summary collapse

VERSION =
'0.6.4'

Class Method Summary collapse

Methods included from Third::LittlePlugger

default_plugin_module, default_plugin_path, extended, underscore, version

Class Method Details

.bind(addr, port, flags) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/einhorn.rb', line 197

def self.bind(addr, port, flags)
  log_info("Binding to #{addr}:#{port} with flags #{flags.inspect}")
  sd = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
  Einhorn::Compat.cloexec!(sd, false)

  if flags.include?('r') || flags.include?('so_reuseaddr')
    sd.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)
  end

  sd.bind(Socket.pack_sockaddr_in(port, addr))
  sd.listen(Einhorn::State.config[:backlog])

  if flags.include?('n') || flags.include?('o_nonblock')
    fl = sd.fcntl(Fcntl::F_GETFL)
    sd.fcntl(Fcntl::F_SETFL, fl | Fcntl::O_NONBLOCK)
  end

  Einhorn::TransientState.socket_handles << sd
  sd.fileno
end

.can_safely_reload?Boolean

Returns true if a reload of the einhorn master via re-execing is not likely to be completely unsafe (that is, the new process’s environment won’t prevent it from loading its code on exec).

Returns:

  • (Boolean)


398
399
400
401
402
403
404
405
406
# File 'lib/einhorn.rb', line 398

def self.can_safely_reload?
  upgrade_sentinel = fork do
    Einhorn::TransientState.whatami = :upgrade_sentinel
    Einhorn.initialize_reload_environment
    Einhorn::Compat.exec(*Einhorn.upgrade_commandline(['--upgrade-check']))
  end
  Process.wait(upgrade_sentinel)
  $?.exitstatus.zero?
end

.dump_environment_infoObject

Log info about the environment as observed by ruby on startup. Currently, this means the bundler and rbenv versions.



425
426
427
428
429
430
431
432
433
# File 'lib/einhorn.rb', line 425

def self.dump_environment_info
  log_info("Running under Ruby #{RUBY_VERSION}", :environment)
  log_info("Rbenv ruby version: #{ENV['RBENV_VERSION']}", :environment) if ENV['RBENV_VERSION']
  begin
    bundler_gem = Gem::Specification.find_by_name('bundler')
    log_info("Using Bundler #{bundler_gem.version.to_s}", :environment)
  rescue Gem::LoadError
  end
end

.initialize_reload_environmentObject

Set up the environment for reloading the einhorn master:

  1. Clear the current process’s environment,

  2. Set it to the environmment at startup

  3. Delete all variables marked to be dropped via ‘–drop-env-var`

This method is safe to call in the master only before ‘exec`ing something.



415
416
417
418
419
420
421
# File 'lib/einhorn.rb', line 415

def self.initialize_reload_environment
  ENV.clear
  ENV.update(Einhorn::TransientState.environ)
  Einhorn::State.drop_environment_variables.each do |var|
    ENV.delete(var)
  end
end

.is_script(file) ⇒ Object

Not really a thing, but whatever.



267
268
269
270
271
272
# File 'lib/einhorn.rb', line 267

def self.is_script(file)
  File.open(file) do |f|
    bytes = f.read(2)
    bytes == '#!'
  end
end

.log_debug(msg, tag = nil) ⇒ Object

Implement these ourselves so it plays nicely with state persistence



219
220
221
222
# File 'lib/einhorn.rb', line 219

def self.log_debug(msg, tag=nil)
  $stderr.puts("#{log_tag} DEBUG: #{msg}") if Einhorn::State.verbosity <= 0
  self.send_tagged_message(tag, msg) if tag
end

.log_error(msg, tag = nil) ⇒ Object



227
228
229
230
# File 'lib/einhorn.rb', line 227

def self.log_error(msg, tag=nil)
  $stderr.puts("#{log_tag} ERROR: #{msg}") if Einhorn::State.verbosity <= 2
  self.send_tagged_message(tag, "ERROR: #{msg}") if tag
end

.log_info(msg, tag = nil) ⇒ Object



223
224
225
226
# File 'lib/einhorn.rb', line 223

def self.log_info(msg, tag=nil)
  $stderr.puts("#{log_tag} INFO: #{msg}") if Einhorn::State.verbosity <= 1
  self.send_tagged_message(tag, msg) if tag
end

.master_ps_nameObject



328
329
330
# File 'lib/einhorn.rb', line 328

def self.master_ps_name
  "einhorn: #{worker_ps_name}"
end

.plugins_send(sym, *args) ⇒ Object



16
17
18
19
20
# File 'lib/einhorn.rb', line 16

def self.plugins_send(sym, *args)
  plugins.values.each do |plugin|
    plugin.send(sym, *args) if plugin.respond_to? sym
  end
end

.preloadObject



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
# File 'lib/einhorn.rb', line 274

def self.preload
  if path = Einhorn::State.path
    set_argv(Einhorn::State.cmd, false)

    begin
      # If it's not going to be requireable, then load it.
      if !path.end_with?('.rb') && File.exists?(path)
        log_info("Loading #{path} (if this hangs, make sure your code can be properly loaded as a library)", :upgrade)
        load path
      else
        log_info("Requiring #{path} (if this hangs, make sure your code can be properly loaded as a library)", :upgrade)
        require path
      end
    rescue Exception => e
      log_info("Proceeding with postload -- could not load #{path}: #{e} (#{e.class})\n  #{e.backtrace.join("\n  ")}", :upgrade)
    else
      if defined?(einhorn_main)
        log_info("Successfully loaded #{path}", :upgrade)
        Einhorn::TransientState.preloaded = true
      else
        log_info("Proceeding with postload -- loaded #{path}, but no einhorn_main method was defined", :upgrade)
      end
    end
  end
end


193
194
195
# File 'lib/einhorn.rb', line 193

def self.print_state
  log_info(Einhorn::State.state.pretty_inspect)
end

.renice_selfObject



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/einhorn.rb', line 336

def self.renice_self
  whatami = Einhorn::TransientState.whatami
  return unless nice = Einhorn::State.nice[whatami]
  pid = $$

  unless nice.kind_of?(Fixnum)
    raise "Nice must be a fixnum: #{nice.inspect}"
  end

  # Explicitly don't shellescape the renice command
  cmd = "#{Einhorn::State.nice[:renice_cmd]} #{nice} -p #{pid}"
  log_info("Running #{cmd.inspect} to renice self to level #{nice}")
  `#{cmd}`
  unless $?.exitstatus == 0
    # TODO: better error handling?
    log_error("Renice command exited with status: #{$?.inspect}, but continuing on anyway.")
  end
end

.restore_state(state) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
# File 'lib/einhorn.rb', line 109

def self.restore_state(state)
  parsed = YAML.load(state)
  updated_state, message = update_state(Einhorn::State, "einhorn", parsed[:state])
  Einhorn::State.state = updated_state
  Einhorn::Event.restore_persistent_descriptors(parsed[:persistent_descriptors])
  plugin_messages = update_plugin_states(parsed[:plugins])
  # Do this after setting state so verbosity is right
  Einhorn.log_info("Using loaded state: #{parsed.inspect}")
  Einhorn.log_info(message) if message
  plugin_messages.each {|msg| Einhorn.log_info(msg)}
end

.runObject



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/einhorn.rb', line 435

def self.run
  Einhorn::Command::Interface.init
  Einhorn::Event.init

  unless Einhorn::TransientState.stateful
    if Einhorn::State.config[:number] < 1
      log_error("You need to spin up at least at least 1 copy of the process")
      return
    end
    Einhorn::Command::Interface.persistent_init

    Einhorn::State.orig_cmd = ARGV.dup
    Einhorn::State.cmd = ARGV.dup
    # TODO: don't actually alter ARGV[0]?
    Einhorn::State.cmd[0] = which(Einhorn::State.cmd[0])
    socketify_env!
    socketify!(Einhorn::State.cmd)
  end

  set_master_ps_name
  renice_self
  preload

  # In the middle of upgrading
  if Einhorn::State.reloading_for_upgrade
    Einhorn::Command.upgrade_workers
    Einhorn::State.reloading_for_upgrade = false
  end

  while Einhorn::State.respawn || Einhorn::State.children.size > 0
    log_debug("Entering event loop")
    Einhorn.plugins_send(:event_loop)

    # All of these are non-blocking
    Einhorn::Command.reap
    Einhorn::Command.replenish
    Einhorn::Command.cull

    # Make sure to do this last, as it's blocking.
    Einhorn::Event.loop_once
  end

  Einhorn.plugins_send(:exit)
end

.send_tagged_message(tag, message, last = false) ⇒ Object



232
233
234
# File 'lib/einhorn.rb', line 232

def self.send_tagged_message(tag, message, last=false)
  Einhorn::Command::Interface.send_tagged_message(tag, message, last)
end

.set_argv(cmd, set_ps_name) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/einhorn.rb', line 300

def self.set_argv(cmd, set_ps_name)
  # TODO: clean up this hack
  idx = 0
  if cmd[0] =~ /(^|\/)ruby$/
    idx = 1
  elsif !is_script(cmd[0])
    log_info("WARNING: Going to set $0 to #{cmd[idx]}, but it doesn't look like a script")
  end

  if set_ps_name
    # Note this will mess up $0 if we try using it in our code, but
    # we don't so that's basically ok. It's a bit annoying that this
    # is how Ruby exposes changing the output of ps. Note that Ruby
    # doesn't seem to shrink your cmdline buffer, so ps just ends up
    # having lots of trailing spaces if we set $0 to something
    # short. In the future, we could try to not pass einhorn's
    # state in ARGV.
    $0 = worker_ps_name
  end

  ARGV[0..-1] = cmd[idx+1..-1]
  log_info("Set#{set_ps_name ? " $0 = #{$0.inspect}, " : nil} ARGV = #{ARGV.inspect}")
end

.set_master_ps_nameObject



324
325
326
# File 'lib/einhorn.rb', line 324

def self.set_master_ps_name
  $0 = master_ps_name
end

.socketify!(cmd) ⇒ Object

This duplicates some code from the environment path, but is deprecated so that’s ok.



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/einhorn.rb', line 364

def self.socketify!(cmd)
  cmd.map! do |arg|
    if arg =~ /^(.*=|)srv:([^:]+):(\d+)((?:,\w+)*)$/
      log_error("Using deprecated command-line configuration for Einhorn; should upgrade to the environment variable interface.")
      opt = $1
      host = $2
      port = $3
      flags = $4.split(',').select {|flag| flag.length > 0}.map {|flag| flag.downcase}
      fd = (Einhorn::State.sockets[[host, port]] ||= bind(host, port, flags))
      "#{opt}#{fd}"
    else
      arg
    end
  end
end

.socketify_env!Object



355
356
357
358
359
360
# File 'lib/einhorn.rb', line 355

def self.socketify_env!
  Einhorn::State.bind.each do |host, port, flags|
    fd = bind(host, port, flags)
    Einhorn::State.bind_fds << fd
  end
end

.update_plugin_states(states) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/einhorn.rb', line 176

def self.update_plugin_states(states)
  plugin_messages = []
  (states || {}).each do |name, plugin_state|
    plugin = Einhorn.plugins[name]
    unless plugin && plugin.const_defined?(:State)
      plugin_messages << "No state defined in this version of the #{name} " +
        "plugin; dropping values for keys #{plugin_state.keys.inspect}"
      next
    end

    updated_state, plugin_message = update_state(plugin::State, "plugin #{name}", plugin_state)
    plugin_messages << plugin_message if plugin_message
    plugin::State.state = updated_state
  end
  plugin_messages
end

.update_state(store, store_name, old_state) ⇒ Object



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
# File 'lib/einhorn.rb', line 121

def self.update_state(store, store_name, old_state)
  message = []
  updated_state = old_state.dup

  # Handle changes in state format updates from previous einhorn versions
  if store == Einhorn::State
    # TODO: Drop this backwards compatibility hack when we hit 0.7
    if updated_state.include?(:reloading_for_preload_upgrade) &&
        !updated_state.include?(:reloading_for_upgrade)
      updated_state[:reloading_for_upgrade] = updated_state.delete(:reloading_for_preload_upgrade)
      message << "upgraded :reloading_for_preload_upgrade to :reloading_for_upgrade"
    end

    if updated_state[:children]
      # For a period, we created children entries for state_passers,
      # but we don't want that (in particular, it probably died
      # before we could setup our SIGCHLD handler
      updated_state[:children].delete_if {|k, v| v[:type] == :state_passer}

      # Depending on what is passed for --reexec-as, it's possible
      # that the process received a SIGCHLD while something other
      # than einhorn was the active executable. If that happened,
      # einhorn might not know about a dead child, so let's check
      # them all
      dead = []
      updated_state[:children].each do |pid, v|
        begin
          pid = Process.wait(pid, Process::WNOHANG)
          dead << pid if pid
        rescue Errno::ECHILD
          dead << pid
        end
      end
      Einhorn::Event::Timer.open(0) do
        dead.each {|pid| Einhorn::Command.mourn(pid)}
      end
    end
  end

  default = store.default_state
  added_keys = default.keys - updated_state.keys
  deleted_keys = updated_state.keys - default.keys
  return [updated_state, message.first] if added_keys.length == 0 && deleted_keys.length == 0

  added_keys.each {|key| updated_state[key] = default[key]}
  deleted_keys.each {|key| updated_state.delete(key)}

  message << "adding default values for #{added_keys.inspect}"
  message << "deleting values for #{deleted_keys.inspect}"
  message = "State format for #{store_name} has changed: #{message.join(', ')}"

  # Can't print yet, since state hasn't been set, so we pass along the message.
  [updated_state, message]
end

.upgrade_commandline(einhorn_flags = []) ⇒ Object

Construct and a command and args that can be used to re-exec Einhorn for upgrades.



382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/einhorn.rb', line 382

def self.upgrade_commandline(einhorn_flags=[])
  cmdline = []
  if Einhorn::State.reexec_commandline
    cmdline += Einhorn::State.reexec_commandline
  else
    cmdline << Einhorn::TransientState.script_name
  end
  cmdline += einhorn_flags
  cmdline << '--'
  cmdline += Einhorn::State.cmd
  [cmdline[0], cmdline[1..-1]]
end

.which(cmd) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/einhorn.rb', line 253

def self.which(cmd)
  if cmd.include?('/')
    return cmd if File.exists?(cmd)
    raise "Could not find #{cmd}"
  else
    ENV['PATH'].split(':').each do |f|
      abs = File.join(f, cmd)
      return abs if File.exists?(abs)
    end
    raise "Could not find #{cmd} in PATH"
  end
end

.worker_ps_nameObject



332
333
334
# File 'lib/einhorn.rb', line 332

def self.worker_ps_name
  Einhorn::State.cmd_name ? "ruby #{Einhorn::State.cmd_name}" : Einhorn::State.orig_cmd.join(' ')
end