_twistd_unix.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. # -*- test-case-name: twisted.test.test_twistd -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from __future__ import absolute_import, division, print_function
  5. import errno
  6. import os
  7. import sys
  8. import traceback
  9. from twisted.python import log, logfile, usage
  10. from twisted.python.compat import (intToBytes, _bytesRepr, _PY3)
  11. from twisted.python.util import (
  12. switchUID, uidFromString, gidFromString, untilConcludes)
  13. from twisted.application import app, service
  14. from twisted.internet.interfaces import IReactorDaemonize
  15. from twisted import copyright, logger
  16. from twisted.python.runtime import platformType
  17. if platformType == "win32":
  18. raise ImportError("_twistd_unix doesn't work on Windows.")
  19. def _umask(value):
  20. return int(value, 8)
  21. class ServerOptions(app.ServerOptions):
  22. synopsis = "Usage: twistd [options]"
  23. optFlags = [['nodaemon', 'n', "don't daemonize, don't use default umask of 0077"],
  24. ['originalname', None, "Don't try to change the process name"],
  25. ['syslog', None, "Log to syslog, not to file"],
  26. ['euid', '',
  27. "Set only effective user-id rather than real user-id. "
  28. "(This option has no effect unless the server is running as "
  29. "root, in which case it means not to shed all privileges "
  30. "after binding ports, retaining the option to regain "
  31. "privileges in cases such as spawning processes. "
  32. "Use with caution.)"],
  33. ]
  34. optParameters = [
  35. ['prefix', None,'twisted',
  36. "use the given prefix when syslogging"],
  37. ['pidfile','','twistd.pid',
  38. "Name of the pidfile"],
  39. ['chroot', None, None,
  40. 'Chroot to a supplied directory before running'],
  41. ['uid', 'u', None, "The uid to run as.", uidFromString],
  42. ['gid', 'g', None, "The gid to run as.", gidFromString],
  43. ['umask', None, None,
  44. "The (octal) file creation mask to apply.", _umask],
  45. ]
  46. compData = usage.Completions(
  47. optActions={"pidfile": usage.CompleteFiles("*.pid"),
  48. "chroot": usage.CompleteDirs(descr="chroot directory"),
  49. "gid": usage.CompleteGroups(descr="gid to run as"),
  50. "uid": usage.CompleteUsernames(descr="uid to run as"),
  51. "prefix": usage.Completer(descr="syslog prefix"),
  52. },
  53. )
  54. def opt_version(self):
  55. """Print version information and exit.
  56. """
  57. print('twistd (the Twisted daemon) %s' % copyright.version)
  58. print(copyright.copyright)
  59. sys.exit()
  60. def postOptions(self):
  61. app.ServerOptions.postOptions(self)
  62. if self['pidfile']:
  63. self['pidfile'] = os.path.abspath(self['pidfile'])
  64. def checkPID(pidfile):
  65. if not pidfile:
  66. return
  67. if os.path.exists(pidfile):
  68. try:
  69. with open(pidfile) as f:
  70. pid = int(f.read())
  71. except ValueError:
  72. sys.exit('Pidfile %s contains non-numeric value' % pidfile)
  73. try:
  74. os.kill(pid, 0)
  75. except OSError as why:
  76. if why.errno == errno.ESRCH:
  77. # The pid doesn't exist.
  78. log.msg('Removing stale pidfile %s' % pidfile, isError=True)
  79. os.remove(pidfile)
  80. else:
  81. sys.exit("Can't check status of PID %s from pidfile %s: %s" %
  82. (pid, pidfile, why[1]))
  83. else:
  84. sys.exit("""\
  85. Another twistd server is running, PID %s\n
  86. This could either be a previously started instance of your application or a
  87. different application entirely. To start a new one, either run it in some other
  88. directory, or use the --pidfile and --logfile parameters to avoid clashes.
  89. """ % pid)
  90. class UnixAppLogger(app.AppLogger):
  91. """
  92. A logger able to log to syslog, to files, and to stdout.
  93. @ivar _syslog: A flag indicating whether to use syslog instead of file
  94. logging.
  95. @type _syslog: C{bool}
  96. @ivar _syslogPrefix: If C{sysLog} is C{True}, the string prefix to use for
  97. syslog messages.
  98. @type _syslogPrefix: C{str}
  99. @ivar _nodaemon: A flag indicating the process will not be daemonizing.
  100. @type _nodaemon: C{bool}
  101. """
  102. def __init__(self, options):
  103. app.AppLogger.__init__(self, options)
  104. self._syslog = options.get("syslog", False)
  105. self._syslogPrefix = options.get("prefix", "")
  106. self._nodaemon = options.get("nodaemon", False)
  107. def _getLogObserver(self):
  108. """
  109. Create and return a suitable log observer for the given configuration.
  110. The observer will go to syslog using the prefix C{_syslogPrefix} if
  111. C{_syslog} is true. Otherwise, it will go to the file named
  112. C{_logfilename} or, if C{_nodaemon} is true and C{_logfilename} is
  113. C{"-"}, to stdout.
  114. @return: An object suitable to be passed to C{log.addObserver}.
  115. """
  116. if self._syslog:
  117. # FIXME: Requires twisted.python.syslog to be ported to Py3
  118. # https://twistedmatrix.com/trac/ticket/7957
  119. from twisted.python import syslog
  120. return syslog.SyslogObserver(self._syslogPrefix).emit
  121. if self._logfilename == '-':
  122. if not self._nodaemon:
  123. sys.exit('Daemons cannot log to stdout, exiting!')
  124. logFile = sys.stdout
  125. elif self._nodaemon and not self._logfilename:
  126. logFile = sys.stdout
  127. else:
  128. if not self._logfilename:
  129. self._logfilename = 'twistd.log'
  130. logFile = logfile.LogFile.fromFullPath(self._logfilename)
  131. try:
  132. import signal
  133. except ImportError:
  134. pass
  135. else:
  136. # Override if signal is set to None or SIG_DFL (0)
  137. if not signal.getsignal(signal.SIGUSR1):
  138. def rotateLog(signal, frame):
  139. from twisted.internet import reactor
  140. reactor.callFromThread(logFile.rotate)
  141. signal.signal(signal.SIGUSR1, rotateLog)
  142. return logger.textFileLogObserver(logFile)
  143. def launchWithName(name):
  144. if name and name != sys.argv[0]:
  145. exe = os.path.realpath(sys.executable)
  146. log.msg('Changing process name to ' + name)
  147. os.execv(exe, [name, sys.argv[0], '--originalname'] + sys.argv[1:])
  148. class UnixApplicationRunner(app.ApplicationRunner):
  149. """
  150. An ApplicationRunner which does Unix-specific things, like fork,
  151. shed privileges, and maintain a PID file.
  152. """
  153. loggerFactory = UnixAppLogger
  154. def preApplication(self):
  155. """
  156. Do pre-application-creation setup.
  157. """
  158. checkPID(self.config['pidfile'])
  159. self.config['nodaemon'] = (self.config['nodaemon']
  160. or self.config['debug'])
  161. self.oldstdout = sys.stdout
  162. self.oldstderr = sys.stderr
  163. def _formatChildException(self, exception):
  164. """
  165. Format the C{exception} in preparation for writing to the
  166. status pipe. This does the right thing on Python 2 if the
  167. exception's message is Unicode, and in all cases limits the
  168. length of the message afte* encoding to 100 bytes.
  169. This means the returned message may be truncated in the middle
  170. of a unicode escape.
  171. @type exception: L{Exception}
  172. @param exception: The exception to format.
  173. @return: The formatted message, suitable for writing to the
  174. status pipe.
  175. @rtype: L{bytes}
  176. """
  177. # On Python 2 this will encode Unicode messages with the ascii
  178. # codec and the backslashreplace error handler.
  179. exceptionLine = traceback.format_exception_only(exception.__class__,
  180. exception)[-1]
  181. # remove the trailing newline
  182. formattedMessage = '1 %s' % exceptionLine.strip()
  183. # On Python 3, encode the message the same way Python 2's
  184. # format_exception_only does
  185. if _PY3:
  186. formattedMessage = formattedMessage.encode('ascii',
  187. 'backslashreplace')
  188. # By this point, the message has been encoded, if appropriate,
  189. # with backslashreplace on both Python 2 and Python 3.
  190. # Truncating the encoded message won't make it completely
  191. # unreadable, and the reader should print out the repr of the
  192. # message it receives anyway. What it will do, however, is
  193. # ensure that only 100 bytes are written to the status pipe,
  194. # ensuring that the child doesn't block because the pipe's
  195. # full. This assumes PIPE_BUF > 100!
  196. return formattedMessage[:100]
  197. def postApplication(self):
  198. """
  199. To be called after the application is created: start the application
  200. and run the reactor. After the reactor stops, clean up PID files and
  201. such.
  202. """
  203. try:
  204. self.startApplication(self.application)
  205. except Exception as ex:
  206. statusPipe = self.config.get("statusPipe", None)
  207. if statusPipe is not None:
  208. message = self._formatChildException(ex)
  209. untilConcludes(os.write, statusPipe, message)
  210. untilConcludes(os.close, statusPipe)
  211. self.removePID(self.config['pidfile'])
  212. raise
  213. else:
  214. statusPipe = self.config.get("statusPipe", None)
  215. if statusPipe is not None:
  216. untilConcludes(os.write, statusPipe, b"0")
  217. untilConcludes(os.close, statusPipe)
  218. self.startReactor(None, self.oldstdout, self.oldstderr)
  219. self.removePID(self.config['pidfile'])
  220. def removePID(self, pidfile):
  221. """
  222. Remove the specified PID file, if possible. Errors are logged, not
  223. raised.
  224. @type pidfile: C{str}
  225. @param pidfile: The path to the PID tracking file.
  226. """
  227. if not pidfile:
  228. return
  229. try:
  230. os.unlink(pidfile)
  231. except OSError as e:
  232. if e.errno == errno.EACCES or e.errno == errno.EPERM:
  233. log.msg("Warning: No permission to delete pid file")
  234. else:
  235. log.err(e, "Failed to unlink PID file:")
  236. except:
  237. log.err(None, "Failed to unlink PID file:")
  238. def setupEnvironment(self, chroot, rundir, nodaemon, umask, pidfile):
  239. """
  240. Set the filesystem root, the working directory, and daemonize.
  241. @type chroot: C{str} or L{None}
  242. @param chroot: If not None, a path to use as the filesystem root (using
  243. L{os.chroot}).
  244. @type rundir: C{str}
  245. @param rundir: The path to set as the working directory.
  246. @type nodaemon: C{bool}
  247. @param nodaemon: A flag which, if set, indicates that daemonization
  248. should not be done.
  249. @type umask: C{int} or L{None}
  250. @param umask: The value to which to change the process umask.
  251. @type pidfile: C{str} or L{None}
  252. @param pidfile: If not L{None}, the path to a file into which to put
  253. the PID of this process.
  254. """
  255. daemon = not nodaemon
  256. if chroot is not None:
  257. os.chroot(chroot)
  258. if rundir == '.':
  259. rundir = '/'
  260. os.chdir(rundir)
  261. if daemon and umask is None:
  262. umask = 0o077
  263. if umask is not None:
  264. os.umask(umask)
  265. if daemon:
  266. from twisted.internet import reactor
  267. self.config["statusPipe"] = self.daemonize(reactor)
  268. if pidfile:
  269. with open(pidfile, 'wb') as f:
  270. f.write(intToBytes(os.getpid()))
  271. def daemonize(self, reactor):
  272. """
  273. Daemonizes the application on Unix. This is done by the usual double
  274. forking approach.
  275. @see: U{http://code.activestate.com/recipes/278731/}
  276. @see: W. Richard Stevens,
  277. "Advanced Programming in the Unix Environment",
  278. 1992, Addison-Wesley, ISBN 0-201-56317-7
  279. @param reactor: The reactor in use. If it provides
  280. L{IReactorDaemonize}, its daemonization-related callbacks will be
  281. invoked.
  282. @return: A writable pipe to be used to report errors.
  283. @rtype: C{int}
  284. """
  285. # If the reactor requires hooks to be called for daemonization, call
  286. # them. Currently the only reactor which provides/needs that is
  287. # KQueueReactor.
  288. if IReactorDaemonize.providedBy(reactor):
  289. reactor.beforeDaemonize()
  290. r, w = os.pipe()
  291. if os.fork(): # launch child and...
  292. code = self._waitForStart(r)
  293. os.close(r)
  294. os._exit(code) # kill off parent
  295. os.setsid()
  296. if os.fork(): # launch child and...
  297. os._exit(0) # kill off parent again.
  298. null = os.open('/dev/null', os.O_RDWR)
  299. for i in range(3):
  300. try:
  301. os.dup2(null, i)
  302. except OSError as e:
  303. if e.errno != errno.EBADF:
  304. raise
  305. os.close(null)
  306. if IReactorDaemonize.providedBy(reactor):
  307. reactor.afterDaemonize()
  308. return w
  309. def _waitForStart(self, readPipe):
  310. """
  311. Wait for the daemonization success.
  312. @param readPipe: file descriptor to read start information from.
  313. @type readPipe: C{int}
  314. @return: code to be passed to C{os._exit}: 0 for success, 1 for error.
  315. @rtype: C{int}
  316. """
  317. data = untilConcludes(os.read, readPipe, 100)
  318. dataRepr = _bytesRepr(data[2:])
  319. if data != b"0":
  320. msg = ("An error has occurred: %s\nPlease look at log "
  321. "file for more information.\n" % (dataRepr,))
  322. untilConcludes(sys.__stderr__.write, msg)
  323. return 1
  324. return 0
  325. def shedPrivileges(self, euid, uid, gid):
  326. """
  327. Change the UID and GID or the EUID and EGID of this process.
  328. @type euid: C{bool}
  329. @param euid: A flag which, if set, indicates that only the I{effective}
  330. UID and GID should be set.
  331. @type uid: C{int} or L{None}
  332. @param uid: If not L{None}, the UID to which to switch.
  333. @type gid: C{int} or L{None}
  334. @param gid: If not L{None}, the GID to which to switch.
  335. """
  336. if uid is not None or gid is not None:
  337. extra = euid and 'e' or ''
  338. desc = '%suid/%sgid %s/%s' % (extra, extra, uid, gid)
  339. try:
  340. switchUID(uid, gid, euid)
  341. except OSError:
  342. log.msg('failed to set %s (are you root?) -- exiting.' % desc)
  343. sys.exit(1)
  344. else:
  345. log.msg('set %s' % desc)
  346. def startApplication(self, application):
  347. """
  348. Configure global process state based on the given application and run
  349. the application.
  350. @param application: An object which can be adapted to
  351. L{service.IProcess} and L{service.IService}.
  352. """
  353. process = service.IProcess(application)
  354. if not self.config['originalname']:
  355. launchWithName(process.processName)
  356. self.setupEnvironment(
  357. self.config['chroot'], self.config['rundir'],
  358. self.config['nodaemon'], self.config['umask'],
  359. self.config['pidfile'])
  360. service.IService(application).privilegedStartService()
  361. uid, gid = self.config['uid'], self.config['gid']
  362. if uid is None:
  363. uid = process.uid
  364. if gid is None:
  365. gid = process.gid
  366. self.shedPrivileges(self.config['euid'], uid, gid)
  367. app.startApplication(application, not self.config['no_save'])