modelverse.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. import urllib
  2. import urllib2
  3. import json
  4. import random
  5. from urllib2 import URLError
  6. import sys
  7. import time
  8. import threading
  9. import Queue
  10. from sccd.runtime.statecharts_core import Event
  11. COMPILER_PATH = "interface/HUTN"
  12. MODE_UNCONNECTED = 0
  13. MODE_UNAUTHORIZED = 1
  14. MODE_MODELLING = 2
  15. MODE_MODIFY = 3
  16. MODE_DIALOG = 4
  17. MODE_MANUAL = 5
  18. MODE_SERVICE = 6
  19. # Bind to the compiler (might have to update path manually!)
  20. sys.path.append(COMPILER_PATH)
  21. from hutn_compiler.compiler import main as do_compile
  22. # Exceptions
  23. class ModelverseException(Exception):
  24. pass
  25. class UnknownError(ModelverseException):
  26. pass
  27. class UnknownIdentifier(ModelverseException):
  28. pass
  29. class CompilationError(ModelverseException):
  30. pass
  31. class NoSuchAttribute(ModelverseException):
  32. pass
  33. class UnknownModel(ModelverseException):
  34. pass
  35. class ConnectionError(ModelverseException):
  36. pass
  37. class ModelExists(ModelverseException):
  38. pass
  39. class PermissionDenied(ModelverseException):
  40. pass
  41. class InvalidMode(ModelverseException):
  42. pass
  43. class InterfaceMismatch(ModelverseException):
  44. pass
  45. class UnknownMetamodellingHierarchy(ModelverseException):
  46. pass
  47. # Helper functions and configuration: do not use yourself!
  48. taskname = None
  49. address = None
  50. mode = MODE_UNCONNECTED
  51. prev_mode = None
  52. current_model = None
  53. registered_metamodels = {}
  54. outputs = [None]
  55. def _output_thread(outputs):
  56. while taskname is None:
  57. time.sleep(0.1)
  58. try:
  59. while 1:
  60. outputs.append(json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read()))
  61. except:
  62. pass
  63. thrd = threading.Thread(target=_output_thread, args=[outputs])
  64. thrd.daemon = True
  65. thrd.start()
  66. def _exec_on_statechart(statechart):
  67. def _exec_sc(controller, inport, outport):
  68. op = controller.addOutputListener(outport)
  69. while 1:
  70. if len(outputs) > 1:
  71. # Is an output message of the Mv, so put it in the SC
  72. del outputs[0]
  73. output_event = outputs[0]
  74. print("Sending MV event: " + str(output_event))
  75. if output_event == "Success" or output_event == "Failure":
  76. # Is a stop event!
  77. controller.addInput(Event("terminate", inport, []))
  78. break
  79. else:
  80. # Is just a normal event!
  81. controller.addInput(Event("input", inport, [output_event]))
  82. input_event = op.fetch(0)
  83. if input_event is not None:
  84. # Expand the event and make it HTTP input
  85. print("Got SC event: " + str(input_event))
  86. _input(input_event.parameters)
  87. time.sleep(0.01)
  88. thrd = threading.Thread(target=_exec_sc, args=statechart)
  89. thrd.daemon = True
  90. thrd.start()
  91. return None
  92. def _get_metamodel(model):
  93. global registered_metamodels
  94. try:
  95. return registered_metamodels[model]
  96. except KeyError:
  97. raise UnknownMetamodellingHierarchy(model)
  98. def _check_type(value):
  99. if not isinstance(value, (int, long, float, str, unicode, bool)):
  100. raise UnsupportedValue("%s : %s" % (value, str(type(value))))
  101. def _check_type_list(value):
  102. if isinstance(value, list):
  103. [_check_type(i) for i in value]
  104. else:
  105. _check_type(value)
  106. def _dict_to_list(python_dict):
  107. lst = []
  108. for k, v in python_dict.items():
  109. lst += [k, v]
  110. return lst
  111. def _goto_mode(new_mode, model_name=None):
  112. global mode
  113. if mode == MODE_MANUAL and new_mode == MODE_MODIFY:
  114. if model_name != None and current_model != model_name:
  115. raise InvalidMode("Mode error: cannot modify other models!")
  116. else:
  117. return
  118. elif mode == MODE_MODELLING and new_mode == MODE_MODIFY:
  119. # Are in root view, but want to modify a model
  120. _model_modify(model_name, _get_metamodel(model_name))
  121. elif mode == MODE_MODIFY and new_mode == MODE_MODIFY and model_name != None and current_model != model_name:
  122. # Are in modify mode, but want to modify a different model
  123. mm = _get_metamodel(model_name)
  124. _model_exit()
  125. _model_modify(model_name, mm)
  126. elif mode == MODE_MODIFY and new_mode == MODE_MODELLING:
  127. _model_exit()
  128. elif mode == new_mode:
  129. return
  130. else:
  131. # Go to a mode that we have no automatic transfer to: raise exception
  132. raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
  133. def _input(value, port=None):
  134. # Ugly json encoding of primitives
  135. print("[IN] %s" % value)
  136. if port is None:
  137. port = taskname
  138. if isinstance(value, type([])):
  139. value = json.dumps(value)
  140. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": port}))).read()
  141. else:
  142. value = json.dumps(value)
  143. #print("Set input: " + str(value))
  144. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": port}))).read()
  145. def _input_raw(value, taskname):
  146. # Ugly json encoding of primitives
  147. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  148. #TODO check that this is actually a Modelverse!
  149. def _compile_AL(code):
  150. # Compile an action language file and send the compiled code
  151. code_fragments = code.split("\n")
  152. code_fragments = [i for i in code_fragments if i.strip() != ""]
  153. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  154. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  155. code_fragments = [i[initial_tabs:] for i in code_fragments]
  156. code_fragments.append("")
  157. code = "\n".join(code_fragments)
  158. with open(".code.alc", "w") as f:
  159. f.write(code)
  160. f.flush()
  161. compiled = do_compile(".code.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
  162. return compiled
  163. def _compile_model(code):
  164. # Compile a model and send the compiled graph
  165. # First change multiple spaces to a tab
  166. code_fragments = code.split("\n")
  167. code_fragments = [i for i in code_fragments if i.strip() != ""]
  168. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  169. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  170. code_fragments = [i[initial_tabs:] for i in code_fragments]
  171. code_fragments.append("")
  172. code = "\n".join(code_fragments)
  173. with open(".model.mvc", "w") as f:
  174. f.write(code)
  175. f.flush()
  176. return do_compile(".model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M")
  177. def _output(expected=None):
  178. try:
  179. while len(outputs) < 2:
  180. time.sleep(0.01)
  181. del outputs[0]
  182. print("[OUT] %s" % outputs[0])
  183. except:
  184. raise UnknownError()
  185. if expected is not None and _last_output() != expected:
  186. raise InterfaceMismatch(_last_output(), expected)
  187. return _last_output()
  188. def _last_output():
  189. return outputs[0]
  190. # Raise common exceptions
  191. def _handle_output(requested=None, split=None):
  192. value = _output()
  193. if value.startswith("Model exists: "):
  194. raise ModelExists(value.split(": ", 1)[1])
  195. elif value.startswith("Permission denied"):
  196. raise PermissionDenied(value.split(": ", 1)[1])
  197. elif value.startswith("Model not found: "):
  198. raise UnknownModel(value.split(": ", 1)[1])
  199. elif value.startswith("Element not found: "):
  200. raise UnknownIdentifier(value.split(": ", 1)[1])
  201. elif value.startswith("Element exists: "):
  202. raise ElementExists(value.split(": ", 1)[1])
  203. elif value.startswith("Attribute not found: "):
  204. raise NoSuchAttribute(value.split(": ", 1)[1])
  205. elif requested is not None and value.startswith(requested):
  206. if split is None:
  207. return value
  208. else:
  209. splitted = value.strip().split(split, 1)
  210. if len(splitted) == 1:
  211. return ""
  212. else:
  213. return splitted[1].rstrip()
  214. else:
  215. raise InterfaceMismatch(value)
  216. def _model_modify(model_name, metamodel_name):
  217. """Modify an existing model."""
  218. global mode
  219. global prev_mode
  220. if mode == MODE_MANUAL:
  221. prev_mode = MODE_MANUAL
  222. mode = MODE_MODIFY
  223. return None
  224. _goto_mode(MODE_MODELLING)
  225. prev_mode = MODE_MODELLING
  226. _input(["model_modify", model_name, metamodel_name])
  227. _handle_output("Success")
  228. global current_model
  229. current_model = model_name
  230. # Mode has changed
  231. mode = MODE_MODIFY
  232. _output("Model loaded, ready for commands!")
  233. def _model_exit():
  234. """Leave model modify mode."""
  235. global mode
  236. global prev_mode
  237. if prev_mode == MODE_MANUAL:
  238. mode = MODE_MANUAL
  239. return
  240. if mode != MODE_MODIFY:
  241. raise InvalidMode()
  242. _input("exit")
  243. _output("Success")
  244. mode = MODE_MODELLING
  245. def alter_context(model_name, metamodel_name):
  246. global registered_metamodels
  247. registered_metamodels[model_name] = metamodel_name
  248. # Main MvC operations
  249. def init(address_param="http://127.0.0.1:8001", timeout=20.0):
  250. """Starts up the connection to the Modelverse."""
  251. global mode
  252. global address
  253. address = address_param
  254. start_time = time.time()
  255. task = random.random()
  256. while 1:
  257. try:
  258. _input_raw('"%s"' % task, "task_manager")
  259. mode = MODE_UNAUTHORIZED
  260. break
  261. except URLError as e:
  262. if time.time() - start_time > timeout:
  263. raise ConnectionError(e.reason)
  264. else:
  265. time.sleep(0.1)
  266. global taskname
  267. taskname = task
  268. def login(username, password):
  269. """Log in a user, if user doesn't exist, it is created."""
  270. global mode
  271. _goto_mode(MODE_UNAUTHORIZED)
  272. _output("Log on as which user?")
  273. _input(username)
  274. if _output() == "Password for existing user?":
  275. _input(password)
  276. if _output() == "Welcome to the Model Management Interface v2.0!":
  277. _output("Use the 'help' command for a list of possible commands")
  278. _input("quiet")
  279. mode = MODE_MODELLING
  280. elif _last_output() == "Wrong password!":
  281. raise PermissionDenied()
  282. else:
  283. raise InterfaceMismatch(_last_output())
  284. elif _last_output() == "This is a new user: please give password!":
  285. _input(password)
  286. _output("Please repeat the password")
  287. _input(password)
  288. if _output() == "Passwords match!":
  289. _output("Welcome to the Model Management Interface v2.0!")
  290. _output("Use the 'help' command for a list of possible commands")
  291. _input("quiet")
  292. mode = MODE_MODELLING
  293. elif _last_output() == "Not the same password!":
  294. # We just sent the same password, so it should be identical, unless the interface changed
  295. raise InterfaceMismatch(_last_output())
  296. else:
  297. raise InterfaceMismatch(_last_output())
  298. else:
  299. raise InterfaceMismatch(_last_output())
  300. def model_add(model_name, metamodel_name, model_code=None):
  301. """Instantiate a new model."""
  302. _goto_mode(MODE_MODELLING)
  303. # Do this before creating the model, as otherwise compilation errors would make us inconsistent
  304. if model_code is not None:
  305. try:
  306. compiled = _compile_model(model_code)
  307. except Exception as e:
  308. raise CompilationError(e)
  309. else:
  310. compiled = [0]
  311. _input(["model_add", metamodel_name, model_name])
  312. _handle_output("Waiting for model constructors...")
  313. _input(compiled)
  314. _output("Success")
  315. global registered_metamodels
  316. registered_metamodels[model_name] = metamodel_name
  317. def upload_code(code):
  318. try:
  319. compiled = _compile_AL(code)
  320. except Exception as e:
  321. raise CompilationError(e)
  322. _input(compiled)
  323. def model_delete(model_name):
  324. """Delete an existing model."""
  325. _goto_mode(MODE_MODELLING)
  326. _input(["model_delete", model_name])
  327. _handle_output("Success")
  328. def model_list(location):
  329. """List all models."""
  330. _goto_mode(MODE_MODELLING)
  331. _input(["model_list", location])
  332. return set(_handle_output("Success: ", split=" ").split("\n"))
  333. def model_list_full(location):
  334. """List full information on all models."""
  335. _goto_mode(MODE_MODELLING)
  336. _input(["model_list_full", location])
  337. output = _handle_output("Success: ", split=" ")
  338. if output == "":
  339. return set([])
  340. lst = set([])
  341. value = output.strip().split("\n")
  342. for v in value:
  343. m = v.strip()
  344. perm, own, grp, m = m.split(" ", 3)
  345. lst.add((m, own, grp, perm))
  346. return lst
  347. def verify(model_name, metamodel_name=None):
  348. """Verify if a model conforms to its metamodel."""
  349. _goto_mode(MODE_MODELLING)
  350. if metamodel_name is None:
  351. metamodel_name = _get_metamodel(model_name)
  352. _input(["verify", model_name, metamodel_name])
  353. return _handle_output("Success: ", split=" ")
  354. def model_overwrite(model_name, new_model=None, metamodel_name=None):
  355. """Upload a new model and overwrite an existing model."""
  356. _goto_mode(MODE_MODIFY, model_name)
  357. if new_model is not None:
  358. try:
  359. compiled = _compile_model(new_model)
  360. except Exception as e:
  361. raise CompilationError(e)
  362. else:
  363. compiled = [0]
  364. _input("upload")
  365. _handle_output("Waiting for model constructors...")
  366. _input(compiled)
  367. _output("Success")
  368. if metamodel_name is not None:
  369. global registered_metamodels
  370. registered_metamodels[model_name] = metamodel_name
  371. def user_logout():
  372. """Log out the current user and break the connection."""
  373. global mode
  374. _goto_mode(MODE_MODELLING)
  375. _input("exit")
  376. mode = MODE_UNCONNECTED
  377. def user_delete():
  378. """Removes the current user and break the connection."""
  379. global mode
  380. _goto_mode(MODE_MODELLING)
  381. _input("self-destruct")
  382. mode = MODE_UNCONNECTED
  383. def model_render(model_name, mapper_name):
  384. """Fetch a rendered verion of a model."""
  385. _goto_mode(MODE_MODELLING)
  386. _input(["model_render", model_name, mapper_name])
  387. return json.loads(_handle_output("Success: ", split=" "))
  388. def transformation_between(source, target):
  389. _goto_mode(MODE_MODELLING)
  390. _input(["transformation_between", source, target])
  391. output = _handle_output("Success: ", split=" ")
  392. if output == "":
  393. return set([])
  394. return set([v for v in output.split("\n")])
  395. def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  396. """Create a new model transformation."""
  397. global mode
  398. _goto_mode(MODE_MODELLING)
  399. import time
  400. start = time.time()
  401. try:
  402. compiled = _compile_model(code)
  403. except Exception as e:
  404. raise CompilationError(e)
  405. #print("Compilation took: %ss" % (time.time() - start))
  406. start = time.time()
  407. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  408. _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
  409. # Possibly modify the merged metamodel first (add tracability links)
  410. if len(source_metamodels) + len(target_metamodels) > 0:
  411. mode = MODE_MANUAL
  412. _output("Model loaded, ready for commands!")
  413. callback()
  414. _input("exit")
  415. mode = MODE_MODELLING
  416. #print("Callbacks took: %ss" % (time.time() - start))
  417. start = time.time()
  418. # Done, so RAMify and upload the model
  419. _handle_output("Waiting for model constructors...")
  420. _input(compiled)
  421. _handle_output("Success")
  422. #print("Upload and RAMify took: %ss" % (time.time() - start))
  423. def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  424. """Create a new action language model, which can be executed."""
  425. global mode
  426. _goto_mode(MODE_MODELLING)
  427. try:
  428. compiled = _compile_AL(code)
  429. except Exception as e:
  430. raise CompilationError(e)
  431. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  432. _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
  433. # Possibly modify the merged metamodel first (add tracability links)
  434. if len(source_metamodels) + len(target_metamodels) > 0:
  435. mode = MODE_MANUAL
  436. _output("Model loaded, ready for commands!")
  437. callback()
  438. _input("exit")
  439. mode = MODE_MODELLING
  440. _handle_output("Waiting for code constructors...")
  441. _input(compiled)
  442. _output("Success")
  443. def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
  444. """Create a new manual model operation."""
  445. global mode
  446. _goto_mode(MODE_MODELLING)
  447. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  448. _input(["transformation_add_MANUAL"] + mv_dict_rep + [operation_name])
  449. # Possibly modify the merged metamodel first (add tracability links)
  450. if len(source_metamodels) + len(target_metamodels) > 0:
  451. mode = MODE_MANUAL
  452. _output("Model loaded, ready for commands!")
  453. callback()
  454. _input("exit")
  455. mode = MODE_MODELLING
  456. _handle_output("Success")
  457. def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, statechart=None):
  458. """Execute an existing model operation."""
  459. global mode
  460. _goto_mode(MODE_MODELLING)
  461. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  462. _input(["transformation_execute", operation_name] + mv_dict_rep)
  463. _handle_output("Success: ready for AL execution")
  464. if statechart is not None:
  465. # We are to delegate this information to another statechart, which wants interaction
  466. # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
  467. mode = MODE_DIALOG
  468. _exec_on_statechart(statechart)
  469. mode = MODE_MODELLING
  470. return None
  471. else:
  472. # No statechart associated, so just wait until we are finished
  473. while _output() not in ["Success", "Failure"]:
  474. pass
  475. if _last_output() == "Success":
  476. return True
  477. else:
  478. return False
  479. def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  480. """Execute an existing model operation."""
  481. global mode
  482. _goto_mode(MODE_MODELLING)
  483. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  484. _input(["transformation_execute", operation_name] + mv_dict_rep)
  485. _handle_output("Success: ready for MANUAL execution")
  486. # Skip over the begin of mini_modify
  487. _handle_output("Please perform manual operation ")
  488. _output("Model loaded, ready for commands!")
  489. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  490. mode = MODE_MANUAL
  491. callback()
  492. # Finished, so leave
  493. _input("exit")
  494. mode = MODE_MODELLING
  495. # Got termination message, so we are done!
  496. if _output() == "Success":
  497. return True
  498. else:
  499. return False
  500. def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, statechart=None):
  501. """Execute an existing model operation."""
  502. global mode
  503. _goto_mode(MODE_MODELLING)
  504. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  505. _input(["transformation_execute", operation_name] + mv_dict_rep)
  506. _handle_output("Success: ready for MT execution")
  507. if statechart is not None:
  508. # We are to delegate this information to another statechart, which wants interaction
  509. # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
  510. mode = MODE_DIALOG
  511. _exec_on_statechart(statechart)
  512. mode = MODE_MODELLING
  513. return None
  514. else:
  515. # No statechart associated, so just wait until we are finished
  516. while _output() not in ["Success", "Failure"]:
  517. pass
  518. if _last_output() == "Success":
  519. return True
  520. else:
  521. return False
  522. def transformation_list():
  523. """List existing model operations."""
  524. _goto_mode(MODE_MODELLING)
  525. _input("transformation_list")
  526. output = _handle_output("Success: ", split=" ")
  527. if output == "":
  528. return set([])
  529. lst = set([])
  530. value = output.strip().split("\n")
  531. for v in value:
  532. t, m = v.strip().split(" ", 1)
  533. t = t[1:-1].strip()
  534. m = m.strip().split(":")[0].strip()
  535. lst.add((t, m))
  536. return lst
  537. def process_execute(process_name, prefix, callbacks):
  538. """Execute a process model."""
  539. global mode
  540. _goto_mode(MODE_MODELLING)
  541. _input(["process_execute", process_name, prefix])
  542. _handle_output("Success")
  543. reuse = False
  544. while reuse or _output() != "Success":
  545. reuse = False
  546. output = _last_output()
  547. if output.startswith("Enacting "):
  548. # Next activity!
  549. t = output.split(" ", 1)[1].split(":", 1)[0]
  550. name = output.split(": ", 1)[1]
  551. if name in callbacks:
  552. callback = callbacks[name]
  553. if t == "ModelTransformation" or t == "ActionLanguage":
  554. while not (_output().startswith("Enacting ") or _last_output() == "Success"):
  555. mode = MODE_DIALOG
  556. reply = callback(_last_output())
  557. mode = MODE_MODELLING
  558. if reply is not None:
  559. _input(reply)
  560. if _last_output().startswith("Enacting "):
  561. reuse = True
  562. elif t == "ManualOperation":
  563. _handle_output("Please perform manual operation ")
  564. _output("Model loaded, ready for commands!")
  565. mode = MODE_MANUAL
  566. callback()
  567. _input("exit")
  568. mode = MODE_MODELLING
  569. def permission_modify(model_name, permissions):
  570. """Modify permissions of a model."""
  571. _goto_mode(MODE_MODELLING)
  572. _input(["permission_modify", model_name, permissions])
  573. _handle_output("Success")
  574. def permission_owner(model_name, owner):
  575. """Modify the owning user of a model."""
  576. _goto_mode(MODE_MODELLING)
  577. _input(["permission_owner", model_name, owner])
  578. _handle_output("Success")
  579. def permission_group(model_name, group):
  580. """Modify the owning group of a model."""
  581. _goto_mode(MODE_MODELLING)
  582. _input(["permission_group", model_name, group])
  583. _handle_output("Success")
  584. def group_create(group_name):
  585. """Create a new group."""
  586. _goto_mode(MODE_MODELLING)
  587. _input(["group_create", group_name])
  588. _handle_output("Success")
  589. def group_delete(group_name):
  590. """Delete a group of which you are an owner."""
  591. _goto_mode(MODE_MODELLING)
  592. _input(["group_delete", group_name])
  593. _handle_output("Success")
  594. def group_owner_add(group_name, user_name):
  595. """Add a new owning user to a group you own."""
  596. _goto_mode(MODE_MODELLING)
  597. _input(["owner_add", group_name, user_name])
  598. _handle_output("Success")
  599. def group_owner_delete(group_name, user_name):
  600. """Delete an owning user to a group you own."""
  601. _goto_mode(MODE_MODELLING)
  602. _input(["owner_delete", group_name, user_name])
  603. _handle_output("Success")
  604. def group_join(group_name, user_name):
  605. """Add a new user to a group you own."""
  606. _goto_mode(MODE_MODELLING)
  607. _input(["group_join", group_name, user_name])
  608. _handle_output("Success")
  609. def group_kick(group_name, user_name):
  610. """Delete a user from a group you own."""
  611. _goto_mode(MODE_MODELLING)
  612. _input(["group_kick", group_name, user_name])
  613. _handle_output("Success")
  614. def group_list():
  615. """List existing groups."""
  616. _goto_mode(MODE_MODELLING)
  617. _input(["group_list"])
  618. _handle_output("Success")
  619. def admin_promote(user_name):
  620. """Promote a user to admin status."""
  621. _goto_mode(MODE_MODELLING)
  622. _input(["admin_promote", user_name])
  623. _handle_output("Success")
  624. def admin_demote():
  625. """Demote a user from admin status."""
  626. _goto_mode(MODE_MODELLING)
  627. _input(["admin_demote", user_name])
  628. _handle_output("Success")
  629. # Actual operations on the model
  630. def element_list(model_name):
  631. """Return a list of all IDs and the type of the element"""
  632. _goto_mode(MODE_MODIFY, model_name)
  633. _input("list_full")
  634. lst = set([])
  635. output = _handle_output("Success: ", split=" ")
  636. if output == "":
  637. return set([])
  638. for v in output.split("\n"):
  639. m, mm = v.split(":")
  640. m = m.strip()
  641. mm = mm.strip()
  642. lst.add((m, mm))
  643. return lst
  644. def types(model_name):
  645. """Return a list of all types usable in the model"""
  646. _goto_mode(MODE_MODIFY, model_name)
  647. _input("types")
  648. lst = set([])
  649. output = _handle_output("Success: ", split=" ")
  650. if output == "":
  651. return set([])
  652. for v in output.split("\n"):
  653. m, mm = v.split(":")
  654. m = m.strip()
  655. lst.add(m)
  656. return lst
  657. def types_full(model_name):
  658. """Return a list of full types usable in the model"""
  659. _goto_mode(MODE_MODIFY, model_name)
  660. _input("types")
  661. lst = set([])
  662. output = _handle_output("Success: ", split=" ")
  663. if output == "":
  664. return set([])
  665. for v in output.split("\n"):
  666. m, mm = v.split(":")
  667. m = m.strip()
  668. mm = mm.strip()
  669. lst.add((m, mm))
  670. return lst
  671. def read(model_name, ID):
  672. """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
  673. _goto_mode(MODE_MODIFY, model_name)
  674. _input(["read", ID])
  675. output = _handle_output("Success: ", split=" ")
  676. v = output.split("\n")
  677. t = v[1].split(":")[1].strip()
  678. if (not v[2].startswith("Source:")):
  679. rval = (t, None)
  680. else:
  681. src = v[2].split(":")[1].strip()
  682. trg = v[3].split(":")[1].strip()
  683. rval = (t, (src, trg))
  684. return rval
  685. def read_attrs(model_name, ID):
  686. """Return a dictionary of attribute value pairs"""
  687. _goto_mode(MODE_MODIFY, model_name)
  688. _input(["read", ID])
  689. output = _handle_output("Success: ", split=" ")
  690. v = output.split("\n")
  691. searching = True
  692. rval = {}
  693. for r in v:
  694. if searching:
  695. if r == "Attributes:":
  696. # Start working on attributes
  697. searching = False
  698. else:
  699. key, value = r.split(":", 1)
  700. _, value = value.split("=", 1)
  701. key = json.loads(key.strip())
  702. value = value.strip()
  703. if value == "None":
  704. value = None
  705. elif value == "True":
  706. value = True
  707. elif value == "False":
  708. value = False
  709. else:
  710. value = json.loads(value)
  711. rval[key] = value
  712. return rval
  713. def instantiate(model_name, typename, edge=None, ID=""):
  714. """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
  715. _goto_mode(MODE_MODIFY, model_name)
  716. if edge is None:
  717. _input(["instantiate_node", typename, ID])
  718. else:
  719. _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
  720. return _handle_output("Success: ", split=" ")
  721. def delete_element(model_name, ID):
  722. """Delete the element with the given ID"""
  723. _goto_mode(MODE_MODIFY, model_name)
  724. _input(["delete", ID])
  725. _handle_output("Success")
  726. def attr_assign(model_name, ID, attr, value):
  727. """Assign a value to an attribute"""
  728. _check_type(value)
  729. _goto_mode(MODE_MODIFY, model_name)
  730. _input(["attr_add", ID, attr, value])
  731. _handle_output("Success")
  732. def attr_assign_code(model_name, ID, attr, code):
  733. """Assign a piece of Action Language code to the attribute"""
  734. _check_type(code)
  735. try:
  736. compiled = _compile_AL(code)
  737. except Exception as e:
  738. raise CompilationError(e)
  739. _goto_mode(MODE_MODIFY, model_name)
  740. _input(["attr_add", ID, attr])
  741. _handle_output("Waiting for code constructors...")
  742. _input(compiled)
  743. _output("Success")
  744. def attr_delete(model_name, ID, attr):
  745. """Remove an attribute."""
  746. _goto_mode(MODE_MODIFY, model_name)
  747. _input(["attr_del", ID, attr])
  748. _handle_output("Success")
  749. def read_outgoing(model_name, ID, typename):
  750. """Returns a list of all outgoing associations of a specific type ("" = all)"""
  751. _goto_mode(MODE_MODIFY, model_name)
  752. _input(["read_outgoing", ID, typename])
  753. output = _handle_output("Success: ", split=" ")
  754. if output == "":
  755. return set([])
  756. else:
  757. return set(output.split("\n"))
  758. def read_incoming(model_name, ID, typename):
  759. """Returns a list of all incoming associations of a specific type ("" = all)"""
  760. _goto_mode(MODE_MODIFY, model_name)
  761. _input(["read_incoming", ID, typename])
  762. output = _handle_output("Success: ", split=" ")
  763. if output == "":
  764. return set([])
  765. else:
  766. return set(output.split("\n"))
  767. def read_association_source(model_name, ID):
  768. """Returns the source of an association."""
  769. _goto_mode(MODE_MODIFY, model_name)
  770. _input(["read_association_source", ID])
  771. return _handle_output("Success: ", split=" ")
  772. def read_association_destination(model_name, ID):
  773. """Returns the destination of an association."""
  774. _goto_mode(MODE_MODIFY, model_name)
  775. _input(["read_association_destination", ID])
  776. return _handle_output("Success: ", split=" ")
  777. ##### To document:
  778. def service_register(name, function):
  779. """Register a function as a service with a specific name."""
  780. def service_process(port):
  781. while 1:
  782. thrd = threading.Thread(target=function, args=[service_get(port)])
  783. thrd.daemon = True
  784. thrd.start()
  785. global mode
  786. _goto_mode(MODE_MODELLING)
  787. _input(["service_register", name])
  788. # Now we are in service-mode
  789. mode = MODE_SERVICE
  790. port = _handle_output("Success: ", split=" ")
  791. # Process events in the background!
  792. threading.Thread(target=service_process, args=[port]).start()
  793. def service_stop():
  794. """Stop the currently executing process."""
  795. _goto_mode(MODE_SERVICE)
  796. _input("service_stop")
  797. _handle_output("Success")
  798. global mode
  799. mode = MODE_MODELLING
  800. def service_get(port):
  801. """Get the values on the specified port."""
  802. _goto_mode(MODE_SERVICE)
  803. return _output(port=port)
  804. def service_set(port, value):
  805. """Set a value on a specified port."""
  806. _check_type_list(value)
  807. _goto_mode(MODE_SERVICE)
  808. _input(value, port=port)
  809. def user_password(user, password):
  810. """Change a user's password."""
  811. raise NotImplementedError()
  812. def transformation_read_signature(transformation):
  813. """Reads an operation's signature, specifying the names and their required types."""
  814. raise NotImplementedError()
  815. def element_list_nice(model_name):
  816. """Fetches a nice representation of models."""
  817. _goto_mode(MODE_MODELLING)
  818. _input(["element_list_nice", model_name, _get_metamodel(model_name)])
  819. data = _handle_output("Success: ", split=" ")
  820. try:
  821. return json.loads(data)
  822. except:
  823. print(data)
  824. raise
  825. def connections_between(model_name, source_element, target_element):
  826. """Gets a list of all allowed connections between the source and target element in the model."""
  827. _goto_mode(MODE_MODIFY, model_name)
  828. _input(["connections_between", source_element, target_element])
  829. output = _handle_output("Success: ", split=" ")
  830. if output == "":
  831. return set([])
  832. else:
  833. return set(output.split("\n"))
  834. def define_attribute(model_name, node, attr_name, attr_type):
  835. """Create a new attribute, which can be instantiated one meta-level below."""
  836. _goto_mode(MODE_MODIFY, model_name)
  837. _input(["define_attribute", node, attr_name, attr_type])
  838. return _handle_output("Success: ", split=" ")
  839. def all_instances(model_name, type_name):
  840. """Returns a list of all elements of a specific type."""
  841. _goto_mode(MODE_MODIFY, model_name)
  842. _input(["all_instances", type_name])
  843. output = _handle_output("Success: ", split=" ")
  844. if output == "":
  845. return set([])
  846. else:
  847. return set(output.split("\n"))
  848. def service_poll(port):
  849. """Checks whether or not the Modelverse side has any input ready to be processed."""
  850. raise NotImplementedError()
  851. def user_name(user, username):
  852. """Change a user's name."""
  853. raise NotImplementedError()
  854. def remove_conformance(model_name, metamodel_name):
  855. """Remove a metamodel for a model."""
  856. _goto_mode(MODE_MODELLING)
  857. _input(["remove_conformance", model_name, metamodel_name])
  858. _handle_output("Success")
  859. def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
  860. """Add a metamodel for a model."""
  861. raise NotImplementedError()
  862. _goto_mode(MODE_MODELLING)
  863. _input(["add_conformance", model_name, metamodel_name])
  864. _handle_output("Success")
  865. def folder_create(folder_name):
  866. _goto_mode(MODE_MODELLING)
  867. _input(["folder_create", folder_name])
  868. _handle_output("Success")