modelverse.py 30 KB

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