Python prometheus_client.CollectorRegistry() Examples

The following are 30 code examples for showing how to use prometheus_client.CollectorRegistry(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module prometheus_client , or try the search function .

Example 1
Project: django-prometheus   Author: korfuri   File: test_testutils.py    License: Apache License 2.0 9 votes vote down vote up
def setUp(self):
        self.registry = prometheus_client.CollectorRegistry()
        self.some_gauge = prometheus_client.Gauge(
            "some_gauge", "Some gauge.", registry=self.registry
        )
        self.some_gauge.set(42)
        self.some_labelled_gauge = prometheus_client.Gauge(
            "some_labelled_gauge",
            "Some labelled gauge.",
            ["labelred", "labelblue"],
            registry=self.registry,
        )
        self.some_labelled_gauge.labels("pink", "indigo").set(1)
        self.some_labelled_gauge.labels("pink", "royal").set(2)
        self.some_labelled_gauge.labels("carmin", "indigo").set(3)
        self.some_labelled_gauge.labels("carmin", "royal").set(4)
        self.test_case = SomeTestCase() 
Example 2
Project: CrawlerMonitor   Author: adrianyoung   File: monitor.py    License: MIT License 7 votes vote down vote up
def create_metric(self):
        # record app conf
        self.conf_info = Info('celery_conf_info','APP_CONF')
        self.conf_info_c = CollectorRegistry()

        # monitor worker info
        self.workers_info = Info('celery_workers_info', 'WORKER_INFO')
        self.workers_info_c = CollectorRegistry()

        # monitor worker info real-time
        self.workers_state = Gauge('celery_workers_state', 'WORKER_STATE', ['worker'])
        self.workers_state_c = CollectorRegistry()
        self.workers_processed = Gauge('celery_processed_tasks_total', 'WORKER_TASKS_PROCESSED', ['worker'])
        self.workers_processed_c = CollectorRegistry()
        self.workers_active = Gauge('celery_active_tasks_total', 'WORKER_TASKS_ACTIVE', ['worker'])
        self.workers_active_c = CollectorRegistry()

        # monitor tasks info
        self.tasks_counter = Counter('celery_tasks_total', 'TASK_COUNT_INFO', ['worker','task','result'])
        self.tasks_counter_c = CollectorRegistry()
        self.tasks_runtime = Summary('celery_tasks_seconds', 'TASK_RUNTIME', ['worker', 'task'])
        self.tasks_runtime_c = CollectorRegistry()
        self.tasks_info = Info('celery_tasks_info', 'TASK_INFO')
        self.tasks_info_c = CollectorRegistry() 
Example 3
Project: naz   Author: komuw   File: my_hook.py    License: MIT License 6 votes vote down vote up
def __init__(self) -> None:
        self.registry = prometheus_client.CollectorRegistry()
        _labels = ["project", "smpp_command", "state", "response_code"]
        self.counter = prometheus_client.Counter(
            name="number_of_messages",
            documentation="number of messages processed by naz.",
            labelnames=_labels,
            registry=self.registry,
        )
        self._LOOP: typing.Union[None, asyncio.events.AbstractEventLoop] = None
        self.thread_name_prefix = "naz_benchmarks_hook_pool"

        # go to prometheus dashboard(http://localhost:9000/) & you can run queries like:
        # 1. container_memory_rss{name="naz_cli", container_label_com_docker_compose_service="naz_cli"}
        # 2. container_memory_rss{name=~"naz_cli|message_producer"}
        # 3. number_of_messages_total{project="naz_benchmarks"}
        # 4. rate(number_of_messages_total{smpp_command="submit_sm",state="request"}[30s])  # msg sending over the past 30seconds 
Example 4
Project: zentral   Author: zentralopensource   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def get_prometheus_incidents_metrics():
    registry = CollectorRegistry()
    g = Gauge('zentral_incidents_count', 'Zentral incidents',
              ['name', 'id', 'severity', 'status', 'opened'],
              registry=registry)
    query = (
        "select count(*), "
        "i.id, i.name, i.severity, "
        "mi.status, (CASE WHEN mi.status in ('CLOSED', 'RESOLVED') THEN FALSE ELSE TRUE END) as opened "
        "from incidents_incident as i "
        "join incidents_machineincident as mi on (mi.incident_id = i.id) "
        "group by i.name, i.id, i.severity, mi.status, opened "
        "order by i.id, mi.status;"
    )
    cursor = connection.cursor()
    cursor.execute(query)
    columns = [col[0] for col in cursor.description]
    for row in cursor.fetchall():
        d = dict(zip(columns, row))
        d["severity"] = str(SEVERITY_CHOICES_DICT.get(d.pop("severity"), "Unknown"))
        d["status"] = str(STATUS_CHOICES_DICT.get(d.pop("status"), "Unknown"))
        d["opened"] = 'Y' if d["opened"] else 'N'
        count = d.pop('count')
        g.labels(**d).set(count)
    return registry 
Example 5
Project: dagster   Author: dagster-io   File: resources.py    License: Apache License 2.0 6 votes vote down vote up
def pushadd_to_gateway(self, job, grouping_key=None, handler=default_handler):
        '''PushAdd metrics to the given pushgateway.
        `job` is the job label to be attached to all pushed metrics
        `registry` is an instance of CollectorRegistry
        `grouping_key` please see the pushgateway documentation for details.
                    Defaults to None
        `handler` is an optional function which can be provided to perform
                requests to the 'gateway'.
                Defaults to None, in which case an http or https request
                will be carried out by a default handler.
                See the 'prometheus_client.push_to_gateway' documentation
                for implementation requirements.
        This replaces metrics with the same name, job and grouping_key.
        This uses the POST HTTP method.'''
        prometheus_client.pushadd_to_gateway(
            gateway=self.gateway,
            job=job,
            registry=self.registry,
            grouping_key=grouping_key,
            timeout=self.timeout,
            handler=handler,
        ) 
Example 6
Project: openstacksdk   Author: openstack   File: test_stats.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.statsd = StatsdFixture()
        self.useFixture(self.statsd)
        # note, use 127.0.0.1 rather than localhost to avoid getting ipv6
        # see: https://github.com/jsocol/pystatsd/issues/61
        self.useFixture(
            fixtures.EnvironmentVariable('STATSD_HOST', '127.0.0.1'))
        self.useFixture(
            fixtures.EnvironmentVariable('STATSD_PORT', str(self.statsd.port)))

        self.add_info_on_exception('statsd_content', self.statsd.stats)
        # Set up the above things before the super setup so that we have the
        # environment variables set when the Connection is created.
        super(TestStats, self).setUp()

        self._registry = prometheus_client.CollectorRegistry()
        self.cloud.config._collector_registry = self._registry
        self.addOnException(self._add_prometheus_samples) 
Example 7
Project: client_python   Author: prometheus   File: test_graphite_bridge.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.registry = CollectorRegistry()

        self.data = ''

        class TCPHandler(SocketServer.BaseRequestHandler):
            def handle(s):
                self.data = s.request.recv(1024)

        server = SocketServer.TCPServer(('', 0), TCPHandler)

        class ServingThread(threading.Thread):
            def run(self):
                server.handle_request()
                server.socket.close()

        self.t = ServingThread()
        self.t.start()

        # Explicitly use localhost as the target host, since connecting to 0.0.0.0 fails on Windows
        address = ('localhost', server.server_address[1])
        self.gb = GraphiteBridge(address, self.registry, _timer=fake_timer) 
Example 8
def __init__(self):
        self.registry = CollectorRegistry()
        self.prodstack = {}
        with open(config['cache_file'], 'rb') as f:
            self.prodstack = pickle.load(f)[0]
        self.hypervisors = self.prodstack['hypervisors']
        self.tenant_map = {t['id']: t['name'] for t in self.prodstack['tenants']}
        self.flavor_map = {f['id']: {'ram': f['ram'], 'disk': f['disk'], 'vcpus': f['vcpus']}
                           for f in self.prodstack['flavors']}
        self.aggregate_map = {}
        self.services_map = {}
        for s in self.prodstack['services']:
            if s['binary'] == 'nova-compute':
                self.services_map[s['host']] = s['status']
        for agg in self.prodstack['aggregates']:
            self.aggregate_map.update({i: agg['name'] for i in agg['hosts']}) 
Example 9
Project: prometheus-openstack-exporter   Author: att-comdev   File: nova_services.py    License: Apache License 2.0 6 votes vote down vote up
def get_stats(self):
        registry = CollectorRegistry()
        labels = ['region', 'host', 'service', 'state']
        services_stats_cache = self.get_cache_data()
        for services_stat in services_stats_cache:
            stat_gauge = Gauge(
                self.gauge_name_sanitize(
                    services_stat['stat_name']),
                'Openstack Nova Service statistic',
                labels,
                registry=registry)
            label_values = [self.osclient.region,
                            services_stat.get('host', ''),
                            services_stat.get('service', ''),
                            services_stat.get('state', '')]
            stat_gauge.labels(*label_values).set(services_stat['stat_value'])
        return generate_latest(registry) 
Example 10
Project: prometheus-openstack-exporter   Author: att-comdev   File: cinder_services.py    License: Apache License 2.0 6 votes vote down vote up
def get_stats(self):
        registry = CollectorRegistry()
        labels = ['region', 'host', 'service', 'state']
        cinder_services_stats_cache = self.get_cache_data()
        for cinder_services_stat in cinder_services_stats_cache:
            stat_gauge = Gauge(
                self.gauge_name_sanitize(
                    cinder_services_stat['stat_name']),
                'Openstack Cinder Service statistic',
                labels,
                registry=registry)
            label_values = [self.osclient.region,
                            cinder_services_stat.get('host', ''),
                            cinder_services_stat.get('service', ''),
                            cinder_services_stat.get('state', '')]
            stat_gauge.labels(
                *
                label_values).set(
                cinder_services_stat['stat_value'])
        return generate_latest(registry) 
Example 11
Project: prometheus-openstack-exporter   Author: att-comdev   File: check_os_api.py    License: Apache License 2.0 6 votes vote down vote up
def get_stats(self):
        registry = CollectorRegistry()
        labels = ['region', 'url', 'service']
        check_api_data_cache = self.get_cache_data()
        for check_api_data in check_api_data_cache:
            label_values = [
                check_api_data['region'],
                check_api_data['url'],
                check_api_data['service']]
            gague_name = self.gauge_name_sanitize(
                "check_{}_api".format(check_api_data['service']))
            check_gauge = Gauge(
                gague_name,
                'Openstack API check. fail = 0, ok = 1 and unknown = 2',
                labels,
                registry=registry)
            check_gauge.labels(*label_values).set(check_api_data['status'])
        return generate_latest(registry) 
Example 12
Project: prometheus-openstack-exporter   Author: att-comdev   File: neutron_agents.py    License: Apache License 2.0 6 votes vote down vote up
def get_stats(self):
        registry = CollectorRegistry()
        labels = ['region', 'host', 'service', 'state']
        neutron_agent_stats_cache = self.get_cache_data()
        for neutron_agent_stat in neutron_agent_stats_cache:
            stat_gauge = Gauge(
                self.gauge_name_sanitize(
                    neutron_agent_stat['stat_name']),
                'Openstack Neutron agent statistic',
                labels,
                registry=registry)
            label_values = [self.osclient.region,
                            neutron_agent_stat.get('host', ''),
                            neutron_agent_stat.get('service', ''),
                            neutron_agent_stat.get('state', '')]
            stat_gauge.labels(
                *
                label_values).set(
                neutron_agent_stat['stat_value'])
        return generate_latest(registry) 
Example 13
Project: azure-cost-mon   Author: blue-yonder   File: test_allocated_vm_collector.py    License: MIT License 6 votes vote down vote up
def test_single_machine(enable_login):
    responses.add(
        method='GET',
        url='https://management.azure.com/subscriptions/SUBSCRIPTION_ID/providers/Microsoft.Compute/virtualMachines?api-version=2017-03-30',
        match_querystring=True,
        json={'value': [
            {
                'id': '/subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/Microsoft.Compute/virtualMachines/NAME',
                'location': 'WESTEUROPE',
                'properties': {'hardwareProfile': {'vmSize': 'SIZE'}}
            }
        ]})

    registry = CollectorRegistry()
    c = AzureAllocatedVMCollector('app_id', 'app_secret', 'tenant_id', ['SUBSCRIPTION_ID'], 'SERIES_NAME')
    registry.register(c)

    result = generate_latest(registry).decode('utf8').split('\n')
    assert 'SERIES_NAME{location="WESTEUROPE",resource_group="RESOURCE_GROUP",subscription="SUBSCRIPTION_ID",vm_size="SIZE"} 1.0' in result 
Example 14
Project: azure-cost-mon   Author: blue-yonder   File: test_enterprise_billing_collector.py    License: MIT License 6 votes vote down vote up
def test_extract_metrics(api_url, enrollment):

    responses.add(
        method='GET',
        url=api_url,
        match_querystring=True,
        json=sample_data
    )

    registry = CollectorRegistry()
    c = AzureEABillingCollector('costs', enrollment, 'ab123xy', 10)
    registry.register(c)

    result = generate_latest(registry).decode('utf8').split('\n')
    assert len(result) == 5

    expected_0 = 'costs{AccountName="platform",DepartmentName="engineering",MeterCategory="virtual network",MeterName="hours",MeterSubCategory="gateway hour",ResourceGroup="",SubscriptionName="production"} 0.0'
    expected_1 = 'costs{AccountName="platform",DepartmentName="engineering",MeterCategory="windows azure storage",MeterName="standard io - page blob/disk (gb)",MeterSubCategory="locally redundant",ResourceGroup="my-group",SubscriptionName="production"} 1.0'

    assert result[2] == expected_0
    assert result[3] == expected_1 
Example 15
Project: kqueen   Author: Mirantis   File: views.py    License: MIT License 6 votes vote down vote up
def root():
    # check access
    ip_whitelist = ip_network(current_app.config.get('PROMETHEUS_WHITELIST'))
    if ip_address(request.remote_addr) not in ip_whitelist:
        _jwt_required(current_app.config['JWT_DEFAULT_REALM'])

    MU = MetricUpdater()
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)

    data = generate_latest(registry)

    response = make_response(data)
    response.headers['Content-Type'] = CONTENT_TYPE_LATEST
    response.headers['Content-Length'] = str(len(data))
    logger.info('Kqueen metrics updating')
    MU.update_metrics()

    return response 
Example 16
Project: maas   Author: maas   File: test_utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_with_extra_labels(self):
        definitions = [
            MetricDefinition("Gauge", "a_gauge", "A Gauge", ["foo", "bar"])
        ]
        prometheus_metrics = PrometheusMetrics(
            definitions=definitions,
            extra_labels={"baz": "BAZ", "bza": "BZA"},
            registry=prometheus_client.CollectorRegistry(),
        )
        prometheus_metrics.update(
            "a_gauge", "set", value=22, labels={"foo": "FOO", "bar": "BAR"}
        )
        self.assertIn(
            'a_gauge{bar="BAR",baz="BAZ",bza="BZA",foo="FOO"} 22.0',
            prometheus_metrics.generate_latest().decode("ascii"),
        ) 
Example 17
Project: maas   Author: maas   File: test_tftp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_wb_start_session(self):
        prometheus_metrics = create_metrics(
            METRICS_DEFINITIONS, registry=prometheus_client.CollectorRegistry()
        )
        stream_session = FakeStreamSession()
        session = FakeSession(stream_session)
        tftp_mock = self.patch(tftp.protocol.TFTP, "_startSession")
        tftp_mock.return_value = succeed(session)
        tracking_tftp = TransferTimeTrackingTFTP(sentinel.backend)
        datagram = RQDatagram(b"file.txt", b"octet", {})
        result = yield tracking_tftp._startSession(
            datagram,
            "192.168.1.1",
            "read",
            prometheus_metrics=prometheus_metrics,
        )
        result.session.cancel()
        metrics = prometheus_metrics.generate_latest().decode("ascii")
        self.assertIs(result, session)
        self.assertTrue(stream_session.cancelled)
        self.assertIn(
            'maas_tftp_file_transfer_latency_count{filename="file.txt"} 1.0',
            metrics,
        ) 
Example 18
Project: PROTON   Author: PruthviKumarBK   File: proton_prometheus.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        super(ProtonPrometheus, self).__init__()
        self.registry = CollectorRegistry()
        self.requests = Counter(
            'http_total_request',
            'Counter of total HTTP requests',
            ['method', 'path', 'status'],
            registry=self.registry)

        self.request_historygram = Histogram(
            'request_latency_seconds',
            'Histogram of request latency',
            ['method', 'path', 'status'],
            registry=self.registry) 
Example 19
Project: integrations-core   Author: DataDog   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poll_mock():
    registry = CollectorRegistry()
    g1 = Gauge('metric1', 'processor usage', ['matched_label', 'node', 'flavor'], registry=registry)
    g1.labels(matched_label="foobar", node="host1", flavor="test").set(99.9)
    g2 = Gauge('metric2', 'memory usage', ['matched_label', 'node', 'timestamp'], registry=registry)
    g2.labels(matched_label="foobar", node="host2", timestamp="123").set(12.2)
    c1 = Counter('counter1', 'hits', ['node'], registry=registry)
    c1.labels(node="host2").inc(42)
    g3 = Gauge('metric3', 'memory usage', ['matched_label', 'node', 'timestamp'], registry=registry)
    g3.labels(matched_label="foobar", node="host2", timestamp="456").set(float('inf'))

    poll_mock_patch = mock.patch(
        'requests.get',
        return_value=mock.MagicMock(
            status_code=200,
            iter_lines=lambda **kwargs: ensure_unicode(generate_latest(registry)).split("\n"),
            headers={'Content-Type': "text/plain"},
        ),
    )
    with poll_mock_patch:
        yield 
Example 20
Project: starlette-prometheus   Author: perdy   File: view.py    License: GNU General Public License v3.0 5 votes vote down vote up
def metrics(request: Request) -> Response:
    if "prometheus_multiproc_dir" in os.environ:
        registry = CollectorRegistry()
        MultiProcessCollector(registry)
    else:
        registry = REGISTRY

    return Response(generate_latest(registry), media_type=CONTENT_TYPE_LATEST) 
Example 21
Project: prometheus-multiprocessing-example   Author: jonashaag   File: yourapp.py    License: ISC License 5 votes vote down vote up
def metrics():
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    data = generate_latest(registry)
    return Response(data, mimetype=CONTENT_TYPE_LATEST) 
Example 22
Project: django-prometheus   Author: korfuri   File: exports.py    License: Apache License 2.0 5 votes vote down vote up
def ExportToDjangoView(request):
    """Exports /metrics as a Django view.

    You can use django_prometheus.urls to map /metrics to this view.
    """
    if "prometheus_multiproc_dir" in os.environ:
        registry = prometheus_client.CollectorRegistry()
        multiprocess.MultiProcessCollector(registry)
    else:
        registry = prometheus_client.REGISTRY
    metrics_page = prometheus_client.generate_latest(registry)
    return HttpResponse(
        metrics_page, content_type=prometheus_client.CONTENT_TYPE_LATEST
    ) 
Example 23
Project: prometheus-pve-exporter   Author: prometheus-pve   File: collector.py    License: Apache License 2.0 5 votes vote down vote up
def collect_pve(config, host):
    """Scrape a host and return prometheus text format for it"""

    pve = ProxmoxAPI(host, **config)

    registry = CollectorRegistry()
    registry.register(StatusCollector(pve))
    registry.register(ClusterResourcesCollector(pve))
    registry.register(ClusterNodeCollector(pve))
    registry.register(ClusterInfoCollector(pve))
    registry.register(ClusterNodeConfigCollector(pve))
    registry.register(VersionCollector(pve))
    return generate_latest(registry) 
Example 24
Project: prometheus_flask_exporter   Author: rycus86   File: test_example.py    License: MIT License 5 votes vote down vote up
def app() -> Flask:
    app = create_app('myapp.config.TestConfig')
    prometheus_client.REGISTRY = prometheus_client.CollectorRegistry(auto_describe=True)
    myapp_extensions.metrics = GunicornInternalPrometheusMetrics.for_app_factory(group_by="endpoint")
    ctx = app.app_context()
    ctx.push()
    yield app
    ctx.pop() 
Example 25
Project: prometheus_flask_exporter   Author: rycus86   File: __init__.py    License: MIT License 5 votes vote down vote up
def register_endpoint(self, path, app=None):
        """
        Register the metrics endpoint on the Flask application.

        :param path: the path of the endpoint
        :param app: the Flask application to register the endpoint on
            (by default it is the application registered with this class)
        """

        if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'):
            return

        if app is None:
            app = self.app or current_app

        @app.route(path)
        @self.do_not_track()
        def prometheus_metrics():
            # import these here so they don't clash with our own multiprocess module
            from prometheus_client import multiprocess, CollectorRegistry

            if 'prometheus_multiproc_dir' in os.environ:
                registry = CollectorRegistry()
            else:
                registry = self.registry

            if 'name[]' in request.args:
                registry = registry.restricted_registry(request.args.getlist('name[]'))

            if 'prometheus_multiproc_dir' in os.environ:
                multiprocess.MultiProcessCollector(registry)

            headers = {'Content-Type': CONTENT_TYPE_LATEST}
            return generate_latest(registry), 200, headers 
Example 26
Project: prometheus_flask_exporter   Author: rycus86   File: multiprocess.py    License: MIT License 5 votes vote down vote up
def __init__(self, app=None, export_defaults=True,
                 defaults_prefix='flask', group_by='path',
                 buckets=None, static_labels=None, registry=None):
        """
        Create a new multiprocess-aware Prometheus metrics export configuration.

        :param app: the Flask application (can be `None`)
        :param export_defaults: expose all HTTP request latencies
            and number of HTTP requests
        :param defaults_prefix: string to prefix the default exported
            metrics name with (when either `export_defaults=True` or
            `export_defaults(..)` is called)
        :param group_by: group default HTTP metrics by
            this request property, like `path`, `endpoint`, `url_rule`, etc.
            (defaults to `path`)
        :param buckets: the time buckets for request latencies
            (will use the default when `None`)
        :param static_labels: static labels to attach to each of the
            metrics exposed by this metrics instance
        :param registry: the Prometheus Registry to use (can be `None` and it
            will be registered with `prometheus_client.multiprocess.MultiProcessCollector`)
        """

        _check_multiproc_env_var()

        registry = registry or CollectorRegistry()
        MultiProcessCollector(registry)

        super(MultiprocessPrometheusMetrics, self).__init__(
            app=app, path=None, export_defaults=export_defaults,
            defaults_prefix=defaults_prefix, group_by=group_by,
            buckets=buckets, static_labels=static_labels,
            registry=registry
        ) 
Example 27
Project: prometheus_flask_exporter   Author: rycus86   File: test_app_factory.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.app = Flask(__name__)
        self.app.testing = True
        self.client = self.app.test_client()

        if sys.version_info.major < 3:
            self.assertRegex = self.assertRegexpMatches
            self.assertNotRegex = self.assertNotRegexpMatches

        registry = CollectorRegistry(auto_describe=True)
        self.metrics = PrometheusMetrics.for_app_factory(registry=registry)
        self.metrics.init_app(self.app) 
Example 28
Project: prometheus_flask_exporter   Author: rycus86   File: unittest_helper.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.app = Flask(__name__)
        self.app.testing = True
        self.client = self.app.test_client()

        # reset the underlying Prometheus registry
        prometheus_client.REGISTRY = prometheus_client.CollectorRegistry(auto_describe=True) 
Example 29
Project: plugins   Author: lightningd   File: prometheus.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init(options, configuration, plugin):
    s = options['prometheus-listen'].rpartition(':')
    if len(s) != 3 or s[1] != ':':
        print("Could not parse prometheus-listen address")
        exit(1)
    ip, port = s[0], int(s[2])

    registry = CollectorRegistry()
    start_http_server(addr=ip, port=port, registry=registry)
    registry.register(NodeCollector(plugin.rpc, registry))
    registry.register(FundsCollector(plugin.rpc, registry))
    registry.register(PeerCollector(plugin.rpc, registry))
    registry.register(ChannelsCollector(plugin.rpc, registry)) 
Example 30
Project: zentral   Author: zentralopensource   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_prometheus_inventory_metrics():
    registry = CollectorRegistry()
    g = Gauge('zentral_inventory_osx_apps', 'Zentral inventory OSX apps',
              ['name', 'version_str', 'source'],
              registry=registry)
    for r in osx_app_count():
        count = r.pop('count')
        g.labels(**r).set(count)
    g = Gauge('zentral_inventory_os_versions', 'Zentral inventory OS Versions',
              ['name', 'major', 'minor', 'patch', 'build', 'source'],
              registry=registry)
    for r in os_version_count():
        count = r.pop('count')
        g.labels(**r).set(count)
    return registry