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
|
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ML_DIMENSION_H
#define ML_DIMENSION_H
#include "Query.h"
#include "Config.h"
#include "ml-private.h"
namespace ml {
enum class MLResult {
Success = 0,
MissingData,
NaN,
};
static inline std::string getMLDimensionID(RRDDIM *RD) {
RRDSET *RS = RD->rrdset;
std::stringstream SS;
SS << rrdset_context(RS) << "|" << rrdset_id(RS) << "|" << rrddim_name(RD);
return SS.str();
}
class Dimension {
public:
Dimension(RRDDIM *RD, RRDSET *AnomalyRateRS) :
RD(RD),
AnomalyRateRD(rrddim_add(AnomalyRateRS, ml::getMLDimensionID(RD).c_str(), NULL, 1, 1000, RRD_ALGORITHM_ABSOLUTE)),
LastTrainedAt(Seconds(0)),
Trained(false),
ConstantModel(false),
AnomalyScore(0.0),
AnomalyBit(0),
AnomalyBitCounter(0)
{ }
RRDDIM *getRD() const {
return RD;
}
unsigned updateEvery() const {
return RD->update_every;
}
time_t latestTime() const {
return Query(RD).latestTime();
}
time_t oldestTime() const {
return Query(RD).oldestTime();
}
void setAnomalyRateRDName(const char *Name) const {
rrddim_reset_name(AnomalyRateRD->rrdset, AnomalyRateRD, Name);
}
RRDDIM *getAnomalyRateRD() const {
return AnomalyRateRD;
}
bool isTrained() const {
return Trained;
}
bool isAnomalous() const {
return AnomalyBit;
}
bool shouldTrain(const TimePoint &TP) const;
bool isActive() const;
MLResult trainModel();
bool predict(CalculatedNumber Value, bool Exists);
void updateAnomalyBitCounter(RRDSET *RS, unsigned Elapsed, bool IsAnomalous);
std::pair<bool, double> detect(size_t WindowLength, bool Reset);
std::array<KMeans, 1> getModels();
private:
std::pair<CalculatedNumber *, size_t> getCalculatedNumbers();
public:
RRDDIM *RD;
RRDDIM *AnomalyRateRD;
TimePoint LastTrainedAt;
std::atomic<bool> Trained;
std::atomic<bool> ConstantModel;
CalculatedNumber AnomalyScore;
std::atomic<bool> AnomalyBit;
unsigned AnomalyBitCounter;
std::vector<CalculatedNumber> CNs;
std::array<KMeans, 1> Models;
std::mutex Mutex;
};
} // namespace ml
#endif /* ML_DIMENSION_H */
|