summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util/pidlock.rb
blob: 05e1459d0fc1cdbd0d6459209064a3971d976e2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
require 'fileutils'

class Puppet::Util::Pidlock
  attr_reader :lockfile

  def initialize(lockfile)
    @lockfile = lockfile
  end

  def locked?
    clear_if_stale
    File.exists? @lockfile
  end

  def mine?
    Process.pid == lock_pid
  end

  def anonymous?
    return false unless File.exists?(@lockfile)
    File.read(@lockfile) == ""
  end

  def lock(opts = {})
    opts = {:anonymous => false}.merge(opts)

    if locked?
      mine?
    else
      if opts[:anonymous]
        File.open(@lockfile, 'w') { |fd| true }
      else
        File.open(@lockfile, "w") { |fd| fd.write(Process.pid) }
      end
      true
    end
  end

  def unlock(opts = {})
    opts = {:anonymous => false}.merge(opts)

    if mine? or (opts[:anonymous] and anonymous?)
      File.unlink(@lockfile)
      true
    else
      false
    end
  end

  private
  def lock_pid
    if File.exists? @lockfile
      File.read(@lockfile).to_i
    else
      nil
    end
  end

  def clear_if_stale
    return if lock_pid.nil?

    begin
      Process.kill(0, lock_pid)
    rescue Errno::ESRCH
      File.unlink(@lockfile)
    end
  end
end