modelverse_coded.py 33 KB

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