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

[14.0][IMP] cetmix_tower_server: On delete flight plan #189

Merged

Conversation

ivs-cetmix
Copy link
Contributor

@ivs-cetmix ivs-cetmix commented Jan 20, 2025

Execute flight plan when server is deleted.

Set "Deleting" status when flight plan is started. Delete server if plan is successful.
Set "Delete Error" status when flight plan fails.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added ability to define a deletion plan for servers.
    • Introduced new server deletion statuses: "deleting" and "delete_error".
  • Improvements

    • Enhanced server management with a more controlled deletion process.
    • Implemented a flight plan mechanism for server deletion.
    • Added structured error handling for server deletion scenarios.
  • UI Changes

    • Updated server form view to include new deletion-related fields.
    • Added conditional visibility for the server template field.

These changes provide more robust server management capabilities with improved deletion workflows and error tracking.

Copy link

coderabbitai bot commented Jan 20, 2025

Walkthrough

The pull request introduces an enhanced server deletion mechanism in the Cetmix Tower Server system. The changes focus on implementing a flight plan-based approach to server deletion, adding new fields and methods to the CxTowerServer and CxTowerPlanLog classes. Modifications include a new plan_delete_id field, updated status options, and test cases to validate the deletion process. The changes provide more controlled and logged server deletion with success and error handling scenarios.

Changes

File Change Summary
cetmix_tower_server/models/cx_tower_plan_log.py - Added _plan_finished() method
- Enhanced finish() method with server deletion logic
cetmix_tower_server/models/cx_tower_server.py - Added plan_delete_id field with Many2one relationship
- Updated server_template_id to readonly
- Added new server statuses: "deleting" and "delete_error"
- Modified unlink method to handle deletion plans
cetmix_tower_server/tests/test_server.py - Added test_server_delete_plan_success and test_server_delete_plan_error methods
- Implemented command_delete_server and plan_delete_server for server deletion
cetmix_tower_server/views/cx_tower_server_view.xml - Added new group with "delete" extra attribute
- Added server_template_id and plan_delete_id fields to form view

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 886f469 and 8652b65.

📒 Files selected for processing (4)
  • cetmix_tower_server/models/cx_tower_plan_log.py (1 hunks)
  • cetmix_tower_server/models/cx_tower_server.py (3 hunks)
  • cetmix_tower_server/tests/test_server.py (2 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (1 hunks)
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/models/cx_tower_server.py (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#189
File: cetmix_tower_server/models/cx_tower_server.py:450-486
Timestamp: 2025-01-20T20:01:46.405Z
Learning: In the cetmix_tower_server module, exceptions during Flight Plan execution are handled at the Flight Plan level itself, making additional exception handling in calling methods like `unlink()` redundant.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (12)
cetmix_tower_server/models/cx_tower_plan_log.py (3)

159-160: LGTM! Well-placed hook method.

The hook method is strategically placed to allow extensions without modifying core logic.


163-173: LGTM! Clean implementation of server deletion logic.

The code properly handles both success and failure scenarios:

  • Verifies that this is indeed a deletion plan
  • On success (status=0), deletes the server with proper context
  • On failure, sets appropriate error status

Line range hint 174-178: LGTM! Well-documented hook method.

The hook method follows Odoo's conventions:

  • Clear docstring explaining the purpose
  • Default implementation returns True
  • Proper naming indicating it's a hook
cetmix_tower_server/tests/test_server.py (3)

56-86: LGTM! Well-structured test setup.

The setup creates isolated test fixtures:

  • Command using Python code for deterministic testing
  • Plan configured with the command
  • Clear separation of concerns

472-491: LGTM! Comprehensive success test.

The test follows best practices:

  • Follows AAA pattern (Arrange-Act-Assert)
  • Verifies both primary effect (server deletion) and side effect (partner creation)
  • Clear test name and docstring

493-519: LGTM! Thorough error test.

The test effectively validates error handling:

  • Simulates failure by modifying command
  • Verifies server is preserved
  • Checks correct error status is set
cetmix_tower_server/views/cx_tower_server_view.xml (1)

261-267: LGTM! Well-organized form view changes.

The changes follow Odoo's view patterns:

  • Logical grouping with semantic extra="delete" attribute
  • Appropriate invisibility condition on server_template_id
  • Clear placement of fields
cetmix_tower_server/models/cx_tower_server.py (5)

356-357: LGTM! Good security practice.

Making server_template_id readonly prevents accidental template changes after server creation.


360-366: LGTM! Well-defined deletion plan field.

The field is properly configured:

  • Restricted to manager group for security
  • Clear help text explaining the purpose
  • Appropriate Many2one relation

381-382: LGTM! Clear status definitions.

The new statuses are well-defined:

  • "deleting" for in-progress deletion
  • "delete_error" for failed deletion
  • Consistent with existing status pattern

450-485: LGTM! Robust unlink implementation.

The unlink method properly handles all scenarios:

  • Skips plan for forced deletion or already deleting servers
  • Executes deletion plan with proper logging
  • Updates server status based on plan result

487-495: LGTM! Clean helper method.

The _is_being_deleted method:

  • Has clear documentation
  • Follows single responsibility principle
  • Uses ensure_one for safety
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 3

🧹 Nitpick comments (3)
cetmix_tower_server/models/cx_tower_server.py (1)

487-495: Simplify the return statement in _is_being_deleted method.

The return statement can be simplified since self.status == "deleting" already returns a boolean value.

Apply this diff to simplify the method:

-        return self.status and self.status == "deleting"
+        return self.status == "deleting"
cetmix_tower_server/views/cx_tower_server_view.xml (2)

261-267: Consider improving field placement and attributes for better UX.

The new deletion-related fields could benefit from the following improvements:

  1. The group name "delete" could be more descriptive, e.g., "Deletion Settings"
  2. The plan_delete_id field lacks domain/context attributes to filter relevant plans
  3. Consider adding tooltips to explain the purpose of these fields

Apply this diff to enhance the field definitions:

-                                <group extra="delete">
+                                <group name="deletion_settings" string="Deletion Settings">
                                     <field
                                         name="server_template_id"
                                         attrs="{'invisible': [('server_template_id', '=', False)]}"
+                                        readonly="1"
                                     />
-                                    <field name="plan_delete_id" />
+                                    <field 
+                                        name="plan_delete_id"
+                                        domain="[('state', '=', 'confirmed')]"
+                                        context="{'default_server_id': active_id}"
+                                        help="Select a flight plan to execute when deleting this server"
+                                    />
                                 </group>

261-267: Consider moving deletion settings to a separate page.

Given the critical nature of server deletion operations, consider moving these settings to a dedicated notebook page. This would:

  1. Make the deletion settings more prominent
  2. Separate critical operations from general settings
  3. Allow for future expansion of deletion-related features

Apply this diff to move the settings to a new page:

-                                <group extra="delete">
-                                    <field
-                                        name="server_template_id"
-                                        attrs="{'invisible': [('server_template_id', '=', False)]}"
-                                    />
-                                    <field name="plan_delete_id" />
-                                </group>
                                <field name="note" placeholder="Put your notes here" />
                            </group>
                        </page>
+                        <page name="deletion" string="Deletion Settings" groups="cetmix_tower_server.group_manager">
+                            <group>
+                                <group name="deletion_settings" string="Flight Plan">
+                                    <field
+                                        name="server_template_id"
+                                        attrs="{'invisible': [('server_template_id', '=', False)]}"
+                                        readonly="1"
+                                    />
+                                    <field 
+                                        name="plan_delete_id"
+                                        domain="[('state', '=', 'confirmed')]"
+                                        context="{'default_server_id': active_id}"
+                                        help="Select a flight plan to execute when deleting this server"
+                                    />
+                                </group>
+                            </group>
+                        </page>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c3f48a and 908a4e7.

📒 Files selected for processing (4)
  • cetmix_tower_server/models/cx_tower_plan_log.py (1 hunks)
  • cetmix_tower_server/models/cx_tower_server.py (3 hunks)
  • cetmix_tower_server/tests/test_server.py (2 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (6)
cetmix_tower_server/models/cx_tower_server.py (3)

356-358: Setting server_template_id as read-only is appropriate.

Marking server_template_id with readonly=True ensures that the server template remains constant after creation, which is suitable if modifications are not allowed post-creation.


361-366: New field plan_delete_id added correctly.

The addition of the plan_delete_id field properly links a server to its deletion flight plan, enhancing the server deletion workflow.


381-382: Status options updated appropriately.

Adding "deleting" and "delete_error" statuses improves the tracking of server states during the deletion process.

cetmix_tower_server/models/cx_tower_plan_log.py (1)

159-162: Hook method _plan_finished added appropriately.

The addition of the _plan_finished method provides a customizable hook for actions upon flight plan completion.

cetmix_tower_server/tests/test_server.py (1)

472-492: Test methods added correctly for server deletion scenarios.

The test cases test_server_delete_plan_success and test_server_delete_plan_error effectively verify the server deletion process under success and error conditions.

cetmix_tower_server/views/cx_tower_server_view.xml (1)

261-267: Verify field definitions in the model.

The new fields should have corresponding field definitions in the model class.

Let's verify the field definitions in the model:

✅ Verification successful

Field definitions verified successfully

Both server_template_id and plan_delete_id are properly defined in the model class with appropriate field types and attributes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check field definitions in the model class
# Expected: Find field definitions for server_template_id and plan_delete_id

# Search for field definitions
rg "server_template_id|plan_delete_id" -A 3 -g "*.py"

Length of output: 22878

cetmix_tower_server/models/cx_tower_server.py Show resolved Hide resolved
cetmix_tower_server/models/cx_tower_plan_log.py Outdated Show resolved Hide resolved
cetmix_tower_server/tests/test_server.py Outdated Show resolved Hide resolved
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 (2)
cetmix_tower_server/models/cx_tower_plan_log.py (2)

163-174: Consider adding transaction handling for server deletion.

While the deletion logic is correct, consider wrapping the server deletion in a try-except block to handle potential database constraints or cascading deletion issues. This would ensure the status is properly set to "delete_error" if the unlink operation fails.

         if plan_status == 0:
             # And finally delete the server
-            self.with_context(server_force_delete=True).server_id.unlink()
+            try:
+                self.with_context(server_force_delete=True).server_id.unlink()
+            except Exception as e:
+                _logger.error("Server deletion failed: %s", str(e))
+                self.server_id.status = "delete_error"
+                return

Line range hint 176-180: Enhance the hook method's documentation.

The docstring could be more detailed to help implementers:

  1. Explain when exactly this hook is triggered (after plan status update but before server deletion).
  2. Document the available context (self.plan_status, self.server_id, etc.).
  3. Remove the unnecessary return True as it's not used.
     def _plan_finished(self):
-        """Triggered when flightplan in finished
-        Inherit to implement your own hooks
-        """
-        return True
+        """Hook method triggered after a flight plan is finished.
+
+        This method is called after updating the plan's status and finish time,
+        but before any server deletion (if applicable). Override this method
+        to implement custom logic that should run when a flight plan completes.
+
+        Available context:
+            - self.plan_status: The final status code of the plan
+            - self.server_id: The server record
+            - self.finish_date: When the plan finished
+        """
+        pass
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 908a4e7 and 886f469.

📒 Files selected for processing (2)
  • cetmix_tower_server/models/cx_tower_plan_log.py (1 hunks)
  • cetmix_tower_server/tests/test_server.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cetmix_tower_server/tests/test_server.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (1)
cetmix_tower_server/models/cx_tower_plan_log.py (1)

159-160: LGTM! Good addition of the extension point.

The hook is correctly placed after updating the plan status, following Odoo's conventions for extensibility.

Copy link
Contributor

@GabbasovDinar GabbasovDinar 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
Contributor

@Aldeigja Aldeigja left a comment

Choose a reason for hiding this comment

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

Functional LGTM

Execute flight plan when server is deleted.

Set "Deleting" status when flight plan is started.
Delete server if plan is successful.
Set "Delete Error" status when flight plan fails.
@ivs-cetmix ivs-cetmix force-pushed the 14.0-t4252-cetmix_tower_server-on_delete_flight_plan branch from 886f469 to 8652b65 Compare January 22, 2025 19:41
@ivs-cetmix
Copy link
Contributor Author

/ocabot merge nobump

@CetmixGitDrone
Copy link

Hey, thanks for contributing! Proceeding to merge this for you.
Prepared branch 14.0-dev-ocabot-merge-pr-189-by-ivs-cetmix-bump-nobump, awaiting test results.

@CetmixGitDrone CetmixGitDrone merged commit 233708a into 14.0-dev Jan 22, 2025
7 checks passed
@CetmixGitDrone
Copy link

Congratulations, your PR was merged at 233708a. Thanks a lot for contributing to cetmix. ❤️

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.

4 participants