All files / src/mixins metrics.prometheus.service.js

7.5% Statements 3/40
0% Branches 0/23
0% Functions 0/10
8.11% Lines 3/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188          5x 5x                   5x                                                                                                                                                                                                                                                                                                                                                      
/*
 * prometheus addons
 */
 
"use strict";
import * as MetricsBase from "./metrics.base";
import { PromClient } from "../drivers/PromClient";
/**
 *  metrics module for Prometheus.
 *
 *      https://prometheus.io/
 *
 *
 * @name moleculer-prometheus
 * @module Service
 */
module.exports = {
    name: "prometheus",
    version: 1,
    mixins: [MetricsBase],
    /**
     * Default settings
     */
    settings: {
        /** @type {Boolean} Enable to collect default metrics. */
        collectDefaultMetrics: true,
 
        /** @type {Number} Timeout option for 'collectDefaultMetrics'. */
        collectDefaultMetricsTimeout: 10 * 1000,
 
        /** @type {Number} push metrics to gateway every ms. */
        prometheusPushInterval: 5000,
        /**
         * Generate labels to group metrics by
         * @return key-value pairs of labels
         * (will have the current broker context)
         */
        prometheusPushGroupBy() {
            return {
                instance: this.broker.nodeID,
                namespace: this.broker.namespace
            };
        },
        /** @type {Object} Metric definitions. */
        metrics: {}
    },
    /**
     * Events
     */
    events: {
        /** custom events */
        // 'metrics.create'(metricsDefs) {
        //  // USE settings instead
        // },
        "metrics.update"(payload) {
            this.updateMetrics(
                payload.name,
                payload.method,
                payload.labels,
                payload.value,
                payload.timestamp
            );
        }
    },
    /**
     * Methods
     */
    methods: {
        /**
         * Create Prometheus metrics.
         *
         * @param {Object} metricsDefs
         */
        createMetrics(metricsDefs) {
            if (!metricsDefs) return;
 
            Object.keys(metricsDefs).map(name => {
                const def = metricsDefs[name];
 
                if (!def || typeof def.type !== "string") return; //invalid defination
 
                this.broker.logger.info(`Creating metric ${name}`);
 
                //create or reuse
                try {
                    this.metrics[name] = new this.prometheus.client[def.type](
                        Object.assign({ name }, def)
                    );
                } catch (err) {
                    if (
                        err.message ===
                        `A metric with the name ${name} has already been registered.`
                    ) {
                        this.metrics[
                            name
                        ] = this.prometheus.client.register.getSingleMetric(
                            name
                        ); //get a reference to a previously registered metric
                    } else {
                        throw err; //bubble up unknown errors
                    }
                }
            });
        },
        /**
         * Update a metric value.
         *
         * @methods
         * @param {String} name
         * @param {String} method
         * @param {Object?} labels
         * @param {any} value
         * @param {any} timestamp
         */
        updateMetrics(name, method, labels, value, timestamp) {
            if (this.metrics[name]) {
                this.broker.logger.debug("Updating metric %s", name);
                if (labels)
                    this.metrics[name][method](labels, value, timestamp);
                else this.metrics[name][method](value, timestamp);
            }
        }
    },
 
    /**
     * Service created lifecycle event handler
     */
    created() {
        if (
            this.settings.prometheus &&
            this.settings.prometheus.client &&
            this.settings.prometheus.pushgateway
        ) {
            this.prometheus = this.settings.prometheus;
        } else {
            this.prometheus = PromClient.Instance; //singleton..., multiple services mixin this one would use the same instance!
        }
 
        this.metrics = {};
    },
 
    /**
     * Service started lifecycle event handler
     */
    started() {
        this.createMetrics(this.settings.metrics);
 
        if (this.settings.collectDefaultMetrics) {
            this.defaultMetrics_timer = this.prometheus.client.collectDefaultMetrics(
                {
                    timeout: this.settings.collectDefaultMetricsTimeout
                }
            );
        }
        //auto push to prometheus gateway
        let my = this;
        my.prometheus_push_timer = setInterval(() => {
            my.prometheus.pushgateway.push(
                {
                    jobName: `v${my.version}.${my.name}`,
                    groupings: this.settings.prometheusPushGroupBy.call(this)
                },
                err => {
                    if (err) return this.broker.logger.error(err);
                    this.broker.logger.debug(
                        `Pushed metrics to gateway @${
                            my.prometheus.pushgateway.gatewayUrl
                        }`
                    );
                }
            );
        }, my.settings.prometheusPushInterval);
    },
 
    /**
     * Service stopped lifecycle event handler
     */
    stopped() {
        if (this.defaultMetrics_timer) {
            clearInterval(this.defaultMetrics_timer);
            this.defaultMetrics_timer = null;
        }
 
        clearInterval(this.prometheus_push_timer);
        this.prometheus_push_timer = null;
    }
};