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