-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (66 loc) · 2.2 KB
/
index.js
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
import http from 'http'
import debug from 'debug'
import { pipe } from 'it-pipe'
import { GraphQLClient } from 'graphql-request'
import { getAnalytics } from './analytics.js'
import { createRegistry, recordMetrics } from './prom.js'
const log = debug('exporter:index')
const ENDPOINT = 'https://api.cloudflare.com/client/v4/graphql'
/**
* @param {Object} config
* @param {string} config.cfApiToken Cloudflare API Token with permissions for zone
* @param {string} config.cfAuthEmail Cloudflare API account email.
* @param {string} config.cfZoneId Cloudflare Zone identifier.
* @param {string} config.promNamespace Prometheus metrics namespace.
* @param {number} [config.port] Port to run the metrics server on.
*/
export async function startExporter({
cfApiToken,
cfAuthEmail,
cfZoneId,
promNamespace,
port = 3000
}) {
log('Creating graphQL client...')
const client = new GraphQLClient(ENDPOINT, { headers: {
'X-AUTH-EMAIL': cfAuthEmail,
'Authorization': `Bearer ${cfApiToken}`
}})
log('creating Prometheus metrics registry...')
const { metrics, registry } = createRegistry(promNamespace)
log('creating HTTP server...')
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`)
if (url.pathname === '/metrics') {
res.write(await registry.metrics())
} else {
res.statusCode = 404
res.write('not found')
}
res.end()
})
server.listen(port, () => log(`server listening on: http://localhost:${port}`))
try {
await pipe(
getAnalytics(client, cfZoneId),
recordMetrics(metrics),
logResult
)
} finally {
log('closing HTTP server...')
server.close()
}
}
/**
* @param {AsyncIterable<import('./analytics').Analytics>} source
*/
async function logResult(source) {
for await (const res of source) {
log(`incremented ${res.requests} requests`)
log(`incremented ${res.cachedRequests} cached requests`)
log(`incremented ${res.firewallBlockedRequests} firewall blocked requests`)
res.contentTypeRequests && Object.keys(res.contentTypeRequests).forEach(key => {
log(`incremented content type ${key} with ${res.contentTypeRequests[key]} requests`)
})
}
}