Add prometheus addons

This commit is contained in:
ai-dev 2024-10-30 10:35:38 +01:00
parent 7cb5adbcf7
commit 5bd412f18a
22 changed files with 780 additions and 0 deletions

0
addon-prometheus-main/.gitignore vendored Normal file
View File

View File

@ -0,0 +1 @@
rules "~MD024"

View File

@ -0,0 +1,66 @@
---
rules:
braces:
level: error
min-spaces-inside: 0
max-spaces-inside: 1
min-spaces-inside-empty: -1
max-spaces-inside-empty: -1
brackets:
level: error
min-spaces-inside: 0
max-spaces-inside: 0
min-spaces-inside-empty: -1
max-spaces-inside-empty: -1
colons:
level: error
max-spaces-before: 0
max-spaces-after: 1
commas:
level: error
max-spaces-before: 0
min-spaces-after: 1
max-spaces-after: 1
comments:
level: error
require-starting-space: true
min-spaces-from-content: 2
comments-indentation:
level: error
document-end:
level: error
present: false
document-start:
level: error
present: true
empty-lines:
level: error
max: 1
max-start: 0
max-end: 1
hyphens:
level: error
max-spaces-after: 1
indentation:
level: error
spaces: 2
indent-sequences: true
check-multi-line-strings: false
key-duplicates:
level: error
line-length:
ignore: |
.github/support.yml
level: warning
max: 120
allow-non-breakable-words: true
allow-non-breakable-inline-mappings: true
new-line-at-end-of-file:
level: error
new-lines:
level: error
type: unix
trailing-spaces:
level: error
truthy:
level: error

View File

@ -0,0 +1,21 @@
# MIT License
Copyright (c) 2020-2022 Robbert Müller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,117 @@
# Home Assistant Community Add-on: Prometheus
[![GitHub Release][releases-shield]][releases]
![Project Stage][project-stage-shield]
[![License][license-shield]](LICENSE.md)
![Supports aarch64 Architecture][aarch64-shield]
![Supports amd64 Architecture][amd64-shield]
![Supports armhf Architecture][armhf-shield]
![Supports armv7 Architecture][armv7-shield]
![Supports i386 Architecture][i386-shield]
[![GitLab CI][gitlabci-shield]][gitlabci]
![Project Maintenance][maintenance-shield]
[![GitHub Activity][commits-shield]][commits]
[![Discord][discord-shield]][discord]
[![Community Forum][forum-shield]][forum]
The open platform for beautiful analytics and monitoring.
![Prometheus in the Home Assistant Frontend](images/screenshot.png)
## About
....
[:books: Read the full add-on documentation][docs]
## Support
Got questions?
You have several options to get them answered:
- The [Home Assistant Community Add-ons Discord chat server][discord] for add-on
support and feature requests.
- The [Home Assistant Discord chat server][discord-ha] for general Home
Assistant discussions and questions.
- The Home Assistant [Community Forum][forum].
- Join the [Reddit subreddit][reddit] in [/r/homeassistant][reddit]
You could also [open an issue here][issue] GitHub.
## Contributing
This is an active open-source project. We are always open to people who want to
use the code or contribute to it.
We have set up a separate document containing our
[contribution guidelines](.github/CONTRIBUTING.md).
Thank you for being involved! :heart_eyes:
## Authors & contributors
The original setup of this repository is by [Robbert Müller][mjrider]
For a full list of all authors and contributors,
check [the contributor's page][contributors].
## We have got some Home Assistant add-ons for you
Want some more functionality to your Home Assistant instance?
We have created multiple add-ons for Home Assistant. For a full list, check out
our [GitHub Repository][repository].
## License
MIT License
Copyright (c) 2020-2022 Robbert Müller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[aarch64-shield]: https://img.shields.io/badge/aarch64-yes-green.svg
[amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
[armhf-shield]: https://img.shields.io/badge/armhf-no-red.svg
[armv7-shield]: https://img.shields.io/badge/armv7-yes-green.svg
[commits-shield]: https://img.shields.io/github/commit-activity/y/hassio-addons/addon-prometheus.svg
[commits]: https://github.com/hassio-addons/addon-prometheus/commits/main
[contributors]: https://github.com/hassio-addons/addon-prometheus/graphs/contributors
[discord-ha]: https://discord.gg/c5DvZ4e
[discord-shield]: https://img.shields.io/discord/478094546522079232.svg
[discord]: https://discord.me/hassioaddons
[docs]: https://github.com/hassio-addons/addon-prometheus/blob/main/prometheus/DOCS.md
[forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg
[forum]: https://example.net
[mjrider]: https://github.com/mjrider
[gitlabci-shield]: https://gitlab.com/hassio-addons/addon-prometheus/badges/master/pipeline.svg
[gitlabci]: https://gitlab.com/hassio-addons/addon-prometheus/pipelines
[i386-shield]: https://img.shields.io/badge/i386-no-red.svg
[issue]: https://github.com/hassio-addons/addon-prometheus/issues
[license-shield]: https://img.shields.io/github/license/hassio-addons/addon-prometheus.svg
[maintenance-shield]: https://img.shields.io/maintenance/yes/2022.svg
[project-stage-shield]: https://img.shields.io/badge/project%20stage-Development-yellowgreen.svg
[reddit]: https://reddit.com/r/homeassistant
[releases-shield]: https://img.shields.io/github/release/hassio-addons/addon-prometheus.svg
[releases]: https://github.com/hassio-addons/addon-prometheus/releases
[repository]: https://github.com/hassio-addons/repository

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

View File

@ -0,0 +1,62 @@
# Home Assistant Community Add-on: Prometheus
[![Release][release-shield]][release] ![Project Stage][project-stage-shield] ![Project Maintenance][maintenance-shield]
[![Discord][discord-shield]][discord] [![Community Forum][forum-shield]][forum]
The open platform for beautiful analytics and monitoring.
## About
...
![Prometheus in the Home Assistant Frontend][screenshot]
{% if channel == "edge" %}
## WARNING! THIS IS AN EDGE VERSION!
This Home Assistant Add-ons repository contains edge builds of add-ons.
Edge builds add-ons are based upon the latest development version.
- They may not work at all.
- They might stop working at any time.
- They could have a negative impact on your system.
This repository was created for:
- Anybody willing to test.
- Anybody interested in trying out upcoming add-ons or add-on features.
- Developers.
If you are more interested in stable releases of our add-ons:
<https://github.com/hassio-addons/repository>
{% endif %}
{% if channel == "beta" %}
## WARNING! THIS IS A BETA VERSION!
This Home Assistant Add-ons repository contains beta releases of add-ons.
- They might stop working at any time.
- They could have a negative impact on your system.
This repository was created for:
- Anybody willing to test.
- Anybody interested in trying out upcoming add-ons or add-on features.
If you are more interested in stable releases of our add-ons:
<https://github.com/hassio-addons/repository>
{% endif %}
[discord-shield]: https://img.shields.io/discord/478094546522079232.svg
[discord]: https://discord.me/hassioaddons
[forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg
[forum]: https://example.org
[maintenance-shield]: https://img.shields.io/maintenance/yes/2022.svg
[project-stage-shield]: https://img.shields.io/badge/project%20stage-Development-yellowgreen.svg
[release-shield]: https://img.shields.io/badge/version-{{ version }}-blue.svg
[release]: {{ repo }}/tree/{{ version }}
[screenshot]: https://github.com/hassio-addons/addon-prometheus/raw/master/images/screenshot.png

View File

@ -0,0 +1,131 @@
# Home Assistant Community Add-on: Prometheus
....
## Installation
The installation of this add-on is pretty straightforward and not different in
comparison to installing any other Home Assistant add-on.
1. Search for the "Prometheus" add-on in the Supervisor add-on store.
1. Install the "Prometheus" add-on.
1. Start the "Prometheus" add-on.
1. Check the logs of the "Prometheus" to see if everything went well.
1. Open the Web UI.
**Note**: The addon supports both Ingress and direct access, this is the default
## Configuration
There are no configuration options for the addon.
To add additional scrape targets you need to create a file per target in /share/prometheus/targets.
Example:
```yaml
---
job_name: "octoprint"
scrape_interval: 5s
metrics_path: "/plugin/prometheus_exporter/metrics"
params:
apikey: ["VERYSECRETAPIKEY"]
static_configs:
- targets: ["octoprint.example.org:5000"]
```
**Note**: _This is just an example, don't copy and paste it! Create your own!_
The job names `home-assistant` and `prometheus` are already defined by default.
For the `homeassistant` target you must add add the following to
the Home Assistant configuration:
```yaml
prometheus:
```
Rules can be created under `/share/prometheus/rules/`
The addon will reload the configuration if a valid configuration is available.
If not it will log errors in the addon log
## Grafana
Grafana can use prometheus as a datasource, to configure this go to grafana
and add a datasource.
The hostname to connect to is depending on the release you installed.
For stable this is `http://a0d7b954-prometheus:9090`
## Known issues and limitations
- Job name must be unique, but this has to be enforced by the user.
- no alert manager yet
## Changelog & Releases
This repository keeps a change log using [GitHub's releases][releases]
functionality.
Releases are based on [Semantic Versioning][semver], and use the format
of `MAJOR.MINOR.PATCH`. In a nutshell, the version will be incremented
based on the following:
- `MAJOR`: Incompatible or major changes.
- `MINOR`: Backwards-compatible new features and enhancements.
- `PATCH`: Backwards-compatible bugfixes and package updates.
## Support
Got questions?
You have several options to get them answered:
- The [Home Assistant Community Add-ons Discord chat server][discord] for add-on
support and feature requests.
- The [Home Assistant Discord chat server][discord-ha] for general Home
Assistant discussions and questions.
- The Home Assistant [Community Forum][forum].
- Join the [Reddit subreddit][reddit] in [/r/homeassistant][reddit]
You could also [open an issue here][issue] GitHub.
## Authors & contributors
The original setup of this repository is by [Robbert Müller][mjrider].
For a full list of all authors and contributors,
check [the contributor's page][contributors].
## License
MIT License
Copyright (c) 2020-2022 Robbert Müller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[contributors]: https://github.com/hassio-addons/addon-Prometheus/graphs/contributors
[discord-ha]: https://discord.gg/c5DvZ4e
[discord]: https://discord.me/hassioaddons
[forum]: https://example.net
[mjrider]: https://github.com/mjrider
[issue]: https://github.com/hassio-addons/addon-prometheus/issues
[reddit]: https://reddit.com/r/homeassistant
[releases]: https://github.com/hassio-addons/addon-prometheus/releases
[semver]: http://semver.org/spec/v2.0.0.htm

View File

@ -0,0 +1,76 @@
ARG BUILD_FROM=ghcr.io/hassio-addons/base:16.3.4
# hadolint ignore=DL3006
FROM ${BUILD_FROM}
# Set shell
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
# Setup base system
ARG BUILD_ARCH=amd64
ENV PROMETHEUS_VERSION=2.55.0
# Copy root filesystem
COPY rootfs /
# hadolint ignore=DL3003
RUN \
ARCH="${BUILD_ARCH}" \
&& if [ "${BUILD_ARCH}" = "aarch64" ]; then ARCH="arm64"; fi \
\
&& apk --no-cache add \
python3=3.10.5-r0 \
py3-idna=3.3-r2 \
py3-certifi=2021.10.8-r0 \
py3-chardet=4.0.0-r3 \
py3-yaml=6.0-r0 \
py3-urllib3=1.26.9-r0 \
py3-requests=2.27.1-r0 \
&& apk --no-cache add --virtual .builddeps \
py-pip=22.1.1-r0 \
\
&& curl -J -L -o /tmp/prometheus.tar.gz \
"https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-${ARCH}.tar.gz" \
&& adduser -s /bin/false -D -H prometheus \
&& cd /tmp \
&& tar -xvf /tmp/prometheus.tar.gz \
&& mkdir -p /etc/prometheus \
&& cp prometheus-${PROMETHEUS_VERSION}.linux-${ARCH}/promtool /usr/local/bin/ \
&& cp prometheus-${PROMETHEUS_VERSION}.linux-${ARCH}/prometheus /usr/local/bin/ \
&& cp -R prometheus-${PROMETHEUS_VERSION}.linux-${ARCH}/console_libraries/ /etc/prometheus/ \
&& cp -R prometheus-${PROMETHEUS_VERSION}.linux-${ARCH}/consoles/ /etc/prometheus/ \
&& rm -r prometheus-${PROMETHEUS_VERSION}.linux-${ARCH} \
&& chown -R prometheus:prometheus /etc/prometheus \
&& pip3 install \
--no-cache-dir \
--prefer-binary \
--find-links "https://wheels.home-assistant.io/alpine-3.15/${BUILD_ARCH}/" \
-r /opt/prometheus-configgen/requirements.txt \
\
&& apk --no-cache del .builddeps \
&& rm -f -r \
/tmp/*
# Build arguments
ARG BUILD_DATE
ARG BUILD_REF
ARG BUILD_VERSION
# Labels
LABEL \
io.hass.name="Prometheus" \
io.hass.description="Cloud native metrics" \
io.hass.arch="${BUILD_ARCH}" \
io.hass.type="addon" \
io.hass.version=${BUILD_VERSION} \
maintainer="feres" \
org.opencontainers.image.title="Prometheus" \
org.opencontainers.image.description="Cloud native metrics" \
org.opencontainers.image.vendor="Home Assistant local Add-ons" \
org.opencontainers.image.authors="Feres" \
org.opencontainers.image.licenses="MIT" \
org.opencontainers.image.url="https://addons.community" \
org.opencontainers.image.source="https://github.com/hassio-addons/addon-prometheus" \
org.opencontainers.image.documentation="https://github.com/hassio-addons/addon-prometheus/blob/master/README.md" \
org.opencontainers.image.created=${BUILD_DATE} \
org.opencontainers.image.revision=${BUILD_REF} \
org.opencontainers.image.version=${BUILD_VERSION}

View File

@ -0,0 +1,8 @@
---
build_from:
aarch64: ghcr.io/hassio-addons/base:16.3.4
amd64: ghcr.io/hassio-addons/base:16.3.4
armv7: ghcr.io/hassio-addons/base:16.3.4
codenotary:
base_image: codenotary@frenck.dev
signer: codenotary@frenck.dev

View File

@ -0,0 +1,26 @@
---
name: Prometheus
version: dev
slug: prometheus
description: Cloud native metrics
url: https://github.com/hassio-addons/addon-prometheus
codenotary: codenotary@frenck.dev
startup: services
ingress: true
ingress_port: 9090
ingress_entry: graph
init: false
panel_icon: mdi:chart-timeline
panel_title: Prometheus
arch:
- aarch64
- amd64
- armv7
hassio_api: true
homeassistant_api: true
map:
- share:rw
ports:
9090/tcp: null
ports_description:
9090/tcp: Not required for Ingress

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,10 @@
#!/command/with-contenv bashio
# ==============================================================================
# Home Assistant Community Add-on: Prometheus
# Configures Prometheus
# ==============================================================================
echo "${SUPERVISOR_TOKEN}" > '/run/home-assistant.token'
mkdir -p /data/prometheus
find /data/prometheus -not -perm 0644 -type f -exec chmod 0660 {} \;
find /data/prometheus -not -perm 0755 -type d -exec chmod 0770 {} \;

View File

@ -0,0 +1,40 @@
---
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "/share/prometheus/rules/*.yml"
- "/share/prometheus/rules/*.yaml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "prometheus"
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ["localhost:9090"]
- job_name: "home-assistant"
scrape_interval: 60s
metrics_path: /core/api/prometheus
# Long-Lived Access Token
bearer_token_file: "/run/home-assistant.token"
scheme: http
static_configs:
- targets: ["supervisor:80"]

View File

@ -0,0 +1,11 @@
#!/command/with-contenv bashio
# ==============================================================================
# Home Assistant Community Add-on: Prometheus
# Take down the S6 supervision tree when Prometheus fails
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "Prometheus config crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "Prometheus config stopped, restarting..."

View File

@ -0,0 +1,13 @@
#!/command/with-contenv bashio
bashio::log.info 'Starting prometheus config generator...'
if ! bashio::fs.directory_exists /share/prometheus/targets; then
mkdir -p /share/prometheus/targets
chown -R prometheus:prometheus /share/prometheus/targets
fi
cd /opt/prometheus-configgen || bashio::exit.nok \
"Could not change working directory for prometheus-configgen."
# Run Prometheus
exec s6-setuidgid prometheus python3 combiner

View File

@ -0,0 +1,11 @@
#!/command/with-contenv bashio
# ==============================================================================
# Home Assistant Community Add-on: Prometheus
# Take down the S6 supervision tree when Prometheus fails
# ==============================================================================
if [[ "${1}" -ne 0 ]] && [[ "${1}" -ne 256 ]]; then
bashio::log.warning "Prometheus crashed, halting add-on"
exec /run/s6/basedir/bin/halt
fi
bashio::log.info "Prometheus stopped, restarting..."

View File

@ -0,0 +1,45 @@
#!/command/with-contenv bashio
# shellcheck disable=SC2191
# ==============================================================================
# Home Assistant Community Add-on: Prometheus
# Runs the Prometheus Server
# ==============================================================================
declare -a options
declare name
declare value
bashio::log.info 'Starting prometheus...'
options+=(--config.file="/etc/prometheus/prometheus.yml" )
options+=(--storage.tsdb.path="/data/prometheus" )
options+=(--web.console.libraries="/usr/share/prometheus/console_libraries" )
options+=(--web.console.templates="/usr/share/prometheus/consoles" )
options+=(--web.route-prefix="/" )
options+=(--web.external-url="http://localhost:9090$(bashio::addon.ingress_entry)/" )
options+=(--web.enable-lifecycle )
# Load custom environment variables
for var in $(bashio::config 'env_vars|keys'); do
name=$(bashio::config "env_vars[${var}].name")
value=$(bashio::config "env_vars[${var}].value")
bashio::log.info "Setting ${name} to ${value}"
export "${name}=${value}"
done
if ! bashio::fs.directory_exists /data/prometheus; then
mkdir -p /data/prometheus
chown prometheus:prometheus /data/prometheus
fi
if ! bashio::fs.directory_exists /share/prometheus/rules; then
mkdir -p /share/prometheus/rules
chown -R prometheus:prometheus /share/prometheus/rules
fi
if ! bashio::fs.directory_exists /share/prometheus/targets; then
mkdir -p /share/prometheus/targets
chown -R prometheus:prometheus /share/prometheus/targets
fi
# Run Prometheus
exec s6-setuidgid prometheus /usr/local/bin/prometheus "${options[@]}"

View File

@ -0,0 +1,100 @@
import sys
import asyncio
import aionotify
import yaml
import os
import tempfile
import requests
from yamlinclude import YamlIncludeConstructor
def generateConfig():
YamlIncludeConstructor.add_to_loader_class(
loader_class=yaml.FullLoader, base_dir="/share/prometheus/"
)
with open("prometheus.template") as f:
data = yaml.load(f, Loader=yaml.FullLoader)
data["scrape_configs"] = (
data[".scrape_configs_static"] + data[".scrape_configs_included"]
)
del data[".scrape_configs_static"]
del data[".scrape_configs_included"]
return yaml.dump(data, default_flow_style=False, default_style="")
def testConfig(config):
tmp = None
result = False
try:
tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, "w") as f:
f.write(config)
r = os.system("promtool check config " + tmp.name + "> /dev/null")
result = r == 0
except:
print("Failed to validate")
raise
if not result:
raise Exception("validation error")
return result
def writeConfig(config, file):
try:
with open(file, "w") as f:
f.write(config)
r = requests.post(url="http://localhost:9090/-/reload", data={})
except:
print("Exception")
loop = asyncio.get_event_loop()
paths_to_watch = ["/share/prometheus/targets/"]
lock = asyncio.Lock()
async def compile():
if lock.locked() == False:
await lock.acquire()
try:
config = generateConfig()
testConfig(config)
writeConfig(config, "/etc/prometheus/prometheus.yml")
print("Compiled")
except:
pass
finally:
lock.release()
async def watcher():
asyncio.create_task(compile())
filewatch = aionotify.Watcher()
for path in paths_to_watch:
filewatch.watch(
path,
aionotify.Flags.MODIFY | aionotify.Flags.CREATE | aionotify.Flags.DELETE,
)
print(path)
await filewatch.setup(loop)
while True:
event = await filewatch.get_event()
sys.stdout.write("Got event: %s\n" % repr(event))
asyncio.create_task(compile())
filewatch.close()
def main():
try:
loop.run_until_complete(watcher())
finally:
# loop.close()
pass
if __name__ == "__main__":
main()

View File

@ -0,0 +1,38 @@
---
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "/share/prometheus/rules/*.yaml"
.scrape_configs_included: !include targets/*.yaml
.scrape_configs_static:
- job_name: 'home-assistant'
scrape_interval: 60s
metrics_path: /core/api/prometheus
# Long-Lived Access Token
bearer_token_file: '/run/home-assistant.token'
scheme: http
static_configs:
- targets: ['supervisor:80']
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:9090']

View File

@ -0,0 +1,4 @@
aionotify
pyyaml-include>=1.2
PyYAML>=5.3.1
requests>=2.23.0