2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local want_pposix_version = "0.3.1";
12 local pposix = assert(require "util.pposix");
13 if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end
15 local signal = select(2, pcall(require, "util.signal"));
16 if type(signal) == "string" then
17 module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
20 local logger_set = require "util.logger".setwriter;
22 local prosody = _G.prosody;
24 module.host = "*"; -- we're a global module
26 -- Don't even think about it!
27 module:add_event_hook("server-starting", function ()
28 if pposix.getuid() == 0 and not module:get_option("run_as_root") then
29 module:log("error", "Danger, Will Robinson! Prosody doesn't need to be run as root, so don't do it!");
30 module:log("error", "For more information on running Prosody as root, see http://prosody.im/doc/root");
31 prosody.shutdown("Refusing to run as root");
35 local pidfile_written;
37 local function remove_pidfile()
38 if pidfile_written then
39 os.remove(pidfile_written);
40 pidfile_written = nil;
44 local function write_pidfile()
45 if pidfile_written then
48 local pidfile = module:get_option("pidfile");
50 local pf, err = io.open(pidfile, "w+");
52 module:log("error", "Couldn't write pidfile; %s", err);
54 pf:write(tostring(pposix.getpid()));
56 pidfile_written = pidfile;
62 function syslog_sink_maker(config)
63 if not syslog_opened then
64 pposix.syslog_open("prosody");
67 local syslog, format = pposix.syslog_log, string.format;
68 return function (name, level, message, ...)
70 syslog(level, format(message, ...));
72 syslog(level, message);
76 require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker);
78 if not module:get_option("no_daemonize") then
79 local function daemonize_server()
80 local ok, ret = pposix.daemonize();
82 module:log("error", "Failed to daemonize: %s", ret);
83 elseif ret and ret > 0 then
86 module:log("info", "Successfully daemonized to PID %d", pposix.getpid());
90 module:add_event_hook("server-starting", daemonize_server);
92 -- Not going to daemonize, so write the pid of this process
96 module:add_event_hook("server-stopped", remove_pidfile);
98 -- Set signal handlers
100 signal.signal("SIGTERM", function ()
101 module:log("warn", "Received SIGTERM");
102 prosody.unlock_globals();
103 prosody.shutdown("Received SIGTERM");
104 prosody.lock_globals();
107 signal.signal("SIGHUP", function ()
108 module:log("info", "Received SIGHUP");
109 prosody.reload_config();
110 prosody.reopen_logfiles();