vexxhost-bot | 1ff9767 | 2024-10-30 18:11:50 -0400 | [diff] [blame] | 1 | # Copyright (c) 2024 VEXXHOST, Inc. |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | import json |
| 5 | import os |
| 6 | import shutil |
| 7 | import tempfile |
| 8 | |
| 9 | import rjsonnet |
| 10 | import yaml |
| 11 | |
| 12 | |
| 13 | def import_callback(base, rel): |
| 14 | """ |
| 15 | :param base: The directory containing the code that did the import. |
| 16 | :param rel: The path imported by the code. |
| 17 | """ |
| 18 | path = os.path.join(base, rel) |
| 19 | with open(path, "r") as f: |
| 20 | return path, f.read() |
| 21 | |
| 22 | |
| 23 | def main(): |
| 24 | compiled_string = rjsonnet.evaluate_file( |
| 25 | "roles/kube_prometheus_stack/files/jsonnet/rules.jsonnet", |
| 26 | import_callback=import_callback, |
| 27 | ) |
| 28 | compiled = json.loads(compiled_string) |
| 29 | |
| 30 | tempdir = tempfile.mkdtemp() |
| 31 | rule_files = [] |
| 32 | |
| 33 | try: |
| 34 | for rule_file, data in compiled.items(): |
| 35 | file_name = rule_file + ".yml" |
| 36 | path = os.path.join(tempdir, file_name) |
| 37 | |
| 38 | if os.path.exists(path): |
| 39 | raise Exception(f"File {path} already exists") |
| 40 | with open(path, "w") as f: |
| 41 | yaml.dump(data, f) |
| 42 | |
| 43 | rule_files.append(path) |
| 44 | |
| 45 | with open("roles/kube_prometheus_stack/files/jsonnet/tests.yml") as f: |
| 46 | tests = yaml.safe_load(f) |
| 47 | |
| 48 | tests["rule_files"] = rule_files |
| 49 | |
| 50 | tests_file = os.path.join(tempdir, "tests.yml") |
| 51 | with open(tests_file, "w") as f: |
| 52 | yaml.dump(tests, f) |
| 53 | |
| 54 | # TODO(mnaser): Enable JUnit output |
| 55 | os.system(f"promtool test rules {tests_file}") |
| 56 | finally: |
| 57 | shutil.rmtree(tempdir) |
| 58 | |
| 59 | |
| 60 | if __name__ == "__main__": |
| 61 | main() |