Skip to content

Instantly share code, notes, and snippets.

@AoJ
Forked from f41gh7/victoria_metrics_push_gw.py
Created August 5, 2022 10:36
Show Gist options
  • Save AoJ/63129cd9983409a0b885183e69be3f07 to your computer and use it in GitHub Desktop.
Save AoJ/63129cd9983409a0b885183e69be3f07 to your computer and use it in GitHub Desktop.
VictoriaMetrics as push gateway.
from prometheus_client import Counter, start_http_server
from threading import Thread
import requests as re
import time
JOB_NAME = 'test'
INSTANCE = 'localhost'
def scrape_and_send(local_url: str, vm_url: str, scrape_interval: int):
s = re.Session()
scrape_cnt = Counter('self_scrapes_ok_total', 'some help')
push_cnt = Counter('self_vm_push_ok_total', 'some help')
vm_url_parametrized = f"{vm_url}?extra_label=job={JOB_NAME}&extra_label=instance={INSTANCE}"
while True:
try:
time.sleep(scrape_interval)
with s.get(local_url, timeout=3) as local_data:
if local_data.status_code != 200:
print(f"bad status code, want 200, got {local_data.status_code}")
continue
scrape_cnt.inc()
with s.post(vm_url_parametrized, data=local_data.text, timeout=5) as vm_resp:
if vm_resp.status_code != 204:
print(f"bad status code, want 204, got {vm_resp.status_code}")
continue
push_cnt.inc()
except Exception as e:
print(f"error occurred: {e}")
def push_to_vm(local_url: str, vm_url: str, scrape_interval=None) -> Thread:
if not scrape_interval:
# scrape interval 10s by default
scrape_interval = 10
th = Thread(target=scrape_and_send, args=(local_url, vm_url, scrape_interval,))
th.start()
return th
push_to_vm("http://localhost:8000", "http://localhost:8428/api/v1/import/prometheus")
start_http_server(8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment