1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/src/lib/metrics.ts

571 lines
21 KiB
TypeScript
Raw Normal View History

import client from 'prom-client';
import memoizee from 'memoizee';
import EventEmitter from 'events';
import { Knex } from 'knex';
2021-04-29 10:21:29 +02:00
import * as events from './metric-events';
import {
DB_POOL_UPDATE,
FEATURE_ARCHIVED,
FEATURE_CREATED,
FEATURE_REVIVED,
FEATURE_STRATEGY_ADD,
FEATURE_STRATEGY_REMOVE,
FEATURE_STRATEGY_UPDATE,
FEATURE_ENVIRONMENT_ENABLED,
FEATURE_ENVIRONMENT_DISABLED,
FEATURE_VARIANTS_UPDATED,
FEATURE_METADATA_UPDATED,
FEATURE_UPDATED,
2021-12-09 21:02:58 +01:00
CLIENT_METRICS,
CLIENT_REGISTER,
2021-04-29 10:21:29 +02:00
} from './types/events';
import { IUnleashConfig } from './types/option';
import { IUnleashStores } from './types/stores';
import { hoursToMilliseconds, minutesToMilliseconds } from 'date-fns';
import { InstanceStatsService } from './features/instance-stats/instance-stats-service';
import { ValidatedClientMetrics } from './services/client-metrics/schema';
import { IEnvironment } from './types';
export default class MetricsMonitor {
chore(deps): update dependency node to v18.19.0 (#4957) [![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | Pending | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---|---|---|---| | [node](https://togithub.com/nodejs/node) | | minor | `18.18.0` -> `18.19.0` | | [![age](https://developer.mend.io/api/mc/badges/age/github-tags/node/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://developer.mend.io/api/mc/badges/adoption/github-tags/node/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://developer.mend.io/api/mc/badges/compatibility/github-tags/node/18.18.0/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/github-tags/node/18.18.0/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | | [@types/node](https://togithub.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://togithub.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node)) | devDependencies | minor | [`18.17.19` -> `18.19.4`](https://renovatebot.com/diffs/npm/@types%2fnode/18.17.19/18.19.4) | `18.19.6` (+1) | [![age](https://developer.mend.io/api/mc/badges/age/npm/@types%2fnode/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/@types%2fnode/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/@types%2fnode/18.17.19/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/@types%2fnode/18.17.19/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes <details> <summary>nodejs/node (node)</summary> ### [`v18.19.0`](https://togithub.com/nodejs/node/compare/v18.18.2...v18.19.0) [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.2...v18.19.0) ### [`v18.18.2`](https://togithub.com/nodejs/node/compare/v18.18.1...v18.18.2) [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.1...v18.18.2) ### [`v18.18.1`](https://togithub.com/nodejs/node/releases/tag/v18.18.1): 2023-10-10, Version 18.18.1 &#x27;Hydrogen&#x27; (LTS), @&#8203;richardlau [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.0...v18.18.1) ##### Notable Changes This release addresses some regressions that appeared in Node.js 18.18.0: - (Windows) FS can not handle certain characters in file name [#&#8203;48673](https://togithub.com/nodejs/node/issues/48673) - 18 and 20 node images give error - Text file busy (after re-build images) [nodejs/docker-node#1968](https://togithub.com/nodejs/docker-node/issues/1968) - libuv update in 18.18.0 breaks webpack's thread-loader [#&#8203;49911](https://togithub.com/nodejs/node/issues/49911) The libuv 1.45.0 and 1.46.0 updates that were released in Node.js 18.18.0 have been temporarily reverted. ##### Commits - \[[`3e3a75cc46`](https://togithub.com/nodejs/node/commit/3e3a75cc46)] - ***Revert*** "**build**: sync libuv header change" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`14ece2c479`](https://togithub.com/nodejs/node/commit/14ece2c479)] - ***Revert*** "**deps**: upgrade to libuv 1.45.0" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`022352acbe`](https://togithub.com/nodejs/node/commit/022352acbe)] - ***Revert*** "**deps**: upgrade to libuv 1.46.0" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`d9f138189c`](https://togithub.com/nodejs/node/commit/d9f138189c)] - ***Revert*** "**deps**: add missing thread-common.c in uv.gyp" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`7a3e1ffbb8`](https://togithub.com/nodejs/node/commit/7a3e1ffbb8)] - **fs**: make sure to write entire buffer (Robert Nagy) [#&#8203;49211](https://togithub.com/nodejs/node/pull/49211) - \[[`04cba95a67`](https://togithub.com/nodejs/node/commit/04cba95a67)] - **test**: add `tmpdir.resolve()` (Livia Medeiros) [#&#8203;49079](https://togithub.com/nodejs/node/pull/49079) </details> --- ### Configuration 📅 **Schedule**: Branch creation - "after 7pm every weekday,before 5am every weekday" in timezone Europe/Madrid, Automerge - At any time (no schedule defined). 🚦 **Automerge**: Enabled. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate](https://www.mend.io/free-developer-tools/renovate/). View repository job log [here](https://developer.mend.io/github/Unleash/unleash). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjMiLCJ1cGRhdGVkSW5WZXIiOiIzNy4xMjcuMCIsInRhcmdldEJyYW5jaCI6Im1haW4ifQ==--> --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Ivar Conradi Østhus <ivar@getunleash.ai>
2024-01-10 08:23:19 +01:00
timer?: NodeJS.Timeout;
chore(deps): update dependency node to v18.19.0 (#4957) [![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | Pending | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---|---|---|---| | [node](https://togithub.com/nodejs/node) | | minor | `18.18.0` -> `18.19.0` | | [![age](https://developer.mend.io/api/mc/badges/age/github-tags/node/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://developer.mend.io/api/mc/badges/adoption/github-tags/node/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://developer.mend.io/api/mc/badges/compatibility/github-tags/node/18.18.0/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/github-tags/node/18.18.0/v18.19.0?slim=true)](https://docs.renovatebot.com/merge-confidence/) | | [@types/node](https://togithub.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://togithub.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node)) | devDependencies | minor | [`18.17.19` -> `18.19.4`](https://renovatebot.com/diffs/npm/@types%2fnode/18.17.19/18.19.4) | `18.19.6` (+1) | [![age](https://developer.mend.io/api/mc/badges/age/npm/@types%2fnode/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/@types%2fnode/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/@types%2fnode/18.17.19/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/@types%2fnode/18.17.19/18.19.4?slim=true)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes <details> <summary>nodejs/node (node)</summary> ### [`v18.19.0`](https://togithub.com/nodejs/node/compare/v18.18.2...v18.19.0) [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.2...v18.19.0) ### [`v18.18.2`](https://togithub.com/nodejs/node/compare/v18.18.1...v18.18.2) [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.1...v18.18.2) ### [`v18.18.1`](https://togithub.com/nodejs/node/releases/tag/v18.18.1): 2023-10-10, Version 18.18.1 &#x27;Hydrogen&#x27; (LTS), @&#8203;richardlau [Compare Source](https://togithub.com/nodejs/node/compare/v18.18.0...v18.18.1) ##### Notable Changes This release addresses some regressions that appeared in Node.js 18.18.0: - (Windows) FS can not handle certain characters in file name [#&#8203;48673](https://togithub.com/nodejs/node/issues/48673) - 18 and 20 node images give error - Text file busy (after re-build images) [nodejs/docker-node#1968](https://togithub.com/nodejs/docker-node/issues/1968) - libuv update in 18.18.0 breaks webpack's thread-loader [#&#8203;49911](https://togithub.com/nodejs/node/issues/49911) The libuv 1.45.0 and 1.46.0 updates that were released in Node.js 18.18.0 have been temporarily reverted. ##### Commits - \[[`3e3a75cc46`](https://togithub.com/nodejs/node/commit/3e3a75cc46)] - ***Revert*** "**build**: sync libuv header change" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`14ece2c479`](https://togithub.com/nodejs/node/commit/14ece2c479)] - ***Revert*** "**deps**: upgrade to libuv 1.45.0" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`022352acbe`](https://togithub.com/nodejs/node/commit/022352acbe)] - ***Revert*** "**deps**: upgrade to libuv 1.46.0" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`d9f138189c`](https://togithub.com/nodejs/node/commit/d9f138189c)] - ***Revert*** "**deps**: add missing thread-common.c in uv.gyp" (Richard Lau) [#&#8203;50036](https://togithub.com/nodejs/node/pull/50036) - \[[`7a3e1ffbb8`](https://togithub.com/nodejs/node/commit/7a3e1ffbb8)] - **fs**: make sure to write entire buffer (Robert Nagy) [#&#8203;49211](https://togithub.com/nodejs/node/pull/49211) - \[[`04cba95a67`](https://togithub.com/nodejs/node/commit/04cba95a67)] - **test**: add `tmpdir.resolve()` (Livia Medeiros) [#&#8203;49079](https://togithub.com/nodejs/node/pull/49079) </details> --- ### Configuration 📅 **Schedule**: Branch creation - "after 7pm every weekday,before 5am every weekday" in timezone Europe/Madrid, Automerge - At any time (no schedule defined). 🚦 **Automerge**: Enabled. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate](https://www.mend.io/free-developer-tools/renovate/). View repository job log [here](https://developer.mend.io/github/Unleash/unleash). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjMiLCJ1cGRhdGVkSW5WZXIiOiIzNy4xMjcuMCIsInRhcmdldEJyYW5jaCI6Im1haW4ifQ==--> --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Ivar Conradi Østhus <ivar@getunleash.ai>
2024-01-10 08:23:19 +01:00
poolMetricsTimer?: NodeJS.Timeout;
constructor() {
this.timer = undefined;
this.poolMetricsTimer = undefined;
}
startMonitoring(
config: IUnleashConfig,
stores: IUnleashStores,
version: string,
eventBus: EventEmitter,
instanceStatsService: InstanceStatsService,
db: Knex,
): Promise<void> {
if (!config.server.serverMetrics) {
return Promise.resolve();
}
const { eventStore, environmentStore } = stores;
const cachedEnvironments: () => Promise<IEnvironment[]> = memoizee(
async () => environmentStore.getAll(),
{
promise: true,
maxAge: hoursToMilliseconds(1),
},
);
2017-06-28 14:21:05 +02:00
client.collectDefaultMetrics();
const requestDuration = new client.Summary({
name: 'http_request_duration_milliseconds',
help: 'App response time',
labelNames: ['path', 'method', 'status', 'appName'],
percentiles: [0.1, 0.5, 0.9, 0.95, 0.99],
maxAgeSeconds: 600,
ageBuckets: 5,
});
const schedulerDuration = new client.Summary({
name: 'scheduler_duration_seconds',
help: 'Scheduler duration time',
labelNames: ['jobId'],
percentiles: [0.1, 0.5, 0.9, 0.95, 0.99],
maxAgeSeconds: 600,
ageBuckets: 5,
});
const dbDuration = new client.Summary({
name: 'db_query_duration_seconds',
help: 'DB query duration time',
labelNames: ['store', 'action'],
percentiles: [0.1, 0.5, 0.9, 0.95, 0.99],
maxAgeSeconds: 600,
ageBuckets: 5,
});
const featureToggleUpdateTotal = new client.Counter({
name: 'feature_toggle_update_total',
help: 'Number of times a toggle has been updated. Environment label would be "n/a" when it is not available, e.g. when a feature toggle is created.',
labelNames: ['toggle', 'project', 'environment', 'environmentType'],
});
const featureToggleUsageTotal = new client.Counter({
name: 'feature_toggle_usage_total',
help: 'Number of times a feature toggle has been used',
labelNames: ['toggle', 'active', 'appName'],
});
const featureTogglesTotal = new client.Gauge({
name: 'feature_toggles_total',
help: 'Number of feature toggles',
labelNames: ['version'],
});
2021-08-27 10:10:14 +02:00
const usersTotal = new client.Gauge({
name: 'users_total',
help: 'Number of users',
});
const serviceAccounts = new client.Gauge({
name: 'service_accounts_total',
help: 'Number of service accounts',
});
const apiTokens = new client.Gauge({
name: 'api_tokens_total',
help: 'Number of API tokens',
labelNames: ['type'],
});
const enabledMetricsBucketsPreviousDay = new client.Gauge({
name: 'enabled_metrics_buckets_previous_day',
help: 'Number of hourly enabled/disabled metric buckets in the previous day',
});
const variantMetricsBucketsPreviousDay = new client.Gauge({
name: 'variant_metrics_buckets_previous_day',
help: 'Number of hourly variant metric buckets in the previous day',
});
const usersActive7days = new client.Gauge({
name: 'users_active_7',
help: 'Number of users active in the last 7 days',
});
const usersActive30days = new client.Gauge({
name: 'users_active_30',
help: 'Number of users active in the last 30 days',
});
const usersActive60days = new client.Gauge({
name: 'users_active_60',
help: 'Number of users active in the last 60 days',
});
const usersActive90days = new client.Gauge({
name: 'users_active_90',
help: 'Number of users active in the last 90 days',
});
2021-08-27 10:10:14 +02:00
const projectsTotal = new client.Gauge({
name: 'projects_total',
help: 'Number of projects',
labelNames: ['mode'],
2021-08-27 10:10:14 +02:00
});
const environmentsTotal = new client.Gauge({
name: 'environments_total',
help: 'Number of environments',
});
const groupsTotal = new client.Gauge({
name: 'groups_total',
help: 'Number of groups',
});
const rolesTotal = new client.Gauge({
name: 'roles_total',
help: 'Number of roles',
});
const customRootRolesTotal = new client.Gauge({
name: 'custom_root_roles_total',
help: 'Number of custom root roles',
});
feat: add prom metric for total custom root roles in use (#4438) https://linear.app/unleash/issue/2-1311/add-a-new-prometheus-metric-with-custom-root-roles-in-use As a follow-up to https://github.com/Unleash/unleash/pull/4435, this PR adds a metric for total custom root roles in use by at least one entity: users, service accounts, groups. `custom_root_roles_in_use_total` Output from `http://localhost:4242/internal-backstage/prometheus`: ``` # HELP process_cpu_user_seconds_total Total user CPU time spent in seconds. # TYPE process_cpu_user_seconds_total counter process_cpu_user_seconds_total 0.060755 # HELP process_cpu_system_seconds_total Total system CPU time spent in seconds. # TYPE process_cpu_system_seconds_total counter process_cpu_system_seconds_total 0.01666 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 0.077415 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1691420275 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 199196672 # HELP nodejs_eventloop_lag_seconds Lag of event loop in seconds. # TYPE nodejs_eventloop_lag_seconds gauge nodejs_eventloop_lag_seconds 0 # HELP nodejs_eventloop_lag_min_seconds The minimum recorded event loop delay. # TYPE nodejs_eventloop_lag_min_seconds gauge nodejs_eventloop_lag_min_seconds 0.009076736 # HELP nodejs_eventloop_lag_max_seconds The maximum recorded event loop delay. # TYPE nodejs_eventloop_lag_max_seconds gauge nodejs_eventloop_lag_max_seconds 0.037683199 # HELP nodejs_eventloop_lag_mean_seconds The mean of the recorded event loop delays. # TYPE nodejs_eventloop_lag_mean_seconds gauge nodejs_eventloop_lag_mean_seconds 0.011063251638989169 # HELP nodejs_eventloop_lag_stddev_seconds The standard deviation of the recorded event loop delays. # TYPE nodejs_eventloop_lag_stddev_seconds gauge nodejs_eventloop_lag_stddev_seconds 0.0013618102764025837 # HELP nodejs_eventloop_lag_p50_seconds The 50th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p50_seconds gauge nodejs_eventloop_lag_p50_seconds 0.011051007 # HELP nodejs_eventloop_lag_p90_seconds The 90th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p90_seconds gauge nodejs_eventloop_lag_p90_seconds 0.011321343 # HELP nodejs_eventloop_lag_p99_seconds The 99th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p99_seconds gauge nodejs_eventloop_lag_p99_seconds 0.013688831 # HELP nodejs_active_resources Number of active resources that are currently keeping the event loop alive, grouped by async resource type. # TYPE nodejs_active_resources gauge nodejs_active_resources{type="FSReqCallback"} 1 nodejs_active_resources{type="TTYWrap"} 3 nodejs_active_resources{type="TCPSocketWrap"} 5 nodejs_active_resources{type="TCPServerWrap"} 1 nodejs_active_resources{type="Timeout"} 1 nodejs_active_resources{type="Immediate"} 1 # HELP nodejs_active_resources_total Total number of active resources. # TYPE nodejs_active_resources_total gauge nodejs_active_resources_total 12 # HELP nodejs_active_handles Number of active libuv handles grouped by handle type. Every handle type is C++ class name. # TYPE nodejs_active_handles gauge nodejs_active_handles{type="WriteStream"} 2 nodejs_active_handles{type="ReadStream"} 1 nodejs_active_handles{type="Socket"} 5 nodejs_active_handles{type="Server"} 1 # HELP nodejs_active_handles_total Total number of active handles. # TYPE nodejs_active_handles_total gauge nodejs_active_handles_total 9 # HELP nodejs_active_requests Number of active libuv requests grouped by request type. Every request type is C++ class name. # TYPE nodejs_active_requests gauge nodejs_active_requests{type="FSReqCallback"} 1 # HELP nodejs_active_requests_total Total number of active requests. # TYPE nodejs_active_requests_total gauge nodejs_active_requests_total 1 # HELP nodejs_heap_size_total_bytes Process heap size from Node.js in bytes. # TYPE nodejs_heap_size_total_bytes gauge nodejs_heap_size_total_bytes 118587392 # HELP nodejs_heap_size_used_bytes Process heap size used from Node.js in bytes. # TYPE nodejs_heap_size_used_bytes gauge nodejs_heap_size_used_bytes 89642552 # HELP nodejs_external_memory_bytes Node.js external memory size in bytes. # TYPE nodejs_external_memory_bytes gauge nodejs_external_memory_bytes 1601594 # HELP nodejs_heap_space_size_total_bytes Process heap space size total from Node.js in bytes. # TYPE nodejs_heap_space_size_total_bytes gauge nodejs_heap_space_size_total_bytes{space="read_only"} 0 nodejs_heap_space_size_total_bytes{space="old"} 70139904 nodejs_heap_space_size_total_bytes{space="code"} 3588096 nodejs_heap_space_size_total_bytes{space="map"} 2899968 nodejs_heap_space_size_total_bytes{space="large_object"} 7258112 nodejs_heap_space_size_total_bytes{space="code_large_object"} 1146880 nodejs_heap_space_size_total_bytes{space="new_large_object"} 0 nodejs_heap_space_size_total_bytes{space="new"} 33554432 # HELP nodejs_heap_space_size_used_bytes Process heap space size used from Node.js in bytes. # TYPE nodejs_heap_space_size_used_bytes gauge nodejs_heap_space_size_used_bytes{space="read_only"} 0 nodejs_heap_space_size_used_bytes{space="old"} 66992120 nodejs_heap_space_size_used_bytes{space="code"} 2892640 nodejs_heap_space_size_used_bytes{space="map"} 2519280 nodejs_heap_space_size_used_bytes{space="large_object"} 7026824 nodejs_heap_space_size_used_bytes{space="code_large_object"} 983200 nodejs_heap_space_size_used_bytes{space="new_large_object"} 0 nodejs_heap_space_size_used_bytes{space="new"} 9236136 # HELP nodejs_heap_space_size_available_bytes Process heap space size available from Node.js in bytes. # TYPE nodejs_heap_space_size_available_bytes gauge nodejs_heap_space_size_available_bytes{space="read_only"} 0 nodejs_heap_space_size_available_bytes{space="old"} 1898360 nodejs_heap_space_size_available_bytes{space="code"} 7328 nodejs_heap_space_size_available_bytes{space="map"} 327888 nodejs_heap_space_size_available_bytes{space="large_object"} 0 nodejs_heap_space_size_available_bytes{space="code_large_object"} 0 nodejs_heap_space_size_available_bytes{space="new_large_object"} 16495616 nodejs_heap_space_size_available_bytes{space="new"} 7259480 # HELP nodejs_version_info Node.js version info. # TYPE nodejs_version_info gauge nodejs_version_info{version="v18.16.0",major="18",minor="16",patch="0"} 1 # HELP nodejs_gc_duration_seconds Garbage collection duration by kind, one of major, minor, incremental or weakcb. # TYPE nodejs_gc_duration_seconds histogram # HELP http_request_duration_milliseconds App response time # TYPE http_request_duration_milliseconds summary # HELP db_query_duration_seconds DB query duration time # TYPE db_query_duration_seconds summary db_query_duration_seconds{quantile="0.1",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.5",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.9",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.95",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.99",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds_sum{store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds_count{store="api-tokens",action="getAllActive"} 1 # HELP feature_toggle_update_total Number of times a toggle has been updated. Environment label would be "n/a" when it is not available, e.g. when a feature toggle is created. # TYPE feature_toggle_update_total counter # HELP feature_toggle_usage_total Number of times a feature toggle has been used # TYPE feature_toggle_usage_total counter # HELP feature_toggles_total Number of feature toggles # TYPE feature_toggles_total gauge feature_toggles_total{version="5.3.0"} 31 # HELP users_total Number of users # TYPE users_total gauge users_total 1011 # HELP projects_total Number of projects # TYPE projects_total gauge projects_total 4 # HELP environments_total Number of environments # TYPE environments_total gauge environments_total 10 # HELP groups_total Number of groups # TYPE groups_total gauge groups_total 5 # HELP roles_total Number of roles # TYPE roles_total gauge roles_total 11 # HELP custom_root_roles_total Number of custom root roles # TYPE custom_root_roles_total gauge custom_root_roles_total 3 # HELP custom_root_roles_in_use_total Number of custom root roles in use # TYPE custom_root_roles_in_use_total gauge custom_root_roles_in_use_total 2 # HELP segments_total Number of segments # TYPE segments_total gauge segments_total 5 # HELP context_total Number of context # TYPE context_total gauge context_total 7 # HELP strategies_total Number of strategies # TYPE strategies_total gauge strategies_total 5 # HELP client_apps_total Number of registered client apps aggregated by range by last seen # TYPE client_apps_total gauge client_apps_total{range="allTime"} 0 client_apps_total{range="30d"} 0 client_apps_total{range="7d"} 0 # HELP saml_enabled Whether SAML is enabled # TYPE saml_enabled gauge saml_enabled 1 # HELP oidc_enabled Whether OIDC is enabled # TYPE oidc_enabled gauge oidc_enabled 0 # HELP client_sdk_versions Which sdk versions are being used # TYPE client_sdk_versions counter # HELP optimal_304_diffing Count the Optimal 304 diffing with status # TYPE optimal_304_diffing counter # HELP db_pool_min Minimum DB pool size # TYPE db_pool_min gauge db_pool_min 0 # HELP db_pool_max Maximum DB pool size # TYPE db_pool_max gauge db_pool_max 4 # HELP db_pool_free Current free connections in DB pool # TYPE db_pool_free gauge db_pool_free 0 # HELP db_pool_used Current connections in use in DB pool # TYPE db_pool_used gauge db_pool_used 4 # HELP db_pool_pending_creates how many asynchronous create calls are running in DB pool # TYPE db_pool_pending_creates gauge db_pool_pending_creates 0 # HELP db_pool_pending_acquires how many acquires are waiting for a resource to be released in DB pool # TYPE db_pool_pending_acquires gauge db_pool_pending_acquires 24 ```
2023-08-08 09:14:40 +02:00
const customRootRolesInUseTotal = new client.Gauge({
name: 'custom_root_roles_in_use_total',
help: 'Number of custom root roles in use',
});
const segmentsTotal = new client.Gauge({
name: 'segments_total',
help: 'Number of segments',
});
const contextTotal = new client.Gauge({
name: 'context_total',
help: 'Number of context',
});
const strategiesTotal = new client.Gauge({
name: 'strategies_total',
help: 'Number of strategies',
});
const clientAppsTotal = new client.Gauge({
name: 'client_apps_total',
help: 'Number of registered client apps aggregated by range by last seen',
labelNames: ['range'],
});
const samlEnabled = new client.Gauge({
name: 'saml_enabled',
help: 'Whether SAML is enabled',
});
const oidcEnabled = new client.Gauge({
name: 'oidc_enabled',
help: 'Whether OIDC is enabled',
});
const clientSdkVersionUsage = new client.Counter({
name: 'client_sdk_versions',
help: 'Which sdk versions are being used',
labelNames: ['sdk_name', 'sdk_version'],
});
const productionChanges30 = new client.Gauge({
name: 'production_changes_30',
help: 'Changes made to production environment last 30 days',
labelNames: ['environment'],
});
const productionChanges60 = new client.Gauge({
name: 'production_changes_60',
help: 'Changes made to production environment last 60 days',
labelNames: ['environment'],
});
const productionChanges90 = new client.Gauge({
name: 'production_changes_90',
help: 'Changes made to production environment last 90 days',
labelNames: ['environment'],
});
const rateLimits = new client.Gauge({
name: 'rate_limits',
help: 'Rate limits (per minute) for METHOD/ENDPOINT pairs',
labelNames: ['endpoint', 'method'],
});
2021-08-27 10:10:14 +02:00
async function collectStaticCounters() {
try {
const stats = await instanceStatsService.getStats();
featureTogglesTotal.reset();
featureTogglesTotal.labels(version).set(stats.featureToggles);
2021-08-27 10:10:14 +02:00
usersTotal.reset();
usersTotal.set(stats.users);
serviceAccounts.reset();
serviceAccounts.set(stats.serviceAccounts);
apiTokens.reset();
for (const [type, value] of stats.apiTokens) {
apiTokens.labels(type).set(value);
}
enabledMetricsBucketsPreviousDay.reset();
enabledMetricsBucketsPreviousDay.set(
stats.previousDayMetricsBucketsCount.enabledCount,
);
variantMetricsBucketsPreviousDay.reset();
variantMetricsBucketsPreviousDay.set(
stats.previousDayMetricsBucketsCount.variantCount,
);
usersActive7days.reset();
usersActive7days.set(stats.activeUsers.last7);
usersActive30days.reset();
usersActive30days.set(stats.activeUsers.last30);
usersActive60days.reset();
usersActive60days.set(stats.activeUsers.last60);
usersActive90days.reset();
usersActive90days.set(stats.activeUsers.last90);
productionChanges30.reset();
productionChanges30.set(stats.productionChanges.last30);
productionChanges60.reset();
productionChanges60.set(stats.productionChanges.last60);
productionChanges90.reset();
productionChanges90.set(stats.productionChanges.last90);
2021-08-27 10:10:14 +02:00
projectsTotal.reset();
stats.projects.forEach((projectStat) => {
projectsTotal
.labels({ mode: projectStat.mode })
.set(projectStat.count);
});
environmentsTotal.reset();
environmentsTotal.set(stats.environments);
groupsTotal.reset();
groupsTotal.set(stats.groups);
rolesTotal.reset();
rolesTotal.set(stats.roles);
customRootRolesTotal.reset();
customRootRolesTotal.set(stats.customRootRoles);
feat: add prom metric for total custom root roles in use (#4438) https://linear.app/unleash/issue/2-1311/add-a-new-prometheus-metric-with-custom-root-roles-in-use As a follow-up to https://github.com/Unleash/unleash/pull/4435, this PR adds a metric for total custom root roles in use by at least one entity: users, service accounts, groups. `custom_root_roles_in_use_total` Output from `http://localhost:4242/internal-backstage/prometheus`: ``` # HELP process_cpu_user_seconds_total Total user CPU time spent in seconds. # TYPE process_cpu_user_seconds_total counter process_cpu_user_seconds_total 0.060755 # HELP process_cpu_system_seconds_total Total system CPU time spent in seconds. # TYPE process_cpu_system_seconds_total counter process_cpu_system_seconds_total 0.01666 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 0.077415 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1691420275 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 199196672 # HELP nodejs_eventloop_lag_seconds Lag of event loop in seconds. # TYPE nodejs_eventloop_lag_seconds gauge nodejs_eventloop_lag_seconds 0 # HELP nodejs_eventloop_lag_min_seconds The minimum recorded event loop delay. # TYPE nodejs_eventloop_lag_min_seconds gauge nodejs_eventloop_lag_min_seconds 0.009076736 # HELP nodejs_eventloop_lag_max_seconds The maximum recorded event loop delay. # TYPE nodejs_eventloop_lag_max_seconds gauge nodejs_eventloop_lag_max_seconds 0.037683199 # HELP nodejs_eventloop_lag_mean_seconds The mean of the recorded event loop delays. # TYPE nodejs_eventloop_lag_mean_seconds gauge nodejs_eventloop_lag_mean_seconds 0.011063251638989169 # HELP nodejs_eventloop_lag_stddev_seconds The standard deviation of the recorded event loop delays. # TYPE nodejs_eventloop_lag_stddev_seconds gauge nodejs_eventloop_lag_stddev_seconds 0.0013618102764025837 # HELP nodejs_eventloop_lag_p50_seconds The 50th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p50_seconds gauge nodejs_eventloop_lag_p50_seconds 0.011051007 # HELP nodejs_eventloop_lag_p90_seconds The 90th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p90_seconds gauge nodejs_eventloop_lag_p90_seconds 0.011321343 # HELP nodejs_eventloop_lag_p99_seconds The 99th percentile of the recorded event loop delays. # TYPE nodejs_eventloop_lag_p99_seconds gauge nodejs_eventloop_lag_p99_seconds 0.013688831 # HELP nodejs_active_resources Number of active resources that are currently keeping the event loop alive, grouped by async resource type. # TYPE nodejs_active_resources gauge nodejs_active_resources{type="FSReqCallback"} 1 nodejs_active_resources{type="TTYWrap"} 3 nodejs_active_resources{type="TCPSocketWrap"} 5 nodejs_active_resources{type="TCPServerWrap"} 1 nodejs_active_resources{type="Timeout"} 1 nodejs_active_resources{type="Immediate"} 1 # HELP nodejs_active_resources_total Total number of active resources. # TYPE nodejs_active_resources_total gauge nodejs_active_resources_total 12 # HELP nodejs_active_handles Number of active libuv handles grouped by handle type. Every handle type is C++ class name. # TYPE nodejs_active_handles gauge nodejs_active_handles{type="WriteStream"} 2 nodejs_active_handles{type="ReadStream"} 1 nodejs_active_handles{type="Socket"} 5 nodejs_active_handles{type="Server"} 1 # HELP nodejs_active_handles_total Total number of active handles. # TYPE nodejs_active_handles_total gauge nodejs_active_handles_total 9 # HELP nodejs_active_requests Number of active libuv requests grouped by request type. Every request type is C++ class name. # TYPE nodejs_active_requests gauge nodejs_active_requests{type="FSReqCallback"} 1 # HELP nodejs_active_requests_total Total number of active requests. # TYPE nodejs_active_requests_total gauge nodejs_active_requests_total 1 # HELP nodejs_heap_size_total_bytes Process heap size from Node.js in bytes. # TYPE nodejs_heap_size_total_bytes gauge nodejs_heap_size_total_bytes 118587392 # HELP nodejs_heap_size_used_bytes Process heap size used from Node.js in bytes. # TYPE nodejs_heap_size_used_bytes gauge nodejs_heap_size_used_bytes 89642552 # HELP nodejs_external_memory_bytes Node.js external memory size in bytes. # TYPE nodejs_external_memory_bytes gauge nodejs_external_memory_bytes 1601594 # HELP nodejs_heap_space_size_total_bytes Process heap space size total from Node.js in bytes. # TYPE nodejs_heap_space_size_total_bytes gauge nodejs_heap_space_size_total_bytes{space="read_only"} 0 nodejs_heap_space_size_total_bytes{space="old"} 70139904 nodejs_heap_space_size_total_bytes{space="code"} 3588096 nodejs_heap_space_size_total_bytes{space="map"} 2899968 nodejs_heap_space_size_total_bytes{space="large_object"} 7258112 nodejs_heap_space_size_total_bytes{space="code_large_object"} 1146880 nodejs_heap_space_size_total_bytes{space="new_large_object"} 0 nodejs_heap_space_size_total_bytes{space="new"} 33554432 # HELP nodejs_heap_space_size_used_bytes Process heap space size used from Node.js in bytes. # TYPE nodejs_heap_space_size_used_bytes gauge nodejs_heap_space_size_used_bytes{space="read_only"} 0 nodejs_heap_space_size_used_bytes{space="old"} 66992120 nodejs_heap_space_size_used_bytes{space="code"} 2892640 nodejs_heap_space_size_used_bytes{space="map"} 2519280 nodejs_heap_space_size_used_bytes{space="large_object"} 7026824 nodejs_heap_space_size_used_bytes{space="code_large_object"} 983200 nodejs_heap_space_size_used_bytes{space="new_large_object"} 0 nodejs_heap_space_size_used_bytes{space="new"} 9236136 # HELP nodejs_heap_space_size_available_bytes Process heap space size available from Node.js in bytes. # TYPE nodejs_heap_space_size_available_bytes gauge nodejs_heap_space_size_available_bytes{space="read_only"} 0 nodejs_heap_space_size_available_bytes{space="old"} 1898360 nodejs_heap_space_size_available_bytes{space="code"} 7328 nodejs_heap_space_size_available_bytes{space="map"} 327888 nodejs_heap_space_size_available_bytes{space="large_object"} 0 nodejs_heap_space_size_available_bytes{space="code_large_object"} 0 nodejs_heap_space_size_available_bytes{space="new_large_object"} 16495616 nodejs_heap_space_size_available_bytes{space="new"} 7259480 # HELP nodejs_version_info Node.js version info. # TYPE nodejs_version_info gauge nodejs_version_info{version="v18.16.0",major="18",minor="16",patch="0"} 1 # HELP nodejs_gc_duration_seconds Garbage collection duration by kind, one of major, minor, incremental or weakcb. # TYPE nodejs_gc_duration_seconds histogram # HELP http_request_duration_milliseconds App response time # TYPE http_request_duration_milliseconds summary # HELP db_query_duration_seconds DB query duration time # TYPE db_query_duration_seconds summary db_query_duration_seconds{quantile="0.1",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.5",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.9",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.95",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds{quantile="0.99",store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds_sum{store="api-tokens",action="getAllActive"} 0.03091475 db_query_duration_seconds_count{store="api-tokens",action="getAllActive"} 1 # HELP feature_toggle_update_total Number of times a toggle has been updated. Environment label would be "n/a" when it is not available, e.g. when a feature toggle is created. # TYPE feature_toggle_update_total counter # HELP feature_toggle_usage_total Number of times a feature toggle has been used # TYPE feature_toggle_usage_total counter # HELP feature_toggles_total Number of feature toggles # TYPE feature_toggles_total gauge feature_toggles_total{version="5.3.0"} 31 # HELP users_total Number of users # TYPE users_total gauge users_total 1011 # HELP projects_total Number of projects # TYPE projects_total gauge projects_total 4 # HELP environments_total Number of environments # TYPE environments_total gauge environments_total 10 # HELP groups_total Number of groups # TYPE groups_total gauge groups_total 5 # HELP roles_total Number of roles # TYPE roles_total gauge roles_total 11 # HELP custom_root_roles_total Number of custom root roles # TYPE custom_root_roles_total gauge custom_root_roles_total 3 # HELP custom_root_roles_in_use_total Number of custom root roles in use # TYPE custom_root_roles_in_use_total gauge custom_root_roles_in_use_total 2 # HELP segments_total Number of segments # TYPE segments_total gauge segments_total 5 # HELP context_total Number of context # TYPE context_total gauge context_total 7 # HELP strategies_total Number of strategies # TYPE strategies_total gauge strategies_total 5 # HELP client_apps_total Number of registered client apps aggregated by range by last seen # TYPE client_apps_total gauge client_apps_total{range="allTime"} 0 client_apps_total{range="30d"} 0 client_apps_total{range="7d"} 0 # HELP saml_enabled Whether SAML is enabled # TYPE saml_enabled gauge saml_enabled 1 # HELP oidc_enabled Whether OIDC is enabled # TYPE oidc_enabled gauge oidc_enabled 0 # HELP client_sdk_versions Which sdk versions are being used # TYPE client_sdk_versions counter # HELP optimal_304_diffing Count the Optimal 304 diffing with status # TYPE optimal_304_diffing counter # HELP db_pool_min Minimum DB pool size # TYPE db_pool_min gauge db_pool_min 0 # HELP db_pool_max Maximum DB pool size # TYPE db_pool_max gauge db_pool_max 4 # HELP db_pool_free Current free connections in DB pool # TYPE db_pool_free gauge db_pool_free 0 # HELP db_pool_used Current connections in use in DB pool # TYPE db_pool_used gauge db_pool_used 4 # HELP db_pool_pending_creates how many asynchronous create calls are running in DB pool # TYPE db_pool_pending_creates gauge db_pool_pending_creates 0 # HELP db_pool_pending_acquires how many acquires are waiting for a resource to be released in DB pool # TYPE db_pool_pending_acquires gauge db_pool_pending_acquires 24 ```
2023-08-08 09:14:40 +02:00
customRootRolesInUseTotal.reset();
customRootRolesInUseTotal.set(stats.customRootRolesInUse);
segmentsTotal.reset();
segmentsTotal.set(stats.segments);
contextTotal.reset();
contextTotal.set(stats.contextFields);
strategiesTotal.reset();
strategiesTotal.set(stats.strategies);
samlEnabled.reset();
samlEnabled.set(stats.SAMLenabled ? 1 : 0);
oidcEnabled.reset();
oidcEnabled.set(stats.OIDCenabled ? 1 : 0);
clientAppsTotal.reset();
stats.clientApps.forEach((clientStat) =>
clientAppsTotal
.labels({ range: clientStat.range })
.set(clientStat.count),
);
rateLimits.reset();
rateLimits
.labels({ endpoint: '/api/client/metrics', method: 'POST' })
.set(config.metricsRateLimiting.clientMetricsMaxPerMinute);
rateLimits
.labels({
endpoint: '/api/client/register',
method: 'POST',
})
.set(config.metricsRateLimiting.clientRegisterMaxPerMinute);
rateLimits
.labels({
endpoint: '/api/frontend/metrics',
method: 'POST',
})
.set(
config.metricsRateLimiting.frontendMetricsMaxPerMinute,
);
rateLimits
.labels({
endpoint: '/api/frontend/register',
method: 'POST',
})
.set(
config.metricsRateLimiting.frontendRegisterMaxPerMinute,
);
rateLimits
.labels({
endpoint: '/api/admin/user-admin',
method: 'POST',
})
.set(config.rateLimiting.createUserMaxPerMinute);
rateLimits
.labels({ endpoint: '/auth/simple', method: 'POST' })
.set(config.rateLimiting.simpleLoginMaxPerMinute);
} catch (e) {}
}
process.nextTick(() => {
collectStaticCounters();
this.timer = setInterval(
() => collectStaticCounters(),
hoursToMilliseconds(2),
).unref();
});
eventBus.on(
events.REQUEST_TIME,
({ path, method, time, statusCode, appName }) => {
requestDuration
.labels(path, method, statusCode, appName)
.observe(time);
},
);
eventBus.on(events.SCHEDULER_JOB_TIME, ({ jobId, time }) => {
schedulerDuration.labels(jobId).observe(time);
});
eventBus.on(events.DB_TIME, ({ store, action, time }) => {
dbDuration.labels(store, action).observe(time);
});
eventStore.on(FEATURE_CREATED, ({ featureName, project }) => {
featureToggleUpdateTotal
.labels(featureName, project, 'n/a', 'n/a')
.inc();
});
eventStore.on(FEATURE_VARIANTS_UPDATED, ({ featureName, project }) => {
featureToggleUpdateTotal
.labels(featureName, project, 'n/a', 'n/a')
.inc();
});
eventStore.on(FEATURE_METADATA_UPDATED, ({ featureName, project }) => {
featureToggleUpdateTotal
.labels(featureName, project, 'n/a', 'n/a')
.inc();
});
eventStore.on(FEATURE_UPDATED, ({ featureName, project }) => {
featureToggleUpdateTotal
.labels(featureName, project, 'default', 'production')
.inc();
});
eventStore.on(
FEATURE_STRATEGY_ADD,
async ({ featureName, project, environment }) => {
const environmentType = await this.resolveEnvironmentType(
environment,
cachedEnvironments,
);
featureToggleUpdateTotal
.labels(featureName, project, environment, environmentType)
.inc();
},
);
eventStore.on(
FEATURE_STRATEGY_REMOVE,
async ({ featureName, project, environment }) => {
const environmentType = await this.resolveEnvironmentType(
environment,
cachedEnvironments,
);
featureToggleUpdateTotal
.labels(featureName, project, environment, environmentType)
.inc();
},
);
eventStore.on(
FEATURE_STRATEGY_UPDATE,
async ({ featureName, project, environment }) => {
const environmentType = await this.resolveEnvironmentType(
environment,
cachedEnvironments,
);
featureToggleUpdateTotal
.labels(featureName, project, environment, environmentType)
.inc();
},
);
eventStore.on(
FEATURE_ENVIRONMENT_DISABLED,
async ({ featureName, project, environment }) => {
const environmentType = await this.resolveEnvironmentType(
environment,
cachedEnvironments,
);
featureToggleUpdateTotal
.labels(featureName, project, environment, environmentType)
.inc();
},
);
eventStore.on(
FEATURE_ENVIRONMENT_ENABLED,
async ({ featureName, project, environment }) => {
const environmentType = await this.resolveEnvironmentType(
environment,
cachedEnvironments,
);
featureToggleUpdateTotal
.labels(featureName, project, environment, environmentType)
.inc();
},
);
eventStore.on(FEATURE_ARCHIVED, ({ featureName, project }) => {
featureToggleUpdateTotal.labels(featureName, project, 'n/a').inc();
});
eventStore.on(FEATURE_REVIVED, ({ featureName, project }) => {
featureToggleUpdateTotal.labels(featureName, project, 'n/a').inc();
});
eventBus.on(CLIENT_METRICS, (m: ValidatedClientMetrics) => {
for (const entry of Object.entries(m.bucket.toggles)) {
featureToggleUsageTotal
.labels(entry[0], 'true', m.appName)
.inc(entry[1].yes);
featureToggleUsageTotal
.labels(entry[0], 'false', m.appName)
.inc(entry[1].no);
}
});
eventStore.on(CLIENT_REGISTER, (m) => {
if (m.sdkVersion && m.sdkVersion.indexOf(':') > -1) {
const [sdkName, sdkVersion] = m.sdkVersion.split(':');
clientSdkVersionUsage.labels(sdkName, sdkVersion).inc();
}
});
this.configureDbMetrics(db, eventBus);
return Promise.resolve();
}
stopMonitoring(): void {
clearInterval(this.timer);
clearInterval(this.poolMetricsTimer);
}
configureDbMetrics(db: Knex, eventBus: EventEmitter): void {
if (db?.client) {
const dbPoolMin = new client.Gauge({
name: 'db_pool_min',
help: 'Minimum DB pool size',
});
dbPoolMin.set(db.client.pool.min);
const dbPoolMax = new client.Gauge({
name: 'db_pool_max',
help: 'Maximum DB pool size',
});
dbPoolMax.set(db.client.pool.max);
const dbPoolFree = new client.Gauge({
name: 'db_pool_free',
help: 'Current free connections in DB pool',
});
const dbPoolUsed = new client.Gauge({
name: 'db_pool_used',
help: 'Current connections in use in DB pool',
});
const dbPoolPendingCreates = new client.Gauge({
name: 'db_pool_pending_creates',
help: 'how many asynchronous create calls are running in DB pool',
});
const dbPoolPendingAcquires = new client.Gauge({
name: 'db_pool_pending_acquires',
help: 'how many acquires are waiting for a resource to be released in DB pool',
});
eventBus.on(DB_POOL_UPDATE, (data) => {
dbPoolFree.set(data.free);
dbPoolUsed.set(data.used);
dbPoolPendingCreates.set(data.pendingCreates);
dbPoolPendingAcquires.set(data.pendingAcquires);
});
this.registerPoolMetrics(db.client.pool, eventBus);
this.poolMetricsTimer = setInterval(
() => this.registerPoolMetrics(db.client.pool, eventBus),
minutesToMilliseconds(1),
);
this.poolMetricsTimer.unref();
}
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
registerPoolMetrics(pool: any, eventBus: EventEmitter) {
try {
eventBus.emit(DB_POOL_UPDATE, {
used: pool.numUsed(),
free: pool.numFree(),
pendingCreates: pool.numPendingCreates(),
pendingAcquires: pool.numPendingAcquires(),
});
// eslint-disable-next-line no-empty
} catch (e) {}
}
async resolveEnvironmentType(
environment: string,
cachedEnvironments: () => Promise<IEnvironment[]>,
): Promise<string> {
const environments = await cachedEnvironments();
const env = environments.find((e) => e.name === environment);
if (env) {
return env.type;
} else {
return 'unknown';
}
}
}
export function createMetricsMonitor(): MetricsMonitor {
return new MetricsMonitor();
}
module.exports = {
createMetricsMonitor,
2016-12-04 14:09:37 +01:00
};