Moved grafana to module

This commit is contained in:
Edgar P. Burkhart 2022-01-26 17:54:27 +01:00
parent 59f00f069c
commit d10118d14b
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
2 changed files with 68 additions and 54 deletions

View file

@ -11,10 +11,9 @@ from datetime import datetime
from pathlib import Path from pathlib import Path
import subprocess as sp import subprocess as sp
import urllib.request
import urllib.parse
import urllib.error import urllib.error
import json
from .grafana import Silencer
_t0 = time() _t0 = time()
@ -41,38 +40,11 @@ log.info('Starting program')
if config.getboolean('grafana', 'pause', fallback=False): if config.getboolean('grafana', 'pause', fallback=False):
log.info('Silencing Grafana alert') log.info('Silencing Grafana alert')
try: grafana = Silencer(
with urllib.request.urlopen( url=config.get('grafana', 'url'),
urllib.request.Request( apikey=config.get('grafana', 'apikey'),
urllib.parse.urljoin( )
config.get('grafana', 'url'), grafana.silence_alert()
'api/alertmanager/grafana/api/v2/silences',
),
headers={
'Authorization':
f'Bearer {config.get("grafana", "apikey")}',
},
),
data=bytes(json.dumps({
"comment": "Openfoam run",
"createdBy": "Python OpenFoam run",
"endsAt": (datetime.utcnow() + timedelta(days=1)).isoformat(),
"matchers": [
{
"isEqual": True,
"isRegex": False,
"name": "alertname",
"value": "CPU Usage"
}
],
"startsAt": datetime.utcnow().isoformat()
}), 'utf-8'),
) as api_req:
api_res = api_req.read()
grafana_alert_id = json.loads(api_res)['id']
except urllib.error.HTTPError as e:
log.error(f'Grafana silence returned code {e.code}')
sys.exit(1)
input_dir = Path(config.get('main', 'input_dir'), config.get('main', 'case'))\ input_dir = Path(config.get('main', 'input_dir'), config.get('main', 'case'))\
.expanduser() .expanduser()
@ -242,25 +214,7 @@ if config.getboolean('olaFlow', 'enable', fallback=False):
if config.getboolean('grafana', 'pause', fallback=False): if config.getboolean('grafana', 'pause', fallback=False):
log.info('Unsilencing Grafana alert') log.info('Unsilencing Grafana alert')
try: grafana.unsilence_alert()
with urllib.request.urlopen(
urllib.request.Request(
urllib.parse.urljoin(
config.get('grafana', 'url'),
'api/alertmanager/grafana/api/v2/silence/'
f'{grafana_alert_id}',
),
headers={
'Authorization':
f'Bearer {config.get("grafana", "apikey")}',
},
method='DELETE',
),
) as api_req:
api_res = api_req.read()
except urllib.error.HTTPError as e:
log.error(f'Grafana unsilence returned code {e.code}')
sys.exit(1)
_t1 = time() _t1 = time()
log.info(f'Program ended successfully after {timedelta(seconds=_t1-_t0)}') log.info(f'Program ended successfully after {timedelta(seconds=_t1-_t0)}')

60
openfoam/run/grafana.py Normal file
View file

@ -0,0 +1,60 @@
from datetime import timedelta
from datetime import datetime
import logging
import urllib.request
import urllib.parse
import json
log = logging.getLogger('grafana')
class Silencer():
def __init__(self, url, apikey):
self._url = url
self._apikey = apikey
def silence_alert(self):
with urllib.request.urlopen(
urllib.request.Request(
urllib.parse.urljoin(
self._url,
'api/alertmanager/grafana/api/v2/silences',
),
headers={
'Authorization':
f'Bearer {self._apikey}',
},
),
data=bytes(json.dumps({
"comment": "Openfoam run",
"createdBy": "Python OpenFoam run",
"endsAt": (datetime.utcnow() \
+ timedelta(days=1)).isoformat(),
"matchers": [
{
"isEqual": True,
"isRegex": False,
"name": "alertname",
"value": "CPU Usage"
}
],
"startsAt": datetime.utcnow().isoformat()
}), 'utf-8')) as api_req:
api_res = api_req.read()
self._alertid = json.loads(api_res)['id']
log.info(f'Grafana alerts silenced (id: {self._alertid})')
def unsilence_alert(self):
input()
with urllib.request.urlopen(
urllib.request.Request(
urllib.parse.urljoin(
self._url,
'api/alertmanager/grafana/api/v2/silence/'
f'{self._alertid}',
),
headers={
'Authorization':
f'Bearer {self._apikey}',
},
method='DELETE')):
log.info(f'Grafana silence (id: {self._alertid}) deleted')