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