-
Notifications
You must be signed in to change notification settings - Fork 1
增加监控导出容器编排镜像audit #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ghangz
wants to merge
2
commits into
MetaX-MACA:main
Choose a base branch
from
ghangz:mengz/mxexporter-k8s-image-audit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| from tools.audit_k8s_images import audit | ||
|
|
||
|
|
||
| class AuditK8sImagesTest(unittest.TestCase): | ||
| def test_detects_inconsistent_exporter_images(self): | ||
| with tempfile.TemporaryDirectory() as tmpdir: | ||
| root = Path(tmpdir) | ||
| deploy = root / "deployment" / "mx-exporter" | ||
| deploy.mkdir(parents=True) | ||
| (deploy / "a.yaml").write_text("image: repo/mx-exporter:v1\n", encoding="utf-8") | ||
| (deploy / "b.yaml").write_text("image: repo/mx-exporter:v2\n", encoding="utf-8") | ||
|
|
||
| report = audit(root) | ||
|
|
||
| self.assertEqual(report["mx_exporter_image_count"], 2) | ||
| self.assertIs(report["mx_exporter_image_consistent"], False) | ||
|
|
||
| def test_preserves_quoted_helm_template_images(self): | ||
| with tempfile.TemporaryDirectory() as tmpdir: | ||
| root = Path(tmpdir) | ||
| deploy = root / "deployment" / "mx-exporter" | ||
| deploy.mkdir(parents=True) | ||
| (deploy / "values.yaml").write_text( | ||
| 'image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"\n', | ||
| encoding="utf-8", | ||
| ) | ||
|
|
||
| report = audit(root) | ||
|
|
||
| self.assertEqual( | ||
| report["mx_exporter_images"], | ||
| ["{{ .Values.image.repository }}:{{ .Values.image.tag }}"], | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| #!/usr/bin/env python3 | ||
| """Audit Kubernetes and Helm manifests for mx-exporter image references.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import json | ||
| import re | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| IMAGE_RE = re.compile(r"^\s*image:\s*['\"]?([^'\"\n]+?)['\"]?\s*(?:#.*)?$", re.MULTILINE) | ||
|
|
||
|
|
||
| def collect_images(root: Path) -> list[dict[str, str]]: | ||
| images: list[dict[str, str]] = [] | ||
| deploy_dir = root / "deployment" | ||
| if not deploy_dir.is_dir(): | ||
| return images | ||
|
|
||
| for path in sorted(deploy_dir.rglob("*")): | ||
| if path.suffix not in {".yaml", ".yml"}: | ||
| continue | ||
| if not path.is_file(): | ||
| continue | ||
| text = path.read_text(encoding="utf-8", errors="replace") | ||
| for match in IMAGE_RE.finditer(text): | ||
| images.append({"path": path.relative_to(root).as_posix(), "image": match.group(1)}) | ||
| return images | ||
|
|
||
|
|
||
| def audit(root: Path) -> dict[str, object]: | ||
| images = collect_images(root) | ||
| exporter_images = sorted({item["image"] for item in images if "mx-exporter" in item["path"].lower()}) | ||
| return { | ||
| "image_count": len(images), | ||
| "images": images, | ||
| "mx_exporter_images": exporter_images, | ||
| "mx_exporter_image_count": len(exporter_images), | ||
| "mx_exporter_image_consistent": len(exporter_images) <= 1, | ||
| } | ||
|
|
||
|
|
||
| def main() -> int: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("--root", type=Path, default=Path.cwd(), help="repository root") | ||
| parser.add_argument("--strict", action="store_true", help="return non-zero when mx-exporter images differ") | ||
| parser.add_argument("--output", type=Path, help="write audit JSON to this path") | ||
| args = parser.parse_args() | ||
|
|
||
| payload = audit(args.root) | ||
| text = json.dumps(payload, indent=2, ensure_ascii=False) | ||
| if args.output: | ||
| args.output.write_text(text + "\n", encoding="utf-8") | ||
| else: | ||
| print(text) | ||
| return 1 if args.strict and not payload["mx_exporter_image_consistent"] else 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| raise SystemExit(main()) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
在遍历
deployment目录时,存在以下两个潜在问题:deployment目录不存在,直接调用rglob可能会导致不符合预期的行为或在某些环境下抛出异常。.yaml或.yml结尾的目录(例如某些临时目录或特定配置),直接调用path.read_text()会抛出IsADirectoryError异常。建议在遍历前先检查
deployment是否为目录,并在循环中增加path.is_file()的判断,以提高代码的健壮性。