modelverse.py 29 KB

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