Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.py 23KB

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