worker.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. # -*- test-case-name: twisted.trial._dist.test.test_worker -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. This module implements the worker classes.
  7. @since: 12.3
  8. """
  9. import os
  10. from typing import Any, Awaitable, Callable, Dict, List, Optional, TextIO, TypeVar
  11. from unittest import TestCase
  12. from zope.interface import implementer
  13. from attrs import frozen
  14. from typing_extensions import Protocol, TypedDict
  15. from twisted.internet.defer import Deferred, DeferredList
  16. from twisted.internet.error import ProcessDone
  17. from twisted.internet.interfaces import IAddress, ITransport
  18. from twisted.internet.protocol import ProcessProtocol
  19. from twisted.logger import Logger
  20. from twisted.protocols.amp import AMP
  21. from twisted.python.failure import Failure
  22. from twisted.python.filepath import FilePath
  23. from twisted.python.reflect import namedObject
  24. from twisted.trial._dist import (
  25. _WORKER_AMP_STDIN,
  26. _WORKER_AMP_STDOUT,
  27. managercommands,
  28. workercommands,
  29. )
  30. from twisted.trial._dist.workerreporter import WorkerReporter
  31. from twisted.trial.reporter import TestResult
  32. from twisted.trial.runner import TestLoader, TrialSuite
  33. from twisted.trial.unittest import Todo
  34. from .stream import StreamOpen, StreamReceiver, StreamWrite
  35. @frozen(auto_exc=False)
  36. class WorkerException(Exception):
  37. """
  38. An exception was reported by a test running in a worker process.
  39. @ivar message: An error message describing the exception.
  40. """
  41. message: str
  42. class RunResult(TypedDict):
  43. """
  44. Represent the result of a L{workercommands.Run} command.
  45. """
  46. success: bool
  47. class Worker(Protocol):
  48. """
  49. An object that can run actions.
  50. """
  51. async def run(self, case: TestCase, result: TestResult) -> RunResult:
  52. """
  53. Run a test case.
  54. """
  55. _T = TypeVar("_T")
  56. WorkerAction = Callable[[Worker], Awaitable[_T]]
  57. class WorkerProtocol(AMP):
  58. """
  59. The worker-side trial distributed protocol.
  60. """
  61. logger = Logger()
  62. def __init__(self, forceGarbageCollection=False):
  63. self._loader = TestLoader()
  64. self._result = WorkerReporter(self)
  65. self._forceGarbageCollection = forceGarbageCollection
  66. @workercommands.Run.responder
  67. async def run(self, testCase: str) -> RunResult:
  68. """
  69. Run a test case by name.
  70. """
  71. with self._result.gatherReportingResults() as results:
  72. case = self._loader.loadByName(testCase)
  73. suite = TrialSuite([case], self._forceGarbageCollection)
  74. suite.run(self._result)
  75. allSucceeded = True
  76. for success, result in await DeferredList(results, consumeErrors=True):
  77. if success:
  78. # Nothing to do here, proceed to the next result.
  79. continue
  80. # There was some error reporting a result to the peer.
  81. allSucceeded = False
  82. # We can try to report the error but since something has already
  83. # gone wrong we shouldn't be extremely confident that this will
  84. # succeed. So we will also log it (and any errors reporting *it*)
  85. # to our local log.
  86. self.logger.failure(
  87. "Result reporting for {id} failed",
  88. # The DeferredList type annotation assumes all results succeed
  89. failure=result, # type: ignore[arg-type]
  90. id=testCase,
  91. )
  92. try:
  93. await self._result.addErrorFallible(
  94. testCase,
  95. # The DeferredList type annotation assumes all results succeed
  96. result, # type: ignore[arg-type]
  97. )
  98. except BaseException:
  99. # We failed to report the failure to the peer. It doesn't
  100. # seem very likely that reporting this new failure to the peer
  101. # will succeed so just log it locally.
  102. self.logger.failure(
  103. "Additionally, reporting the reporting failure failed."
  104. )
  105. return {"success": allSucceeded}
  106. @workercommands.Start.responder
  107. def start(self, directory):
  108. """
  109. Set up the worker, moving into given directory for tests to run in
  110. them.
  111. """
  112. os.chdir(directory)
  113. return {"success": True}
  114. class LocalWorkerAMP(AMP):
  115. """
  116. Local implementation of the manager commands.
  117. """
  118. def __init__(self, boxReceiver=None, locator=None):
  119. super().__init__(boxReceiver, locator)
  120. self._streams = StreamReceiver()
  121. @StreamOpen.responder
  122. def streamOpen(self):
  123. return {"streamId": self._streams.open()}
  124. @StreamWrite.responder
  125. def streamWrite(self, streamId, data):
  126. self._streams.write(streamId, data)
  127. return {}
  128. @managercommands.AddSuccess.responder
  129. def addSuccess(self, testName):
  130. """
  131. Add a success to the reporter.
  132. """
  133. self._result.addSuccess(self._testCase)
  134. return {"success": True}
  135. def _buildFailure(
  136. self,
  137. error: WorkerException,
  138. errorClass: str,
  139. frames: List[str],
  140. ) -> Failure:
  141. """
  142. Helper to build a C{Failure} with some traceback.
  143. @param error: An C{Exception} instance.
  144. @param errorClass: The class name of the C{error} class.
  145. @param frames: A flat list of strings representing the information need
  146. to approximatively rebuild C{Failure} frames.
  147. @return: A L{Failure} instance with enough information about a test
  148. error.
  149. """
  150. errorType = namedObject(errorClass)
  151. failure = Failure(error, errorType)
  152. for i in range(0, len(frames), 3):
  153. failure.frames.append(
  154. (frames[i], frames[i + 1], int(frames[i + 2]), [], [])
  155. )
  156. return failure
  157. @managercommands.AddError.responder
  158. def addError(
  159. self,
  160. testName: str,
  161. errorClass: str,
  162. errorStreamId: int,
  163. framesStreamId: int,
  164. ) -> Dict[str, bool]:
  165. """
  166. Add an error to the reporter.
  167. @param errorStreamId: The identifier of a stream over which the text
  168. of this error was previously completely sent to the peer.
  169. @param framesStreamId: The identifier of a stream over which the lines
  170. of the traceback for this error were previously completely sent to
  171. the peer.
  172. @param error: A message describing the error.
  173. """
  174. error = b"".join(self._streams.finish(errorStreamId)).decode("utf-8")
  175. frames = [
  176. frame.decode("utf-8") for frame in self._streams.finish(framesStreamId)
  177. ]
  178. # Wrap the error message in ``WorkerException`` because it is not
  179. # possible to transfer arbitrary exception values over the AMP
  180. # connection to the main process but we must give *some* Exception
  181. # (not a str) to the test result object.
  182. failure = self._buildFailure(WorkerException(error), errorClass, frames)
  183. self._result.addError(self._testCase, failure)
  184. return {"success": True}
  185. @managercommands.AddFailure.responder
  186. def addFailure(
  187. self,
  188. testName: str,
  189. failStreamId: int,
  190. failClass: str,
  191. framesStreamId: int,
  192. ) -> Dict[str, bool]:
  193. """
  194. Add a failure to the reporter.
  195. @param failStreamId: The identifier of a stream over which the text of
  196. this failure was previously completely sent to the peer.
  197. @param framesStreamId: The identifier of a stream over which the lines
  198. of the traceback for this error were previously completely sent to the
  199. peer.
  200. """
  201. fail = b"".join(self._streams.finish(failStreamId)).decode("utf-8")
  202. frames = [
  203. frame.decode("utf-8") for frame in self._streams.finish(framesStreamId)
  204. ]
  205. # See addError for info about use of WorkerException here.
  206. failure = self._buildFailure(WorkerException(fail), failClass, frames)
  207. self._result.addFailure(self._testCase, failure)
  208. return {"success": True}
  209. @managercommands.AddSkip.responder
  210. def addSkip(self, testName, reason):
  211. """
  212. Add a skip to the reporter.
  213. """
  214. self._result.addSkip(self._testCase, reason)
  215. return {"success": True}
  216. @managercommands.AddExpectedFailure.responder
  217. def addExpectedFailure(
  218. self, testName: str, errorStreamId: int, todo: Optional[str]
  219. ) -> Dict[str, bool]:
  220. """
  221. Add an expected failure to the reporter.
  222. @param errorStreamId: The identifier of a stream over which the text
  223. of this error was previously completely sent to the peer.
  224. """
  225. error = b"".join(self._streams.finish(errorStreamId)).decode("utf-8")
  226. _todo = Todo("<unknown>" if todo is None else todo)
  227. self._result.addExpectedFailure(self._testCase, error, _todo)
  228. return {"success": True}
  229. @managercommands.AddUnexpectedSuccess.responder
  230. def addUnexpectedSuccess(self, testName, todo):
  231. """
  232. Add an unexpected success to the reporter.
  233. """
  234. self._result.addUnexpectedSuccess(self._testCase, todo)
  235. return {"success": True}
  236. @managercommands.TestWrite.responder
  237. def testWrite(self, out):
  238. """
  239. Print test output from the worker.
  240. """
  241. self._testStream.write(out + "\n")
  242. self._testStream.flush()
  243. return {"success": True}
  244. async def run(self, testCase: TestCase, result: TestResult) -> RunResult:
  245. """
  246. Run a test.
  247. """
  248. self._testCase = testCase
  249. self._result = result
  250. self._result.startTest(testCase)
  251. testCaseId = testCase.id()
  252. try:
  253. return await self.callRemote(workercommands.Run, testCase=testCaseId) # type: ignore[no-any-return]
  254. finally:
  255. self._result.stopTest(testCase)
  256. def setTestStream(self, stream):
  257. """
  258. Set the stream used to log output from tests.
  259. """
  260. self._testStream = stream
  261. @implementer(IAddress)
  262. class LocalWorkerAddress:
  263. """
  264. A L{IAddress} implementation meant to provide stub addresses for
  265. L{ITransport.getPeer} and L{ITransport.getHost}.
  266. """
  267. @implementer(ITransport)
  268. class LocalWorkerTransport:
  269. """
  270. A stub transport implementation used to support L{AMP} over a
  271. L{ProcessProtocol} transport.
  272. """
  273. def __init__(self, transport):
  274. self._transport = transport
  275. def write(self, data):
  276. """
  277. Forward data to transport.
  278. """
  279. self._transport.writeToChild(_WORKER_AMP_STDIN, data)
  280. def writeSequence(self, sequence):
  281. """
  282. Emulate C{writeSequence} by iterating data in the C{sequence}.
  283. """
  284. for data in sequence:
  285. self._transport.writeToChild(_WORKER_AMP_STDIN, data)
  286. def loseConnection(self):
  287. """
  288. Closes the transport.
  289. """
  290. self._transport.loseConnection()
  291. def getHost(self):
  292. """
  293. Return a L{LocalWorkerAddress} instance.
  294. """
  295. return LocalWorkerAddress()
  296. def getPeer(self):
  297. """
  298. Return a L{LocalWorkerAddress} instance.
  299. """
  300. return LocalWorkerAddress()
  301. class NotRunning(Exception):
  302. """
  303. An operation was attempted on a worker process which is not running.
  304. """
  305. class LocalWorker(ProcessProtocol):
  306. """
  307. Local process worker protocol. This worker runs as a local process and
  308. communicates via stdin/out.
  309. @ivar _ampProtocol: The L{AMP} protocol instance used to communicate with
  310. the worker.
  311. @ivar _logDirectory: The directory where logs will reside.
  312. @ivar _logFile: The main log file for tests output.
  313. """
  314. def __init__(
  315. self,
  316. ampProtocol: LocalWorkerAMP,
  317. logDirectory: FilePath[Any],
  318. logFile: TextIO,
  319. ):
  320. self._ampProtocol = ampProtocol
  321. self._logDirectory = logDirectory
  322. self._logFile = logFile
  323. self.endDeferred: Deferred[None] = Deferred()
  324. async def exit(self) -> None:
  325. """
  326. Cause the worker process to exit.
  327. """
  328. if self.transport is None:
  329. raise NotRunning()
  330. endDeferred = self.endDeferred
  331. self.transport.closeChildFD(_WORKER_AMP_STDIN)
  332. try:
  333. await endDeferred
  334. except ProcessDone:
  335. pass
  336. def connectionMade(self):
  337. """
  338. When connection is made, create the AMP protocol instance.
  339. """
  340. self._ampProtocol.makeConnection(LocalWorkerTransport(self.transport))
  341. self._logDirectory.makedirs(ignoreExistingDirectory=True)
  342. self._outLog = self._logDirectory.child("out.log").open("w")
  343. self._errLog = self._logDirectory.child("err.log").open("w")
  344. self._ampProtocol.setTestStream(self._logFile)
  345. d = self._ampProtocol.callRemote(
  346. workercommands.Start,
  347. directory=self._logDirectory.path,
  348. )
  349. # Ignore the potential errors, the test suite will fail properly and it
  350. # would just print garbage.
  351. d.addErrback(lambda x: None)
  352. def connectionLost(self, reason):
  353. """
  354. On connection lost, close the log files that we're managing for stdin
  355. and stdout.
  356. """
  357. self._outLog.close()
  358. self._errLog.close()
  359. self.transport = None
  360. def processEnded(self, reason: Failure) -> None:
  361. """
  362. When the process closes, call C{connectionLost} for cleanup purposes
  363. and forward the information to the C{_ampProtocol}.
  364. """
  365. self.connectionLost(reason)
  366. self._ampProtocol.connectionLost(reason)
  367. self.endDeferred.callback(reason)
  368. def outReceived(self, data):
  369. """
  370. Send data received from stdout to log.
  371. """
  372. self._outLog.write(data)
  373. def errReceived(self, data):
  374. """
  375. Write error data to log.
  376. """
  377. self._errLog.write(data)
  378. def childDataReceived(self, childFD, data):
  379. """
  380. Handle data received on the specific pipe for the C{_ampProtocol}.
  381. """
  382. if childFD == _WORKER_AMP_STDOUT:
  383. self._ampProtocol.dataReceived(data)
  384. else:
  385. ProcessProtocol.childDataReceived(self, childFD, data)