Python prometheus_client.CollectorRegistry() Examples

The following are 30 code examples of prometheus_client.CollectorRegistry(). 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 also want to check out all available functions/classes of the module prometheus_client , or try the search function .
Example #1
Source File: test_testutils.py    From django-prometheus with Apache License 2.0 12 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
Source File: monitor.py    From CrawlerMonitor with 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
Source File: utils.py    From zentral with Apache License 2.0 7 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 #4
Source File: nova_services.py    From prometheus-openstack-exporter with 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 #5
Source File: test_tftp.py    From maas with 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 #6
Source File: my_hook.py    From naz with 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 #7
Source File: proton_prometheus.py    From PROTON with 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 #8
Source File: test_utils.py    From maas with 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 #9
Source File: resources.py    From dagster with 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 #10
Source File: test_stats.py    From openstacksdk with 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 #11
Source File: views.py    From kqueen with 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 #12
Source File: prometheus_openstack_exporter.py    From prometheus-openstack-exporter with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: conftest.py    From integrations-core with 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 #14
Source File: cinder_services.py    From prometheus-openstack-exporter with 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 #15
Source File: check_os_api.py    From prometheus-openstack-exporter with 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 #16
Source File: neutron_agents.py    From prometheus-openstack-exporter with 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 #17
Source File: test_allocated_vm_collector.py    From azure-cost-mon with 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 #18
Source File: test_enterprise_billing_collector.py    From azure-cost-mon with 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 #19
Source File: test_graphite_bridge.py    From client_python with 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 #20
Source File: views.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def metrics():
    registry = CollectorRegistry()
    _register_collectors(registry)

    try:
        content = generate_latest(registry)
        return content, 200, {'Content-Type': CONTENT_TYPE_LATEST}
    except Exception as e:
        abort(Response("Scrape failed: {}".format(e), status=502)) 
Example #21
Source File: test_reserved_vm_collector.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def test_base_reservation(enable_login, single_order, reservation):
    responses.add(
        method='GET',
        url='https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/SINGLE_ORDER/reservations?api-version=2017-11-01',
        match_querystring=True,
        json={'value': [reservation]})

    registry = CollectorRegistry()
    c = AzureReservedVMCollector('app_id', 'app_secret', 'tenant_id', 'SERIES_NAME')
    registry.register(c)

    result = generate_latest(registry).decode('utf8').split('\n')
    assert 'SERIES_NAME{duration="1-year",location="WESTEUROPE",subscription="SOME_SUBSCRIPTION",vm_size="SIZE"} 42.0' in result
    assert 'SERIES_NAME_next_expiration{duration="1-year",location="WESTEUROPE",subscription="SOME_SUBSCRIPTION",vm_size="SIZE"} 1546300800.0' in result 
Example #22
Source File: test_utils.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_extra_labels(self):
        prometheus_metrics = create_metrics(
            self.metrics_definitions,
            extra_labels={"foo": "FOO", "bar": "BAR"},
            registry=prometheus_client.CollectorRegistry(),
        )
        prometheus_metrics.update("sample_counter", "inc")
        content = prometheus_metrics.generate_latest().decode("ascii")
        self.assertIn('sample_counter{bar="BAR",foo="FOO"} 1.0', content) 
Example #23
Source File: test_enterprise_billing_collector.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def test_failing_requests(api_url, enrollment, status):
    registry = CollectorRegistry()
    c = AzureEABillingCollector('cloud_costs', enrollment, 'abc123xyz', 42.3)
    registry.register(c)

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

    with pytest.raises(requests.HTTPError):
        generate_latest(registry) 
Example #24
Source File: test_utils.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_extra_labels_callable(self):
        values = ["a", "b"]
        prometheus_metrics = create_metrics(
            self.metrics_definitions,
            extra_labels={"foo": values.pop},
            registry=prometheus_client.CollectorRegistry(),
        )
        prometheus_metrics.update("sample_counter", "inc")
        prometheus_metrics.update("sample_counter", "inc")
        content = prometheus_metrics.generate_latest().decode("ascii")
        self.assertIn('sample_counter{foo="a"} 1.0', content)
        self.assertIn('sample_counter{foo="b"} 1.0', content) 
Example #25
Source File: test_allocated_vm_collector.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def test_multiple_machines_in_multiple_subscriptions(enable_login):
    responses.add(
        method='GET',
        url='https://management.azure.com/subscriptions/SUBSCRIPTION_A/providers/Microsoft.Compute/virtualMachines?api-version=2017-03-30',
        match_querystring=True,
        json={'value': [
            {
                'id': '/subscriptions/SUBSCRIPTION_A/resourceGroups/RESOURCE_GROUP/providers/Microsoft.Compute/virtualMachines/NAME',
                'location': 'WESTEUROPE',
                'properties': {'hardwareProfile': {'vmSize': 'SIZE'}}
            }
        ]})
    responses.add(
        method='GET',
        url='https://management.azure.com/subscriptions/SUBSCRIPTION_B/providers/Microsoft.Compute/virtualMachines?api-version=2017-03-30',
        match_querystring=True,
        json={'value': [
            {
                'id': '/subscriptions/SUBSCRIPTION_B/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_A', 'SUBSCRIPTION_B'], 'SERIES_NAME')
    registry.register(c)

    result = generate_latest(registry).decode('utf8').split('\n')
    assert 'SERIES_NAME{location="WESTEUROPE",resource_group="RESOURCE_GROUP",subscription="SUBSCRIPTION_A",vm_size="SIZE"} 1.0' in result
    assert 'SERIES_NAME{location="WESTEUROPE",resource_group="RESOURCE_GROUP",subscription="SUBSCRIPTION_B",vm_size="SIZE"} 1.0' in result 
Example #26
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_latest_metrics(self, request):
        """ gets the latest metrics """
        section = request.args.get(b'section', [b'default'])[0].decode('utf-8')
        if section not in self.config.keys():
            logging.info("{} is not a valid section, using default".format(section))
            section = 'default'

        if self.config[section].get('vsphere_host') and self.config[section].get('vsphere_host') != "None":
            vsphere_host = self.config[section].get('vsphere_host')
        elif request.args.get(b'target', [None])[0]:
            vsphere_host = request.args.get(b'target', [None])[0].decode('utf-8')
        elif request.args.get(b'vsphere_host', [None])[0]:
            vsphere_host = request.args.get(b'vsphere_host')[0].decode('utf-8')
        else:
            request.setResponseCode(500)
            logging.info("No vsphere_host or target defined")
            request.write(b'No vsphere_host or target defined!\n')
            request.finish()
            return

        collector = VmwareCollector(
            vsphere_host,
            self.config[section]['vsphere_user'],
            self.config[section]['vsphere_password'],
            self.config[section]['collect_only'],
            self.config[section]['specs_size'],
            self.config[section]['fetch_custom_attributes'],
            self.config[section]['ignore_ssl'],
            self.config[section]['fetch_tags'],
            self.config[section]['fetch_alarms'],
        )
        metrics = yield collector.collect()

        registry = CollectorRegistry()
        registry.register(ListCollector(metrics))
        output = generate_latest(registry)

        request.setHeader("Content-Type", "text/plain; charset=UTF-8")
        request.setResponseCode(200)
        request.write(output)
        request.finish() 
Example #27
Source File: valve_test_lib.py    From faucet with Apache License 2.0 5 votes vote down vote up
def setup_valves(self, config, error_expected=0, log_stdout=False):
            """
            Set up test with config
            Args:
                config (str): The Faucet config file
                error_expected (int): The error expected, if any
                log_stdout: Whether to log to stdout or not
            """
            self.tmpdir = tempfile.mkdtemp()
            self.config_file = os.path.join(self.tmpdir, 'valve_unit.yaml')
            self.faucet_event_sock = os.path.join(self.tmpdir, 'event.sock')
            logfile = 'STDOUT' if log_stdout else os.path.join(self.tmpdir, 'faucet.log')
            self.logger = valve_util.get_logger(self.LOGNAME, logfile, logging.DEBUG, 0)
            self.registry = CollectorRegistry()
            self.metrics = faucet_metrics.FaucetMetrics(reg=self.registry)
            self.notifier = faucet_event.FaucetEventNotifier(
                self.faucet_event_sock, self.metrics, self.logger)
            self.bgp = faucet_bgp.FaucetBgp(
                self.logger, logfile, self.metrics, self.send_flows_to_dp_by_id)
            self.dot1x = faucet_dot1x.FaucetDot1x(
                self.logger, logfile, self.metrics, self.send_flows_to_dp_by_id)
            self.valves_manager = valves_manager.ValvesManager(
                self.LOGNAME, self.logger, self.metrics, self.notifier,
                self.bgp, self.dot1x, self.CONFIG_AUTO_REVERT, self.send_flows_to_dp_by_id)
            self.last_flows_to_dp[self.DP_ID] = []
            self.notifier.start()
            initial_ofmsgs = self.update_config(
                config, reload_expected=False,
                error_expected=error_expected, configure_network=True)
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(self.faucet_event_sock)
            if not error_expected:
                for dp_id in self.valves_manager.valves:
                    self.connect_dp(dp_id)
            return initial_ofmsgs 
Example #28
Source File: oscache.py    From prometheus-openstack-exporter with Apache License 2.0 5 votes vote down vote up
def get_stats(self):
        registry = CollectorRegistry()
        labels = ['region']
        label_values = [self.region]
        duration = Gauge('openstack_exporter_cache_refresh_duration_seconds',
                         'Cache refresh duration in seconds.',
                         labels, registry=registry)
        duration.labels(*label_values).set(self.duration)
        return generate_latest(registry) 
Example #29
Source File: test_reserved_vm_collector.py    From azure-cost-mon with MIT License 5 votes vote down vote up
def test_three_year_reservation(enable_login, single_order, reservation):
    reservation['properties']['effectiveDateTime'] = '2016-01-01T00:00:00.000000Z'
    responses.add(
        method='GET',
        url='https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/SINGLE_ORDER/reservations?api-version=2017-11-01',
        match_querystring=True,
        json={'value': [reservation]})

    registry = CollectorRegistry()
    c = AzureReservedVMCollector('app_id', 'app_secret', 'tenant_id', 'SERIES_NAME')
    registry.register(c)

    result = generate_latest(registry).decode('utf8').split('\n')
    assert 'SERIES_NAME{duration="3-year",location="WESTEUROPE",subscription="SOME_SUBSCRIPTION",vm_size="SIZE"} 42.0' in result
    assert 'SERIES_NAME_next_expiration{duration="3-year",location="WESTEUROPE",subscription="SOME_SUBSCRIPTION",vm_size="SIZE"} 1546300800.0' in result 
Example #30
Source File: test_tftp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_track_tftp_latency(self):
        class Thing:
            did_something = False

            def do_something(self):
                self.did_something = True
                return True

        thing = Thing()
        start_time = time.time()
        prometheus_metrics = create_metrics(
            METRICS_DEFINITIONS, registry=prometheus_client.CollectorRegistry()
        )
        thing.do_something = track_tftp_latency(
            thing.do_something,
            start_time=start_time,
            filename="myfile.txt",
            prometheus_metrics=prometheus_metrics,
        )
        time_mock = self.patch(tftp_module, "time")
        time_mock.return_value = start_time + 0.5
        result = thing.do_something()
        self.assertTrue(result)
        self.assertTrue(thing.did_something)

        metrics = prometheus_metrics.generate_latest().decode("ascii")
        self.assertIn(
            'maas_tftp_file_transfer_latency_count{filename="myfile.txt"} 1.0',
            metrics,
        )
        self.assertIn(
            "maas_tftp_file_transfer_latency_bucket"
            '{filename="myfile.txt",le="0.5"} 1.0',
            metrics,
        )
        self.assertIn(
            "maas_tftp_file_transfer_latency_bucket"
            '{filename="myfile.txt",le="0.25"} 0.0',
            metrics,
        )