Sha256: 95633c395951ba53f07977b7e66c3ddfabe400702784b7a496219a9a06d02344

Contents?: true

Size: 1.55 KB

Versions: 2

Compression:

Stored size: 1.55 KB

Contents

require 'fileutils'

module Daemonic
  class Pidfile
    include FileUtils
    include Logging

    attr_reader :pid, :config, :index

    def initialize(options = {})
      @pid      = options.fetch(:pid)
      @config   = options.fetch(:config)
      @index    = options[:index]
    end

    def write
      mkdir_p(File.dirname(filename))

      if File.exist?(filename)
        existing_pid = File.open(filename, 'r').read.chomp
        running = Process.getpgid(existing_pid) rescue false
        if running
          fatal "Error: PID file already exists at `#{filename}` and a process with PID `#{existing_pid}` is running"
          exit 1
        else
          debug "Warning: cleaning up stale pid file at `#{filename}`"
          write!
        end
      else
        debug "Writing pidfile #{filename} with pid #{pid}"
        write!
      end
    end

    def clean
      if File.exist?(filename)
        existing_pid = File.open(filename, 'r').read.chomp
        if existing_pid == pid.to_s
          debug "Cleaning up my own pid file at `#{filename}`"
          rm(filename)
        else
          debug "Pid file `#{filename}` did not belong to me, so not cleaning. I am #{Process.pid}, and the pid file says #{existing_pid}"
        end
      else
        debug "Pid file disappeared from `#{filename}`"
      end
    end

    private

    def filename
      if index
        config.pidfile.to_s.sub(/\.([^\.]+)\z/, ".#{index}.\\1")
      else
        config.pidfile
      end
    end

    def write!
      File.open(filename, 'w') { |f| f.write(pid) }
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
daemonic-0.0.2 lib/daemonic/pidfile.rb
daemonic-0.0.1 lib/daemonic/pidfile.rb