modelverse.py 33 KB

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