modelverse.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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 _check_type(value):
  54. if not isinstance(value, (int, long, float, str, unicode, bool)):
  55. raise UnsupportedValue("%s : %s" % (value, str(type(value))))
  56. def _dict_to_list(python_dict):
  57. lst = []
  58. for k, v in python_dict.items():
  59. lst += [k, v]
  60. return lst
  61. def _goto_mode(new_mode, model_name=None):
  62. global mode
  63. global registered_metamodels
  64. if mode == MODE_MANUAL and new_mode == MODE_MODIFY:
  65. if model_name != None and current_model != model_name:
  66. raise InvalidMode("Mode error: cannot modify other models!")
  67. else:
  68. return
  69. elif mode == MODE_MODELLING and new_mode == MODE_MODIFY:
  70. # Are in root view, but want to modify a model
  71. if model_name not in registered_metamodels:
  72. raise UnfamiliarMetamodel(model_name)
  73. _model_modify(model_name, registered_metamodels[model_name])
  74. elif mode == MODE_MODIFY and new_mode == MODE_MODIFY and model_name != None and current_model != model_name:
  75. # Are in modify mode, but want to modify a different model
  76. if model_name not in registered_metamodels:
  77. raise UnfamiliarMetamodel(model_name)
  78. _model_exit()
  79. _model_modify(model_name, registered_metamodels[model_name])
  80. elif mode == MODE_MODIFY and new_mode == MODE_MODELLING:
  81. _model_exit()
  82. elif mode == new_mode:
  83. return
  84. else:
  85. # Go to a mode that we have no automatic transfer to: raise exception
  86. raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
  87. def _input(value, port=None):
  88. # Ugly json encoding of primitives
  89. #print("[IN] %s" % value)
  90. if port is None:
  91. port = taskname
  92. if isinstance(value, type([])):
  93. value = json.dumps(value)
  94. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": port}))).read()
  95. else:
  96. value = json.dumps(value)
  97. #print("Set input: " + str(value))
  98. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": port}))).read()
  99. def _input_raw(value, taskname):
  100. # Ugly json encoding of primitives
  101. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  102. #TODO check that this is actually a Modelverse!
  103. def _compile_AL(code):
  104. # Compile an action language file and send the compiled code
  105. code_fragments = code.split("\n")
  106. code_fragments = [i for i in code_fragments if i.strip() != ""]
  107. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  108. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  109. code_fragments = [i[initial_tabs:] for i in code_fragments]
  110. code_fragments.append("")
  111. code = "\n".join(code_fragments)
  112. with open(".code.alc", "w") as f:
  113. f.write(code)
  114. f.flush()
  115. return do_compile(".code.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
  116. def _compile_model(code):
  117. # Compile a model and send the compiled graph
  118. # First change multiple spaces to a tab
  119. code_fragments = code.split("\n")
  120. code_fragments = [i for i in code_fragments if i.strip() != ""]
  121. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  122. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  123. code_fragments = [i[initial_tabs:] for i in code_fragments]
  124. code_fragments.append("")
  125. code = "\n".join(code_fragments)
  126. with open(".model.mvc", "w") as f:
  127. f.write(code)
  128. f.flush()
  129. return do_compile(".model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M") + ["exit"]
  130. def _output(expected=None,port=None):
  131. if port is None:
  132. port = taskname
  133. try:
  134. global last_output
  135. last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": port}))).read())
  136. #print("[OUT] %s" % last_output)
  137. except:
  138. raise UnknownError()
  139. if expected is not None and last_output != expected:
  140. raise InterfaceMismatch(_last_output(), expected)
  141. return last_output
  142. def _last_output():
  143. return last_output
  144. # Raise common exceptions
  145. def _handle_output(requested=None, split=None):
  146. value = _output()
  147. if value.startswith("Model exists: "):
  148. raise ModelExists(value.split(": ", 1)[1])
  149. elif value.startswith("Permission denied"):
  150. raise PermissionDenied(value.split(": ", 1)[1])
  151. elif value.startswith("Model not found: "):
  152. raise UnknownModel(value.split(": ", 1)[1])
  153. elif value.startswith("Element not found: "):
  154. raise UnknownIdentifier(value.split(": ", 1)[1])
  155. elif value.startswith("Element exists: "):
  156. raise ElementExists(value.split(": ", 1)[1])
  157. elif value.startswith("Attribute not found: "):
  158. raise NoSuchAttribute(value.split(": ", 1)[1])
  159. elif requested is not None and value.startswith(requested):
  160. if split is None:
  161. return value
  162. else:
  163. splitted = value.strip().split(split, 1)
  164. if len(splitted) == 1:
  165. return ""
  166. else:
  167. return splitted[1].rstrip()
  168. else:
  169. raise InterfaceMismatch(value)
  170. def _model_modify(model_name, metamodel_name):
  171. """Modify an existing model."""
  172. global mode
  173. global prev_mode
  174. if mode == MODE_MANUAL:
  175. prev_mode = MODE_MANUAL
  176. mode = MODE_MODIFY
  177. return None
  178. _goto_mode(MODE_MODELLING)
  179. prev_mode = MODE_MODELLING
  180. _input(["model_modify", model_name, metamodel_name])
  181. _handle_output("Success")
  182. global current_model
  183. current_model = model_name
  184. # Mode has changed
  185. mode = MODE_MODIFY
  186. _output("Model loaded, ready for commands!")
  187. def _model_exit():
  188. """Leave model modify mode."""
  189. global mode
  190. global prev_mode
  191. if prev_mode == MODE_MANUAL:
  192. mode = MODE_MANUAL
  193. return
  194. if mode != MODE_MODIFY:
  195. raise InvalidMode()
  196. _input("exit")
  197. _output("Success")
  198. mode = MODE_MODELLING
  199. def alter_context(model_name, metamodel_name):
  200. global registered_metamodels
  201. registered_metamodels[model_name] = metamodel_name
  202. # Main MvC operations
  203. def init(address_param="http://127.0.0.1:8001", timeout=20.0):
  204. """Starts up the connection to the Modelverse."""
  205. global mode
  206. global address
  207. global taskname
  208. address = address_param
  209. start_time = time.time()
  210. taskname = random.random()
  211. while 1:
  212. try:
  213. _input_raw('"%s"' % taskname, "task_manager")
  214. mode = MODE_UNAUTHORIZED
  215. break
  216. except URLError as e:
  217. if time.time() - start_time > timeout:
  218. raise ConnectionError(e.reason)
  219. else:
  220. time.sleep(0.1)
  221. def login(username, password):
  222. """Log in a user, if user doesn't exist, it is created."""
  223. global mode
  224. _goto_mode(MODE_UNAUTHORIZED)
  225. _output("Log on as which user?")
  226. _input(username)
  227. if _output() == "Password for existing user?":
  228. _input(password)
  229. if _output() == "Welcome to the Model Management Interface v2.0!":
  230. _output("Use the 'help' command for a list of possible commands")
  231. _input("quiet")
  232. mode = MODE_MODELLING
  233. elif _last_output() == "Wrong password!":
  234. raise PermissionDenied()
  235. else:
  236. raise InterfaceMismatch(_last_output())
  237. elif _last_output() == "This is a new user: please give password!":
  238. _input(password)
  239. _output("Please repeat the password")
  240. _input(password)
  241. if _output() == "Passwords match!":
  242. _output("Welcome to the Model Management Interface v2.0!")
  243. _output("Use the 'help' command for a list of possible commands")
  244. _input("quiet")
  245. mode = MODE_MODELLING
  246. elif _last_output() == "Not the same password!":
  247. # We just sent the same password, so it should be identical, unless the interface changed
  248. raise InterfaceMismatch(_last_output())
  249. else:
  250. raise InterfaceMismatch(_last_output())
  251. else:
  252. raise InterfaceMismatch(_last_output())
  253. def model_add(model_name, metamodel_name, model_code=None):
  254. """Instantiate a new model."""
  255. _goto_mode(MODE_MODELLING)
  256. # Do this before creating the model, as otherwise compilation errors would make us inconsistent
  257. if model_code is not None:
  258. try:
  259. compiled = _compile_model(model_code)
  260. except Exception as e:
  261. raise CompilationError(e)
  262. else:
  263. compiled = ["exit"]
  264. _input(["model_add", metamodel_name, model_name])
  265. _handle_output("Waiting for model constructors...")
  266. _input(compiled)
  267. _output("Success")
  268. global registered_metamodels
  269. registered_metamodels[model_name] = metamodel_name
  270. def upload_code(code):
  271. try:
  272. compiled = _compile_AL(code)
  273. except Exception as e:
  274. raise CompilationError(e)
  275. _input(compiled)
  276. def model_delete(model_name):
  277. """Delete an existing model."""
  278. _goto_mode(MODE_MODELLING)
  279. _input(["model_delete", model_name])
  280. _handle_output("Success")
  281. def model_list():
  282. """List all models."""
  283. _goto_mode(MODE_MODELLING)
  284. _input("model_list")
  285. output = _handle_output("Success: ", split=" ")
  286. if output == "":
  287. return set([])
  288. lst = set([])
  289. value = output.strip().split("\n")
  290. for v in value:
  291. m, mm = v.split(":")
  292. m = m.strip()
  293. mm = mm.strip()
  294. lst.add((m, mm))
  295. return lst
  296. def model_list_full():
  297. """List full information on all models."""
  298. _goto_mode(MODE_MODELLING)
  299. _input("model_list_full")
  300. output = _handle_output("Success: ", split=" ")
  301. if output == "":
  302. return set([])
  303. lst = set([])
  304. value = output.strip().split("\n")
  305. for v in value:
  306. m, mm = v.split(":")
  307. m = m.strip()
  308. mm = mm.strip()
  309. perm, own, grp, m = m.split(" ")
  310. lst.add((m, mm, own, grp, perm))
  311. return lst
  312. def verify(model_name, metamodel_name=None):
  313. """Verify if a model conforms to its metamodel."""
  314. _goto_mode(MODE_MODELLING)
  315. if metamodel_name is None:
  316. global registered_metamodels
  317. if model_name not in registered_metamodels:
  318. raise UnknownMetamodellingHierarchy(model_name)
  319. metamodel_name = registered_metamodels[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. global registered_metamodels
  325. _goto_mode(MODE_MODIFY, model_name)
  326. if new_model is not None:
  327. try:
  328. compiled = _compile_model(new_model)
  329. except Exception as e:
  330. raise CompilationError(e)
  331. else:
  332. compiled = ["exit"]
  333. _input("upload")
  334. _handle_output("Waiting for model constructors...")
  335. _input(compiled)
  336. _output("Success")
  337. if metamodel_name is not None:
  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. global registered_metamodels
  777. _input(["element_list_nice", model_name, registered_metamodels[model_name]])
  778. return json.loads(_handle_output("Success: ", split=" "))
  779. def connections_between(model_name, source_element, target_element):
  780. """Gets a list of all allowed connections between the source and target element in the model."""
  781. _goto_mode(MODE_MODIFY, model_name)
  782. _input(["connections_between", source_element, target_element])
  783. output = _handle_output("Success: ", split=" ")
  784. if output == "":
  785. return set([])
  786. else:
  787. return set(output.split("\n"))
  788. def define_attribute(model_name, node, attr_name, attr_type):
  789. """Create a new attribute, which can be instantiated one meta-level below."""
  790. _goto_mode(MODE_MODIFY, model_name)
  791. _input(["define_attribute", node, attr_name, attr_type])
  792. return _handle_output("Success: ", split=" ")
  793. def all_instances(model_name, type_name):
  794. """Returns a list of all elements of a specific type."""
  795. _goto_mode(MODE_MODIFY, model_name)
  796. _input(["all_instances", type_name])
  797. output = _handle_output("Success: ", split=" ")
  798. if output == "":
  799. return set([])
  800. else:
  801. return set(output.split("\n"))
  802. def service_poll(port):
  803. """Checks whether or not the Modelverse side has any input ready to be processed."""
  804. raise NotImplementedError()
  805. def user_name(user, username):
  806. """Change a user's name."""
  807. raise NotImplementedError()
  808. def remove_conformance(model_name, metamodel_name):
  809. """Remove a metamodel for a model."""
  810. _goto_mode(MODE_MODELLING)
  811. _input(["remove_conformance", model_name, metamodel_name])
  812. _handle_output("Success")
  813. def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
  814. """Add a metamodel for a model."""
  815. raise NotImplementedError()
  816. _goto_mode(MODE_MODELLING)
  817. _input(["add_conformance", model_name, metamodel_name])
  818. _handle_output("Success")