Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

📈 PaaS-friendly metrics #4874

Merged
merged 86 commits into from
Apr 19, 2020
Merged
Show file tree
Hide file tree
Changes from 75 commits
Commits
Show all changes
86 commits
Select commit Hold shift + click to select a range
77d04df
prom-client JSON to InfluxDB line protocol converter
platan Feb 9, 2020
119d610
Converts a metric with separate names
platan Feb 11, 2020
f0a14c8
prom-client JSON to InfluxDB line protocol (version 2) converter
platan Feb 17, 2020
b0dc8a7
Server has instance id
platan Mar 2, 2020
f844e9f
Read the instance id from an environment variable
platan Mar 3, 2020
dcd34cc
More unit tests for instance-metadata
platan Mar 3, 2020
2ef4820
Log instance id
platan Mar 3, 2020
8a74971
Push influx metrics
platan Mar 4, 2020
1fd5bc1
INSTANCE_ID with dyno metadata
platan Mar 6, 2020
1029661
Prepare influx metrics in one place
platan Mar 7, 2020
a95079d
Influx metrics endpoint should return metrics
platan Mar 9, 2020
c89cfc1
More readable tests
platan Mar 9, 2020
2ea4311
Env added to instance metadata
platan Mar 9, 2020
9adf0cb
hostname as an instance label value
platan Mar 14, 2020
2e7fa64
HEROKU_DYNO_ID as an instance id for heroku
platan Mar 15, 2020
c91c667
Instance env can be set by env variable
platan Mar 15, 2020
2a4f0e0
HEROKU_APP_NAME as an instance env
platan Mar 15, 2020
fb2fb9b
Log instance metadata as a JSON
platan Mar 15, 2020
44bf13c
Typo fix
platan Mar 15, 2020
d755b6f
Code refactoring in tests
platan Mar 15, 2020
5680463
Merge remote-tracking branch 'badges/master' into paas-friendly-metrics
platan Mar 15, 2020
aaa1d1d
wait-for-expect dev dependency added
platan Mar 15, 2020
1d811ea
Test for pushing metrics
platan Mar 15, 2020
dfe2721
Test for pushing metrics
platan Mar 15, 2020
61f9e3c
Use basic authentication for pushing metrics
platan Mar 16, 2020
fafc622
intervalSeconds=2 for development env
platan Mar 16, 2020
c297eba
Using existing methods
platan Mar 16, 2020
b7749e0
TODOs removed
platan Mar 16, 2020
1a9fc93
Schema for influx credentials
platan Mar 16, 2020
6792b6a
Influx config removed from config files
platan Mar 16, 2020
628b5b9
Require username and password when influx metrics are enabled
platan Mar 16, 2020
6fe4956
Unused args removed
platan Mar 17, 2020
a59a94f
pushing component should log errors
platan Mar 17, 2020
2c1b3b2
Speed up tests
platan Mar 17, 2020
d259568
should log error responses
platan Mar 17, 2020
633362a
InstanceMetadata class replaces by simple object
platan Mar 18, 2020
ade7c2c
Influx metrics can be configuredd by env variables
platan Mar 18, 2020
1282cf5
Use application label name instead of service
platan Mar 20, 2020
ee0082c
Unused code removed
platan Mar 21, 2020
1bff31c
Integration test for prom-client and converter
platan Mar 22, 2020
d2eb269
metrics.influx.enabled configuration option added
platan Mar 24, 2020
a15a7e9
Improved influx configuration schema
platan Mar 28, 2020
8c46bce
instanceMetadata validation
platan Mar 28, 2020
31f5cc9
Merge remote-tracking branch 'badges/master' into paas-friendly-metrics
platan Mar 28, 2020
d091d3b
Typo fix
platan Mar 28, 2020
96d4086
Default value for env
platan Mar 29, 2020
68b6e72
metrics.infux.hostnameAsAInstanceId added
platan Mar 29, 2020
b2f9583
should add hostname as an instance label when hostnameAsAInstanceId i…
platan Mar 29, 2020
1f55d31
Default values for influx configuration
platan Mar 29, 2020
a43d423
Merge remote-tracking branch 'badges/master' into paas-friendly-metrics
platan Mar 29, 2020
e2e6dfd
flatMap is not available in Node.js 9.4
platan Mar 29, 2020
6d6b78e
Env vars removed from Procfile
platan Apr 2, 2020
749d2e1
Merge remote-tracking branch 'badges/master' into paas-friendly-metrics
platan Apr 5, 2020
b63be09
Better instance metadata values in tests
platan Apr 5, 2020
282ce88
Typo fix
platan Apr 5, 2020
8a091c7
lodash.groupby added to prod dependencies
platan Apr 5, 2020
0970871
Allow other keys in private config
platan Apr 5, 2020
78bb612
Missing test - should allow other private keys when influx metrics ar…
platan Apr 6, 2020
8542af3
Missing test - should require private metrics config when influx conf…
platan Apr 6, 2020
95d42ad
log.error instead of console.log
platan Apr 7, 2020
acc35fe
metrics.influx.uri -> metrics.influx.url
platan Apr 8, 2020
86beb55
Unused arguments removed
platan Apr 8, 2020
8ff4743
async removed
platan Apr 8, 2020
55af35b
Merge remote-tracking branch 'badges/master' into paas-friendly-metrics
platan Apr 8, 2020
e15ce4e
promisify sendMetrics
platan Apr 10, 2020
0abf2ef
Allow to disable prometheus metrics
platan Apr 11, 2020
5582cee
Create test server with custom config
platan Apr 11, 2020
14a0f98
'metrics-influx' resource removed
platan Apr 11, 2020
fe5b4b9
'metrics-influx' resource removed
platan Apr 11, 2020
5054400
Private config schema flattened out
platan Apr 12, 2020
3418797
Merge branch 'master' into paas-friendly-metrics
platan Apr 12, 2020
92bb991
Extra code removed in Prometheus tests
platan Apr 13, 2020
0632a63
promisify moved outside of the class
platan Apr 15, 2020
18939dc
Do not throw errors from got in a specific test
platan Apr 15, 2020
bc79028
hostnameAliases added
platan Apr 15, 2020
9f7953e
instanceIdFrom added
platan Apr 15, 2020
43af149
instanceIdEnvVarName added
platan Apr 15, 2020
aac697d
envLabel added to schema
platan Apr 16, 2020
64915a0
instanceMetadata is not used by InfluxMetrics
platan Apr 17, 2020
95c763a
Instance metadata removed
platan Apr 17, 2020
53b29b4
hostnameAsAnInstanceId removed
platan Apr 17, 2020
d621ed8
A comment added
platan Apr 17, 2020
3d8e385
waitForExpect removed
platan Apr 17, 2020
32ec8cc
Merge branch 'master' into paas-friendly-metrics
platan Apr 18, 2020
1e2999c
Unused code removed
platan Apr 18, 2020
7f75fa0
Merge branch 'master' into paas-friendly-metrics
platan Apr 19, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions config/custom-environment-variables.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ public:
metrics:
prometheus:
enabled: 'METRICS_PROMETHEUS_ENABLED'
endpointEnabled: 'METRICS_PROMETHEUS_ENDPOINT_ENABLED'
influx:
enabled: 'METRICS_INFLUX_ENABLED'
url: 'METRICS_INFLUX_URL'
timeoutMilliseconds: 'METRICS_INFLUX_TIMEOUT_MILLISECONDS'
intervalSeconds: 'METRICS_INFLUX_INTERVAL_SECONDS'
hostnameAsAnInstanceId: 'METRICS_INFLUX_HOSTNAME_AS_AN_INSTANCE_ID'

ssl:
isSecure: 'HTTPS'
Expand Down Expand Up @@ -85,3 +92,5 @@ private:
twitch_client_id: 'TWITCH_CLIENT_ID'
twitch_client_secret: 'TWITCH_CLIENT_SECRET'
wheelmap_token: 'WHEELMAP_TOKEN'
influx_username: 'INFLUX_USERNAME'
influx_password: 'INFLUX_PASSWORD'
6 changes: 5 additions & 1 deletion config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ public:
metrics:
prometheus:
enabled: false

endpointEnabled: false
influx:
enabled: false
timeoutMilliseconds: 1000
intervalSeconds: 15
ssl:
isSecure: false

Expand Down
1 change: 1 addition & 0 deletions config/shields-io-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ public:
metrics:
prometheus:
enabled: true
endpointEnabled: true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


ssl:
isSecure: true
Expand Down
22 changes: 11 additions & 11 deletions core/server/in-process-server-test-helpers.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
'use strict'

const merge = require('deepmerge')
const config = require('config').util.toObject()
const portfinder = require('portfinder')
const Server = require('./server')

function createTestServer({ port }) {
const serverConfig = {
...config,
public: {
...config.public,
bind: {
...config.public.bind,
port,
},
},
async function createTestServer(customConfig = {}) {
const mergedConfig = merge(config, customConfig)
if (!mergedConfig.public.bind.port) {
mergedConfig.public.bind.port = await portfinder.getPortPromise()
}
const requiredInstanceMetadata = {
env: 'testing',
hostname: 'localhost',
}

return new Server(serverConfig)
return new Server(mergedConfig, requiredInstanceMetadata)
}

module.exports = {
Expand Down
72 changes: 72 additions & 0 deletions core/server/influx-metrics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
'use strict'

const { promisify } = require('util')
const { post } = require('request')
const postAsync = promisify(post)
const { promClientJsonToInfluxV2 } = require('./metrics/format-converters')
const log = require('./log')

module.exports = class InfluxMetrics {
constructor(metricInstance, instanceMetadata, config) {
this._metricInstance = metricInstance
this._instanceMetadata = instanceMetadata
this._config = config
}

async sendMetrics() {
const auth = {
user: this._config.username,
pass: this._config.password,
}
const request = {
uri: this._config.url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: this.metrics(),
timeout: this._config.timeoutMillseconds,
auth,
}

let response
try {
response = await postAsync(request)
} catch (error) {
log.error(
new Error(`Cannot push metrics. Cause: ${error.name}: ${error.message}`)
)
}
if (response && response.statusCode >= 300) {
log.error(
new Error(
`Cannot push metrics. ${response.request.href} responded with status code ${response.statusCode}`
)
)
}
}

startPushingMetrics() {
this._intervalId = setInterval(
() => this.sendMetrics(),
this._config.intervalSeconds * 1000
)
}

metrics() {
const { env, hostname, id } = this._instanceMetadata
const { hostnameAliases = {}, hostnameAsAnInstanceId } = this._config
const instance = hostnameAsAnInstanceId
? hostnameAliases[hostname] || hostname
: id
return promClientJsonToInfluxV2(this._metricInstance.metrics(), {
env,
application: 'shields',
instance,
})
}

stopPushingMetrics() {
if (this._intervalId) {
clearInterval(this._intervalId)
this._intervalId = undefined
}
}
}
177 changes: 177 additions & 0 deletions core/server/influx-metrics.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
'use strict'

const nock = require('nock')
const sinon = require('sinon')
const waitForExpect = require('wait-for-expect')
const { expect } = require('chai')
const log = require('./log')
const InfluxMetrics = require('./influx-metrics')
require('../register-chai-plugins.spec')
describe('Influx metrics', function() {
const metricInstance = {
metrics() {
return [
{
help: 'counter 1 help',
name: 'counter1',
type: 'counter',
values: [{ value: 11, labels: {} }],
aggregator: 'sum',
},
]
},
}
const instanceMetadata = {
id: 'instance2',
env: 'test-env',
}
const config = {}
describe('"metrics" function', function() {
it('should add instance id as an instance label', async function() {
const influxMetrics = new InfluxMetrics(
metricInstance,
instanceMetadata,
config
)

expect(influxMetrics.metrics()).to.contain('instance=instance2')
})

it('should add hostname as an instance label when hostnameAsAnInstanceId is enabled', async function() {
const instanceMetadata = {
id: 'instance2',
env: 'test-env',
hostname: 'test-hostname',
}
const customConfig = {
hostnameAsAnInstanceId: true,
}
const influxMetrics = new InfluxMetrics(
metricInstance,
instanceMetadata,
customConfig
)

expect(influxMetrics.metrics()).to.be.contain('instance=test-hostname')
})

it('should use a hostname alias as an instance label', async function() {
const instanceMetadata = {
id: 'instance2',
env: 'test-env',
hostname: 'test-hostname',
}
const customConfig = {
hostnameAsAnInstanceId: true,
hostnameAliases: { 'test-hostname': 'test-hostname-aliass' },
}
const influxMetrics = new InfluxMetrics(
metricInstance,
instanceMetadata,
customConfig
)

expect(influxMetrics.metrics()).to.be.contain(
'instance=test-hostname-alias'
)
})
})

describe('startPushingMetrics', function() {
let influxMetrics
afterEach(function() {
influxMetrics.stopPushingMetrics()
nock.cleanAll()
nock.enableNetConnect()
})
it('should send metrics', async function() {
const scope = nock('http://shields-metrics.io/', {
reqheaders: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.persist()
.post(
'/metrics',
'prometheus,application=shields,env=test-env,instance=instance2 counter1=11'
)
.basicAuth({ user: 'metrics-username', pass: 'metrics-password' })
.reply(200)
influxMetrics = new InfluxMetrics(metricInstance, instanceMetadata, {
url: 'http://shields-metrics.io/metrics',
timeoutMillseconds: 100,
intervalSeconds: 0,
username: 'metrics-username',
password: 'metrics-password',
})

influxMetrics.startPushingMetrics()

await waitForExpect(
() => {
expect(scope.isDone()).to.be.equal(
true,
`pending mocks: ${scope.pendingMocks()}`
)
},
1000,
1
)
})
})

describe('sendMetrics', function() {
beforeEach(function() {
sinon.spy(log, 'error')
})
afterEach(function() {
log.error.restore()
nock.cleanAll()
nock.enableNetConnect()
})

const influxMetrics = new InfluxMetrics(metricInstance, instanceMetadata, {
url: 'http://shields-metrics.io/metrics',
timeoutMillseconds: 50,
intervalSeconds: 0,
username: 'metrics-username',
password: 'metrics-password',
})
it('should log errors', async function() {
nock.disableNetConnect()

await influxMetrics.sendMetrics()

expect(log.error).to.be.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'Cannot push metrics. Cause: NetConnectNotAllowedError: Nock: Disallowed net connect for "shields-metrics.io:80/metrics"'
)
)
)
})

it('should log error responses', async function() {
nock('http://shields-metrics.io/')
.persist()
.post('/metrics')
.reply(400)

await influxMetrics.sendMetrics()

expect(log.error).to.be.calledWith(
sinon.match
.instanceOf(Error)
.and(
sinon.match.has(
'message',
'Cannot push metrics. http://shields-metrics.io/metrics responded with status code 400'
)
)
)
})
})
})
10 changes: 10 additions & 0 deletions core/server/instance-id-generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict'

function generateInstanceId() {
// from https://gist.github.com/gordonbrander/2230317
return Math.random()
.toString(36)
.substr(2, 9)
}

module.exports = generateInstanceId
27 changes: 27 additions & 0 deletions core/server/metrics/format-converters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict'
const groupBy = require('lodash.groupby')

function promClientJsonToInfluxV2(metrics, extraLabels = {}) {
// TODO Replace with Array.prototype.flatMap() after migrating to Node.js >= 11
const flatMap = (f, arr) => arr.reduce((acc, x) => acc.concat(f(x)), [])
return flatMap(metric => {
const valuesByLabels = groupBy(metric.values, value =>
JSON.stringify(Object.entries(value.labels).sort())
)
return Object.values(valuesByLabels).map(metricsWithSameLabel => {
const labels = Object.entries(metricsWithSameLabel[0].labels)
.concat(Object.entries(extraLabels))
.sort((a, b) => a[0].localeCompare(b[0]))
.map(labelEntry => `${labelEntry[0]}=${labelEntry[1]}`)
.join(',')
const labelsFormatted = labels ? `,${labels}` : ''
const values = metricsWithSameLabel
.sort((a, b) => a.metricName.localeCompare(b.metricName))
.map(value => `${value.metricName || metric.name}=${value.value}`)
.join(',')
return `prometheus${labelsFormatted} ${values}`
})
}, metrics).join('\n')
}

module.exports = { promClientJsonToInfluxV2 }
Loading