forked from LuizOz/openvswitch-collectd-plugin
/
openvswitch.py
252 lines (204 loc) · 7.68 KB
/
openvswitch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# openvswitch-collectd-plugin
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; only version 2
# of the License is applicable.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import re
import collectd
from subprocess import Popen, PIPE
is_network_node = False
last_values = {}
def determine_node_role():
"""
Runs virsh list as a simple check if that's a compute or network node.
"""
try:
cmd = Popen(("virsh", "list"),
stdout=PIPE, stderr=PIPE, close_fds=True)
cmd.communicate()
except OSError:
global is_network_node
is_network_node = True
def get_popen_cmd_stdout(cmd, stdin=None):
"""
Executes the given cmd with stdin if any and returns the stdout.
Logs the stderr if any.
"""
try:
cmd_out = Popen(cmd,
stdout=PIPE, stderr=PIPE, stdin=stdin, close_fds=True)
cmd_std_err = cmd_out.stderr.read()
if cmd_std_err:
collectd.info("%s wrote to stderr: %s" % (cmd, cmd_std_err))
return cmd_out.stdout
except (OSError, IOError) as exc:
collectd.error("An error occured while running %s cmd: %s" % (cmd, exc))
#TODO: handle further
def get_ovs_ctl_stdout(cmd, stdin=None):
"""
Using Popen, runs the given 'cmd' and returns its stdout.
"""
cmd_stdout = get_popen_cmd_stdout(cmd, stdin)
return cmd_stdout.readlines()
def get_ovs_statistics():
"""
Runs the Openvswitch Datapath Control utility to grab statistics.
"""
data = {}
cmd = ("ovs-dpctl", "show", "--timeout=5")
ovs_stdout = get_ovs_ctl_stdout(cmd)
for i, line in enumerate(ovs_stdout):
if line.find("@ovs-system") != -1:
# TODO: find vs regex
# TODO: a better parsing?
bridge = line.strip().replace(":", "")
data[bridge] = ovs_stdout[i+1].strip()
flows_number = ovs_stdout[i+2].strip()
break # we run only 1 DP
flows_number = flows_number.split(": ")[1]
all_vals = struct_info(data)
all_vals['system@ovs-system']['flows'] = flows_number
return all_vals
def get_ps_ovs_cpu_usage():
"""
Returns a cpu usage of ovs-vswitchd (userspace) service in percent.
This represents the load generated by data-path 'missed' packets plus
internal OVS stuff.
"""
cpu_usage = 0.0
try:
with open("/var/run/openvswitch/ovs-vswitchd.pid", "r") as pid_file:
pid = pid_file.read().strip()
cmd = ("ps", "-p", pid, "-o" "%cpu")
ps_out = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True)
std_err = ps_out.stderr.readlines()
if std_err:
collectd.info("ps wrote to stderr: %s" % std_err)
cpu_usage = float(ps_out.stdout.readlines()[-1].strip())
except (OSError, IOError, ValueError) as exc:
collectd.error("An error occured while getting cpu usage: %s" % exc)
return cpu_usage
def get_num_of_vxlans():
"""
Returns a number of vxlan tunnels as reported by ovs-ofctl;
All should be on br-tun interface.
"""
num_vxlans = 0
# grep all vxlans on br-tun and count them:
cmd = ("ovs-ofctl", "show", "br-tun", "--timeout=5")
ovs_stdout = get_popen_cmd_stdout(cmd)
grep_out = get_popen_cmd_stdout(("grep", "(vxlan-"), ovs_stdout)
wc_out = get_popen_cmd_stdout(("wc", "-l"), grep_out)
try:
num_vxlans = int(wc_out.read()) # no extra line here
except TypeError as exc:
collectd.error("An error occured while getting vxlan count: %s" % exc)
return num_vxlans
def get_virsh_list_num_instances():
"""
Returns the number of VMs running on current host as reported by
'virsh list --uuid --state-running'
"""
num_instances = 0
if is_network_node: # return 0
return num_instances
# cmd to list all running VM uuids and count their number (-1 line):
cmd = ("virsh", "list", "--uuid", "--state-running")
virsh_list_out = get_popen_cmd_stdout(cmd)
wc_out = get_popen_cmd_stdout(("wc", "-l"), virsh_list_out)
try:
num_instances = int(wc_out.read()) - 1 # an empty line
except TypeError as exc:
collectd.error("An error occured while running virsh: %s" % exc)
return num_instances
def struct_info(lines):
"""
Returns a parced data from given lines.
"""
struct = {}
for line in lines:
#TODO: why?
struct[line] = {}
for d in re.split(":? ", lines[line], 3):
if d.find(":") != -1:
stats = d.split(":")
struct[line][stats[0]] = float(stats[1])
return struct
def calculate_ratio(last, values):
"""
Calculates the current ratio between hit/miss/lost packets
based on given last values and new values. Returns ratios in percent.
"""
d = []
total = 0
ratio_keys = ["hit", "missed", "lost"]
if (last):
for i in range(len(ratio_keys)):
if (values[i] and last[i]):
d.append(values[i] - last[i])
total += (values[i] - last[i])
else:
d.append(0.00)
if (total != 0):
return [(d[i]/total)*100 for i, key in enumerate(ratio_keys)]
return [0.00, 0.00, 0.00]
def dispatch_to_collectd(data_type, values):
"""
Submits the given values of the given type to collectd.
"""
cc = collectd.Values(plugin="openvswitch")
#cc.type_instance = "system@ovs-system" # optional
cc.type = data_type
cc.values = values
cc.dispatch()
def send_data_to_collectd(ovs_data, cpu_usage, vms_running, vxlan_count):
"""
Sends all acquired statistics to collectd.
"""
global last_values
keys = ["hit", "missed", "lost"]
for val in ovs_data:
values = []
# OVS DP (hit/miss/loss/flows):
for key in keys:
if (ovs_data[val].get(key) is not None):
values.append(ovs_data[val][key])
else:
values.append(0.00)
dispatch_to_collectd("datapath", values)
dispatch_to_collectd("datapath_flows", (ovs_data[val]["flows"],))
# OVS DP as percentage:
ratio_values = calculate_ratio(last_values.get(val), values)
dispatch_to_collectd("datapath_ratio", ratio_values)
last_values[val] = values
# CPU use; number of VMs; VXLAN count:
dispatch_to_collectd("cpu_usage", (cpu_usage,))
dispatch_to_collectd("total_vxlans", (vxlan_count,))
if not is_network_node:
# compute node -> report amount of VMs
dispatch_to_collectd("running_vms", (vms_running,))
def read_openvswitch_stats():
"""
A callback method used by collectd.
An entry point. Gets all the possible stats and sends them to collectd.
"""
ovs_stats = get_ovs_statistics() # OVS DataPath Stats
ovs_cpu_usage = get_ps_ovs_cpu_usage() # ps -o %cpu for OVS
vms_running = get_virsh_list_num_instances() # libvirt VM count
vxlan_count = get_num_of_vxlans() # OVS OF vxlan count
if not ovs_stats:
collectd.error("Did not receive the main OVS stats")
return None
send_data_to_collectd(ovs_stats, ovs_cpu_usage, vms_running, vxlan_count)
determine_node_role()
collectd.register_read(read_openvswitch_stats)