modelverse.py 31 KB

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