├── .dockerignore ├── .gitignore ├── CONTRIBUTORS.md ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── RELEASE.md ├── config.yml ├── connectbox_exporter ├── __init__.py ├── config.py ├── connectbox_exporter.py ├── logger.py └── xml2metric.py ├── docker-compose.yml ├── docker-run.sh ├── requirements.txt ├── resources ├── docs │ └── grafana_dashboard_screenshot.png ├── requirements │ ├── development.txt │ └── production.txt └── schema │ └── 123.xsd ├── run.py └── setup.py /.dockerignore: -------------------------------------------------------------------------------- 1 | # ignore everything by default 2 | ** 3 | 4 | # add exeptions for files we actually need in the docker image 5 | !resources/requirements/production.txt 6 | !config.yml 7 | !connectbox_exporter/** 8 | !run.py 9 | !setup.py 10 | !docker-run.sh 11 | 12 | # we need README.md so setup.py does not fail 13 | !README.md 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit tests / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | .static_storage/ 56 | .media/ 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # pycharm 107 | .idea/ 108 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | - Michael Bugert (mbugert) - Owner 4 | - IndeedNotJames - Docker integration 5 | - Dobrosław Kijowski (dobo90) - Bug fix 6 | 7 | ## Thanks to 8 | - Ties de Kock (ties) - for the ` 9 | compal_CH7465LG_py` library -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3-alpine 2 | 3 | RUN apk add --no-cache --virtual .build-deps \ 4 | g++ \ 5 | python3-dev \ 6 | libxml2 \ 7 | libxml2-dev \ 8 | && apk add \ 9 | libxslt-dev \ 10 | su-exec 11 | 12 | WORKDIR /opt/connectbox-prometheus 13 | COPY resources/requirements/production.txt requirements.txt 14 | RUN pip3 --no-cache-dir install -r requirements.txt \ 15 | && apk del .build-deps 16 | 17 | COPY . . 18 | RUN python3 setup.py install 19 | 20 | VOLUME /data 21 | EXPOSE 9705 22 | 23 | CMD ["/opt/connectbox-prometheus/docker-run.sh"] 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include config.yml 2 | graft resources/schema -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Connectbox Prometheus 2 | [![PyPI - License](https://img.shields.io/pypi/l/connectbox-prometheus.svg)](https://pypi.org/project/connectbox-prometheus/) 3 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/connectbox-prometheus.svg)](https://pypi.org/project/connectbox-prometheus/) 4 | [![PyPI](https://img.shields.io/pypi/v/connectbox-prometheus.svg)](https://pypi.org/project/connectbox-prometheus/) 5 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 6 | 7 | A [Prometheus](https://prometheus.io/) exporter for monitoring Compal CH7465LG cable modems. These are sold under the name "Connect Box" by Unitymedia in Germany, Ziggo in the Netherlands and UPC in Switzerland/Austria/Poland. Or as "Virgin Media Super Hub 3" by Virgin Media. 8 | 9 | Makes thorough use of [compal_CH7465LG_py](https://github.com/ties/compal_CH7465LG_py) by [@ties](https://github.com/ties/) (thanks!). 10 | 11 | ## Installation 12 | On your Prometheus server host: 13 | 14 | ### Using pip 15 | 1. [Create a virtual environment](https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments) using python3.7 or higher 16 | 2. Install the exporter via `pip install connectbox-prometheus` 17 | 18 | ### Using Docker 19 | Alternatively you could use the provided `Dockerfile`. 20 | We don't provide builds on [Docker Hub](https://hub.docker.com/) or similar, so you need to `git clone` and build it yourself: 21 | 22 | `git clone https://github.com/mbugert/connectbox-prometheus.git` 23 | 24 | `cd connectbox-prometheus` 25 | 26 | Choose **either** `docker run` **or** `docker-compose`. 27 | 28 | #### docker run 29 | 30 | To build your own local docker image run 31 | `docker build -t connectbox-prometheus .` 32 | 33 | To actually create and run a container named `connectbox-prometheus` use the following command: 34 | 35 | `docker run -v connectbox-prometheus-volume:/data -p 9705:9705 --name connectbox-prometheus connectbox-prometheus` 36 | 37 | The example `config.yml` found in the root of this repo will be copied to the provided `/data` volume (e.g. `connectbox-prometheus-volume`, usually found under `/var/lib/docker/volumes/connectbox-prometheus-volume` and the container will stop, because you most likely need to modify the given config. See [Usage](#usage). 38 | 39 | After modifying, run `docker start connectbox-prometheus` to keep the container running. 40 | 41 | #### docker-compose 42 | 43 | `docker-compose up` will automatically build the docker image, start the container the first time to copy the example `config.yml` and exit again. 44 | Now there should be an directory named `data` where you can find your `config.yml`. Modify it to your needs. See [Usage](#usage). 45 | 46 | After modifying, run `docker-compose up -d` to keep the container running. 47 | 48 | ## Usage 49 | This exporter queries exactly one Connect Box as a remote target. 50 | To get started, modify `config.yml` from this repository or start out with the following content: 51 | ```yaml 52 | # Connect Box IP address 53 | ip_address: 192.168.0.1 54 | 55 | # Connect Box web interface password 56 | password: WhatEverYourPasswordIs 57 | ``` 58 | 59 | Then run `connectbox_exporter path/to/your/config.yml` . 60 | 61 | ## Prometheus Configuration 62 | Add the following to your `prometheus.yml`: 63 | ```yaml 64 | scrape_configs: 65 | - job_name: 'connectbox' 66 | static_configs: 67 | - targets: 68 | - localhost:9705 69 | ``` 70 | One scrape takes roughly 6 seconds. 71 | 72 | ## Exported Metrics 73 | | Metric name | Description | 74 | |:------------------------------------------------------|:----------------------------------------------------------| 75 | | `connectbox_device_info` | Assorted device information | 76 | | `connectbox_provisioning_status` | Modem provisioning status | 77 | | `connectbox_uptime_seconds` | Device uptime in seconds | 78 | | `connectbox_tuner_temperature_celsius` | Tuner temperature | 79 | | `connectbox_temperature_celsius` | Temperature | 80 | | `connectbox_ethernet_client_speed_mbit` | Maximum speed of connected ethernet clients | 81 | | `connectbox_wifi_client_speed_mbit` | Maximum speed of connected Wi-Fi clients | 82 | | `connectbox_downstream_frequency_hz` | Downstream channel frequency | 83 | | `connectbox_downstream_power_level_dbmv` | Downstream channel power level | 84 | | `connectbox_downstream_snr_db` | Downstream channel signal-to-noise ratio (SNR) | 85 | | `connectbox_downstream_rxmer_db` | Downstream channel receive modulation error ratio (RxMER) | 86 | | `connectbox_downstream_codewords_unerrored_total` | Unerrored downstream codewords | 87 | | `connectbox_downstream_codewords_corrected_total` | Corrected downstream codewords | 88 | | `connectbox_downstream_codewords_uncorrectable_total` | Uncorrectable downstream codewords | 89 | | `connectbox_upstream_frequency_hz` | Upstream channel frequency | 90 | | `connectbox_upstream_power_level_dbmv` | Upstream channel power level | 91 | | `connectbox_upstream_symbol_rate_ksps` | Upstream channel symbol rate | 92 | | `connectbox_upstream_timeouts_total` | Upstream channel timeout occurrences | 93 | | `connectbox_scrape_duration_seconds` | Connect Box exporter scrape duration | 94 | | `connectbox_up` | Connect Box exporter scrape success | 95 | 96 | ## Grafana Dashboard 97 | 98 | The above metrics can be monitored nicely in [Grafana](https://github.com/grafana/grafana) using [this dashboard](https://grafana.com/grafana/dashboards/12078/): 99 | 100 | ![Grafana Dashboard](resources/docs/grafana_dashboard_screenshot.png) 101 | 102 | ## Contributing / Development 103 | Pull requests are welcome. 😊 104 | 105 | To install development dependencies, run: 106 | 107 | `pip install -r resources/requirements/development.txt` -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | # Release Checklist 2 | - [ ] Testing 3 | - [ ] Update version and info in `setup.py` 4 | - [ ] Build 5 | ``` 6 | python -m build 7 | ``` 8 | - [ ] Test pypi release 9 | ``` 10 | python -m twine upload --repository testpypi dist/* 11 | ``` 12 | - [ ] Try installing that 13 | ``` 14 | python3 -m venv tmpvenv 15 | source tmpvenv/bin/activate 16 | pip install -i https://test.pypi.org/simple/ --no-deps PACKAGE_NAME 17 | deactivate 18 | rm -rf tmpvenv 19 | ``` 20 | - [ ] Commit, merge into `master` with PR 21 | - [ ] Proper pypi release 22 | ``` 23 | python -m twine upload dist/* 24 | ``` 25 | - [ ] Release on github with appropriate tag 26 | 27 | ## Wishlist 28 | Automate this with https://github.com/pypa/gh-action-pypi-publish -------------------------------------------------------------------------------- /config.yml: -------------------------------------------------------------------------------- 1 | # Connect Box IP address 2 | ip_address: 192.168.0.1 3 | 4 | # Connect Box web interface password 5 | password: WhatEverYourPasswordIs 6 | 7 | # All following parameters are optional. 8 | #exporter: 9 | # port on which this exporter exposes metrics (default: 9705) 10 | #port: 9705 11 | 12 | # timeout duration for connections to the Connect Box (default: 9) 13 | #timeout_seconds: 9 14 | 15 | # Customize the family of metrics to scrape. By default, all metrics are scraped. 16 | #metrics: [device_status, downstream, upstream, lan_users, temperature] -------------------------------------------------------------------------------- /connectbox_exporter/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbugert/connectbox-prometheus/360668b1cf97490658d16b3030eeccdf212f8e78/connectbox_exporter/__init__.py -------------------------------------------------------------------------------- /connectbox_exporter/config.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import Union, Dict 3 | 4 | from deepmerge import Merger 5 | from ruamel.yaml import YAML 6 | 7 | from connectbox_exporter.xml2metric import ( 8 | DEVICE_STATUS, 9 | DOWNSTREAM, 10 | UPSTREAM, 11 | LAN_USERS, 12 | TEMPERATURE, 13 | ) 14 | 15 | IP_ADDRESS = "ip_address" 16 | PASSWORD = "password" 17 | EXPORTER = "exporter" 18 | PORT = "port" 19 | TIMEOUT_SECONDS = "timeout_seconds" 20 | EXTRACTORS = "metrics" 21 | 22 | # pick default timeout one second less than the default prometheus timeout of 10s 23 | DEFAULT_CONFIG = { 24 | EXPORTER: { 25 | PORT: 9705, 26 | TIMEOUT_SECONDS: 9, 27 | EXTRACTORS: {DEVICE_STATUS, DOWNSTREAM, UPSTREAM, LAN_USERS, TEMPERATURE}, 28 | } 29 | } 30 | 31 | 32 | def load_config(config_file: Union[str, Path]) -> Dict: 33 | """ 34 | Loads and validates YAML config for this exporter and fills in default values 35 | :param config_file: 36 | :return: config as dictionary 37 | """ 38 | yaml = YAML() 39 | with open(config_file) as f: 40 | config = yaml.load(f) 41 | 42 | # merge with default config: use 'override' for lists to let users replace extractor setting entirely 43 | merger = Merger([(list, "override"), (dict, "merge")], ["override"], ["override"]) 44 | config = merger.merge(DEFAULT_CONFIG, config) 45 | 46 | for param in [IP_ADDRESS, PASSWORD]: 47 | if not param in config: 48 | raise ValueError( 49 | f"'{param}' is a mandatory config parameter, but it is missing in the YAML configuration file. Please see README.md for an example." 50 | ) 51 | if config[EXPORTER][TIMEOUT_SECONDS] <= 0: 52 | raise ValueError(f"'{TIMEOUT_SECONDS} must be positive.") 53 | if config[EXPORTER][PORT] < 0 or config[EXPORTER][PORT] > 65535: 54 | raise ValueError(f"Invalid exporter port.") 55 | 56 | if not config[EXPORTER][EXTRACTORS]: 57 | raise ValueError( 58 | "The config file needs to specify at least one family of metrics." 59 | ) 60 | config[EXPORTER][EXTRACTORS] = sorted(set(config[EXPORTER][EXTRACTORS])) 61 | 62 | return config 63 | -------------------------------------------------------------------------------- /connectbox_exporter/connectbox_exporter.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import threading 4 | import time 5 | from http.server import HTTPServer 6 | from socketserver import ThreadingMixIn 7 | from typing import Dict 8 | 9 | import click 10 | import compal 11 | from lxml.etree import XMLSyntaxError 12 | from prometheus_client import CollectorRegistry, MetricsHandler 13 | from prometheus_client.metrics_core import GaugeMetricFamily 14 | from requests import Timeout 15 | 16 | from connectbox_exporter.config import ( 17 | load_config, 18 | IP_ADDRESS, 19 | PASSWORD, 20 | EXPORTER, 21 | PORT, 22 | TIMEOUT_SECONDS, 23 | EXTRACTORS, 24 | ) 25 | from connectbox_exporter.logger import get_logger, VerboseLogger 26 | from connectbox_exporter.xml2metric import get_metrics_extractor 27 | 28 | 29 | # Taken 1:1 from prometheus-client==0.7.1, see https://github.com/prometheus/client_python/blob/3cb4c9247f3f08dfbe650b6bdf1f53aa5f6683c1/prometheus_client/exposition.py 30 | class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer): 31 | """Thread per request HTTP server.""" 32 | 33 | # Make worker threads "fire and forget". Beginning with Python 3.7 this 34 | # prevents a memory leak because ``ThreadingMixIn`` starts to gather all 35 | # non-daemon threads in a list in order to join on them at server close. 36 | # Enabling daemon threads virtually makes ``_ThreadingSimpleServer`` the 37 | # same as Python 3.7's ``ThreadingHTTPServer``. 38 | daemon_threads = True 39 | 40 | 41 | class ConnectBoxCollector(object): 42 | def __init__( 43 | self, 44 | logger: VerboseLogger, 45 | ip_address: str, 46 | password: str, 47 | exporter_config: Dict, 48 | ): 49 | self.logger = logger 50 | self.ip_address = ip_address 51 | self.password = password 52 | self.timeout = exporter_config[TIMEOUT_SECONDS] 53 | 54 | extractors = exporter_config[EXTRACTORS] 55 | self.metric_extractors = [get_metrics_extractor(e, logger) for e in extractors] 56 | 57 | def collect(self): 58 | # Collect scrape duration and scrape success for each extractor. Scrape success is initialized with False for 59 | # all extractors so that we can report a value for each extractor even in cases where we abort midway through 60 | # because we lost connection to the modem. 61 | scrape_duration = {} # type: Dict[str, float] 62 | scrape_success = {e.name: False for e in self.metric_extractors} 63 | 64 | # attempt login 65 | login_logout_success = True 66 | try: 67 | self.logger.debug("Logging in at " + self.ip_address) 68 | connectbox = compal.Compal( 69 | self.ip_address, key=self.password, timeout=self.timeout 70 | ) 71 | connectbox.login() 72 | except (ConnectionError, Timeout, ValueError) as e: 73 | self.logger.error(repr(e)) 74 | connectbox = None 75 | login_logout_success = False 76 | 77 | # skip extracting further metrics if login failed 78 | if connectbox is not None: 79 | for extractor in self.metric_extractors: 80 | raw_xmls = {} 81 | try: 82 | pre_scrape_time = time.time() 83 | 84 | # obtain all raw XML responses for an extractor, then extract metrics 85 | for fun in extractor.functions: 86 | self.logger.debug(f"Querying fun={fun}...") 87 | raw_xml = connectbox.xml_getter(fun, {}).content 88 | self.logger.verbose( 89 | f"Raw XML response for fun={fun}:\n{raw_xml.decode()}" 90 | ) 91 | raw_xmls[fun] = raw_xml 92 | yield from extractor.extract(raw_xmls) 93 | post_scrape_time = time.time() 94 | 95 | scrape_duration[extractor.name] = post_scrape_time - pre_scrape_time 96 | scrape_success[extractor.name] = True 97 | except (XMLSyntaxError, AttributeError) as e: 98 | # in case of a less serious error, log and continue scraping the next extractor 99 | jsonized = json.dumps(raw_xmls) 100 | message = f"Failed to extract '{extractor.name}'. Please open an issue on Github and include the following:\n{repr(e)}\n{jsonized}" 101 | self.logger.error(message) 102 | except (ConnectionError, Timeout) as e: 103 | # in case of serious connection issues, abort and do not try the next extractor 104 | self.logger.error(repr(e)) 105 | break 106 | 107 | # attempt logout once done 108 | try: 109 | self.logger.debug("Logging out.") 110 | connectbox.logout() 111 | except Exception as e: 112 | self.logger.error(e) 113 | login_logout_success = False 114 | scrape_success["login_logout"] = int(login_logout_success) 115 | 116 | # create metrics from previously durations and successes collected 117 | EXTRACTOR = "extractor" 118 | scrape_duration_metric = GaugeMetricFamily( 119 | "connectbox_scrape_duration", 120 | documentation="Scrape duration by extractor", 121 | unit="seconds", 122 | labels=[EXTRACTOR], 123 | ) 124 | for name, duration in scrape_duration.items(): 125 | scrape_duration_metric.add_metric([name], duration) 126 | yield scrape_duration_metric 127 | 128 | scrape_success_metric = GaugeMetricFamily( 129 | "connectbox_up", 130 | documentation="Connect Box exporter scrape success by extractor", 131 | labels=[EXTRACTOR], 132 | ) 133 | for name, success in scrape_success.items(): 134 | scrape_success_metric.add_metric([name], int(success)) 135 | yield scrape_success_metric 136 | 137 | 138 | @click.command() 139 | @click.argument("config_file", type=click.Path(exists=True, dir_okay=False)) 140 | @click.option( 141 | "-v", 142 | "--verbose", 143 | help="Log more messages. Multiple -v increase verbosity.", 144 | count=True, 145 | ) 146 | def main(config_file, verbose): 147 | """ 148 | Launch the exporter using a YAML config file. 149 | """ 150 | 151 | # hush the logger from the compal library and use our own custom logger 152 | compal.LOGGER.setLevel(logging.WARNING) 153 | logger = get_logger(verbose) 154 | 155 | # load user and merge with defaults 156 | config = load_config(config_file) 157 | exporter_config = config[EXPORTER] 158 | 159 | # fire up collector 160 | reg = CollectorRegistry() 161 | reg.register( 162 | ConnectBoxCollector( 163 | logger, 164 | ip_address=config[IP_ADDRESS], 165 | password=config[PASSWORD], 166 | exporter_config=config[EXPORTER], 167 | ) 168 | ) 169 | 170 | # start http server 171 | CustomMetricsHandler = MetricsHandler.factory(reg) 172 | httpd = _ThreadingSimpleServer(("", exporter_config[PORT]), CustomMetricsHandler) 173 | httpd_thread = threading.Thread(target=httpd.serve_forever) 174 | httpd_thread.start() 175 | 176 | logger.info( 177 | f"Exporter running at http://localhost:{exporter_config[PORT]}, querying {config[IP_ADDRESS]}" 178 | ) 179 | 180 | # wait indefinitely 181 | try: 182 | while True: 183 | time.sleep(3) 184 | except KeyboardInterrupt: 185 | httpd.shutdown() 186 | httpd_thread.join() 187 | -------------------------------------------------------------------------------- /connectbox_exporter/logger.py: -------------------------------------------------------------------------------- 1 | from logging import Logger, NOTSET, addLevelName, INFO, DEBUG, StreamHandler, Formatter 2 | import sys 3 | 4 | VERBOSE = 5 5 | 6 | 7 | class VerboseLogger(Logger): 8 | """ 9 | Logger with custom log level VERBOSE which is lower than DEBUG. 10 | """ 11 | 12 | def __init__(self, name, level=NOTSET): 13 | super().__init__(name, level) 14 | addLevelName(VERBOSE, "VERBOSE") 15 | 16 | def verbose(self, msg, *args, **kwargs): 17 | if self.isEnabledFor(VERBOSE): 18 | self._log(VERBOSE, msg, args, **kwargs) 19 | 20 | 21 | def get_logger(verbosity: int) -> VerboseLogger: 22 | """ 23 | Get logger object which logs to stdout with given verbosity. 24 | :param verbosity: logs INFO if 0, DEBUG if 1 and VERBOSE if >1 25 | :return: 26 | """ 27 | if verbosity <= 0: 28 | log_level = INFO 29 | elif verbosity == 1: 30 | log_level = DEBUG 31 | else: 32 | log_level = VERBOSE 33 | 34 | logger = VerboseLogger("connectbox_exporter") 35 | logger.setLevel(log_level) 36 | handler = StreamHandler(sys.stdout) 37 | handler.setLevel(log_level) 38 | formatter = Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 39 | handler.setFormatter(formatter) 40 | logger.addHandler(handler) 41 | 42 | return logger 43 | -------------------------------------------------------------------------------- /connectbox_exporter/xml2metric.py: -------------------------------------------------------------------------------- 1 | import re 2 | from datetime import timedelta 3 | from enum import Enum 4 | from logging import Logger 5 | from pathlib import Path 6 | from typing import Iterable, Set, Dict 7 | 8 | from compal.functions import GetFunction as GET 9 | from lxml import etree 10 | from prometheus_client import Metric 11 | from prometheus_client.metrics_core import ( 12 | InfoMetricFamily, 13 | CounterMetricFamily, 14 | GaugeMetricFamily, 15 | StateSetMetricFamily, 16 | ) 17 | 18 | DEVICE_STATUS = "device_status" 19 | DOWNSTREAM = "downstream" 20 | UPSTREAM = "upstream" 21 | LAN_USERS = "lan_users" 22 | TEMPERATURE = "temperature" 23 | 24 | 25 | class XmlMetricsExtractor: 26 | 27 | PROJECT_ROOT = Path(__file__).parent.parent 28 | SCHEMA_ROOT = PROJECT_ROOT / "resources" / "schema" 29 | 30 | def __init__(self, name: str, functions: Set[int], logger: Logger): 31 | self._name = name 32 | self._logger = logger 33 | 34 | # create one parser per function, use an XML schema if available 35 | self._parsers = {} 36 | for fun in functions: 37 | path = XmlMetricsExtractor.SCHEMA_ROOT / f"{fun}.xsd" 38 | if path.exists(): 39 | schema = etree.XMLSchema(file=str(path)) 40 | else: 41 | schema = None 42 | parser = etree.XMLParser(schema=schema) 43 | self._parsers[fun] = parser 44 | 45 | @property 46 | def name(self): 47 | """ 48 | Descriptive name for this extractor, to be used in metric labels 49 | :return: 50 | """ 51 | return self._name 52 | 53 | @property 54 | def functions(self) -> Iterable[int]: 55 | """ 56 | Connect Box getter.xml function(s) this metrics extractor is working on 57 | :return: 58 | """ 59 | return self._parsers.keys() 60 | 61 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 62 | """ 63 | Returns metrics given raw XML responses corresponding to the functions returned in the `functions` property. 64 | :param raw_xmls: 65 | :return: metrics iterable 66 | :raises: lxml.etree.XMLSyntaxError in case a raw XML does not match the expected schema 67 | """ 68 | raise NotImplementedError 69 | 70 | 71 | class DownstreamStatusExtractor(XmlMetricsExtractor): 72 | def __init__(self, logger: Logger): 73 | super(DownstreamStatusExtractor, self).__init__( 74 | DOWNSTREAM, {GET.DOWNSTREAM_TABLE, GET.SIGNAL_TABLE}, logger 75 | ) 76 | 77 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 78 | assert len(raw_xmls) == 2 79 | 80 | # DOWNSTREAM_TABLE gives us frequency, power level, SNR and RxMER per channel 81 | root = etree.fromstring( 82 | raw_xmls[GET.DOWNSTREAM_TABLE], parser=self._parsers[GET.DOWNSTREAM_TABLE] 83 | ) 84 | 85 | CHANNEL_ID = "channel_id" 86 | ds_frequency = GaugeMetricFamily( 87 | "connectbox_downstream_frequency", 88 | "Downstream channel frequency", 89 | unit="hz", 90 | labels=[CHANNEL_ID], 91 | ) 92 | ds_power_level = GaugeMetricFamily( 93 | "connectbox_downstream_power_level", 94 | "Downstream channel power level", 95 | unit="dbmv", 96 | labels=[CHANNEL_ID], 97 | ) 98 | ds_snr = GaugeMetricFamily( 99 | "connectbox_downstream_snr", 100 | "Downstream channel signal-to-noise ratio (SNR)", 101 | unit="db", 102 | labels=[CHANNEL_ID], 103 | ) 104 | ds_rxmer = GaugeMetricFamily( 105 | "connectbox_downstream_rxmer", 106 | "Downstream channel receive modulation error ratio (RxMER)", 107 | unit="db", 108 | labels=[CHANNEL_ID], 109 | ) 110 | for channel in root.findall("downstream"): 111 | channel_id = channel.find("chid").text 112 | frequency = int(channel.find("freq").text) 113 | power_level = int(channel.find("pow").text) 114 | snr = int(channel.find("snr").text) 115 | rxmer = float(channel.find("RxMER").text) 116 | 117 | labels = [channel_id.zfill(2)] 118 | ds_frequency.add_metric(labels, frequency) 119 | ds_power_level.add_metric(labels, power_level) 120 | ds_snr.add_metric(labels, snr) 121 | ds_rxmer.add_metric(labels, rxmer) 122 | yield from [ds_frequency, ds_power_level, ds_snr, ds_rxmer] 123 | 124 | # SIGNAL_TABLE gives us unerrored, corrected and uncorrectable errors per channel 125 | root = etree.fromstring( 126 | raw_xmls[GET.SIGNAL_TABLE], parser=self._parsers[GET.SIGNAL_TABLE] 127 | ) 128 | 129 | ds_unerrored_codewords = CounterMetricFamily( 130 | "connectbox_downstream_codewords_unerrored", 131 | "Unerrored downstream codewords", 132 | labels=[CHANNEL_ID], 133 | ) 134 | ds_correctable_codewords = CounterMetricFamily( 135 | "connectbox_downstream_codewords_corrected", 136 | "Corrected downstream codewords", 137 | labels=[CHANNEL_ID], 138 | ) 139 | ds_uncorrectable_codewords = CounterMetricFamily( 140 | "connectbox_downstream_codewords_uncorrectable", 141 | "Uncorrectable downstream codewords", 142 | labels=[CHANNEL_ID], 143 | ) 144 | for channel in root.findall("signal"): 145 | channel_id = channel.find("dsid").text 146 | unerrored = int(channel.find("unerrored").text) 147 | correctable = int(channel.find("correctable").text) 148 | uncorrectable = int(channel.find("uncorrectable").text) 149 | 150 | labels = [channel_id.zfill(2)] 151 | ds_unerrored_codewords.add_metric(labels, unerrored) 152 | ds_correctable_codewords.add_metric(labels, correctable) 153 | ds_uncorrectable_codewords.add_metric(labels, uncorrectable) 154 | yield from [ 155 | ds_unerrored_codewords, 156 | ds_correctable_codewords, 157 | ds_uncorrectable_codewords, 158 | ] 159 | 160 | 161 | class UpstreamStatusExtractor(XmlMetricsExtractor): 162 | def __init__(self, logger: Logger): 163 | super(UpstreamStatusExtractor, self).__init__(UPSTREAM, {GET.UPSTREAM_TABLE}, logger) 164 | 165 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 166 | assert len(raw_xmls) == 1 167 | 168 | CHANNEL_ID = "channel_id" 169 | TIMEOUT_TYPE = "timeout_type" 170 | 171 | us_frequency = GaugeMetricFamily( 172 | "connectbox_upstream_frequency", 173 | "Upstream channel frequency", 174 | unit="hz", 175 | labels=[CHANNEL_ID], 176 | ) 177 | us_power_level = GaugeMetricFamily( 178 | "connectbox_upstream_power_level", 179 | "Upstream channel power level", 180 | unit="dbmv", 181 | labels=[CHANNEL_ID], 182 | ) 183 | us_symbol_rate = GaugeMetricFamily( 184 | "connectbox_upstream_symbol_rate", 185 | "Upstream channel symbol rate", 186 | unit="ksps", 187 | labels=[CHANNEL_ID], 188 | ) 189 | us_timeouts = CounterMetricFamily( 190 | "connectbox_upstream_timeouts", 191 | "Upstream channel timeout occurrences", 192 | labels=[CHANNEL_ID, TIMEOUT_TYPE], 193 | ) 194 | root = etree.fromstring( 195 | raw_xmls[GET.UPSTREAM_TABLE], parser=self._parsers[GET.UPSTREAM_TABLE] 196 | ) 197 | for channel in root.findall("upstream"): 198 | channel_id = channel.find("usid").text 199 | 200 | frequency = int(channel.find("freq").text) 201 | power_level = float(channel.find("power").text) 202 | symbol_rate = float(channel.find("srate").text) 203 | t1_timeouts = int(channel.find("t1Timeouts").text) 204 | t2_timeouts = int(channel.find("t2Timeouts").text) 205 | t3_timeouts = int(channel.find("t3Timeouts").text) 206 | t4_timeouts = int(channel.find("t4Timeouts").text) 207 | 208 | labels = [channel_id.zfill(2)] 209 | us_frequency.add_metric(labels, frequency) 210 | us_power_level.add_metric(labels, power_level) 211 | us_symbol_rate.add_metric(labels, symbol_rate) 212 | us_timeouts.add_metric(labels + ["T1"], t1_timeouts) 213 | us_timeouts.add_metric(labels + ["T2"], t2_timeouts) 214 | us_timeouts.add_metric(labels + ["T3"], t3_timeouts) 215 | us_timeouts.add_metric(labels + ["T4"], t4_timeouts) 216 | yield from [us_frequency, us_power_level, us_symbol_rate, us_timeouts] 217 | 218 | 219 | class LanUserExtractor(XmlMetricsExtractor): 220 | def __init__(self, logger: Logger): 221 | super(LanUserExtractor, self).__init__(LAN_USERS, {GET.LANUSERTABLE}, logger) 222 | 223 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 224 | assert len(raw_xmls) == 1 225 | 226 | root = etree.fromstring( 227 | raw_xmls[GET.LANUSERTABLE], parser=self._parsers[GET.LANUSERTABLE] 228 | ) 229 | 230 | # LAN and Wi-Fi clients have the same XML format so we can reuse the code to extract their values 231 | def extract_client(client, target_metric: GaugeMetricFamily): 232 | mac_address = client.find("MACAddr").text 233 | 234 | # depending on the firmware, both IPv4/IPv6 addresses or only one of both are reported 235 | ipv4_address_elmt = client.find("IPv4Addr") 236 | ipv4_address = ( 237 | ipv4_address_elmt.text if ipv4_address_elmt is not None else "" 238 | ) 239 | ipv6_address_elmt = client.find("IPv6Addr") 240 | ipv6_address = ( 241 | ipv6_address_elmt.text if ipv6_address_elmt is not None else "" 242 | ) 243 | 244 | hostname = client.find("hostname").text 245 | speed = int(client.find("speed").text) 246 | target_metric.add_metric( 247 | [mac_address, ipv4_address, ipv6_address, hostname], speed 248 | ) 249 | 250 | label_names = ["mac_address", "ipv4_address", "ipv6_address", "hostname"] 251 | 252 | # set up ethernet user speed metric 253 | ethernet_user_speed = GaugeMetricFamily( 254 | "connectbox_ethernet_client_speed", 255 | "Ethernet client network speed", 256 | labels=label_names, 257 | unit="mbit", 258 | ) 259 | for client in root.find("Ethernet").findall("clientinfo"): 260 | extract_client(client, ethernet_user_speed) 261 | yield ethernet_user_speed 262 | 263 | # set up Wi-Fi user speed metric 264 | wifi_user_speed = GaugeMetricFamily( 265 | "connectbox_wifi_client_speed", 266 | "Wi-Fi client network speed", 267 | labels=label_names, 268 | unit="mbit", 269 | ) 270 | for client in root.find("WIFI").findall("clientinfo"): 271 | extract_client(client, wifi_user_speed) 272 | yield wifi_user_speed 273 | 274 | 275 | class TemperatureExtractor(XmlMetricsExtractor): 276 | def __init__(self, logger: Logger): 277 | super(TemperatureExtractor, self).__init__(TEMPERATURE, {GET.CMSTATE}, logger) 278 | 279 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 280 | assert len(raw_xmls) == 1 281 | 282 | root = etree.fromstring( 283 | raw_xmls[GET.CMSTATE], parser=self._parsers[GET.CMSTATE] 284 | ) 285 | 286 | fahrenheit_to_celsius = lambda f: (f - 32) * 5.0 / 9 287 | tuner_temperature = fahrenheit_to_celsius( 288 | float(root.find("TunnerTemperature").text) 289 | ) 290 | temperature = fahrenheit_to_celsius(float(root.find("Temperature").text)) 291 | 292 | yield GaugeMetricFamily( 293 | "connectbox_tuner_temperature", 294 | "Tuner temperature", 295 | unit="celsius", 296 | value=tuner_temperature, 297 | ) 298 | yield GaugeMetricFamily( 299 | "connectbox_temperature", 300 | "Temperature", 301 | unit="celsius", 302 | value=temperature, 303 | ) 304 | 305 | 306 | class ProvisioningStatus(Enum): 307 | ONLINE = "Online" 308 | PARTIAL_SERVICE_US = "Partial Service (US only)" 309 | PARTIAL_SERVICE_DS = "Partial Service (DS only)" 310 | PARTIAL_SERVICE_USDS = "Partial Service (US+DS)" 311 | MODEM_MODE = "Modem Mode" 312 | DS_SCANNING = "DS scanning" # confirmed to exist 313 | US_SCANNING = "US scanning" # probably exists too 314 | US_RANGING = "US ranging" # confirmed to exist 315 | DS_RANGING = "DS ranging" # probably exists too 316 | REQUESTING_CM_IP_ADDRESS = "Requesting CM IP address" 317 | 318 | # default case for all future unknown provisioning status 319 | UNKNOWN = "unknown" 320 | 321 | 322 | class DeviceStatusExtractor(XmlMetricsExtractor): 323 | def __init__(self, logger: Logger): 324 | super(DeviceStatusExtractor, self).__init__( 325 | DEVICE_STATUS, {GET.GLOBALSETTINGS, GET.CM_SYSTEM_INFO, GET.CMSTATUS}, logger 326 | ) 327 | 328 | def extract(self, raw_xmls: Dict[int, bytes]) -> Iterable[Metric]: 329 | assert len(raw_xmls) == 3 330 | 331 | # parse GlobalSettings 332 | root = etree.fromstring( 333 | raw_xmls[GET.GLOBALSETTINGS], parser=self._parsers[GET.GLOBALSETTINGS] 334 | ) 335 | firmware_version = root.find("SwVersion").text 336 | cm_provision_mode = root.find("CmProvisionMode").text 337 | gw_provision_mode = root.find("GwProvisionMode").text 338 | operator_id = root.find("OperatorId").text 339 | 340 | # `cm_provision_mode` is known to be None in case `provisioning_status` is "DS scanning". We need to set it to 341 | # some string, otherwise the InfoMetricFamily call fails with AttributeError. 342 | if cm_provision_mode is None: 343 | cm_provision_mode = "Unknown" 344 | 345 | # parse cm_system_info 346 | root = etree.fromstring( 347 | raw_xmls[GET.CM_SYSTEM_INFO], parser=self._parsers[GET.CM_SYSTEM_INFO] 348 | ) 349 | docsis_mode = root.find("cm_docsis_mode").text 350 | hardware_version = root.find("cm_hardware_version").text 351 | uptime_as_str = root.find("cm_system_uptime").text 352 | 353 | # parse cmstatus 354 | root = etree.fromstring( 355 | raw_xmls[GET.CMSTATUS], parser=self._parsers[GET.CMSTATUS] 356 | ) 357 | cable_modem_status = root.find("cm_comment").text 358 | provisioning_status = root.find("provisioning_st").text 359 | 360 | yield InfoMetricFamily( 361 | "connectbox_device", 362 | "Assorted device information", 363 | value={ 364 | "hardware_version": hardware_version, 365 | "firmware_version": firmware_version, 366 | "docsis_mode": docsis_mode, 367 | "cm_provision_mode": cm_provision_mode, 368 | "gw_provision_mode": gw_provision_mode, 369 | "cable_modem_status": cable_modem_status, 370 | "operator_id": operator_id, 371 | }, 372 | ) 373 | 374 | # return an enum-style metric for the provisioning status 375 | try: 376 | enum_provisioning_status = ProvisioningStatus(provisioning_status) 377 | except ValueError: 378 | self._logger.warning(f"Unknown provisioning status '{provisioning_status}'. Please open an issue on Github.") 379 | enum_provisioning_status = ProvisioningStatus.UNKNOWN 380 | 381 | yield StateSetMetricFamily( 382 | "connectbox_provisioning_status", 383 | "Provisioning status description", 384 | value={ 385 | state.value: state == enum_provisioning_status 386 | for state in ProvisioningStatus 387 | }, 388 | ) 389 | 390 | # uptime is reported in a format like "36day(s)15h:24m:58s" which needs parsing 391 | uptime_pattern = r"(\d+)day\(s\)(\d+)h:(\d+)m:(\d+)s" 392 | m = re.fullmatch(uptime_pattern, uptime_as_str) 393 | if m is not None: 394 | uptime_timedelta = timedelta(days=int(m[1]), hours=int(m[2]), minutes=int(m[3]), seconds=int(m[4])) 395 | uptime_seconds = uptime_timedelta.total_seconds() 396 | else: 397 | self._logger.warning(f"Unexpected duration format '{uptime_as_str}', please open an issue on github.") 398 | uptime_seconds = -1 399 | 400 | yield GaugeMetricFamily( 401 | "connectbox_uptime", 402 | "Device uptime in seconds", 403 | unit="seconds", 404 | value=uptime_seconds, 405 | ) 406 | 407 | 408 | def get_metrics_extractor(ident: str, logger: Logger): 409 | """ 410 | Factory method for metrics extractors. 411 | :param ident: metric extractor identifier 412 | :param logger: logging logger 413 | :return: extractor instance 414 | """ 415 | extractors = { 416 | DEVICE_STATUS: DeviceStatusExtractor, 417 | DOWNSTREAM: DownstreamStatusExtractor, 418 | UPSTREAM: UpstreamStatusExtractor, 419 | LAN_USERS: LanUserExtractor, 420 | TEMPERATURE: TemperatureExtractor, 421 | } 422 | if not ident in extractors.keys(): 423 | raise ValueError( 424 | f"Unknown extractor '{ident}', supported are: {', '.join(extractors.keys())}" 425 | ) 426 | cls = extractors[ident] 427 | return cls(logger) 428 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | connectbox-prometheus: 4 | build: 5 | context: . 6 | volumes: 7 | - ./data:/data 8 | ports: 9 | - 9705:9705 10 | -------------------------------------------------------------------------------- /docker-run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | if [ ! -f /data/config.yml ]; then 4 | echo "Config file not found. Copying example to /data/config.yml..." 5 | cp /opt/connectbox-prometheus/config.yml /data/config.yml 6 | echo "Done. Please modify the config file to your liking and restart the container." 7 | exit 8 | fi 9 | 10 | chown -R nobody /data 11 | exec su-exec nobody connectbox_exporter /data/config.yml 12 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -r resources/requirements/production.txt -------------------------------------------------------------------------------- /resources/docs/grafana_dashboard_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbugert/connectbox-prometheus/360668b1cf97490658d16b3030eeccdf212f8e78/resources/docs/grafana_dashboard_screenshot.png -------------------------------------------------------------------------------- /resources/requirements/development.txt: -------------------------------------------------------------------------------- 1 | -r production.txt 2 | black==20.8b1 3 | build==0.3.1.post1 4 | twine==3.3.0 -------------------------------------------------------------------------------- /resources/requirements/production.txt: -------------------------------------------------------------------------------- 1 | click==7.1.2 2 | compal==0.3.1 3 | deepmerge==0.2.1 4 | lxml>=4.5.0 5 | prometheus-client==0.9.0 6 | ruamel.yaml==0.16.13 -------------------------------------------------------------------------------- /resources/schema/123.xsd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from connectbox_exporter.connectbox_exporter import main 4 | 5 | if __name__ == "__main__": 6 | main() 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from setuptools import find_packages, setup 3 | 4 | with open("README.md", "rb") as f: 5 | long_descr = f.read().decode("utf-8") 6 | 7 | 8 | RESOURCES_ROOT = Path(__file__).parent / "resources" 9 | REQUIREMENTS_ROOT = RESOURCES_ROOT / "requirements" 10 | PRODUCTION_REQUIREMENTS = REQUIREMENTS_ROOT / "production.txt" 11 | 12 | with PRODUCTION_REQUIREMENTS.open() as f: 13 | install_requires = [s.strip() for s in f.readlines()] 14 | 15 | setup( 16 | name="connectbox-prometheus", 17 | version="0.2.10", 18 | author="Michael Bugert", 19 | author_email="git@mbugert.de", 20 | description='Prometheus exporter for Compal CH7465LG cable modems, commonly sold as "Connect Box"', 21 | long_description=long_descr, 22 | long_description_content_type="text/markdown", 23 | url="https://github.com/mbugert/connectbox-prometheus", 24 | entry_points={ 25 | "console_scripts": [ 26 | "connectbox_exporter = connectbox_exporter.connectbox_exporter:main" 27 | ] 28 | }, 29 | include_package_data=True, 30 | packages=find_packages(exclude=["tests"]), 31 | install_requires=install_requires, 32 | python_requires=">=3.7", 33 | classifiers=[ 34 | "Development Status :: 5 - Production/Stable", 35 | "Intended Audience :: System Administrators", 36 | "License :: OSI Approved :: Apache Software License", 37 | "Programming Language :: Python :: 3.7", 38 | "Programming Language :: Python :: 3.8", 39 | "Programming Language :: Python :: 3.9", 40 | "Topic :: System :: Networking :: Monitoring", 41 | ], 42 | ) 43 | --------------------------------------------------------------------------------