forked from huksley/prometheus-remote-write
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
142 lines (126 loc) · 3.73 KB
/
index.js
File metadata and controls
142 lines (126 loc) · 3.73 KB
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
const SnappyJS = require("snappyjs");
const fetch = require("node-fetch");
const protobuf = require("protobufjs");
const btoa = (s) => Buffer.from(s, "binary").toString("base64");
const prom = require("./prom");
const __holder = {
type: null,
};
const kv = (o) =>
typeof o === "object"
? Object.entries(o).map((e) => ({
name: e[0],
value: e[1],
}))
: undefined;
/** Loads protocol definition, caches it */
async function loadProto(options) {
if (__holder.root) {
return __holder.type;
}
if (options?.proto) {
const root = await protobuf.load(options?.proto);
if (options?.verbose) {
logger.info("Loaded protocol definitions", fileName, root);
}
const WriteRequest = root.lookupType("prometheus.WriteRequest");
__holder.type = WriteRequest;
return WriteRequest;
}
return prom.prometheus.WriteRequest;
}
/** Serializes JSON as protobuf buffer */
async function serialize(payload, options) {
const type = await loadProto(options);
const errMsg = type.verify(payload);
if (errMsg) {
throw new Error(errMsg);
}
const buffer = type.encode(payload).finish();
return buffer;
}
/**
* Sends metrics over HTTP(s)
*
* @param {import("./types").Timeseries | import("./types").Timeseries[]} timeseries
* @param {import("./types").Options} options
*/
async function pushTimeseries(timeseries, options) {
const orig = timeseries;
// Brush up a little
timeseries = !Array.isArray(timeseries) ? [timeseries] : timeseries;
// Nothing to do
if (timeseries.length === 0) {
return {
status: 200,
statusText: "OK",
};
}
const start1 = Date.now();
const writeRequest = {
timeseries: timeseries.map((t) => ({
labels: Array.isArray(t.labels) ? [t.labels, ...(kv(options?.labels) || [])] : kv({
...options?.labels,
...t.labels
}),
samples: t.samples.map((s) => ({
value: s.value,
timestamp: s.timestamp ? s.timestamp : Date.now(),
})),
})),
}
const buffer = await serialize(
writeRequest,
options?.proto
);
const logger = options?.console || console;
const start2 = Date.now();
if (options?.timing) {
logger.info("Serialized in", start2 - start1, "ms");
}
if (options?.url) {
return (options.fetch || fetch)(options?.url, {
method: "POST",
headers: {
"Content-Type": "application/vnd.google.protobuf",
...(options?.auth?.username && options?.auth?.password
? {
Authorization: "Basic " + btoa(options?.auth.username + ":" + options?.auth?.password),
}
: undefined),
},
body: SnappyJS.compress(buffer),
}).then(async (r) => {
const text = await r.text();
if (options?.verbose && r.status != 200) {
logger.warn("Failed to send write request, error", r.status + " " + r.statusText + " " + text, writeRequest);
} else if (options?.verbose && !options?.timing) {
logger.info("Write request sent", r.status + " " + r.statusText + " " + text, writeRequest);
} else if (options?.verbose && options?.timing) {
logger.info("Write request sent", r.status + " " + r.statusText + " in", Date.now() - start2, "ms", writeRequest);
}
return {
status: r.status,
statusText: r.statusText,
errorMessage: r.status !== 200 ? text : undefined,
};
});
} else {
logger.warn("Unable to send timeseries, no endpoing configured", timeseries);
}
}
async function pushMetrics(metrics, options) {
return pushTimeseries(
Object.entries(metrics).map(c => ({
labels: { __name__: c[0] },
samples: [{ value: c[1] }]
})),
options
)
}
module.exports = {
serialize,
loadProto,
pushTimeseries,
pushMetrics
};