modelverse.py 31 KB

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