app.py 22 KB

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