|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import subprocess |
| 4 | +import sys |
| 5 | +import yaml |
| 6 | +import shutil |
| 7 | + |
| 8 | + |
| 9 | +def get_nncp_yaml_documents(yaml_file): |
| 10 | + try: |
| 11 | + with open(yaml_file, "r") as f: |
| 12 | + documents = list(yaml.safe_load_all(f)) |
| 13 | + except Exception as e: |
| 14 | + print(f"Error reading YAML file: {e}") |
| 15 | + sys.exit(1) |
| 16 | + |
| 17 | + return documents |
| 18 | + |
| 19 | + |
| 20 | +def validate_nncp_documents(docs): |
| 21 | + # Process each document that has spec.desiredState |
| 22 | + for _idx, doc in enumerate(docs): |
| 23 | + if doc and "spec" in doc and "desiredState" in doc["spec"]: |
| 24 | + desired_state = doc["spec"]["desiredState"] |
| 25 | + |
| 26 | + # Convert the desiredState back to YAML for nmstatectl |
| 27 | + content = yaml.dump(desired_state, default_flow_style=False) |
| 28 | + |
| 29 | + # Validate with nmstatectl |
| 30 | + cmd = ["nmstatectl", "-q", "validate", "--"] |
| 31 | + try: |
| 32 | + subprocess.run( |
| 33 | + cmd, input=content, text=True, capture_output=True, check=True |
| 34 | + ) |
| 35 | + except subprocess.CalledProcessError as e: |
| 36 | + print(f"Document {_idx}: Validation failed") |
| 37 | + if e.stderr: |
| 38 | + print(f"Error: {e.stderr.strip()}") |
| 39 | + sys.exit(1) |
| 40 | + except Exception as e: |
| 41 | + print(f"Document {_idx}: Error running nmstatectl - {e}") |
| 42 | + sys.exit(1) |
| 43 | + |
| 44 | + |
| 45 | +def main(): |
| 46 | + print(sys.argv) |
| 47 | + if len(sys.argv) < 2: |
| 48 | + print("Usage: nmstate_validate.py <yaml_file> <yaml_file> ...") |
| 49 | + sys.exit(1) |
| 50 | + |
| 51 | + # Check if nmstatectl is installed |
| 52 | + if not shutil.which("nmstatectl"): |
| 53 | + print("nmstatectl is not installed") |
| 54 | + sys.exit(0) |
| 55 | + |
| 56 | + for yaml_file in sys.argv[1:]: |
| 57 | + print(f"Validating {yaml_file}") |
| 58 | + documents = get_nncp_yaml_documents(yaml_file) |
| 59 | + validate_nncp_documents(documents) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + main() |
0 commit comments