@cryptotaxi247 / netdata-1 / commits / 9dda12cf9

Anomalies collector (#10060)

ML based anomaly detection python collector built on top of PyOD.

Andrew Maguire committed Dec 2, 2020 at 20:45 UTC 9dda12cf92e847cb86527a1994a9fa5585e9fa8f
9 files changed +794
collectors/python.d.plugin/Makefile.am
+1
@@ -42,6 +42,7 @@ dist_pythonconfig_DATA = \
42 include adaptec_raid/Makefile.inc
43 include alarms/Makefile.inc
44 include am2320/Makefile.inc
45 +include anomalies/Makefile.inc
46 include apache/Makefile.inc
47 include beanstalk/Makefile.inc
48 include bind_rndc/Makefile.inc
collectors/python.d.plugin/anomalies/Makefile.inc new
+13
@@ -0,0 +1,13 @@
1 +# SPDX-License-Identifier: GPL-3.0-or-later
2 +
3 +# THIS IS NOT A COMPLETE Makefile
4 +# IT IS INCLUDED BY ITS PARENT'S Makefile.am
5 +# IT IS REQUIRED TO REFERENCE ALL FILES RELATIVE TO THE PARENT
6 +
7 +# install these files
8 +dist_python_DATA += anomalies/anomalies.chart.py
9 +dist_pythonconfig_DATA += anomalies/anomalies.conf
10 +
11 +# do not install these files, but include them in the distribution
12 +dist_noinst_DATA += anomalies/README.md anomalies/Makefile.inc
13 +
collectors/python.d.plugin/anomalies/README.md new
+225
@@ -0,0 +1,225 @@
1 +<!--
2 +title: "Anomalies"
3 +custom_edit_url: https://github.com/netdata/netdata/edit/master/collectors/python.d.plugin/anomalies/README.md
4 +-->
5 +
6 +# Anomalies: ML-driven anomaly detection for the Netdata Agent
7 +
8 +This collector uses the Python [PyOD](https://pyod.readthedocs.io/en/latest/index.html) library to perform unsupervised [anomaly detection](https://en.wikipedia.org/wiki/Anomaly_detection) on your Netdata charts and/or dimensions.
9 +
10 +Instead of this collector just _collecting_ data, it also does some computation on the data it collects to return an anomaly probability and anomaly flag for each chart or custom model you define. This computation consists of a **train** function that runs every `train_n_secs` to train the ML models to learn what 'normal' typically looks like on your node. At each iteration there is also a **predict** function that uses the latest trained models and most recent metrics to produce an anomaly probability and anomaly flag for each chart or custom model you define.
11 +
12 +## Charts
13 +
14 +Two charts are produced:
15 +
16 +- **Anomaly Probability** (`anomalies.probability`): This chart shows the probability that the latest observed data is anomalous based on the trained model for that chart (using the [`predict_proba()`](https://pyod.readthedocs.io/en/latest/api_cc.html#pyod.models.base.BaseDetector.predict_proba) method of the trained PyOD model).
17 +- **Anomaly** (`anomalies.anomaly`): This chart shows `1` or `0` predictions of if the latest observed data is considered anomalous or not based on the trained model (using the [`predict()`](https://pyod.readthedocs.io/en/latest/api_cc.html#pyod.models.base.BaseDetector.predict) method of the trained PyOD model).
18 +
19 +Below is an example of the charts produced by this collector and how they might look when things are 'normal' on the node. The anomaly probabilities tend to bounce randomly around a typically low probability range, one or two might randomly jump or drift outside of this range every now and then and show up as anomalies on the anomaly chart.
20 +
21 +![netdata-anomalies-collector-normal](https://user-images.githubusercontent.com/2178292/100663699-99755000-334e-11eb-922f-0c41a0176484.jpg)
22 +
23 +If we then go onto the system and run a command like `stress-ng --all 2` to create some [stress](https://wiki.ubuntu.com/Kernel/Reference/stress-ng), we see some charts begin to have anomaly probabilities that jump outside the typical range. When the anomaly probabilities change enough, we will start seeing anomalies being flagged on the `anomalies.anomaly` chart. The idea is that these charts are the most anomalous right now so could be a good place to start your troubleshooting.
24 +
25 +![netdata-anomalies-collector-abnormal](https://user-images.githubusercontent.com/2178292/100663710-9bd7aa00-334e-11eb-9d14-76fda73bc309.jpg)
26 +
27 +Then, as the issue passes, the anomaly probabilities should settle back down into their 'normal' range again.
28 +
29 +![netdata-anomalies-collector-normal-again](https://user-images.githubusercontent.com/2178292/100666681-481a9000-3351-11eb-9979-64728ee2dfb6.jpg)
30 +
31 +## Requirements
32 +
33 +- This collector will only work with Python 3 and requires the packages below be installed.
34 +
35 +```bash
36 +# become netdata user
37 +sudo su -s /bin/bash netdata
38 +# install required packages for the netdata user
39 +pip3 install --user netdata-pandas==0.0.32 numba==0.50.1 scikit-learn==0.23.2 pyod==0.8.3
40 +```
41 +
42 +## Configuration
43 +
44 +Install the Python requirements above, enable the collector and restart Netdata.
45 +
46 +```bash
47 +cd /etc/netdata/
48 +sudo ./edit-config python.d.conf
49 +# Set `anomalies: no` to `anomalies: yes`
50 +sudo systemctl restart netdata
51 +```
52 +
53 +The configuration for the anomalies collector defines how it will behave on your system and might take some experimentation with over time to set it optimally for your node. Out of the box, the config comes with some [sane defaults](https://www.netdata.cloud/blog/redefining-monitoring-netdata/) to get you started that try to balance the flexibility and power of the ML models with the goal of being as cheap as possible in term of cost on the node resources.
54 +
55 +_**Note**: If you are unsure about any of the below configuration options then it's best to just ignore all this and leave the `anomalies.conf` file alone to begin with. Then you can return to it later if you would like to tune things a bit more once the collector is running for a while and you have a feeling for its performance on your node._
56 +
57 +Edit the `python.d/anomalies.conf` configuration file using `edit-config` from the your agent's [config
58 +directory](/docs/configure/nodes.md), which is usually at `/etc/netdata`.
59 +
60 +```bash
61 +cd /etc/netdata # Replace this path with your Netdata config directory, if different
62 +sudo ./edit-config python.d/anomalies.conf
63 +```
64 +
65 +The default configuration should look something like this. Here you can see each parameter (with sane defaults) and some information about each one and what it does.
66 +
67 +```yaml
68 +# ----------------------------------------------------------------------
69 +# JOBS (data collection sources)
70 +
71 +# Pull data from local Netdata node.
72 +local:
73 + name: 'local'
74 +
75 + # Host to pull data from.
76 + host: '127.0.0.1:19999'
77 +
78 + # Username and Password for Netdata if using basic auth.
79 + # username: '???'
80 + # password: '???'
81 +
82 + # Use http or https to pull data
83 + protocol: 'http'
84 +
85 + # What charts to pull data for - A regex like 'system\..*|' or 'system\..*|apps.cpu|apps.mem' etc.
86 + charts_regex: 'system\..*'
87 +
88 + # Charts to exclude, useful if you would like to exclude some specific charts.
89 + # Note: should be a ',' separated string like 'chart.name,chart.name'.
90 + charts_to_exclude: 'system.uptime,system.entropy'
91 +
92 + # What model to use - can be one of 'pca', 'hbos', 'iforest', 'cblof', 'loda', 'copod' or 'feature_bagging'.
93 + # More details here: https://pyod.readthedocs.io/en/latest/pyod.models.html.
94 + model: 'pca'
95 +
96 + # Max number of observations to train on, to help cap compute cost of training model if you set a very large train_n_secs.
97 + train_max_n: 100000
98 +
99 + # How often to re-train the model (assuming update_every=1 then train_every_n=1800 represents (re)training every 30 minutes).
100 + # Note: If you want to turn off re-training set train_every_n=0 and after initial training the models will not be retrained.
101 + train_every_n: 1800
102 +
103 + # The length of the window of data to train on (14400 = last 4 hours).
104 + train_n_secs: 14400
105 +
106 + # How many prediction steps after a train event to just use previous prediction value for.
107 + # Used to reduce possibility of the training step itself appearing as an anomaly on the charts.
108 + train_no_prediction_n: 10
109 +
110 + # If you would like to train the model for the first time on a specific window then you can define it using the below two variables.
111 + # Start of training data for initial model.
112 + # initial_train_data_after: 1604578857
113 +
114 + # End of training data for initial model.
115 + # initial_train_data_before: 1604593257
116 +
117 + # If you would like to ignore recent data in training then you can offset it by offset_n_secs.
118 + offset_n_secs: 0
119 +
120 + # How many lagged values of each dimension to include in the 'feature vector' each model is trained on.
121 + lags_n: 5
122 +
123 + # How much smoothing to apply to each dimension in the 'feature vector' each model is trained on.
124 + smooth_n: 3
125 +
126 + # How many differences to take in preprocessing your data.
127 + # More info on differencing here: https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average#Differencing
128 + # diffs_n=0 would mean training models on the raw values of each dimension.
129 + # diffs_n=1 means everything is done in terms of differences.
130 + diffs_n: 1
131 +
132 + # What is the typical proportion of anomalies in your data on average?
133 + # This paramater can control the sensitivity of your models to anomalies.
134 + # Some discussion here: https://github.com/yzhao062/pyod/issues/144
135 + contamination: 0.001
136 +
137 + # Set to true to include an "average_prob" dimension on anomalies probability chart which is
138 + # just the average of all anomaly probabilities at each time step
139 + include_average_prob: true
140 +
141 + # Define any custom models you would like to create anomaly probabilties for, some examples below to show how.
142 + # For example below example creates two custom models, one to run anomaly detection user and system cpu for our demo servers
143 + # and one on the cpu and mem apps metrics for the python.d.plugin.
144 + # custom_models:
145 + # - name: 'demos_cpu'
146 + # dimensions: 'london.my-netdata.io::system.cpu|user,london.my-netdata.io::system.cpu|system,newyork.my-netdata.io::system.cpu|user,newyork.my-netdata.io::system.cpu|system'
147 + # - name: 'apps_python_d_plugin'
148 + # dimensions: 'apps.cpu|python.d.plugin,apps.mem|python.d.plugin'
149 +
150 + # Set to true to normalize, using min-max standardization, features used for the custom models.
151 + # Useful if your custom models contain dimensions on very different scales an model you use does
152 + # not internally do its own normalization. Usually best to leave as false.
153 + # custom_models_normalize: false
154 +```
155 +
156 +## Custom models
157 +
158 +In the `anomalies.conf` file you can also define some "custom models" which you can use to group one or more metrics into a single model much like is done by default for the charts you specify. This is useful if you have a handful of metrics that exist in different charts but perhaps are related to the same underlying thing you would like to perform anomaly detection on, for example a specific app or user.
159 +
160 +To define a custom model you would include configuation like below in `anomalies.conf`. By default there should already be some commented out examples in there.
161 +
162 +`name` is a name you give your custom model, this is what will appear alongside any other specified charts in the `anomalies.probability` and `anomalies.anomaly` charts. `dimensions` is a string of metrics you want to include in your custom model. By default the [netdata-pandas](https://github.com/netdata/netdata-pandas) library used to pull the data from Netdata uses a "chart.a|dim.1" type of naming convention in the pandas columns it returns, hence the `dimensions` string should look like "chart.name|dimension.name,chart.name|dimension.name". The examples below hopefully make this clear.
163 +
164 +```yaml
165 +custom_models:
166 + # a model for anomaly detection on the netdata user in terms of cpu, mem, threads, processes and sockets.
167 + - name: 'user_netdata'
168 + dimensions: 'users.cpu|netdata,users.mem|netdata,users.threads|netdata,users.processes|netdata,users.sockets|netdata'
169 + # a model for anomaly detection on the netdata python.d.plugin app in terms of cpu, mem, threads, processes and sockets.
170 + - name: 'apps_python_d_plugin'
171 + dimensions: 'apps.cpu|python.d.plugin,apps.mem|python.d.plugin,apps.threads|python.d.plugin,apps.processes|python.d.plugin,apps.sockets|python.d.plugin'
172 +
173 +custom_models_normalize: false
174 +```
175 +
176 +## Troubleshooting
177 +
178 +To see any relevant log messages you can use a command like below.
179 +
180 +```bash
181 +`grep 'anomalies' /var/log/netdata/error.log`
182 +```
183 +
184 +If you would like to log in as `netdata` user and run the collector in debug mode to see more detail.
185 +
186 +```bash
187 +# become netdata user
188 +sudo su -s /bin/bash netdata
189 +# run collector in debug using `nolock` option if netdata is already running the collector itself.
190 +/usr/libexec/netdata/plugins.d/python.d.plugin anomalies debug trace nolock
191 +```
192 +
193 +## Deepdive turorial
194 +
195 +If you would like to go deeper on what exactly the anomalies collector is doing under the hood then check out this [deepdive tutorial](https://github.com/netdata/community/blob/main/netdata-agent-api/netdata-pandas/anomalies_collector_deepdive.ipynb) in our community repo where you can play around with some data from our demo servers (or your own if its accessible to you) and work through the calculations step by step.
196 +
197 +(Note: as its a Jupyter Notebook it might render a little prettier on [nbviewer](https://nbviewer.jupyter.org/github/netdata/community/blob/main/netdata-agent-api/netdata-pandas/anomalies_collector_deepdive.ipynb))
198 +
199 +## Notes
200 +
201 +- Python 3 is required as the [`netdata-pandas`](https://github.com/netdata/netdata-pandas) package uses Python async libraries ([asks](https://pypi.org/project/asks/) and [trio](https://pypi.org/project/trio/)) to make asynchronous calls to the [Netdata REST API](https://learn.netdata.cloud/docs/agent/web/api) to get the required data for each chart.
202 +- Python 3 is also required for the underlying ML libraries of [numba](https://pypi.org/project/numba/), [scikit-learn](https://pypi.org/project/scikit-learn/), and [PyOD](https://pypi.org/project/pyod/).
203 +- It may take a few hours or so (depending on your choice of `train_secs_n`) for the collector to 'settle' into it's typical behaviour in terms of the trained models and probabilities you will see in the normal running of your node.
204 +- As this collector does most of the work in Python itself, with [PyOD](https://pyod.readthedocs.io/en/latest/) leveraging [numba](https://numba.pydata.org/) under the hood, you may want to try it out first on a test or development system to get a sense of its performance characteristics on a node similar to where you would like to use it.
205 +- `lags_n`, `smooth_n`, and `diffs_n` together define the preprocessing done to the raw data before models are trained and before each prediction. This essentially creates a [feature vector](https://en.wikipedia.org/wiki/Feature_(machine_learning)#:~:text=In%20pattern%20recognition%20and%20machine,features%20that%20represent%20some%20object.&text=Feature%20vectors%20are%20often%20combined,score%20for%20making%20a%20prediction.) for each chart model (or each custom model). The default settings for these parameters aim to create a rolling matrix of recent smoothed [differenced](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average#Differencing) values for each chart. The aim of the model then is to score how unusual this 'matrix' of features is for each chart based on what it has learned as 'normal' from the training data. So as opposed to just looking at the single most recent value of a dimension and considering how strange it is, this approach looks at a recent smoothed window of all dimensions for a chart (or dimensions in a custom model) and asks how unusual the data as a whole looks. This should be more flexibile in capturing a wider range of [anomaly types](https://andrewm4894.com/2020/10/19/different-types-of-time-series-anomalies/) and be somewhat more robust to temporary 'spikes' in the data that tend to always be happening somewhere in your metrics but often are not the most important type of anomaly (this is all covered in a lot more detail in the [deepdive tutorial](https://nbviewer.jupyter.org/github/netdata/community/blob/main/netdata-agent-api/netdata-pandas/anomalies_collector_deepdive.ipynb)).
206 +- You can see how long model training is taking by looking in the logs for the collector `grep 'anomalies' /var/log/netdata/error.log | grep 'training'` and you should see lines like `2020-12-01 22:02:14: python.d INFO: anomalies[local] : training complete in 2.81 seconds (runs_counter=2700, model=pca, train_n_secs=14400, models=26, n_fit_success=26, n_fit_fails=0, after=1606845731, before=1606860131).`.
207 + - This also gives counts of the number of models, if any, that failed to fit and so had to default back to the DefaultModel (which is currently [HBOS](https://pyod.readthedocs.io/en/latest/_modules/pyod/models/hbos.html)).
208 + - `after` and `before` here refer to the start and end of the training data used to train the models.
209 +- On a development n1-standard-2 (2 vCPUs, 7.5 GB memory) vm running Ubuntu 18.04 LTS and not doing any work some of the typical performance characteristics we saw from running this collector (with defaults) were:
210 + - A runtime (`netdata.runtime_anomalies`) of ~80ms when doing scoring and ~3 seconds when training or retraining the models.
211 + - Typically ~3%-3.5% additional cpu usage from scoring, jumping to ~60% for a couple of seconds during model training.
212 + - About ~150mb of ram (`apps.mem`) being continually used by the `python.d.plugin`.
213 +- If you activate this collector on a fresh node, it might take a little while to build up enough data to calculate a realistic and useful model.
214 +- Some models like `iforest` can be comparatively expensive (on same n1-standard-2 system above ~2s runtime during predict, ~40s training time, ~50% cpu on both train and predict) so if you would like to use it you might be advised to set a relativley high `update_every` maybe 10, 15 or 30 in `anomalies.conf`.
215 +- Setting a higher `train_every_n` and `update_every` is an easy way to devote less resources on the node to anomaly detection. Specifying less charts and a lower `train_n_secs` will also help reduce resources at the expense of covering less charts and maybe a more noisey model if you set `train_n_secs` to be too small for how your node tends to behave.
216 +
217 +## Useful links and further reading
218 +
219 +- [PyOD documentation](https://pyod.readthedocs.io/en/latest/), [PyOD Github](https://github.com/yzhao062/pyod).
220 +- [Anomaly Detection](https://en.wikipedia.org/wiki/Anomaly_detection) wikipedia page.
221 +- [Anomaly Detection YouTube playlist](https://www.youtube.com/playlist?list=PL6Zhl9mK2r0KxA6rB87oi4kWzoqGd5vp0) maintained by [andrewm4894](https://github.com/andrewm4894/) from Netdata.
222 +- [awesome-TS-anomaly-detection](https://github.com/rob-med/awesome-TS-anomaly-detection) Github list of useful tools, libraries and resources.
223 +- [Mendeley public group](https://www.mendeley.com/community/interesting-anomaly-detection-papers/) with some interesting anomaly detection papers we have been reading.
224 +- Good [blog post](https://www.anodot.com/blog/what-is-anomaly-detection/) from Anodot on time series anomaly detection. Anodot also have some great whitepapers in this space too that some may find useful.
225 +- Novelty and outlier detection in the [scikit-learn documentation](https://scikit-learn.org/stable/modules/outlier_detection.html).
collectors/python.d.plugin/anomalies/anomalies.chart.py new
+349
@@ -0,0 +1,349 @@
1 +# -*- coding: utf-8 -*-
2 +# Description: anomalies netdata python.d module
3 +# Author: andrewm4894
4 +# SPDX-License-Identifier: GPL-3.0-or-later
5 +
6 +import time
7 +from datetime import datetime
8 +import re
9 +import warnings
10 +
11 +import requests
12 +import numpy as np
13 +import pandas as pd
14 +from netdata_pandas.data import get_data, get_allmetrics_async
15 +from pyod.models.hbos import HBOS
16 +from pyod.models.pca import PCA
17 +from pyod.models.loda import LODA
18 +from pyod.models.iforest import IForest
19 +from pyod.models.cblof import CBLOF
20 +from pyod.models.feature_bagging import FeatureBagging
21 +from pyod.models.copod import COPOD
22 +from sklearn.preprocessing import MinMaxScaler
23 +
24 +from bases.FrameworkServices.SimpleService import SimpleService
25 +
26 +# ignore some sklearn/numpy warnings that are ok
27 +warnings.filterwarnings('ignore', r'All-NaN slice encountered')
28 +warnings.filterwarnings('ignore', r'invalid value encountered in true_divide')
29 +
30 +disabled_by_default = True
31 +
32 +ORDER = ['probability', 'anomaly']
33 +
34 +CHARTS = {
35 + 'probability': {
36 + 'options': ['probability', 'Anomaly Probability', 'probability', 'anomalies', 'anomalies.probability', 'line'],
37 + 'lines': []
38 + },
39 + 'anomaly': {
40 + 'options': ['anomaly', 'Anomaly', 'count', 'anomalies', 'anomalies.anomaly', 'stacked'],
41 + 'lines': []
42 + },
43 +}
44 +
45 +
46 +class Service(SimpleService):
47 + def __init__(self, configuration=None, name=None):
48 + SimpleService.__init__(self, configuration=configuration, name=name)
49 + self.basic_init()
50 + self.charts_init()
51 + self.custom_models_init()
52 + self.model_params_init()
53 + self.models_init()
54 +
55 + def check(self):
56 + _ = get_allmetrics_async(
57 + host_charts_dict=self.host_charts_dict, host_prefix=True, host_sep='::', wide=True, sort_cols=True,
58 + protocol=self.protocol, numeric_only=True, float_size='float32', user=self.username, pwd=self.password
59 + )
60 + return True
61 +
62 + def basic_init(self):
63 + """Perform some basic initialization.
64 + """
65 + self.order = ORDER
66 + self.definitions = CHARTS
67 + self.protocol = self.configuration.get('protocol', 'http')
68 + self.host = self.configuration.get('host', '127.0.0.1:19999')
69 + self.username = self.configuration.get('username', None)
70 + self.password = self.configuration.get('password', None)
71 + self.fitted_at = {}
72 + self.df_allmetrics = pd.DataFrame()
73 + self.data_latest = {}
74 + self.expected_cols = []
75 + self.last_train_at = 0
76 + self.include_average_prob = bool(self.configuration.get('include_average_prob', True))
77 +
78 + def charts_init(self):
79 + """Do some initialisation of charts in scope related variables.
80 + """
81 + self.charts_regex = re.compile(self.configuration.get('charts_regex','None'))
82 + self.charts_available = [c for c in list(requests.get(f'{self.protocol}://{self.host}/api/v1/charts').json().get('charts', {}).keys())]
83 + self.charts_in_scope = list(filter(self.charts_regex.match, self.charts_available))
84 + self.charts_to_exclude = self.configuration.get('charts_to_exclude', '').split(',')
85 + if len(self.charts_to_exclude) > 0:
86 + self.charts_in_scope = [c for c in self.charts_in_scope if c not in self.charts_to_exclude]
87 +
88 + def custom_models_init(self):
89 + """Perform initialization steps related to custom models.
90 + """
91 + self.custom_models = self.configuration.get('custom_models', None)
92 + self.custom_models_normalize = bool(self.configuration.get('custom_models_normalize', False))
93 + if self.custom_models:
94 + self.custom_models_names = [model['name'] for model in self.custom_models]
95 + self.custom_models_dims = [i for s in [model['dimensions'].split(',') for model in self.custom_models] for i in s]
96 + self.custom_models_dims = [dim if '::' in dim else f'{self.host}::{dim}' for dim in self.custom_models_dims]
97 + self.custom_models_charts = list(set([dim.split('|')[0].split('::')[1] for dim in self.custom_models_dims]))
98 + self.custom_models_hosts = list(set([dim.split('::')[0] for dim in self.custom_models_dims]))
99 + self.custom_models_host_charts_dict = {}
100 + for host in self.custom_models_hosts:
101 + 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)]))
102 + self.custom_models_dims_renamed = [f"{model['name']}.{dim}" for model in self.custom_models for dim in model['dimensions'].split(',')]
103 + self.models_in_scope = list(set([f'{self.host}::{c}' for c in self.charts_in_scope] + self.custom_models_names))
104 + self.charts_in_scope = list(set(self.charts_in_scope + self.custom_models_charts))
105 + self.host_charts_dict = {self.host: self.charts_in_scope}
106 + for host in self.custom_models_host_charts_dict:
107 + if host not in self.host_charts_dict:
108 + self.host_charts_dict[host] = self.custom_models_host_charts_dict[host]
109 + else:
110 + for chart in self.custom_models_host_charts_dict[host]:
111 + if chart not in self.host_charts_dict[host]:
112 + self.host_charts_dict[host].extend(chart)
113 + else:
114 + self.models_in_scope = [f'{self.host}::{c}' for c in self.charts_in_scope]
115 + self.host_charts_dict = {self.host: self.charts_in_scope}
116 + self.model_display_names = {model: model.split('::')[1] if '::' in model else model for model in self.models_in_scope}
117 +
118 + def model_params_init(self):
119 + """Model paramaters initialisation.
120 + """
121 + self.train_max_n = self.configuration.get('train_max_n', 100000)
122 + self.train_n_secs = self.configuration.get('train_n_secs', 14400)
123 + self.offset_n_secs = self.configuration.get('offset_n_secs', 0)
124 + self.train_every_n = self.configuration.get('train_every_n', 1800)
125 + self.train_no_prediction_n = self.configuration.get('train_no_prediction_n', 10)
126 + self.initial_train_data_after = self.configuration.get('initial_train_data_after', 0)
127 + self.initial_train_data_before = self.configuration.get('initial_train_data_before', 0)
128 + self.contamination = self.configuration.get('contamination', 0.001)
129 + self.lags_n = {model: self.configuration.get('lags_n', 5) for model in self.models_in_scope}
130 + self.smooth_n = {model: self.configuration.get('smooth_n', 5) for model in self.models_in_scope}
131 + self.diffs_n = {model: self.configuration.get('diffs_n', 5) for model in self.models_in_scope}
132 +
133 + def models_init(self):
134 + """Models initialisation.
135 + """
136 + self.model = self.configuration.get('model', 'pca')
137 + if self.model == 'pca':
138 + self.models = {model: PCA(contamination=self.contamination) for model in self.models_in_scope}
139 + elif self.model == 'loda':
140 + self.models = {model: LODA(contamination=self.contamination) for model in self.models_in_scope}
141 + elif self.model == 'iforest':
142 + self.models = {model: IForest(n_estimators=50, bootstrap=True, behaviour='new', contamination=self.contamination) for model in self.models_in_scope}
143 + elif self.model == 'cblof':
144 + self.models = {model: CBLOF(n_clusters=3, contamination=self.contamination) for model in self.models_in_scope}
145 + elif self.model == 'feature_bagging':
146 + self.models = {model: FeatureBagging(base_estimator=PCA(contamination=self.contamination), contamination=self.contamination) for model in self.models_in_scope}
147 + elif self.model == 'copod':
148 + self.models = {model: COPOD(contamination=self.contamination) for model in self.models_in_scope}
149 + elif self.model == 'hbos':
150 + self.models = {model: HBOS(contamination=self.contamination) for model in self.models_in_scope}
151 + else:
152 + self.models = {model: HBOS(contamination=self.contamination) for model in self.models_in_scope}
153 + self.custom_model_scalers = {model: MinMaxScaler() for model in self.models_in_scope}
154 +
155 + def validate_charts(self, name, data, algorithm='absolute', multiplier=1, divisor=1):
156 + """If dimension not in chart then add it.
157 + """
158 + for dim in data:
159 + if dim not in self.charts[name]:
160 + self.charts[name].add_dimension([dim, dim, algorithm, multiplier, divisor])
161 +
162 + def add_custom_models_dims(self, df):
163 + """Given a df, select columns used by custom models, add custom model name as prefix, and append to df.
164 +
165 + :param df <pd.DataFrame>: dataframe to append new renamed columns to.
166 + :return: <pd.DataFrame> dataframe with additional columns added relating to the specified custom models.
167 + """
168 + df_custom = df[self.custom_models_dims].copy()
169 + df_custom.columns = self.custom_models_dims_renamed
170 + df = df.join(df_custom)
171 +
172 + return df
173 +
174 + def make_features(self, arr, train=False, model=None):
175 + """Take in numpy array and preprocess accordingly by taking diffs, smoothing and adding lags.
176 +
177 + :param arr <np.ndarray>: numpy array we want to make features from.
178 + :param train <bool>: True if making features for training, in which case need to fit_transform scaler and maybe sample train_max_n.
179 + :param model <str>: model to make features for.
180 + :return: <np.ndarray> transformed numpy array.
181 + """
182 +
183 + def lag(arr, n):
184 + res = np.empty_like(arr)
185 + res[:n] = np.nan
186 + res[n:] = arr[:-n]
187 +
188 + return res
189 +
190 + arr = np.nan_to_num(arr)
191 +
192 + diffs_n = self.diffs_n[model]
193 + smooth_n = self.smooth_n[model]
194 + lags_n = self.lags_n[model]
195 +
196 + if self.custom_models_normalize and model in self.custom_models_names:
197 + if train:
198 + arr = self.custom_model_scalers[model].fit_transform(arr)
199 + else:
200 + arr = self.custom_model_scalers[model].transform(arr)
201 +
202 + if diffs_n > 0:
203 + arr = np.diff(arr, diffs_n, axis=0)
204 + arr = arr[~np.isnan(arr).any(axis=1)]
205 +
206 + if smooth_n > 1:
207 + arr = np.cumsum(arr, axis=0, dtype=float)
208 + arr[smooth_n:] = arr[smooth_n:] - arr[:-smooth_n]
209 + arr = arr[smooth_n - 1:] / smooth_n
210 + arr = arr[~np.isnan(arr).any(axis=1)]
211 +
212 + if lags_n > 0:
213 + arr_orig = np.copy(arr)
214 + for lag_n in range(1, lags_n + 1):
215 + arr = np.concatenate((arr, lag(arr_orig, lag_n)), axis=1)
216 + arr = arr[~np.isnan(arr).any(axis=1)]
217 +
218 + if train:
219 + if len(arr) > self.train_max_n:
220 + arr = arr[np.random.randint(arr.shape[0], size=self.train_max_n), :]
221 +
222 + arr = np.nan_to_num(arr)
223 +
224 + return arr
225 +
226 + def train(self, models_to_train=None, train_data_after=0, train_data_before=0):
227 + """Pull required training data and train a model for each specified model.
228 +
229 + :param models_to_train <list>: list of models to train on.
230 + :param train_data_after <int>: integer timestamp for start of train data.
231 + :param train_data_before <int>: integer timestamp for end of train data.
232 + """
233 + now = datetime.now().timestamp()
234 + if train_data_after > 0 and train_data_before > 0:
235 + before = train_data_before
236 + after = train_data_after
237 + else:
238 + before = int(now) - self.offset_n_secs
239 + after = before - self.train_n_secs
240 +
241 + # get training data
242 + df_train = get_data(
243 + host_charts_dict=self.host_charts_dict, host_prefix=True, host_sep='::', after=after, before=before,
244 + sort_cols=True, numeric_only=True, protocol=self.protocol, float_size='float32', user=self.username, pwd=self.password
245 + ).ffill()
246 + self.expected_cols = list(df_train.columns)
247 + if self.custom_models:
248 + df_train = self.add_custom_models_dims(df_train)
249 +
250 + # train model
251 + self.try_fit(df_train, models_to_train=models_to_train)
252 + self.info(f'training complete in {round(time.time() - now, 2)} seconds (runs_counter={self.runs_counter}, model={self.model}, train_n_secs={self.train_n_secs}, models={len(self.fitted_at)}, n_fit_success={self.n_fit_success}, n_fit_fails={self.n_fit_fail}, after={after}, before={before}).')
253 + self.last_train_at = self.runs_counter
254 +
255 + def try_fit(self, df_train, models_to_train=None):
256 + """Try fit each model and try to fallback to a default model if fit fails for any reason.
257 +
258 + :param df_train <pd.DataFrame>: data to train on.
259 + :param models_to_train <list>: list of models to train.
260 + """
261 + if models_to_train is None:
262 + models_to_train = list(self.models.keys())
263 + self.n_fit_fail, self.n_fit_success = 0, 0
264 + for model in models_to_train:
265 + X_train = self.make_features(
266 + df_train[df_train.columns[df_train.columns.str.startswith(f'{model}|')]].values,
267 + train=True, model=model)
268 + try:
269 + self.models[model].fit(X_train)
270 + self.n_fit_success += 1
271 + except Exception as e:
272 + self.n_fit_fail += 1
273 + self.info(e)
274 + self.info(f'training failed for {model} at run_counter {self.runs_counter}, defaulting to hbos model.')
275 + self.models[model] = HBOS(contamination=self.contamination)
276 + self.models[model].fit(X_train)
277 + self.fitted_at[model] = self.runs_counter
278 +
279 + def predict(self):
280 + """Get latest data, make it into a feature vector, and get predictions for each available model.
281 +
282 + :return: (<dict>,<dict>) tuple of dictionaries, one for probability scores and the other for anomaly predictions.
283 + """
284 + # get recent data to predict on
285 + df_allmetrics = get_allmetrics_async(
286 + host_charts_dict=self.host_charts_dict, host_prefix=True, host_sep='::', wide=True, sort_cols=True,
287 + protocol=self.protocol, numeric_only=True, float_size='float32', user=self.username, pwd=self.password
288 + )[self.expected_cols]
289 + if self.custom_models:
290 + df_allmetrics = self.add_custom_models_dims(df_allmetrics)
291 + self.df_allmetrics = self.df_allmetrics.append(df_allmetrics).ffill().tail((max(self.lags_n.values()) + max(self.smooth_n.values()) + max(self.diffs_n.values())) * 2)
292 +
293 + # get predictions
294 + data_probability, data_anomaly = self.try_predict()
295 +
296 + return data_probability, data_anomaly
297 +
298 + def try_predict(self):
299 + """Try make prediction and fall back to last known prediction if fails.
300 +
301 + :return: (<dict>,<dict>) tuple of dictionaries, one for probability scores and the other for anomaly predictions.
302 + """
303 + data_probability, data_anomaly = {}, {}
304 + for model in self.fitted_at.keys():
305 + model_display_name = self.model_display_names[model]
306 + X_model = np.nan_to_num(self.make_features(
307 + self.df_allmetrics[self.df_allmetrics.columns[self.df_allmetrics.columns.str.startswith(f'{model}|')]].values,
308 + model=model)[-1,:].reshape(1, -1))
309 + try:
310 + data_probability[model_display_name + '_prob'] = np.nan_to_num(self.models[model].predict_proba(X_model)[-1][1]) * 10000
311 + data_anomaly[model_display_name + '_anomaly'] = self.models[model].predict(X_model)[-1]
312 + except Exception:
313 + #self.info(e)
314 + if model_display_name + '_prob' in self.data_latest:
315 + #self.info(f'prediction failed for {model} at run_counter {self.runs_counter}, using last prediction instead.')
316 + data_probability[model_display_name + '_prob'] = self.data_latest[model_display_name + '_prob']
317 + data_anomaly[model_display_name + '_anomaly'] = self.data_latest[model_display_name + '_anomaly']
318 + else:
319 + #self.info(f'prediction failed for {model} at run_counter {self.runs_counter}, skipping as no previous prediction.')
320 + continue
321 +
322 + return data_probability, data_anomaly
323 +
324 + def get_data(self):
325 +
326 + # if not all models have been trained then train those we need to
327 + if len(self.fitted_at) < len(self.models):
328 + self.train(
329 + models_to_train=[m for m in self.models if m not in self.fitted_at],
330 + train_data_after=self.initial_train_data_after,
331 + train_data_before=self.initial_train_data_before)
332 + # retrain all models as per schedule from config
333 + elif self.train_every_n > 0 and self.runs_counter % self.train_every_n == 0:
334 + self.train()
335 +
336 + # roll forward previous predictions around a training step to avoid the possibility of having the training itself trigger an anomaly
337 + if (self.runs_counter - self.last_train_at) <= self.train_no_prediction_n:
338 + data = self.data_latest
339 + else:
340 + data_probability, data_anomaly = self.predict()
341 + if self.include_average_prob:
342 + data_probability['average_prob'] = np.mean(list(data_probability.values()))
343 + data = {**data_probability, **data_anomaly}
344 + self.validate_charts('probability', data_probability, divisor=100)
345 + self.validate_charts('anomaly', data_anomaly)
346 +
347 + self.data_latest = data
348 +
349 + return data
collectors/python.d.plugin/anomalies/anomalies.conf new
+181
@@ -0,0 +1,181 @@
1 +# netdata python.d.plugin configuration for anomalies
2 +#
3 +# This file is in YaML format. Generally the format is:
4 +#
5 +# name: value
6 +#
7 +# There are 2 sections:
8 +# - global variables
9 +# - one or more JOBS
10 +#
11 +# JOBS allow you to collect values from multiple sources.
12 +# Each source will have its own set of charts.
13 +#
14 +# JOB parameters have to be indented (using spaces only, example below).
15 +
16 +# ----------------------------------------------------------------------
17 +# Global Variables
18 +# These variables set the defaults for all JOBs, however each JOB
19 +# may define its own, overriding the defaults.
20 +
21 +# update_every sets the default data collection frequency.
22 +# If unset, the python.d.plugin default is used.
23 +# update_every: 2
24 +
25 +# priority controls the order of charts at the netdata dashboard.
26 +# Lower numbers move the charts towards the top of the page.
27 +# If unset, the default for python.d.plugin is used.
28 +# priority: 60000
29 +
30 +# ----------------------------------------------------------------------
31 +# JOBS (data collection sources)
32 +
33 +# Pull data from local Netdata node.
34 +local:
35 + name: 'local'
36 +
37 + # Host to pull data from.
38 + host: '127.0.0.1:19999'
39 +
40 + # Username and Password for Netdata if using basic auth.
41 + # username: '???'
42 + # password: '???'
43 +
44 + # Use http or https to pull data
45 + protocol: 'http'
46 +
47 + # What charts to pull data for - A regex like 'system\..*|' or 'system\..*|apps.cpu|apps.mem' etc.
48 + charts_regex: 'system\..*'
49 +
50 + # Charts to exclude, useful if you would like to exclude some specific charts.
51 + # Note: should be a ',' separated string like 'chart.name,chart.name'.
52 + charts_to_exclude: 'system.uptime,system.entropy'
53 +
54 + # What model to use - can be one of 'pca', 'hbos', 'iforest', 'cblof', 'loda', 'copod' or 'feature_bagging'.
55 + # More details here: https://pyod.readthedocs.io/en/latest/pyod.models.html.
56 + model: 'pca'
57 +
58 + # Max number of observations to train on, to help cap compute cost of training model if you set a very large train_n_secs.
59 + train_max_n: 100000
60 +
61 + # How often to re-train the model (assuming update_every=1 then train_every_n=1800 represents (re)training every 30 minutes).
62 + # Note: If you want to turn off re-training set train_every_n=0 and after initial training the models will not be retrained.
63 + train_every_n: 1800
64 +
65 + # The length of the window of data to train on (14400 = last 4 hours).
66 + train_n_secs: 14400
67 +
68 + # How many prediction steps after a train event to just use previous prediction value for.
69 + # Used to reduce possibility of the training step itself appearing as an anomaly on the charts.
70 + train_no_prediction_n: 10
71 +
72 + # If you would like to train the model for the first time on a specific window then you can define it using the below two variables.
73 + # Start of training data for initial model.
74 + # initial_train_data_after: 1604578857
75 +
76 + # End of training data for initial model.
77 + # initial_train_data_before: 1604593257
78 +
79 + # If you would like to ignore recent data in training then you can offset it by offset_n_secs.
80 + offset_n_secs: 0
81 +
82 + # How many lagged values of each dimension to include in the 'feature vector' each model is trained on.
83 + lags_n: 5
84 +
85 + # How much smoothing to apply to each dimension in the 'feature vector' each model is trained on.
86 + smooth_n: 3
87 +
88 + # How many differences to take in preprocessing your data.
89 + # More info on differencing here: https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average#Differencing
90 + # diffs_n=0 would mean training models on the raw values of each dimension.
91 + # diffs_n=1 means everything is done in terms of differences.
92 + diffs_n: 1
93 +
94 + # What is the typical proportion of anomalies in your data on average?
95 + # This paramater can control the sensitivity of your models to anomalies.
96 + # Some discussion here: https://github.com/yzhao062/pyod/issues/144
97 + contamination: 0.001
98 +
99 + # Set to true to include an "average_prob" dimension on anomalies probability chart which is
100 + # just the average of all anomaly probabilities at each time step
101 + include_average_prob: true
102 +
103 + # Define any custom models you would like to create anomaly probabilties for, some examples below to show how.
104 + # For example below example creates two custom models, one to run anomaly detection user and system cpu for our demo servers
105 + # and one on the cpu and mem apps metrics for the python.d.plugin.
106 + # custom_models:
107 + # - name: 'demos_cpu'
108 + # dimensions: 'london.my-netdata.io::system.cpu|user,london.my-netdata.io::system.cpu|system,newyork.my-netdata.io::system.cpu|user,newyork.my-netdata.io::system.cpu|system'
109 + # - name: 'apps_python_d_plugin'
110 + # dimensions: 'apps.cpu|python.d.plugin,apps.mem|python.d.plugin'
111 +
112 + # Set to true to normalize, using min-max standardization, features used for the custom models.
113 + # Useful if your custom models contain dimensions on very different scales an model you use does
114 + # not internally do its own normalization. Usually best to leave as false.
115 + # custom_models_normalize: false
116 +
117 +# Standalone Custom models example as an additional collector job.
118 +# custom:
119 +# name: 'custom'
120 +# host: '127.0.0.1:19999'
121 +# protocol: 'http'
122 +# charts_regex: 'None'
123 +# charts_to_exclude: 'None'
124 +# model: 'pca'
125 +# train_max_n: 100000
126 +# train_every_n: 1800
127 +# train_n_secs: 14400
128 +# offset_n_secs: 0
129 +# lags_n: 5
130 +# smooth_n: 3
131 +# diffs_n: 1
132 +# contamination: 0.001
133 +# custom_models:
134 +# - name: 'user_netdata'
135 +# dimensions: 'users.cpu|netdata,users.mem|netdata,users.threads|netdata,users.processes|netdata,users.sockets|netdata'
136 +# - name: 'apps_python_d_plugin'
137 +# dimensions: 'apps.cpu|python.d.plugin,apps.mem|python.d.plugin,apps.threads|python.d.plugin,apps.processes|python.d.plugin,apps.sockets|python.d.plugin'
138 +
139 +# Pull data from some demo nodes for cross node custom models.
140 +# demos:
141 +# name: 'demos'
142 +# host: '127.0.0.1:19999'
143 +# protocol: 'http'
144 +# charts_regex: 'None'
145 +# charts_to_exclude: 'None'
146 +# model: 'pca'
147 +# train_max_n: 100000
148 +# train_every_n: 1800
149 +# train_n_secs: 14400
150 +# offset_n_secs: 0
151 +# lags_n: 5
152 +# smooth_n: 3
153 +# diffs_n: 1
154 +# contamination: 0.001
155 +# custom_models:
156 +# - name: 'system.cpu'
157 +# dimensions: 'london.my-netdata.io::system.cpu|user,london.my-netdata.io::system.cpu|system,newyork.my-netdata.io::system.cpu|user,newyork.my-netdata.io::system.cpu|system'
158 +# - name: 'system.ip'
159 +# dimensions: 'london.my-netdata.io::system.ip|received,london.my-netdata.io::system.ip|sent,newyork.my-netdata.io::system.ip|received,newyork.my-netdata.io::system.ip|sent'
160 +# - name: 'system.net'
161 +# dimensions: 'london.my-netdata.io::system.net|received,london.my-netdata.io::system.net|sent,newyork.my-netdata.io::system.net|received,newyork.my-netdata.io::system.net|sent'
162 +# - name: 'system.io'
163 +# dimensions: 'london.my-netdata.io::system.io|in,london.my-netdata.io::system.io|out,newyork.my-netdata.io::system.io|in,newyork.my-netdata.io::system.io|out'
164 +
165 +# Example additional job if you want to also pull data from a child streaming to your
166 +# local parent or even a remote node so long as the Netdata REST API is accessible.
167 +# mychildnode1:
168 +# name: 'mychildnode1'
169 +# host: '127.0.0.1:19999/host/mychildnode1'
170 +# protocol: 'http'
171 +# charts_regex: 'system\..*'
172 +# charts_to_exclude: 'None'
173 +# model: 'pca'
174 +# train_max_n: 100000
175 +# train_every_n: 1800
176 +# train_n_secs: 14400
177 +# offset_n_secs: 0
178 +# lags_n: 5
179 +# smooth_n: 3
180 +# diffs_n: 1
181 +# contamination: 0.001
collectors/python.d.plugin/python.d.conf
+1
@@ -31,6 +31,7 @@ gc_interval: 300
31 # adaptec_raid: yes
32 # alarms: yes
33 # am2320: yes
34 +# anomalies: no
35 apache_cache: no
36 # beanstalk: yes
37 # bind_rndc: yes
health/Makefile.am
+1
@@ -26,6 +26,7 @@ healthconfigdir=$(libconfigdir)/health.d
26 dist_healthconfig_DATA = \
27 health.d/adaptec_raid.conf \
28 health.d/am2320.conf \
29 + health.d/anomalies.conf \
30 health.d/apache.conf \
31 health.d/apcupsd.conf \
32 health.d/backend.conf \
health/health.d/anomalies.conf new
+17
@@ -0,0 +1,17 @@
1 +# raise a warning alarm if an anomaly probability is consistently above 50%
2 +
3 +template: anomaly_probabilities
4 + on: anomalies.probability
5 + lookup: average -2m foreach *
6 + every: 1m
7 + warn: $this > 50
8 + info: average anomaly probability > 50% for last 2 minutes
9 +
10 +# raise a warning alarm if an anomaly flag is consistently firing
11 +
12 +template: anomaly_flags
13 + on: anomalies.anomaly
14 + lookup: sum -2m foreach *
15 + every: 1m
16 + warn: $this > 10
17 + info: count of anomalies > 10 for last 2 minutes
web/gui/dashboard_info.js
+6
@@ -571,6 +571,12 @@ netdataDashboard.menu = {
571 info: 'Summary, namespaces and topics performance data for the <b><a href="http://pulsar.apache.org/">Apache Pulsar</a></b> pub-sub messaging system.'
572 },
573
574 + 'anomalies': {
575 + title: 'Anomalies',
576 + icon: '<i class="fas fa-flask"></i>',
577 + info: 'Anomaly scores relating to key system metrics. A high anomaly probability indicates strange behaviour and may trigger an anomaly prediction from the trained models. Read the <a href="https://github.com/netdata/netdata/tree/master/collectors/python.d.plugin/anomalies" target="_blank">anomalies collector docs</a> for more details.'
578 + },
579 +
580 'alarms': {
581 title: 'Alarms',
582 icon: '<i class="fas fa-bell"></i>',