Sha256: f2cc62017c1459bf26e13997414a3fa9c675b19da82bc5389f0ce17f8e95ff7f

Contents?: true

Size: 1.63 KB

Versions: 4

Compression:

Stored size: 1.63 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
      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
    end

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

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
srv_manager-0.0.4 lib/srv_manager/process.rb
srv_manager-0.0.3 lib/srv_manager/process.rb
srv_manager-0.0.2 lib/srv_manager/process.rb
srv_manager-0.0.1 lib/srv_manager/process.rb