/
azure.include
212 lines (170 loc) · 7.66 KB
/
azure.include
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
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2018 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import json
_AZURE_METRIC_FMT = {
"count": lambda n: "%d" % n,
"percent": get_percent_human_readable,
"bytes": get_bytes_human_readable,
"bytes_per_second": lambda b: "%s/s" % get_bytes_human_readable(b),
"seconds": lambda s: "%.2f s" % s,
"milli_seconds": lambda ms: "%d ms" % (ms * 1000),
}
def get_data_or_go_stale(check_function):
"""Variant of get_parsed_item_data that raises MKCounterWrapped
if data is not found.
"""
@functools.wraps(check_function)
def wrapped_check_function(item, params, parsed):
if not isinstance(parsed, dict):
return 3, "Wrong usage of decorator: parsed is not a dict"
if item not in parsed or not parsed[item]:
raise MKCounterWrapped("Data not present at the moment")
return check_function(item, params, parsed[item])
return wrapped_check_function
def azure_iter_informative_attrs(resource, include_keys=('location',)):
def cap(string): # not quite what str.title() does
return string[0].upper() + string[1:]
for key in include_keys:
if key in resource:
yield cap(key), resource[key]
for key, value in sorted(resource.get('tags', {}).iteritems()):
if not key.startswith("hidden-"):
yield cap(key), value
def check_azure_metric( # pylint: disable=too-many-locals
resource,
metric_key,
cmk_key,
display_name,
levels=None,
levels_lower=None,
use_rate=False):
metric = resource.get('metrics', {}).get(metric_key)
if metric is None:
return None
if use_rate:
countername = "%s.%s" % (resource['id'], metric_key)
value = get_rate(countername, time.time(), metric.value)
unit = "%s_rate" % metric.unit
else:
value = metric.value
unit = metric.unit
if value is None:
return 3, "Metric %s is 'None'" % display_name, []
# convert to SI-unit
if unit == "milli_seconds":
value /= 1000.
elif unit == "seconds_rate":
# we got seconds, but we computed the rate -> seconds per second:
# how long happend something / time period = percent of the time
# e.g. CPU time: how much percent of of the time was the CPU busy.
value *= 100.
unit = "percent"
return check_levels(
value,
cmk_key,
(levels or (None, None)) + (levels_lower or (None, None)),
infoname=display_name,
human_readable_func=_AZURE_METRIC_FMT.get(unit, str),
boundaries=(0, None),
)
# .--Parse---------------------------------------------------------------.
# | ____ |
# | | _ \ __ _ _ __ ___ ___ |
# | | |_) / _` | '__/ __|/ _ \ |
# | | __/ (_| | | \__ \ __/ |
# | |_| \__,_|_| |___/\___| |
# | |
# '----------------------------------------------------------------------'
_AZURE_AGENT_SEPARATOR = '|'
Metric = collections.namedtuple(
"Metric", ["name", "aggregation", "value", "unit", "timestamp", "timegrain", "filters"])
def _read(row, types, defaults=None):
if defaults is None:
defaults = [None for __ in types]
if len(defaults) != len(types):
raise ValueError("expected %d default values" % len(types))
for i, (tfunc, default) in enumerate(zip(types, defaults)):
try:
raw = row[i]
yield tfunc(raw)
except (IndexError, ValueError):
yield default
def _parse_resource(info):
'''read resource json and parse metric lines
Metrics are stored in a dict. Key is name, prefixed by their aggregation,
spaces become underspcores:
Disk Read Bytes|average|0.0|...
is stored at
resource["metrics"]["average_Disk_Read_Bytes"]
'''
try:
resource = json.loads(_AZURE_AGENT_SEPARATOR.join(info[0]))
except (ValueError, IndexError):
return None
if len(info) < 3:
return resource
key, count = _read(info[1], (str, int), ("", 0))
if key != "metrics following":
return resource
for mline in info[2:2 + count]:
metric_dict = json.loads(_AZURE_AGENT_SEPARATOR.join(mline))
value = metric_dict['value']
if metric_dict['unit'] in ('count', 'bytes') and value is not None:
value = int(value)
key = "%s_%s" % (metric_dict['aggregation'], metric_dict['name'].replace(" ", "_"))
metr = Metric(metric_dict['name'], metric_dict['aggregation'], value, metric_dict['unit'],
metric_dict['timestamp'], metric_dict['interval_id'], metric_dict['filter'])
resource.setdefault('metrics', {})[key] = metr
return resource
def parse_azure(info):
raw_resources = []
# create list of lines per resource
for row in info:
if row == ["Resource"]:
raw_resources.append([])
continue
if raw_resources:
raw_resources[-1].append(row)
parsed_resources = (_parse_resource(r) for r in raw_resources)
return {r['name']: r for r in parsed_resources if r}
#.
# .--Discovery-----------------------------------------------------------.
# | ____ _ |
# | | _ \(_)___ ___ _____ _____ _ __ _ _ |
# | | | | | / __|/ __/ _ \ \ / / _ \ '__| | | | |
# | | |_| | \__ \ (_| (_) \ V / __/ | | |_| | |
# | |____/|_|___/\___\___/ \_/ \___|_| \__, | |
# | |___/ |
# +----------------------------------------------------------------------+
def discover_azure_by_metrics(*desired_metrics):
"""Return a discovery function, that will discover if any of the metrics are found"""
def discovery_function(parsed):
for name, resource in parsed.iteritems():
metr = resource.get('metrics', {})
if set(desired_metrics) & set(metr.keys()):
yield name, {}
return discovery_function
#.