forked from celery/celery
/
platforms.py
349 lines (262 loc) · 8.43 KB
/
platforms.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import os
import sys
import errno
import signal
try:
from setproctitle import setproctitle as _setproctitle
except ImportError:
_setproctitle = None
CAN_DETACH = True
try:
import resource
except ImportError:
CAN_DETACH = False
try:
import pwd
except ImportError:
pwd = None
try:
import grp
except ImportError:
grp = None
DAEMON_UMASK = 0
DAEMON_WORKDIR = "/"
DAEMON_REDIRECT_TO = getattr(os, "devnull", "/dev/nulll")
class LockFailed(Exception):
pass
def get_fdmax(default=None):
fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if fdmax == resource.RLIM_INFINITY:
return default
return fdmax
class PIDFile(object):
def __init__(self, path):
self.path = os.path.abspath(path)
def write_pid(self):
open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
open_mode = (((os.R_OK | os.W_OK) << 6) |
((os.R_OK) << 3) |
((os.R_OK)))
pidfile_fd = os.open(self.path, open_flags, open_mode)
pidfile = os.fdopen(pidfile_fd, "w")
pid = os.getpid()
pidfile.write("%d\n" % (pid, ))
pidfile.close()
def acquire(self):
try:
self.write_pid()
except OSError, exc:
raise LockFailed(str(exc))
return self
def is_locked(self):
return os.path.exists(self.path)
def release(self):
self.remove()
def read_pid(self):
try:
fh = open(self.path, "r")
except IOError, exc:
if exc.errno == errno.ENOENT:
return
raise
line = fh.readline().strip()
fh.close()
try:
return int(line)
except ValueError:
raise ValueError("PID file %r contents invalid." % self.path)
def remove(self):
try:
os.unlink(self.path)
except OSError, exc:
if exc.errno in (errno.ENOENT, errno.EACCES):
return
raise
def remove_if_stale(self):
try:
pid = self.read_pid()
except ValueError, exc:
sys.stderr.write("Broken pidfile found. Removing it.\n")
self.remove()
return True
if not pid:
self.remove()
return True
try:
os.kill(pid, 0)
except os.error, exc:
if exc.errno == errno.ESRCH:
sys.stderr.write("Stale pidfile exists. Removing it.\n")
self.remove()
return True
return False
def create_pidlock(pidfile):
"""Create and verify pidfile.
If the pidfile already exists the program exits with an error message,
however if the process it refers to is not running anymore, the pidfile
is just deleted.
"""
pidlock = PIDFile(pidfile)
if pidlock.is_locked() and not pidlock.remove_if_stale():
raise SystemExit(
"ERROR: Pidfile (%s) already exists.\n"
"Seems we're already running? (PID: %s)" % (
pidfile, pidlock.read_pid()))
return pidlock
class DaemonContext(object):
_is_open = False
def __init__(self, pidfile=None,
working_directory=DAEMON_WORKDIR, umask=DAEMON_UMASK, **kwargs):
self.working_directory = working_directory
self.umask = umask
def detach(self):
if os.fork() == 0: # first child
os.setsid() # create new session
if os.fork() > 0: # second child
os._exit(0)
else:
os._exit(0)
def open(self):
if self._is_open:
return
self.detach()
os.chdir(self.working_directory)
os.umask(self.umask)
for fd in reversed(range(get_fdmax(default=2048))):
try:
os.close(fd)
except OSError, exc:
if exc.errno != errno.EBADF:
raise
os.open(DAEMON_REDIRECT_TO, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2)
self._is_open = True
def close(self):
if self._is_open:
self._is_open = False
def create_daemon_context(logfile=None, pidfile=None, uid=None, gid=None,
**options):
if not CAN_DETACH:
raise RuntimeError(
"This platform does not support detach.")
# Make sure SIGCLD is using the default handler.
reset_signal("SIGCLD")
set_effective_user(uid=uid, gid=gid)
# Since without stderr any errors will be silently suppressed,
# we need to know that we have access to the logfile.
if logfile:
open(logfile, "a").close()
if pidfile:
# Doesn't actually create the pidfile, but makes sure it's
# not stale.
create_pidlock(pidfile)
defaults = {"umask": lambda: 0,
"working_directory": lambda: os.getcwd()}
for opt_name, opt_default_gen in defaults.items():
if opt_name not in options or options[opt_name] is None:
options[opt_name] = opt_default_gen()
context = DaemonContext(**options)
return context, context.close
def parse_uid(uid):
"""Parse user id.
uid can be an interger (uid) or a string (username), if a username
the uid is taken from the password file.
"""
try:
return int(uid)
except ValueError:
if pwd:
return pwd.getpwnam(uid).pw_uid
raise
def parse_gid(gid):
"""Parse group id.
gid can be an integer (gid) or a string (group name), if a group name
the gid is taken from the password file.
"""
try:
return int(gid)
except ValueError:
if grp:
return grp.getgrnam(gid).gr_gid
raise
def setegid(gid):
"""Set effective group id."""
gid = parse_gid(gid)
if gid != os.getgid():
os.setegid
def seteuid(uid):
"""Set effective user id."""
uid = parse_uid(uid)
if uid != os.getuid():
os.seteuid(uid)
def set_effective_user(uid=None, gid=None):
"""Change process privileges to new user/group.
If uid and gid is set the effective user/group is set.
If only uid is set, the effective uer is set, and the group is
set to the users primary group.
If only gid is set, the effective group is set.
"""
uid = uid and parse_uid(uid)
gid = gid and parse_gid(gid)
if uid:
# If gid isn't defined, get the primary gid of the uer.
if not gid and pwd:
gid = pwd.getpwuid(uid).pw_gid
setegid(gid)
seteuid(uid)
else:
gid and setegid(gid)
def reset_signal(signal_name):
"""Reset signal to the default signal handler.
Does nothing if the platform doesn't support signals,
or the specified signal in particular.
"""
try:
signum = getattr(signal, signal_name)
signal.signal(signum, signal.SIG_DFL)
except (AttributeError, ValueError):
pass
def ignore_signal(signal_name):
"""Ignore signal using :const:`SIG_IGN`.
Does nothing if the platform doesn't support signals,
or the specified signal in particular.
"""
try:
signum = getattr(signal, signal_name)
signal.signal(signum, signal.SIG_IGN)
except (AttributeError, ValueError):
pass
def install_signal_handler(signal_name, handler):
"""Install a handler.
Does nothing if the current platform doesn't support signals,
or the specified signal in particular.
"""
try:
signum = getattr(signal, signal_name)
signal.signal(signum, handler)
except (AttributeError, ValueError):
pass
def strargv(argv):
arg_start = "manage" in argv[0] and 2 or 1
if len(argv) > arg_start:
return " ".join(argv[arg_start:])
return ""
def set_process_title(progname, info=None):
"""Set the ps name for the currently running process.
Only works if :mod:`setproctitle` is installed.
"""
proctitle = "[%s]" % progname
proctitle = info and "%s %s" % (proctitle, info) or proctitle
if _setproctitle:
_setproctitle(proctitle)
return proctitle
def set_mp_process_title(progname, info=None, hostname=None):
"""Set the ps name using the multiprocessing process name.
Only works if :mod:`setproctitle` is installed.
"""
from multiprocessing.process import current_process
if hostname:
progname = "%s@%s" % (progname, hostname.split(".")[0])
return set_process_title("%s:%s" % (progname, current_process().name),
info=info)