Coder Social home page Coder Social logo

cdot65 / pan-os-upgrade Goto Github PK

View Code? Open in Web Editor NEW
38.0 7.0 7.0 5.27 MB

An efficient tool to execute configuration backups, network state snapshots, system readiness checks, and operating system upgrades of Palo Alto Networks firewalls and Panorama appliances.

Home Page: https://cdot65.github.io/pan-os-upgrade/

License: Apache License 2.0

JavaScript 0.07% Python 99.61% Dockerfile 0.32%
networkautomation palo-alto-networks paloaltonetworks pan-os upgrades

pan-os-upgrade's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pan-os-upgrade's Issues

Fix Session Timeout Issue During Install Step in Upgrade Script

We have identified a bug in the upgrade script where a session timeout error can occur during the install step. Despite this error, the upgrade process continues on the remote device, but the script incorrectly reports a failure and halts execution.

Current Behavior:

During the upgrade process, if a session timeout occurs, the script outputs an error message and prematurely stops, as illustrated below:

πŸš€ katy-fw1: Attempting upgrade to version 10.1.4-h4 (Attempt 1 of 3).
Device 007054000242051 installing version: 10.1.4-h4
❌ katy-fw1: Upgrade error: Session timed out
πŸ›‘ katy-fw1: Critical error during upgrade. Halting script.

Expected Behavior:

The script should handle session timeouts more gracefully. Instead of halting the upgrade process, it should allow the upgrade to continue in the background and periodically check the progress through subsequent API calls for the job status.

Proposed Solution:

  • Implement a mechanism within the script to detect session timeouts and differentiate them from actual upgrade failures.
  • Upon detecting a session timeout, the script should log a warning instead of an error and continue to monitor the upgrade progress via API calls to the remote device.
  • Provide clear logging to inform the user that the upgrade is proceeding in the background and include instructions on how to manually check the upgrade status if needed.

This enhancement will improve the reliability and user experience of the upgrade script, ensuring that upgrades can proceed smoothly even in the face of transient network issues or session timeouts.

Steps to Reproduce:

  1. Initiate an upgrade using the script on a device with a known propensity for session timeouts.
  2. Observe the script behavior when a session timeout occurs during the install step.

Acceptance Criteria:

  • The script no longer halts on session timeouts during the upgrade install step.
  • Users are informed about the continuation of the upgrade in the background and how to check its progress.
  • The script successfully completes the upgrade process or provides a clear error message if the upgrade fails for reasons other than a session timeout.

Modify Script to Auto-Create 'logs' and 'assurance' Directories for PyPI Readiness

Issue Summary

In preparation for deploying our pan-os-upgrade package to PyPI, we need to remove the logs and assurance directories from the package structure. Instead, the script should be modified to auto-create these directories at runtime. This change is essential to ensure that our package adheres to Python packaging standards and functions correctly across different environments.

Detailed Description

Current State: The logs and assurance directories are currently included in the repository. This approach is not ideal for PyPI deployment, as these directories may not be correctly set up in the user environment post-installation.

Proposed Change: Modify the pan-os-upgrade script to check for the existence of these directories when it runs. If they do not exist, the script should create them.

Rationale: This change will make the package more portable and user-friendly, as it reduces manual setup requirements for users. It also ensures that the script can manage its own file system dependencies, which is a best practice for Python packages.

Related Issues

This change is part of the broader effort to prepare the pan-os-upgrade package for PyPI deployment. It complements the work being tracked in Issue #16 related to PyPI project preparation.

Implementation Considerations

  • Ensure that directory creation is handled in a cross-platform manner.
  • Include error handling to manage potential issues with directory creation, such as permissions errors.
  • Update the README or documentation to inform users about this behavior.

Request for Contributions

We welcome contributions to implement this change. This includes:

Code modifications to implement the directory creation logic.
Testing across different platforms to ensure the changes work as expected.
Documentation updates reflecting the new script behavior.

Firewall snapshot after upgrade not generated

Describe the bug
Firewall snapshot after upgrade not generated, and therefore the reports are not generated either (standalone firewall). The script returns after "LabFW1: Waiting for the device to become ready for the post upgrade snapshot.". This happens when using settings.yaml file.

I assume that the issue lies in code "upgrade.py" line 716 ->

# Load settings if the file exists
if settings_file_path.exists():

This seems to check if the settings file exists and whether snapshots are enabled or not. In this case when snapshots are enabled it skips the snapshots due to the snapshot and reporting part being included in the else statement (which is never reached due to constuction of the if/else statement).

To Reproduce
Steps to reproduce the behavior:

  1. Generate settings.yaml file
  2. Run the script (using: "pan-os-upgrade firewall")
  3. Post-upgrade snapshot not generated

Expected behavior
Post upgrade snapshots and reports to be generated.

Log output
LabFW1: Upgrade completed successfully
LabFW1: Rebooting the target device.
LabFW1: Retry attempt 1 due to error: URLError: reason: [Errno 110] Connection timed out
LabFW1: Retry attempt 2 due to error: URLError: reason: [Errno 111] Connection refused
LabFW1: Current device version: 11.0.1-h2
LabFW1: Device rebooted to the target version successfully.
LabFW1: Performing backup of configuration to local filesystem.
LabFW1: Waiting for the device to become ready for the post upgrade snapshot.
Script exits here.

Environment

  • Ubuntu 20.04
  • Python 3.11

Serial group upgrades via Panorama

User Story

User should be able to specify a Panorama IP address, username, and password, and then an arbitary filter for running a series of firewall upgrades.

Upgrades should run serially, that is, one after the other.

Example

pan-os-upgrade --ip-address 1.1.1.1 --username test --password test --filter 'serial=22222222222'

Enhancement Request: Support for Configuration Files to Override Default Settings

Summary

This issue proposes the addition of support for external configuration files to override default settings within the application. The ability to use configuration files would offer users more flexibility and control over the application's behavior without altering the codebase.

Current Behavior

Currently, the application relies on hard-coded default settings or requires parameters to be specified via the command line or environment variables. This approach can limit usability and flexibility, especially in complex deployments or when managing multiple instances of the application.

Desired Behavior

Introduce the capability to read from external configuration files (e.g., YAML, JSON, INI) that users can create and maintain separately. The application should prioritize these settings over the default ones, allowing for easy customization of behavior, features, and operational parameters.

Use Cases

Custom Configuration: Users can specify custom settings tailored to their specific use cases without modifying the application code.
Environment-Specific Settings: Enable different configurations for development, testing, and production environments, improving deployment flexibility.
Easier Management: Simplify the management of settings for instances running in different contexts or with varying requirements.

Potential Benefits

Enhanced Usability: Makes it easier for users to customize the application to their needs.
Increased Flexibility: Allows for more granular control over application behavior without the need for code changes.
Improved Scalability: Facilitates managing configurations for multiple instances or environments.
Suggested Implementation:

Determine the preferred formats for the configuration files (YAML, JSON, INI, etc.).
Implement a configuration management module to parse and apply settings from these files.
Define a clear hierarchy for settings precedence (e.g., command-line arguments > configuration file > defaults).
Provide documentation and examples on creating and using configuration files.

Request for Comments

Feedback is sought from the community on this proposal, including any concerns, alternative approaches, or additional features that should be considered. Contributions to the design and implementation are also welcome.

Semantic versioning

Code should support semantic versioning based on conventional commits to simplify the release cycle.

Upgrade Process Fails When Software Manager is Busy

Issue Summary

The perform_upgrade function in the pan-os-upgrade script encounters an error and exits when attempting to install a new PAN-OS version while the software manager is already in use.

Detailed Description

Behavior: When the script tries to upgrade the PAN-OS version using firewall.software.install, it fails if the software manager on the device is currently in use. The script then raises a PanDeviceError and exits.

Error Message:

PanDeviceError: Device [serial] attempt to install version [version] failed: ['Failed to install [version] with the following errors.\nThe software manager is currently in use. Please try again later.\nFailed to install version [version] type panos\n\n']

Expected Behavior: The script should handle this scenario gracefully by retrying the installation after a brief wait period.

Steps to Reproduce

Run the pan-os-upgrade script to upgrade a PAN-OS firewall.
If the software manager on the firewall is busy, observe the script failing with the mentioned error.

Suggested Fix

Improve the error handling in the perform_upgrade function to catch PanDeviceError and implement a retry mechanism. The script should wait for a configurable amount of time and then retry the upgrade process a few times before finally failing.

Impact

This bug impedes the ability of the script to reliably perform upgrades, especially in environments where the software manager might be frequently busy.

Request for Assistance

We are looking for contributions to:

  • Analyze and confirm the bug.
  • Propose and implement a solution to handle busy software manager scenarios.
  • Test the solution in different conditions to ensure reliability.

Enhancement: Ship Docker Container for `pan-os-upgrade` Script Execution

Title

Enhancement: Ship Docker Container for pan-os-upgrade Script Execution

Description

Feature Request
Introduce a Docker container to encapsulate the pan-os-upgrade script, ensuring a consistent execution environment across various systems.

Background:
The pan-os-upgrade script is currently run directly on user systems, which may lead to variability in execution due to differences in system configurations and dependencies. Shipping the script within a Docker container would abstract away these environmental differences, providing a consistent, isolated, and reproducible execution environment.

Proposed Solution:

  • Develop a Dockerfile to build an image containing the pan-os-upgrade script along with all necessary dependencies.
  • Provide detailed documentation on how to use the Docker container, including pulling the image, running the container, and passing necessary parameters to the script.
  • Optionally, set up a workflow to automatically build and push the Docker image to a container registry (like Docker Hub) upon new releases.

Benefits:

  • Consistency: Ensures that the script runs in a standardized environment, mitigating issues caused by system-specific configurations.
  • Ease of Use: Simplifies the setup process for users, as they would not need to install Python and other dependencies on their systems.
  • Portability: Allows the script to be easily run on any system that supports Docker, increasing its usability.

Additional Considerations:

  • Ensuring that the Docker container can connect to the necessary network resources to perform the upgrade tasks.
  • Addressing any potential security concerns with running the script within a container.

This enhancement would significantly improve the user experience and reliability of the pan-os-upgrade script by leveraging the benefits of containerization.

Upgrade Workflow Continues to Reboot Despite Failed Software Installation Attempts

Describe the bug
During the firewall upgrade process, if the software manager is busy and cannot install the target PAN-OS version, the script retries the installation up to three times with a 60-second delay between each attempt. If all attempts fail, the script proceeds to reboot the firewall without the new target version being successfully installed.

To Reproduce
Steps to reproduce the behavior:

  1. Initiate the upgrade process on a firewall where the software manager is expected to be busy or unable to install the target PAN-OS version.
  2. Observe the script attempting to install the target PAN-OS version three times, failing each time due to the software manager being busy.
  3. Notice that after the third failed attempt, the script proceeds to reboot the firewall without the successful installation of the target version.

Expected behavior
The expected behavior is for the script to halt the upgrade process and not proceed with the reboot if the target PAN-OS version cannot be installed after the specified number of retry attempts. The script should log an appropriate error message indicating the failure to install the target version and the decision not to proceed with the reboot.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS
  • Version: latest

Additional context
This issue may lead to unnecessary reboots of firewalls without completing the intended upgrade, potentially causing disruptions in network traffic and affecting production environments. A fix to ensure the script properly handles failed installation attempts before proceeding to the reboot phase is necessary to avoid unintended consequences.

Integrate Material for MkDocs for Documentation

Description

We are planning to enhance our documentation by integrating Material for MkDocs. This will involve setting up MkDocs with the Material theme, reorganizing our existing documentation into the MkDocs format, and ensuring that our documentation is easy to navigate and visually appealing.

Objectives

  • Add Material for MkDocs to our Poetry development dependencies.
  • Initialize MkDocs in the docs directory of the pan_os_upgrade library.
  • Configure mkdocs.yml to use the Material theme and set up basic site structure.
  • Transfer existing documentation from README and other markdown files into the MkDocs structure.
  • Organize the documentation into multiple markdown files for different sections.
  • Test the documentation site locally using mkdocs serve.
  • Build the static site using mkdocs build.
  • Set up version control for the new MkDocs files and directory structure.
  • Create a CI/CD pipeline for automatic deployment of the documentation site (consider using GitHub Actions for deployment to GitHub Pages or another hosting service).

Additional Notes

  • Ensure that the documentation style aligns with the project's branding and aesthetics.
  • Explore Material for MkDocs customization options for advanced styling and features.

Implement Post-Upgrade Snapshots and Configuration Backups with Diff Support

Enhancement Overview

This issue proposes an enhancement to the current upgrade workflow by incorporating an additional step to capture snapshots and configuration backups after an upgrade has completed. This will mirror the pre-upgrade assurance steps, utilizing the same mechanisms as those defined within the panos-upgrade-assurance suite.

Goals

  • Post-Upgrade State Capture: Automatically capture snapshots of the network state and configuration backups post-upgrade, allowing for a clear view of the system's state after changes have been applied.
  • Change Analysis: Implement a diff functionality to compare pre and post-upgrade snapshots, providing users with a detailed overview of what has changed within their network as a result of the upgrade. This aims to enhance transparency and confidence in the upgrade process by making it easy to audit changes.

Implementation Details

Utilize existing panos-upgrade-assurance library mechanisms to ensure consistency in how snapshots and backups are captured and stored.

Extend the library to support diff operations between pre and post-upgrade snapshots, ensuring changes are easily identifiable.
Store the post-upgrade snapshots and configurations in a structured manner, akin to the pre-upgrade data, ensuring easy access and analysis.

Value Proposition

This enhancement will significantly improve the upgrade process's robustness by offering a clear before-and-after state comparison. It will aid administrators in quickly identifying and addressing any unintended changes, thereby minimizing potential disruptions and enhancing the overall security and stability of the network infrastructure.

Request for Comments

Feedback on the proposed approach, suggestions for implementation strategies, or concerns about potential impacts on the upgrade workflow are highly welcome. Please share your insights or endorse the proposal to help prioritize this enhancement in our development roadmap.

pan-os-upgrade panorama Licensing Check/Software Download Check

Is your feature request related to a problem? Please describe.

This is not necessarily a problem. The script should tell us when there is a software download issue due to expired licensing.

Describe the solution you'd like
When upgrading a single panorama appliance using the pan-os-upgrade panorama command the script halts and it tells us if panorama is in HA mode and the software version of each panorama appliance. It should tell us if there is a licensing issue. It was a bit confusing not knowing why the script was exiting as if we were in dry run mode. I did try both dry run mode and upgrade mode and the result was identical.

Describe alternatives you've considered
At this point I will try to solve the panorama licensing issue and try again.

Additional context
Add any other context or screenshots about the feature request here:

(.venv) pan_os_upgrade % pan-os-upgrade panorama
Panorama hostname or IP: REMOVED
Panorama username: REMOVED
Panorama password:
Target Panorama version: 11.1.1
Dry Run? [Y/n]: y

Welcome to the PAN-OS upgrade tool

This script software is provided on an 'as-is' basis with no warranties, and no support provided.

The selected panorama subcommand will upgrade a single Panorama appliance.

Settings: Custom configuration loaded file detected and loaded at:
/Downloads/pan-os-upgrade-main/pan_os_upgrade/settings.yaml

πŸš€ REMOVED : Connection to the appliance successful.
πŸ“ REMOVED: None REMOVED
πŸ“REMOVED HA mode: primary-passive
πŸ“ REMOVED: Local state: primary-passive, Local version: 10.2.7-h1, Peer version: 10.2.7-h1
πŸ“ REMOVED:Version comparison: equal
(.venv) pan_os_upgrade % pan-os-upgrade panorama
Panorama hostname or IP: REMOVED
Panorama username: REMOVED
Panorama password:
Target Panorama version: 11.0.3-h3
Dry Run? [Y/n]: n

Welcome to the PAN-OS upgrade tool

This script software is provided on an 'as-is' basis with no warranties, and no support provided.

The selected panorama subcommand will upgrade a single Panorama appliance.

Settings: Custom configuration loaded file detected and loaded at:
/Downloads/pan-os-upgrade-main/pan_os_upgrade/settings.yaml

πŸš€ REMOVED Connection to the appliance successful.
πŸ“ REMOVED: None REMOVED
πŸ“ REMOVED: HA mode: primary-passive
πŸ“ REMOVED: Local state: primary-passive, Local version: 10.2.7-h1, Peer version: 10.2.7-h1
πŸ“ REMOVED: Version comparison: equal
(.venv) pan_os_upgrade %

Enhancement: Refactor Script Functions into Dedicated Class Objects for Improved Modularity and Maintainability

Overview

This enhancement request proposes a significant refactor of our existing script functions into dedicated class objects. The aim is to improve code modularity, maintainability, and scalability by organizing related functionalities into cohesive units. The proposed class objects are as follows:

  • Assurance
  • ConfigurationManager
  • HAManagement
  • UpgradeManager
  • Utilities

Rationale

Currently, our script consists of various standalone functions that, while functional, contribute to a monolithic codebase that can be challenging to maintain and extend. By transitioning these functions into dedicated class objects, we stand to gain several benefits:

Enhanced Modularity: Grouping related functions into classes will make the codebase more organized and navigable. This modularity facilitates easier understanding and modification of the code, especially for new contributors.

Improved Maintainability: With functionalities encapsulated within classes, maintaining the code becomes more straightforward. Updates, bug fixes, and enhancements can be managed more efficiently, with reduced risk of side effects.

Increased Reusability: Class objects allow for the reuse of code across different parts of the project without duplication. This not only reduces the overall code volume but also ensures consistency in functionality.

Scalability: As new requirements emerge, the class-based structure will accommodate additional functionalities with minimal disruption to the existing codebase. This scalability is crucial for adapting to future needs and integrations.

Better Testing: Class objects facilitate unit testing by providing a clear structure for mocking dependencies and isolating test cases. This leads to more robust and reliable code.

Proposed Class Objects:

  • Assurance: To handle snapshots, readiness checks, and diff reports, ensuring system readiness and post-upgrade integrity.
  • ConfigurationManager: To manage configurations, including setting, updating, and retrieving configuration parameters.
  • HAManagement: To oversee High Availability (HA) configurations, status checks, and related operations.
  • UpgradeManager: To orchestrate the upgrade process, from pre-checks to the actual upgrade and verification.
  • Utilities: To provide common utility functions used across various parts of the script, such as logging, version parsing, and XML handling.

Implementation Considerations

  • Each class should be self-contained, with a clear interface and well-defined responsibilities.
  • Where possible, classes should follow the Single Responsibility Principle to ensure that each class addresses a specific aspect of the system.
  • Inter-class dependencies should be minimized and managed through interfaces or dependency injection to maintain loose coupling.

Conclusion

Refactoring our script functions into these dedicated class objects represents a strategic investment in the codebase's future. This reorganization will not only address current maintainability concerns but also lay a solid foundation for future enhancements and expansions. We invite feedback and contributions from all stakeholders as we undertake this significant improvement to our project's structure.

Add Multithreading Support for Firewall Upgrade Process

Overview

The current script for upgrading PAN-OS firewalls operates sequentially, which can be time-consuming when dealing with multiple firewalls. The goal of this enhancement is to integrate multithreading into the script to improve the efficiency and reduce the overall execution time.

Detailed Explanation

The script needs to be updated to use multithreading for the following parts of the workflow:

Initial pass of upgrades when connected to Panorama.
Revisiting firewalls that were active in an HA pair and had the same version as their peers.
The proposed solution is to use ThreadPoolExecutor from Python's concurrent.futures module to manage threads efficiently.

Expected Benefits

  • Performance Improvement: Parallel processing of firewall upgrades will significantly reduce the time taken for bulk upgrades.
  • Scalability: The script will be more scalable, handling a larger number of firewalls efficiently.
  • Maintainability: Using ThreadPoolExecutor simplifies thread management, leading to cleaner and more maintainable code.

Implementation Considerations

Thread safety needs to be ensured, particularly when accessing shared resources like firewalls_to_revisit.
Error handling within threads should be robust to avoid any unmanaged thread terminations.
Testing should be thorough to ensure that the new implementation does not introduce any regressions.

Additional Notes

This feature should be optional, allowing users to choose between sequential and parallel execution modes.
Logging should clearly indicate the start, progress, and completion of tasks in each thread for ease of monitoring and debugging.

Discrepancy in Targeted Firewalls for Batch Upgrade in HA Configuration

Summary

We have identified an issue in the batch upgrade script where the firewalls selected and confirmed for an upgrade are not being accurately targeted in a High Availability (HA) configuration. Specifically, one of the selected firewalls (katy-fw1) was not included in the upgrade process, and instead, a firewall not selected for upgrade (katy-fw2) was targeted.

Steps to Reproduce

Run the batch upgrade command with the -u, -p, -h, and -v options to initiate a batch upgrade through Panorama.
Select and confirm a list of firewalls for the upgrade, including firewalls in an HA configuration.
Observe the logs to verify which firewalls are targeted for the upgrade.

Expected Behavior

All and only the firewalls confirmed by the user in the selection process should be targeted and included in the upgrade process.

Actual Behavior

The confirmed firewall katy-fw1 was not targeted for the upgrade.
The non-confirmed firewall katy-fw2, which was not part of the user's selection, was targeted for the upgrade.

Logs/Output

Relevant logs show the user's confirmation of the selected firewalls, including katy-fw1, but the subsequent upgrade process logs indicate that katy-fw2 is being targeted instead of katy-fw1.

Possible Cause/Suspected Area

The issue may lie in the handling of firewall objects in HA configurations within the script. It's possible that the script is incorrectly mapping or identifying the HA pair, leading to one member of the HA pair being incorrectly excluded from the upgrade process.

Suggested Fix/Workaround

A thorough review and possibly a redesign of the logic handling HA configurations and firewall selection for upgrades are needed. Ensuring that the script accurately maps user-selected firewalls to their corresponding objects, especially in HA configurations, is crucial.

Impact

This issue can lead to unintended firewalls being upgraded, which may disrupt network operations and cause confusion. It undermines the reliability of the upgrade process in environments with HA configurations.

Additional Context

This issue was discovered during routine upgrade operations in a controlled environment. It is critical to address this issue to ensure the reliability and accuracy of the batch upgrade process, particularly for users managing firewalls in HA configurations through Panorama.

Enhance Performance of get_firewall_info with Multi-Threading

Summary

The current implementation of the get_firewall_info function fetches system information for each firewall sequentially. This approach can be time-consuming, especially when dealing with a large number of firewalls managed by Panorama. To improve performance and efficiency, it's proposed to refactor this function to use multi-threading, allowing system information for multiple firewalls to be fetched concurrently.

Current Behavior

The get_firewall_info function iterates over a list of Firewall objects, fetching system information for each firewall one at a time.
This sequential processing leads to increased execution time, especially noticeable when the number of firewalls is large.

Expected Behavior

System information for multiple firewalls should be fetched concurrently, leveraging multi-threading.
A significant reduction in the total execution time of the get_firewall_info function.

Proposed Solution

  • Introduce a helper function fetch_firewall_info that handles fetching system information for a single firewall.
  • Utilize concurrent.futures.ThreadPoolExecutor within get_firewall_info to execute fetch_firewall_info concurrently for each firewall in the input list.
  • Aggregate the results from each thread into a list of dictionaries, maintaining the current return structure of get_firewall_info.

Benefits

  • Performance Improvement: By fetching firewall information concurrently, the overall execution time of get_firewall_info will be significantly reduced.
  • Scalability: This enhancement will make the function more scalable, handling a larger number of firewalls more efficiently.
  • Resource Utilization: Improved resource utilization by leveraging I/O wait times to perform other fetches concurrently.

Considerations

  • Error Handling: Ensure robust error handling within fetch_firewall_info to manage partial failures or timeouts gracefully.
  • Concurrency Limit: Carefully choose the max_workers parameter for ThreadPoolExecutor to balance concurrency and system resource utilization.
  • This enhancement is expected to provide a noticeable performance improvement in environments with a large number of firewalls managed by Panorama, enhancing the overall user experience and efficiency of firewall management tasks.

Enhance HA Handling in Batch Upgrades for pan-os-upgrade Script

Summary

Requesting an enhancement to the pan-os-upgrade script to improve handling of High Availability (HA) configurations during batch upgrades. The goal is to automate the determination of which firewall in an HA pair should be upgraded first, ensuring a smoother and more reliable upgrade process.

Current Behavior

The current implementation of batch upgrades in the pan-os-upgrade script does not specifically account for HA configurations. The script assumes that the operator targets the passive firewall within an HA pair. However, this approach requires manual intervention and verification, which can be error-prone and inefficient in environments with multiple HA pairs.

Desired Behavior

The script should automatically identify firewalls in HA configurations and determine the passive unit within each HA pair. The upgrade process should then be initiated on the passive firewall first. Upon successful completion of the upgrade and HA synchronization, the script should then trigger a failover to upgrade the formerly active unit.

Implementation Considerations

HA Pair Detection: Automatically identify firewalls that are part of an HA pair.
HA Status Determination: Dynamically determine which firewall in the HA pair is passive and should be upgraded first.
Sequential Upgrade Process: Automate the upgrade process, starting with the passive unit, followed by a controlled failover and upgrade of the other unit.
Error Handling and Recovery: Implement robust error handling to manage potential issues during the upgrade process, especially in HA environments.

Use Cases

Batch Upgrades in HA Environments: Efficiently handle batch upgrades where multiple firewalls are configured in HA pairs.
Reduced Operator Overhead: Minimize manual intervention and reduce the risk of errors in HA upgrade processes.

Potential Benefits

Automated HA Handling: Simplify the upgrade process in HA environments, making it more reliable and less prone to human error.
Enhanced Reliability: Ensure high availability and minimal downtime during upgrades.
Scalability: Improve the script's ability to handle complex environments with multiple HA configurations.

Request for Comments

Feedback is requested from the community on the proposed enhancement. This includes any concerns about HA handling, alternative approaches, and specific requirements from users managing HA configurations in PAN-OS environments.

TypeError on CLI Invocation Post Typer Integration: Missing Required Positional Arguments

Issue Summary

After integrating Typer into the pan-os-upgrade script to handle command-line arguments, executing the script via CLI results in a TypeError, indicating missing required positional arguments. This behavior was observed subsequent to the replacement of direct function calls in the script entry point with Typer's CLI runner.

Steps to Reproduce

  • Run the command pan-os-upgrade in the CLI after installing the package with Poetry.
  • Observe the resulting TypeError.

Expected Behavior

The script should correctly interpret and accept command-line arguments without throwing errors, utilizing Typer's argument handling capabilities.

Actual Behavior

The script execution fails with a TypeError, stating that main() is missing 4 required positional arguments: 'ip_address', 'username', 'password', and 'target_version'.

Potential Cause

The script's entry point in pyproject.toml was not appropriately updated to reflect the change to Typer. It's currently pointing directly to the main() function, while it should be configured to invoke Typer's CLI runner (app instance) to properly handle the command-line arguments.

Suggested Fix

Modify the [tool.poetry.scripts] section in pyproject.toml to point to the Typer app instance instead of the main() function. For example:

[tool.poetry.scripts]
pan-os-upgrade = 'pan_os_upgrade.upgrade:app'

Bug: Missing Logs Directory Causing Script to Error Out

Issue Summary

There's a critical bug in the current version of our script where it fails to execute properly due to a missing logs directory in the root of the project. This issue prevents the creation of any logs, causing the script to error out.

Detailed Description

Error Behavior: When attempting to run the script, it tries to access or create logs in a 'logs' directory expected to be present in the root of the project. However, since this directory does not exist, the script is unable to proceed, leading to an error.

Expected Behavior: The script should either check for the existence of the 'logs' directory and create it if it's not there or handle the absence of this directory more gracefully without causing a runtime error.

Steps to Reproduce

Clone the repository and set up the environment as per the instructions.
Run the script without manually creating a 'logs' directory in the project root.
Observe that the script errors out due to the absence of the expected logs directory.

Suggested Fix

There are a few potential approaches to resolve this issue:

.gitkeep: Create a .gitkeep fild within the empty ./logs directory will ensure that it is checked into the repository

Automatic Directory Creation: Modify the script to check if the 'logs' directory exists at the start. If it doesn't, the script should automatically create it.

Error Handling Improvement: Enhance the script's error handling to manage the absence of the 'logs' directory more gracefully, possibly by logging to an alternative location or generating a clear error message.
Impact:

This bug currently impedes the script’s usability for any new users or setups where the 'logs' directory is not pre-created, making it a critical issue that needs immediate attention.

Request for Assistance

We are seeking contributions for a quick resolution of this bug. This can include:

Analyzing and identifying the exact cause of the error.

Implementing the suggested fix or an alternative solution.

Testing the fix to ensure the issue is resolved and the script functions as expected in environments without an existing 'logs' directory.

Readiness Checks Failing Due to Error Handling in "jobs" Check

Summary

A bug has been identified where the readiness checks in our panos-upgrade-assurance script are failing. This is specifically occurring during the "jobs" readiness check, leading to errors when handling certain log messages.

Issue Details

Date Encountered: 2024-01-18
Error Messages:

2024-01-18 11:29:58,624 - root - ERROR - ❌ Error running readiness checks: 'id'
2024-01-18 11:29:58,629 - root - ERROR - ❌ Failed to create readiness check

Context: The issue seems to occur when the "jobs" readiness check encounters log entries with failed or errored jobs. An example of such an error entry is:

OrderedDict([('type', 'Failed-Job'), ('details', OrderedDict([('line', 'job failed because of configd restart')])), ('warnings', None)])

Hypothesis

The bug might be related to how the panos-upgrade-assurance library processes failed log messages. It appears that the script is not handling certain log message structures correctly, leading to a failure in creating the readiness check.

Temporary Workaround

As a temporary measure, it might be necessary to remove or disable the "jobs" readiness check from the script. This would prevent the script from halting due to these errors, though it will also bypass the checks that this part of the script is responsible for.

Request for Assistance

We are seeking help in identifying the root cause of this issue and implementing a fix. Contributions can include:

Analyzing the code related to the "jobs" readiness check.
Suggesting improvements in error handling for log message processing.
Testing potential fixes to ensure they resolve the issue without introducing new problems.

Steps to Reproduce

Run the panos-upgrade-assurance script on a system where the "jobs" check encounters failed or errored log entries.
Observe the error output as described above.

Add support for active/active HA upgrades in pan-os-upgrade

Is your feature request related to a problem? Please describe.
Currently, the pan-os-upgrade tool only supports HA upgrades for active/passive configurations. This limitation prevents users from efficiently upgrading their PAN-OS devices in active/active HA setups, requiring manual intervention and increasing the risk of errors.

Describe the solution you'd like
We propose adding support for active/active HA upgrades to the pan-os-upgrade tool. The enhanced feature should:

  1. Recognize and handle different HA status types, including active-primary, active-secondary, and Tentative.
  2. Account for the HA3 interface, which is unique to active/active HA configurations.
  3. Implement the proper active/active HA upgrade workflow, ensuring a smooth and automated upgrade process.

To achieve this, the following steps should be taken:

  1. Research and document the active/active HA upgrade workflow.
  2. Modify the existing codebase to detect and handle active/active HA configurations.
  3. Implement logic to manage the HA3 interface during the upgrade process.
  4. Thoroughly test the new feature to ensure compatibility with various active/active HA setups.

Describe alternatives you've considered
One alternative could be to create a separate subcommand specifically for active/active HA upgrades. However, this would require users to maintain and use multiple upgrade workflows, leading to increased complexity and potential confusion. Integrating the active/active HA upgrade feature into the existing pan-os-upgrade batch subcommand is a more streamlined and user-friendly approach.

Additional context
The addition of active/active HA upgrade support will greatly enhance the usability and versatility of the pan-os-upgrade tool. This feature will benefit organizations running PAN-OS devices in active/active HA configurations, allowing them to automate their upgrade process and reduce the risk of human error. By encompassing both active/passive and active/active HA upgrades, pan-os-upgrade will become a comprehensive solution for upgrading PAN-OS devices in various HA setups.

Implement safeguards to prevent upgrades that may cause HA pair incompatibility

Is your feature request related to a problem? Please describe.
When upgrading PAN-OS firewalls in an HA pair, selecting a version that is two or more minor releases ahead of the current version can lead to compatibility issues. If one firewall is upgraded to a version that is significantly ahead of its peer, it may not be able to rejoin the HA pair after the upgrade, putting itself in a suspended state. When the upgrade process begins on the other firewall, it issues an HA state switch over. If the peer is in a suspended state, neither firewall will be able to forward traffic, as they both operate in a suspended state.

Describe the solution you'd like
To mitigate this issue, we propose implementing a safeguard in the pan-os-upgrade tool that gracefully exits the execution of an upgrade if the following conditions are met:

  1. The user has selected an upgrade version that is two or more minor releases apart from the current release.
  2. The selected firewalls are in an HA state.

The pan-os-upgrade tool should:

  1. Check the current PAN-OS version of the firewalls and compare it with the user-selected upgrade version.
  2. Determine if the firewalls are in an HA state.
  3. If both conditions are met, display a warning message to the user, explaining the potential consequences of proceeding with the upgrade.
  4. Gracefully exit the upgrade process to prevent any unintended downtime or compatibility issues.

Describe alternatives you've considered
An alternative approach could be to allow the upgrade to proceed but display a prominent warning message to the user, highlighting the potential risks associated with upgrading firewalls that are two or more minor releases apart. However, this approach may not be sufficient to prevent users from inadvertently causing compatibility issues and downtime.

Additional context
Implementing this safeguard feature will help prevent users from accidentally causing HA pair incompatibility issues when using the pan-os-upgrade tool. By gracefully exiting the upgrade process when the specified conditions are met, the tool will ensure that users are aware of the potential consequences and can make informed decisions about their upgrade path. This feature enhancement will contribute to a more robust and user-friendly upgrade experience, minimizing the risk of unintended downtime and compatibility problems.

Implement Post-Upgrade Snapshots and Readiness Checks with Differential Analysis

Background

Our current Python script for upgrading PAN-OS firewalls includes pre-upgrade snapshots and readiness checks. These are essential for ensuring that the firewall is in a suitable state before initiating the upgrade process.

Current Limitations

While the pre-upgrade checks are valuable, there is no equivalent functionality for post-upgrade evaluations. This limits our ability to automatically assess the impact of the upgrade and identify any immediate issues resulting from it.

Proposed Enhancement

This feature request aims to introduce post-upgrade snapshots and readiness checks, mirroring the pre-upgrade ones. Additionally, we propose implementing a differential analysis to compare pre and post-upgrade states. This enhancement will involve:

Post-Upgrade Readiness Checks and Snapshots: Implementing the same set of checks and snapshots as the pre-upgrade ones, to be executed after the upgrade process completes. This includes checks for active support, ARP entry existence, certificate requirements, content version, disk space, HA status, IPsec tunnel status, NTP synchronization, and more.

Differential Analysis: Developing a mechanism to compare the results of pre and post-upgrade checks and snapshots. This would highlight any changes, discrepancies, or issues introduced by the upgrade process.

Reporting and Logging: Enhancing the script's reporting and logging capabilities to include details of the differential analysis, providing clear insights into the impact of the upgrade.

Challenges and Considerations

Accuracy in Differential Analysis: Ensuring the comparison mechanism accurately identifies and reports meaningful changes without false positives.

Performance Impact: Minimizing the performance impact of additional checks and analyses on the firewall appliances.
User Interface and Experience: Designing a clear and user-friendly way to present the differential analysis results.

Error Handling and Rollback: Strengthening error handling procedures, particularly if post-upgrade checks reveal critical issues.

Request for Contributions

We are looking for community input and contributions to help develop this feature. Contributions can include code development, testing, documentation, or any insights related to PAN-OS upgrade processes and differential analysis.

Update Documentation for GitHub Repository and PyPI Package Deployment

Issue Summary

Our project requires comprehensive documentation updates to ensure clarity and usability both on our GitHub repository and for our PyPI package deployment. This includes updating inline docstrings, README files, and setting up Sphinx for auto-generated documentation.

Detailed Tasks

Update Inline Docstrings

  • Go through the entire codebase and update all inline docstrings to ensure they are clear, concise, and follow a consistent format. This includes docstrings for functions, classes, modules, etc.
  • Ensure that the docstrings provide enough context for understanding the functionality and usage of each code segment.

Update README for GitHub Repository

  • Revise the existing README.md in the root directory of the repository.
  • Include sections on installation, usage, contributing, license, and contact information.
  • Provide examples and usage scenarios to help new users understand how to use the project.
  • Ensure the README is engaging and informative, serving as the first point of entry for new users and contributors.

Create README for PyPI Package

  • Create a new README file specifically tailored for the PyPI package deployment.
  • This file is typically placed in the package directory (pan_os_upgrade), and it should focus on usage and installation via PyPI.
  • The content should be concise and to the point, guiding users on how to install and get started with the package quickly.

Set Up Sphinx for Auto-Generated Documentation

  • Install Sphinx and configure it to auto-generate documentation from the project's docstrings.
  • The generated documentation should be stored in the project's docs/ folder.
  • Configure Sphinx to generate webpages that are compatible with GitHub Pages.
  • Ensure that Sphinx is set up to automatically update the documentation as the codebase evolves.

Impact

These updates will greatly enhance the user and developer experience, making it easier to understand, use, and contribute to the project. Well-maintained documentation is crucial for open-source project adoption and growth.

Request for Assistance

Contributions are welcome for:

  • Reviewing and updating docstrings.
  • Writing and structuring the README files.
  • Configuring Sphinx and integrating it with GitHub Pages.
  • Testing the documentation for clarity and completeness.

HA Configuration Sync Failures Block Panorama Primary-Suspended Upgrades

Description

When attempting to upgrade Panorama instances in an HA configuration, the upgrade process for the primary-suspended unit is blocked due to strict configuration sync checks. This behavior is observed even in scenarios where a configuration sync failure should not prevent the upgrade from proceeding. The root cause has been identified as the strict_sync_check parameter being set to True, which enforces strict synchronization status checks before allowing the upgrade to continue.

Expected Behavior

The upgrade process should be more resilient to HA configuration sync discrepancies, especially when they are not critical to the upgrade process. Users should have the flexibility to bypass non-critical sync failures to ensure that upgrades can proceed without unnecessary interruptions.

Current Behavior

Upgrades are halted for the primary-suspended unit in an HA configuration if there are any configuration sync failures, regardless of their impact on the upgrade process. This strict behavior is due to the strict_sync_check parameter being set to True by default.

Steps to Reproduce

  • Setup Panorama in an HA configuration with a primary-active and primary-suspended setup.
  • Introduce a non-critical configuration sync discrepancy between the units.
  • Attempt to upgrade the primary-suspended unit.
  • Observe that the upgrade is blocked due to the configuration sync failure.

Proposed Solution

Change the default value of the strict_sync_check parameter from True to False. This change will allow the upgrade process to be more lenient towards non-critical sync failures, improving the robustness and user experience of the upgrade process.

  • Impact

Positive: Increases the resilience of the upgrade process by avoiding unnecessary blocks due to non-critical HA sync issues.
Negative: There may be scenarios where a strict sync check is desirable for ensuring consistency before an upgrade. This change could potentially bypass such checks, so careful consideration and user control over this behavior are recommended.

Additional Context

The issue has been reported by multiple users facing challenges in upgrading their Panorama setups in HA configurations.

A configuration option to toggle the strictness of the sync check (allowing users to opt-in for strict checks when needed) might be a balanced approach to address this issue.

This issue aims to enhance the upgrade process's flexibility and user experience by providing better control over HA sync checks during upgrades.

UnicodeEncodeError on Windows When Logging Messages with Emojis

Environment

  • OS: Windows 10
  • Python Version: 3.12
  • Application: pan-os-upgrade

Issue Summary

When running the pan-os-upgrade script on Windows machines, a UnicodeEncodeError is thrown during logging operations that involve emojis. This issue seems to stem from the default character encoding in Windows command prompt and PowerShell, which does not support certain Unicode characters used in the script's logging messages.

Steps to Reproduce

  1. Run the pan-os-upgrade script using PowerShell or cmd.exe on a Windows machine.
  2. Observe the UnicodeEncodeError that occurs when the script attempts to log messages containing emojis.

Expected Behavior

The script should log messages without causing encoding errors, regardless of the operating system or the shell used.

Actual Behavior

The script fails to log messages correctly and throws a UnicodeEncodeError when it encounters emojis in log messages on Windows.

Possible Solutions

  • Remove emojis from log messages to ensure compatibility across different platforms.
  • Implement a custom logging handler or filter to encode log messages in UTF-8 and handle encoding issues.

Additional Context

This issue impacts Windows users of the pan-os-upgrade tool, potentially affecting usability and user experience. Addressing this issue would improve the tool's robustness and cross-platform compatibility.

Duplicate Log Entries in Script Execution Due to Logger Propagation

Issue Summary

In our script upgrade.py, we've observed that each log message appears twice in the console output. This issue seems to be related to Python's logging configuration, particularly the propagation of log messages to the root logger in addition to our script's custom logger.

Steps to Reproduce

Execute the upgrade.py script with any standard set of arguments.
Observe the console output where each log message is duplicated.

Expected Behavior

Each log message should appear only once in the console output.

Actual Behavior

Each log message is duplicated, appearing twice consecutively in the console output.

Possible Cause

This duplication likely results from the logger's propagate attribute being set to True (default behavior), causing log messages to be handled by both the script's logger and the root logger.

Suggested Solution

Adjust the logger configuration in the configure_logging function by setting logger.propagate = False. This change should stop the log messages from being propagated to the root logger.

Additional Context

The issue was identified during routine script execution.
Python's logging module is used for logging in the script.
Example log output demonstrating the issue is attached for reference.

❯ docker run -v $(pwd)/assurance:/app/assurance -v $(pwd)/logs:/app/logs -it ghcr.io/cdot65/pan-os-upgrade:latest      
Hostname or IP: 192.168.255.41
Username: cdot
Password: 
Target PAN-OS version: 10.2.2
INFO:root:βœ… Connection to firewall established
INFO - βœ… Connection to firewall established
INFO:root:πŸ“ 007054000242051 Katy-fw1 192.168.255.41
INFO - πŸ“ 007054000242051 Katy-fw1 192.168.255.41
INFO:root:πŸ“ Firewall HA mode: active
INFO - πŸ“ Firewall HA mode: active
INFO:root:πŸ“ Current PAN-OS version: 11.0.0
INFO - πŸ“ Current PAN-OS version: 11.0.0
INFO:root:πŸ“ Target PAN-OS version: 10.2.2
INFO - πŸ“ Target PAN-OS version: 10.2.2
ERROR:root:❌ Upgrade is not required or a downgrade was attempted.
ERROR - ❌ Upgrade is not required or a downgrade was attempted.
ERROR:root:πŸ›‘ Halting script.
ERROR - πŸ›‘ Halting script.

Enhance CLI Argument Handling for Distinct PAN-OS Device Upgrade Types

Summary

Requesting an enhancement to the pan-os-upgrade script to allow users to explicitly differentiate between target device types when executing upgrades. This feature aims to streamline the upgrade process for individual firewalls, Panorama-managed devices, and batch upgrades.

Current Behavior

The current implementation of the pan-os-upgrade script does not distinctly differentiate between various target device types. As a result, users might face challenges in specifying whether they are targeting a standalone firewall, a Panorama-managed device, or performing batch operations.

Desired Behavior

Introduce new CLI arguments or options in the script to enable users to clearly specify the target device type for the upgrade process:

  • Firewall Upgrade: A specific CLI argument to target individual firewalls.
  • Panorama Upgrade: A separate argument or option to specify upgrades for Panorama-managed devices.
  • Batch Upgrade: An option to facilitate batch processing for upgrading multiple devices.

Use Cases

  1. Case 1: Upgrading a single firewall where the user specifies the target device directly.
  2. Case 2: Upgrading devices managed by Panorama, possibly using filters to select specific devices.
  3. Case 3: Performing batch upgrades where the script processes multiple devices in a sequence or batch.

Potential Benefits

Improved Usability: Clearer, more intuitive CLI options aligned with common operational scenarios.

Increased Flexibility: Ability to target specific device types or groups of devices, enhancing control in diverse environments.

Better Script Management: Streamlined process for managing different upgrade paths within the same script framework.

Suggested Implementation

Propose adding new subcommands or flags to the existing Typer-based CLI structure to handle different upgrade scenarios. This could involve parsing additional arguments or modifying existing argument processing logic.

Request for Comments

Seeking input on the proposed enhancement, including any potential concerns, alternative suggestions, or specific requirements from users who frequently interact with different PAN-OS devices for upgrades.

Post-Upgrade Snapshot and Report Generation Skipped for Firewalls

Describe the bug

After completing firewall upgrades, the post-upgrade process is expected to take snapshots and generate diff reports. However, these steps are being skipped, seemingly due to the code block that bypasses the report generation process if settings.yaml is not found. This results in missing post-upgrade snapshots and reports, which are crucial for verifying upgrade success and diagnosing issues.

To Reproduce

Steps to reproduce the behavior:

  1. Execute the firewall upgrade script without a settings.yaml file in the working directory.
  2. Complete the firewall upgrade process.
  3. Observe that the post-upgrade snapshots and diff report generation steps are skipped.

Expected behavior

Regardless of the presence of settings.yaml, post-upgrade snapshots and reports should be generated to ensure that the upgrade's effects can be reviewed and verified.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: macOS, Linux, WSL2

Additional context

The issue seems to stem from the conditional check for settings.yaml presence, which also considers the snapshot settings within the file. If settings.yaml is not found, the process to generate snapshots, diff, and PDF reports is entirely skipped. A proposed solution is to decouple the snapshot and report generation from the settings.yaml presence and its snapshot settings, ensuring these post-upgrade steps are always executed.

Standalone Firewall Upgrade Completion Signal Issue

Summary

The current script implementation for the pan-os-upgrade tool is encountering issues with detecting the completion of the upgrade process on standalone firewalls. This seems to stem from the script's reliance on output analysis designed for HA (High Availability) setups, which doesn't translate well to standalone environments.

Steps to Reproduce

  1. Run the pan-os-upgrade tool on a standalone PAN-OS firewall.
  2. Observe the behavior of the tool during the completion phase of the firewall upgrade.

Expected Behavior

After a successful upgrade, the script should accurately detect the completion of the process and provide appropriate feedback or next steps for standalone firewalls.

Actual Behavior

The script, while waiting for a signal or output indicative of an HA environment, fails to recognize the completion state of the upgrade in standalone firewall setups. This may lead to prolonged wait times or incorrect assumptions about the upgrade status.

Possible Solutions or Suggestions

  • Implement a detection mechanism that differentiates between HA and standalone environments, allowing for tailored output analysis based on the setup.
  • Introduce a timeout or fallback mechanism that assumes successful completion after a certain period if no explicit HA signals are detected.

Enhancement: Check for Preempt Setting in HA Configuration Before Upgrade

Description

Currently, the pan-os-upgrade script upgrades firewalls without considering the preempt setting in High Availability (HA) configurations. This can lead to situations where an upgraded firewall with preempt enabled might take over as the active unit from a non-upgraded peer, potentially causing issues in the network.

Proposed Enhancement

It is proposed to enhance the script to check for the preempt setting in the HA configuration of a firewall pair before proceeding with the upgrade. If preempt is enabled, the script should inform the operator and prompt for confirmation to continue with the upgrade process.

Goals

  • Safety: Ensure that the upgrade process does not inadvertently cause an unexpected failover in HA configurations.
  • Awareness: Increase operator awareness of HA configurations that might impact the network during the upgrade process.
  • Control: Provide operators with the ability to make informed decisions before proceeding with upgrades in complex HA environments.

Non-Goals

  • Configuration Changes: The script will not modify any HA or firewall configurations, including the preempt setting. The responsibility for any configuration changes remains with the operator.

Implementation Notes

  • The script should query the firewall's HA configuration to determine if preempt is enabled.
  • If preempt is enabled, the script should display a clear message to the operator, indicating the potential implications.
  • The operator should be prompted to confirm if they wish to proceed with the upgrade, with a clear option to cancel or continue.

Use Cases

  • Upgrading HA Firewalls: Operators upgrading firewalls in an HA pair need to be aware of the preempt setting to prevent unexpected failovers.
  • Maintenance Windows: During planned maintenance, operators need to ensure that upgrades do not lead to unintended service disruptions.

Questions for Discussion

  • What is the best method to query the preempt setting from the firewall's HA configuration?
  • How should the script handle scenarios where it cannot determine the preempt setting due to connectivity issues or other errors?

Additional Context

This enhancement request stems from operational feedback where an unexpected failover occurred during an upgrade due to the preempt setting. Addressing this will improve the reliability and predictability of the upgrade process in HA environments.

Implement Comprehensive Unit and Integration Tests for Enhanced Reliability

Overview

The pan-os-upgrade project currently lacks a comprehensive suite of unit and integration tests. As the project grows in complexity and usage, the absence of automated tests poses a risk to stability and maintainability. Implementing a structured testing framework will significantly improve the reliability of the tool, catch regressions early, and facilitate future enhancements by ensuring new changes do not inadvertently break existing functionality.

Objectives

  • Establish Testing Framework: Set up a testing framework compatible with our project stack, considering tools like pytest for unit tests and potentially tox for testing across multiple Python versions.
  • Unit Tests: Develop unit tests for critical functions, particularly those handling upgrade logic, HA functionality, and response parsing. Focus should initially be placed on areas of the codebase that are most prone to errors or have had issues in the past.
  • Integration Tests: Create integration tests that simulate real-world upgrade scenarios, including HA and non-HA setups, to ensure the tool behaves as expected in a variety of environments and configurations.
  • Continuous Integration (CI) Integration: Integrate the tests into a CI pipeline to automatically run tests against pull requests and commits, ensuring that all changes are verified before merging.

Specific Areas for Testing

  • HA Logic Separation: Given recent enhancements to handle Panorama and PAN-OS HA functionality distinctly, it's crucial to ensure these paths are thoroughly tested.
  • Upgrade Path Calculations: The logic that determines the upgrade path for devices should be rigorously tested to prevent incorrect upgrade recommendations.
  • Error Handling: Tests should cover scenarios where the tool encounters unexpected responses or errors from devices to ensure graceful handling and clear, informative logging.

Expected Outcome

The implementation of unit and integration tests will bolster the project's reliability and facilitate a more streamlined development process. It will provide contributors with immediate feedback on their changes, reducing the likelihood of introducing bugs and regressions.

Call for Contributions

Contributions to this testing effort are highly welcome, whether in the form of writing tests, setting up testing infrastructure, or providing guidance and best practices. If you have experience in Python testing frameworks and are interested in improving the robustness of the pan-os-upgrade tool, your input would be invaluable.

Please share any initial thoughts, proposed testing strategies, or areas of the codebase you believe should be prioritized for testing.

Enhance Batch Subcommand with Interactive Firewall Selection Mechanism

This issue proposes the development of a new mechanism to enhance user interaction with the batch subcommand, specifically aimed at simplifying the process of selecting firewalls for batch operations.

Current Mechanism Limitations:
The existing approach requires users to specify firewalls using a filter string, which demands prior knowledge of firewall hostnames or serial numbers. This method can be cumbersome and inefficient, especially in environments with a large number of devices.

Proposed Enhancement:
We suggest implementing a feature that automatically retrieves a list of all available firewalls, along with their pertinent details such as hostnames, serial numbers, and version numbers. Post-retrieval, users should be presented with an interactive interface that allows them to easily select one or multiple firewalls to target for upgrades or other batch operations.

Key Features of the New Mechanism:

  • Automatic Discovery: Fetch and display a comprehensive list of firewalls connected to the system or network.
  • Detailed Information: Provide essential information for each firewall, including hostname, serial number, and current software version, to assist users in making informed decisions.
  • Interactive Selection: Enable users to interactively select firewalls from the list for batch operations, improving usability and reducing the potential for errors.
  • Flexibility: Allow both single and multiple selections, catering to various operational needs and scenarios.

Benefits:

  • User-Friendly: Significantly enhances user experience by providing a straightforward and intuitive selection process.
  • Efficiency: Reduces the time and effort required to identify and select target firewalls, especially in large-scale environments.
  • Accuracy: Minimizes the risk of targeting incorrect devices by providing clear and detailed information for each selectable firewall.

Implementation Considerations:

  • Ensure compatibility with existing systems and workflows to avoid disrupting current operations.
  • Prioritize security and integrity of the selection process to prevent unauthorized actions or access.
  • Develop comprehensive documentation and user guides to facilitate the adoption of the new mechanism.

This enhancement is aimed at streamlining operations and improving the efficiency and user-friendliness of the batch subcommand. Feedback and suggestions from the community are highly encouraged to refine this proposal further.

Option to connect directly to each firewall instead of using Panorama as proxy

Is your feature request related to a problem? Please describe.
No but a potential one if too many calls to Panorama API endpoint.

Describe the solution you'd like
Provide a way to bypass default behaviour of proxying via Panorama

Describe alternatives you've considered
None

Additional context
We had issues when using upgrade assurance module in Ansible when proxying connection via Panorama

Panorama based "inventory"

User Story

User should be able to request a list of devices based on those managed by Panorama. Script should accept Panorama as a target instead of a specific firewall and provide a selection function to allow the user to select multiple devices to upgrade. This will allow for scalable upgrades of the largest PAN-OS environments.

Further, the selection function should support the use of the pan-os-upgrade-assurance 'health checks' to allow selection of all devices that are failing a specific check.

Example

python upgrade.py --version 11.0.2-h3 --device-group 'test-dg'
python upgrade.py --version 11.0.2-h3 --affected-by 'device_panorama_and_cdss_certificate_issue'

Enhance Typer Application with Readiness Check Bypass and Advanced Firewall Inventory Management

Description:

We are proposing an enhancement to the Typer application to introduce two major functionalities aimed at optimizing user experience and operational efficiency.

New Feature 1: Bypass Readiness Checks and Snapshots Option

The first part of this enhancement focuses on providing users with the ability to bypass readiness checks and snapshots within the "settings" subcommand. This feature is intended for advanced users who require faster execution times and are confident in the pre-conditions of their environments.

Acceptance Criteria:

  • Introduce a new flag --bypass-readiness within the "settings" subcommand.
  • When enabled, the application should skip all readiness checks and snapshot operations.
  • Ensure clear documentation is provided, warning users of the potential risks associated with using this bypass.

New Feature 2: Simplified Firewall Inventory Mechanism

The second part of the enhancement aims to simplify the management and targeting of specific firewalls connected to Panorama. This will involve creating a more intuitive inventory mechanism that allows for easier identification and selection of firewalls for various operations.

Acceptance Criteria:

  • Develop a new inventory mechanism that integrates seamlessly with the Typer application.
  • Allow users to list, add, remove, and target specific firewalls within the Panorama-connected environment.
  • Ensure the mechanism is user-friendly and reduces the complexity of managing large numbers of firewalls.
  • Provide detailed documentation on how to use the new inventory features, including examples and best practices.

General Requirements:

Thorough testing must be conducted to ensure both new features work as expected without introducing regressions to existing functionalities.

Update the documentation to reflect the new features, including clear instructions, use cases, and any limitations.

Consider backward compatibility and ensure that existing workflows are not disrupted for users who do not opt into the new features.

This enhancement is aimed at making the Typer application more versatile and efficient, particularly for power users and those managing large-scale environments. We welcome feedback and contributions from the community to refine these features further.

Enhance Upgrade Script to Support Major/Minor Version Upgrades for PAN-OS Firewalls

Background

The current Python script for upgrading PAN-OS firewalls efficiently handles upgrades for hotfix and maintenance releases. However, it's limited in scope and does not support upgrading between minor or major releases of PAN-OS.

Issue

When attempting to upgrade to a different minor or major release, the script halts if the base image for the target version is not present on the device. This limitation hinders users who need to perform such upgrades, especially in scenarios requiring a transition across multiple version levels.

Proposed Enhancement

The enhancement aims to expand the script's capability to include the upgrade process for minor and major PAN-OS releases. This would involve:

Identifying and Handling Base Images: Implementing a method to identify, download (if not present), and utilize the correct base images required for major/minor version upgrades.

Workflow Adjustments for HA Setups: Addressing the challenges posed by active/passive High Availability (HA) setups, where both firewalls in an HA pair cannot have drastic version differences during the upgrade process. This would require a careful synchronization and staging strategy to ensure both units in the HA pair are upgraded consistently and without causing service disruptions.

Challenges and Considerations:

HA Synchronization: Developing a mechanism to ensure that both units in an HA pair are upgraded in a manner that maintains their compatibility and avoids service disruption.

Rollback Procedures: Establishing reliable rollback procedures in case of upgrade failures, especially critical in HA environments.

Testing Across Versions: Extensive testing will be required to ensure the script's reliability across different upgrade paths and PAN-OS versions.

User Guidance: Updating documentation and user guidelines to cover the new upgrade scenarios and best practices.

Request for Contributions

We are seeking contributions from the community to address these challenges. Input, suggestions, and code contributions are highly welcomed, especially from those with experience in PAN-OS upgrades and HA environments.

Snapshot Error on PAN-OS 10.1.8: Missing Session Counters in Batch Upgrade

Issue Description

When performing a dry run batch upgrade using the pan-os-upgrade script with a filter targeting specific firewalls, an error occurred during the snapshot phase. The error was related to missing session statistics, specifically num-imsi and potentially tcp-cong-ctrl, which were not present in the response from a PAN-OS version 10.1.8 firewall.

Error Details

The script successfully established a connection to Panorama and identified the target firewall (tffw01). However, during the snapshot of network state information, the following validation errors were encountered:

❌ tffw01: Error running snapshots: 2 validation errors for SnapshotReport
session_stats.num-imsi
  Field required [type=missing, input_value={'tmo-5gcdelete': '15', '...'num-gtpu-pending': '0'}, input_type=dict]
session_stats.tcp-cong-ctrl
  Field required [type=missing, input_value={'tmo-5gcdelete': '15', '...'num-gtpu-pending': '0'}, input_type=dict]

This suggests that the session statistics expected by the script, particularly num-imsi and potentially tcp-cong-ctrl, were not available in the PAN-OS 10.1.8 firewall response.

Investigation

Upon reviewing the firewall's available counters, it was noted that the counters for "Hardware UDP session offloading" and "Number of active IMSI sessions" were indeed missing, which corresponds to the num-imsi counter error. The tcp-cong-ctrl error is suspected to be related, possibly due to the absence of the num-imsi counter.

Pydantic Model Configuration

The Pydantic model used for parsing session statistics (SessionStats) has all fields marked as Optional, which should theoretically allow for missing data without causing validation errors. However, the observed behavior suggests an issue with handling optional fields for missing session counters.

Steps to Reproduce

Execute the pan-os-upgrade batch command targeting a Panorama appliance with a filter for a specific firewall running PAN-OS 10.1.8.
Provide necessary authentication details and choose a dry run.
Observe the error during the snapshot phase.

Expected Behavior

The script should handle missing session counters gracefully, especially when they are marked as optional in the Pydantic model. The absence of specific counters should not prevent the snapshot process from completing.

Suggested Resolution

Investigate the handling of optional fields in the Pydantic model and ensure that missing session statistics do not result in validation errors. Consider implementing additional checks or fallback mechanisms for environments with older PAN-OS versions where certain counters may not be available.

Enhance Network-Related Error Handling for User Clarity

Issue Description

Currently, in our application, when a user encounters network connectivity issues, especially related to DNS resolution or IP address validation, the error messages provided are not very informative. This lack of detail makes it difficult for users to understand the specific nature of the problem – whether it is due to the hostname not resolving to their network's DNS server or an issue with the IP address format.

Proposed Enhancement

We propose enhancing the error handling mechanism to provide more context-specific information to the user. This enhancement would involve improving the way we handle and report errors in DNS resolution and IP address validation processes.

Goals

  • Clear Distinction in Error Messages: Ensure that error messages clearly differentiate between a DNS resolution failure and an IP address validation issue.
  • Detailed Error Information: Where possible, provide additional details in the error message, such as whether the failure is due to a non-existent domain, a timeout, or an invalid IP address format.
  • User Guidance: Offer suggestions or possible actions in the error message that the user can take to resolve or diagnose the issue.

Expected Impact

  • Improved User Experience: Users will have a better understanding of what went wrong and how they might fix it.
  • Reduced Support Queries: Clearer error messages can reduce the number of support queries regarding network connectivity issues.
  • Easier Troubleshooting: Users and support teams can more easily diagnose and resolve issues based on the enhanced error information.

Implementation Notes

We might need to revisit the resolve_hostname and ip_callback functions to implement this enhancement.
Care should be taken to ensure that the error messages are user-friendly and avoid overly technical jargon.

Additional Context

This enhancement is particularly important for users who are not deeply familiar with network terminologies or who might be troubleshooting connectivity issues without in-depth technical knowledge.

PyPi deployment

Package should be deployed to PyPi so it can be easily pip installed.

Package should automatically add upgrade.py to scripts/bin directory so it can be executed directly within a venv.

Locale Error: Unsupported Locale Setting in Ubuntu WSL2 Environment

Summary:
Encountering a locale-related error when running a Python script in Ubuntu WSL2. The error message indicates an unsupported locale setting.

Environment:

  • OS: Ubuntu 20.04 (WSL2)
  • Python Version: 3.12

Steps to Reproduce:

  1. Run the Python script pan-os-upgrade in the Ubuntu WSL2 environment.
  2. The script fails with a locale error.

Expected Behavior:
The script should run without any locale-related errors.

Actual Behavior:
The script execution halts with the following error:

locale.Error: unsupported locale setting

Attempts to Resolve:

  • Checked current locale settings with locale.
  • Generated and reconfigured locales using locale-gen and dpkg-reconfigure.
  • Updated .bashrc with export commands for LC_ALL, LANG, and LANGUAGE.
  • Restarted the WSL session.

However, the issue persists.

Additional Context:
This issue seems specific to the Ubuntu WSL2 environment. The script runs fine on native Linux and Windows systems. Attached is the detailed error log for reference.


Would appreciate any guidance or insights on resolving this locale issue. Thank you!

Inconsistent HA Peer Upgrade Order Due to Thread Limitations

Description

When performing batch upgrades on firewalls configured in High Availability (HA) mode, there's an observed inconsistency in the upgrade order, particularly when the number of targeted firewalls surpasses the available thread count. This leads to scenarios where an HA peer firewall may be upgraded prior to the active unit. Given the script's two-phase operationβ€”initially enforcing HA synchronization, then relaxing this requirement in the latter phaseβ€”this behavior can cause issues. Specifically, when an HA peer is upgraded ahead of the active unit, the subsequent attempt to upgrade the active firewall might fail due to the HA synchronization requirement not being met due to version mismatches.

Impact

This issue can disrupt the intended sequential upgrade process in HA configurations, potentially leading to situations where the active firewall cannot be upgraded due to its peer already being on a different version, thereby violating the HA synchronization check in the script's initial phase.

Proposed Solution

It is suggested that the requirement for HA synchronization be relaxed for both phases of the script. This adjustment would accommodate scenarios where the upgrade sequence cannot be strictly controlled due to threading limitations, ensuring that upgrades can proceed even when HA peers are temporarily out of sync due to version discrepancies.

Steps to Reproduce

  • Configure a set of firewalls in HA mode, ensuring they are managed by Panorama.
  • Initiate a batch upgrade through the script, targeting more firewalls than the configured thread count allows.
  • Observe the order in which firewalls are picked up for upgrade by the available threads.

Expected Behavior

The script should maintain HA synchronization requirements flexibly, allowing upgrades to proceed even when an HA peer has been upgraded first due to threading constraints.

Actual Behavior

The script enforces HA synchronization strictly in its initial phase, potentially halting the upgrade process if the active unit's HA peer has already been upgraded, leading to version discrepancies and failed HA sync checks.

Suggested Enhancement

Modify the ha_sync_check_firewall function (and any related logic) to relax the HA synchronization checks throughout the script's operation, thereby accommodating the non-deterministic upgrade order induced by threading limitations. This change aims to enhance the script's resilience and adaptability in complex HA configurations, ensuring a smoother upgrade experience across diverse deployment scenarios.

Update README Screenshot to Illustrate Full Upgrade Workflow

Overview

The current README file of our panos-upgrade-assurance script contains a screenshot that provides a visual aid for a portion of the upgrade process. However, this screenshot does not encompass the entire upgrade workflow. To enhance user understanding and provide a comprehensive overview, we propose updating this screenshot.

Proposed Enhancement

Create a New Screenshot: Develop a new screenshot that captures the full upgrade workflow of the script. This should include all major steps and stages of the upgrade process, from initial readiness checks to post-upgrade validation.
High-Quality Visuals: Ensure the screenshot is of high quality, clearly legible, and effectively formatted to fit within the README layout.

Detailed Annotations: Where applicable, annotate the screenshot to highlight key features, steps, or important information within the workflow. This can help users quickly grasp the script's functionality and flow.
Impact:

This enhancement will provide users with a clearer, more comprehensive understanding of the script's capabilities and workflow. It will make the README more informative and user-friendly, potentially reducing the learning curve for new users.

Contribution Request

Contributions are welcome in the following areas:

  • Designing and creating the updated screenshot.
  • Suggestions on specific workflow elements to highlight in the screenshot.
  • Feedback on the clarity and effectiveness of the proposed screenshot.

Additional Notes

The updated screenshot should be optimized for web viewing (consider file size, dimensions, and format).
Ensure that the screenshot adheres to any privacy or security considerations, avoiding the display of sensitive or proprietary information.

Support HA Upgrades for Firewalls and Panorama Using firewall Subcommand

Is your feature request related to a problem? Please describe.
Yes. The pan-os-upgrade tool's reliance on the batch subcommand for HA upgrades imposes limitations. It cannot directly upgrade standalone HA firewalls (those not managed by Panorama), nor can it handle HA upgrades for Panorama appliances themselves.

Describe the solution you'd like
Extend the pan-os-upgrade tool to support HA upgrades using the firewall and panorama subcommands. This would allow direct upgrades of both standalone firewall HA pairs and Panorama HA pairs.

Describe alternatives you've considered
Currently, the only way to upgrade HA pairs without the proposed change is by either:

Manual Process: Performing the upgrade manually, which can be time-consuming, complex, and error-prone.
Panorama Reliance (for firewalls): Upgrading firewalls through Panorama, which isn't always feasible or desirable.

Additional context
This enhancement would improve pan-os-upgrade in several significant ways:

  • Greater Flexibility: Provides more options for upgrade workflows across various environments.
  • Standalone Firewall Support: Empowers direct upgrades of firewalls not managed by Panorama.
  • Panorama Upgrade Capability: Enables simpler upgrades for HA Panorama setups.

Enhance Support for HA Panorama Upgrades in pan-os-upgrade Tool

The current pan-os-upgrade CLI tool lacks dedicated support for upgrading High Availability (HA) Panorama instances, due to differences in the HA response structure compared to firewalls. Specifically, the existing handle_ha_logic function fails to accommodate Panorama's unique response to the "show high-availability state" command, which lacks a "group" concept present in firewall responses.

Current Limitation:

The handle_ha_logic function is not compatible with Panorama's HA state response structure, causing the upgrade process for HA Panorama setups to fail.

Example HA Panorama Response:

<response status="success">
    <result>
        <enabled>yes</enabled>
        <local-info>
            <version>1</version>
            <state>primary-active</state>
            <state-duration>74869</state-duration>
            <last-error-reason>Path down</last-error-reason>
            <last-error-state>primary-non-functional</last-error-state>
            <mgmt-ip>192.168.255.191/24</mgmt-ip>
            <mgmt-ipv6></mgmt-ipv6>
            <preemptive>yes</preemptive>
            <promotion-hold>2000</promotion-hold>
            <hello-interval>8000</hello-interval>
            <heartbeat-interval>2000</heartbeat-interval>
            <preempt-hold>1</preempt-hold>
            <monitor-fail-holdup>0</monitor-fail-holdup>
            <addon-master-holdup>7000</addon-master-holdup>
            <encrypt-imported>no</encrypt-imported>
            <mgmt-macaddr>82:2c:5b:03:6b:c1</mgmt-macaddr>
            <encrypt-enable>no</encrypt-enable>
            <link-mon-intv>3000</link-mon-intv>
            <priority>primary</priority>
            <build-rel>10.2.7-h3</build-rel>
            <url-version>Not Installed</url-version>
            <app-version>8804-8537</app-version>
            <iot-version>113-471</iot-version>
            <av-version>4719-5237</av-version>
            <VMS>Match</VMS>
            <build-compat>Match</build-compat>
            <url-compat>Match</url-compat>
            <app-compat>Match</app-compat>
            <iot-compat>Match</iot-compat>
            <av-compat>Match</av-compat>
        </local-info>
        <peer-info>
            <conn-ha1>
                <conn-status>up</conn-status>
                <conn-primary>yes</conn-primary>
                <conn-desc>heartbeat status</conn-desc>
            </conn-ha1>
            <conn-status>up</conn-status>
            <version>1</version>
            <state>secondary-passive</state>
            <state-duration>74319</state-duration>
            <last-error-reason>User requested</last-error-reason>
            <last-error-state>secondary-suspended</last-error-state>
            <preemptive>yes</preemptive>
            <mgmt-ip>192.168.255.192</mgmt-ip>
            <mgmt-macaddr>82:2c:5b:03:6b:c2</mgmt-macaddr>
            <priority>secondary</priority>
            <build-rel>10.2.7-h3</build-rel>
            <url-version>Not Installed</url-version>
            <app-version>8804-8537</app-version>
            <iot-version>113-471</iot-version>
            <av-version>4719-5237</av-version>
            <VMS>3.0.5</VMS>
        </peer-info>
        <path-monitoring>
            <enabled>yes</enabled>
            <failure-condition>any</failure-condition>
            <groups>
                <entry>
                    <name>panorama2</name>
                    <failure-condition>any</failure-condition>
                    <enabled>yes</enabled>
                    <ping-interval>5000</ping-interval>
                    <ping-count>3</ping-count>
                    <destination-groups>
                        <entry>
                            <name>panorama2</name>
                            <enabled>yes</enabled>
                            <failure-condition>any</failure-condition>
                            <dest-ip>
                                <entry>
                                    <addr>192.168.255.192</addr>
                                    <status>up</status>
                                </entry>
                            </dest-ip>
                        </entry>
                    </destination-groups>
                </entry>
            </groups>
        </path-monitoring>
        <running-sync>synchronized</running-sync>
        <running-sync-enabled>yes</running-sync-enabled>
    </result>
</response>

Required Enchancement

Develop a new function specifically designed for HA Panorama upgrades, acknowledging the absence of "group" structures in Panorama's HA state responses. This function should effectively manage the upgrade process, ensuring compatibility with Panorama's HA architecture and facilitating a seamless upgrade experience.

This enhancement is crucial for customers needing to safely and efficiently upgrade large numbers of HA Panorama instances in short time frames. Addressing this will significantly improve the tool's utility and reliability for complex Panorama environments.

Enhancement: Support for Upgrading Active Firewall First in HA Pairs

Summary

Currently, our pan-os-upgrade script adopts a conservative approach by prioritizing upgrades for "passive" firewalls in an HA pair, moving "active" firewalls to a revisit list for post-upgrade actions. This workflow aligns with a common best practice of minimizing disruptions during upgrades. However, there are documented scenarios where upgrading the "active" firewall first is preferred. This enhancement aims to introduce flexibility into our upgrade process by allowing users to opt for a workflow that upgrades the "active" firewall first, thereby accommodating a broader range of upgrade strategies.

Enhancement Details

The proposed enhancement will introduce a new workflow option within the pan-os-upgrade script, enabling users to prioritize the upgrade of the "active" firewall in an HA pair. This workflow will involve:

  • Temporarily failing the HA state of the "active" firewall, prompting a failover to the "passive" firewall, which then becomes the new "active" member.
  • Initiating the upgrade process on the now "passive" firewall (formerly "active").
  • Upon successful upgrade and reboot of the first firewall, the script will proceed to upgrade the remaining firewalls, which are now in the "passive" state and were part of the initial "revisit" list.

Rationale

This enhancement is motivated by the need to provide a more versatile tool that accommodates various HA upgrade strategies documented across different best practices. It allows users to choose the upgrade sequence that best fits their operational requirements and risk management policies.

Use Cases

  • High Availability Environments: In environments where minimal downtime and immediate recovery are paramount, this option allows for a quicker return to full redundancy post-upgrade.
  • Compliance with Specific Upgrade Protocols: Certain network policies or compliance standards may dictate specific upgrade sequences for HA pairs, necessitating this flexible approach.

Implementation Considerations:

User Input: Introduce a command-line option or a configuration parameter allowing users to select the preferred upgrade workflow.
State Management: Ensure robust state management to handle failovers, upgrades, and potential rollback scenarios gracefully.
Documentation: Update the script documentation to clearly outline the new workflow, its use cases, and any additional steps required to initiate this upgrade path.

Potential Challenges

Risk of Downtime: Upgrading the "active" firewall first may entail a higher risk of temporary service disruption, which should be clearly communicated to the users.

Complexity in Rollback: In cases where the upgrade encounters issues, the rollback process may be more complex due to the involved failover and state changes.

Request for Comments

We invite feedback from the community on this proposed enhancement, particularly regarding its utility, potential impact on existing workflows, and any additional features that would make this option more effective for users' needs.

Enhancement: Replace `argparse` with `Click` for CLI Argument Handling in `pan-os-upgrade`

Title

Enhancement: Replace argparse with Click for CLI Argument Handling in pan-os-upgrade

Description

Feature Request:
Revamp the CLI argument handling in the pan-os-upgrade script by replacing the current argparse implementation with Click or a similar CLI builder tool.

Background:
The script currently uses argparse for parsing command-line arguments. While argparse is robust, tools like Click offer a more intuitive and decorator-based approach for creating complex CLI applications. This enhancement aims to leverage the additional functionalities and ease of development provided by these modern CLI frameworks.

Proposed Solution:

  • Integrate Click (or a similar tool) into the pan-os-upgrade script.
  • Refactor the current argument parsing logic to align with Click's decorator-based system.
  • Ensure that all existing command-line functionalities are preserved and enhanced with the new implementation.
  • Update the documentation to reflect changes in the way commands and options are used.
  • Test thoroughly to ensure backward compatibility and to identify any breaking changes for existing users.

Benefits:

  • Improved Code Readability and Maintainability: Using a decorator-based approach makes the code more readable and easier to maintain.
  • Enhanced User Experience: Provides a more intuitive command-line interface, potentially with better help prompts and error messages.
  • Feature-Rich: Click offers out-of-the-box support for things like nested commands and environment variable parsing, which can enrich the tool's functionality.
  • Easier Future Enhancements: Adding new features or modifying existing ones becomes simpler with a more streamlined CLI framework.

Additional Considerations:

  • Ensuring the transition to Click does not introduce regressions or significantly alter the expected behavior for current users.
  • Providing a detailed changelog and documentation to aid users in transitioning to the new CLI format.

This enhancement would modernize the pan-os-upgrade tool's command-line interface, making it more user-friendly and easier to maintain and extend in the future.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.