modelverse.py 31 KB

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