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