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

add migration for dv #455

Merged
merged 1 commit into from
Oct 24, 2024
Merged

Conversation

klinch0
Copy link
Contributor

@klinch0 klinch0 commented Oct 24, 2024

Summary by CodeRabbit

  • New Features

    • Updated versioning logic to support migration from version 5 to version 6.
    • Introduced a migration script for managing Persistent Volume Claims (PVCs) and updating configurations.
  • Bug Fixes

    • Ensured error handling and waiting mechanisms for Kubernetes resources are preserved during migrations.

@klinch0 klinch0 requested a review from kvaps as a code owner October 24, 2024 12:34
@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Oct 24, 2024
Copy link
Contributor

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes involve updating the versioning logic in the installer.sh script from version 5 to version 6. This update impacts the migration process, where the script checks the current version and executes necessary migration scripts to transition to the new version. Additionally, a new migration script has been introduced to handle the migration of Persistent Volume Claims (PVCs) for the Kamaji project, which includes updating configurations and applying labels.

Changes

File Change Summary
scripts/installer.sh Updated VERSION from 5 to 6, modifying the migration logic to check and apply migrations accordingly.
scripts/migrations/5 Introduced a new migration script for version 5 to 6, handling PVCs, updating ConfigMaps, and applying labels.

Sequence Diagram(s)

sequenceDiagram
    participant Installer
    participant MigrationScript
    participant Kubernetes

    Installer->>MigrationScript: Check current version
    MigrationScript->>Kubernetes: Retrieve PVCs and Secrets
    Kubernetes-->>MigrationScript: Provide PVCs and Secrets
    MigrationScript->>MigrationScript: Apply labels to PVCs and DVs
    MigrationScript->>Kubernetes: Create/Update ConfigMap
    Kubernetes-->>MigrationScript: Confirm ConfigMap update
    MigrationScript->>Installer: Migration complete
Loading

🐇 "In the garden, changes bloom,
A version rise, dispelling gloom.
From five to six, we hop along,
With PVCs and ConfigMaps, we sing our song!
Labels applied, the clusters cheer,
In our cozy home, there's nothing to fear!" 🌼


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
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (2)
scripts/installer.sh (2)

Line range hint 9-20: Consider enhancing migration process safety.

The current migration implementation could benefit from additional safety measures:

  1. No atomic transaction handling - if a migration fails mid-way, the system could be left in an inconsistent state
  2. Missing rollback mechanism
  3. Limited logging for debugging purposes

Consider implementing these improvements:

  1. Add a backup mechanism before running migrations
  2. Implement rollback functionality
  3. Enhanced logging with timestamps and status details
  4. Add a dry-run mode for testing migrations

Would you like me to provide a detailed implementation for these improvements?


Line range hint 14-19: Improve error handling in migration loop.

The current migration loop lacks robust error handling:

  1. No timeout protection against infinite loops
  2. Missing explicit error handling for kubectl commands
  3. No validation of migration success

Consider applying this improvement:

  current_version=$(kubectl get configmap -n cozy-system cozystack-version -o jsonpath='{.data.version}') || true
+ start_time=$(date +%s)
  until [ "$current_version" = "$VERSION" ]; do
+   # Add timeout after 30 minutes
+   current_time=$(date +%s)
+   if [ $((current_time - start_time)) -gt 1800 ]; then
+     echo "Error: Migration timeout after 30 minutes"
+     exit 1
+   fi
    echo "run migration: $current_version --> $VERSION"
-   scripts/migrations/$current_version
+   if ! scripts/migrations/$current_version; then
+     echo "Error: Migration $current_version failed"
+     exit 1
+   fi
    current_version=$(kubectl get configmap -n cozy-system cozystack-version -o jsonpath='{.data.version}')
+   if [ -z "$current_version" ]; then
+     echo "Error: Failed to get current version after migration"
+     exit 1
+   fi
  done
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b894930 and 42b297a.

📒 Files selected for processing (2)
  • scripts/installer.sh (1 hunks)
  • scripts/migrations/5 (1 hunks)
🔇 Additional comments (2)
scripts/migrations/5 (2)

1-3: LGTM! Clear script purpose declaration.

The shebang and comment clearly indicate this is a migration script from version 5 to 6.


1-15: Verify the migration's idempotency.

The script should be idempotent to handle potential reruns safely.

Let's verify the current version and existing labels:

✅ Verification successful

Let me analyze the migration script for idempotency without relying on kubectl commands, as they're not available in the sandbox environment.

Looking at the script's operations:

  1. The first part (kubectl get secret ... | while read ...) applies labels to PVCs and DVs:

    • Uses --overwrite flag for labels, making it safe to rerun
    • Temporary files are properly cleaned up with rm -f
  2. The second part creates/updates the version configmap:

    • Uses kubectl apply -f- which is idempotent by design
    • The version is set to a fixed value of 6

The migration script is safely idempotent

The script is idempotent because:

  • Label operations use --overwrite flag which safely updates existing labels
  • ConfigMap creation uses kubectl apply which is idempotent by design
  • Temporary files are properly cleaned up
  • No destructive operations are performed that could cause issues on reruns
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check current version and existing labels to ensure idempotent migration

# Test 1: Check if version 6 already exists
echo "Checking current version..."
kubectl get configmap -n cozy-system cozystack-version -o jsonpath='{.data.version}'

# Test 2: Check for existing cluster labels
echo -e "\nChecking existing cluster labels..."
kubectl get pvc,dv -A -l 'cluster.x-k8s.io/cluster-name' -o jsonpath='{range .items[*]}{.kind}/{.metadata.name}: {.metadata.labels.cluster\.x-k8s\.io/cluster-name}{"\n"}{end}'

Length of output: 565

rm -f "$config"
done

kubectl create configmap -n cozy-system cozystack-version --from-literal=version=6 --dry-run=client -o yaml | kubectl apply -f-
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for version update.

The version update command should verify success.

Apply this improvement:

-kubectl create configmap -n cozy-system cozystack-version --from-literal=version=6 --dry-run=client -o yaml | kubectl apply -f-
+if ! kubectl create configmap -n cozy-system cozystack-version --from-literal=version=6 --dry-run=client -o yaml | kubectl apply -f-; then
+  echo "Failed to update version ConfigMap"
+  exit 1
+fi
📝 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
kubectl create configmap -n cozy-system cozystack-version --from-literal=version=6 --dry-run=client -o yaml | kubectl apply -f-
if ! kubectl create configmap -n cozy-system cozystack-version --from-literal=version=6 --dry-run=client -o yaml | kubectl apply -f-; then
echo "Failed to update version ConfigMap"
exit 1
fi

Comment on lines +4 to +13
# Fix tenant-kubernetes PVCs
kubectl get secret -l kamaji.clastix.io/project=kamaji,kamaji.clastix.io/component=admin-kubeconfig -A --output=go-template='{{ range .items }}{{ printf "%s %s %s %s\n" .metadata.namespace .metadata.name (index .metadata.labels "kamaji.clastix.io/name") (index .data "super-admin.conf") }}{{ end }}' | while read NAMESPACE NAME CLUSTER CONFIGB64; do
config=$(mktemp)
echo "$CONFIGB64" | base64 -d > "$config"
kubectl get pv --kubeconfig="$config" --output=go-template='{{ range .items }}{{ printf "%s\n" .metadata.name }}{{ end }}' | while read PVC; do
(set -x; kubectl label pvc --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
(set -x; kubectl label dv --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
done
rm -f "$config"
done
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and safety measures.

While the core logic is correct, the script could benefit from additional error handling and safety measures:

  1. Missing error handling for kubectl commands
  2. No validation of base64 decoded content
  3. Temporary file could persist if script fails between creation and cleanup

Consider applying these improvements:

 #!/bin/sh
+set -euo pipefail
+
+cleanup() {
+    [ -f "$config" ] && rm -f "$config"
+}
+trap cleanup EXIT
+
 # Migration 5 --> 6
 
 # Fix tenant-kubernetes PVCs
 kubectl get secret -l kamaji.clastix.io/project=kamaji,kamaji.clastix.io/component=admin-kubeconfig -A --output=go-template='{{ range .items }}{{ printf "%s %s %s %s\n" .metadata.namespace .metadata.name (index .metadata.labels "kamaji.clastix.io/name") (index .data "super-admin.conf") }}{{ end }}' | while read NAMESPACE NAME CLUSTER CONFIGB64; do
+  [ -z "$NAMESPACE" ] || [ -z "$CLUSTER" ] || [ -z "$CONFIGB64" ] && echo "Missing required values" && exit 1
   config=$(mktemp)
-  echo "$CONFIGB64" | base64 -d > "$config"
+  if ! echo "$CONFIGB64" | base64 -d > "$config"; then
+    echo "Failed to decode kubeconfig"
+    exit 1
+  fi
+  if ! kubectl --kubeconfig="$config" cluster-info > /dev/null 2>&1; then
+    echo "Invalid kubeconfig"
+    exit 1
+  fi
   kubectl get pv --kubeconfig="$config" --output=go-template='{{ range .items }}{{ printf "%s\n" .metadata.name }}{{ end }}' | while read PVC; do
-    (set -x; kubectl label pvc --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
-    (set -x; kubectl label dv --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
+    if ! kubectl label pvc --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER"; then
+      echo "Failed to label PVC $PVC"
+      exit 1
+    fi
+    if ! kubectl label dv --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER"; then
+      echo "Failed to label DV $PVC"
+      exit 1
+    fi
   done
-  rm -f "$config"
 done
📝 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
# Fix tenant-kubernetes PVCs
kubectl get secret -l kamaji.clastix.io/project=kamaji,kamaji.clastix.io/component=admin-kubeconfig -A --output=go-template='{{ range .items }}{{ printf "%s %s %s %s\n" .metadata.namespace .metadata.name (index .metadata.labels "kamaji.clastix.io/name") (index .data "super-admin.conf") }}{{ end }}' | while read NAMESPACE NAME CLUSTER CONFIGB64; do
config=$(mktemp)
echo "$CONFIGB64" | base64 -d > "$config"
kubectl get pv --kubeconfig="$config" --output=go-template='{{ range .items }}{{ printf "%s\n" .metadata.name }}{{ end }}' | while read PVC; do
(set -x; kubectl label pvc --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
(set -x; kubectl label dv --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER")
done
rm -f "$config"
done
#!/bin/sh
set -euo pipefail
cleanup() {
[ -f "$config" ] && rm -f "$config"
}
trap cleanup EXIT
# Migration 5 --> 6
# Fix tenant-kubernetes PVCs
kubectl get secret -l kamaji.clastix.io/project=kamaji,kamaji.clastix.io/component=admin-kubeconfig -A --output=go-template='{{ range .items }}{{ printf "%s %s %s %s\n" .metadata.namespace .metadata.name (index .metadata.labels "kamaji.clastix.io/name") (index .data "super-admin.conf") }}{{ end }}' | while read NAMESPACE NAME CLUSTER CONFIGB64; do
[ -z "$NAMESPACE" ] || [ -z "$CLUSTER" ] || [ -z "$CONFIGB64" ] && echo "Missing required values" && exit 1
config=$(mktemp)
if ! echo "$CONFIGB64" | base64 -d > "$config"; then
echo "Failed to decode kubeconfig"
exit 1
fi
if ! kubectl --kubeconfig="$config" cluster-info > /dev/null 2>&1; then
echo "Invalid kubeconfig"
exit 1
fi
kubectl get pv --kubeconfig="$config" --output=go-template='{{ range .items }}{{ printf "%s\n" .metadata.name }}{{ end }}' | while read PVC; do
if ! kubectl label pvc --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER"; then
echo "Failed to label PVC $PVC"
exit 1
fi
if ! kubectl label dv --overwrite -n "$NAMESPACE" "$PVC" "cluster.x-k8s.io/cluster-name=$CLUSTER"; then
echo "Failed to label DV $PVC"
exit 1
fi
done
done

@@ -3,7 +3,7 @@ set -o pipefail
set -e

BUNDLE=$(set -x; kubectl get configmap -n cozy-system cozystack -o 'go-template={{index .data "bundle-name"}}')
VERSION=5
VERSION=6
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Migration script 5 exists but is not executable

The migration script for version 5 exists at scripts/migrations/5 but lacks executable permissions (shown as -rw-r--r--), while all previous migration scripts (1-4) are properly executable. This will cause the migration process to fail since the installer script attempts to execute these files directly.

  • scripts/migrations/5 needs executable permissions to be set using chmod +x
🔗 Analysis chain

Verify migration script existence.

The version bump from 5 to 6 requires a corresponding migration script at scripts/migrations/5 to handle the transition.


Let me try to gather more information about the migration scripts in the repository to ensure we're looking at the correct path.


Let me check one more thing to specifically look for migration scripts in any numbered directories, as the installer.sh suggests they should exist with version numbers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration script exists and is executable
# Expected: File should exist and be executable

if [ -x "scripts/migrations/5" ]; then
    echo "Migration script exists and is executable"
    head -n 5 "scripts/migrations/5" # Show first few lines for context
else
    echo "ERROR: Missing or non-executable migration script"
    exit 1
fi

Length of output: 151


Script:

#!/bin/bash
# Search for migration scripts in the repository
echo "=== Looking for migration-related files ==="
fd -t f "migration" -x ls -l {}

echo -e "\n=== Searching for version-related content in installer.sh ==="
cat scripts/installer.sh

echo -e "\n=== Searching for migration-related patterns in the codebase ==="
rg -l "migration" --type sh

Length of output: 3695


Script:

#!/bin/bash
# Look for numbered migration scripts
echo "=== Looking for numbered migration scripts ==="
fd -t f "^[0-9]+$" scripts/migrations

echo "=== Checking migrations directory structure ==="
ls -la scripts/migrations 2>/dev/null || echo "migrations directory not found"

echo "=== Checking if migrations directory exists ==="
if [ -d "scripts/migrations" ]; then
    echo "Directory exists"
    tree scripts/migrations
else
    echo "Directory does not exist"
fi

Length of output: 1023

Copy link
Member

@kvaps kvaps left a comment

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Oct 24, 2024
@kvaps kvaps merged commit 0ae7db6 into aenix-io:main Oct 24, 2024
1 check passed
@kvaps
Copy link
Member

kvaps commented Oct 24, 2024

Merged, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lgtm This PR has been approved by a maintainer size:S This PR changes 10-29 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants