Class: Iyyov::Daemon

Inherits:
Object
  • Object
show all
Includes:
RJack
Defined in:
lib/iyyov/daemon.rb

Overview

A daemon instance to start and monitor

Constant Summary collapse

STATES =

States tracked

[ :begin, :up, :failed, :stopped ]
LVARS =

Instance variables which may be set as Procs

[ :@instance, :@exe_path, :@args, :@base_dir, :@run_dir, :@pid_file,
:@gem_name, :@version, :@init_name ]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context = Iyyov.context) {|_self| ... } ⇒ Daemon

New daemon given specified or default global Iyyov.context. Yields self to block for configuration.

Yields:

  • (_self)

Yield Parameters:

  • _self (Iyyov::Daemon)

    the object that the method was called on



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
# File 'lib/iyyov/daemon.rb', line 116

def initialize( context = Iyyov.context )

  @context      = context
  @name         = nil

  @instance     = nil
  @exe_path     = method :gem_exe_path
  @args         = []
  @base_dir     = method :default_base_dir
  @run_dir      = method :default_run_dir
  @make_run_dir = @context.make_run_dir
  @stop_on_exit = @context.stop_on_exit
  @stop_delay   = @context.stop_delay

  @pid_file     = method :default_pid_file
  @gem_name     = method :name
  @version      = '>= 0'
  @init_name    = method :name

  @state        = :begin
  @gem_spec     = nil
  @rotators     = {}

  yield self if block_given?

  raise "name not specified" unless name

  @log = SLF4J[ [ SLF4J[ self.class ].name,
                  name, instance ].compact.join( '.' ) ]
end

Instance Attribute Details

#args=(value) ⇒ Object (writeonly)

Any additional args to use on start

Proc,Array (default: [])



49
50
51
# File 'lib/iyyov/daemon.rb', line 49

def args=(value)
  @args = value
end

#base_dir=(value) ⇒ Object (writeonly)

Base directory under which run directories are found

Proc,~to_s (default: Context.base_dir)



54
55
56
# File 'lib/iyyov/daemon.rb', line 54

def base_dir=(value)
  @base_dir = value
end

#exe_path=(value) ⇒ Object (writeonly)

Full path to executable to start.

Proc,~to_s (default: compute from gem_name, init_name, and version)



44
45
46
# File 'lib/iyyov/daemon.rb', line 44

def exe_path=(value)
  @exe_path = value
end

#gem_name=(value) ⇒ Object (writeonly)

The gem name used, in conjunction with version for gem-based default exe_path

Proc,~to_s (default: name)



87
88
89
# File 'lib/iyyov/daemon.rb', line 87

def gem_name=(value)
  @gem_name = value
end

#init_name=(value) ⇒ Object (writeonly)

The init script name used for gem-based default exe_path.

Proc,~to_s (default: name)



97
98
99
# File 'lib/iyyov/daemon.rb', line 97

def init_name=(value)
  @init_name = value
end

#instance=(value) ⇒ Object (writeonly)

Optional specific instance identifier, distinguishing this daemon from others of the same name. For example, a port number could be used.

Proc,~to_s (default: nil)



39
40
41
# File 'lib/iyyov/daemon.rb', line 39

def instance=(value)
  @instance = value
end

#logObject (readonly)

SLF4J logger



105
106
107
# File 'lib/iyyov/daemon.rb', line 105

def log
  @log
end

#make_run_dirObject

Whether to make run_dir, if not already present

Boolean (default: Context.make_run_dir )



64
65
66
# File 'lib/iyyov/daemon.rb', line 64

def make_run_dir
  @make_run_dir
end

#nameObject

Name of this daemon. Must be unique in combination with any specified instance.

String (required)



32
33
34
# File 'lib/iyyov/daemon.rb', line 32

def name
  @name
end

#pid_file=(value) ⇒ Object (writeonly)

PID file written by the daemon process after start, containing the running daemon Process ID

Proc,~to_s (default: run_dir, init_name + ‘.pid’)



81
82
83
# File 'lib/iyyov/daemon.rb', line 81

def pid_file=(value)
  @pid_file = value
end

#run_dir=(value) ⇒ Object (writeonly)

Directory to execute under

Proc,~to_s (default: base_dir / full_name)



59
60
61
# File 'lib/iyyov/daemon.rb', line 59

def run_dir=(value)
  @run_dir = value
end

#stateObject (readonly)

Last found state of this daemon.

Symbol (in STATES)



102
103
104
# File 'lib/iyyov/daemon.rb', line 102

def state
  @state
end

#stop_delayObject

Duration in seconds between SIGTERM and final SIGKILL when stopping.

Numeric (default: Context.stop_delay)



75
76
77
# File 'lib/iyyov/daemon.rb', line 75

def stop_delay
  @stop_delay
end

#stop_on_exitObject

Whether to stop this daemon when Iyyov exits

Boolean (default: Context.stop_on_exit)



69
70
71
# File 'lib/iyyov/daemon.rb', line 69

def stop_on_exit
  @stop_on_exit
end

#version=(value) ⇒ Object (writeonly)

The gem version requirements, i.e ‘~> 1.1.3’

Proc,~to_s,Array (default: ‘>= 0’)



92
93
94
# File 'lib/iyyov/daemon.rb', line 92

def version=(value)
  @version = value
end

Instance Method Details

#alive?(p = pid) ⇒ Boolean

True if process is up

Returns:

  • (Boolean)


307
308
309
310
311
# File 'lib/iyyov/daemon.rb', line 307

def alive?( p = pid )
  ( Process.getpgid( p ) != -1 ) if p
rescue Errno::ESRCH
  false
end

#default_base_dirObject



204
205
206
# File 'lib/iyyov/daemon.rb', line 204

def default_base_dir
  @context.base_dir
end

#default_logObject



216
217
218
# File 'lib/iyyov/daemon.rb', line 216

def default_log
  in_dir( init_name + '.log' )
end

#default_pid_fileObject



212
213
214
# File 'lib/iyyov/daemon.rb', line 212

def default_pid_file
  in_dir( init_name + '.pid' )
end

#default_run_dirObject



208
209
210
# File 'lib/iyyov/daemon.rb', line 208

def default_run_dir
  File.join( base_dir, full_name )
end

#do_exitObject



200
201
202
# File 'lib/iyyov/daemon.rb', line 200

def do_exit
  stop if stop_on_exit
end

#do_first(scheduler) ⇒ Object

Post initialization validation, attempt immediate start if needed, and add appropriate tasks to scheduler.



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/iyyov/daemon.rb', line 163

def do_first( scheduler )
  unless File.directory?( run_dir )
    if make_run_dir
      @log.info { "Creating run_dir [#{run_dir}]." }
      FileUtils.mkdir_p( run_dir, :mode => 0755 )
    else
      raise( DaemonFailed, "run_dir [#{run_dir}] not found" )
    end
  end

  res = start_check
  unless res == :stop
    tasks.each { |t| scheduler.add( t ) }
  end
  res
rescue DaemonFailed, SystemCallError => e
  #FIXME: Ruby 1.4.0 throws SystemCallError when mkdir fails from
  #permissions
  @log.error( "Do first", e )
  @state = :failed
  :stop
end

#exec_keyObject

Return array suitable for comparing this daemon with prior running instance.



279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/iyyov/daemon.rb', line 279

def exec_key
  epath = begin
            exe_path
          rescue Gem::LoadError, Gem::GemNotFoundException => e
            @log.warn( e.to_s )
            # Use a bogus, unique path instead
            "/tmp/gem-not-found/#{ Time.now.usec }/#{ rand( 2**31 ) }"
          end

  keys = [ run_dir, epath ].map { |p| File.expand_path( p ) }
  keys += args.map { |a| a.to_s.strip }
  keys.compact
end

#find_gem_specObject



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/iyyov/daemon.rb', line 229

def find_gem_spec
  @gem_spec ||=
    if Gem::Specification.respond_to?( :find_by_name )
      Gem::Specification.find_by_name( gem_name, version )
    else
      Gem.source_index.find_name( gem_name, version ).last
    end
  unless @gem_spec
    raise( Gem::GemNotFoundException, "Missing gem #{gem_name} (#{version})" )
  end
  @gem_spec
end

#full_nameObject

Given name + ( ‘-’ + instance ) if provided.



148
149
150
# File 'lib/iyyov/daemon.rb', line 148

def full_name
  [ name, instance ].compact.join('-')
end

#gem_exe_pathObject



225
226
227
# File 'lib/iyyov/daemon.rb', line 225

def gem_exe_path
  File.join( find_gem_spec.full_gem_path, 'init', init_name )
end

#in_dir(file_name) ⇒ Object

Return full path to file_name within run_dir



221
222
223
# File 'lib/iyyov/daemon.rb', line 221

def in_dir( file_name )
  File.join( run_dir, file_name )
end

#log_rotate(&block) ⇒ Object

Create a new LogRotator and yields it to block for configuration. The default log path is name + “.log” in run_dir



155
156
157
158
159
# File 'lib/iyyov/daemon.rb', line 155

def log_rotate( &block )
  lr = LogRotator.new( default_log, &block )
  @rotators[ lr.log ] = lr
  nil
end

#pidObject

Return process ID from pid_file if exists or nil otherwise



352
353
354
355
356
357
# File 'lib/iyyov/daemon.rb', line 352

def pid
  id = IO.read( pid_file ).strip.to_i
  ( id > 0 ) ? id : nil
rescue Errno::ENOENT # Pid file doesn't exist
  nil
end

#pre_checkObject

Return true if passes initial checks for start. This includes gem availability and/or if the exe_path is executable, i.e. everything that can be checked before starting.



267
268
269
270
271
272
273
274
275
# File 'lib/iyyov/daemon.rb', line 267

def pre_check
  epath = File.expand_path( exe_path )
  is_exec = File.executable?( epath )
  @log.warn( "#{epath} is not executable" ) unless is_exec
  is_exec
rescue Gem::LoadError, Gem::GemNotFoundException, Errno::ENOENT => e
  @log.warn( e.to_s )
  false
end

#startObject



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/iyyov/daemon.rb', line 242

def start
  epath = File.expand_path( exe_path )
  eargs = args.map { |a| a.to_s.strip }.compact
  aversion = @gem_spec && @gem_spec.version
  @log.info { ( [ "starting", aversion || epath ] + eargs ).join(' ') }

  unless File.executable?( epath )
    raise( DaemonFailed, "Exe path: #{epath} not found/executable." )
  end

  Dir.chdir( run_dir ) do
    system( epath, *eargs ) or raise( DaemonFailed, "Start failed with #{$?}" )
  end

  @state = :up
  true
rescue Gem::LoadError, Gem::GemNotFoundException, DaemonFailed, Errno::ENOENT => e
  @log.error( "On exec", e )
  @state = :failed
  false
end

#start_checkObject



293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/iyyov/daemon.rb', line 293

def start_check
  p = pid
  if alive?( p )
    @log.debug { "checked: alive pid: #{p}" }
    @state = :up
  else
    unless start
      @log.info "start failed, done trying"
      :stop
    end
  end
end

#stopObject

Stop via SIGTERM, waiting for shutdown for up to stop_delay, then SIGKILL as last resort. Return true if a process was stopped.



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/iyyov/daemon.rb', line 315

def stop
  p = pid
  if p
    @log.info "Sending TERM signal"
    Process.kill( "TERM", p )
    unless wait_pid( p )
      @log.info "Sending KILL signal"
      Process.kill( "KILL", p )
    end
    @status = :stopped
    true
  end
  false
rescue Errno::ESRCH
  # No such process: only raised by MRI ruby currently
  false
rescue Errno::EPERM => e
  # Not permitted: only raised by MRI ruby currently
  @log.error( "On stop", e )
  false
end

#tasksObject



186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/iyyov/daemon.rb', line 186

def tasks
  t = [ Task.new( :name => full_name, :period => 5.0 ) { start_check } ]
  t += @rotators.values.map do |lr|
    Task.new( :name => "#{full_name}.rotate",
              :mode => :async,
              :period => lr.check_period ) do
      lr.check_rotate( pid ) do |rlog|
        @log.info { "Rotating log #{rlog}" }
      end
    end
  end
  t
end

#wait_pid(p = pid) ⇒ Object

Wait for process to go away



338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/iyyov/daemon.rb', line 338

def wait_pid( p = pid )
  delta = 1.0 / 16
  delay = 0.0
  check = false
  while delay < stop_delay do
    break if ( check = ! alive?( p ) )
    sleep delta
    delay += delta
    delta += ( 1.0 / 16 ) if delta < 0.50
  end
  check
end