Comparison

plugins/mod_posix.lua @ 2793:08892e3f24bd

mod_posix: Lock pidfile when in use, shut down if we can't write or lock the pidfile
author Matthew Wild <mwild1@gmail.com>
date Sun, 10 Jan 2010 23:49:38 +0000
parent 2074:c59c8f3ec645
child 2795:d6fcd13c07e7
comparison
equal deleted inserted replaced
2792:1b14388f1512 2793:08892e3f24bd
16 if type(signal) == "string" then 16 if type(signal) == "string" then
17 module:log("warn", "Couldn't load signal library, won't respond to SIGTERM"); 17 module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
18 end 18 end
19 19
20 local logger_set = require "util.logger".setwriter; 20 local logger_set = require "util.logger".setwriter;
21
22 local lfs = require "lfs";
21 23
22 local prosody = _G.prosody; 24 local prosody = _G.prosody;
23 25
24 module.host = "*"; -- we're a global module 26 module.host = "*"; -- we're a global module
25 27
57 prosody.shutdown("Refusing to run as root"); 59 prosody.shutdown("Refusing to run as root");
58 end 60 end
59 end 61 end
60 end); 62 end);
61 63
62 local pidfile_written; 64 local pidfile;
65 local pidfile_handle;
63 66
64 local function remove_pidfile() 67 local function remove_pidfile()
65 if pidfile_written then 68 if pidfile_handle then
66 os.remove(pidfile_written); 69 pidfile_handle:close();
67 pidfile_written = nil; 70 os.remove(pidfile);
71 pidfile, pidfile_handle = nil, nil;
68 end 72 end
69 end 73 end
70 74
71 local function write_pidfile() 75 local function write_pidfile()
72 if pidfile_written then 76 if pidfile_handle then
73 remove_pidfile(); 77 remove_pidfile();
74 end 78 end
75 local pidfile = module:get_option("pidfile"); 79 pidfile = module:get_option("pidfile");
76 if pidfile then 80 if pidfile then
77 local pf, err = io.open(pidfile, "w+"); 81 pidfile_handle, err = io.open(pidfile, "a+");
78 if not pf then 82 if not pidfile_handle then
79 module:log("error", "Couldn't write pidfile; %s", err); 83 module:log("error", "Couldn't write pidfile at %s; %s", pidfile, err);
84 prosody.shutdown("Couldn't write pidfile");
80 else 85 else
81 pf:write(tostring(pposix.getpid())); 86 if not lfs.lock(pidfile_handle, "w") then -- Exclusive lock
82 pf:close(); 87 local other_pid = pidfile_handle:read("*a");
83 pidfile_written = pidfile; 88 module:log("error", "Another Prosody instance seems to be running with PID %s, quitting", other_pid);
89 pidfile_handle = nil;
90 prosody.shutdown("Prosody already running");
91 else
92 pidfile_handle:write(tostring(pposix.getpid()));
93 pidfile_handle:flush();
94 end
84 end 95 end
85 end 96 end
86 end 97 end
87 98
88 local syslog_opened 99 local syslog_opened