blob: 05cd8596b9475b21a5e2694b0b88013b1b3cf44c [file] [log] [blame]
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -07001#!/usr/bin/env python
2
3# Copyright 2020-present Open Networking Foundation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain 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,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Andy Bavier614af142020-08-07 14:49:56 -070017import os
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070018import time
Andy Bavier614af142020-08-07 14:49:56 -070019import datetime
20import pytz
21import threading
22from icalevents.icalevents import events
Andy Bavier4021a2f2020-07-29 12:39:47 -070023from flask import Flask, jsonify, abort, request, Response
24import prometheus_client as prom
25
Andy Bavier8a5c9872020-10-21 13:17:53 -070026# URL of maintenance calendar
Andy Bavier614af142020-08-07 14:49:56 -070027SECRET_ICAL_URL = os.environ.get("SECRET_ICAL_URL")
Andy Bavier8a5c9872020-10-21 13:17:53 -070028
29# Aether environment that the server is monitoring (e.g., "production")
30# To schedule downtime, postfix the cluster name with the env: "ace-tucson-production"
31AETHER_ENV = os.environ.get("AETHER_ENV", "production")
32
33# Move to "no result" status if we don't hear from agent for this many seconds
Andy Bavier4021a2f2020-07-29 12:39:47 -070034NO_RESULT_THRESHOLD = 720
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070035
36app = Flask(__name__)
37edges = [
38 {
Andy Bavier8a5c9872020-10-21 13:17:53 -070039 'name': 'ace-example',
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070040 'status': {
41 'control_plane': 'connected',
42 'user_plane': 'connected'
43 },
Andy Bavier614af142020-08-07 14:49:56 -070044 'last_update': time.time(),
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070045 }
46]
47
Andy Bavier4021a2f2020-07-29 12:39:47 -070048status_codes = {
49 "no result": -2,
50 "error": -1,
51 "disconnected": 0,
52 "connecting": 1,
53 "connected": 2
54}
55
Andy Bavier614af142020-08-07 14:49:56 -070056room_mapping = {
Andy Bavier0423cbd2020-10-23 10:50:29 -070057 "ace-menlo-pixel-production": "(Compute)-MP-1-Aether Production",
58 "ace-menlo-staging": "(Compute)-MP-1-Aether Staging"
Andy Bavier614af142020-08-07 14:49:56 -070059}
60
Andy Bavier4021a2f2020-07-29 12:39:47 -070061cp_status = prom.Gauge("aetheredge_status_control_plane", "Control plane status code", ["name"])
62up_status = prom.Gauge("aetheredge_status_user_plane", "User plane status code", ["name"])
63last_update = prom.Gauge("aetheredge_last_update", "Last reported test result", ["name"])
Andy Bavier614af142020-08-07 14:49:56 -070064maint_window = prom.Gauge("aetheredge_in_maintenance_window", "Currently in a maintenance window", ["name"])
65
66def is_my_event(event, name):
67 for field in ["summary", "location", "description"]:
Andy Bavier8a5c9872020-10-21 13:17:53 -070068 fullname = name
69 if name.startswith("ace-"):
70 fullname = "%s-%s" % (name, AETHER_ENV)
71 if fullname in getattr(event, field, ""):
Andy Bavier614af142020-08-07 14:49:56 -070072 return True
Andy Bavier0423cbd2020-10-23 10:50:29 -070073 if fullname in room_mapping and room_mapping[fullname] in getattr(event, field, ""):
74 return True
Andy Bavier614af142020-08-07 14:49:56 -070075 return False
76
Andy Bavierc41cf0c2020-09-02 14:49:21 -070077def is_naive_datetime(d):
78 return d.tzinfo is None or d.tzinfo.utcoffset(d) is None
79
80def process_all_day_events(es):
81 for event in es:
82 if event.all_day:
83 # All day events have naive datetimes, which breaks comparisons
84 pacific = pytz.timezone('US/Pacific')
85 if is_naive_datetime(event.start):
86 event.start = pacific.localize(event.start)
87 if is_naive_datetime(event.end):
88 event.end = pacific.localize(event.end)
89
Andy Bavier614af142020-08-07 14:49:56 -070090def in_maintenance_window(events, name, now):
91 for event in events:
92 if event.start < now and event.end > now:
93 if is_my_event(event, name):
94 return True
Andy Bavier614af142020-08-07 14:49:56 -070095 return False
96
97def pull_maintenance_events():
98 while(True):
99 now = datetime.datetime.now(pytz.utc)
100 try:
101 es = events(SECRET_ICAL_URL, start = now)
Andy Bavierc41cf0c2020-09-02 14:49:21 -0700102 process_all_day_events(es)
Andy Bavier614af142020-08-07 14:49:56 -0700103 except Exception as e:
104 print(e)
105 else:
106 for edge in edges:
107 if 'maintenance' not in edge:
108 edge['maintenance'] = {}
109 edge['maintenance']['in_window'] = in_maintenance_window(es, edge['name'], now)
110 edge['maintenance']['last_update'] = time.time()
111 time.sleep(60)
Andy Bavier4021a2f2020-07-29 12:39:47 -0700112
113def time_out_stale_results():
114 for edge in edges:
115 time_elapsed = time.time() - edge["last_update"]
116 if time_elapsed > NO_RESULT_THRESHOLD:
117 edge['status']['control_plane'] = "no result"
118 edge['status']['user_plane'] = "no result"
119
120
121@app.route('/edges/metrics', methods=['GET'])
122def get_prometheus_metrics():
123 res = []
124 time_out_stale_results()
125 for edge in edges:
Andy Bavier8a5c9872020-10-21 13:17:53 -0700126 if edge['name'] == "ace-example":
Andy Bavier4021a2f2020-07-29 12:39:47 -0700127 continue
128
129 cp_status.labels(edge['name']).set(status_codes[edge['status']['control_plane']])
130 up_status.labels(edge['name']).set(status_codes[edge['status']['user_plane']])
131 last_update.labels(edge['name']).set(edge['last_update'])
Andy Bavier614af142020-08-07 14:49:56 -0700132 if 'maintenance' in edge:
133 maint_window.labels(edge['name']).set(int(edge['maintenance']['in_window']))
Andy Bavier4021a2f2020-07-29 12:39:47 -0700134
135 res.append(prom.generate_latest(cp_status))
136 res.append(prom.generate_latest(up_status))
137 res.append(prom.generate_latest(last_update))
Andy Bavier614af142020-08-07 14:49:56 -0700138 res.append(prom.generate_latest(maint_window))
139
Andy Bavier4021a2f2020-07-29 12:39:47 -0700140 return Response(res, mimetype="text/plain")
141
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700142
143@app.route('/edges/healthz', methods=['GET'])
144def get_health():
145 return {'message': 'healthy'}
146
147
148@app.route('/edges', methods=['GET'])
149def get_edges():
Andy Bavier4021a2f2020-07-29 12:39:47 -0700150 time_out_stale_results()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700151 return jsonify({'edges': edges})
152
153
154@app.route('/edges/<string:name>', methods=['GET'])
155def get_edge(name):
Andy Bavier4021a2f2020-07-29 12:39:47 -0700156 time_out_stale_results()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700157 edge = [edge for edge in edges if edge['name'] == name]
158 if len(edge) == 0:
159 abort(404)
160 return jsonify({'edge': edge[0]})
161
162
163@app.route('/edges', methods=['POST'])
164def create_or_update_edge():
165 if not request.json:
166 abort(400)
167 if 'name' not in request.json:
168 abort(400)
169 if 'status' not in request.json:
170 abort(400)
171
172 req_edge = {
173 'name': request.json['name'],
174 'status': {
175 'control_plane': request.json['status']['control_plane'],
176 'user_plane': request.json['status']['user_plane']
177 },
178 'last_update': time.time()
179 }
180
181 edge = [edge for edge in edges if edge['name'] == req_edge['name']]
182 if len(edge) == 0:
183 print("new edge request " + req_edge['name'])
184 edges.append(req_edge)
185 else:
186 edge[0]['status']['control_plane'] = req_edge['status']['control_plane']
187 edge[0]['status']['user_plane'] = req_edge['status']['user_plane']
188 edge[0]['last_update'] = req_edge['last_update']
189
190 return jsonify({'edge': req_edge}), 201
191
192
Hyunsun Moon5f237ec2020-09-29 14:45:52 -0700193@app.route('/edges/<string:name>', methods=['DELETE'])
194def delete_edge(name):
195 print("delete edge request " + name)
196 result = False
197 for i in range(len(edges)):
198 if edges[i]['name'] == name:
199 del edges[i]
200 result = True
201 break
202 if not result:
203 abort(404)
204 return jsonify({'result': True})
205
206
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700207if __name__ == '__main__':
Andy Bavier8a5c9872020-10-21 13:17:53 -0700208 if SECRET_ICAL_URL and AETHER_ENV:
209 print(" * Starting maintenance calendar polling thread (Aether env: %s)" % AETHER_ENV)
Andy Bavier614af142020-08-07 14:49:56 -0700210 t = threading.Thread(target=pull_maintenance_events)
211 t.start()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700212 app.run(debug=True, host='0.0.0.0', port=80)