Skip to content
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

Testrunningpods #549

Merged
merged 9 commits into from
Dec 31, 2024
Merged

Testrunningpods #549

merged 9 commits into from
Dec 31, 2024

Conversation

kooomix
Copy link
Contributor

@kooomix kooomix commented Dec 31, 2024

PR Type

Enhancement, Bug fix


Description

  • Refactored pod filtering logic in get_pods() method to use clearer list comprehensions instead of nested lambda functions
  • Added comprehensive cluster state logging using kubectl get pods -A command when verifying pod status
  • Fixed incorrect elapsed time reporting in pod readiness verification (was showing remaining time instead of elapsed time)
  • Enhanced error messages with more detailed information about running pods and their status
  • Improved code readability and maintainability throughout the BaseK8S class
  • Added better error handling for edge cases like None pods

Changes walkthrough 📝

Relevant files
Enhancement
base_k8s.py
Enhance pod management and logging in Kubernetes base class

tests_scripts/kubernetes/base_k8s.py

  • Improved pod filtering logic with clearer list comprehensions
  • Added cluster state logging using 'kubectl get pods -A'
  • Fixed elapsed time reporting in pod readiness verification
  • Enhanced error messages with more detailed pod information
  • +27/-9   

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 Security concerns

    Command injection:
    The code executes kubectl commands using shell=True without proper input sanitization. If the namespace parameter is user-controlled, this could allow arbitrary command execution. The command should be executed with shell=False and arguments passed as a list to prevent injection attacks.

    ⚡ Recommended focus areas for review

    Shell Injection

    The kubectl command is executed directly through shell=True without sanitizing the namespace input, which could allow command injection if namespace is user-controlled

    result = subprocess.run("kubectl get pods -A", timeout=300, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    Error Handling

    The subprocess.run() call should handle potential exceptions and timeouts that could occur when executing the kubectl command

    result = subprocess.run("kubectl get pods -A", timeout=300, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    @kooomix kooomix merged commit 5946418 into master Dec 31, 2024
    2 checks passed
    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    General
    Add proper error handling for shell command execution and improve logging output clarity

    Add error handling for the subprocess.run() call as it could raise TimeoutExpired or
    CalledProcessError exceptions, which would mask the original pod verification
    failure.

    tests_scripts/kubernetes/base_k8s.py [770-771]

    -result = subprocess.run("kubectl get pods -A", timeout=300, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    -Logger.logger.info(f"cluster state {result}")
    +try:
    +    result = subprocess.run("kubectl get pods -A", timeout=300, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    +    Logger.logger.info(f"cluster state: stdout={result.stdout}, stderr={result.stderr}")
    +except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
    +    Logger.logger.error(f"Failed to get cluster state: {str(e)}")
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion adds crucial error handling for subprocess execution and improves log clarity by including both stdout and stderr. This enhancement helps prevent silent failures and makes debugging easier.

    8
    Enhance error messages with detailed pod status information for better debugging

    In verify_running_pods(), include pod status details in the error message to help
    diagnose why pods are not ready.

    tests_scripts/kubernetes/base_k8s.py [783-784]

    -raise Exception("wrong number of pods are running after {} seconds. expected: {}, running: {}, pods:{}"
    -                .format(delta_t, replicas, len(running_pods), running_pods))
    +raise Exception("wrong number of pods are running after {} seconds. expected: {}, running: {}. Pod statuses: {}"
    +                .format(delta_t, replicas, len(running_pods), 
    +                       [(pod.metadata.name, pod.status.phase, pod.status.conditions) for pod in running_pods]))
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Adding detailed pod status information to error messages significantly improves debugging capabilities by providing crucial context about why pods aren't ready, making troubleshooting more efficient.

    7
    Possible issue
    Simplify null check and provide a default empty list to prevent potential NoneType errors

    The get_pods() method should validate that pods is not None before applying name
    filtering to avoid potential NoneType attribute errors.

    tests_scripts/kubernetes/base_k8s.py [632-635]

    -pods = self.kubernetes_obj.get_namespaced_workloads(kind='Pod', namespace=namespace)
    -if pods is None:
    -    return []
    +pods = self.kubernetes_obj.get_namespaced_workloads(kind='Pod', namespace=namespace) or []
    • Apply this suggestion
    Suggestion importance[1-10]: 4

    Why: While the suggestion offers a more concise way to handle None values, the existing code already handles this case correctly. The improvement is mainly syntactic and offers minimal functional benefit.

    4

    Copy link

    Failed to generate code suggestions for PR

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant