modelverse.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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") + ["exit"]
  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 = ["exit"]
  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():
  285. """List all models."""
  286. _goto_mode(MODE_MODELLING)
  287. _input("model_list")
  288. output = _handle_output("Success: ", split=" ")
  289. if output == "":
  290. return set([])
  291. lst = set([])
  292. value = output.strip().split("\n")
  293. for v in value:
  294. m, mm = v.split(":")
  295. m = m.strip()
  296. mm = mm.strip()
  297. lst.add((m, mm))
  298. return lst
  299. def model_list_full():
  300. """List full information on all models."""
  301. _goto_mode(MODE_MODELLING)
  302. _input("model_list_full")
  303. output = _handle_output("Success: ", split=" ")
  304. if output == "":
  305. return set([])
  306. lst = set([])
  307. value = output.strip().split("\n")
  308. for v in value:
  309. m, mm = v.split(":")
  310. m = m.strip()
  311. mm = mm.strip()
  312. perm, own, grp, m = m.split(" ")
  313. lst.add((m, mm, own, grp, perm))
  314. return lst
  315. def verify(model_name, metamodel_name=None):
  316. """Verify if a model conforms to its metamodel."""
  317. _goto_mode(MODE_MODELLING)
  318. if metamodel_name is None:
  319. metamodel_name = _get_metamodel(model_name)
  320. _input(["verify", model_name, metamodel_name])
  321. return _handle_output("Success: ", split=" ")
  322. def model_overwrite(model_name, new_model=None, metamodel_name=None):
  323. """Upload a new model and overwrite an existing model."""
  324. _goto_mode(MODE_MODIFY, model_name)
  325. if new_model is not None:
  326. try:
  327. compiled = _compile_model(new_model)
  328. except Exception as e:
  329. raise CompilationError(e)
  330. else:
  331. compiled = ["exit"]
  332. _input("upload")
  333. _handle_output("Waiting for model constructors...")
  334. _input(compiled)
  335. _output("Success")
  336. if metamodel_name is not None:
  337. global registered_metamodels
  338. registered_metamodels[model_name] = metamodel_name
  339. def user_logout():
  340. """Log out the current user and break the connection."""
  341. global mode
  342. _goto_mode(MODE_MODELLING)
  343. _input("exit")
  344. mode = MODE_UNCONNECTED
  345. def user_delete():
  346. """Removes the current user and break the connection."""
  347. global mode
  348. _goto_mode(MODE_MODELLING)
  349. _input("self-destruct")
  350. mode = MODE_UNCONNECTED
  351. def model_render(model_name, mapper_name):
  352. """Fetch a rendered verion of a model."""
  353. _goto_mode(MODE_MODELLING)
  354. _input(["model_render", model_name, mapper_name])
  355. return json.loads(_handle_output("Success: ", split=" "))
  356. def transformation_between(source, target):
  357. _goto_mode(MODE_MODELLING)
  358. _input(["transformation_between", source, target])
  359. output = _handle_output("Success: ", split=" ")
  360. if output == "":
  361. return set([])
  362. return set([v for v in output.split("\n")])
  363. def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  364. """Create a new model transformation."""
  365. global mode
  366. _goto_mode(MODE_MODELLING)
  367. import time
  368. start = time.time()
  369. try:
  370. compiled = _compile_model(code)
  371. except Exception as e:
  372. raise CompilationError(e)
  373. #print("Compilation took: %ss" % (time.time() - start))
  374. start = time.time()
  375. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  376. _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
  377. # Possibly modify the merged metamodel first (add tracability links)
  378. if len(source_metamodels) + len(target_metamodels) > 0:
  379. mode = MODE_MANUAL
  380. _output("Model loaded, ready for commands!")
  381. callback()
  382. _input("exit")
  383. mode = MODE_MODELLING
  384. #print("Callbacks took: %ss" % (time.time() - start))
  385. start = time.time()
  386. # Done, so RAMify and upload the model
  387. _handle_output("Waiting for model constructors...")
  388. _input(compiled)
  389. _handle_output("Success")
  390. #print("Upload and RAMify took: %ss" % (time.time() - start))
  391. def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  392. """Create a new action language model, which can be executed."""
  393. global mode
  394. _goto_mode(MODE_MODELLING)
  395. try:
  396. compiled = _compile_AL(code)
  397. except Exception as e:
  398. raise CompilationError(e)
  399. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  400. _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
  401. # Possibly modify the merged metamodel first (add tracability links)
  402. if len(source_metamodels) + len(target_metamodels) > 0:
  403. mode = MODE_MANUAL
  404. _output("Model loaded, ready for commands!")
  405. callback()
  406. _input("exit")
  407. mode = MODE_MODELLING
  408. _handle_output("Waiting for code constructors...")
  409. _input(compiled)
  410. _output("Success")
  411. def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
  412. """Create a new manual model operation."""
  413. global mode
  414. _goto_mode(MODE_MODELLING)
  415. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  416. _input(["transformation_add_MANUAL"] + mv_dict_rep + [operation_name])
  417. # Possibly modify the merged metamodel first (add tracability links)
  418. if len(source_metamodels) + len(target_metamodels) > 0:
  419. mode = MODE_MANUAL
  420. _output("Model loaded, ready for commands!")
  421. callback()
  422. _input("exit")
  423. mode = MODE_MODELLING
  424. _handle_output("Success")
  425. def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  426. """Execute an existing model operation."""
  427. global mode
  428. _goto_mode(MODE_MODELLING)
  429. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  430. _input(["transformation_execute", operation_name] + mv_dict_rep)
  431. _handle_output("Success: ready for AL execution")
  432. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  433. while _output() not in ["Success", "Failure"]:
  434. mode = MODE_DIALOG
  435. reply = callback(_last_output())
  436. mode = MODE_MODELLING
  437. if reply is not None:
  438. _input(reply)
  439. # Got termination message, so we are done!
  440. if _last_output() == "Success":
  441. return True
  442. else:
  443. return False
  444. def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  445. """Execute an existing model operation."""
  446. global mode
  447. _goto_mode(MODE_MODELLING)
  448. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  449. _input(["transformation_execute", operation_name] + mv_dict_rep)
  450. _handle_output("Success: ready for MANUAL execution")
  451. # Skip over the begin of mini_modify
  452. _handle_output("Please perform manual operation ")
  453. _output("Model loaded, ready for commands!")
  454. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  455. mode = MODE_MANUAL
  456. callback()
  457. # Finished, so leave
  458. _input("exit")
  459. mode = MODE_MODELLING
  460. # Got termination message, so we are done!
  461. if _output() == "Success":
  462. return True
  463. else:
  464. return False
  465. def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  466. """Execute an existing model operation."""
  467. global mode
  468. _goto_mode(MODE_MODELLING)
  469. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  470. _input(["transformation_execute", operation_name] + mv_dict_rep)
  471. _handle_output("Success: ready for MT execution")
  472. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  473. while _output() not in ["Success", "Failure"]:
  474. mode = MODE_DIALOG
  475. reply = callback(_last_output())
  476. mode = MODE_MODELLING
  477. if reply is not None:
  478. _input(reply)
  479. # Got termination message, so we are done!
  480. if _last_output() == "Success":
  481. return True
  482. else:
  483. return False
  484. def transformation_list():
  485. """List existing model operations."""
  486. _goto_mode(MODE_MODELLING)
  487. _input("transformation_list")
  488. output = _handle_output("Success: ", split=" ")
  489. if output == "":
  490. return set([])
  491. lst = set([])
  492. value = output.strip().split("\n")
  493. for v in value:
  494. t, m = v.strip().split(" ", 1)
  495. t = t[1:-1].strip()
  496. m = m.strip().split(":")[0].strip()
  497. lst.add((t, m))
  498. return lst
  499. def process_execute(process_name, prefix, callbacks):
  500. """Execute a process model."""
  501. global mode
  502. _goto_mode(MODE_MODELLING)
  503. _input(["process_execute", process_name, prefix])
  504. _handle_output("Success")
  505. while _output() != "Success":
  506. output = _last_output()
  507. if output.startswith("Enacting "):
  508. # Next activity!
  509. t = output.split(" ", 1)[1].split(":", 1)[0]
  510. name = output.split(": ", 1)[1]
  511. if name in callbacks:
  512. callback = callbacks[name]
  513. if t == "ModelTransformation" or t == "ActionLanguage":
  514. while not (_output().startswith("Enacting ") or _last_output() == "Success"):
  515. mode = MODE_DIALOG
  516. reply = callback(_last_output())
  517. mode = MODE_MODELLING
  518. if reply is not None:
  519. _input(reply)
  520. elif t == "ManualOperation":
  521. _handle_output("Please perform manual operation ")
  522. _output("Model loaded, ready for commands!")
  523. mode = MODE_MANUAL
  524. callback()
  525. _input("exit")
  526. mode = MODE_MODELLING
  527. def permission_modify(model_name, permissions):
  528. """Modify permissions of a model."""
  529. _goto_mode(MODE_MODELLING)
  530. _input(["permission_modify", model_name, permissions])
  531. _handle_output("Success")
  532. def permission_owner(model_name, owner):
  533. """Modify the owning user of a model."""
  534. _goto_mode(MODE_MODELLING)
  535. _input(["permission_owner", model_name, owner])
  536. _handle_output("Success")
  537. def permission_group(model_name, group):
  538. """Modify the owning group of a model."""
  539. _goto_mode(MODE_MODELLING)
  540. _input(["permission_group", model_name, group])
  541. _handle_output("Success")
  542. def group_create(group_name):
  543. """Create a new group."""
  544. _goto_mode(MODE_MODELLING)
  545. _input(["group_create", group_name])
  546. _handle_output("Success")
  547. def group_delete(group_name):
  548. """Delete a group of which you are an owner."""
  549. _goto_mode(MODE_MODELLING)
  550. _input(["group_delete", group_name])
  551. _handle_output("Success")
  552. def group_owner_add(group_name, user_name):
  553. """Add a new owning user to a group you own."""
  554. _goto_mode(MODE_MODELLING)
  555. _input(["owner_add", group_name, user_name])
  556. _handle_output("Success")
  557. def group_owner_delete(group_name, user_name):
  558. """Delete an owning user to a group you own."""
  559. _goto_mode(MODE_MODELLING)
  560. _input(["owner_delete", group_name, user_name])
  561. _handle_output("Success")
  562. def group_join(group_name, user_name):
  563. """Add a new user to a group you own."""
  564. _goto_mode(MODE_MODELLING)
  565. _input(["group_join", group_name, user_name])
  566. _handle_output("Success")
  567. def group_kick(group_name, user_name):
  568. """Delete a user from a group you own."""
  569. _goto_mode(MODE_MODELLING)
  570. _input(["group_kick", group_name, user_name])
  571. _handle_output("Success")
  572. def group_list():
  573. """List existing groups."""
  574. _goto_mode(MODE_MODELLING)
  575. _input(["group_list"])
  576. _handle_output("Success")
  577. def admin_promote(user_name):
  578. """Promote a user to admin status."""
  579. _goto_mode(MODE_MODELLING)
  580. _input(["admin_promote", user_name])
  581. _handle_output("Success")
  582. def admin_demote():
  583. """Demote a user from admin status."""
  584. _goto_mode(MODE_MODELLING)
  585. _input(["admin_demote", user_name])
  586. _handle_output("Success")
  587. # Actual operations on the model
  588. def element_list(model_name):
  589. """Return a list of all IDs and the type of the element"""
  590. _goto_mode(MODE_MODIFY, model_name)
  591. _input("list_full")
  592. lst = set([])
  593. output = _handle_output("Success: ", split=" ")
  594. if output == "":
  595. return set([])
  596. for v in output.split("\n"):
  597. m, mm = v.split(":")
  598. m = m.strip()
  599. mm = mm.strip()
  600. lst.add((m, mm))
  601. return lst
  602. def types(model_name):
  603. """Return a list of all types usable in the model"""
  604. _goto_mode(MODE_MODIFY, model_name)
  605. _input("types")
  606. lst = set([])
  607. output = _handle_output("Success: ", split=" ")
  608. if output == "":
  609. return set([])
  610. for v in output.split("\n"):
  611. m, mm = v.split(":")
  612. m = m.strip()
  613. lst.add(m)
  614. return lst
  615. def types_full(model_name):
  616. """Return a list of full types usable in the model"""
  617. _goto_mode(MODE_MODIFY, model_name)
  618. _input("types")
  619. lst = set([])
  620. output = _handle_output("Success: ", split=" ")
  621. if output == "":
  622. return set([])
  623. for v in output.split("\n"):
  624. m, mm = v.split(":")
  625. m = m.strip()
  626. mm = mm.strip()
  627. lst.add((m, mm))
  628. return lst
  629. def read(model_name, ID):
  630. """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
  631. _goto_mode(MODE_MODIFY, model_name)
  632. _input(["read", ID])
  633. output = _handle_output("Success: ", split=" ")
  634. v = output.split("\n")
  635. t = v[1].split(":")[1].strip()
  636. if (not v[2].startswith("Source:")):
  637. rval = (t, None)
  638. else:
  639. src = v[2].split(":")[1].strip()
  640. trg = v[3].split(":")[1].strip()
  641. rval = (t, (src, trg))
  642. return rval
  643. def read_attrs(model_name, ID):
  644. """Return a dictionary of attribute value pairs"""
  645. _goto_mode(MODE_MODIFY, model_name)
  646. _input(["read", ID])
  647. output = _handle_output("Success: ", split=" ")
  648. v = output.split("\n")
  649. searching = True
  650. rval = {}
  651. for r in v:
  652. if searching:
  653. if r == "Attributes:":
  654. # Start working on attributes
  655. searching = False
  656. else:
  657. key, value = r.split(":", 1)
  658. _, value = value.split("=", 1)
  659. key = json.loads(key.strip())
  660. value = value.strip()
  661. if value == "None":
  662. value = None
  663. elif value == "True":
  664. value = True
  665. elif value == "False":
  666. value = False
  667. else:
  668. value = json.loads(value)
  669. rval[key] = value
  670. return rval
  671. def instantiate(model_name, typename, edge=None, ID=""):
  672. """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
  673. _goto_mode(MODE_MODIFY, model_name)
  674. if edge is None:
  675. _input(["instantiate_node", typename, ID])
  676. else:
  677. _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
  678. return _handle_output("Success: ", split=" ")
  679. def delete_element(model_name, ID):
  680. """Delete the element with the given ID"""
  681. _goto_mode(MODE_MODIFY, model_name)
  682. _input(["delete", ID])
  683. _handle_output("Success")
  684. def attr_assign(model_name, ID, attr, value):
  685. """Assign a value to an attribute"""
  686. _check_type(value)
  687. _goto_mode(MODE_MODIFY, model_name)
  688. _input(["attr_add", ID, attr, value])
  689. _handle_output("Success")
  690. def attr_assign_code(model_name, ID, attr, code):
  691. """Assign a piece of Action Language code to the attribute"""
  692. _check_type(code)
  693. try:
  694. compiled = _compile_AL(code)
  695. except Exception as e:
  696. raise CompilationError(e)
  697. _goto_mode(MODE_MODIFY, model_name)
  698. _input(["attr_add", ID, attr])
  699. _handle_output("Waiting for code constructors...")
  700. _input(compiled)
  701. _output("Success")
  702. def attr_delete(model_name, ID, attr):
  703. """Remove an attribute."""
  704. _goto_mode(MODE_MODIFY, model_name)
  705. _input(["attr_del", ID, attr])
  706. _handle_output("Success")
  707. def read_outgoing(model_name, ID, typename):
  708. """Returns a list of all outgoing associations of a specific type ("" = all)"""
  709. _goto_mode(MODE_MODIFY, model_name)
  710. _input(["read_outgoing", ID, typename])
  711. output = _handle_output("Success: ", split=" ")
  712. if output == "":
  713. return set([])
  714. else:
  715. return set(output.split("\n"))
  716. def read_incoming(model_name, ID, typename):
  717. """Returns a list of all incoming associations of a specific type ("" = all)"""
  718. _goto_mode(MODE_MODIFY, model_name)
  719. _input(["read_incoming", ID, typename])
  720. output = _handle_output("Success: ", split=" ")
  721. if output == "":
  722. return set([])
  723. else:
  724. return set(output.split("\n"))
  725. def read_association_source(model_name, ID):
  726. """Returns the source of an association."""
  727. _goto_mode(MODE_MODIFY, model_name)
  728. _input(["read_association_source", ID])
  729. return _handle_output("Success: ", split=" ")
  730. def read_association_destination(model_name, ID):
  731. """Returns the destination of an association."""
  732. _goto_mode(MODE_MODIFY, model_name)
  733. _input(["read_association_destination", ID])
  734. return _handle_output("Success: ", split=" ")
  735. ##### To document:
  736. def service_register(name, function):
  737. """Register a function as a service with a specific name."""
  738. def service_process(port):
  739. while 1:
  740. thrd = threading.Thread(target=function, args=[service_get(port)])
  741. thrd.daemon = True
  742. thrd.start()
  743. global mode
  744. _goto_mode(MODE_MODELLING)
  745. _input(["service_register", name])
  746. # Now we are in service-mode
  747. mode = MODE_SERVICE
  748. port = _handle_output("Success: ", split=" ")
  749. # Process events in the background!
  750. threading.Thread(target=service_process, args=[port]).start()
  751. def service_stop():
  752. """Stop the currently executing process."""
  753. _goto_mode(MODE_SERVICE)
  754. _input("service_stop")
  755. _handle_output("Success")
  756. global mode
  757. mode = MODE_MODELLING
  758. def service_get(port):
  759. """Get the values on the specified port."""
  760. _goto_mode(MODE_SERVICE)
  761. return _output(port=port)
  762. def service_set(port, value):
  763. """Set a value on a specified port."""
  764. _check_type(value)
  765. _goto_mode(MODE_SERVICE)
  766. _input(value, port=port)
  767. def user_password(user, password):
  768. """Change a user's password."""
  769. raise NotImplementedError()
  770. def transformation_read_signature(transformation):
  771. """Reads an operation's signature, specifying the names and their required types."""
  772. raise NotImplementedError()
  773. def element_list_nice(model_name):
  774. """Fetches a nice representation of models."""
  775. _goto_mode(MODE_MODELLING)
  776. _input(["element_list_nice", model_name, _get_metamodel(model_name)])
  777. return json.loads(_handle_output("Success: ", split=" "))
  778. def connections_between(model_name, source_element, target_element):
  779. """Gets a list of all allowed connections between the source and target element in the model."""
  780. _goto_mode(MODE_MODIFY, model_name)
  781. _input(["connections_between", source_element, target_element])
  782. output = _handle_output("Success: ", split=" ")
  783. if output == "":
  784. return set([])
  785. else:
  786. return set(output.split("\n"))
  787. def define_attribute(model_name, node, attr_name, attr_type):
  788. """Create a new attribute, which can be instantiated one meta-level below."""
  789. _goto_mode(MODE_MODIFY, model_name)
  790. _input(["define_attribute", node, attr_name, attr_type])
  791. return _handle_output("Success: ", split=" ")
  792. def all_instances(model_name, type_name):
  793. """Returns a list of all elements of a specific type."""
  794. _goto_mode(MODE_MODIFY, model_name)
  795. _input(["all_instances", type_name])
  796. output = _handle_output("Success: ", split=" ")
  797. if output == "":
  798. return set([])
  799. else:
  800. return set(output.split("\n"))
  801. def service_poll(port):
  802. """Checks whether or not the Modelverse side has any input ready to be processed."""
  803. raise NotImplementedError()
  804. def user_name(user, username):
  805. """Change a user's name."""
  806. raise NotImplementedError()
  807. def remove_conformance(model_name, metamodel_name):
  808. """Remove a metamodel for a model."""
  809. _goto_mode(MODE_MODELLING)
  810. _input(["remove_conformance", model_name, metamodel_name])
  811. _handle_output("Success")
  812. def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
  813. """Add a metamodel for a model."""
  814. raise NotImplementedError()
  815. _goto_mode(MODE_MODELLING)
  816. _input(["add_conformance", model_name, metamodel_name])
  817. _handle_output("Success")