You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.5 KiB

6 years ago
import { getJsonDataSync, writeJsonDataSync } from '../services/json'
6 years ago
import { ANOMALIES_PATH } from '../config'
6 years ago
6 years ago
import * as crypto from 'crypto';
6 years ago
import * as path from 'path'
import * as fs from 'fs'
6 years ago
export type Datasource = {
method: string,
data: Object,
params: Object,
type: string,
url: string
}
export type Metric = {
datasource: string,
targets: string[]
}
export type AnalyticUnit = {
name: string,
panelUrl: string,
pattern: string,
metric: Metric,
datasource: Datasource
status: string,
error?: string,
lastPredictionTime: number,
nextId: number
}
6 years ago
export type AnalyticUnitId = string;
6 years ago
6 years ago
function createItem(item: AnalyticUnit): AnalyticUnitId {
6 years ago
const hashString = item.name + (new Date()).toString();
6 years ago
const newId: AnalyticUnitId = crypto.createHash('md5').update(hashString).digest('hex');
let filename = path.join(ANOMALIES_PATH, `${newId}.json`);
6 years ago
if(fs.existsSync(filename)) {
return null;
}
6 years ago
save(newId, item);
return newId;
6 years ago
}
6 years ago
function removeItem(key: AnalyticUnitId) {
let filename = path.join(ANOMALIES_PATH, `${key}.json`);
6 years ago
fs.unlinkSync(filename);
}
6 years ago
function save(predictorId: AnalyticUnitId, anomaly: AnalyticUnit) {
6 years ago
let filename = path.join(ANOMALIES_PATH, `${predictorId}.json`);
return writeJsonDataSync(filename, anomaly);
}
6 years ago
function loadById(predictorId: AnalyticUnitId): AnalyticUnit {
6 years ago
let filename = path.join(ANOMALIES_PATH, `${predictorId}.json`);
if(!fs.existsSync(filename)) {
return null;
}
return getJsonDataSync(filename);
}
function saveAnomalyTypeInfo(info) {
console.log('Saving');
let filename = path.join(ANOMALIES_PATH, `${info.name}.json`);
if(info.next_id === undefined) {
info.next_id = 0;
}
if(info.last_prediction_time === undefined) {
info.last_prediction_time = 0;
}
return writeJsonDataSync(filename, info);
}
function getAnomalyTypeInfo(name) {
return getJsonDataSync(path.join(ANOMALIES_PATH, `${name}.json`));
}
6 years ago
function setAnomalyStatus(predictorId: AnalyticUnitId, status: string, error?: string) {
let info = loadById(predictorId);
6 years ago
info.status = status;
if(error !== undefined) {
info.error = error;
} else {
info.error = '';
}
6 years ago
save(predictorId, info);
6 years ago
}
6 years ago
function setAnomalyPredictionTime(predictorId: AnalyticUnitId, lastPredictionTime: number) {
let info = loadById(predictorId);
6 years ago
info.lastPredictionTime = lastPredictionTime;
6 years ago
save(predictorId, info);
6 years ago
}
export {
6 years ago
save, loadById, createItem, removeItem, saveAnomalyTypeInfo,
6 years ago
getAnomalyTypeInfo, setAnomalyStatus, setAnomalyPredictionTime
}