first commit

This commit is contained in:
meewan 2021-02-14 18:47:41 +01:00
parent 64ecbd1f19
commit c9ad686bd1
3 changed files with 112 additions and 0 deletions

96
cachetupdater.py Normal file
View File

@ -0,0 +1,96 @@
#!/usr/lib/python3
from configparser import ConfigParser
import requests
COMPONENT_PATH = "%(cachet_url)s/api/v1/components/%(component_id)s"
def checker(config, section):
"""Main entry point to check and update a target status
:param dict config: a dict like object with whole configuration
:param str section: the section to check
"""
config_section = config[section]
result = http_checker(config_section)
update(config, section, result)
def http_checker(conf):
"""Check an http/https endpoint
:param dict conf: a dict like object with the target configuration
:rtype: boolean
:returns: True if the target was reachable witin timeout and the status
code was 200 or 204
"""
url = conf["url"]
timeout = conf.get('timeout', 2)
try:
result = requests.get(url, timeout=timeout)
except requests.exceptions.Timeout:
return False
return result.status_code in (200, 204)
def update(config, section, result):
"""Update the cachet instance with the given result
"""
cachet_url = config["cachetupdater"]["url"]
cachet_token = config["cachetupdater"]["token"]
component_id = config[section]["id"]
status = 1 if result else 4
url = COMPONENT_PATH % {
"cachet_url": cachet_url,
"component_id": component_id,
}
if need_update(url, status):
headers = {
"Content-Type": "application/json",
"X-Cachet-Token": cachet_token,
}
payload = {
"status": 1 if result else 4
}
requests.request("PUT", url, json=payload, headers=headers)
def need_update(url, status):
response = requests.request("GET", url)
current = response.json()
current_status = int(current.get("data", {}).get("status", None))
if current_status == status or current_status not in (1, 4):
return False
else:
return True
def main(args):
"""Entry point for the script
:param configParser args: tha argmuents given via the command line
"""
config = get_configuration(args.configuration)
for section in config.sections():
if section != "cachetupdater":
checker(config, section)
def get_configuration(config_path):
"""Reads the configuration and returns it
:param str config_path: path to retrieve the configuration file
:rtype: a dict like object
:returns: a dict like object containing the configuration
"""
config = ConfigParser()
config.read(config_path)
return config
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("configuration", help="path to the config file")
main(parser.parse_args())

15
config/cachetupdater.ini Normal file
View File

@ -0,0 +1,15 @@
[cachetupdater]
url = https://status.example.com
token = XXXXXXXXXXXXXXXXXXXX
[katzei.fr]
id = 1
url = https://katzei.fr
[bw.katzei.fr]
id = 2
url = https://bw.katzei.fr
[cloud.katzei.fr]
id = 3
url = https://cloud.katzei.fr

1
requirement.txt Normal file
View File

@ -0,0 +1 @@
requests