app.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. # -*- test-case-name: twisted.test.test_application,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 sys
  6. import os
  7. import pdb
  8. import getpass
  9. import traceback
  10. import signal
  11. import warnings
  12. from operator import attrgetter
  13. from twisted import copyright, plugin, logger
  14. from twisted.application import service, reactors
  15. from twisted.internet import defer
  16. from twisted.persisted import sob
  17. from twisted.python import runtime, log, usage, failure, util, logfile
  18. from twisted.python._oldstyle import _oldStyle
  19. from twisted.python.reflect import (qual, namedAny, namedModule)
  20. from twisted.internet.interfaces import _ISupportsExitSignalCapturing
  21. # Expose the new implementation of installReactor at the old location.
  22. from twisted.application.reactors import installReactor
  23. from twisted.application.reactors import NoSuchReactor
  24. class _BasicProfiler(object):
  25. """
  26. @ivar saveStats: if C{True}, save the stats information instead of the
  27. human readable format
  28. @type saveStats: C{bool}
  29. @ivar profileOutput: the name of the file use to print profile data.
  30. @type profileOutput: C{str}
  31. """
  32. def __init__(self, profileOutput, saveStats):
  33. self.profileOutput = profileOutput
  34. self.saveStats = saveStats
  35. def _reportImportError(self, module, e):
  36. """
  37. Helper method to report an import error with a profile module. This
  38. has to be explicit because some of these modules are removed by
  39. distributions due to them being non-free.
  40. """
  41. s = "Failed to import module %s: %s" % (module, e)
  42. s += """
  43. This is most likely caused by your operating system not including
  44. the module due to it being non-free. Either do not use the option
  45. --profile, or install the module; your operating system vendor
  46. may provide it in a separate package.
  47. """
  48. raise SystemExit(s)
  49. class ProfileRunner(_BasicProfiler):
  50. """
  51. Runner for the standard profile module.
  52. """
  53. def run(self, reactor):
  54. """
  55. Run reactor under the standard profiler.
  56. """
  57. try:
  58. import profile
  59. except ImportError as e:
  60. self._reportImportError("profile", e)
  61. p = profile.Profile()
  62. p.runcall(reactor.run)
  63. if self.saveStats:
  64. p.dump_stats(self.profileOutput)
  65. else:
  66. tmp, sys.stdout = sys.stdout, open(self.profileOutput, 'a')
  67. try:
  68. p.print_stats()
  69. finally:
  70. sys.stdout, tmp = tmp, sys.stdout
  71. tmp.close()
  72. class CProfileRunner(_BasicProfiler):
  73. """
  74. Runner for the cProfile module.
  75. """
  76. def run(self, reactor):
  77. """
  78. Run reactor under the cProfile profiler.
  79. """
  80. try:
  81. import cProfile
  82. import pstats
  83. except ImportError as e:
  84. self._reportImportError("cProfile", e)
  85. p = cProfile.Profile()
  86. p.runcall(reactor.run)
  87. if self.saveStats:
  88. p.dump_stats(self.profileOutput)
  89. else:
  90. with open(self.profileOutput, 'w') as stream:
  91. s = pstats.Stats(p, stream=stream)
  92. s.strip_dirs()
  93. s.sort_stats(-1)
  94. s.print_stats()
  95. class AppProfiler(object):
  96. """
  97. Class which selects a specific profile runner based on configuration
  98. options.
  99. @ivar profiler: the name of the selected profiler.
  100. @type profiler: C{str}
  101. """
  102. profilers = {"profile": ProfileRunner, "cprofile": CProfileRunner}
  103. def __init__(self, options):
  104. saveStats = options.get("savestats", False)
  105. profileOutput = options.get("profile", None)
  106. self.profiler = options.get("profiler", "cprofile").lower()
  107. if self.profiler in self.profilers:
  108. profiler = self.profilers[self.profiler](profileOutput, saveStats)
  109. self.run = profiler.run
  110. else:
  111. raise SystemExit("Unsupported profiler name: %s" %
  112. (self.profiler,))
  113. class AppLogger(object):
  114. """
  115. An L{AppLogger} attaches the configured log observer specified on the
  116. commandline to a L{ServerOptions} object, a custom L{logger.ILogObserver},
  117. or a legacy custom {log.ILogObserver}.
  118. @ivar _logfilename: The name of the file to which to log, if other than the
  119. default.
  120. @type _logfilename: C{str}
  121. @ivar _observerFactory: Callable object that will create a log observer, or
  122. None.
  123. @ivar _observer: log observer added at C{start} and removed at C{stop}.
  124. @type _observer: a callable that implements L{logger.ILogObserver} or
  125. L{log.ILogObserver}.
  126. """
  127. _observer = None
  128. def __init__(self, options):
  129. """
  130. Initialize an L{AppLogger} with a L{ServerOptions}.
  131. """
  132. self._logfilename = options.get("logfile", "")
  133. self._observerFactory = options.get("logger") or None
  134. def start(self, application):
  135. """
  136. Initialize the global logging system for the given application.
  137. If a custom logger was specified on the command line it will be used.
  138. If not, and an L{logger.ILogObserver} or legacy L{log.ILogObserver}
  139. component has been set on C{application}, then it will be used as the
  140. log observer. Otherwise a log observer will be created based on the
  141. command line options for built-in loggers (e.g. C{--logfile}).
  142. @param application: The application on which to check for an
  143. L{logger.ILogObserver} or legacy L{log.ILogObserver}.
  144. @type application: L{twisted.python.components.Componentized}
  145. """
  146. if self._observerFactory is not None:
  147. observer = self._observerFactory()
  148. else:
  149. observer = application.getComponent(logger.ILogObserver, None)
  150. if observer is None:
  151. # If there's no new ILogObserver, try the legacy one
  152. observer = application.getComponent(log.ILogObserver, None)
  153. if observer is None:
  154. observer = self._getLogObserver()
  155. self._observer = observer
  156. if logger.ILogObserver.providedBy(self._observer):
  157. observers = [self._observer]
  158. elif log.ILogObserver.providedBy(self._observer):
  159. observers = [logger.LegacyLogObserverWrapper(self._observer)]
  160. else:
  161. warnings.warn(
  162. ("Passing a logger factory which makes log observers which do "
  163. "not implement twisted.logger.ILogObserver or "
  164. "twisted.python.log.ILogObserver to "
  165. "twisted.application.app.AppLogger was deprecated in "
  166. "Twisted 16.2. Please use a factory that produces "
  167. "twisted.logger.ILogObserver (or the legacy "
  168. "twisted.python.log.ILogObserver) implementing objects "
  169. "instead."),
  170. DeprecationWarning,
  171. stacklevel=2)
  172. observers = [logger.LegacyLogObserverWrapper(self._observer)]
  173. logger.globalLogBeginner.beginLoggingTo(observers)
  174. self._initialLog()
  175. def _initialLog(self):
  176. """
  177. Print twistd start log message.
  178. """
  179. from twisted.internet import reactor
  180. logger._loggerFor(self).info(
  181. "twistd {version} ({exe} {pyVersion}) starting up.",
  182. version=copyright.version, exe=sys.executable,
  183. pyVersion=runtime.shortPythonVersion())
  184. logger._loggerFor(self).info('reactor class: {reactor}.',
  185. reactor=qual(reactor.__class__))
  186. def _getLogObserver(self):
  187. """
  188. Create a log observer to be added to the logging system before running
  189. this application.
  190. """
  191. if self._logfilename == '-' or not self._logfilename:
  192. logFile = sys.stdout
  193. else:
  194. logFile = logfile.LogFile.fromFullPath(self._logfilename)
  195. return logger.textFileLogObserver(logFile)
  196. def stop(self):
  197. """
  198. Remove all log observers previously set up by L{AppLogger.start}.
  199. """
  200. logger._loggerFor(self).info("Server Shut Down.")
  201. if self._observer is not None:
  202. logger.globalLogPublisher.removeObserver(self._observer)
  203. self._observer = None
  204. def fixPdb():
  205. def do_stop(self, arg):
  206. self.clear_all_breaks()
  207. self.set_continue()
  208. from twisted.internet import reactor
  209. reactor.callLater(0, reactor.stop)
  210. return 1
  211. def help_stop(self):
  212. print("stop - Continue execution, then cleanly shutdown the twisted "
  213. "reactor.")
  214. def set_quit(self):
  215. os._exit(0)
  216. pdb.Pdb.set_quit = set_quit
  217. pdb.Pdb.do_stop = do_stop
  218. pdb.Pdb.help_stop = help_stop
  219. def runReactorWithLogging(config, oldstdout, oldstderr, profiler=None,
  220. reactor=None):
  221. """
  222. Start the reactor, using profiling if specified by the configuration, and
  223. log any error happening in the process.
  224. @param config: configuration of the twistd application.
  225. @type config: L{ServerOptions}
  226. @param oldstdout: initial value of C{sys.stdout}.
  227. @type oldstdout: C{file}
  228. @param oldstderr: initial value of C{sys.stderr}.
  229. @type oldstderr: C{file}
  230. @param profiler: object used to run the reactor with profiling.
  231. @type profiler: L{AppProfiler}
  232. @param reactor: The reactor to use. If L{None}, the global reactor will
  233. be used.
  234. """
  235. if reactor is None:
  236. from twisted.internet import reactor
  237. try:
  238. if config['profile']:
  239. if profiler is not None:
  240. profiler.run(reactor)
  241. elif config['debug']:
  242. sys.stdout = oldstdout
  243. sys.stderr = oldstderr
  244. if runtime.platformType == 'posix':
  245. signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
  246. signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
  247. fixPdb()
  248. pdb.runcall(reactor.run)
  249. else:
  250. reactor.run()
  251. except:
  252. close = False
  253. if config['nodaemon']:
  254. file = oldstdout
  255. else:
  256. file = open("TWISTD-CRASH.log", "a")
  257. close = True
  258. try:
  259. traceback.print_exc(file=file)
  260. file.flush()
  261. finally:
  262. if close:
  263. file.close()
  264. def getPassphrase(needed):
  265. if needed:
  266. return getpass.getpass('Passphrase: ')
  267. else:
  268. return None
  269. def getSavePassphrase(needed):
  270. if needed:
  271. return util.getPassword("Encryption passphrase: ")
  272. else:
  273. return None
  274. class ApplicationRunner(object):
  275. """
  276. An object which helps running an application based on a config object.
  277. Subclass me and implement preApplication and postApplication
  278. methods. postApplication generally will want to run the reactor
  279. after starting the application.
  280. @ivar config: The config object, which provides a dict-like interface.
  281. @ivar application: Available in postApplication, but not
  282. preApplication. This is the application object.
  283. @ivar profilerFactory: Factory for creating a profiler object, able to
  284. profile the application if options are set accordingly.
  285. @ivar profiler: Instance provided by C{profilerFactory}.
  286. @ivar loggerFactory: Factory for creating object responsible for logging.
  287. @ivar logger: Instance provided by C{loggerFactory}.
  288. """
  289. profilerFactory = AppProfiler
  290. loggerFactory = AppLogger
  291. def __init__(self, config):
  292. self.config = config
  293. self.profiler = self.profilerFactory(config)
  294. self.logger = self.loggerFactory(config)
  295. def run(self):
  296. """
  297. Run the application.
  298. """
  299. self.preApplication()
  300. self.application = self.createOrGetApplication()
  301. self.logger.start(self.application)
  302. self.postApplication()
  303. self.logger.stop()
  304. def startReactor(self, reactor, oldstdout, oldstderr):
  305. """
  306. Run the reactor with the given configuration. Subclasses should
  307. probably call this from C{postApplication}.
  308. @see: L{runReactorWithLogging}
  309. """
  310. if reactor is None:
  311. from twisted.internet import reactor
  312. runReactorWithLogging(
  313. self.config, oldstdout, oldstderr, self.profiler, reactor)
  314. if _ISupportsExitSignalCapturing.providedBy(reactor):
  315. self._exitSignal = reactor._exitSignal
  316. else:
  317. self._exitSignal = None
  318. def preApplication(self):
  319. """
  320. Override in subclass.
  321. This should set up any state necessary before loading and
  322. running the Application.
  323. """
  324. raise NotImplementedError()
  325. def postApplication(self):
  326. """
  327. Override in subclass.
  328. This will be called after the application has been loaded (so
  329. the C{application} attribute will be set). Generally this
  330. should start the application and run the reactor.
  331. """
  332. raise NotImplementedError()
  333. def createOrGetApplication(self):
  334. """
  335. Create or load an Application based on the parameters found in the
  336. given L{ServerOptions} instance.
  337. If a subcommand was used, the L{service.IServiceMaker} that it
  338. represents will be used to construct a service to be added to
  339. a newly-created Application.
  340. Otherwise, an application will be loaded based on parameters in
  341. the config.
  342. """
  343. if self.config.subCommand:
  344. # If a subcommand was given, it's our responsibility to create
  345. # the application, instead of load it from a file.
  346. # loadedPlugins is set up by the ServerOptions.subCommands
  347. # property, which is iterated somewhere in the bowels of
  348. # usage.Options.
  349. plg = self.config.loadedPlugins[self.config.subCommand]
  350. ser = plg.makeService(self.config.subOptions)
  351. application = service.Application(plg.tapname)
  352. ser.setServiceParent(application)
  353. else:
  354. passphrase = getPassphrase(self.config['encrypted'])
  355. application = getApplication(self.config, passphrase)
  356. return application
  357. def getApplication(config, passphrase):
  358. s = [(config[t], t)
  359. for t in ['python', 'source', 'file'] if config[t]][0]
  360. filename, style = s[0], {'file': 'pickle'}.get(s[1], s[1])
  361. try:
  362. log.msg("Loading %s..." % filename)
  363. application = service.loadApplication(filename, style, passphrase)
  364. log.msg("Loaded.")
  365. except Exception as e:
  366. s = "Failed to load application: %s" % e
  367. if isinstance(e, KeyError) and e.args[0] == "application":
  368. s += """
  369. Could not find 'application' in the file. To use 'twistd -y', your .tac
  370. file must create a suitable object (e.g., by calling service.Application())
  371. and store it in a variable named 'application'. twistd loads your .tac file
  372. and scans the global variables for one of this name.
  373. Please read the 'Using Application' HOWTO for details.
  374. """
  375. traceback.print_exc(file=log.logfile)
  376. log.msg(s)
  377. log.deferr()
  378. sys.exit('\n' + s + '\n')
  379. return application
  380. def _reactorAction():
  381. return usage.CompleteList([r.shortName for r in
  382. reactors.getReactorTypes()])
  383. @_oldStyle
  384. class ReactorSelectionMixin:
  385. """
  386. Provides options for selecting a reactor to install.
  387. If a reactor is installed, the short name which was used to locate it is
  388. saved as the value for the C{"reactor"} key.
  389. """
  390. compData = usage.Completions(
  391. optActions={"reactor": _reactorAction})
  392. messageOutput = sys.stdout
  393. _getReactorTypes = staticmethod(reactors.getReactorTypes)
  394. def opt_help_reactors(self):
  395. """
  396. Display a list of possibly available reactor names.
  397. """
  398. rcts = sorted(self._getReactorTypes(), key=attrgetter('shortName'))
  399. notWorkingReactors = ""
  400. for r in rcts:
  401. try:
  402. namedModule(r.moduleName)
  403. self.messageOutput.write(' %-4s\t%s\n' %
  404. (r.shortName, r.description))
  405. except ImportError as e:
  406. notWorkingReactors += (' !%-4s\t%s (%s)\n' %
  407. (r.shortName, r.description, e.args[0]))
  408. if notWorkingReactors:
  409. self.messageOutput.write('\n')
  410. self.messageOutput.write(' reactors not available '
  411. 'on this platform:\n\n')
  412. self.messageOutput.write(notWorkingReactors)
  413. raise SystemExit(0)
  414. def opt_reactor(self, shortName):
  415. """
  416. Which reactor to use (see --help-reactors for a list of possibilities)
  417. """
  418. # Actually actually actually install the reactor right at this very
  419. # moment, before any other code (for example, a sub-command plugin)
  420. # runs and accidentally imports and installs the default reactor.
  421. #
  422. # This could probably be improved somehow.
  423. try:
  424. installReactor(shortName)
  425. except NoSuchReactor:
  426. msg = ("The specified reactor does not exist: '%s'.\n"
  427. "See the list of available reactors with "
  428. "--help-reactors" % (shortName,))
  429. raise usage.UsageError(msg)
  430. except Exception as e:
  431. msg = ("The specified reactor cannot be used, failed with error: "
  432. "%s.\nSee the list of available reactors with "
  433. "--help-reactors" % (e,))
  434. raise usage.UsageError(msg)
  435. else:
  436. self["reactor"] = shortName
  437. opt_r = opt_reactor
  438. class ServerOptions(usage.Options, ReactorSelectionMixin):
  439. longdesc = ("twistd reads a twisted.application.service.Application out "
  440. "of a file and runs it.")
  441. optFlags = [['savestats', None,
  442. "save the Stats object rather than the text output of "
  443. "the profiler."],
  444. ['no_save', 'o', "do not save state on shutdown"],
  445. ['encrypted', 'e',
  446. "The specified tap/aos file is encrypted."]]
  447. optParameters = [['logfile', 'l', None,
  448. "log to a specified file, - for stdout"],
  449. ['logger', None, None,
  450. "A fully-qualified name to a log observer factory to "
  451. "use for the initial log observer. Takes precedence "
  452. "over --logfile and --syslog (when available)."],
  453. ['profile', 'p', None,
  454. "Run in profile mode, dumping results to specified "
  455. "file."],
  456. ['profiler', None, "cprofile",
  457. "Name of the profiler to use (%s)." %
  458. ", ".join(AppProfiler.profilers)],
  459. ['file', 'f', 'twistd.tap',
  460. "read the given .tap file"],
  461. ['python', 'y', None,
  462. "read an application from within a Python file "
  463. "(implies -o)"],
  464. ['source', 's', None,
  465. "Read an application from a .tas file (AOT format)."],
  466. ['rundir', 'd', '.',
  467. 'Change to a supplied directory before running']]
  468. compData = usage.Completions(
  469. mutuallyExclusive=[("file", "python", "source")],
  470. optActions={"file": usage.CompleteFiles("*.tap"),
  471. "python": usage.CompleteFiles("*.(tac|py)"),
  472. "source": usage.CompleteFiles("*.tas"),
  473. "rundir": usage.CompleteDirs()}
  474. )
  475. _getPlugins = staticmethod(plugin.getPlugins)
  476. def __init__(self, *a, **kw):
  477. self['debug'] = False
  478. if 'stdout' in kw:
  479. self.stdout = kw['stdout']
  480. else:
  481. self.stdout = sys.stdout
  482. usage.Options.__init__(self)
  483. def opt_debug(self):
  484. """
  485. Run the application in the Python Debugger (implies nodaemon),
  486. sending SIGUSR2 will drop into debugger
  487. """
  488. defer.setDebugging(True)
  489. failure.startDebugMode()
  490. self['debug'] = True
  491. opt_b = opt_debug
  492. def opt_spew(self):
  493. """
  494. Print an insanely verbose log of everything that happens.
  495. Useful when debugging freezes or locks in complex code.
  496. """
  497. sys.settrace(util.spewer)
  498. try:
  499. import threading
  500. except ImportError:
  501. return
  502. threading.settrace(util.spewer)
  503. def parseOptions(self, options=None):
  504. if options is None:
  505. options = sys.argv[1:] or ["--help"]
  506. usage.Options.parseOptions(self, options)
  507. def postOptions(self):
  508. if self.subCommand or self['python']:
  509. self['no_save'] = True
  510. if self['logger'] is not None:
  511. try:
  512. self['logger'] = namedAny(self['logger'])
  513. except Exception as e:
  514. raise usage.UsageError("Logger '%s' could not be imported: %s"
  515. % (self['logger'], e))
  516. def subCommands(self):
  517. plugins = self._getPlugins(service.IServiceMaker)
  518. self.loadedPlugins = {}
  519. for plug in sorted(plugins, key=attrgetter('tapname')):
  520. self.loadedPlugins[plug.tapname] = plug
  521. yield (plug.tapname,
  522. None,
  523. # Avoid resolving the options attribute right away, in case
  524. # it's a property with a non-trivial getter (eg, one which
  525. # imports modules).
  526. lambda plug=plug: plug.options(),
  527. plug.description)
  528. subCommands = property(subCommands)
  529. def run(runApp, ServerOptions):
  530. config = ServerOptions()
  531. try:
  532. config.parseOptions()
  533. except usage.error as ue:
  534. print(config)
  535. print("%s: %s" % (sys.argv[0], ue))
  536. else:
  537. runApp(config)
  538. def convertStyle(filein, typein, passphrase, fileout, typeout, encrypt):
  539. application = service.loadApplication(filein, typein, passphrase)
  540. sob.IPersistable(application).setStyle(typeout)
  541. passphrase = getSavePassphrase(encrypt)
  542. if passphrase:
  543. fileout = None
  544. sob.IPersistable(application).save(filename=fileout, passphrase=passphrase)
  545. def startApplication(application, save):
  546. from twisted.internet import reactor
  547. service.IService(application).startService()
  548. if save:
  549. p = sob.IPersistable(application)
  550. reactor.addSystemEventTrigger('after', 'shutdown', p.save, 'shutdown')
  551. reactor.addSystemEventTrigger('before', 'shutdown',
  552. service.IService(application).stopService)
  553. def _exitWithSignal(sig):
  554. """
  555. Force the application to terminate with the specified signal by replacing
  556. the signal handler with the default and sending the signal to ourselves.
  557. @param sig: Signal to use to terminate the process with C{os.kill}.
  558. @type sig: C{int}
  559. """
  560. signal.signal(sig, signal.SIG_DFL)
  561. os.kill(os.getpid(), sig)