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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
# -*- coding: utf-8 -*-
# Description: anomalies netdata python.d module
# Author: andrewm4894
# SPDX-License-Identifier: GPL-3.0-or-later
import time
from datetime import datetime
import re
import warnings
import requests
import numpy as np
import pandas as pd
from netdata_pandas.data import get_data, get_allmetrics_async
from pyod.models.hbos import HBOS
from pyod.models.pca import PCA
from pyod.models.loda import LODA
from pyod.models.iforest import IForest
from pyod.models.cblof import CBLOF
from pyod.models.feature_bagging import FeatureBagging
from pyod.models.copod import COPOD
from sklearn.preprocessing import MinMaxScaler
from bases.FrameworkServices.SimpleService import SimpleService
# ignore some sklearn/numpy warnings that are ok
warnings.filterwarnings('ignore', r'All-NaN slice encountered')
warnings.filterwarnings('ignore', r'invalid value encountered in true_divide')
warnings.filterwarnings('ignore', r'divide by zero encountered in true_divide')
warnings.filterwarnings('ignore', r'invalid value encountered in subtract')
disabled_by_default = True
ORDER = ['probability', 'anomaly']
CHARTS = {
'probability': {
'options': ['probability', 'Anomaly Probability', 'probability', 'anomalies', 'anomalies.probability', 'line'],
'lines': []
},
'anomaly': {
'options': ['anomaly', 'Anomaly', 'count', 'anomalies', 'anomalies.anomaly', 'stacked'],
'lines': []
},
}
class Service(SimpleService):
def __init__(self, configuration=None, name=None):
SimpleService.__init__(self, configuration=configuration, name=name)
self.basic_init()
self.charts_init()
self.custom_models_init()
self.model_params_init()
self.models_init()
def check(self):
_ = get_allmetrics_async(
host_charts_dict=self.host_charts_dict, host_prefix=True, host_sep='::', wide=True, sort_cols=True,
protocol=self.protocol, numeric_only=True, float_size='float32', user=self.username, pwd=self.password
)
return True
def basic_init(self):
"""Perform some basic initialization.
"""
self.order = ORDER
self.definitions = CHARTS
self.protocol = self.configuration.get('protocol', 'http')
self.host = self.configuration.get('host', '127.0.0.1:19999')
self.username = self.configuration.get('username', None)
self.password = self.configuration.get('password', None)
self.fitted_at = {}
self.df_allmetrics = pd.DataFrame()
self.data_latest = {}
self.last_train_at = 0
self.include_average_prob = bool(self.configuration.get('include_average_prob', True))
def charts_init(self):
"""Do some initialisation of charts in scope related variables.
"""
self.charts_regex = re.compile(self.configuration.get('charts_regex','None'))
self.charts_available = [c for c in list(requests.get(f'{self.protocol}://{self.host}/api/v1/charts').json().get('charts', {}).keys())]
self.charts_in_scope = list(filter(self.charts_regex.match, self.charts_available))
self.charts_to_exclude = self.configuration.get('charts_to_exclude', '').split(',')
if len(self.charts_to_exclude) > 0:
self.charts_in_scope = [c for c in self.charts_in_scope if c not in self.charts_to_exclude]
def custom_models_init(self):
"""Perform initialization steps related to custom models.
"""
self.custom_models = self.configuration.get('custom_models', None)
self.custom_models_normalize = bool(self.configuration.get('custom_models_normalize', False))
if self.custom_models:
self.custom_models_names = [model['name'] for model in self.custom_models]
self.custom_models_dims = [i for s in [model['dimensions'].split(',') for model in self.custom_models] for i in s]
self.custom_models_dims = [dim if '::' in dim else f'{self.host}::{dim}' for dim in self.custom_models_dims]
self.custom_models_charts = list(set([dim.split('|')[0].split('::')[1] for dim in self.custom_models_dims]))
self.custom_models_hosts = list(set([dim.split('::')[0] for dim in self.custom_models_dims]))
self.custom_models_host_charts_dict = {}
for host in self.custom_models_hosts:
self.custom_models_host_charts_dict[host] = list(set([dim.split('::')[1].split('|')[0] for dim in self.custom_models_dims if dim.startswith(host)]))
self.custom_models_dims_renamed = [f"{model['name']}|{dim}" for model in self.custom_models for dim in model['dimensions'].split(',')]
self.models_in_scope = list(set([f'{self.host}::{c}' for c in self.charts_in_scope] + self.custom_models_names))
self.charts_in_scope = list(set(self.charts_in_scope + self.custom_models_charts))
self.host_charts_dict = {self.host: self.charts_in_scope}
for host in self.custom_models_host_charts_dict:
if host not in self.host_charts_dict:
self.host_charts_dict[host] = self.custom_models_host_charts_dict[host]
else:
for chart in self.custom_models_host_charts_dict[host]:
if chart not in self.host_charts_dict[host]:
self.host_charts_dict[host].extend(chart)
else:
self.models_in_scope = [f'{self.host}::{c}' for c in self.charts_in_scope]
self.host_charts_dict = {self.host: self.charts_in_scope}
self.model_display_names = {model: model.split('::')[1] if '::' in model else model for model in self.models_in_scope}
def model_params_init(self):
"""Model paramaters initialisation.
"""
self.train_max_n = self.configuration.get('train_max_n', 100000)
self.train_n_secs = self.configuration.get('train_n_secs', 14400)
self.offset_n_secs = self.configuration.get('offset_n_secs', 0)
self.train_every_n = self.configuration.get('train_every_n', 1800)
self.train_no_prediction_n = self.configuration.get('train_no_prediction_n', 10)
self.initial_train_data_after = self.configuration.get('initial_train_data_after', 0)
self.initial_train_data_before = self.configuration.get('initial_train_data_before', 0)
self.contamination = self.configuration.get('contamination', 0.001)
self.lags_n = {model: self.configuration.get('lags_n', 5) for model in self.models_in_scope}
self.smooth_n = {model: self.configuration.get('smooth_n', 5) for model in self.models_in_scope}
self.diffs_n = {model: self.configuration.get('diffs_n', 5) for model in self.models_in_scope}
def models_init(self):
"""Models initialisation.
"""
self.model = self.configuration.get('model', 'pca')
if self.model == 'pca':
self.models = {model: PCA(contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'loda':
self.models = {model: LODA(contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'iforest':
self.models = {model: IForest(n_estimators=50, bootstrap=True, behaviour='new', contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'cblof':
self.models = {model: CBLOF(n_clusters=3, contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'feature_bagging':
self.models = {model: FeatureBagging(base_estimator=PCA(contamination=self.contamination), contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'copod':
self.models = {model: COPOD(contamination=self.contamination) for model in self.models_in_scope}
elif self.model == 'hbos':
self.models = {model: HBOS(
|