summaryrefslogtreecommitdiffstats
path: root/lib/puppet/daemon.rb
blob: 52197f562f32541952405fc92c18747f1d46a64d (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require 'puppet'
require 'puppet/util/pidlock'

# A module that handles operations common to all daemons.  This is included
# into the Server and Client base classes.
module Puppet::Daemon
    include Puppet::Util

    def daemonname
        Puppet[:name]
    end

    # Put the daemon into the background.
    def daemonize
        if pid = fork()
            Process.detach(pid)
            exit(0)
        end
        
        setpidfile()

        # Get rid of console logging
        Puppet::Util::Log.close(:console)

        Process.setsid
        Dir.chdir("/")
        begin
            $stdin.reopen "/dev/null"
            $stdout.reopen "/dev/null", "a"
            $stderr.reopen $stdout
            Puppet::Util::Log.reopen
        rescue => detail
            File.open("/tmp/daemonout", "w") { |f|
                f.puts "Could not start %s: %s" % [Puppet[:name], detail]
            }
            Puppet.err "Could not start %s: %s" % [Puppet[:name], detail]
            exit(12)
        end
    end

    # The path to the pid file for this server
    def pidfile
        if Puppet[:pidfile] != ""
            Puppet[:pidfile]
        else
            File.join(Puppet[:rundir], daemonname() + ".pid")
        end
    end

    # Remove the pid file
    def rmpidfile
        threadlock(:pidfile) do
            locker = Puppet::Util::Pidlock.new(pidfile)
            if locker.locked?
                locker.unlock or Puppet.err "Could not remove PID file %s" % [pidfile]
            end
        end
    end

    # Create the pid file.
    def setpidfile
        threadlock(:pidfile) do
            unless Puppet::Util::Pidlock.new(pidfile).lock
                Puppet.err("Could not create PID file: %s" % [pidfile])
                exit(74)
            end
        end
    end

    # Shut down our server
    def shutdown
        # Remove our pid file
        rmpidfile()

        # And close all logs except the console.
        Puppet::Util::Log.destinations.reject { |d| d == :console }.each do |dest|
            Puppet::Util::Log.close(dest)
        end

        super
    end
end

# $Id$