utils.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import unittest
  2. import sys
  3. import os
  4. import sys
  5. import time
  6. import json
  7. import urllib
  8. try:
  9. import urllib2
  10. except ImportError:
  11. import urllib as urllib2
  12. import subprocess
  13. import signal
  14. import random
  15. sys.path.append("interface/HUTN")
  16. sys.path.append("scripts")
  17. #from interface.HUTN.hutn_compiler.compiler import main as do_compile
  18. taskname = "test_task"
  19. INIT_TIMEOUT = 30
  20. try:
  21. import pytest
  22. slow = pytest.mark.skipif(
  23. not pytest.config.getoption("--runslow"),
  24. reason="need --runslow option to run"
  25. )
  26. except:
  27. slow = lambda i:i
  28. ports = set()
  29. def getFreePort():
  30. """Gets a unique new port."""
  31. while 1:
  32. port = random.randint(10000, 20000)
  33. # Check if this port is in the set of ports.
  34. if port not in ports:
  35. # We have found a unique port. Add it to the set and return.
  36. ports.add(port)
  37. return port
  38. def execute(scriptname, parameters=[], wait=False):
  39. if os.name not in ["nt", "posix"]:
  40. # Stop now, as we would have no clue on how to kill its subtree
  41. raise Exception("Unknown OS version: " + str(os.name))
  42. command = [sys.executable, "-u", "scripts/%s.py" % scriptname] + parameters
  43. if wait:
  44. return subprocess.call(command, shell=False)
  45. else:
  46. return subprocess.Popen(command, shell=False)
  47. def child_kill(pid):
  48. subprocess.call(["pkill", "-P", "%i" % pid])
  49. start = time.time()
  50. with open(os.devnull, 'w') as null:
  51. while subprocess.call(["pgrep", "-P", "%i" % pid], stdout=null) > 1:
  52. time.sleep(0.1)
  53. if time.time() > start + 4:
  54. subprocess.call(["pkill", "-9", "-P", "%i" % pid])
  55. def kill(process):
  56. if os.name == "nt":
  57. #TODO this is Windows and I don't care too much about that...
  58. subprocess.call(["taskkill", "/F", "/T", "/PID", "%i" % process.pid])
  59. elif os.name == "posix":
  60. child_kill(process.pid)
  61. process.send_signal(signal.SIGINT)
  62. process.wait()
  63. child_kill(os.getpid())
  64. def flush_data(address, data):
  65. if data:
  66. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": taskname})), timeout=INIT_TIMEOUT).read()
  67. return []
  68. def start_mvc():
  69. port = getFreePort()
  70. address = "127.0.0.1:%s" % port
  71. print("Execute run local MV")
  72. proc = execute("run_local_modelverse", [str(port)], wait=False)
  73. return proc, address