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.

distrib.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # -*- test-case-name: twisted.web.test.test_distrib -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Distributed web servers.
  6. This is going to have to be refactored so that argument parsing is done
  7. by each subprocess and not by the main web server (i.e. GET, POST etc.).
  8. """
  9. import copy
  10. import os
  11. import sys
  12. try:
  13. import pwd
  14. except ImportError:
  15. pwd = None # type: ignore[assignment]
  16. from io import BytesIO
  17. from xml.dom.minidom import getDOMImplementation
  18. from twisted.internet import address, reactor
  19. from twisted.logger import Logger
  20. from twisted.persisted import styles
  21. from twisted.spread import pb
  22. from twisted.spread.banana import SIZE_LIMIT
  23. from twisted.web import http, resource, server, static, util
  24. from twisted.web.http_headers import Headers
  25. class _ReferenceableProducerWrapper(pb.Referenceable):
  26. def __init__(self, producer):
  27. self.producer = producer
  28. def remote_resumeProducing(self):
  29. self.producer.resumeProducing()
  30. def remote_pauseProducing(self):
  31. self.producer.pauseProducing()
  32. def remote_stopProducing(self):
  33. self.producer.stopProducing()
  34. class Request(pb.RemoteCopy, server.Request):
  35. """
  36. A request which was received by a L{ResourceSubscription} and sent via
  37. PB to a distributed node.
  38. """
  39. def setCopyableState(self, state):
  40. """
  41. Initialize this L{twisted.web.distrib.Request} based on the copied
  42. state so that it closely resembles a L{twisted.web.server.Request}.
  43. """
  44. for k in "host", "client":
  45. tup = state[k]
  46. addrdesc = {"INET": "TCP", "UNIX": "UNIX"}[tup[0]]
  47. addr = {
  48. "TCP": lambda: address.IPv4Address(addrdesc, tup[1], tup[2]),
  49. "UNIX": lambda: address.UNIXAddress(tup[1]),
  50. }[addrdesc]()
  51. state[k] = addr
  52. state["requestHeaders"] = Headers(dict(state["requestHeaders"]))
  53. pb.RemoteCopy.setCopyableState(self, state)
  54. # Emulate the local request interface --
  55. self.content = BytesIO(self.content_data)
  56. self.finish = self.remote.remoteMethod("finish")
  57. self.setHeader = self.remote.remoteMethod("setHeader")
  58. self.addCookie = self.remote.remoteMethod("addCookie")
  59. self.setETag = self.remote.remoteMethod("setETag")
  60. self.setResponseCode = self.remote.remoteMethod("setResponseCode")
  61. self.setLastModified = self.remote.remoteMethod("setLastModified")
  62. # To avoid failing if a resource tries to write a very long string
  63. # all at once, this one will be handled slightly differently.
  64. self._write = self.remote.remoteMethod("write")
  65. def write(self, bytes):
  66. """
  67. Write the given bytes to the response body.
  68. @param bytes: The bytes to write. If this is longer than 640k, it
  69. will be split up into smaller pieces.
  70. """
  71. start = 0
  72. end = SIZE_LIMIT
  73. while True:
  74. self._write(bytes[start:end])
  75. start += SIZE_LIMIT
  76. end += SIZE_LIMIT
  77. if start >= len(bytes):
  78. break
  79. def registerProducer(self, producer, streaming):
  80. self.remote.callRemote(
  81. "registerProducer", _ReferenceableProducerWrapper(producer), streaming
  82. ).addErrback(self.fail)
  83. def unregisterProducer(self):
  84. self.remote.callRemote("unregisterProducer").addErrback(self.fail)
  85. def fail(self, failure):
  86. self._log.failure("", failure=failure)
  87. pb.setUnjellyableForClass(server.Request, Request)
  88. class Issue:
  89. _log = Logger()
  90. def __init__(self, request):
  91. self.request = request
  92. def finished(self, result):
  93. if result is not server.NOT_DONE_YET:
  94. assert isinstance(result, str), "return value not a string"
  95. self.request.write(result)
  96. self.request.finish()
  97. def failed(self, failure):
  98. # XXX: Argh. FIXME.
  99. failure = str(failure)
  100. self.request.write(
  101. resource._UnsafeErrorPage(
  102. http.INTERNAL_SERVER_ERROR,
  103. "Server Connection Lost",
  104. # GHSA-vg46-2rrj-3647 note: _PRE does HTML-escape the input.
  105. "Connection to distributed server lost:" + util._PRE(failure),
  106. ).render(self.request)
  107. )
  108. self.request.finish()
  109. self._log.info(failure)
  110. class ResourceSubscription(resource.Resource):
  111. isLeaf = 1
  112. waiting = 0
  113. _log = Logger()
  114. def __init__(self, host, port):
  115. resource.Resource.__init__(self)
  116. self.host = host
  117. self.port = port
  118. self.pending = []
  119. self.publisher = None
  120. def __getstate__(self):
  121. """Get persistent state for this ResourceSubscription."""
  122. # When I unserialize,
  123. state = copy.copy(self.__dict__)
  124. # Publisher won't be connected...
  125. state["publisher"] = None
  126. # I won't be making a connection
  127. state["waiting"] = 0
  128. # There will be no pending requests.
  129. state["pending"] = []
  130. return state
  131. def connected(self, publisher):
  132. """I've connected to a publisher; I'll now send all my requests."""
  133. self._log.info("connected to publisher")
  134. publisher.broker.notifyOnDisconnect(self.booted)
  135. self.publisher = publisher
  136. self.waiting = 0
  137. for request in self.pending:
  138. self.render(request)
  139. self.pending = []
  140. def notConnected(self, msg):
  141. """I can't connect to a publisher; I'll now reply to all pending
  142. requests.
  143. """
  144. self._log.info("could not connect to distributed web service: {msg}", msg=msg)
  145. self.waiting = 0
  146. self.publisher = None
  147. for request in self.pending:
  148. request.write("Unable to connect to distributed server.")
  149. request.finish()
  150. self.pending = []
  151. def booted(self):
  152. self.notConnected("connection dropped")
  153. def render(self, request):
  154. """Render this request, from my server.
  155. This will always be asynchronous, and therefore return NOT_DONE_YET.
  156. It spins off a request to the pb client, and either adds it to the list
  157. of pending issues or requests it immediately, depending on if the
  158. client is already connected.
  159. """
  160. if not self.publisher:
  161. self.pending.append(request)
  162. if not self.waiting:
  163. self.waiting = 1
  164. bf = pb.PBClientFactory()
  165. timeout = 10
  166. if self.host == "unix":
  167. reactor.connectUNIX(self.port, bf, timeout)
  168. else:
  169. reactor.connectTCP(self.host, self.port, bf, timeout)
  170. d = bf.getRootObject()
  171. d.addCallbacks(self.connected, self.notConnected)
  172. else:
  173. i = Issue(request)
  174. self.publisher.callRemote("request", request).addCallbacks(
  175. i.finished, i.failed
  176. )
  177. return server.NOT_DONE_YET
  178. class ResourcePublisher(pb.Root, styles.Versioned):
  179. """
  180. L{ResourcePublisher} exposes a remote API which can be used to respond
  181. to request.
  182. @ivar site: The site which will be used for resource lookup.
  183. @type site: L{twisted.web.server.Site}
  184. """
  185. _log = Logger()
  186. def __init__(self, site):
  187. self.site = site
  188. persistenceVersion = 2
  189. def upgradeToVersion2(self):
  190. self.application.authorizer.removeIdentity("web")
  191. del self.application.services[self.serviceName]
  192. del self.serviceName
  193. del self.application
  194. del self.perspectiveName
  195. def getPerspectiveNamed(self, name):
  196. return self
  197. def remote_request(self, request):
  198. """
  199. Look up the resource for the given request and render it.
  200. """
  201. res = self.site.getResourceFor(request)
  202. self._log.info(request)
  203. result = res.render(request)
  204. if result is not server.NOT_DONE_YET:
  205. request.write(result)
  206. request.finish()
  207. return server.NOT_DONE_YET
  208. class UserDirectory(resource.Resource):
  209. """
  210. A resource which lists available user resources and serves them as
  211. children.
  212. @ivar _pwd: An object like L{pwd} which is used to enumerate users and
  213. their home directories.
  214. """
  215. userDirName = "public_html"
  216. userSocketName = ".twistd-web-pb"
  217. template = """
  218. <html>
  219. <head>
  220. <title>twisted.web.distrib.UserDirectory</title>
  221. <style>
  222. a
  223. {
  224. font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
  225. color: #369;
  226. text-decoration: none;
  227. }
  228. th
  229. {
  230. font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
  231. font-weight: bold;
  232. text-decoration: none;
  233. text-align: left;
  234. }
  235. pre, code
  236. {
  237. font-family: "Courier New", Courier, monospace;
  238. }
  239. p, body, td, ol, ul, menu, blockquote, div
  240. {
  241. font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
  242. color: #000;
  243. }
  244. </style>
  245. </head>
  246. <body>
  247. <h1>twisted.web.distrib.UserDirectory</h1>
  248. %(users)s
  249. </body>
  250. </html>
  251. """
  252. def __init__(self, userDatabase=None):
  253. resource.Resource.__init__(self)
  254. if userDatabase is None:
  255. userDatabase = pwd
  256. self._pwd = userDatabase
  257. def _users(self):
  258. """
  259. Return a list of two-tuples giving links to user resources and text to
  260. associate with those links.
  261. """
  262. users = []
  263. for user in self._pwd.getpwall():
  264. name, passwd, uid, gid, gecos, dir, shell = user
  265. realname = gecos.split(",")[0]
  266. if not realname:
  267. realname = name
  268. if os.path.exists(os.path.join(dir, self.userDirName)):
  269. users.append((name, realname + " (file)"))
  270. twistdsock = os.path.join(dir, self.userSocketName)
  271. if os.path.exists(twistdsock):
  272. linkName = name + ".twistd"
  273. users.append((linkName, realname + " (twistd)"))
  274. return users
  275. def render_GET(self, request):
  276. """
  277. Render as HTML a listing of all known users with links to their
  278. personal resources.
  279. """
  280. domImpl = getDOMImplementation()
  281. newDoc = domImpl.createDocument(None, "ul", None)
  282. listing = newDoc.documentElement
  283. for link, text in self._users():
  284. linkElement = newDoc.createElement("a")
  285. linkElement.setAttribute("href", link + "/")
  286. textNode = newDoc.createTextNode(text)
  287. linkElement.appendChild(textNode)
  288. item = newDoc.createElement("li")
  289. item.appendChild(linkElement)
  290. listing.appendChild(item)
  291. htmlDoc = self.template % ({"users": listing.toxml()})
  292. return htmlDoc.encode("utf-8")
  293. def getChild(self, name, request):
  294. if name == b"":
  295. return self
  296. td = b".twistd"
  297. if name.endswith(td):
  298. username = name[: -len(td)]
  299. sub = 1
  300. else:
  301. username = name
  302. sub = 0
  303. try:
  304. # Decode using the filesystem encoding to reverse a transformation
  305. # done in the pwd module.
  306. (
  307. pw_name,
  308. pw_passwd,
  309. pw_uid,
  310. pw_gid,
  311. pw_gecos,
  312. pw_dir,
  313. pw_shell,
  314. ) = self._pwd.getpwnam(username.decode(sys.getfilesystemencoding()))
  315. except KeyError:
  316. return resource._UnsafeNoResource()
  317. if sub:
  318. twistdsock = os.path.join(pw_dir, self.userSocketName)
  319. rs = ResourceSubscription("unix", twistdsock)
  320. self.putChild(name, rs)
  321. return rs
  322. else:
  323. path = os.path.join(pw_dir, self.userDirName)
  324. if not os.path.exists(path):
  325. return resource._UnsafeNoResource()
  326. return static.File(path)