You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. from urllib.request import urlopen
  2. import glob
  3. import grp
  4. import http.client
  5. import os
  6. import os.path
  7. import psutil
  8. import pwd
  9. import shutil
  10. import signal
  11. import socket
  12. import stat
  13. import sys
  14. import tempfile
  15. from robot.api import logger
  16. from robot.libraries.BuiltIn import BuiltIn
  17. import demjson
  18. def Check_JSON(j):
  19. d = demjson.decode(j, strict=True)
  20. logger.debug('got json %s' % d)
  21. assert len(d) > 0
  22. assert 'error' not in d
  23. return d
  24. def cleanup_temporary_directory(directory):
  25. shutil.rmtree(directory)
  26. def save_run_results(directory, filenames):
  27. current_directory = os.getcwd()
  28. suite_name = BuiltIn().get_variable_value("${SUITE_NAME}")
  29. test_name = BuiltIn().get_variable_value("${TEST NAME}")
  30. if os.path.exists(directory):
  31. onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
  32. logger.debug('%s content before cleanup: %s' % (directory, onlyfiles))
  33. if test_name is None:
  34. # this is suite-level tear down
  35. destination_directory = "%s/robot-save/%s" % (current_directory, suite_name)
  36. else:
  37. destination_directory = "%s/robot-save/%s/%s" % (current_directory, suite_name, test_name)
  38. if not os.path.isdir(destination_directory):
  39. os.makedirs(destination_directory)
  40. for file in filenames.split(' '):
  41. source_file = "%s/%s" % (directory, file)
  42. logger.debug('check if we can save %s' % source_file)
  43. if os.path.isfile(source_file):
  44. logger.debug('found %s, save it' % file)
  45. shutil.copy(source_file, "%s/%s" % (destination_directory, file))
  46. shutil.copy(source_file, "%s/robot-save/%s.last" % (current_directory, file))
  47. def encode_filename(filename):
  48. return "".join(['%%%0X' % ord(b) for b in filename])
  49. def get_test_directory():
  50. return os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "../../")
  51. def get_top_dir():
  52. if os.environ.get('RSPAMD_TOPDIR'):
  53. return os.environ['RSPAMD_TOPDIR']
  54. return get_test_directory() + "/../../"
  55. def get_install_root():
  56. if os.environ.get('RSPAMD_INSTALLROOT'):
  57. return os.path.abspath(os.environ['RSPAMD_INSTALLROOT'])
  58. return os.path.abspath("../install/")
  59. def get_rspamd():
  60. if os.environ.get('RSPAMD'):
  61. return os.environ['RSPAMD']
  62. if os.environ.get('RSPAMD_INSTALLROOT'):
  63. return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamd"
  64. dname = get_top_dir()
  65. return dname + "/src/rspamd"
  66. def get_rspamc():
  67. if os.environ.get('RSPAMC'):
  68. return os.environ['RSPAMC']
  69. if os.environ.get('RSPAMD_INSTALLROOT'):
  70. return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamc"
  71. dname = get_top_dir()
  72. return dname + "/src/client/rspamc"
  73. def get_rspamadm():
  74. if os.environ.get('RSPAMADM'):
  75. return os.environ['RSPAMADM']
  76. if os.environ.get('RSPAMD_INSTALLROOT'):
  77. return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamadm"
  78. dname = get_top_dir()
  79. return dname + "/src/rspamadm/rspamadm"
  80. def HTTP(method, host, port, path, data=None, headers={}):
  81. c = http.client.HTTPConnection("%s:%s" % (host, port))
  82. c.request(method, path, data, headers)
  83. r = c.getresponse()
  84. t = r.read()
  85. s = r.status
  86. c.close()
  87. return [s, t]
  88. def hard_link(src, dst):
  89. os.link(src, dst)
  90. def make_temporary_directory():
  91. """Creates and returns a unique temporary directory
  92. Example:
  93. | ${RSPAMD_TMPDIR} = | Make Temporary Directory |
  94. """
  95. dirname = tempfile.mkdtemp()
  96. os.chmod(dirname, stat.S_IRUSR |
  97. stat.S_IXUSR |
  98. stat.S_IWUSR |
  99. stat.S_IRGRP |
  100. stat.S_IXGRP |
  101. stat.S_IROTH |
  102. stat.S_IXOTH)
  103. return dirname
  104. def make_temporary_file():
  105. return tempfile.mktemp()
  106. def path_splitter(path):
  107. dirname = os.path.dirname(path)
  108. basename = os.path.basename(path)
  109. return [dirname, basename]
  110. def rspamc(addr, port, filename):
  111. mboxgoo = b"From MAILER-DAEMON Fri May 13 19:17:40 2016\r\n"
  112. goo = open(filename, 'rb').read()
  113. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  114. s.connect((addr, port))
  115. s.send(b"CHECK RSPAMC/1.0\r\nContent-length: ")
  116. s.send(str(len(goo+mboxgoo)).encode('utf-8'))
  117. s.send(b"\r\n\r\n")
  118. s.send(mboxgoo)
  119. s.send(goo)
  120. r = s.recv(2048)
  121. return r.decode('utf-8')
  122. def Scan_File(filename, **headers):
  123. addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}")
  124. port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL}")
  125. headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}")
  126. c = http.client.HTTPConnection("%s:%s" % (addr, port))
  127. c.request("POST", "/checkv2", open(filename, "rb"), headers)
  128. r = c.getresponse()
  129. assert r.status == 200
  130. d = demjson.decode(r.read())
  131. c.close()
  132. BuiltIn().set_test_variable("${SCAN_RESULT}", d)
  133. return
  134. def Send_SIGUSR1(pid):
  135. pid = int(pid)
  136. os.kill(pid, signal.SIGUSR1)
  137. def set_directory_ownership(path, username, groupname):
  138. if os.getuid() == 0:
  139. uid=pwd.getpwnam(username).pw_uid
  140. gid=grp.getgrnam(groupname).gr_gid
  141. os.chown(path, uid, gid)
  142. def spamc(addr, port, filename):
  143. goo = open(filename, 'rb').read()
  144. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  145. s.connect((addr, port))
  146. s.send(b"SYMBOLS SPAMC/1.0\r\nContent-length: ")
  147. s.send(str(len(goo)).encode('utf-8'))
  148. s.send(b"\r\n\r\n")
  149. s.send(goo)
  150. s.shutdown(socket.SHUT_WR)
  151. r = s.recv(2048)
  152. return r.decode('utf-8')
  153. def TCP_Connect(addr, port):
  154. """Attempts to open a TCP connection to specified address:port
  155. Example:
  156. | Wait Until Keyword Succeeds | 5s | 10ms | TCP Connect | localhost | 8080 |
  157. """
  158. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  159. s.settimeout(5) # seconds
  160. s.connect((addr, port))
  161. s.close()
  162. def ping_rspamd(addr, port):
  163. return str(urlopen("http://%s:%s/ping" % (addr, port)).read())
  164. def redis_check(addr, port):
  165. """Attempts to open a TCP connection to specified address:port
  166. Example:
  167. | Wait Until Keyword Succeeds | 5s | 10ms | TCP Connect | localhost | 8080 |
  168. """
  169. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  170. s.settimeout(1.0) # seconds
  171. s.connect((addr, port))
  172. if s.sendall(b"ECHO TEST\n"):
  173. result = s.recv(128)
  174. return result == b'TEST\n'
  175. else:
  176. return False
  177. def update_dictionary(a, b):
  178. a.update(b)
  179. return a
  180. TERM_TIMEOUT = 10 # wait after sending a SIGTERM signal
  181. KILL_WAIT = 20 # additional wait after sending a SIGKILL signal
  182. def shutdown_process(process):
  183. # send SIGTERM
  184. process.terminate()
  185. try:
  186. process.wait(TERM_TIMEOUT)
  187. return
  188. except psutil.TimeoutExpired:
  189. logger.info( "PID {} is not terminated in {} seconds, sending SIGKILL...".format(process.pid, TERM_TIMEOUT))
  190. try:
  191. # send SIGKILL
  192. process.kill()
  193. except psutil.NoSuchProcess:
  194. # process exited just before we tried to kill
  195. return
  196. try:
  197. process.wait(KILL_WAIT)
  198. except psutil.TimeoutExpired:
  199. raise RuntimeError("Failed to shutdown process {} ({})".format(process.pid, process.name()))
  200. def shutdown_process_with_children(pid):
  201. pid = int(pid)
  202. try:
  203. process = psutil.Process(pid=pid)
  204. except psutil.NoSuchProcess:
  205. return
  206. children = process.children(recursive=True)
  207. shutdown_process(process)
  208. for child in children:
  209. try:
  210. child.kill()
  211. except psutil.NoSuchProcess:
  212. pass
  213. psutil.wait_procs(children, timeout=KILL_WAIT)
  214. def write_to_stdin(process_handle, text):
  215. if not isinstance(text, bytes):
  216. text = bytes(text, 'utf-8')
  217. lib = BuiltIn().get_library_instance('Process')
  218. obj = lib.get_process_object()
  219. obj.stdin.write(text + b"\n")
  220. obj.stdin.flush()
  221. obj.stdin.close()
  222. out = obj.stdout.read(4096)
  223. return out.decode('utf-8')
  224. def get_file_if_exists(file_path):
  225. if os.path.exists(file_path):
  226. with open(file_path, 'r') as myfile:
  227. return myfile.read()
  228. return None
  229. def _merge_luacov_stats(statsfile, coverage):
  230. """
  231. Reads a coverage stats file written by luacov and merges coverage data to
  232. 'coverage' dict: { src_file: hits_list }
  233. Format of the file defined in:
  234. https://github.com/keplerproject/luacov/blob/master/src/luacov/stats.lua
  235. """
  236. with open(statsfile, 'r') as fh:
  237. while True:
  238. # max_line:filename
  239. line = fh.readline().rstrip()
  240. if not line:
  241. break
  242. max_line, src_file = line.split(':')
  243. counts = [int(x) for x in fh.readline().split()]
  244. assert len(counts) == int(max_line)
  245. if src_file in coverage:
  246. # enlarge list if needed: lenght of list in different luacov.stats.out files may differ
  247. old_len = len(coverage[src_file])
  248. new_len = len(counts)
  249. if new_len > old_len:
  250. coverage[src_file].extend([0] * (new_len - old_len))
  251. # sum execution counts for each line
  252. for l, exe_cnt in enumerate(counts):
  253. coverage[src_file][l] += exe_cnt
  254. else:
  255. coverage[src_file] = counts
  256. def _dump_luacov_stats(statsfile, coverage):
  257. """
  258. Saves data to the luacov stats file. Existing file is overwritted if exists.
  259. """
  260. src_files = sorted(coverage)
  261. with open(statsfile, 'w') as fh:
  262. for src in src_files:
  263. stats = " ".join(str(n) for n in coverage[src])
  264. fh.write("%s:%s\n%s\n" % (len(coverage[src]), src, stats))
  265. # File used by luacov to collect coverage stats
  266. LUA_STATSFILE = "luacov.stats.out"
  267. def collect_lua_coverage():
  268. """
  269. Merges ${RSPAMD_TMPDIR}/*.luacov.stats.out into luacov.stats.out
  270. Example:
  271. | Collect Lua Coverage |
  272. """
  273. # decided not to do optional coverage so far
  274. #if not 'ENABLE_LUA_COVERAGE' in os.environ['HOME']:
  275. # logger.info("ENABLE_LUA_COVERAGE is not present in env, will not collect Lua coverage")
  276. # return
  277. tmp_dir = BuiltIn().get_variable_value("${RSPAMD_TMPDIR}")
  278. coverage = {}
  279. input_files = []
  280. for f in glob.iglob("%s/*.luacov.stats.out" % tmp_dir):
  281. _merge_luacov_stats(f, coverage)
  282. input_files.append(f)
  283. if input_files:
  284. if os.path.isfile(LUA_STATSFILE):
  285. _merge_luacov_stats(LUA_STATSFILE, coverage)
  286. _dump_luacov_stats(LUA_STATSFILE, coverage)
  287. logger.info("%s merged into %s" % (", ".join(input_files), LUA_STATSFILE))
  288. else:
  289. logger.info("no *.luacov.stats.out files found in %s" % tmp_dir)
  290. def file_exists(file):
  291. return os.path.isfile(file)