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.

service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # -*- test-case-name: twisted.application.test.test_service -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Service architecture for Twisted.
  6. Services are arranged in a hierarchy. At the leafs of the hierarchy,
  7. the services which actually interact with the outside world are started.
  8. Services can be named or anonymous -- usually, they will be named if
  9. there is need to access them through the hierarchy (from a parent or
  10. a sibling).
  11. Maintainer: Moshe Zadka
  12. """
  13. from zope.interface import Attribute, Interface, implementer
  14. from twisted.internet import defer
  15. from twisted.persisted import sob
  16. from twisted.plugin import IPlugin
  17. from twisted.python import components
  18. from twisted.python.reflect import namedAny
  19. class IServiceMaker(Interface):
  20. """
  21. An object which can be used to construct services in a flexible
  22. way.
  23. This interface should most often be implemented along with
  24. L{twisted.plugin.IPlugin}, and will most often be used by the
  25. 'twistd' command.
  26. """
  27. tapname = Attribute(
  28. "A short string naming this Twisted plugin, for example 'web' or "
  29. "'pencil'. This name will be used as the subcommand of 'twistd'."
  30. )
  31. description = Attribute(
  32. "A brief summary of the features provided by this "
  33. "Twisted application plugin."
  34. )
  35. options = Attribute(
  36. "A C{twisted.python.usage.Options} subclass defining the "
  37. "configuration options for this application."
  38. )
  39. def makeService(options):
  40. """
  41. Create and return an object providing
  42. L{twisted.application.service.IService}.
  43. @param options: A mapping (typically a C{dict} or
  44. L{twisted.python.usage.Options} instance) of configuration
  45. options to desired configuration values.
  46. """
  47. @implementer(IPlugin, IServiceMaker)
  48. class ServiceMaker:
  49. """
  50. Utility class to simplify the definition of L{IServiceMaker} plugins.
  51. """
  52. def __init__(self, name, module, description, tapname):
  53. self.name = name
  54. self.module = module
  55. self.description = description
  56. self.tapname = tapname
  57. @property
  58. def options(self):
  59. return namedAny(self.module).Options
  60. @property
  61. def makeService(self):
  62. return namedAny(self.module).makeService
  63. class IService(Interface):
  64. """
  65. A service.
  66. Run start-up and shut-down code at the appropriate times.
  67. """
  68. name = Attribute("A C{str} which is the name of the service or C{None}.")
  69. running = Attribute("A C{boolean} which indicates whether the service is running.")
  70. parent = Attribute("An C{IServiceCollection} which is the parent or C{None}.")
  71. def setName(name):
  72. """
  73. Set the name of the service.
  74. @type name: C{str}
  75. @raise RuntimeError: Raised if the service already has a parent.
  76. """
  77. def setServiceParent(parent):
  78. """
  79. Set the parent of the service. This method is responsible for setting
  80. the C{parent} attribute on this service (the child service).
  81. @type parent: L{IServiceCollection}
  82. @raise RuntimeError: Raised if the service already has a parent
  83. or if the service has a name and the parent already has a child
  84. by that name.
  85. """
  86. def disownServiceParent():
  87. """
  88. Use this API to remove an L{IService} from an L{IServiceCollection}.
  89. This method is used symmetrically with L{setServiceParent} in that it
  90. sets the C{parent} attribute on the child.
  91. @rtype: L{Deferred<defer.Deferred>}
  92. @return: a L{Deferred<defer.Deferred>} which is triggered when the
  93. service has finished shutting down. If shutting down is immediate,
  94. a value can be returned (usually, L{None}).
  95. """
  96. def startService():
  97. """
  98. Start the service.
  99. """
  100. def stopService():
  101. """
  102. Stop the service.
  103. @rtype: L{Deferred<defer.Deferred>}
  104. @return: a L{Deferred<defer.Deferred>} which is triggered when the
  105. service has finished shutting down. If shutting down is immediate,
  106. a value can be returned (usually, L{None}).
  107. """
  108. def privilegedStartService():
  109. """
  110. Do preparation work for starting the service.
  111. Here things which should be done before changing directory,
  112. root or shedding privileges are done.
  113. """
  114. @implementer(IService)
  115. class Service:
  116. """
  117. Base class for services.
  118. Most services should inherit from this class. It handles the
  119. book-keeping responsibilities of starting and stopping, as well
  120. as not serializing this book-keeping information.
  121. """
  122. running = 0
  123. name = None
  124. parent = None
  125. def __getstate__(self):
  126. dict = self.__dict__.copy()
  127. if "running" in dict:
  128. del dict["running"]
  129. return dict
  130. def setName(self, name):
  131. if self.parent is not None:
  132. raise RuntimeError("cannot change name when parent exists")
  133. self.name = name
  134. def setServiceParent(self, parent):
  135. if self.parent is not None:
  136. self.disownServiceParent()
  137. parent = IServiceCollection(parent, parent)
  138. self.parent = parent
  139. self.parent.addService(self)
  140. def disownServiceParent(self):
  141. d = self.parent.removeService(self)
  142. self.parent = None
  143. return d
  144. def privilegedStartService(self):
  145. pass
  146. def startService(self):
  147. self.running = 1
  148. def stopService(self):
  149. self.running = 0
  150. class IServiceCollection(Interface):
  151. """
  152. Collection of services.
  153. Contain several services, and manage their start-up/shut-down.
  154. Services can be accessed by name if they have a name, and it
  155. is always possible to iterate over them.
  156. """
  157. def getServiceNamed(name):
  158. """
  159. Get the child service with a given name.
  160. @type name: C{str}
  161. @rtype: L{IService}
  162. @raise KeyError: Raised if the service has no child with the
  163. given name.
  164. """
  165. def __iter__():
  166. """
  167. Get an iterator over all child services.
  168. """
  169. def addService(service):
  170. """
  171. Add a child service.
  172. Only implementations of L{IService.setServiceParent} should use this
  173. method.
  174. @type service: L{IService}
  175. @raise RuntimeError: Raised if the service has a child with
  176. the given name.
  177. """
  178. def removeService(service):
  179. """
  180. Remove a child service.
  181. Only implementations of L{IService.disownServiceParent} should
  182. use this method.
  183. @type service: L{IService}
  184. @raise ValueError: Raised if the given service is not a child.
  185. @rtype: L{Deferred<defer.Deferred>}
  186. @return: a L{Deferred<defer.Deferred>} which is triggered when the
  187. service has finished shutting down. If shutting down is immediate,
  188. a value can be returned (usually, L{None}).
  189. """
  190. @implementer(IServiceCollection)
  191. class MultiService(Service):
  192. """
  193. Straightforward Service Container.
  194. Hold a collection of services, and manage them in a simplistic
  195. way. No service will wait for another, but this object itself
  196. will not finish shutting down until all of its child services
  197. will finish.
  198. """
  199. def __init__(self):
  200. self.services = []
  201. self.namedServices = {}
  202. self.parent = None
  203. def privilegedStartService(self):
  204. Service.privilegedStartService(self)
  205. for service in self:
  206. service.privilegedStartService()
  207. def startService(self):
  208. Service.startService(self)
  209. for service in self:
  210. service.startService()
  211. def stopService(self):
  212. Service.stopService(self)
  213. l = []
  214. services = list(self)
  215. services.reverse()
  216. for service in services:
  217. l.append(defer.maybeDeferred(service.stopService))
  218. return defer.DeferredList(l)
  219. def getServiceNamed(self, name):
  220. return self.namedServices[name]
  221. def __iter__(self):
  222. return iter(self.services)
  223. def addService(self, service):
  224. if service.name is not None:
  225. if service.name in self.namedServices:
  226. raise RuntimeError(
  227. "cannot have two services with same name" " '%s'" % service.name
  228. )
  229. self.namedServices[service.name] = service
  230. self.services.append(service)
  231. if self.running:
  232. # It may be too late for that, but we will do our best
  233. service.privilegedStartService()
  234. service.startService()
  235. def removeService(self, service):
  236. if service.name:
  237. del self.namedServices[service.name]
  238. self.services.remove(service)
  239. if self.running:
  240. # Returning this so as not to lose information from the
  241. # MultiService.stopService deferred.
  242. return service.stopService()
  243. else:
  244. return None
  245. class IProcess(Interface):
  246. """
  247. Process running parameters.
  248. Represents parameters for how processes should be run.
  249. """
  250. processName = Attribute(
  251. """
  252. A C{str} giving the name the process should have in ps (or L{None}
  253. to leave the name alone).
  254. """
  255. )
  256. uid = Attribute(
  257. """
  258. An C{int} giving the user id as which the process should run (or
  259. L{None} to leave the UID alone).
  260. """
  261. )
  262. gid = Attribute(
  263. """
  264. An C{int} giving the group id as which the process should run (or
  265. L{None} to leave the GID alone).
  266. """
  267. )
  268. @implementer(IProcess)
  269. class Process:
  270. """
  271. Process running parameters.
  272. Sets up uid/gid in the constructor, and has a default
  273. of L{None} as C{processName}.
  274. """
  275. processName = None
  276. def __init__(self, uid=None, gid=None):
  277. """
  278. Set uid and gid.
  279. @param uid: The user ID as whom to execute the process. If
  280. this is L{None}, no attempt will be made to change the UID.
  281. @param gid: The group ID as whom to execute the process. If
  282. this is L{None}, no attempt will be made to change the GID.
  283. """
  284. self.uid = uid
  285. self.gid = gid
  286. def Application(name, uid=None, gid=None):
  287. """
  288. Return a compound class.
  289. Return an object supporting the L{IService}, L{IServiceCollection},
  290. L{IProcess} and L{sob.IPersistable} interfaces, with the given
  291. parameters. Always access the return value by explicit casting to
  292. one of the interfaces.
  293. """
  294. ret = components.Componentized()
  295. availableComponents = [MultiService(), Process(uid, gid), sob.Persistent(ret, name)]
  296. for comp in availableComponents:
  297. ret.addComponent(comp, ignoreClass=1)
  298. IService(ret).setName(name)
  299. return ret
  300. def loadApplication(filename, kind, passphrase=None):
  301. """
  302. Load Application from a given file.
  303. The serialization format it was saved in should be given as
  304. C{kind}, and is one of C{pickle}, C{source}, C{xml} or C{python}. If
  305. C{passphrase} is given, the application was encrypted with the
  306. given passphrase.
  307. @type filename: C{str}
  308. @type kind: C{str}
  309. @type passphrase: C{str}
  310. """
  311. if kind == "python":
  312. application = sob.loadValueFromFile(filename, "application")
  313. else:
  314. application = sob.load(filename, kind)
  315. return application
  316. __all__ = [
  317. "IServiceMaker",
  318. "IService",
  319. "Service",
  320. "IServiceCollection",
  321. "MultiService",
  322. "IProcess",
  323. "Process",
  324. "Application",
  325. "loadApplication",
  326. ]