Sha256: 85d074d9a1a33e4b4c505c17d420f893697ac82e4a57fd49b4cab77296b496b5

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

module SrvManager
  class Process

    attr_reader :command
    attr_reader :id

    def initialize(command)
      @command = command
    end
    
    def start
      return if alive?
      command.rvm ? rvm_start : default_start
      @id = wait_for_pid(command.pidfile) if command.pidfile
      LOGGER.info "Started process #{@id}"
    end

    def stop
      return unless started?
      begin
        ::Process.kill 'TERM', @id
      rescue Errno::ESRCH
      end
      LOGGER.info "Stoped process #{@id}"
      @id = nil
    end

    def restart
      stop if alive?
      start
    end

    def started?
      !id.nil?
    end

    def alive?
      started? && ::Process.kill(0, id) ? true : false
    rescue Errno::ESRCH
      false
    end

    private

    def detault_start
      @id = ::Process.spawn command.env, 
                            command.text, 
                            chdir: command.dir, 
                            out: '/dev/null', 
                            err: '/dev/null'
      ::Process.detach @id
    end

    def rvm_start
      pid_file = File.expand_path "#{self.object_id}_#{Time.now.to_i}.pid", TMP_PATH
      rvm_pid = ::Process.spawn command.env.merge('SRV_COMMAND' => command.text, 'SRV_PIDFILE' => pid_file), 
                                RVM_RUNNER, 
                                chdir: command.dir, 
                                out: '/dev/null', 
                                err: '/dev/null'
      ::Process.detach rvm_pid
      @id = wait_for_pid pid_file, true
    end

    def wait_for_pid(filename, delete=false)
      Timeout.timeout(60) do
        loop do
          if File.exists? filename
            pid = File.read(filename).to_i
            File.delete filename if delete
            return pid
          end
          sleep 0.1
        end
      end
    rescue Timeout::Error
      nil
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
srv_manager-0.0.5 lib/srv_manager/process.rb