├── prometheus_openstack_exporter.py ├── snap ├── .snapcraft │ └── state └── snapcraft.yaml ├── .yamllint ├── requirements.txt ├── snap_cmd_wrapper ├── prometheus-openstack-exporter.service ├── .github ├── CODEOWNERS ├── .jira_sync_config.yaml └── workflows │ └── check.yaml ├── prometheus-openstack-exporter.conf ├── admin.novarc.example ├── Dockerfile ├── SECURITY.md ├── Makefile ├── .gitignore ├── setup.py ├── tox.ini ├── prometheus-openstack-exporter.yaml ├── prometheus-openstack-exporter.sample.yaml ├── tests ├── test_SwiftAccountUsage.py └── test_poe.py ├── wrapper.sh ├── CONTRIBUTING.md ├── pyproject.toml ├── README.md ├── LICENSE └── prometheus-openstack-exporter /prometheus_openstack_exporter.py: -------------------------------------------------------------------------------- 1 | prometheus-openstack-exporter -------------------------------------------------------------------------------- /snap/.snapcraft/state: -------------------------------------------------------------------------------- 1 | !GlobalState 2 | assets: 3 | build-packages: [] 4 | build-snaps: [] 5 | -------------------------------------------------------------------------------- /.yamllint: -------------------------------------------------------------------------------- 1 | extends: default 2 | 3 | rules: 4 | line-length: disable 5 | document-start: disable 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | configparser==3.5 2 | flake8 3 | mock 4 | prometheus-client 5 | python-neutronclient 6 | python-novaclient 7 | python-cinderclient 8 | swift 9 | -------------------------------------------------------------------------------- /snap_cmd_wrapper: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Fail if these vars are not present (e.g. from direct wrapper runs) 4 | : ${SNAP?} ${SNAP_DATA?} 5 | # Copy only if not existing 6 | cp -pn $SNAP/etc/prometheus/prometheus-openstack-exporter.yaml.example $SNAP_DATA/prometheus-openstack-exporter.yaml 7 | test -r $SNAP_DATA/admin.novarc && . $SNAP_DATA/admin.novarc 8 | exec $SNAP/bin/python3 $SNAP/bin/prometheus-openstack-exporter $SNAP_DATA/prometheus-openstack-exporter.yaml 9 | -------------------------------------------------------------------------------- /prometheus-openstack-exporter.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=prometheus-openstack-exporter 3 | After=network.target 4 | 5 | [Service] 6 | EnvironmentFile=/etc/default/prometheus-openstack-exporter 7 | #EnvironmentFile=/etc/prometheus-openstack-exporter/admin.novarc 8 | ExecStart=/bin/sh -c '. /etc/prometheus-openstack-exporter/admin.novarc; exec /opt/prometheus-openstack-exporter/prometheus-openstack-exporter $CONFIG_FILE' 9 | KillMode=process 10 | 11 | [Install] 12 | WantedBy=multi-user.target 13 | 14 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | # 7 | # These owners will be the default owners for everything in the repo. Unless a 8 | # later match takes precedence, @canonical/soleng-reviewers will be requested for 9 | # review when someone opens a pull request. 10 | * @canonical/soleng-reviewers 11 | -------------------------------------------------------------------------------- /prometheus-openstack-exporter.conf: -------------------------------------------------------------------------------- 1 | # Configuration is read from /etc/default/prometheus-openstack-exporter 2 | # Copyright (C) 2016 Canonical, Ltd. 3 | 4 | description "Prometheus Openstack Exporter" 5 | author "Jacek Nykis " 6 | 7 | # The following variable must be set: 8 | # NOVARC - full path to the novarc file 9 | # 10 | # Optionall variables: 11 | # CONFIG_FILE - path to configuration file 12 | 13 | start on runlevel [2345] 14 | stop on runlevel [!2345] 15 | respawn 16 | 17 | script 18 | . /etc/default/prometheus-openstack-exporter 19 | . $NOVARC 20 | exec /usr/local/bin/prometheus-openstack-exporter $CONFIG_FILE 21 | end script 22 | -------------------------------------------------------------------------------- /admin.novarc.example: -------------------------------------------------------------------------------- 1 | OS_PROJECT_DOMAIN_NAME=Default 2 | OS_USER_DOMAIN_NAME=Default 3 | OS_PROJECT_NAME=admin 4 | OS_TENANT_NAME=admin 5 | OS_USERNAME=admin 6 | OS_PASSWORD=XXXXXXXXXX 7 | OS_AUTH_URL=http://XX.XX.XX.XX:35357/v3 8 | OS_INTERFACE=internal 9 | OS_IDENTITY_API_VERSION=3 10 | OS_REGION_NAME=mycloud 11 | 12 | #logLevel=INFO 13 | #listenPort=9183 14 | #cacheRefreshInterval=300 15 | #vcpuRatio=1.0 16 | #ramRatio=1.0 17 | #diskRatio=1.0 18 | #enabledCollectors=cinder neutron nova 19 | #schedulableInstanceRam=4096 20 | #schedulableInstanceVcpu=2 21 | #schedulableInstanceDisk=20 22 | #useNovaVolumes=True 23 | #swiftHosts=host1.example.com host2.example.com 24 | #keystoneTenantsMap="firstname,1234567890 secondname,0987654321" 25 | #resellerPrefix=AUTH_ 26 | #ringPath=/etc/swift 27 | #hashPathPrefix= 28 | #hashPathSuffix= 29 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10-alpine 2 | 3 | RUN \ 4 | apk update && \ 5 | apk --no-cache -q add build-base linux-headers libffi-dev openssl-dev python3-dev && \ 6 | apk --no-cache -q add git gcc make autoconf automake libtool libxml2-dev libxslt-dev && \ 7 | cd /tmp && git clone https://github.com/openstack/liberasurecode && \ 8 | cd liberasurecode && ./autogen.sh && ./configure && make && make test && make install && \ 9 | cd / && rm -rf /tmp/liberasurecode && \ 10 | pip install -U pip && \ 11 | pip install python-neutronclient python-novaclient python-keystoneclient python-cinderclient \ 12 | prometheus-client requests pyyaml netaddr swift flake8 13 | 14 | COPY prometheus-openstack-exporter / 15 | COPY prometheus-openstack-exporter.sample.yaml / 16 | COPY wrapper.sh / 17 | 18 | EXPOSE 9183 19 | ENTRYPOINT ["/bin/sh", "/wrapper.sh"] 20 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | # Security policy 8 | 9 | 10 | ## Reporting a vulnerability 11 | To report a security issue, file a [Private Security Report](https://github.com/canonical/prometheus-openstack-exporter/security/advisories/new) 12 | with a description of the issue, the steps you took to create the issue, affected versions, and, 13 | if known, mitigations for the issue. 14 | 15 | The [Ubuntu Security disclosure and embargo policy](https://ubuntu.com/security/disclosure-policy) 16 | contains more information about what you can expect when you contact us and what we expect from you. 17 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROJECTPATH = $(dir $(realpath $(firstword $(MAKEFILE_LIST)))) 2 | 3 | VENV := .venv 4 | VENV_PIP := $(PROJECTPATH)/$(VENV)/bin/pip 5 | VENV_PYTHON := $(PROJECTPATH)/$(VENV)/bin/python3 6 | 7 | EXTRA_PY := $(PROJECTPATH)/prometheus-openstack-exporter 8 | 9 | FLAKE8 := $(VENV_PYTHON) -m flake8 10 | 11 | all: lint test build 12 | 13 | clean: clean-python clean-venv 14 | 15 | clean-python: 16 | rm -rf $(PROJECTPATH)/__pycache__ 17 | 18 | clean-venv: 19 | rm -rf $(PROJECTPATH)/$(VENV) 20 | 21 | dch: 22 | gbp dch --debian-tag='%(version)s' -D bionic --git-log --first-parent 23 | 24 | deb-src: 25 | debuild -S -sa -I.git 26 | 27 | install-build-depends: 28 | sudo apt install \ 29 | debhelper \ 30 | git-buildpackage 31 | 32 | lint: 33 | @echo "Running lint checks" 34 | @tox -e lint 35 | 36 | black: 37 | @echo "Reformat files with black" 38 | @tox -e black 39 | 40 | test: test-python 41 | 42 | test-python: $(VENV) 43 | $(VENV_PYTHON) -m unittest discover tests 44 | 45 | $(VENV): 46 | virtualenv --system-site-packages -p python3 $(PROJECTPATH)/$(VENV) 47 | $(VENV_PIP) install -I -r requirements.txt 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | 7 | # Python Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # Test files and directories 13 | .pytest_cache/ 14 | .coverage* 15 | .tox 16 | reports/ 17 | **/report/ 18 | htmlcov/ 19 | .mypy_cache 20 | .unit-state.db 21 | 22 | # python virtual environments (for local dev) 23 | .venv 24 | venv 25 | env 26 | 27 | # Build artefacts 28 | output/ 29 | .build/ 30 | build/ 31 | *.charm 32 | *.snap 33 | # python build artefacts 34 | deb_dist/ 35 | dist/ 36 | *.egg-info/ 37 | 38 | # Log files 39 | *.log 40 | 41 | # general backup files 42 | *~ 43 | *.bak 44 | 45 | # Note: for editor-specific files, please don't add them here, as they are specific to your environment, not the project. 46 | # Instead, consider using a global gitignore on your workstation. 47 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """This module install prometheus-openstack-exporter.""" 2 | 3 | import os 4 | 5 | from setuptools import setup 6 | 7 | 8 | def read(fname): 9 | """Read a file and return the content.""" 10 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 11 | 12 | 13 | setup( 14 | name="prometheus_openstack_exporter", 15 | version="0.0.4", 16 | author="Jacek Nykis", 17 | description="Exposes high level OpenStack metrics to Prometheus.", 18 | license="GPLv3", 19 | keywords=["prometheus", "openstack", "exporter"], 20 | url="https://github.com/CanonicalLtd/prometheus-openstack-exporter", 21 | scripts=["prometheus-openstack-exporter"], 22 | packages=[], 23 | install_requires=[ 24 | "prometheus_client", 25 | "python-keystoneclient<=3.10.0", 26 | "python-novaclient==6.0.0", 27 | "python-neutronclient<=6.1.0", 28 | "python-cinderclient", 29 | "netaddr", 30 | "swift", 31 | ], 32 | long_description=read("README.md"), 33 | classifiers=[ 34 | "Development Status :: 4 - Beta", 35 | "Topic :: System :: Networking :: Monitoring", 36 | "License :: OSI Approved :: " "GNU General Public License v3 or later (GPLv3+)", 37 | ], 38 | ) 39 | -------------------------------------------------------------------------------- /.github/.jira_sync_config.yaml: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | # 7 | # For more info about the settings, please refre to the github repository: 8 | # https://github.com/canonical/gh-jira-sync-bot 9 | # 10 | 11 | settings: 12 | # Jira project key to create the issue in 13 | jira_project_key: "SOLENG" 14 | 15 | # Dictionary mapping GitHub issue status to Jira issue status 16 | status_mapping: 17 | opened: Untriaged 18 | closed: done 19 | 20 | # (Optional) Jira project components that should be attached to the created issue 21 | # Component names are case-sensitive 22 | components: 23 | - openstack-exporter 24 | 25 | # (Optional) (Default: false) Add a new comment in GitHub with a link to Jira created issue 26 | add_gh_comment: true 27 | 28 | # (Optional) (Default: None) Parent Epic key to link the issue to 29 | epic_key: SOLENG-46 30 | 31 | # (Optional) Dictionary mapping GitHub issue labels to Jira issue types. 32 | # If label on the issue is not in specified list, this issue will be created as a Bug 33 | label_mapping: 34 | enhancement: Story 35 | -------------------------------------------------------------------------------- /snap/snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: prometheus-openstack-exporter 2 | base: core20 3 | version: git 4 | summary: Exposes high level OpenStack metrics to Prometheus. 5 | description: | 6 | Exposes high level OpenStack metrics to Prometheus 7 | 8 | confinement: strict 9 | grade: stable 10 | apps: 11 | prometheus-openstack-exporter: 12 | command: 'bin/prometheus-openstack-exporter.wrapper' 13 | plugs: [network-bind, network] 14 | daemon: simple 15 | parts: 16 | prometheus-openstack-exporter: 17 | plugin: python 18 | source: . 19 | build-packages: 20 | - build-essential 21 | - liberasurecode-dev 22 | - libncursesw5 23 | - libtinfo5 24 | - libpython3-stdlib 25 | - libpython3.8-minimal 26 | - libpython3.8-stdlib 27 | - python3.8-minimal 28 | - python3-distutils 29 | - python3-minimal 30 | - python3-pkg-resources 31 | - python3-pip 32 | - python3-setuptools 33 | - python3-venv 34 | - python3-wheel 35 | # for building lxml 36 | - libxml2-dev 37 | - libxslt1-dev 38 | # for building cffi 39 | - libffi-dev 40 | # for building cryptography 41 | - rustc 42 | - cargo 43 | - libssl-dev 44 | - pkg-config 45 | stage-packages: 46 | - libdb5.3 47 | - liberasurecode-dev 48 | example-config: 49 | plugin: dump 50 | source: . 51 | organize: 52 | prometheus-openstack-exporter.yaml: etc/prometheus/prometheus-openstack-exporter.yaml.example 53 | prime: 54 | - etc/prometheus/prometheus-openstack-exporter.yaml.example 55 | snap-wrappers: 56 | plugin: dump 57 | source: . 58 | organize: 59 | snap_cmd_wrapper: bin/prometheus-openstack-exporter.wrapper 60 | prime: 61 | - bin/prometheus-openstack-exporter.wrapper 62 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | 7 | [tox] 8 | skipsdist=True 9 | skip_missing_interpreters = True 10 | envlist = lint, unit 11 | 12 | [testenv] 13 | basepython = python3 14 | setenv = 15 | PYTHONPATH = {toxinidir}:{toxinidir}/src/:{toxinidir}/reactive/:{toxinidir}/hooks/:{toxinidir}/lib/:{toxinidir}/actions:{toxinidir}/files/:{toxinidir}/files/plugins/ 16 | # avoid state written to file during tests - see https://github.com/juju/charm-helpers/blob/85dcbeaf63b0d0f38e8cb17825985460dc2cd02d/charmhelpers/core/unitdata.py#L179-L184 17 | UNIT_STATE_DB = :memory: 18 | # Default to juju 3, but don't overwrite it if already set in the environment. 19 | # This allows us to still test with juju2.9 for some projects by updating the env externally. 20 | TEST_JUJU3 = {env:TEST_JUJU3:1} 21 | passenv = * 22 | 23 | [testenv:lint] 24 | commands = 25 | black --check --diff --color . 26 | isort --check --diff --color . 27 | flake8 28 | deps = 29 | black 30 | colorama 31 | flake8 32 | flake8-colors 33 | flake8-docstrings 34 | flake8-import-order 35 | flake8-pyproject 36 | isort 37 | pep8-naming 38 | # so pylint and mypy can reason about the code 39 | 40 | [testenv:reformat] 41 | commands = 42 | black . 43 | isort . 44 | deps = 45 | black 46 | isort 47 | 48 | [testenv:unit] 49 | setenv = 50 | {[testenv]setenv} 51 | COVERAGE_FILE = .coverage-unit 52 | allowlist_externals = 53 | echo 54 | commands = echo "No unit tests, skipping." 55 | 56 | [testenv:func] 57 | setenv = 58 | {[testenv]setenv} 59 | COVERAGE_FILE = .coverage-func 60 | allowlist_externals = 61 | echo 62 | commands = echo "No func tests, skipping." 63 | -------------------------------------------------------------------------------- /prometheus-openstack-exporter.yaml: -------------------------------------------------------------------------------- 1 | # Example configuration file for prometheus-openstack-exporter 2 | # Copyright (C) 2016-2019 Canonical, Ltd. 3 | # 4 | 5 | listen_port: 9183 6 | cache_refresh_interval: 300 # In seconds 7 | cache_file: /var/cache/prometheus-openstack-exporter/mycloud 8 | cloud: mycloud 9 | openstack_allocation_ratio_vcpu: 2.5 10 | openstack_allocation_ratio_ram: 1.1 11 | openstack_allocation_ratio_disk: 1.0 12 | log_level: INFO 13 | 14 | # Configure the enabled collectors here. Note that the Swift account 15 | # collector in particular has special requirements. 16 | enabled_collectors: 17 | - cinder 18 | - neutron 19 | - nova 20 | - swift 21 | # - swift-account-usage 22 | 23 | # To export hypervisor_schedulable_instances metric set desired instance size 24 | schedulable_instance_size: 25 | ram_mbs: 4096 26 | vcpu: 2 27 | disk_gbs: 20 28 | 29 | # Uncomment if the cloud doesn't provide cinder / nova volumes: 30 | #use_nova_volumes: False 31 | 32 | ## Swift 33 | 34 | # There is no way to retrieve them using OpenStack APIs 35 | # For clouds deployed without swift, remove this part 36 | swift_hosts: 37 | - host1.example.com 38 | - host2.example.com 39 | 40 | # There is no API to ask Swift for a list of accounts it knows about. 41 | # Even if there were, Swift (in common case of Keystone auth, at 42 | # least) only knows them by the corresponding tenant ID, which would 43 | # be a less than useful label without post-processing. The following 44 | # should point to a file containing one line per tenant, with the 45 | # tenant name first, then whitespace, followed by the tenant ID. 46 | keystone_tenants_map: 47 | 48 | # The reseller prefix is typically used by the Swift middleware to 49 | # keep accounts with different providers separate. We would ideally 50 | # look this up dynamically from the Swift configuration. 51 | # The Keystone middlware defaults to the following value. 52 | reseller_prefix: AUTH_ 53 | 54 | ring_path: /etc/swift 55 | 56 | # These will typically be read from /etc/swift/swift.conf. If that 57 | # file cannot be opened, then the Swift library will log an error and 58 | # try to exit. To run p-s-a-e as a user other than Swift, these 59 | # settings must be set to the same values as Swift itself, and the 60 | # above must point to an always-current readable copy of the rings. 61 | 62 | hash_path_prefix: 63 | hash_path_suffix: 64 | -------------------------------------------------------------------------------- /prometheus-openstack-exporter.sample.yaml: -------------------------------------------------------------------------------- 1 | # Example configuration file for prometheus-openstack-exporter 2 | # Copyright (C) 2016-2019 Canonical, Ltd. 3 | # 4 | 5 | listen_port: VAR_LISTEN_PORT # listenPort=9183 6 | cache_refresh_interval: VAR_CACHE_REFRESH_INTERVAL # cacheRefreshInterval=300 In seconds 7 | cache_file: VAR_CACHE_FILE # cacheFileName=$(mktemp -p /dev/shm/) 8 | cloud: VAR_CLOUD # cloud=${OS_REGION_NAME:-mycloud} 9 | openstack_allocation_ratio_vcpu: VAR_VCPU_RATIO # vcpuRatio=1.0 10 | openstack_allocation_ratio_ram: VAR_RAM_RATIO # ramRatio=1.0 11 | openstack_allocation_ratio_disk: VAR_DISK_RATIO # diskRatio=1.0 12 | log_level: VAR_LOG_LEVEL # logLevel=INFO 13 | 14 | # Configure the enabled collectors here. Note that the Swift account 15 | # collector in particular has special requirements. 16 | enabled_collectors: # enabledCollectors=cinder neutron nova 17 | - VAR_ENABLED_COLLECTORS 18 | 19 | # To export hypervisor_schedulable_instances metric set desired instance size 20 | schedulable_instance_size: 21 | ram_mbs: VAR_SCHEDULABLE_INSTANCE_RAM # schedulableInstanceRam=4096 22 | vcpu: VAR_SCHEDULABLE_INSTANCE_VCPU # schedulableInstanceVcpu=2 23 | disk_gbs: VAR_SCHEDULABLE_INSTANCE_DISK # schedulableInstanceDisk=20 24 | 25 | # Uncomment if the cloud doesn't provide cinder / nova volumes: 26 | use_nova_volumes: VAR_USE_NOVA_VOLUMES # useNovaVolumes=True 27 | 28 | ## Swift 29 | 30 | # There is no way to retrieve them using OpenStack APIs 31 | # For clouds deployed without swift, remove this part 32 | swift_hosts: # swiftHosts=host1.example.com host2.example.com 33 | - VAR_SWIFT_HOSTS 34 | 35 | # There is no API to ask Swift for a list of accounts it knows about. 36 | # Even if there were, Swift (in common case of Keystone auth, at 37 | # least) only knows them by the corresponding tenant ID, which would 38 | # be a less than useful label without post-processing. The following 39 | # should point to a file containing one line per tenant, with the 40 | # tenant name first, then whitespace, followed by the tenant ID. 41 | keystone_tenants_map: # keystoneTenantsMap="firstname,1234567890 secondname,0987654321" 42 | - VAR_KEYSTONE_TENANTS_MAP 43 | 44 | # The reseller prefix is typically used by the Swift middleware to 45 | # keep accounts with different providers separate. We would ideally 46 | # look this up dynamically from the Swift configuration. 47 | # The Keystone middlware defaults to the following value. 48 | reseller_prefix: VAR_RESELLER_PREFIX # resellerPrefix=AUTH_ 49 | 50 | ring_path: VAR_RING_PATH # ringPath=/etc/swift 51 | 52 | # These will typically be read from /etc/swift/swift.conf. If that 53 | # file cannot be opened, then the Swift library will log an error and 54 | # try to exit. To run p-s-a-e as a user other than Swift, these 55 | # settings must be set to the same values as Swift itself, and the 56 | # above must point to an always-current readable copy of the rings. 57 | 58 | hash_path_prefix: VAR_HASH_PATH_PREFIX # hashPathPrefix= 59 | hash_path_suffix: VAR_HASH_PATH_SUFFIX # hashPathSuffix= 60 | -------------------------------------------------------------------------------- /tests/test_SwiftAccountUsage.py: -------------------------------------------------------------------------------- 1 | """Unit Test for Swift Account metrics collector.""" 2 | 3 | import unittest 4 | 5 | from mock import Mock, call, patch 6 | from requests.structures import CaseInsensitiveDict 7 | 8 | import prometheus_openstack_exporter as poe 9 | 10 | 11 | class TestSwiftAccountUsage(unittest.TestCase): 12 | @patch("prometheus_openstack_exporter.SwiftAccountUsage._get_account_ring") 13 | @patch("prometheus_openstack_exporter.requests.head") 14 | @patch("prometheus_openstack_exporter.config") 15 | def test__get_account_usage(self, _config, _requests_head, _get_account_ring): 16 | """Test Swift Account Usage metrics collection.""" 17 | s = poe.SwiftAccountUsage() 18 | s.account_ring.get_nodes.return_value = ( 19 | 26701, 20 | [ 21 | { 22 | "device": "sdb", 23 | "id": 0, 24 | "ip": "10.24.0.18", 25 | "meta": "", 26 | "port": 6002, 27 | "region": 1, 28 | "replication_ip": "10.24.0.18", 29 | "replication_port": 6002, 30 | "weight": 100.0, 31 | "zone": 1, 32 | }, 33 | { 34 | "device": "sdd", 35 | "id": 50, 36 | "ip": "10.24.0.71", 37 | "meta": "", 38 | "port": 6002, 39 | "region": 1, 40 | "replication_ip": "10.24.0.71", 41 | "replication_port": 6002, 42 | "weight": 180.0, 43 | "zone": 3, 44 | }, 45 | { 46 | "device": "sdi", 47 | "id": 59, 48 | "ip": "10.24.0.72", 49 | "meta": "", 50 | "port": 6002, 51 | "region": 1, 52 | "replication_ip": "10.24.0.72", 53 | "replication_port": 6002, 54 | "weight": 360.0, 55 | "zone": 2, 56 | }, 57 | ], 58 | ) 59 | 60 | response_mock = Mock() 61 | response_mock.configure_mock( 62 | status_code=204, 63 | headers=CaseInsensitiveDict({"x-account-bytes-used": "368259416"}), 64 | ) 65 | _requests_head.return_value = response_mock 66 | 67 | # Assert that _get_account_ring does what we expect. 68 | self.assertEqual(s._get_account_usage("AUTH_12bb569bf909441b90791482ae6f9ca9"), 368259416) 69 | 70 | # Assert that _get_account_ring did it in the manner we expected. 71 | s.account_ring.get_nodes.assert_called_once_with( 72 | account="AUTH_12bb569bf909441b90791482ae6f9ca9" 73 | ) 74 | poe.requests.head.assert_called_once() 75 | self.assertTrue( 76 | poe.requests.head.call_args 77 | in [ 78 | call("http://10.24.0.18:6002/sdb/26701/AUTH_12bb569bf909441b90791482ae6f9ca9"), 79 | call("http://10.24.0.71:6002/sdd/26701/AUTH_12bb569bf909441b90791482ae6f9ca9"), 80 | call("http://10.24.0.72:6002/sdi/26701/AUTH_12bb569bf909441b90791482ae6f9ca9"), 81 | ] 82 | ) 83 | -------------------------------------------------------------------------------- /wrapper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | prometheusDir='/etc/prometheus' 4 | configFile=${configFile:-"${prometheusDir}/prometheus-openstack-exporter.yaml"} 5 | logLevel=${logLevel:-INFO} 6 | listenPort=${listenPort:-9183} 7 | cacheRefreshInterval=${cacheRefreshInterval:-300} 8 | cacheFileName=${cacheFileName:-"$(mktemp -p /dev/shm/)"} 9 | cloud=${OS_REGION_NAME:-mycloud} 10 | vcpuRatio=${vcpuRatio:-1.0} 11 | ramRatio=${ramRatio:-1.0} 12 | diskRatio=${diskRatio:-1.0} 13 | enabledCollectors=${enabledCollectors:-cinder neutron nova} 14 | schedulableInstanceRam=${schedulableInstanceRam:-4096} 15 | schedulableInstanceVcpu=${schedulableInstanceVcpu:-2} 16 | schedulableInstanceDisk=${schedulableInstanceDisk:-20} 17 | useNovaVolumes=${useNovaVolumes:-True} 18 | swiftHosts=${swiftHosts:-host1.example.com host2.example.com} 19 | #keystoneTenantsMap="firstname,1234567890 secondname,0987654321" 20 | resellerPrefix=${resellerPrefix:-AUTH_} 21 | ringPath=${ringPath:-/etc/swift} 22 | #hashPathPrefix= 23 | #hashPathSuffix= 24 | 25 | if [ ! -e "${configFile}" ]; then 26 | mkdir -p ${prometheusDir} 27 | cp prometheus-openstack-exporter.sample.yaml ${configFile} 28 | 29 | sed -i "s|VAR_LISTEN_PORT|${listenPort}|g" ${configFile} 30 | sed -i "s|VAR_LOG_LEVEL|${logLevel}|g" ${configFile} 31 | sed -i "s|VAR_CACHE_REFRESH_INTERVAL|${cacheRefreshInterval}|g" ${configFile} 32 | sed -i "s|VAR_CACHE_FILE|${cacheFileName}|g" ${configFile} 33 | sed -i "s|VAR_CLOUD|${cloud}|g" ${configFile} 34 | sed -i "s|VAR_VCPU_RATIO|${vcpuRatio}|g" ${configFile} 35 | sed -i "s|VAR_RAM_RATIO|${ramRatio}|g" ${configFile} 36 | sed -i "s|VAR_DISK_RATIO|${diskRatio}|g" ${configFile} 37 | sed -i "s|VAR_SCHEDULABLE_INSTANCE_RAM|${schedulableInstanceRam}|g" ${configFile} 38 | sed -i "s|VAR_SCHEDULABLE_INSTANCE_VCPU|${schedulableInstanceVcpu}|g" ${configFile} 39 | sed -i "s|VAR_SCHEDULABLE_INSTANCE_DISK|${schedulableInstanceDisk}|g" ${configFile} 40 | sed -i "s|VAR_USE_NOVA_VOLUMES|${useNovaVolumes}|g" ${configFile} 41 | 42 | for i in ${enabledCollectors}; do 43 | sed -i "s/.*VAR_ENABLED_COLLECTORS/ - ${i}\n - VAR_ENABLED_COLLECTORS/g" ${configFile} 44 | done 45 | sed -i '/.*VAR_ENABLED_COLLECTORS.*/d' ${configFile} 46 | 47 | for i in ${swiftHosts}; do 48 | sed -i "s/.*VAR_SWIFT_HOSTS/ - ${i}\n - VAR_SWIFT_HOSTS/g" ${configFile} 49 | done 50 | sed -i '/.*VAR_SWIFT_HOSTS.*/d' ${configFile} 51 | 52 | for i in ${keystoneTenantsMap}; do 53 | tenantName=$(echo ${i} | cut -d',' -f1) 54 | tenantId=$( echo ${i} | cut -d',' -f2) 55 | sed -i "s/.*VAR_KEYSTONE_TENANTS_MAP/ - ${tenantName} ${tenantId}\n - VAR_KEYSTONE_TENANTS_MAP/g" ${configFile} 56 | done 57 | sed -i '/.*VAR_KEYSTONE_TENANTS_MAP.*/d' ${configFile} 58 | 59 | sed -i "s|VAR_RESELLER_PREFIX|${resellerPrefix}|g" ${configFile} 60 | sed -i "s|VAR_RING_PATH|${ringPath}|g" ${configFile} 61 | sed -i "s|VAR_HASH_PATH_PREFIX|${hashPathPrefix}|g" ${configFile} 62 | sed -i "s|VAR_HASH_PATH_SUFFIX|${hashPathSuffix}|g" ${configFile} 63 | 64 | sed -i 's/VAR_.*//g' ${configFile} 65 | 66 | touch ${cacheFileName} 67 | 68 | cat ${configFile} 69 | fi 70 | 71 | /prometheus-openstack-exporter ${configFile} 72 | 73 | rm ${cacheFileName} 74 | 75 | exit 0 76 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributor Guide 2 | 3 | Thank you for your interest in helping us improve this project! We're open to 4 | community contributions, suggestions, fixes, and feedback. This documentation 5 | will assist you in navigating through our processes. 6 | 7 | Make sure to review this guide thoroughly before beginning your contribution. It 8 | provides all the necessary details to increase the likelihood of your contribution 9 | being accepted. 10 | 11 | This project is hosted and managed on [GitHub](https://github.com). If you're new to GitHub 12 | and not familiar with how it works, their 13 | [quickstart documentation](https://docs.github.com/en/get-started/quickstart) 14 | provides an excellent introduction to all the tools and processes you'll need 15 | to know. 16 | 17 | ## Prerequisites 18 | 19 | Before you can begin, you will need to: 20 | 21 | * Read and agree to abide by our 22 | [Code of Conduct](https://ubuntu.com/community/code-of-conduct). 23 | 24 | * Sign the Canonical 25 | [contributor license agreement](https://ubuntu.com/legal/contributors). This 26 | grants us your permission to use your contributions in the project. 27 | 28 | * Create (or have) a GitHub account. 29 | 30 | * If you're working in a local environment, it's important to create a signing 31 | key, typically using GPG or SSH, and register it in your GitHub account to 32 | verify the origin of your code changes. For instructions on setting this up, 33 | please refer to 34 | [Managing commit signature verification](https://docs.github.com/en/authentication/managing-commit-signature-verification). 35 | 36 | ## Contributing Code 37 | 38 | ### Workflow 39 | 40 | 1. **Choose/Create an Issue**: Before starting work on an enhancement, create an issue that explains your use case. This helps track progress and keeps the discussion organized. The issue will be tracked on the GitHub issue page. 41 | 42 | 2. **Fork the Repository**: Create a fork of the repository to make your changes. 43 | 44 | 3. **Create a New Branch**: Make sure to create a new branch for your contribution. 45 | 46 | 4. **Commit your changes**: Commit messages should be well-structured and provide a meaningful explanation of the changes made 47 | 48 | 5. **Submit a Pull Request**: Submit a pull request to merge your changes into the main branch. Reference the issue by adding issue link or `Fixes: #xxx` (replace `xxx` with the issue number) to automatically link the issue to your PR. 49 | 50 | 6. **Review Process**: A team member will review your pull request. They may suggest changes or leave comments, so keep an eye on the PR status and be ready to make updates if needed. 51 | 52 | 7. **Documentation**: Any documentation changes should be included as part of your PR or as a separate PR linked to your original PR. 53 | 54 | 55 | ### Hard Requirements 56 | 57 | - **Testing and Code Coverage**: Changes must be accompanied by appropriate unit tests and meet the project's code coverage requirements. Functional and integration tests should be added when applicable to ensure the stability of the codebase. 58 | 59 | - **Sign Your Commits**: Be sure to [sign your commits](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits), refer to the [Prerequisites](#prerequisites) section. 60 | 61 | ## Code of Conduct 62 | 63 | This project follows the Ubuntu Code of Conduct. You can read it in full [here](https://ubuntu.com/community/code-of-conduct). 64 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | 7 | [tool.setuptools_scm] 8 | 9 | [tool.flake8] 10 | max-line-length = 99 11 | max-doc-length = 99 12 | max-complexity = 10 13 | exclude = [ 14 | ".git", 15 | "__pycache__", 16 | ".tox", 17 | ".build", 18 | "build", 19 | "dist", 20 | ".eggs", 21 | "*.egg_info", 22 | "venv", 23 | ".venv", 24 | "report", 25 | "docs", 26 | "lib", 27 | "mod", 28 | "hooks/charmhelpers", 29 | "tests/charmhelpers", 30 | ] 31 | select = ["E", "W", "F", "C", "N", "R", "D", "H"] 32 | # Ignore W503, E501 because using black creates errors with this 33 | # Ignore D107 Missing docstring in __init__ 34 | # Ignore D415 Docstring first line punctuation (doesn't make sense for properties) 35 | # Ignore N818 Exceptions end with "Error" (not all exceptions are errors) 36 | # D100, D101, D102, D103: Ignore missing docstrings in tests 37 | ignore = ["C901", "W503", "E501", "D107", "D415", "N818", "D100", "D101", "D102", "D103", "W504"] 38 | per-file-ignores = ["tests/*:D100,D101,D102,D103,D104"] 39 | # Check for properly formatted copyright header in each file 40 | copyright-check = "True" 41 | copyright-author = "Canonical Ltd." 42 | copyright-regexp = "Copyright\\s\\d{4}([-,]\\d{4})*\\s+%(author)s" 43 | 44 | [tool.black] 45 | line-length = 99 46 | exclude = ''' 47 | /( 48 | | .eggs 49 | | .git 50 | | .tox 51 | | .venv 52 | | .build 53 | | build 54 | | lib 55 | | report 56 | | docs 57 | | mod 58 | | hooks/charmhelpers 59 | | tests/charmhelpers 60 | )/ 61 | ''' 62 | 63 | [tool.isort] 64 | profile = "black" 65 | line_length = 99 66 | skip_glob = [".eggs", ".git", ".tox", ".venv", ".build", "build", "lib", "report", "mod/*", "hooks/charmhelpers", "tests/charmhelpers"] 67 | 68 | [tool.pylint] 69 | max-line-length = 99 70 | disable = ["E1102"] 71 | ignore = ['.eggs', '.git', '.tox', '.venv', '.build', 'lib', 'report', 'tests', 'docs', "mod", "hooks/charmhelpers", "tests/charmhelpers"] 72 | 73 | [tool.mypy] 74 | warn_unused_ignores = true 75 | warn_unused_configs = true 76 | warn_unreachable = true 77 | disallow_untyped_defs = true 78 | ignore_missing_imports = true 79 | no_namespace_packages = true 80 | exclude = ['.eggs', '.git', '.tox', '.venv', '.build', 'lib', 'report', 'tests', 'docs', "mod", "hooks/charmhelpers", "tests/charmhelpers"] 81 | 82 | [tool.codespell] 83 | skip = ".eggs,.tox,.git,.venv,venv,build,.build,lib,report,docs,poetry.lock,htmlcov,mod,hooks/charmhelpers,tests/charmhelpers" 84 | quiet-level = 3 85 | check-filenames = true 86 | ignore-words-list = "assertIn" 87 | 88 | ## Ignore unsupported imports 89 | [[tool.mypy.overrides]] 90 | module = ["charmhelpers.*", "setuptools"] 91 | ignore_missing_imports = true 92 | 93 | [tool.coverage.run] 94 | relative_files = true 95 | source = ["."] 96 | omit = ["tests/**", "docs/**", "lib/**", "snap/**", "build/**", "setup.py", "mod/**", "hooks/charmhelpers/**", "tests/charmhelpers/**"] 97 | 98 | [tool.coverage.report] 99 | fail_under = 100 100 | show_missing = true 101 | 102 | [tool.coverage.html] 103 | directory = "tests/report/html" 104 | 105 | [tool.coverage.xml] 106 | output = "tests/report/coverage.xml" 107 | -------------------------------------------------------------------------------- /tests/test_poe.py: -------------------------------------------------------------------------------- 1 | """Unit Test for Prometheus OpenStack exporter.""" 2 | 3 | import unittest 4 | 5 | import mock 6 | 7 | import prometheus_openstack_exporter as poe 8 | 9 | 10 | class TestPrometheusOpenstackExporter(unittest.TestCase): 11 | def test_data_gatherer_needed(self): 12 | self.assertTrue( 13 | poe.data_gatherer_needed( 14 | {"enabled_collectors": ["cinder", "neutron", "nova", "swift"]} 15 | ) 16 | ) 17 | self.assertTrue( 18 | poe.data_gatherer_needed( 19 | { 20 | "enabled_collectors": [ 21 | "cinder", 22 | "neutron", 23 | "nova", 24 | "swift", 25 | "swift-account-usage", 26 | ] 27 | } 28 | ) 29 | ) 30 | self.assertFalse(poe.data_gatherer_needed({"enabled_collectors": ["swift-account-usage"]})) 31 | self.assertFalse( 32 | poe.data_gatherer_needed({"enabled_collectors": ["swift", "swift-account-usage"]}) 33 | ) 34 | self.assertEqual( 35 | poe.data_gatherer_needed( 36 | {"enabled_collectors": ["cinder", "neutron", "nova", "swift"]} 37 | ), 38 | set(["cinder", "nova", "neutron"]), 39 | ) 40 | self.assertEqual( 41 | poe.data_gatherer_needed({}), 42 | set(["cinder", "nova", "neutron"]), 43 | ) 44 | 45 | @mock.patch("prometheus_openstack_exporter.config") 46 | def test_get_nova_info(self, config): 47 | config.return_value = {} 48 | prodstack = {"tenants": []} 49 | nova = mock.Mock() 50 | nova.aggregates = mock.MagicMock() 51 | nova.flavors = mock.MagicMock() 52 | nova.hypervisors = mock.MagicMock() 53 | nova.servers = mock.MagicMock() 54 | nova.servers.list = mock.MagicMock() 55 | nova.services = mock.MagicMock() 56 | 57 | data_gatherer = poe.DataGatherer() 58 | data_gatherer._get_nova_info(nova, None, prodstack) 59 | 60 | expected = [ 61 | mock.call( 62 | search_opts={ 63 | "marker": "", 64 | "limit": "100", 65 | "status": "ACTIVE", 66 | "all_tenants": "1", 67 | } 68 | ), 69 | mock.call( 70 | search_opts={ 71 | "marker": "", 72 | "limit": "100", 73 | "status": "ERROR", 74 | "all_tenants": "1", 75 | } 76 | ), 77 | mock.call( 78 | search_opts={ 79 | "marker": "", 80 | "limit": "100", 81 | "status": "SHELVED_OFFLOADED", 82 | "all_tenants": "1", 83 | } 84 | ), 85 | mock.call( 86 | search_opts={ 87 | "marker": "", 88 | "limit": "100", 89 | "status": "SHUTOFF", 90 | "all_tenants": "1", 91 | } 92 | ), 93 | mock.call( 94 | search_opts={ 95 | "marker": "", 96 | "limit": "100", 97 | "status": "SUSPENDED", 98 | "all_tenants": "1", 99 | } 100 | ), 101 | mock.call( 102 | search_opts={ 103 | "marker": "", 104 | "limit": "100", 105 | "status": "VERIFY_RESIZE", 106 | "all_tenants": "1", 107 | } 108 | ), 109 | ] 110 | nova.servers.list.assert_has_calls(expected, any_order=True) 111 | 112 | not_expected = mock.call( 113 | search_opts={ 114 | "marker": "", 115 | "limit": "100", 116 | "status": "BUILD", 117 | "all_tenants": "1", 118 | } 119 | ) 120 | self.assertTrue(not_expected not in nova.servers.list.call_args_list) 121 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Prometheus OpenStack exporter 2 | 3 | > [!NOTE] 4 | > This charm is deprecated. Please use the new charm [openstack-exporter](https://charmhub.io/openstack-exporter) instead. It is integrate with [COS](https://charmhub.io/cos-lite) natively. 5 | 6 | Exposes high level [OpenStack](http://www.openstack.org/) metrics to [Prometheus](https://prometheus.io/). 7 | 8 | Data can be visualised using [Grafana](https://grafana.com/) and the [OpenStack Clouds Dashboard](https://grafana.com/dashboards/7924) 9 | 10 | ## Deployment 11 | 12 | ### Requirements 13 | 14 | ``` 15 | sudo apt-get install python-neutronclient python-novaclient python-keystoneclient python-netaddr python-cinderclient 16 | ``` 17 | 18 | Install prometheus_client. On Ubuntu 16.04: 19 | ``` 20 | apt-get install python-prometheus-client 21 | ``` 22 | 23 | On Ubuntu 14.04: 24 | ``` 25 | pip install prometheus_client 26 | ``` 27 | 28 | ### Installation 29 | 30 | ``` 31 | # Copy example config in place, edit to your needs 32 | sudo cp prometheus-openstack-exporter.yaml /etc/prometheus/ 33 | 34 | ## Upstart 35 | # Install job 36 | sudo cp prometheus-openstack-exporter.conf /etc/init 37 | 38 | # Configure novarc location: 39 | sudo sh -c 'echo "NOVARC=/path/to/admin-novarc">/etc/default/prometheus-openstack-exporter' 40 | 41 | ## Systemd 42 | # Install job 43 | sudo cp prometheus-openstack-exporter.service /etc/systemd/system/ 44 | 45 | # create novarc 46 | sudo cat < /etc/prometheus-openstack-exporter/admin.novarc 47 | export OS_USERNAME=Admin 48 | export OS_TENANT_NAME=admin 49 | export OS_PASSWORD=XXXX 50 | export OS_REGION_NAME=cloudname 51 | export OS_AUTH_URL=http://XX.XX.XX.XX:35357/v2.0 52 | EOF 53 | 54 | # create default config location 55 | sudo sh -c 'echo "CONFIG_FILE=/etc/prometheus-openstack-exporter/prometheus-openstack-exporter.yaml">/etc/default/prometheus-openstack-exporter' 56 | 57 | 58 | # Start 59 | sudo start prometheus-openstack-exporter 60 | ``` 61 | 62 | Or to run interactively: 63 | 64 | ``` 65 | . /path/to/admin-novarc 66 | ./prometheus-openstack-exporter prometheus-openstack-exporter.yaml 67 | 68 | ``` 69 | 70 | Or use Docker Image: 71 | 72 | ``` 73 | # docker-compose.yml 74 | version: '2.1' 75 | services: 76 | ostackexporter: 77 | image: moghaddas/prom-openstack-exporter:latest 78 | # check this examle env file 79 | env_file: 80 | - ./admin.novarc.example 81 | restart: unless-stopped 82 | expose: 83 | - 9183 84 | ports: 85 | - 9183:9183 86 | 87 | # docker run 88 | docker run \ 89 | -itd \ 90 | --name prom_openstack_exporter \ 91 | -p 9183:9183 \ 92 | --env-file=$(pwd)/admin.novarc.example \ 93 | --restart=unless-stopped \ 94 | moghaddas/prom-openstack-exporter:latest 95 | 96 | ``` 97 | 98 | ## Configuration 99 | 100 | Configuration options are documented in prometheus-openstack-exporter.yaml shipped with this project 101 | 102 | ## FAQ 103 | 104 | ### Why are openstack_allocation_ratio values hardcoded? 105 | 106 | There is no way to retrieve them using OpenStack API. 107 | 108 | Alternative approach could be to hardcode those values in queries but this approach breaks when allocation ratios change. 109 | 110 | ### Why hardcode swift host list? 111 | 112 | Same as above, there is no way to retrieve swift hosts using API. 113 | 114 | ### Why not write dedicated swift exporter? 115 | 116 | Swift stats are included mainly because they are trivial to retrieve. If and when standalone swift exporter appears we can revisit this approach 117 | 118 | ### Why cache data? 119 | 120 | We are aware that Prometheus best practise is to avoid caching. Unfortunately queries we need to run are very heavy and in bigger clouds can take minutes to execute. This is problematic not only because of delays but also because multiple servers scraping the exporter could have negative impact on the cloud performance 121 | 122 | ### How are Swift account metrics obtained? 123 | 124 | Fairly simply! Given a copy of the Swift rings (in fact, we just need 125 | account.ring.gz) we can load this up and then ask it where particular 126 | accounts are located in the cluster. We assume that Swift is 127 | replicating properly, pick a node at random, and ask it for the 128 | account's statistics with an HTTP HEAD request, which it returns. 129 | 130 | ### How hard would it be to export Swift usage by container? 131 | 132 | Sending a GET request to the account URL yields a list of containers 133 | (probably paginated, so watch out for that!). In order to write a 134 | container-exporter, one could add some code to fetch a list of 135 | containers from the account server, load up the container ring, and 136 | then use container_ring.get_nodes(account, container) and HTTP HEAD on 137 | one of the resulting nodes to get a containers' statistics, although 138 | without some caching cleverness this will scale poorly. 139 | 140 | ## Known Issues 141 | ### EOFError by pickle.py 142 | 143 | You should wait. It needs dump file to generate metrics 144 | -------------------------------------------------------------------------------- /.github/workflows/check.yaml: -------------------------------------------------------------------------------- 1 | # This file is centrally managed as a template file in https://github.com/canonical/solutions-engineering-automation 2 | # To update the file: 3 | # - Edit it in the canonical/solutions-engineering-automation repository. 4 | # - Open a PR with the changes. 5 | # - When the PR merges, the soleng-terraform bot will open a PR to the target repositories with the changes. 6 | name: Tests 7 | 8 | on: 9 | workflow_call: 10 | workflow_dispatch: 11 | pull_request: 12 | types: [opened, synchronize, reopened] 13 | branches: [main] 14 | paths-ignore: 15 | - "**.md" 16 | - "**.rst" 17 | 18 | concurrency: 19 | group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} 20 | cancel-in-progress: true 21 | 22 | jobs: 23 | lint: 24 | runs-on: ubuntu-22.04 25 | steps: 26 | - uses: actions/checkout@v4 27 | with: 28 | fetch-depth: 0 # Complete git history is required to generate the version from git tags. 29 | 30 | - name: Set up Python 3.10 31 | uses: actions/setup-python@v5 32 | with: 33 | python-version: "3.10" 34 | 35 | - name: Install dependencies 36 | run: | 37 | sudo apt update 38 | sudo apt install -y yamllint 39 | python -m pip install --upgrade pip 40 | # pin tox to the current major version to avoid 41 | # workflows breaking all at once when a new major version is released. 42 | python -m pip install 'tox<5' 43 | 44 | - name: Run linters 45 | run: tox -e lint 46 | 47 | - name: Lint yaml files 48 | run: | 49 | yamllint .yamllint snap/snapcraft.yaml 50 | 51 | unit: 52 | name: Unit 53 | strategy: 54 | fail-fast: false 55 | matrix: 56 | python-version: ['3.10'] 57 | runs-on: ubuntu-22.04 58 | steps: 59 | - uses: actions/checkout@v4 60 | with: 61 | submodules: true 62 | 63 | - name: Set up Python ${{ matrix.python-version }} 64 | uses: actions/setup-python@v5 65 | with: 66 | python-version: ${{ matrix.python-version }} 67 | 68 | - name: Install dependencies 69 | run: | 70 | python -m pip install --upgrade pip 71 | python -m pip install 'tox<5' 72 | 73 | - name: Run unit tests 74 | run: tox -e unit 75 | 76 | - name: Determine system architecture 77 | run: echo "SYSTEM_ARCH=$(uname -m)" >> $GITHUB_ENV 78 | 79 | - name: Create artifact name suffix 80 | run: | 81 | PYTHON_VERSION_SANITIZED=${{ matrix.python-version }} 82 | PYTHON_VERSION_SANITIZED=${PYTHON_VERSION_SANITIZED//./-} 83 | echo "ARTIFACT_SUFFIX=$PYTHON_VERSION_SANITIZED-${{ env.SYSTEM_ARCH }}" >> $GITHUB_ENV 84 | 85 | - name: Rename Unit Test Coverage Artifact 86 | run: | 87 | if [ -e ".coverage-unit" ]; then 88 | mv .coverage-unit .coverage-unit-${{ env.ARTIFACT_SUFFIX }} 89 | else 90 | echo "No coverage file found, skipping rename" 91 | fi 92 | 93 | - name: Upload Unit Test Coverage File 94 | uses: actions/upload-artifact@v4 95 | with: 96 | include-hidden-files: true 97 | if-no-files-found: ignore 98 | name: coverage-unit-${{ env.ARTIFACT_SUFFIX }} 99 | path: .coverage-unit-${{ env.ARTIFACT_SUFFIX }} 100 | 101 | build: 102 | needs: 103 | - lint 104 | runs-on: ${{ matrix.runs-on }} 105 | strategy: 106 | fail-fast: false 107 | matrix: 108 | runs-on: [[ubuntu-24.04], [self-hosted, jammy, ARM64]] 109 | steps: 110 | - uses: actions/checkout@v4 111 | with: 112 | fetch-depth: 0 # Complete git history is required to generate the version from git tags. 113 | 114 | - name: Verify snap builds successfully 115 | id: build 116 | uses: canonical/action-build@v1 117 | 118 | - name: Determine system architecture 119 | run: echo "SYSTEM_ARCH=$(uname -m)" >> $GITHUB_ENV 120 | 121 | - name: Upload the built snap 122 | uses: actions/upload-artifact@v4 123 | with: 124 | name: snap_${{ env.SYSTEM_ARCH }} 125 | path: ${{ steps.build.outputs.snap }} 126 | 127 | func: 128 | needs: 129 | - build 130 | runs-on: ${{ matrix.runs-on }} 131 | strategy: 132 | fail-fast: false 133 | matrix: 134 | runs-on: [[ubuntu-24.04], [self-hosted, jammy, ARM64]] 135 | steps: 136 | - uses: actions/checkout@v4 137 | with: 138 | fetch-depth: 0 # Complete git history is required to generate the version from git tags. 139 | 140 | - name: Determine system architecture 141 | run: echo "SYSTEM_ARCH=$(uname -m)" >> $GITHUB_ENV 142 | 143 | - name: Download snap file artifact 144 | uses: actions/download-artifact@v4 145 | with: 146 | name: snap_${{ env.SYSTEM_ARCH }} 147 | 148 | - name: Set up Python 3.10 149 | uses: actions/setup-python@v5 150 | with: 151 | python-version: "3.10" 152 | 153 | - name: Install dependencies 154 | run: | 155 | python -m pip install --upgrade pip 156 | python -m pip install 'tox<5' 157 | 158 | - name: Run func tests 159 | run: | 160 | export TEST_SNAP="$(pwd)/$(ls | grep '.*_.*\.snap$')" 161 | echo "$TEST_SNAP" 162 | tox -e func 163 | 164 | - name: Create artifact name suffix 165 | run: | 166 | BASE_VERSION_SANITIZED=${{ matrix.runs-on }} 167 | BASE_VERSION_SANITIZED=${BASE_VERSION_SANITIZED//./-} 168 | echo "ARTIFACT_SUFFIX=$BASE_VERSION_SANITIZED-${{ env.SYSTEM_ARCH }}" >> $GITHUB_ENV 169 | 170 | - name: Rename Functional Test Coverage Artifact 171 | run: | 172 | if [ -e ".coverage-func" ]; then 173 | mv .coverage-func .coverage-func-${{ env.ARTIFACT_SUFFIX }} 174 | else 175 | echo "No coverage file found, skipping rename" 176 | fi 177 | 178 | - name: Upload Functional Test Coverage Artifact 179 | uses: actions/upload-artifact@v4 180 | with: 181 | include-hidden-files: true 182 | if-no-files-found: ignore 183 | name: coverage-functional-${{ env.ARTIFACT_SUFFIX }} 184 | path: .coverage-func-${{ env.ARTIFACT_SUFFIX }} 185 | 186 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /prometheus-openstack-exporter: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | OpenStack exporter for the prometheus monitoring system. 4 | 5 | Copyright (C) 2016-2019 Canonical, Ltd. 6 | Authors: 7 | Jacek Nykis 8 | Laurent Sesques 9 | Paul Collins 10 | Chris Martin 11 | 12 | This program is free software: you can redistribute it and/or modify 13 | it under the terms of the GNU General Public License version 3, 14 | as published by the Free Software Foundation. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranties of 18 | MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. 19 | See the GNU General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License 22 | along with this program. If not, see . 23 | """ 24 | # We must import and monkey patch before importing any other modules: 25 | # https://eventlet.readthedocs.io/en/latest/patching.html 26 | import eventlet 27 | 28 | eventlet.patcher.monkey_patch() 29 | 30 | # Ignore lint errors for E402 (module level import not at top of file), 31 | # because they cannot be at top of file here because of the monkey patching above. 32 | import argparse # noqa: E402 33 | import ast # noqa: E402 34 | import json # noqa: E402 35 | import logging.handlers # noqa: E402 36 | import pickle # noqa: E402 37 | import random # noqa: E402 38 | import traceback # noqa: E402 39 | import urllib.parse # noqa: E402 40 | from http.server import BaseHTTPRequestHandler # noqa: E402 41 | from http.server import HTTPServer # noqa: E402 42 | from os import environ as env # noqa: E402 43 | from os import path, rename # noqa: E402 44 | from threading import Thread # noqa: E402 45 | from time import sleep, time # noqa: E402 46 | 47 | import requests # noqa: E402 48 | import swift.common.utils # noqa: E402 49 | import yaml # noqa: E402 50 | from cinderclient.v3 import client as cinder_client # noqa: E402 51 | from netaddr import IPRange # noqa: E402 52 | from neutronclient.v2_0 import client as neutron_client # noqa: E402 53 | 54 | # from novaclient.v1_1 import client as nova_client 55 | # http://docs.openstack.org/developer/python-novaclient/api.html 56 | from novaclient import client as nova_client # noqa: E402 57 | from prometheus_client import ( # noqa: E402 58 | CONTENT_TYPE_LATEST, 59 | CollectorRegistry, 60 | Gauge, 61 | generate_latest, 62 | ) 63 | from swift.common.ring.ring import Ring # noqa: E402 64 | 65 | config = None 66 | log = logging.getLogger("poe-logger") 67 | 68 | 69 | def get_creds_dict(*names): 70 | """Get dictionary with cred envvars.""" 71 | return {name: env["OS_%s" % name.upper()] for name in names if "OS_%s" % name.upper() in env} 72 | 73 | 74 | def get_creds_list(*names): 75 | """Get list with cred envvars, error if not set.""" 76 | return [env["OS_%s" % name.upper()] for name in names] 77 | 78 | 79 | def maybe_get_cacert(): 80 | """Get cacert, None if unset.""" 81 | return env.get("OS_CACERT") 82 | 83 | 84 | def get_clients(): 85 | """Return openstack clients.""" 86 | ks_version = int(env.get("OS_IDENTITY_API_VERSION", 2)) 87 | if ks_version == 2: 88 | from keystoneclient.v2_0 import client as keystone_client 89 | 90 | # Legacy v2 env vars: 91 | # OS_USERNAME OS_PASSWORD OS_TENANT_NAME OS_AUTH_URL OS_REGION_NAME 92 | ks_creds = get_creds_dict("username", "password", "tenant_name", "auth_url", "region_name") 93 | cacert = maybe_get_cacert() 94 | if cacert: 95 | ks_creds["cacert"] = cacert 96 | nova_creds = [2] + get_creds_list("username", "password", "tenant_name", "auth_url") 97 | cinder_creds = get_creds_list("username", "password", "tenant_name", "auth_url") 98 | keystone = keystone_client.Client(**ks_creds) 99 | nova = nova_client.Client(*nova_creds, cacert=cacert) 100 | neutron = neutron_client.Client(**ks_creds) 101 | cinder = cinder_client.Client(*cinder_creds, cacert=cacert) 102 | 103 | elif ks_version == 3: 104 | from keystoneauth1 import session 105 | from keystoneauth1.identity import v3 106 | from keystoneclient.v3 import client 107 | 108 | # A little helper for the poor human trying to figure out which env vars 109 | # are needed, it worked for me (jjo) having: 110 | # OS_USERNAME OS_PASSWORD OS_USER_DOMAIN_NAME OS_AUTH_URL 111 | # OS_PROJECT_DOMAIN_NAME OS_PROJECT_DOMAIN_ID OS_PROJECT_ID OS_DOMAIN_NAME 112 | # Keystone needs domain creds for e.g. project list 113 | # project and project_domain are needed for listing projects 114 | ks_creds_domain = get_creds_dict( 115 | "username", 116 | "password", 117 | "user_domain_name", 118 | "auth_url", 119 | "project_domain_name", 120 | "project_name", 121 | "project_domain_id", 122 | "project_id", 123 | ) 124 | # Need non-domain creds to get full catalog 125 | ks_creds_admin = get_creds_dict( 126 | "username", 127 | "password", 128 | "user_domain_name", 129 | "auth_url", 130 | "project_domain_name", 131 | "project_name", 132 | "project_domain_id", 133 | "project_id", 134 | ) 135 | auth_domain = v3.Password(**ks_creds_domain) 136 | auth_admin = v3.Password(**ks_creds_admin) 137 | # Need to pass in cacert separately 138 | verify = maybe_get_cacert() 139 | if verify is None: 140 | verify = True 141 | sess_domain = session.Session(auth=auth_domain, verify=verify) 142 | sess_admin = session.Session(auth=auth_admin, verify=verify) 143 | 144 | interface = env.get("OS_INTERFACE", "admin") 145 | 146 | region_name = env.get("OS_REGION_NAME", None) 147 | 148 | # Keystone has not switched from interface to endpoint_type yet 149 | keystone = client.Client(session=sess_domain, interface=interface) 150 | nova = nova_client.Client( 151 | 2, session=sess_admin, endpoint_type=interface, region_name=region_name 152 | ) 153 | neutron = neutron_client.Client( 154 | session=sess_admin, endpoint_type=interface, region_name=region_name 155 | ) 156 | cinder = cinder_client.Client( 157 | session=sess_admin, endpoint_type=interface, region_name=region_name 158 | ) 159 | 160 | else: 161 | raise ValueError 162 | log.debug("Client setup done, keystone ver {}".format(ks_version)) 163 | return (keystone, nova, neutron, cinder) 164 | 165 | 166 | class DataGatherer(Thread): 167 | """Periodically retrieve data from openstack in a separate thread. 168 | 169 | Save as pickle to cache_file. 170 | """ 171 | 172 | def __init__(self): 173 | """Initialize DataGatherer.""" 174 | Thread.__init__(self) 175 | self.daemon = True 176 | self.duration = 0 177 | self.refresh_interval = config.get("cache_refresh_interval", 900) 178 | self.cache_file = config["cache_file"] 179 | self.use_nova_volumes = config.get("use_nova_volumes", True) 180 | 181 | def _get_keystone_info(self, keystone): 182 | """Return a dict containing tentants details.""" 183 | info = {} 184 | try: 185 | info["tenants"] = [x._info for x in keystone.tenants.list()] 186 | except AttributeError: 187 | log.info("Error getting tenants.list, continue with projects.list") 188 | info["tenants"] = [x._info for x in keystone.projects.list()] 189 | log.debug("Number of projects: %s", len(info["tenants"])) 190 | return info 191 | 192 | def _get_neutron_info(self, neutron): 193 | """Return neutron resources details.""" 194 | info = {} 195 | info["floatingips"] = neutron.list_floatingips()["floatingips"] 196 | info["networks"] = neutron.list_networks()["networks"] 197 | info["ports"] = neutron.list_ports()["ports"] 198 | info["routers"] = neutron.list_routers()["routers"] 199 | info["subnets"] = neutron.list_subnets()["subnets"] 200 | return info 201 | 202 | def _get_nova_info(self, nova, cinder, prodstack): 203 | """Return nova resources details.""" 204 | info = {} 205 | info["hypervisors"] = [x._info for x in nova.hypervisors.list()] 206 | info["services"] = [x._info for x in nova.services.list()] 207 | info["flavors"] = [x._info for x in nova.flavors.list(is_public=None)] 208 | info["aggregates"] = [x.to_dict() for x in nova.aggregates.list()] 209 | 210 | info["instances"] = [] 211 | # Exclude instances in 'BUILD' state as they cannot be used as markers: 212 | # https://github.com/CanonicalLtd/prometheus-openstack-exporter/issues/90 213 | valid_statuses = [ 214 | "ACTIVE", 215 | "ERROR", 216 | "SHELVED_OFFLOADED", 217 | "SHUTOFF", 218 | "SUSPENDED", 219 | "VERIFY_RESIZE", 220 | ] 221 | for status in valid_statuses: 222 | marker = "" 223 | while True: 224 | search_opts = { 225 | "all_tenants": "1", 226 | "limit": "100", 227 | "marker": marker, 228 | "status": status, 229 | } 230 | new_instances = [x._info for x in nova.servers.list(search_opts=search_opts)] 231 | if new_instances: 232 | marker = new_instances[-1]["id"] 233 | info["instances"].extend(new_instances) 234 | else: 235 | break 236 | 237 | info["volume_quotas"] = {} 238 | info["nova_quotas"] = {} 239 | for t in prodstack["tenants"]: 240 | tid = t["id"] 241 | if self.use_nova_volumes: 242 | info["volume_quotas"][tid] = cinder.quotas.get(tid, usage=True)._info 243 | # old OS versions (e.g. Mitaka) will 404 if we request details 244 | try: 245 | info["nova_quotas"][tid] = nova.quotas.get(tid, detail=True)._info 246 | except Exception: 247 | info["nova_quotas"][tid] = nova.quotas.get(tid)._info 248 | return info 249 | 250 | def run(self): 251 | """Start collecting openstack resources details.""" 252 | log.debug("Starting data gather thread") 253 | prodstack = {} 254 | while True: 255 | log.debug("DataGatherer: Start refresh") 256 | start_time = time() 257 | try: 258 | keystone, nova, neutron, cinder = get_clients() 259 | 260 | log.debug("DataGatherer: Update keystone") 261 | prodstack.update(self._get_keystone_info(keystone)) 262 | log.debug("DataGatherer: Update neutron") 263 | prodstack.update(self._get_neutron_info(neutron)) 264 | log.debug("DataGatherer: Update nova") 265 | prodstack.update(self._get_nova_info(nova, cinder, prodstack)) 266 | 267 | except Exception: 268 | # Ignore failures, we will try again after refresh_interval. 269 | # Most of them are temporary ie. connectivity problems 270 | # To alert on stale cache use 271 | # openstack_exporter_cache_age_seconds metric 272 | log.critical("Error getting stats: {}".format(traceback.format_exc())) 273 | else: 274 | with open(self.cache_file + ".new", "wb+") as f: 275 | pickle.dump((prodstack,), f, pickle.HIGHEST_PROTOCOL) 276 | rename(self.cache_file + ".new", self.cache_file) 277 | log.debug("Done dumping stats to {}".format(self.cache_file)) 278 | self.duration = time() - start_time 279 | log.debug("DataGatherer: Done, duration={}".format(self.duration)) 280 | sleep(self.refresh_interval) 281 | 282 | def get_stats(self): 283 | """Return collection statistics.""" 284 | registry = CollectorRegistry() 285 | labels = ["cloud"] 286 | age = Gauge( 287 | "openstack_exporter_cache_age_seconds", 288 | "Cache age in seconds. It can reset more frequently " 289 | "than scraping interval so we use Gauge", 290 | labels, 291 | registry=registry, 292 | ) 293 | label_values = [config["cloud"]] 294 | age.labels(*label_values).set(time() - path.getmtime(self.cache_file)) 295 | duration = Gauge( 296 | "openstack_exporter_cache_refresh_duration_seconds", 297 | "Cache refresh duration in seconds.", 298 | labels, 299 | registry=registry, 300 | ) 301 | duration.labels(*label_values).set(self.duration) 302 | return generate_latest(registry) 303 | 304 | 305 | class Neutron: 306 | """Class to manage neutron resources metrics collection.""" 307 | 308 | def __init__(self): 309 | """Initialize Neutron collector.""" 310 | self.registry = CollectorRegistry() 311 | self.prodstack = {} 312 | with open(config["cache_file"], "rb") as f: 313 | self.prodstack = pickle.load(f)[0] 314 | 315 | self.tenant_map = {t["id"]: t["name"] for t in self.prodstack["tenants"]} 316 | self.network_map = {n["id"]: n["name"] for n in self.prodstack["networks"]} 317 | self.subnet_map = { 318 | n["id"]: {"name": n["name"], "pool": n["allocation_pools"]} 319 | for n in self.prodstack["subnets"] 320 | } 321 | self.routers = self.prodstack["routers"] 322 | self.ports = self.prodstack["ports"] 323 | self.floating_ips = self.prodstack["floatingips"] 324 | 325 | def _get_router_ip(self, uuid): 326 | owner = "network:router_gateway" 327 | for port in self.ports: 328 | if port["device_id"] == uuid and port["device_owner"] == owner: 329 | if port["status"] == "ACTIVE" and port["fixed_ips"]: 330 | return port["fixed_ips"][0]["ip_address"] 331 | 332 | def get_floating_ips(self): 333 | """Collect Floating IPs.""" 334 | ips = {} 335 | for ip in self.floating_ips: 336 | subnet = self.network_map[ip["floating_network_id"]] 337 | try: 338 | tenant = self.tenant_map[ip["tenant_id"]] 339 | except KeyError: 340 | tenant = "Unknown tenant ({})".format(ip["tenant_id"]) 341 | key = ( 342 | config["cloud"], 343 | subnet, 344 | tenant, 345 | ip["tenant_id"], 346 | "floatingip", 347 | ip["status"], 348 | ) 349 | if key in ips: 350 | ips[key] += 1 351 | else: 352 | ips[key] = 1 353 | return ips 354 | 355 | def get_router_ips(self): 356 | """Collect Router IPs.""" 357 | ips = {} 358 | for r in self.routers: 359 | if self._get_router_ip(r["id"]): 360 | if r["tenant_id"].startswith(" 0: 495 | return min( 496 | int(free_vcpus / s["vcpu"]), 497 | int(free_ram_mbs / s["ram_mbs"]), 498 | int(free_disk_gbs / s["disk_gbs"]), 499 | ) 500 | else: 501 | return min(int(free_vcpus / s["vcpu"]), int(free_ram_mbs / s["ram_mbs"])) 502 | 503 | def _get_schedulable_instances_capacity(self, host): 504 | capacity_vcpus = host["vcpus"] * config["openstack_allocation_ratio_vcpu"] 505 | capacity_ram_mbs = host["memory_mb"] * config["openstack_allocation_ratio_ram"] 506 | capacity_disk_gbs = host["local_gb"] * config["openstack_allocation_ratio_disk"] 507 | s = config["schedulable_instance_size"] 508 | if s["disk_gbs"] > 0: 509 | return min( 510 | int(capacity_vcpus / s["vcpu"]), 511 | int(capacity_ram_mbs / s["ram_mbs"]), 512 | int(capacity_disk_gbs / s["disk_gbs"]), 513 | ) 514 | else: 515 | return min(int(capacity_vcpus / s["vcpu"]), int(capacity_ram_mbs / s["ram_mbs"])) 516 | 517 | def gen_hypervisor_stats(self): 518 | """Collect Nova Hypervisors statistics.""" 519 | labels = [ 520 | "cloud", 521 | "hypervisor_hostname", 522 | "aggregate", 523 | "nova_service_status", 524 | "arch", 525 | ] 526 | vms = Gauge( 527 | "hypervisor_running_vms", 528 | "Number of running VMs", 529 | labels, 530 | registry=self.registry, 531 | ) 532 | vcpus_total = Gauge( 533 | "hypervisor_vcpus_total", 534 | "Total number of vCPUs", 535 | labels, 536 | registry=self.registry, 537 | ) 538 | vcpus_used = Gauge( 539 | "hypervisor_vcpus_used", 540 | "Number of used vCPUs", 541 | labels, 542 | registry=self.registry, 543 | ) 544 | mem_total = Gauge( 545 | "hypervisor_memory_mbs_total", 546 | "Total amount of memory in MBs", 547 | labels, 548 | registry=self.registry, 549 | ) 550 | mem_used = Gauge( 551 | "hypervisor_memory_mbs_used", 552 | "Used memory in MBs", 553 | labels, 554 | registry=self.registry, 555 | ) 556 | disk_total = Gauge( 557 | "hypervisor_disk_gbs_total", 558 | "Total amount of disk space in GBs", 559 | labels, 560 | registry=self.registry, 561 | ) 562 | disk_used = Gauge( 563 | "hypervisor_disk_gbs_used", 564 | "Used disk space in GBs", 565 | labels, 566 | registry=self.registry, 567 | ) 568 | schedulable_instances = Gauge( 569 | "hypervisor_schedulable_instances", 570 | 'Number of schedulable instances, see "schedulable_instance_size" option', 571 | labels, 572 | registry=self.registry, 573 | ) 574 | schedulable_instances_capacity = Gauge( 575 | "hypervisor_schedulable_instances_capacity", 576 | "Number of schedulable instances we have capacity for", 577 | labels, 578 | registry=self.registry, 579 | ) 580 | 581 | def squashnone(val, default=0): 582 | if val is None: 583 | return default 584 | return val 585 | 586 | for h in self.hypervisors: 587 | log.debug("Hypervisor: %s", h) 588 | host = h["service"]["host"] 589 | log.debug("host: %s", host) 590 | cpu_info = h["cpu_info"] 591 | log.debug("cpu_info: %s", cpu_info) 592 | arch = "Unknown" 593 | if not cpu_info: 594 | log.info("Could not get cpu info") 595 | elif not isinstance(cpu_info, dict): 596 | cpu_info = json.loads(cpu_info) 597 | arch = cpu_info["arch"] 598 | 599 | at_least_one_aggregate = False 600 | for agg in self.prodstack["aggregates"]: 601 | agg_key = host + "_" + agg["name"] 602 | if self.aggregate_map.get(agg_key) is None: 603 | continue 604 | at_least_one_aggregate = True 605 | label_values = [ 606 | config["cloud"], 607 | host, 608 | self.aggregate_map[agg_key], 609 | self.services_map[host], 610 | arch, 611 | ] 612 | # Disabled hypervisors return None below, convert to 0 613 | vms.labels(*label_values).set(squashnone(h["running_vms"])) 614 | vcpus_total.labels(*label_values).set(squashnone(h["vcpus"])) 615 | vcpus_used.labels(*label_values).set(squashnone(h["vcpus_used"])) 616 | mem_total.labels(*label_values).set(squashnone(h["memory_mb"])) 617 | mem_used.labels(*label_values).set(squashnone(h["memory_mb_used"])) 618 | disk_total.labels(*label_values).set(squashnone(h["local_gb"])) 619 | disk_used.labels(*label_values).set(squashnone(h["local_gb_used"])) 620 | 621 | if config.get("schedulable_instance_size", False): 622 | schedulable_instances.labels(*label_values).set( 623 | self._get_schedulable_instances(h) 624 | ) 625 | schedulable_instances_capacity.labels(*label_values).set( 626 | self._get_schedulable_instances_capacity(h) 627 | ) 628 | 629 | # host isn't part of any aggregate 630 | if not at_least_one_aggregate: 631 | label_values = [ 632 | config["cloud"], 633 | host, 634 | "unknown", 635 | self.services_map[host], 636 | arch, 637 | ] 638 | # Disabled hypervisors return None below, convert to 0 639 | vms.labels(*label_values).set(squashnone(h["running_vms"])) 640 | vcpus_total.labels(*label_values).set(squashnone(h["vcpus"])) 641 | vcpus_used.labels(*label_values).set(squashnone(h["vcpus_used"])) 642 | mem_total.labels(*label_values).set(squashnone(h["memory_mb"])) 643 | mem_used.labels(*label_values).set(squashnone(h["memory_mb_used"])) 644 | disk_total.labels(*label_values).set(squashnone(h["local_gb"])) 645 | disk_used.labels(*label_values).set(squashnone(h["local_gb_used"])) 646 | 647 | if config.get("schedulable_instance_size", False): 648 | schedulable_instances.labels(*label_values).set( 649 | self._get_schedulable_instances(h) 650 | ) 651 | schedulable_instances_capacity.labels(*label_values).set( 652 | self._get_schedulable_instances_capacity(h) 653 | ) 654 | 655 | def gen_instance_stats(self): 656 | """Collect Nova instances statistics.""" 657 | missing_flavors = False 658 | instances = Gauge( 659 | "nova_instances", 660 | "Nova instances metrics", 661 | ["cloud", "name", "tenant", "tenant_id", "instance_state"], 662 | registry=self.registry, 663 | ) 664 | res_ram = Gauge( 665 | "nova_resources_ram_mbs", 666 | "Nova RAM usage metric", 667 | ["cloud", "tenant", "tenant_id"], 668 | registry=self.registry, 669 | ) 670 | res_vcpus = Gauge( 671 | "nova_resources_vcpus", 672 | "Nova vCPU usage metric", 673 | ["cloud", "tenant", "tenant_id"], 674 | registry=self.registry, 675 | ) 676 | res_disk = Gauge( 677 | "nova_resources_disk_gbs", 678 | "Nova disk usage metric", 679 | ["cloud", "tenant", "tenant_id"], 680 | registry=self.registry, 681 | ) 682 | for i in self.prodstack["instances"]: 683 | if i["tenant_id"] in self.tenant_map: 684 | tenant = self.tenant_map[i["tenant_id"]] 685 | else: 686 | tenant = "orphaned" 687 | instances.labels(config["cloud"], i["name"], tenant, i["tenant_id"], i["status"]).inc() 688 | 689 | if i["flavor"]["id"] in self.flavor_map: 690 | flavor = self.flavor_map[i["flavor"]["id"]] 691 | res_ram.labels(config["cloud"], tenant, i["tenant_id"]).inc(flavor["ram"]) 692 | res_vcpus.labels(config["cloud"], tenant, i["tenant_id"]).inc(flavor["vcpus"]) 693 | res_disk.labels(config["cloud"], tenant, i["tenant_id"]).inc(flavor["disk"]) 694 | else: 695 | missing_flavors = True 696 | 697 | # If flavors were deleted we can't reliably find out resouerce use 698 | if missing_flavors: 699 | self.registry.unregister(res_ram) 700 | self.registry.unregister(res_vcpus) 701 | self.registry.unregister(res_disk) 702 | res_ram = Gauge( 703 | "nova_resources_ram_mbs", 704 | "Nova RAM usage metric unavailable, missing flavors", 705 | [], 706 | registry=self.registry, 707 | ) 708 | res_vcpus = Gauge( 709 | "nova_resources_vcpus", 710 | "Nova vCPU usage metric unavailable, missing flavors", 711 | [], 712 | registry=self.registry, 713 | ) 714 | res_disk = Gauge( 715 | "nova_resources_disk_gbs", 716 | "Nova disk usage metric unavailable, missing flavors", 717 | [], 718 | registry=self.registry, 719 | ) 720 | 721 | def gen_overcommit_stats(self): 722 | """Calculate allocation ratio for vcpu, ram and disks.""" 723 | labels = ["cloud", "resource"] 724 | openstack_overcommit = Gauge( 725 | "openstack_allocation_ratio", 726 | "Openstack overcommit ratios", 727 | labels, 728 | registry=self.registry, 729 | ) 730 | label_values = [config["cloud"], "vcpu"] 731 | openstack_overcommit.labels(*label_values).set(config["openstack_allocation_ratio_vcpu"]) 732 | label_values = [config["cloud"], "ram"] 733 | openstack_overcommit.labels(*label_values).set(config["openstack_allocation_ratio_ram"]) 734 | label_values = [config["cloud"], "disk"] 735 | openstack_overcommit.labels(*label_values).set(config["openstack_allocation_ratio_disk"]) 736 | 737 | def gen_quota_stats(self): 738 | """Collect Nova compute quotas.""" 739 | cores = Gauge( 740 | "nova_quota_cores", 741 | "Nova cores metric", 742 | ["cloud", "tenant", "tenant_id", "type"], 743 | registry=self.registry, 744 | ) 745 | fips = Gauge( 746 | "nova_quota_floating_ips", 747 | "Nova floating IP addresses (number)", 748 | ["cloud", "tenant", "tenant_id", "type"], 749 | registry=self.registry, 750 | ) 751 | inst = Gauge( 752 | "nova_quota_instances", 753 | "Nova instances (number)", 754 | ["cloud", "tenant", "tenant_id", "type"], 755 | registry=self.registry, 756 | ) 757 | ram = Gauge( 758 | "nova_quota_ram_mbs", 759 | "Nova RAM (MB)", 760 | ["cloud", "tenant", "tenant_id", "type"], 761 | registry=self.registry, 762 | ) 763 | for t, q in list(self.prodstack["nova_quotas"].items()): 764 | if t in self.tenant_map: 765 | tenant = self.tenant_map[t] 766 | else: 767 | tenant = "orphaned" 768 | 769 | # we get detailed quota information only on recent OS versions 770 | if isinstance(q["cores"], int): 771 | cores.labels(config["cloud"], tenant, t, "limit").set(q["cores"]) 772 | fips.labels(config["cloud"], tenant, t, "limit").set(q["floating_ips"]) 773 | inst.labels(config["cloud"], tenant, t, "limit").set(q["instances"]) 774 | ram.labels(config["cloud"], tenant, t, "limit").set(q["ram"]) 775 | else: 776 | for tt in ["limit", "in_use", "reserved"]: 777 | cores.labels(config["cloud"], tenant, t, tt).inc(q["cores"][tt]) 778 | fips.labels(config["cloud"], tenant, t, tt).inc(q["floating_ips"][tt]) 779 | inst.labels(config["cloud"], tenant, t, tt).inc(q["instances"][tt]) 780 | ram.labels(config["cloud"], tenant, t, tt).inc(q["ram"][tt]) 781 | 782 | def get_stats(self): 783 | """Collect Nova metrics.""" 784 | log.debug("get_stats") 785 | self.gen_hypervisor_stats() 786 | self.gen_instance_stats() 787 | self.gen_overcommit_stats() 788 | self.gen_quota_stats() 789 | return generate_latest(self.registry) 790 | 791 | 792 | class Swift: 793 | """Class to manage Swift resources metrics collection.""" 794 | 795 | def __init__(self): 796 | """Initilize Swift collector.""" 797 | self.registry = CollectorRegistry() 798 | self.baseurl = "http://{}:6000/recon/{}" 799 | self.swift_hosts = config.get("swift_hosts", []) 800 | 801 | def gen_up_stats(self): 802 | """Collect Swift host up metric.""" 803 | labels = ["cloud", "hostname"] 804 | swift_up = Gauge( 805 | "swift_host_up", "Swift host reachability", labels, registry=self.registry 806 | ) 807 | for h in self.swift_hosts: 808 | try: 809 | requests.get(self.baseurl.format(h, "diskusage")) 810 | swift_up.labels(config["cloud"], h).set(1) 811 | except requests.exceptions.RequestException: 812 | swift_up.labels(config["cloud"], h).set(0) 813 | 814 | def gen_disk_usage_stats(self): 815 | """Collect Swift hosts disk usage metric.""" 816 | labels = ["cloud", "hostname", "device", "type"] 817 | swift_disk = Gauge( 818 | "swift_disk_usage_bytes", 819 | "Swift disk usage in bytes", 820 | labels, 821 | registry=self.registry, 822 | ) 823 | for h in self.swift_hosts: 824 | try: 825 | r = requests.get(self.baseurl.format(h, "diskusage")) 826 | except requests.exceptions.RequestException: 827 | continue 828 | for disk in r.json(): 829 | if not all([disk.get(i, False) for i in ["size", "used", "device"]]): 830 | continue 831 | swift_disk.labels(config["cloud"], h, disk["device"], "size").set( 832 | int(disk["size"]) 833 | ) 834 | swift_disk.labels(config["cloud"], h, disk["device"], "used").set( 835 | int(disk["used"]) 836 | ) 837 | 838 | def gen_quarantine_stats(self): 839 | """Collect Swift object in quarantine metric.""" 840 | labels = ["cloud", "hostname", "ring"] 841 | swift_quarantine = Gauge( 842 | "swift_quarantined_objects", 843 | "Number of quarantined objects", 844 | labels, 845 | registry=self.registry, 846 | ) 847 | for h in self.swift_hosts: 848 | try: 849 | r = requests.get(self.baseurl.format(h, "quarantined")) 850 | except requests.exceptions.RequestException: 851 | continue 852 | for ring in ["accounts", "objects", "containers"]: 853 | swift_quarantine.labels(config["cloud"], h, ring).set(r.json().get(ring)) 854 | 855 | def _get_object_ring_replication_stats(self, h, swift_repl_duration): 856 | # Object replication is special 857 | try: 858 | r = requests.get(self.baseurl.format(h, "replication/object")) 859 | except requests.exceptions.RequestException: 860 | return 861 | try: 862 | swift_repl_duration.labels(config["cloud"], h, "object").set( 863 | r.json()["object_replication_time"] 864 | ) 865 | except TypeError: 866 | print(traceback.format_exc()) 867 | 868 | def _get_ring_replication_stats(self, ring, h, swift_repl_duration, swift_repl): 869 | metrics = [ 870 | "attempted", 871 | "diff", 872 | "diff_capped", 873 | "empty", 874 | "failure", 875 | "hashmatch", 876 | "no_change", 877 | "remote_merge", 878 | "remove", 879 | "rsync", 880 | "success", 881 | "ts_repl", 882 | ] 883 | try: 884 | r = requests.get(self.baseurl.format(h, "replication/" + ring)) 885 | except requests.exceptions.RequestException: 886 | return 887 | try: 888 | swift_repl_duration.labels(config["cloud"], h, ring).set(r.json()["replication_time"]) 889 | except TypeError: 890 | print(traceback.format_exc()) 891 | 892 | for metric in metrics: 893 | try: 894 | swift_repl.labels(config["cloud"], h, ring, metric).set( 895 | r.json()["replication_stats"][metric] 896 | ) 897 | except TypeError: 898 | print(traceback.format_exc()) 899 | 900 | def gen_replication_stats(self): 901 | """Collect Swift replication statistics.""" 902 | labels = ["cloud", "hostname", "ring", "type"] 903 | swift_repl = Gauge( 904 | "swift_replication_stats", 905 | "Swift replication stats", 906 | labels, 907 | registry=self.registry, 908 | ) 909 | labels = ["cloud", "hostname", "ring"] 910 | swift_repl_duration = Gauge( 911 | "swift_replication_duration_seconds", 912 | "Swift replication duration in seconds", 913 | labels, 914 | registry=self.registry, 915 | ) 916 | for h in self.swift_hosts: 917 | self._get_object_ring_replication_stats(h, swift_repl_duration) 918 | for ring in ["account", "container"]: 919 | self._get_ring_replication_stats(ring, h, swift_repl_duration, swift_repl) 920 | 921 | def get_stats(self): 922 | """Collect all Swift statistics.""" 923 | self.gen_up_stats() 924 | self.gen_disk_usage_stats() 925 | self.gen_quarantine_stats() 926 | self.gen_replication_stats() 927 | return generate_latest(self.registry) 928 | 929 | 930 | class SwiftAccountUsage: 931 | """Class to manage Swift Account metrics collection.""" 932 | 933 | def __init__(self): 934 | """Initialize Swift Account collector.""" 935 | self.registry = CollectorRegistry() 936 | 937 | self.hash_path_prefix = config.get("hash_path_prefix", None) 938 | if self.hash_path_prefix: 939 | swift.common.utils.HASH_PATH_PREFIX = self.hash_path_prefix 940 | self.hash_path_suffix = config.get("hash_path_suffix", None) 941 | if self.hash_path_suffix: 942 | swift.common.utils.HASH_PATH_SUFFIX = self.hash_path_suffix 943 | 944 | self.reseller_prefix = config.get("reseller_prefix", "AUTH_") 945 | self.ring_path = config.get("ring_path", "/etc/swift") 946 | 947 | try: 948 | self.account_ring = self._get_account_ring() 949 | except SystemExit: 950 | # Most likely raised by swift.common.utils.validate_configuration(). 951 | raise Exception( 952 | "Is swift.conf readable or at least one hash path variable configured?" 953 | ) 954 | 955 | def _read_keystone_tenants_map(self, map_path): 956 | if not map_path: 957 | return {} 958 | 959 | m = {} 960 | with open(map_path) as km: 961 | line = km.readline() 962 | while line != "": 963 | name, id = line.strip().split() 964 | m[name] = id 965 | line = km.readline() 966 | 967 | return m 968 | 969 | def _get_account_ring(self): 970 | """Read the account ring from the configured location, and return it.""" 971 | return Ring( 972 | serialized_path=self.ring_path, 973 | ring_name="account", 974 | ) 975 | 976 | def _get_account_usage(self, account): 977 | partition, nodes = self.account_ring.get_nodes(account=account) 978 | node = random.choice(nodes) 979 | account_url = "http://{ip}:{port}/{device}/{partition}/{account}".format( 980 | account=account, partition=partition, **node 981 | ) 982 | response = requests.head(account_url) 983 | if response.status_code == 204: 984 | return int(response.headers["X-Account-Bytes-Used"]) 985 | else: 986 | return 0 987 | 988 | def gen_account_stats(self): 989 | """Collect Swift account metrics.""" 990 | self.keystone_tenants_map = self._read_keystone_tenants_map( 991 | config.get("keystone_tenants_map", None) 992 | ) 993 | labels = ["cloud", "swift_account", "tenant", "tenant_id"] 994 | swift_account = Gauge( 995 | "swift_account_bytes_used", 996 | "Swift account usage in bytes", 997 | labels, 998 | registry=self.registry, 999 | ) 1000 | 1001 | for tenant_name, tenant_id in self.keystone_tenants_map.items(): 1002 | account = self.reseller_prefix + tenant_id 1003 | bytes_used = self._get_account_usage(account) 1004 | 1005 | swift_account.labels(config["cloud"], account, tenant_name, tenant_id).set(bytes_used) 1006 | 1007 | def get_stats(self): 1008 | """Get Swift account metrics.""" 1009 | self.gen_account_stats() 1010 | return generate_latest(self.registry) 1011 | 1012 | 1013 | # This could perhaps be cleverer, but surely not simpler. 1014 | COLLECTORS = { 1015 | "cinder": Cinder, 1016 | "neutron": Neutron, 1017 | "nova": Nova, 1018 | "swift": Swift, 1019 | "swift-account-usage": SwiftAccountUsage, 1020 | } 1021 | 1022 | DATA_GATHERER_USERS = [ 1023 | "cinder", 1024 | "neutron", 1025 | "nova", 1026 | ] 1027 | 1028 | 1029 | def get_collectors(collectors): 1030 | """Return OpenStack collectors names.""" 1031 | # For backwards compatibility and when enabled_collectors isn't defined, 1032 | # specify default set of collectors before commit 662b70f and f27cda8. 1033 | # https://github.com/CanonicalLtd/prometheus-openstack-exporter/issues/80 1034 | if not collectors: 1035 | return ["cinder", "swift", "nova", "neutron"] 1036 | return collectors 1037 | 1038 | 1039 | def data_gatherer_needed(config): 1040 | return set(get_collectors(config.get("enabled_collectors"))).intersection(DATA_GATHERER_USERS) 1041 | 1042 | 1043 | class OpenstackExporterHandler(BaseHTTPRequestHandler): 1044 | """Manage the webserver that exposes exporter metrics.""" 1045 | 1046 | def __init__(self, *args, **kwargs): 1047 | """Initilize the webserver.""" 1048 | BaseHTTPRequestHandler.__init__(self, *args, **kwargs) 1049 | 1050 | def do_GET(self): # noqa: N802 1051 | url = urllib.parse.urlparse(self.path) 1052 | if url.path == "/metrics": 1053 | try: 1054 | collectors = [ 1055 | COLLECTORS[collector]() 1056 | for collector in get_collectors(config.get("enabled_collectors")) 1057 | ] 1058 | log.debug("Collecting stats..") 1059 | output = bytes() 1060 | for collector in collectors: 1061 | output += collector.get_stats() 1062 | if data_gatherer: 1063 | output += data_gatherer.get_stats() 1064 | 1065 | self.send_response(200) 1066 | self.send_header("Content-Type", CONTENT_TYPE_LATEST) 1067 | self.end_headers() 1068 | self.wfile.write(output) 1069 | except Exception: 1070 | log.exception("") 1071 | self.send_response(500) 1072 | self.end_headers() 1073 | self.wfile.write(traceback.format_exc()) 1074 | elif url.path == "/": 1075 | self.send_response(200) 1076 | self.end_headers() 1077 | self.wfile.write( 1078 | b""" 1079 | OpenStack Exporter 1080 | 1081 |

OpenStack Exporter

1082 |

Visit /metrics to use.

1083 | 1084 | """ 1085 | ) 1086 | else: 1087 | self.send_response(404) 1088 | self.end_headers() 1089 | 1090 | def log_message(self, format, *args): 1091 | log.info( 1092 | "%s - - [%s] %s\n" 1093 | % (self.address_string(), self.log_date_time_string(), format % args) 1094 | ) 1095 | 1096 | 1097 | def handler(*args, **kwargs): 1098 | OpenstackExporterHandler(*args, **kwargs) 1099 | 1100 | 1101 | if __name__ == "__main__": 1102 | parser = argparse.ArgumentParser( 1103 | usage=__doc__, 1104 | description="Prometheus OpenStack exporter", 1105 | formatter_class=argparse.RawTextHelpFormatter, 1106 | ) 1107 | parser.add_argument( 1108 | "config_file", 1109 | nargs="?", 1110 | help="Configuration file path", 1111 | default="/etc/prometheus/prometheus-openstack-exporter.yaml", 1112 | type=argparse.FileType("r"), 1113 | ) 1114 | args = parser.parse_args() 1115 | log.setLevel(logging.DEBUG) 1116 | for logsock in ("/dev/log", "/var/run/syslog"): 1117 | if path.exists(logsock): 1118 | log.addHandler(logging.handlers.SysLogHandler(address=logsock)) 1119 | break 1120 | else: 1121 | log.addHandler(logging.StreamHandler()) 1122 | config = yaml.safe_load(args.config_file.read()) 1123 | numeric_log_level = getattr(logging, config.get("log_level", "INFO").upper(), None) 1124 | if not isinstance(numeric_log_level, int): 1125 | raise ValueError("Invalid log level: %s" % config.get("log_level")) 1126 | log.setLevel(numeric_log_level) 1127 | data_gatherer = None 1128 | if data_gatherer_needed(config): 1129 | data_gatherer = DataGatherer() 1130 | data_gatherer.start() 1131 | server = HTTPServer(("", config.get("listen_port")), handler) 1132 | server.serve_forever() 1133 | --------------------------------------------------------------------------------