start prometheus pushgateway
[osm/vim-emu.git] / src / emuvim / dcemulator / monitoring.py
1 __author__ = 'Administrator'
2
3 import urllib2
4 import logging
5 from mininet.node import OVSSwitch
6 import ast
7 import time
8 from prometheus_client import start_http_server, Summary, Histogram, Gauge, Counter, REGISTRY
9 import threading
10 from subprocess import Popen, PIPE
11 import os
12
13 logging.basicConfig(level=logging.INFO)
14
15 """
16 class to read openflow stats from the Ryu controller of the DCNetwork
17 """
18
19 class DCNetworkMonitor():
20 def __init__(self, net):
21 self.net = net
22 # link to Ryu REST_API
23 self.ip = '0.0.0.0'
24 self.port = '8080'
25 self.REST_api = 'http://{0}:{1}'.format(self.ip,self.port)
26
27 # helper variables to calculate the metrics
28 # Start up the server to expose the metrics to Prometheus.
29 start_http_server(8000)
30 # supported Prometheus metrics
31 self.prom_tx_packet_count = Gauge('sonemu_tx_count_packets', 'Total number of packets sent',
32 ['vnf_name', 'vnf_interface'])
33 self.prom_rx_packet_count = Gauge('sonemu_rx_count_packets', 'Total number of packets received',
34 ['vnf_name', 'vnf_interface'])
35 self.prom_tx_byte_count = Gauge('sonemu_tx_count_bytes', 'Total number of bytes sent',
36 ['vnf_name', 'vnf_interface'])
37 self.prom_rx_byte_count = Gauge('sonemu_rx_count_bytes', 'Total number of bytes received',
38 ['vnf_name', 'vnf_interface'])
39
40 self.prom_metrics={'tx_packets':self.prom_tx_packet_count, 'rx_packets':self.prom_rx_packet_count,
41 'tx_bytes':self.prom_tx_byte_count,'rx_bytes':self.prom_rx_byte_count}
42
43 # list of installed metrics to monitor
44 # each entry can contain this data
45 '''
46 {
47 switch_dpid = 0
48 vnf_name = None
49 vnf_interface = None
50 previous_measurement = 0
51 previous_monitor_time = 0
52 metric_key = None
53 mon_port = None
54 }
55 '''
56 self.network_metrics = []
57
58 # start monitoring thread
59 self.start_monitoring = True
60 self.monitor_thread = threading.Thread(target=self.get_network_metrics)
61 self.monitor_thread.start()
62
63 # helper tools
64 self.pushgateway_process = self.start_PushGateway()
65 self.prometheus_process = self.start_Prometheus()
66 self.cadvisor_process = self.start_cadvisor()
67
68 # first set some parameters, before measurement can start
69 def setup_metric(self, vnf_name, vnf_interface=None, metric='tx_packets'):
70
71 network_metric = {}
72
73 # check if port is specified (vnf:port)
74 if vnf_interface is None:
75 # take first interface by default
76 connected_sw = self.net.DCNetwork_graph.neighbors(vnf_name)[0]
77 link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]
78 vnf_interface = link_dict[0]['src_port_id']
79
80 network_metric['vnf_name'] = vnf_name
81 network_metric['vnf_interface'] = vnf_interface
82
83 for connected_sw in self.net.DCNetwork_graph.neighbors(vnf_name):
84 link_dict = self.net.DCNetwork_graph[vnf_name][connected_sw]
85 for link in link_dict:
86 # logging.info("{0},{1}".format(link_dict[link],vnf_interface))
87 if link_dict[link]['src_port_id'] == vnf_interface:
88 # found the right link and connected switch
89 # logging.info("{0},{1}".format(link_dict[link]['src_port_id'], vnf_source_interface))
90 network_metric['mon_port'] = link_dict[link]['dst_port']
91 break
92
93 if 'mon_port' not in network_metric:
94 logging.exception("vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface))
95 return "vnf interface {0}:{1} not found!".format(vnf_name,vnf_interface)
96
97 try:
98 # default port direction to monitor
99 if metric is None:
100 metric = 'tx_packets'
101
102 vnf_switch = self.net.DCNetwork_graph.neighbors(str(vnf_name))
103
104 if len(vnf_switch) > 1:
105 logging.info("vnf: {0} has multiple ports".format(vnf_name))
106 return
107 elif len(vnf_switch) == 0:
108 logging.info("vnf: {0} is not connected".format(vnf_name))
109 return
110 else:
111 vnf_switch = vnf_switch[0]
112 next_node = self.net.getNodeByName(vnf_switch)
113
114 if not isinstance(next_node, OVSSwitch):
115 logging.info("vnf: {0} is not connected to switch".format(vnf_name))
116 return
117
118 network_metric['previous_measurement'] = 0
119 network_metric['previous_monitor_time'] = 0
120
121
122 network_metric['switch_dpid'] = int(str(next_node.dpid), 16)
123 network_metric['metric_key'] = metric
124
125 self.network_metrics.append(network_metric)
126
127 logging.info('Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))
128 return 'Started monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)
129
130 except Exception as ex:
131 logging.exception("setup_metric error.")
132 return ex.message
133
134 def stop_metric(self, vnf_name, vnf_interface, metric):
135 for metric_dict in self.network_metrics:
136 if metric_dict['vnf_name'] == vnf_name and metric_dict['vnf_interface'] == vnf_interface \
137 and metric_dict['metric_key'] == metric:
138
139 self.network_metrics.remove(metric_dict)
140
141 #this removes the complete metric, all labels...
142 #REGISTRY.unregister(self.prom_metrics[metric_dict['metric_key']])
143
144 # set values to NaN, prometheus api currently does not support removal of metrics
145 self.prom_metrics[metric_dict['metric_key']].labels(vnf_name, vnf_interface).set(float('nan'))
146
147 logging.info('Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric))
148 return 'Stopped monitoring: {2} on {0}:{1}'.format(vnf_name, vnf_interface, metric)
149
150
151 # get all metrics defined in the list and export it to Prometheus
152 def get_network_metrics(self):
153 while self.start_monitoring:
154 # group metrics by dpid to optimize the rest api calls
155 dpid_list = [metric_dict['switch_dpid'] for metric_dict in self.network_metrics]
156 dpid_set = set(dpid_list)
157
158 for dpid in dpid_set:
159
160 # query Ryu
161 ret = self.REST_cmd('stats/port', dpid)
162 port_stat_dict = ast.literal_eval(ret)
163
164 metric_list = [metric_dict for metric_dict in self.network_metrics
165 if int(metric_dict['switch_dpid'])==int(dpid)]
166 #logging.info('1set prom packets:{0} '.format(self.network_metrics))
167 for metric_dict in metric_list:
168 self.set_network_metric(metric_dict, port_stat_dict)
169
170 time.sleep(1)
171
172 # add metric to the list to export to Prometheus, parse the Ryu port-stats reply
173 def set_network_metric(self, metric_dict, port_stat_dict):
174 # vnf tx is the datacenter switch rx and vice-versa
175 metric_key = self.switch_tx_rx(metric_dict['metric_key'])
176 switch_dpid = metric_dict['switch_dpid']
177 vnf_name = metric_dict['vnf_name']
178 vnf_interface = metric_dict['vnf_interface']
179 previous_measurement = metric_dict['previous_measurement']
180 previous_monitor_time = metric_dict['previous_monitor_time']
181 mon_port = metric_dict['mon_port']
182
183 for port_stat in port_stat_dict[str(switch_dpid)]:
184 if int(port_stat['port_no']) == int(mon_port):
185 port_uptime = port_stat['duration_sec'] + port_stat['duration_nsec'] * 10 ** (-9)
186 this_measurement = int(port_stat[metric_key])
187 #logging.info('set prom packets:{0} {1}:{2}'.format(this_measurement, vnf_name, vnf_interface))
188
189 # set prometheus metric
190 self.prom_metrics[metric_dict['metric_key']].labels(vnf_name, vnf_interface).set(this_measurement)
191
192 if previous_monitor_time <= 0 or previous_monitor_time >= port_uptime:
193 metric_dict['previous_measurement'] = int(port_stat[metric_key])
194 metric_dict['previous_monitor_time'] = port_uptime
195 # do first measurement
196 #logging.info('first measurement')
197 time.sleep(1)
198 byte_rate = self.get_network_metrics()
199 return byte_rate
200 else:
201 time_delta = (port_uptime - metric_dict['previous_monitor_time'])
202 byte_rate = (this_measurement - metric_dict['previous_measurement']) / float(time_delta)
203 # logging.info('uptime:{2} delta:{0} rate:{1}'.format(time_delta,byte_rate,port_uptime))
204
205 metric_dict['previous_measurement'] = this_measurement
206 metric_dict['previous_monitor_time'] = port_uptime
207 return byte_rate
208
209 logging.exception('metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface))
210 return 'metric {0} not found on {1}:{2}'.format(metric_key, vnf_name, vnf_interface)
211
212
213 def REST_cmd(self, prefix, dpid):
214 url = self.REST_api + '/' + str(prefix) + '/' + str(dpid)
215 req = urllib2.Request(url)
216 ret = urllib2.urlopen(req).read()
217 return ret
218
219 def start_Prometheus(self, port=9090):
220 # prometheus.yml configuration file is located in the same directory as this file
221 cmd = ["docker",
222 "run",
223 "--rm",
224 "-p", "{0}:9090".format(port),
225 "-v", "{0}/prometheus.yml:/etc/prometheus/prometheus.yml".format(os.path.dirname(os.path.abspath(__file__))),
226 "--name", "prometheus",
227 "prom/prometheus"
228 ]
229 logging.info('Start Prometheus container {0}'.format(cmd))
230 return Popen(cmd)
231
232 def start_PushGateway(self, port=9091):
233 cmd = ["docker",
234 "run",
235 "-d",
236 "-p", "{0}:9091".format(port),
237 "--name", "pushgateway",
238 "prom/pushgateway"
239 ]
240
241 logging.info('Start Prometheus Push Gateway container {0}'.format(cmd))
242 return Popen(cmd)
243
244 def start_cadvisor(self, port=8090):
245 cmd = ["docker",
246 "run",
247 "--rm",
248 "--volume=/:/rootfs:ro",
249 "--volume=/var/run:/var/run:rw",
250 "--volume=/sys:/sys:ro",
251 "--volume=/var/lib/docker/:/var/lib/docker:ro",
252 "--publish={0}:8080".format(port),
253 "--name=cadvisor",
254 "google/cadvisor:latest"
255 ]
256 logging.info('Start cAdvisor container {0}'.format(cmd))
257 return Popen(cmd)
258
259 def stop(self):
260 # stop the monitoring thread
261 self.start_monitoring = False
262 self.monitor_thread.join()
263
264 if self.prometheus_process is not None:
265 logging.info('stopping prometheus container')
266 self.prometheus_process.terminate()
267 self.prometheus_process.kill()
268 self._stop_container('prometheus')
269
270 if self.pushgateway_process is not None:
271 logging.info('stopping pushgateway container')
272 self.pushgateway_process.terminate()
273 self.pushgateway_process.kill()
274 self._stop_container('pushgateway')
275
276 if self.cadvisor_process is not None:
277 logging.info('stopping cadvisor container')
278 self.cadvisor_process.terminate()
279 self.cadvisor_process.kill()
280 self._stop_container('cadvisor')
281
282 def switch_tx_rx(self,metric=''):
283 # when monitoring vnfs, the tx of the datacenter switch is actually the rx of the vnf
284 # so we need to change the metric name to be consistent with the vnf rx or tx
285 if 'tx' in metric:
286 metric = metric.replace('tx','rx')
287 elif 'rx' in metric:
288 metric = metric.replace('rx','tx')
289
290 return metric
291
292 def _stop_container(self, name):
293 cmd = ["docker",
294 "stop",
295 name]
296 Popen(cmd).wait()
297
298 cmd = ["docker",
299 "rm",
300 name]
301 Popen(cmd).wait()
302
303