Skip to content

Add an env var that allows excluding containers by name#466

Merged
Avi-Robusta merged 3 commits intomainfrom
krr-eforcer-exclude-containers
Aug 27, 2025
Merged

Add an env var that allows excluding containers by name#466
Avi-Robusta merged 3 commits intomainfrom
krr-eforcer-exclude-containers

Conversation

@arikalon1
Copy link
Contributor

Useful for containers that have memory spike that is too fast to be captured by krr (prometheus)

Useful for containers that have memory spike that is too fast to be captured by krr (prometheus)
@coderabbitai
Copy link

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds EXCLUDED_CONTAINERS parsing from environment to enforcer/env_vars.py, integrates it into enforcer/patch_manager.py to skip patching containers listed, reorders ENFORCER_SSL_CERT_FILE assignment, and updates README with documentation for the new env var.

Changes

Cohort / File(s) Change summary
Env vars parsing
enforcer/env_vars.py
Added public constant EXCLUDED_CONTAINERS parsed from env var EXCLUDED_CONTAINERS (comma-separated, trimmed, empties removed). Moved ENFORCER_SSL_CERT_FILE assignment to file end and ensured trailing newline.
Patch manager exclusion logic
enforcer/patch_manager.py
Imported EXCLUDED_CONTAINERS. Added early-return guard in patch_container_resources: if container name is in EXCLUDED_CONTAINERS, log skip and return without generating patches; otherwise unchanged.
Documentation
enforcer/README.md
Added "Additional settings" documentation describing EXCLUDED_CONTAINERS and example Helm values showing how to set it.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant PM as PatchManager
  participant EV as EnvVars

  Caller->>PM: patch_container_resources(container)
  PM->>EV: Read EXCLUDED_CONTAINERS
  alt container.name in EXCLUDED_CONTAINERS
    PM-->>Caller: Log "Skipping excluded container {name}" and return []
  else not excluded
    PM->>PM: Perform resource diffing and validation
    PM-->>Caller: Return generated patches
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch krr-eforcer-exclude-containers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@arikalon1 arikalon1 requested a review from Avi-Robusta August 26, 2025 20:12
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
enforcer/env_vars.py (1)

26-27: Normalize and Precompute EXCLUDED_CONTAINERS for O(1), Case-Insensitive Lookups

I verified that EXCLUDED_CONTAINERS is defined only in enforcer/env_vars.py and used once in enforcer/patch_manager.py (membership check) and nowhere else (via rg -nC2 '\bEXCLUDED_CONTAINERS(_SET)?\b'). The following optional refactor will:

  • Keep the original list for iteration/debugging
  • Add a lowercase-normalized frozenset for constant-time membership tests
  • Preserve backward compatibility (no existing code breaks)

Key locations:

  • enforcer/env_vars.py: definition site
  • enforcer/patch_manager.py: import & membership check

Proposed diff:

--- a/enforcer/env_vars.py
+++ b/enforcer/env_vars.py
@@ -24,4 +24,10 @@ ENFORCER_SSL_CERT_FILE = os.environ.get("ENFORCER_SSL_CERT_FILE", "")
 _raw_excluded = os.environ.get("EXCLUDED_CONTAINERS", "")
-EXCLUDED_CONTAINERS = [container_name.strip() for container_name
-                       in _raw_excluded.split(",") if container_name.strip()]
+EXCLUDED_CONTAINERS = [
+    name.strip()
+    for name in _raw_excluded.split(",")
+    if name.strip()
+]
+# Normalized, constant-time membership set (lowercase)
+EXCLUDED_CONTAINERS_SET = frozenset(name.lower() for name in EXCLUDED_CONTAINERS)
--- a/enforcer/patch_manager.py
+++ b/enforcer/patch_manager.py
@@ -5,7 +5,7 @@ from enforcer.model import ContainerRecommendation
-from enforcer.env_vars import UPDATE_THRESHOLD, EXCLUDED_CONTAINERS
+from enforcer.env_vars import UPDATE_THRESHOLD, EXCLUDED_CONTAINERS, EXCLUDED_CONTAINERS_SET
 
 logger = logging.getLogger()
@@ -243,7 +243,8 @@ def patch_container(container: Dict[str, Any]) -> List[Dict[str, Any]]:
     container_name = container.get("name")
-    if container_name and container_name in EXCLUDED_CONTAINERS:
+    # Use lowercase set for O(1), case-insensitive membership
+    if container_name and container_name.lower() in EXCLUDED_CONTAINERS_SET:
         logging.info(f"Skipping excluded container {container_name}")
         return patches

Let me know if you’d like a short README/Helm values snippet added to document EXCLUDED_CONTAINERS with examples.

enforcer/patch_manager.py (2)

5-6: Import of EXCLUDED_CONTAINERS is OK; consider importing the normalized set if added

This aligns with the new env var. If you adopt EXCLUDED_CONTAINERS_SET as suggested in env_vars.py, import it here to avoid per-call normalization.

If you add the set, update the import like:

-from enforcer.env_vars import UPDATE_THRESHOLD, EXCLUDED_CONTAINERS
+from enforcer.env_vars import UPDATE_THRESHOLD, EXCLUDED_CONTAINERS, EXCLUDED_CONTAINERS_SET

245-249: Use the module logger consistently; optionally make exclusion check case-insensitive

Everything else looks good. Two tweaks:

  • Consistency: the file defines logger = logging.getLogger() but this block uses logging.info.
  • Optional: case-insensitive membership avoids surprises if the env var has mixed case.

Minimal fix for logging:

-    if container_name and container_name in EXCLUDED_CONTAINERS:
-        logging.info(f"Skipping excluded container {container_name}")
+    if container_name and container_name in EXCLUDED_CONTAINERS:
+        logger.info(f"Skipping excluded container {container_name}")

If you added EXCLUDED_CONTAINERS_SET in env_vars.py:

-    if container_name and container_name in EXCLUDED_CONTAINERS:
+    if container_name and container_name.lower() in EXCLUDED_CONTAINERS_SET:
         logger.info(f"Skipping excluded container {container_name}")
         return patches

Alternatively, without changing env_vars.py (micro-optimization trade-off: computes set per call):

-    if container_name and container_name in EXCLUDED_CONTAINERS:
+    if container_name and container_name.lower() in {n.lower() for n in EXCLUDED_CONTAINERS}:
         logger.info(f"Skipping excluded container {container_name}")
         return patches

If you want the skip to be logged even when there’s no recommendation (today it returns earlier), consider moving this block above the “if not recommendation” check. Verify desired verbosity before changing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 97b49a5 and 7f3ed64.

📒 Files selected for processing (2)
  • enforcer/env_vars.py (1 hunks)
  • enforcer/patch_manager.py (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
enforcer/patch_manager.py (1)
enforcer/model.py (1)
  • get (62-63)
🔇 Additional comments (1)
enforcer/env_vars.py (1)

24-24: No-op move of ENFORCER_SSL_CERT_FILE is fine

Reordering within the constants block has no behavioral impact. Keeping SSL-related vars adjacent is clearer.

Avi-Robusta
Avi-Robusta previously approved these changes Aug 27, 2025
Copy link
Contributor

@Avi-Robusta Avi-Robusta left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
enforcer/README.md (1)

105-113: Clarify comma-separated format, matching semantics, and quote YAML value.

Hyphenate “comma-separated”, remove the extra comma, and note exact, case-sensitive matching. Quote the YAML value to avoid ambiguity.

Please confirm: matching is exact and case-sensitive against the container.name field (including init containers and sidecars), and whitespace around names is trimmed.

-You can do that by adding an environment variable named `EXCLUDED_CONTAINERS`, with a list of comma separated container names that should be excluded.
-For example:
+You can do that by adding an environment variable named `EXCLUDED_CONTAINERS` with a comma-separated list of container names to exclude (exact, case-sensitive; surrounding whitespace is ignored).
+Example:
@@
 additionalEnvVars:
   ...
   - name: EXCLUDED_CONTAINERS
-    value: my-spiky-container, java-init-container
+    value: "my-spiky-container, java-init-container"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7f3ed64 and 461393f.

📒 Files selected for processing (1)
  • enforcer/README.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
enforcer/README.md

[grammar] ~102-~102: There might be a mistake here.
Context: ...forcement`, across all Deployments/Pods. For example, if you have some init conta...

(QB_NEW_EN)


[grammar] ~105-~105: There might be a mistake here.
Context: ...container names that should be excluded. For example: ```yaml additionalEnvVars:...

(QB_NEW_EN)

@Avi-Robusta Avi-Robusta merged commit f82111d into main Aug 27, 2025
3 checks passed
@Avi-Robusta Avi-Robusta deleted the krr-eforcer-exclude-containers branch August 27, 2025 07:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants