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.

__main__.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. # this module is available as the 'wamp' command-line tool or as
  27. # 'python -m autobahn'
  28. import os
  29. import sys
  30. import argparse
  31. import json
  32. from copy import copy
  33. try:
  34. from autobahn.twisted.component import Component
  35. except ImportError:
  36. print("The 'wamp' command-line tool requires Twisted.")
  37. print(" pip install autobahn[twisted]")
  38. sys.exit(1)
  39. from twisted.internet.defer import Deferred, inlineCallbacks
  40. from twisted.internet.task import react
  41. from twisted.internet.protocol import ProcessProtocol
  42. from autobahn.wamp.exception import ApplicationError
  43. from autobahn.wamp.types import PublishOptions
  44. from autobahn.wamp.types import SubscribeOptions
  45. import txaio
  46. txaio.use_twisted()
  47. # XXX other ideas to get 'connection config':
  48. # - if there .crossbar/ here, load that config and accept a --name or
  49. # so to indicate which transport to use
  50. # wamp [options] {call,publish,subscribe,register} wamp-uri [args] [kwargs]
  51. #
  52. # kwargs are spec'd with a 2-value-consuming --keyword option:
  53. # --keyword name value
  54. top = argparse.ArgumentParser(prog="wamp")
  55. top.add_argument(
  56. '--url',
  57. action='store',
  58. help='A WAMP URL to connect to, like ws://127.0.0.1:8080/ws or rs://localhost:1234',
  59. required=True,
  60. )
  61. top.add_argument(
  62. '--realm', '-r',
  63. action='store',
  64. help='The realm to join',
  65. default='default',
  66. )
  67. top.add_argument(
  68. '--private-key', '-k',
  69. action='store',
  70. help='Hex-encoded private key (via WAMP_PRIVATE_KEY if not provided here)',
  71. default=os.environ.get('WAMP_PRIVATE_KEY', None),
  72. )
  73. top.add_argument(
  74. '--authid',
  75. action='store',
  76. help='The authid to use, if authenticating',
  77. default=None,
  78. )
  79. top.add_argument(
  80. '--authrole',
  81. action='store',
  82. help='The role to use, if authenticating',
  83. default=None,
  84. )
  85. top.add_argument(
  86. '--max-failures', '-m',
  87. action='store',
  88. type=int,
  89. help='Failures before giving up (0 forever)',
  90. default=0,
  91. )
  92. sub = top.add_subparsers(
  93. title="subcommands",
  94. dest="subcommand_name",
  95. )
  96. call = sub.add_parser(
  97. 'call',
  98. help='Do a WAMP call() and print any results',
  99. )
  100. call.add_argument(
  101. 'uri',
  102. type=str,
  103. help="A WAMP URI to call"
  104. )
  105. call.add_argument(
  106. 'call_args',
  107. nargs='*',
  108. help="All additional arguments are positional args",
  109. )
  110. call.add_argument(
  111. '--keyword',
  112. nargs=2,
  113. action='append',
  114. help="Specify a keyword argument to send: name value",
  115. )
  116. publish = sub.add_parser(
  117. 'publish',
  118. help='Do a WAMP publish() with the given args, kwargs',
  119. )
  120. publish.add_argument(
  121. 'uri',
  122. type=str,
  123. help="A WAMP URI to publish"
  124. )
  125. publish.add_argument(
  126. 'publish_args',
  127. nargs='*',
  128. help="All additional arguments are positional args",
  129. )
  130. publish.add_argument(
  131. '--keyword',
  132. nargs=2,
  133. action='append',
  134. help="Specify a keyword argument to send: name value",
  135. )
  136. register = sub.add_parser(
  137. 'register',
  138. help='Do a WAMP register() and run a command when called',
  139. )
  140. register.add_argument(
  141. 'uri',
  142. type=str,
  143. help="A WAMP URI to call"
  144. )
  145. register.add_argument(
  146. '--times',
  147. type=int,
  148. default=0,
  149. help="Listen for this number of events, then exit. Default: forever",
  150. )
  151. register.add_argument(
  152. 'command',
  153. type=str,
  154. nargs='*',
  155. help=(
  156. "Takes one or more args: the executable to call, and any positional "
  157. "arguments. As well, the following environment variables are set: "
  158. "WAMP_ARGS, WAMP_KWARGS and _JSON variants."
  159. )
  160. )
  161. subscribe = sub.add_parser(
  162. 'subscribe',
  163. help='Do a WAMP subscribe() and print one line of JSON per event',
  164. )
  165. subscribe.add_argument(
  166. 'uri',
  167. type=str,
  168. help="A WAMP URI to call"
  169. )
  170. subscribe.add_argument(
  171. '--times',
  172. type=int,
  173. default=0,
  174. help="Listen for this number of events, then exit. Default: forever",
  175. )
  176. subscribe.add_argument(
  177. '--match',
  178. type=str,
  179. default='exact',
  180. choices=['exact', 'prefix'],
  181. help="Massed in the SubscribeOptions, how to match the URI",
  182. )
  183. def _create_component(options):
  184. """
  185. Configure and return a Component instance according to the given
  186. `options`
  187. """
  188. if options.url.startswith('ws://'):
  189. kind = 'websocket'
  190. elif options.url.startswith('rs://'):
  191. kind = 'rawsocket'
  192. else:
  193. raise ValueError(
  194. "URL should start with ws:// or rs://"
  195. )
  196. authentication = dict()
  197. if options.private_key:
  198. if not options.authid:
  199. raise ValueError(
  200. "Require --authid and --authrole if --private-key (or WAMP_PRIVATE_KEY) is provided"
  201. )
  202. authentication["cryptosign"] = {
  203. "authid": options.authid,
  204. "authrole": options.authrole,
  205. "privkey": options.private_key,
  206. }
  207. return Component(
  208. transports=[{
  209. "type": kind,
  210. "url": options.url,
  211. }],
  212. authentication=authentication if authentication else None,
  213. realm=options.realm,
  214. )
  215. @inlineCallbacks
  216. def do_call(reactor, session, options):
  217. call_args = list(options.call_args)
  218. call_kwargs = dict()
  219. if options.keyword is not None:
  220. call_kwargs = {
  221. k: v
  222. for k, v in options.keyword
  223. }
  224. results = yield session.call(options.uri, *call_args, **call_kwargs)
  225. print("result: {}".format(results))
  226. @inlineCallbacks
  227. def do_publish(reactor, session, options):
  228. publish_args = list(options.publish_args)
  229. publish_kwargs = {} if options.keyword is None else {
  230. k: v
  231. for k, v in options.keyword
  232. }
  233. yield session.publish(
  234. options.uri,
  235. *publish_args,
  236. options=PublishOptions(acknowledge=True),
  237. **publish_kwargs
  238. )
  239. @inlineCallbacks
  240. def do_register(reactor, session, options):
  241. """
  242. run a command-line upon an RPC call
  243. """
  244. all_done = Deferred()
  245. countdown = [options.times]
  246. @inlineCallbacks
  247. def called(*args, **kw):
  248. print("called: args={}, kwargs={}".format(args, kw), file=sys.stderr)
  249. env = copy(os.environ)
  250. env['WAMP_ARGS'] = ' '.join(args)
  251. env['WAMP_ARGS_JSON'] = json.dumps(args)
  252. env['WAMP_KWARGS'] = ' '.join('{}={}'.format(k, v) for k, v in kw.items())
  253. env['WAMP_KWARGS_JSON'] = json.dumps(kw)
  254. exe = os.path.abspath(options.command[0])
  255. args = options.command
  256. done = Deferred()
  257. class DumpOutput(ProcessProtocol):
  258. def outReceived(self, data):
  259. sys.stdout.write(data.decode('utf8'))
  260. def errReceived(self, data):
  261. sys.stderr.write(data.decode('utf8'))
  262. def processExited(self, reason):
  263. done.callback(reason.value.exitCode)
  264. proto = DumpOutput()
  265. reactor.spawnProcess(
  266. proto, exe, args, env=env, path="."
  267. )
  268. code = yield done
  269. if code != 0:
  270. print("Failed with exit-code {}".format(code))
  271. if countdown[0]:
  272. countdown[0] -= 1
  273. if countdown[0] <= 0:
  274. reactor.callLater(0, all_done.callback, None)
  275. yield session.register(called, options.uri)
  276. yield all_done
  277. @inlineCallbacks
  278. def do_subscribe(reactor, session, options):
  279. """
  280. print events (one line of JSON per event)
  281. """
  282. all_done = Deferred()
  283. countdown = [options.times]
  284. @inlineCallbacks
  285. def published(*args, **kw):
  286. print(
  287. json.dumps({
  288. "args": args,
  289. "kwargs": kw,
  290. })
  291. )
  292. if countdown[0]:
  293. countdown[0] -= 1
  294. if countdown[0] <= 0:
  295. reactor.callLater(0, all_done.callback, None)
  296. yield session.subscribe(published, options.uri, options=SubscribeOptions(match=options.match))
  297. yield all_done
  298. def _main():
  299. """
  300. This is a magic name for `python -m autobahn`, and specified as
  301. our entry_point in setup.py
  302. """
  303. react(_real_main)
  304. @inlineCallbacks
  305. def _real_main(reactor):
  306. """
  307. Sanity check options, create a connection and run our subcommand
  308. """
  309. options = top.parse_args()
  310. component = _create_component(options)
  311. if options.subcommand_name is None:
  312. print("Must select a subcommand")
  313. sys.exit(1)
  314. if options.subcommand_name == "register":
  315. exe = options.command[0]
  316. if not os.path.isabs(exe):
  317. print("Full path to the executable required. Found: {}".format(exe), file=sys.stderr)
  318. sys.exit(1)
  319. if not os.path.exists(exe):
  320. print("Executable not found: {}".format(exe), file=sys.stderr)
  321. sys.exit(1)
  322. subcommands = {
  323. "call": do_call,
  324. "register": do_register,
  325. "subscribe": do_subscribe,
  326. "publish": do_publish,
  327. }
  328. command_fn = subcommands[options.subcommand_name]
  329. exit_code = [0]
  330. @component.on_join
  331. @inlineCallbacks
  332. def _(session, details):
  333. print("connected: authrole={} authmethod={}".format(details.authrole, details.authmethod), file=sys.stderr)
  334. try:
  335. yield command_fn(reactor, session, options)
  336. except ApplicationError as e:
  337. print("\n{}: {}\n".format(e.error, ''.join(e.args)))
  338. exit_code[0] = 5
  339. yield session.leave()
  340. failures = []
  341. @component.on_connectfailure
  342. def _(comp, fail):
  343. print("connect failure: {}".format(fail))
  344. failures.append(fail)
  345. if options.max_failures > 0 and len(failures) > options.max_failures:
  346. print("Too many failures ({}). Exiting".format(len(failures)))
  347. reactor.stop()
  348. yield component.start(reactor)
  349. # sys.exit(exit_code[0])
  350. if __name__ == "__main__":
  351. _main()