modelverse.py 30 KB

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