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

ci: fix test failures caused by unstable harvester cluster #2144

Merged
merged 1 commit into from
Oct 21, 2024

Conversation

yangchiu
Copy link
Member

@yangchiu yangchiu commented Oct 18, 2024

Which issue(s) this PR fixes:

Issue longhorn/longhorn#9670

What this PR does / why we need it:

fix test failures caused by unstable harvester cluster

Special notes for your reviewer:

Additional documentation or context

Summary by CodeRabbit

  • New Features

    • Enhanced VM management with retry logic for starting and stopping virtual machines, improving resilience against transient failures.
    • Improved terraform_setup.sh script to wait for Kubernetes nodes to reach a "Ready" state before proceeding, ensuring smoother deployments.
  • Bug Fixes

    • Streamlined output handling for Terraform commands, ensuring accurate retrieval of Kubernetes configuration and public IP mappings.

@yangchiu yangchiu self-assigned this Oct 18, 2024
@yangchiu yangchiu requested a review from a team as a code owner October 18, 2024 07:02
Copy link

coderabbitai bot commented Oct 18, 2024

Walkthrough

The changes in this pull request enhance the error handling and resilience of the VM management process in the Harvester class. Specifically, retry logic has been added to the power_off_node and power_on_node methods, allowing multiple attempts to stop or start a VM while logging each attempt and any exceptions encountered. Additionally, the terraform_setup.sh script has been updated to include a loop that waits for Kubernetes nodes to reach a "Ready" state before proceeding, improving the script's robustness during cluster deployments.

Changes

File Change Summary
e2e/libs/host/harvester.py Added retry logic for power_off_node and power_on_node methods to handle transient failures.
pipelines/utilities/terraform_setup.sh Implemented a loop to wait for nodes to reach "Ready" state and streamlined output handling for Terraform commands.

Assessment against linked issues

Objective Addressed Explanation
Enhance error handling in VM management to prevent failures during operations (#9670)
Ensure stability in test execution by waiting for nodes to be ready before proceeding (#9670)

Poem

In fields of code, a rabbit hops,
With retries in place, no need for stops.
VMs now power on with grace,
Waiting for nodes in their rightful place.
Oh, what joy, in scripts we trust,
For every task, we adapt and adjust! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

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: 6

🧹 Outside diff range and nitpick comments (2)
e2e/libs/host/harvester.py (2)

74-80: Ensure robust handling of VM status checks

When checking the VM's status, consider verifying that the response JSON contains the expected keys to prevent potential KeyError exceptions if the response structure changes.

Apply this diff to safely access the JSON data:

                 resp = requests.get(url, cookies=self.cookies, verify=False)
-                if "Stopped" in resp.json()['metadata']['fields']:
+                resp_json = resp.json()
+                metadata = resp_json.get('metadata', {})
+                fields = metadata.get('fields', [])
+                if "Stopped" in fields:
                     stopped = True
                     break

102-108: Ensure robust handling of VM status checks

When checking the VM's status, consider verifying that the response JSON contains the expected keys to prevent potential KeyError exceptions if the response structure changes.

Apply this diff to safely access the JSON data:

                 resp = requests.get(url, cookies=self.cookies, verify=False)
-                if "Running" in resp.json()['metadata']['fields']:
+                resp_json = resp.json()
+                metadata = resp_json.get('metadata', {})
+                fields = metadata.get('fields', [])
+                if "Running" in fields:
                     started = True
                     break
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 460c7b0 and c84dd0a.

📒 Files selected for processing (2)
  • e2e/libs/host/harvester.py (1 hunks)
  • pipelines/utilities/terraform_setup.sh (1 hunks)
🧰 Additional context used

Comment on lines +35 to +38
until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq '.[] | select(.type == "Ready").status' | grep -ci true)" -eq 4 ]; do
echo "waiting for harvester cluster nodes to be running"
sleep 2
done
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure the script correctly handles any errors from kubectl commands

If the kubectl command fails (e.g., due to configuration issues or cluster unavailability), the script may produce misleading output or errors.

Add error handling to catch failures of the kubectl command:

 until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes --no-headers 2>/dev/null | grep -cw 'Ready')" -eq $EXPECTED_NODE_COUNT ]; do
   echo "waiting for harvester cluster nodes to be running"
+  if ! KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes >/dev/null 2>&1; then
+    echo "kubectl command failed. Please check your Kubernetes configuration."
+    exit 1
+  fi
   sleep $WAIT_INTERVAL
   TIME_WAITED=$((TIME_WAITED + WAIT_INTERVAL))
   if [ $TIME_WAITED -ge $MAX_WAIT_TIME ]; then
     echo "Timeout reached while waiting for nodes to be ready"
     exit 1
   fi
 done

This addition:

  • Redirects stderr to /dev/null in the condition check to prevent error messages from breaking the loop logic.
  • Checks the success of the kubectl get nodes command separately.
  • Exits with an error message if kubectl fails.

Committable suggestion was skipped due to low confidence.


🛠️ Refactor suggestion

Parameterize the expected number of nodes and add a timeout to prevent indefinite waiting

The until loop is hardcoded to wait for 4 nodes to be ready. If the cluster size changes, this script will need to be updated manually each time. Additionally, without a timeout, the script could hang indefinitely if the nodes fail to become ready.

Consider introducing variables for the expected node count and a maximum wait time. This makes the script more flexible and prevents indefinite execution.

Apply the following changes:

+EXPECTED_NODE_COUNT=4
+MAX_WAIT_TIME=300  # in seconds
+WAIT_INTERVAL=2    # in seconds
+TIME_WAITED=0

 until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq '.[] | select(.type  == "Ready").status' | grep -ci true)" -eq $EXPECTED_NODE_COUNT ]; do
   echo "waiting for harvester cluster nodes to be running"
   sleep $WAIT_INTERVAL
+  TIME_WAITED=$((TIME_WAITED + WAIT_INTERVAL))
+  if [ $TIME_WAITED -ge $MAX_WAIT_TIME ]; then
+    echo "Timeout reached while waiting for nodes to be ready"
+    exit 1
+  fi
 done

This modification:

  • Introduces EXPECTED_NODE_COUNT to specify how many nodes should be ready.
  • Adds a timeout mechanism with MAX_WAIT_TIME to prevent infinite loops.
  • Uses TIME_WAITED to track the total time spent waiting.
  • Exits the script with an error if the timeout is reached.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq '.[] | select(.type == "Ready").status' | grep -ci true)" -eq 4 ]; do
echo "waiting for harvester cluster nodes to be running"
sleep 2
done
EXPECTED_NODE_COUNT=4
MAX_WAIT_TIME=300 # in seconds
WAIT_INTERVAL=2 # in seconds
TIME_WAITED=0
until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq '.[] | select(.type == "Ready").status' | grep -ci true)" -eq $EXPECTED_NODE_COUNT ]; do
echo "waiting for harvester cluster nodes to be running"
sleep $WAIT_INTERVAL
TIME_WAITED=$((TIME_WAITED + WAIT_INTERVAL))
if [ $TIME_WAITED -ge $MAX_WAIT_TIME ]; then
echo "Timeout reached while waiting for nodes to be ready"
exit 1
fi
done

🛠️ Refactor suggestion

Simplify the node readiness check for better readability

The current command to check node readiness is complex and could be simplified for clarity.

You can achieve the same result with a more straightforward command:

-until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes -o jsonpath='{.items[*].status.conditions}' | jq '.[] | select(.type  == "Ready").status' | grep -ci true)" -eq $EXPECTED_NODE_COUNT ]; do
+until [ "$(KUBECONFIG=${PWD}/test_framework/kube_config.yaml kubectl get nodes --no-headers | grep -cw 'Ready')" -eq $EXPECTED_NODE_COUNT ]; do
   echo "waiting for harvester cluster nodes to be running"
   sleep $WAIT_INTERVAL
   TIME_WAITED=$((TIME_WAITED + WAIT_INTERVAL))
   if [ $TIME_WAITED -ge $MAX_WAIT_TIME ]; then
     echo "Timeout reached while waiting for nodes to be ready"
     exit 1
   fi
 done

This change:

  • Uses kubectl get nodes --no-headers for a cleaner output.
  • Utilizes grep -cw 'Ready' to count lines where the word "Ready" appears exactly once, ensuring accurate counting.
  • Improves readability and maintainability of the script.

Committable suggestion was skipped due to low confidence.

Comment on lines +60 to +68
for i in range(self.retry_count):
logging(f"Trying to stop vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=stop", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
assert resp.status_code == 204, f"Failed to stop vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
break
except Exception as e:
logging(f"Stopping vm failed with error {e}")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicate retry logic into a helper method

The retry logic in the power_off_node and power_on_node methods is very similar. Consider refactoring this code into a separate helper method to reduce duplication and improve maintainability.

Here's a suggested approach:

def _retry_vm_action(self, action, vm_id):
    url = f"{self.url}/{vm_id}"
    for i in range(self.retry_count):
        logging(f"Trying to {action} vm {vm_id} ... ({i})")
        try:
            resp = requests.post(f"{url}?action={action}", cookies=self.cookies, verify=False)
            logging(f"resp = {resp}")
            if resp.status_code != 204:
                logging(f"Failed to {action} vm {vm_id}. Response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}")
                continue
            break
        except Exception as e:
            logging(f"{action.capitalize()}ing vm failed with error {e}")

def power_off_node(self, node_name):
    vm_id = self.mapping[node_name]
    self._retry_vm_action('stop', vm_id)
    # Existing code for checking VM stopped status

def power_on_node(self, node_name):
    vm_id = self.mapping[node_name]
    self._retry_vm_action('start', vm_id)
    # Existing code for checking VM started status

Also applies to: 88-96


⚠️ Potential issue

Replace assert statements with explicit error handling

Using assert statements for control flow is not recommended in production code because assertions can be disabled with optimization flags (-O, -OO). Instead, consider checking the response status code explicitly and handling errors accordingly.

Apply this diff to replace the assertion:

                 resp = requests.post(f"{url}?action=stop", cookies=self.cookies, verify=False)
                 logging(f"resp = {resp}")
-                assert resp.status_code == 204, f"Failed to stop vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
+                if resp.status_code != 204:
+                    logging(f"Failed to stop vm {vm_id}. Response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}")
+                    continue
                 break
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i in range(self.retry_count):
logging(f"Trying to stop vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=stop", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
assert resp.status_code == 204, f"Failed to stop vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
break
except Exception as e:
logging(f"Stopping vm failed with error {e}")
for i in range(self.retry_count):
logging(f"Trying to stop vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=stop", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
if resp.status_code != 204:
logging(f"Failed to stop vm {vm_id}. Response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}")
continue
break
except Exception as e:
logging(f"Stopping vm failed with error {e}")

Comment on lines +88 to +96
for i in range(self.retry_count):
logging(f"Trying to start vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=start", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
assert resp.status_code == 204, f"Failed to start vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
break
except Exception as e:
logging(f"Starting vm failed with error {e}")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace assert statements with explicit error handling

Using assert statements for control flow is not recommended in production code because assertions can be disabled with optimization flags (-O, -OO). Instead, consider checking the response status code explicitly and handling errors accordingly.

Apply this diff to replace the assertion:

                 resp = requests.post(f"{url}?action=start", cookies=self.cookies, verify=False)
                 logging(f"resp = {resp}")
-                assert resp.status_code == 204, f"Failed to start vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
+                if resp.status_code != 204:
+                    logging(f"Failed to start vm {vm_id}. Response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}")
+                    continue
                 break
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i in range(self.retry_count):
logging(f"Trying to start vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=start", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
assert resp.status_code == 204, f"Failed to start vm {vm_id} response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}"
break
except Exception as e:
logging(f"Starting vm failed with error {e}")
for i in range(self.retry_count):
logging(f"Trying to start vm {vm_id} ... ({i})")
try:
resp = requests.post(f"{url}?action=start", cookies=self.cookies, verify=False)
logging(f"resp = {resp}")
if resp.status_code != 204:
logging(f"Failed to start vm {vm_id}. Response: {resp.status_code} {resp.reason}, request: {resp.request.url} {resp.request.headers}")
continue
break
except Exception as e:
logging(f"Starting vm failed with error {e}")

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