Puppet module to manage log processor
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.
 
 
 
 
 

554 lines
20 KiB

  1. #!/usr/bin/python2
  2. #
  3. # Copyright 2013 Hewlett-Packard Development Company, L.P.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. import argparse
  17. import daemon
  18. import gear
  19. import json
  20. import logging
  21. import os
  22. import Queue
  23. import re
  24. import requests
  25. import select
  26. import socket
  27. import subprocess
  28. import sys
  29. import threading
  30. import time
  31. import yaml
  32. import paho.mqtt.publish as publish
  33. try:
  34. import daemon.pidlockfile as pidfile_mod
  35. except ImportError:
  36. import daemon.pidfile as pidfile_mod
  37. def semi_busy_wait(seconds):
  38. # time.sleep() may return early. If it does sleep() again and repeat
  39. # until at least the number of seconds specified has elapsed.
  40. start_time = time.time()
  41. while True:
  42. time.sleep(seconds)
  43. cur_time = time.time()
  44. seconds = seconds - (cur_time - start_time)
  45. if seconds <= 0.0:
  46. return
  47. class FilterException(Exception):
  48. pass
  49. class CRM114Filter(object):
  50. def __init__(self, script, path, build_status):
  51. self.p = None
  52. self.script = script
  53. self.path = path
  54. self.build_status = build_status
  55. if build_status not in ['SUCCESS', 'FAILURE']:
  56. return
  57. if not os.path.exists(path):
  58. os.makedirs(path)
  59. args = [script, path, build_status]
  60. self.p = subprocess.Popen(args,
  61. stdout=subprocess.PIPE,
  62. stderr=subprocess.PIPE,
  63. stdin=subprocess.PIPE,
  64. close_fds=True)
  65. def process(self, data):
  66. if not self.p:
  67. return True
  68. self.p.stdin.write(data['message'].encode('utf-8') + '\n')
  69. (r, w, x) = select.select([self.p.stdout], [],
  70. [self.p.stdin, self.p.stdout], 20)
  71. if not r:
  72. self.p.kill()
  73. raise FilterException('Timeout reading from CRM114')
  74. r = self.p.stdout.readline()
  75. if not r:
  76. err = self.p.stderr.read()
  77. if err:
  78. raise FilterException(err)
  79. else:
  80. raise FilterException('Early EOF from CRM114')
  81. r = r.strip()
  82. data['error_pr'] = float(r)
  83. return True
  84. def _catchOSError(self, method):
  85. try:
  86. method()
  87. except OSError:
  88. logging.exception("Subprocess cleanup failed.")
  89. def close(self):
  90. if not self.p:
  91. return
  92. # CRM114 should die when its stdinput is closed. Close that
  93. # fd along with stdout and stderr then return.
  94. self._catchOSError(self.p.stdin.close)
  95. self._catchOSError(self.p.stdout.close)
  96. self._catchOSError(self.p.stderr.close)
  97. self._catchOSError(self.p.wait)
  98. class CRM114FilterFactory(object):
  99. name = "CRM114"
  100. def __init__(self, script, basepath):
  101. self.script = script
  102. self.basepath = basepath
  103. # Precompile regexes
  104. self.re_remove_suffix = re.compile(r'(\.[^a-zA-Z]+)?(\.gz)?$')
  105. self.re_remove_dot = re.compile(r'\.')
  106. def create(self, fields):
  107. # We only want the basename so that the same logfile at different
  108. # paths isn't treated as different
  109. filename = os.path.basename(fields['filename'])
  110. # We want to collapse any numeric or compression suffixes so that
  111. # nova.log and nova.log.1 and nova.log.1.gz are treated as the same
  112. # logical file
  113. filename = self.re_remove_suffix.sub(r'', filename)
  114. filename = self.re_remove_dot.sub('_', filename)
  115. path = os.path.join(self.basepath, filename)
  116. return CRM114Filter(self.script, path, fields['build_status'])
  117. class OsloSeverityFilter(object):
  118. DATEFMT = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}((\.|\,)\d{3,6})?'
  119. SEVERITYFMT = '(DEBUG|INFO|WARNING|ERROR|TRACE|AUDIT|CRITICAL)'
  120. OSLO_LOGMATCH = ('^(?P<date>%s)(?P<line>(?P<pid> \d+)? '
  121. '(?P<severity>%s).*)' %
  122. (DATEFMT, SEVERITYFMT))
  123. OSLORE = re.compile(OSLO_LOGMATCH)
  124. def process(self, data):
  125. msg = data['message']
  126. m = self.OSLORE.match(msg)
  127. if m:
  128. data['severity'] = m.group('severity')
  129. if data['severity'].lower == 'debug':
  130. # Ignore debug-level lines
  131. return False
  132. return True
  133. def close(self):
  134. pass
  135. class OsloSeverityFilterFactory(object):
  136. name = "OsloSeverity"
  137. def create(self, fields):
  138. return OsloSeverityFilter()
  139. class SystemdSeverityFilter(object):
  140. '''
  141. Match systemd DEBUG level logs
  142. A line to match looks like:
  143. Aug 15 18:58:49.910786 hostname devstack@keystone.service[31400]: DEBUG uwsgi ...
  144. '''
  145. SYSTEMDDATE = '\w+\s+\d+\s+\d{2}:\d{2}:\d{2}((\.|\,)\d{3,6})?'
  146. DATEFMT = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}((\.|\,)\d{3,6})?'
  147. SEVERITYFMT = '(DEBUG|INFO|WARNING|ERROR|TRACE|AUDIT|CRITICAL)'
  148. SYSTEMD_LOGMATCH = '^(?P<date>%s)( (\S+) \S+\[\d+\]\: ' \
  149. '(?P<severity>%s)?.*)' % (SYSTEMDDATE, SEVERITYFMT)
  150. SYSTEMDRE = re.compile(SYSTEMD_LOGMATCH)
  151. def process(self, data):
  152. msg = data['message']
  153. m = self.SYSTEMDRE.match(msg)
  154. if m:
  155. if m.group('severity') == 'DEBUG':
  156. return False
  157. return True
  158. def close(self):
  159. pass
  160. class SystemdSeverityFilterFactory(object):
  161. name = "SystemdSeverity"
  162. def create(self, fields):
  163. return SystemdSeverityFilter()
  164. class LogRetriever(threading.Thread):
  165. def __init__(self, gearman_worker, filters, logq, mqtt=None):
  166. threading.Thread.__init__(self)
  167. self.gearman_worker = gearman_worker
  168. self.filters = filters
  169. self.logq = logq
  170. self.mqtt = mqtt
  171. def run(self):
  172. while True:
  173. try:
  174. self._handle_event()
  175. except:
  176. logging.exception("Exception retrieving log event.")
  177. def _handle_event(self):
  178. fields = {}
  179. num_log_lines = 0
  180. source_url = ''
  181. http_session = None
  182. job = self.gearman_worker.getJob()
  183. try:
  184. arguments = json.loads(job.arguments.decode('utf-8'))
  185. source_url = arguments['source_url']
  186. event = arguments['event']
  187. logging.debug("Handling event: " + json.dumps(event))
  188. fields = event.get('fields') or event.get('@fields')
  189. tags = event.get('tags') or event.get('@tags')
  190. if fields['build_status'] != 'ABORTED':
  191. # Handle events ignoring aborted builds. These builds are
  192. # discarded by zuul.
  193. file_obj, http_session = self._open_log_file_url(source_url)
  194. try:
  195. all_filters = []
  196. for f in self.filters:
  197. logging.debug("Adding filter: %s" % f.name)
  198. all_filters.append(f.create(fields))
  199. filters = all_filters
  200. base_event = {}
  201. base_event.update(fields)
  202. base_event["tags"] = tags
  203. for line in self._retrieve_log_line(file_obj):
  204. keep_line = True
  205. out_event = base_event.copy()
  206. out_event["message"] = line
  207. new_filters = []
  208. for f in filters:
  209. if not keep_line:
  210. new_filters.append(f)
  211. continue
  212. try:
  213. keep_line = f.process(out_event)
  214. new_filters.append(f)
  215. except FilterException:
  216. logging.exception("Exception filtering event: "
  217. "%s" % line.encode("utf-8"))
  218. filters = new_filters
  219. if keep_line:
  220. self.logq.put(out_event)
  221. num_log_lines += 1
  222. logging.debug("Pushed " + str(num_log_lines) +
  223. " log lines.")
  224. finally:
  225. for f in all_filters:
  226. f.close()
  227. if http_session:
  228. http_session.close()
  229. job.sendWorkComplete()
  230. # Only send mqtt events for log files we processed.
  231. if self.mqtt and num_log_lines:
  232. msg = json.dumps({
  233. 'build_uuid': fields.get('build_uuid'),
  234. 'source_url': source_url,
  235. 'status': 'success',
  236. })
  237. self.mqtt.publish_single(msg, fields.get('project'),
  238. fields.get('build_change'),
  239. 'retrieve_logs',
  240. fields.get('build_queue'))
  241. except Exception as e:
  242. logging.exception("Exception handling log event.")
  243. job.sendWorkException(str(e).encode('utf-8'))
  244. if self.mqtt:
  245. msg = json.dumps({
  246. 'build_uuid': fields.get('build_uuid'),
  247. 'source_url': source_url,
  248. 'status': 'failure',
  249. })
  250. self.mqtt.publish_single(msg, fields.get('project'),
  251. fields.get('build_change'),
  252. 'retrieve_logs',
  253. fields.get('build_queue'))
  254. def _retrieve_log_line(self, file_obj, chunk_size=4096):
  255. if not file_obj:
  256. return
  257. # Response.iter_lines automatically decodes 'gzip' and 'deflate'
  258. # encodings.
  259. # https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content
  260. for line in file_obj.iter_lines(chunk_size, decode_unicode=True):
  261. yield line
  262. def _open_log_file_url(self, source_url):
  263. file_obj = None
  264. try:
  265. logging.debug("Retrieving: " + source_url)
  266. # Use a session to persist the HTTP connection across requests
  267. # while downloading chunks of the log file.
  268. session = requests.Session()
  269. session.headers = {'Accept-encoding': 'deflate, gzip'}
  270. file_obj = session.get(source_url, stream=True)
  271. file_obj.raise_for_status()
  272. except requests.HTTPError as e:
  273. if e.response.status_code == 404:
  274. logging.info("Unable to retrieve %s: HTTP error 404" %
  275. source_url)
  276. else:
  277. logging.exception("Unable to get log data.")
  278. except Exception:
  279. # Silently drop fatal errors when retrieving logs.
  280. # TODO (clarkb): Handle these errors.
  281. # Perhaps simply add a log message to file_obj?
  282. logging.exception("Unable to retrieve source file.")
  283. raise
  284. return file_obj, session
  285. class StdOutLogProcessor(object):
  286. def __init__(self, logq, pretty_print=False):
  287. self.logq = logq
  288. self.pretty_print = pretty_print
  289. def handle_log_event(self):
  290. log = self.logq.get()
  291. if self.pretty_print:
  292. print(json.dumps(log, sort_keys=True,
  293. indent=4, separators=(',', ': ')))
  294. else:
  295. print(json.dumps(log))
  296. # Push each log event through to keep logstash up to date.
  297. sys.stdout.flush()
  298. class INETLogProcessor(object):
  299. socket_type = None
  300. def __init__(self, logq, host, port):
  301. self.logq = logq
  302. self.host = host
  303. self.port = port
  304. self.socket = None
  305. def _connect_socket(self):
  306. logging.debug("Creating socket.")
  307. self.socket = socket.socket(socket.AF_INET, self.socket_type)
  308. self.socket.connect((self.host, self.port))
  309. def handle_log_event(self):
  310. log = self.logq.get()
  311. try:
  312. if self.socket is None:
  313. self._connect_socket()
  314. self.socket.sendall((json.dumps(log) + '\n').encode('utf-8'))
  315. except:
  316. logging.exception("Exception sending INET event.")
  317. # Logstash seems to take about a minute to start again. Wait 90
  318. # seconds before attempting to reconnect. If logstash is not
  319. # available after 90 seconds we will throw another exception and
  320. # die.
  321. semi_busy_wait(90)
  322. self._connect_socket()
  323. self.socket.sendall((json.dumps(log) + '\n').encode('utf-8'))
  324. class UDPLogProcessor(INETLogProcessor):
  325. socket_type = socket.SOCK_DGRAM
  326. class TCPLogProcessor(INETLogProcessor):
  327. socket_type = socket.SOCK_STREAM
  328. class PushMQTT(object):
  329. def __init__(self, hostname, base_topic, port=1883, client_id=None,
  330. keepalive=60, will=None, auth=None, tls=None, qos=0):
  331. self.hostname = hostname
  332. self.port = port
  333. self.client_id = client_id
  334. self.keepalive = 60
  335. self.will = will
  336. self.auth = auth
  337. self.tls = tls
  338. self.qos = qos
  339. self.base_topic = base_topic
  340. def _generate_topic(self, project, job_id, action):
  341. return '/'.join([self.base_topic, project, job_id, action])
  342. def publish_single(self, msg, project, job_id, action, build_queue=None):
  343. if job_id:
  344. topic = self._generate_topic(project, job_id, action)
  345. elif build_queue:
  346. topic = self._generate_topic(project, build_queue, action)
  347. else:
  348. topic = self.base_topic + '/' + project
  349. publish.single(topic, msg, hostname=self.hostname,
  350. port=self.port, client_id=self.client_id,
  351. keepalive=self.keepalive, will=self.will,
  352. auth=self.auth, tls=self.tls, qos=self.qos)
  353. class Server(object):
  354. def __init__(self, config, debuglog):
  355. # Config init.
  356. self.config = config
  357. self.gearman_host = self.config['gearman-host']
  358. self.gearman_port = self.config['gearman-port']
  359. self.output_host = self.config['output-host']
  360. self.output_port = self.config['output-port']
  361. self.output_mode = self.config['output-mode']
  362. mqtt_host = self.config.get('mqtt-host')
  363. mqtt_port = self.config.get('mqtt-port', 1883)
  364. mqtt_user = self.config.get('mqtt-user')
  365. mqtt_pass = self.config.get('mqtt-pass')
  366. mqtt_topic = self.config.get('mqtt-topic', 'gearman-subunit')
  367. mqtt_ca_certs = self.config.get('mqtt-ca-certs')
  368. mqtt_certfile = self.config.get('mqtt-certfile')
  369. mqtt_keyfile = self.config.get('mqtt-keyfile')
  370. # Pythong logging output file.
  371. self.debuglog = debuglog
  372. self.retriever = None
  373. self.logqueue = Queue.Queue(16384)
  374. self.processor = None
  375. self.filter_factories = []
  376. # Run the severity filter first so it can filter out chatty
  377. # logs.
  378. self.filter_factories.append(OsloSeverityFilterFactory())
  379. self.filter_factories.append(SystemdSeverityFilterFactory())
  380. crmscript = self.config.get('crm114-script')
  381. crmdata = self.config.get('crm114-data')
  382. if crmscript and crmdata:
  383. self.filter_factories.append(
  384. CRM114FilterFactory(crmscript, crmdata))
  385. # Setup MQTT
  386. self.mqtt = None
  387. if mqtt_host:
  388. auth = None
  389. if mqtt_user:
  390. auth = {'username': mqtt_user}
  391. if mqtt_pass:
  392. auth['password'] = mqtt_pass
  393. tls = None
  394. if mqtt_ca_certs:
  395. tls = {'ca_certs': mqtt_ca_certs, 'certfile': mqtt_certfile,
  396. 'keyfile': mqtt_keyfile}
  397. self.mqtt = PushMQTT(mqtt_host, mqtt_topic, port=mqtt_port,
  398. auth=auth, tls=tls)
  399. def setup_logging(self):
  400. if self.debuglog:
  401. logging.basicConfig(format='%(asctime)s %(message)s',
  402. filename=self.debuglog, level=logging.DEBUG)
  403. else:
  404. # Prevent leakage into the logstash log stream.
  405. logging.basicConfig(level=logging.CRITICAL)
  406. logging.debug("Log pusher starting.")
  407. def wait_for_name_resolution(self, host, port):
  408. while True:
  409. try:
  410. socket.getaddrinfo(host, port)
  411. except socket.gaierror as e:
  412. if e.errno == socket.EAI_AGAIN:
  413. logging.debug("Temporary failure in name resolution")
  414. time.sleep(2)
  415. continue
  416. else:
  417. raise
  418. break
  419. def setup_retriever(self):
  420. hostname = socket.gethostname()
  421. gearman_worker = gear.Worker(hostname + b'-pusher')
  422. self.wait_for_name_resolution(self.gearman_host, self.gearman_port)
  423. gearman_worker.addServer(self.gearman_host,
  424. self.gearman_port)
  425. gearman_worker.registerFunction(b'push-log')
  426. self.retriever = LogRetriever(gearman_worker, self.filter_factories,
  427. self.logqueue, mqtt=self.mqtt)
  428. def setup_processor(self):
  429. if self.output_mode == "tcp":
  430. self.processor = TCPLogProcessor(self.logqueue,
  431. self.output_host,
  432. self.output_port)
  433. elif self.output_mode == "udp":
  434. self.processor = UDPLogProcessor(self.logqueue,
  435. self.output_host,
  436. self.output_port)
  437. else:
  438. # Note this processor will not work if the process is run as a
  439. # daemon. You must use the --foreground option.
  440. self.processor = StdOutLogProcessor(self.logqueue)
  441. def main(self):
  442. self.setup_retriever()
  443. self.setup_processor()
  444. self.retriever.daemon = True
  445. self.retriever.start()
  446. while True:
  447. try:
  448. self.processor.handle_log_event()
  449. except:
  450. logging.exception("Exception processing log event.")
  451. raise
  452. def main():
  453. parser = argparse.ArgumentParser()
  454. parser.add_argument("-c", "--config", required=True,
  455. help="Path to yaml config file.")
  456. parser.add_argument("-d", "--debuglog",
  457. help="Enable debug log. "
  458. "Specifies file to write log to.")
  459. parser.add_argument("--foreground", action='store_true',
  460. help="Run in the foreground.")
  461. parser.add_argument("-p", "--pidfile",
  462. default="/var/run/jenkins-log-pusher/"
  463. "jenkins-log-gearman-worker.pid",
  464. help="PID file to lock during daemonization.")
  465. args = parser.parse_args()
  466. with open(args.config, 'r') as config_stream:
  467. config = yaml.load(config_stream)
  468. server = Server(config, args.debuglog)
  469. if args.foreground:
  470. server.setup_logging()
  471. server.main()
  472. else:
  473. pidfile = pidfile_mod.TimeoutPIDLockFile(args.pidfile, 10)
  474. with daemon.DaemonContext(pidfile=pidfile):
  475. server.setup_logging()
  476. server.main()
  477. if __name__ == '__main__':
  478. main()