blob: ff29151808e425654e1a7597c7c9647c86fc9801 [file] [log] [blame]
bravofc973b572020-10-21 16:58:50 -03001#!/usr/bin/env python
2
3# Copyright 2021 Whitestack, LLC
4# *************************************************************
5
6# This file is part of OSM Monitoring module
7# All Rights Reserved to Whitestack, LLC
8
9# Licensed under the Apache License, Version 2.0 (the "License"); you may
10# not use this file except in compliance with the License. You may obtain
11# a copy of the License at
12
13# http://www.apache.org/licenses/LICENSE-2.0
14
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18# License for the specific language governing permissions and limitations
19# under the License.
20
21# For those usages not covered by the Apache License, Version 2.0 please
22# contact: fbravo@whitestack.com
23##
24
25import os
26import pymongo
27import yaml
28import aiohttp
29import asyncio
30import copy
31import json
bravof9af7d422021-11-23 17:21:58 -030032import time
bravofc973b572020-10-21 16:58:50 -030033from bson.json_util import dumps
34from bson import ObjectId
35
garciadeblasefa4c2b2022-09-07 22:35:53 +020036# Env variables
37mongodb_url = os.environ["MONGODB_URL"]
38target_database = os.environ["TARGET_DATABASE"]
39prometheus_config_file = os.environ["PROMETHEUS_CONFIG_FILE"]
garciadeblas09eaa922022-09-07 22:57:53 +020040prometheus_base_config_file = os.environ["PROMETHEUS_BASE_CONFIG_FILE"]
garciadeblasefa4c2b2022-09-07 22:35:53 +020041prometheus_url = os.environ["PROMETHEUS_URL"]
42
bravofc973b572020-10-21 16:58:50 -030043
44def get_jobs(client):
garciadeblasefa4c2b2022-09-07 22:35:53 +020045 return json.loads(dumps(client[target_database].prometheus_jobs.find({})))
46
bravofc973b572020-10-21 16:58:50 -030047
48def save_successful_jobs(client, jobs):
garciadeblasefa4c2b2022-09-07 22:35:53 +020049 for job in jobs:
50 client[target_database].prometheus_jobs.update_one(
garciadeblas84fe31f2022-11-15 14:12:48 +010051 {"_id": ObjectId(job["_id"]["$oid"])}, {"$set": {"is_active": True}}
garciadeblasefa4c2b2022-09-07 22:35:53 +020052 )
53
bravofc973b572020-10-21 16:58:50 -030054
55def clean_up_job(prometheus_job):
garciadeblasefa4c2b2022-09-07 22:35:53 +020056 cleaned_prometheus_job = copy.deepcopy(prometheus_job)
57 # take out _id and internal keys
58 cleaned_prometheus_job.pop("_id", None)
59 cleaned_prometheus_job.pop("is_active", None)
60 cleaned_prometheus_job.pop("vnfr_id", None)
61 cleaned_prometheus_job.pop("nsr_id", None)
62 return cleaned_prometheus_job
63
bravofc973b572020-10-21 16:58:50 -030064
65def generate_prometheus_config(prometheus_jobs, config_file_path):
garciadeblas09eaa922022-09-07 22:57:53 +020066 with open(config_file_path, encoding="utf-8", mode="r") as config_file:
67 config_file_yaml = yaml.safe_load(config_file)
garciadeblasefa4c2b2022-09-07 22:35:53 +020068 if config_file_yaml is None:
69 config_file_yaml = {}
garciadeblas09eaa922022-09-07 22:57:53 +020070 if "scrape_configs" not in config_file_yaml:
garciadeblasefa4c2b2022-09-07 22:35:53 +020071 config_file_yaml["scrape_configs"] = []
garciadeblasefa4c2b2022-09-07 22:35:53 +020072
73 for prometheus_job in prometheus_jobs:
74 cleaned_up_job = clean_up_job(prometheus_job)
75 config_file_yaml["scrape_configs"].append(cleaned_up_job)
76
bravofc973b572020-10-21 16:58:50 -030077 return config_file_yaml
78
bravofc973b572020-10-21 16:58:50 -030079
garciadeblasefa4c2b2022-09-07 22:35:53 +020080async def reload_prometheus_config(prom_url):
81 async with aiohttp.ClientSession() as session:
82 async with session.post(prom_url + "/-/reload") as resp:
83 if resp.status > 204:
84 print(f"Error while updating prometheus config: {resp.text()}")
85 return False
86 await asyncio.sleep(5)
87 return True
bravofc973b572020-10-21 16:58:50 -030088
bravofc973b572020-10-21 16:58:50 -030089
90def check_configuration_equal(a_config, b_config):
garciadeblasefa4c2b2022-09-07 22:35:53 +020091 if a_config is None and b_config is None:
92 return True
93 if a_config is None or b_config is None:
94 return False
95 if "scrape_configs" not in a_config and "scrape_configs" not in b_config:
96 return True
97 if "scrape_configs" not in a_config or "scrape_configs" not in b_config:
98 return False
99 a_jobs = [j["job_name"] for j in a_config["scrape_configs"]]
100 b_jobs = [j["job_name"] for j in b_config["scrape_configs"]]
bravofc973b572020-10-21 16:58:50 -0300101
garciadeblasefa4c2b2022-09-07 22:35:53 +0200102 return a_jobs == b_jobs
bravofc973b572020-10-21 16:58:50 -0300103
garciadeblasefa4c2b2022-09-07 22:35:53 +0200104
105async def validate_configuration(prom_url, new_config):
106 async with aiohttp.ClientSession() as session:
107 # Gets the configuration from prometheus
108 # and compares with the inserted one
109 # If prometheus does not admit this configuration,
110 # the old one will remain
111 async with session.get(prom_url + "/api/v1/status/config") as resp:
112 if resp.status > 204:
113 print(f"Error while updating prometheus config: {resp.text()}")
114 return False
115 current_config = await resp.json()
116 return check_configuration_equal(
117 yaml.safe_load(current_config["data"]["yaml"]), new_config
118 )
119
bravofc973b572020-10-21 16:58:50 -0300120
121async def main_task(client):
garciadeblasefa4c2b2022-09-07 22:35:53 +0200122 stored_jobs = get_jobs(client)
123 print(f"Jobs detected : {len(stored_jobs):d}")
124 generated_prometheus_config = generate_prometheus_config(
garciadeblas09eaa922022-09-07 22:57:53 +0200125 stored_jobs, prometheus_base_config_file
garciadeblasefa4c2b2022-09-07 22:35:53 +0200126 )
127 print(f"Writing new config file to {prometheus_config_file}")
128 config_file = open(prometheus_config_file, "w")
129 config_file.truncate(0)
garciadeblas09eaa922022-09-07 22:57:53 +0200130 config_file.write(yaml.safe_dump(generated_prometheus_config))
garciadeblasefa4c2b2022-09-07 22:35:53 +0200131 config_file.close()
132 print("New config written, updating prometheus")
133 update_resp = await reload_prometheus_config(prometheus_url)
garciadeblas84fe31f2022-11-15 14:12:48 +0100134 is_valid = await validate_configuration(prometheus_url, generated_prometheus_config)
garciadeblasefa4c2b2022-09-07 22:35:53 +0200135 if update_resp and is_valid:
136 print("Prometheus config update successful")
137 save_successful_jobs(client, stored_jobs)
138 else:
139 print(
140 "Error while updating prometheus config: "
141 "current config doesn't match with updated values"
142 )
143
bravofc973b572020-10-21 16:58:50 -0300144
145async def main():
garciadeblasefa4c2b2022-09-07 22:35:53 +0200146 client = pymongo.MongoClient(mongodb_url)
garciadeblas84fe31f2022-11-15 14:12:48 +0100147 print("Created MongoClient to connect to MongoDB!")
bravofc973b572020-10-21 16:58:50 -0300148
garciadeblas84fe31f2022-11-15 14:12:48 +0100149 # Initial loop. First refresh of prometheus config file
150 first_refresh_completed = False
151 tries = 1
152 while tries <= 3:
153 try:
154 print("Refreshing prometheus config file for first time")
155 await main_task(client)
156 first_refresh_completed = True
157 except Exception as error:
158 print(f"Error in configuration attempt! Number of tries: {tries}/3")
159 print(error)
160 time.sleep(5)
161 tries += 1
162 if not first_refresh_completed:
163 print("Not possible to refresh prometheus config file for first time")
164 return
garciadeblasefa4c2b2022-09-07 22:35:53 +0200165
garciadeblas84fe31f2022-11-15 14:12:48 +0100166 # Main loop
garciadeblasefa4c2b2022-09-07 22:35:53 +0200167 while True:
168 try:
169 # Needs mongodb in replica mode as this feature relies in OpLog
170 change_stream = client[target_database].prometheus_jobs.watch(
171 [
172 {
173 "$match": {
174 # If you want to modify a particular job,
175 # delete and insert it again
176 "operationType": {"$in": ["insert", "delete"]}
177 }
178 }
179 ]
180 )
181
182 # Single thread, no race conditions and ops are queued up in order
183 print("Listening to changes in prometheus jobs collection")
184 for change in change_stream:
185 print("Change detected, updating prometheus config")
garciadeblas84fe31f2022-11-15 14:12:48 +0100186 print(f"{change}")
garciadeblasefa4c2b2022-09-07 22:35:53 +0200187 await main_task(client)
188 print()
189 except Exception as error:
190 print(error)
191 print(
192 "Detected failure while listening to prometheus jobs collection, "
193 "retrying..."
194 )
195 time.sleep(5)
196
bravofc973b572020-10-21 16:58:50 -0300197
198asyncio.run(main())