blob: 29d66f568faa28cdbb00c62cc09e911285f3e246 [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 Bavier614af142020-08-07 14:49:56 -070026SECRET_ICAL_URL = os.environ.get("SECRET_ICAL_URL")
Andy Bavier4021a2f2020-07-29 12:39:47 -070027NO_RESULT_THRESHOLD = 720
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070028
29app = Flask(__name__)
30edges = [
31 {
32 'name': 'production-edge-example',
33 'status': {
34 'control_plane': 'connected',
35 'user_plane': 'connected'
36 },
Andy Bavier614af142020-08-07 14:49:56 -070037 'last_update': time.time(),
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -070038 }
39]
40
Andy Bavier4021a2f2020-07-29 12:39:47 -070041status_codes = {
42 "no result": -2,
43 "error": -1,
44 "disconnected": 0,
45 "connecting": 1,
46 "connected": 2
47}
48
Andy Bavier614af142020-08-07 14:49:56 -070049room_mapping = {
50 "production-edge-onf-menlo": "(Compute)-MP-1-Aether Production",
51 "production-edge-example": "(Compute)-MP-1-Aether Production" # for testing
52}
53
Andy Bavier4021a2f2020-07-29 12:39:47 -070054cp_status = prom.Gauge("aetheredge_status_control_plane", "Control plane status code", ["name"])
55up_status = prom.Gauge("aetheredge_status_user_plane", "User plane status code", ["name"])
56last_update = prom.Gauge("aetheredge_last_update", "Last reported test result", ["name"])
Andy Bavier614af142020-08-07 14:49:56 -070057maint_window = prom.Gauge("aetheredge_in_maintenance_window", "Currently in a maintenance window", ["name"])
58
59def is_my_event(event, name):
60 for field in ["summary", "location", "description"]:
61 if name in getattr(event, field, ""):
62 return True
63 return False
64
65def in_maintenance_window(events, name, now):
66 for event in events:
67 if event.start < now and event.end > now:
68 if is_my_event(event, name):
69 return True
70 if name in room_mapping and is_my_event(event, room_mapping[name]):
71 return True
72 return False
73
74def pull_maintenance_events():
75 while(True):
76 now = datetime.datetime.now(pytz.utc)
77 try:
78 es = events(SECRET_ICAL_URL, start = now)
79 except Exception as e:
80 print(e)
81 else:
82 for edge in edges:
83 if 'maintenance' not in edge:
84 edge['maintenance'] = {}
85 edge['maintenance']['in_window'] = in_maintenance_window(es, edge['name'], now)
86 edge['maintenance']['last_update'] = time.time()
87 time.sleep(60)
Andy Bavier4021a2f2020-07-29 12:39:47 -070088
89def time_out_stale_results():
90 for edge in edges:
91 time_elapsed = time.time() - edge["last_update"]
92 if time_elapsed > NO_RESULT_THRESHOLD:
93 edge['status']['control_plane'] = "no result"
94 edge['status']['user_plane'] = "no result"
95
96
97@app.route('/edges/metrics', methods=['GET'])
98def get_prometheus_metrics():
99 res = []
100 time_out_stale_results()
101 for edge in edges:
102 if edge['name'] == "production-edge-example":
103 continue
104
105 cp_status.labels(edge['name']).set(status_codes[edge['status']['control_plane']])
106 up_status.labels(edge['name']).set(status_codes[edge['status']['user_plane']])
107 last_update.labels(edge['name']).set(edge['last_update'])
Andy Bavier614af142020-08-07 14:49:56 -0700108 if 'maintenance' in edge:
109 maint_window.labels(edge['name']).set(int(edge['maintenance']['in_window']))
Andy Bavier4021a2f2020-07-29 12:39:47 -0700110
111 res.append(prom.generate_latest(cp_status))
112 res.append(prom.generate_latest(up_status))
113 res.append(prom.generate_latest(last_update))
Andy Bavier614af142020-08-07 14:49:56 -0700114 res.append(prom.generate_latest(maint_window))
115
Andy Bavier4021a2f2020-07-29 12:39:47 -0700116 return Response(res, mimetype="text/plain")
117
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700118
119@app.route('/edges/healthz', methods=['GET'])
120def get_health():
121 return {'message': 'healthy'}
122
123
124@app.route('/edges', methods=['GET'])
125def get_edges():
Andy Bavier4021a2f2020-07-29 12:39:47 -0700126 time_out_stale_results()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700127 return jsonify({'edges': edges})
128
129
130@app.route('/edges/<string:name>', methods=['GET'])
131def get_edge(name):
Andy Bavier4021a2f2020-07-29 12:39:47 -0700132 time_out_stale_results()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700133 edge = [edge for edge in edges if edge['name'] == name]
134 if len(edge) == 0:
135 abort(404)
136 return jsonify({'edge': edge[0]})
137
138
139@app.route('/edges', methods=['POST'])
140def create_or_update_edge():
141 if not request.json:
142 abort(400)
143 if 'name' not in request.json:
144 abort(400)
145 if 'status' not in request.json:
146 abort(400)
147
148 req_edge = {
149 'name': request.json['name'],
150 'status': {
151 'control_plane': request.json['status']['control_plane'],
152 'user_plane': request.json['status']['user_plane']
153 },
154 'last_update': time.time()
155 }
156
157 edge = [edge for edge in edges if edge['name'] == req_edge['name']]
158 if len(edge) == 0:
159 print("new edge request " + req_edge['name'])
160 edges.append(req_edge)
161 else:
162 edge[0]['status']['control_plane'] = req_edge['status']['control_plane']
163 edge[0]['status']['user_plane'] = req_edge['status']['user_plane']
164 edge[0]['last_update'] = req_edge['last_update']
165
166 return jsonify({'edge': req_edge}), 201
167
168
169if __name__ == '__main__':
Andy Bavier614af142020-08-07 14:49:56 -0700170 if SECRET_ICAL_URL:
171 print(" * Starting maintenance calendar polling thread")
172 t = threading.Thread(target=pull_maintenance_events)
173 t.start()
Hyunsun Moonf32ae9a2020-05-28 13:17:45 -0700174 app.run(debug=True, host='0.0.0.0', port=80)