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.

rspamd.py 10KB

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