modelverse.py 32 KB

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