modelverse.py 29 KB

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