Adds basic healthcheck to Dockerfile
[osm/POL.git] / osm_policy_module / cmd / policy_module_healthcheck.py
1 # Copyright 2018 Whitestack, LLC
2 # *************************************************************
3
4 # This file is part of OSM Monitoring module
5 # All Rights Reserved to Whitestack, LLC
6
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10
11 # http://www.apache.org/licenses/LICENSE-2.0
12
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact: bdiaz@whitestack.com or glavado@whitestack.com
21 ##
22 import argparse
23 import asyncio
24 import logging
25 import subprocess
26 import sys
27
28 from aiokafka import AIOKafkaConsumer
29
30 from osm_policy_module.core.config import Config
31
32 log = logging.getLogger(__name__)
33
34
35 def main():
36 parser = argparse.ArgumentParser(prog='osm-policy-healthcheck')
37 parser.add_argument('--config-file', nargs='?', help='POL configuration file')
38 args = parser.parse_args()
39 cfg = Config(args.config_file)
40
41 if not _processes_running():
42 sys.exit(1)
43 if not _is_kafka_ok(cfg.get('message', 'host'), cfg.get('message', 'port')):
44 sys.exit(1)
45 sys.exit(0)
46
47
48 def _processes_running():
49 def _contains_process(processes, process_name):
50 for row in processes:
51 if process_name in row:
52 return True
53 return False
54
55 processes_to_check = ['osm-policy-agent']
56 ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
57 processes_running = ps.decode().split('\n')
58 for p in processes_to_check:
59 if not _contains_process(processes_running, p):
60 return False
61 return True
62
63
64 def _is_kafka_ok(host, port):
65 async def _test_kafka(loop):
66 consumer = AIOKafkaConsumer(
67 'healthcheck',
68 loop=loop, bootstrap_servers='{}:{}'.format(host, port))
69 await consumer.start()
70 await consumer.stop()
71
72 try:
73 loop = asyncio.get_event_loop()
74 loop.run_until_complete(_test_kafka(loop))
75 return True
76 except Exception:
77 log.exception("POL can not connect to Kafka")
78 return False
79
80
81 if __name__ == '__main__':
82 main()