5 # Copyright © 2018 Amdocs
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # http://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
24 from datetime import datetime
26 consul_server = "consul-server:8500"
27 message_router = "message-router:3904"
28 topic = '{{.Values.config.messageRouterTopic}}'
29 log_file='/app/monitor.log'
30 status_file='/app/.health'
34 if os.environ.get('SDNC_IS_PRIMARY_CLUSTER', 'true') == 'false':
38 if len(sys.argv) > 1 and sys.argv[1] == '--debug':
41 def get_state(healthcheck):
42 response = requests.get("http://" + consul_server + "/v1/health/checks/" + healthcheck)
43 if response.status_code != 200:
44 raise RuntimeError("HTTP " + str(response.status_code))
45 data = response.json()
47 raise RuntimeError(healthcheck + " not found")
49 raise RuntimeError("Multiple states for " + healthcheck + " found")
56 with open(log_file, 'a') as f:
57 f.write(str(datetime.now()) + " " + message + "\n")
59 def healthcheck(checks, failFirst=True):
64 if type(check) is list:
65 passing = healthcheck(check, False)
67 state = get_state(check)
68 status = state['Status']
69 passing = status == "passing" or status == "warning"
70 log(check + " " + status)
72 if status == "passing":
73 color = "\033[32m" # green
74 elif status == "warning":
75 color = "\033[33m" # yellow
77 color = "\033[31m" # red
78 print check, color + status + "\033[0m"
80 print "\tCause:", state['Output']
85 # found a passing check so can stop here
89 # found a failing check so can stop here
96 with open("/app/config/healthchecks.json") as f:
100 with open(status_file) as f:
101 previous_result = f.read()
104 previous_result = 'unknown'
106 if healthcheck(checks):
113 # save current result to file
114 with open(status_file, 'w') as f:
117 if previous_result != 'unknown' and result != previous_result:
118 payload = { 'type' : 'health-change', 'status': result, 'site': siteName, 'deployment': '{{.Values.config.deployment}}', 'timestamp': str(datetime.now()) }
119 log("Posting event " + str(payload))
121 requests.post("http://" + message_router + "/events/" + topic, data=json.dumps(payload), headers={ 'Content-Type' : 'application/json' } )
123 # events are best-effort
126 except Exception as e: