modelverse.py 31 KB

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