{"id":29600665,"url":"https://github.com/nerdcopter/opendrs","last_synced_at":"2025-07-20T12:07:41.680Z","repository":{"id":305024358,"uuid":"1020897286","full_name":"nerdCopter/OpenDRS","owner":"nerdCopter","description":"Open-source PowerShell alternative to VMware DRS for analyzing cluster health and executing intelligent VM migrations with maintenance mode evacuation support.","archived":false,"fork":false,"pushed_at":"2025-07-17T18:50:36.000Z","size":38,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-07-17T22:21:06.758Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PowerShell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nerdCopter.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-16T15:01:06.000Z","updated_at":"2025-07-17T18:50:39.000Z","dependencies_parsed_at":"2025-07-18T00:46:58.851Z","dependency_job_id":"288acf6f-06a4-4b1f-bff7-86754172820d","html_url":"https://github.com/nerdCopter/OpenDRS","commit_stats":null,"previous_names":["nerdcopter/opendrs"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/nerdCopter/OpenDRS","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerdCopter%2FOpenDRS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerdCopter%2FOpenDRS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerdCopter%2FOpenDRS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerdCopter%2FOpenDRS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nerdCopter","download_url":"https://codeload.github.com/nerdCopter/OpenDRS/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerdCopter%2FOpenDRS/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266120910,"owners_count":23879410,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-20T12:07:37.543Z","updated_at":"2025-07-20T12:07:41.669Z","avatar_url":"https://github.com/nerdCopter.png","language":"PowerShell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# OpenDRS Scripts\n**Version 1.0.0**\n\n## 1. Project Purpose\n\nThis project provides a set of PowerShell scripts for analyzing and executing VMware vSphere Distributed Resource Scheduler (DRS) recommendations for compute resources. The scripts are designed to respect VMware's VM/Host Rules and Groups, focusing exclusively on VM-to-host migration logic. Datastore migration is not part of this toolset.\n\n---\n\n## 2. Architecture\n\nThe project consists of a modular, two-part system to separate analysis from execution:\n\n*   **`Get-OpenDrsRecommendation.ps1`**: A read-only \"engine\" that analyzes cluster health and generates migration recommendations.\n*   **`Invoke-OpenDrsMigration.ps1`**: An \"executor\" that consumes recommendations from the analysis engine and performs the actual VM migrations.\n\n### 2.1. Important: Not a Direct VMware DRS Replacement\n\n**This toolset is NOT a 1:1 equivalent of VMware's integrated DRS or PowerCLI's `Get-DrsRecommendation`/`Invoke-DrsRecommendation` cmdlets.** Key differences include:\n\n*   **Real-time Analysis Only**: Uses current host utilization (`QuickStats`) rather than historical data or saved statistics that VMware DRS leverages for trend analysis.\n*   **Custom Algorithm**: Implements independent load balancing logic based on standard deviation analysis, not VMware's proprietary DRS algorithms.\n*   **VM Count-Based Balancing**: The `-Balance` parameter distributes VMs based on quantity (count) across hosts, prioritizing migration of smallest VMs first, rather than resource-weighted distribution.\n*   **Potential Conflicts**: Since this operates independently of VMware DRS, recommendations may occasionally conflict with or counteract VMware's native DRS decisions, especially when both systems are active simultaneously.\n\n### 2.2. Connection Management and Maintenance Mode Detection\n\nBoth scripts feature intelligent connection management - they detect existing vCenter connections and only connect/disconnect when necessary. This enables efficient chaining and variable assignment workflows.\n\nThe scripts automatically detect hosts in maintenance mode or entering maintenance mode and generate evacuation recommendations that take priority over normal DRS analysis. Maintenance mode evacuations bypass all rules and ensure rapid VM evacuation.\n\n---\n\n## 3. Script Roles and Behaviors\n\n### 3.1. Get-OpenDrsRecommendation.ps1 (The Engine)\n\n*   **Role:**  \n    The primary analysis engine. It is strictly **read-only** and makes no changes to the vSphere environment.\n*   **Behavior:**  \n    Connects to vCenter, analyzes cluster health using standard deviation analysis, and generates migration recommendations while respecting VM/Host rules. Automatically detects maintenance mode hosts and generates evacuation recommendations.\n*   **Parameters:**\n    *   `-vCenterServer` (string, Required): FQDN or IP address of the vCenter Server.\n    *   `-Clusters` (string[], Optional): Specify one or more cluster names to analyze. If not provided, all clusters are analyzed.\n    *   `-MigrationThreshold` (integer, 1–5): Controls the aggressiveness of recommendations (1=conservative, 5=aggressive). Defaults to 3.\n    *   `-Balance` (switch): Generates load balancing recommendations to evenly distribute VMs across hosts, even when hosts are not resource-constrained. Useful for clusters with uneven VM distribution. Excludes vCLS (vSphere Cluster Services) VMs from balancing calculations.\n    *   `-BypassHostRulesAndGroups` (switch): If set, recommendations will ignore all VM/Host affinity and anti-affinity rules.\n    *   `-ExportToCsv` (switch): Exports recommendations to a timestamped CSV file when recommendations exist.\n    *   `-Quiet` (switch): Suppresses console output for variable assignment workflows.\n    *   `-NoDisconnect` (switch): Internal parameter to prevent disconnecting from vCenter when called by other scripts.\n*   **Output:**  \n    Returns an array of `PSCustomObject`s representing migration recommendations. Displays complete cluster analysis including host utilization, cluster balance statistics, and recommendation tables.\n\n### 3.2. Invoke-OpenDrsMigration.ps1 (The Executor)\n\n*   **Role:**  \n    Executes the VM migrations recommended by the analysis engine. This is the only script that performs **write operations**. Supports variable assignment for direct consumption of recommendations.\n*   **Behavior:**  \n    1.  If used independently, calls `Get-OpenDrsRecommendation.ps1` internally.\n    2.  If used with variable assignment, accepts recommendation objects directly from `Get-OpenDrsRecommendation.ps1`.\n    3.  If CSV file is provided, loads recommendations from file instead of calling the analysis engine.\n    4.  Executes `Move-VM` operations with high vMotion priority for each recommendation.\n    5.  Logs the success or failure of each migration attempt.\n*   **Parameters:**\n    *   `-vCenterServer` (string): FQDN or IP address of the vCenter Server (required for independent use, optional for variable assignment workflows).\n    *   `-Clusters` (string[], Optional): Specify one or more cluster names to analyze. Passthrough parameter for the analysis engine.\n    *   `-CsvFile` (string): Path to a CSV file containing migration recommendations. When provided, the script loads recommendations from this file instead of calling the analysis engine.\n    *   `-ExportToCsv` (switch): Passthrough parameter for the analysis engine.\n    *   `-Balance` (switch): Passthrough parameter for the analysis engine.\n    *   `-BypassHostRulesAndGroups` (switch): Passthrough parameter for the analysis engine.\n    *   `-MigrationThreshold` (integer, 1–5): Passthrough parameter for the analysis engine.\n    *   `-WhatIf`, `-Confirm`: Natively supported via `CmdletBinding` to allow users to preview actions before execution.\n*   **Output:**  \n    Displays migration execution status and results for each recommendation processed.\n\n---\n\n## 4. Usage Examples\n\n### Analyze all clusters without making changes:\n```powershell\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\"\n```\n\n### Analyze specific cluster only:\n```powershell\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\"\n```\n\n### Analyze multiple specific clusters:\n```powershell\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\",\"Backup Cluster\"\n```\n\n### Execute migrations for specific cluster with confirmation:\n```powershell\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\"\n```\n\n### Preview migrations for specific clusters without executing:\n```powershell\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Cluster1\",\"Cluster2\" -WhatIf\n```\n\n### Aggressive analysis of specific cluster with CSV export:\n```powershell\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -MigrationThreshold 5 -ExportToCsv\n```\n\n### Load balancing for specific cluster:\n```powershell\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -Balance\n```\n\n### Execute load balancing migrations for specific cluster:\n```powershell\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -Balance\n```\n\n### Variable assignment workflow for efficient processing of specific clusters:\n```powershell\n$recommendations = .\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -Quiet -NoDisconnect\nif ($recommendations) { .\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" }\n```\n\n### Execute migrations from CSV file:\n```powershell\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -CsvFile \"20250716-143022-drs_recommendations.csv\"\n```\n\n### Preview migrations from CSV file:\n```powershell\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -CsvFile \"recommendations.csv\" -WhatIf\n```\n\n### Advanced cluster-specific workflows:\n```powershell\n# Generate recommendations for production clusters only, then execute with confirmation\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Prod-Cluster-01\",\"Prod-Cluster-02\" -MigrationThreshold 4 -ExportToCsv\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Prod-Cluster-01\",\"Prod-Cluster-02\" -Confirm\n\n# Targeted load balancing for specific cluster with aggressive threshold\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Backup Cluster\" -Balance -MigrationThreshold 5 -WhatIf\n```\n\n## 4.1. Invoke-OpenDrsMigration.ps1 Parameter Behavior\n\nThe `Invoke-OpenDrsMigration.ps1` script supports different execution modes through PowerShell's `ShouldProcess` framework:\n\n| Parameters | Analysis | Recommendations | CSV Export | VM Migration | Prompts |\n|------------|----------|----------------|------------|--------------|---------|\n| `(none)` | ✅ Shows | ✅ Shows | ❌ N/A | ✅ Executes | ❌ No prompts |\n| `-WhatIf` | ✅ Shows | ✅ Shows | ❌ N/A | ❌ Simulated | ❌ No prompts |\n| `-Confirm` | ✅ Shows | ✅ Shows | ❌ N/A | ✅ Executes | ✅ **Prompts for each VM** |\n| `-ExportToCsv` | ✅ Shows | ✅ Shows | ✅ Executes* | ✅ Executes | ❌ No prompts |\n| `-ExportToCsv -WhatIf` | ✅ Shows | ✅ Shows | ✅ Executes* | ❌ Simulated | ❌ No prompts |\n| `-ExportToCsv -Confirm` | ✅ Shows | ✅ Shows | ✅ Executes* | ✅ Executes | ✅ **Prompts for each VM** |\n| `-ExportToCsv -Confirm -WhatIf` | ✅ Shows | ✅ Shows | ✅ Executes* | ❌ Simulated | ✅ **Prompts for each VM** |\n\n*CSV Export is handled by the analysis engine (`Get-OpenDrsRecommendation.ps1`)\n\n**Key Points:**\n- **Analysis and Recommendations** always display regardless of parameters\n- **CSV Export** is handled by the analysis engine (`Get-OpenDrsRecommendation.ps1`) when `-ExportToCsv` is passed through\n- **`-WhatIf`** simulates VM migrations but does NOT affect CSV export behavior (CSV is still created)\n- **`-Confirm`** prompts separately for each VM migration (CSV export prompting is handled by the analysis engine)\n- **`-ExportToCsv -Confirm -WhatIf`** creates CSV file and only simulates VM migrations\n\n## 4.2. Maintenance Mode Evacuation\n\nThe scripts automatically detect hosts in maintenance mode or entering maintenance mode and generate evacuation recommendations that bypass all DRS rules and affinity groups.\n\n### Detection Method\n- **Hosts in Maintenance Mode**: `ConnectionState -eq 'Maintenance'`\n- **Hosts Entering Maintenance Mode**: Uses `Get-Task -Status Running` to find active \"EnterMaintenanceMode\" tasks\n\n### Evacuation Behavior\n- **Processing Order**: Evacuation recommendations are processed first\n- **Rule Bypassing**: All VM/Host affinity rules and groups are automatically bypassed for evacuations\n- **VM Support**: Handles both powered-on (vMotion) and powered-off (cold migration) VMs\n- **Load Balancing**: Distributes evacuated VMs across available hosts\n- **Combined Analysis**: Both evacuation and normal DRS recommendations are generated and included in the output\n\n### Examples\n```powershell\n# Check for maintenance mode evacuations in specific cluster\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -Verbose\n\n# Execute evacuations with preview for specific cluster\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -WhatIf\n```\n\n### Output Format\nEvacuation recommendations include:\n- `Reason`: \"Maintenance Evacuation\"\n- Console output displays evacuation recommendations clearly in tables\n- Both evacuation and normal DRS recommendations are combined in the final output\n\n## 4.3. CSV Export and Recommendation Types\n\nWhen using `-ExportToCsv`, all recommendation types are exported to a single timestamped CSV file:\n\n### Recommendation Types in CSV:\n1. **Evacuation Recommendations**: `Reason` = \"Maintenance Evacuation\"\n2. **Standard DRS Recommendations**: `Reason` = \"High CPU/Mem on source\"  \n3. **Load Balancing Recommendations**: `Reason` = \"Load Balancing\"\n\n### CSV File Format:\n- **Filename**: `YYYYMMDD-HHMMSS-drs_recommendations.csv`\n- **Location**: Same directory as the script\n- **Contents**: All recommendation types combined in a single file\n- **Columns**: Cluster, VM_to_Move, Reason, Source_Host, Source_Host_CPU, Source_Host_Mem, Recommended_Destination_Host, Destination_Host_CPU, Destination_Host_Mem\n\n### Example:\n```powershell\n# Export all types of recommendations to CSV for specific cluster\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter.domain.com\" -Clusters \"Production Cluster\" -Balance -ExportToCsv\n```\n\n---\n\n## 5. Advanced Features\n\n### 5.1. Cluster Filtering\nBoth scripts support targeted analysis by specifying specific clusters:\n\n- **Default Behavior**: Analyze all clusters when no `-Clusters` parameter is specified\n- **Single Cluster**: `-Clusters \"Production Cluster\"` to analyze only one cluster\n- **Multiple Clusters**: `-Clusters \"Cluster1\",\"Cluster2\"` to analyze specific clusters\n- **Exact Matching**: Cluster names must match exactly (case-sensitive)\n- **Error Handling**: Clear error messages when specified clusters are not found\n\n**Benefits:**\n- **Focused Analysis**: Target specific clusters without analyzing entire infrastructure\n- **Reduced Scope**: Faster execution when working with large vCenter environments\n- **Operational Safety**: Limit operations to specific clusters for controlled changes\n- **Resource Efficiency**: Minimize vCenter API calls and processing time\n\n### 5.2. Smart Connection Management\nBoth scripts intelligently manage vCenter connections:\n- **Reuse existing connections** when already connected to the target server\n- **Only connect when necessary**, avoiding unnecessary disconnection/reconnection cycles  \n- **Independent operation** - each script manages its own connection lifecycle\n- **Clear status messages** indicating connection decisions\n\n### 5.3. Variable Assignment Support\nThe scripts support efficient chaining using PowerShell variable assignment:\n```powershell\n# Efficient chaining with quiet analysis output for all clusters\n$recommendations = .\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter\" -Quiet -NoDisconnect\nif ($recommendations) { .\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter\" }\n\n# Efficient chaining for specific clusters\n$recommendations = .\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter\" -Clusters \"Production Cluster\" -Quiet -NoDisconnect\nif ($recommendations) { .\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter\" }\n\n# Traditional separate execution (shows full analysis output)\n.\\Get-OpenDrsRecommendation.ps1 -vCenterServer \"vcenter\" -Clusters \"Production Cluster\"\n.\\Invoke-OpenDrsMigration.ps1 -vCenterServer \"vcenter\" -Clusters \"Production Cluster\"\n```\n\nThe `-Quiet` parameter suppresses console output from the analysis engine while preserving all returned recommendation objects. Both scripts share vCenter connections efficiently, avoiding unnecessary reconnections.\n\n---\n\n## 6. Requirements\n\n*   **VMware PowerCLI**: Must be installed and available (VMware.PowerCLI or VCF.PowerCLI)\n*   **vCenter Access**: Appropriate permissions for VM migration operations\n*   **PowerShell**: Windows PowerShell 5.1 or later\n\n---\n\n## 7. Technical Details\n\n### 7.1. Algorithm Implementation\n\n**Important**: These scripts implement a custom DRS-like algorithm that is **not equivalent** to VMware's native DRS engine. Key technical differences:\n\n**Data Source:**\n- Uses real-time vSphere `QuickStats` data (current CPU/memory utilization)\n- Does NOT use historical performance data or saved statistics that VMware DRS leverages\n- No trend analysis or predictive modeling capabilities\n\n**Analysis Methods:**\n\n**Cluster Filtering:**\n- Analyze all clusters when no `-Clusters` parameter is specified (default behavior)\n- Analyze only specified clusters when `-Clusters` parameter is provided with one or more cluster names\n- Supports exact cluster name matching for precise targeting\n\n**Standard DRS Analysis:**\n- Calculate average CPU and memory utilization across cluster hosts using standard deviation analysis\n- Identify hosts exceeding threshold based on standard deviation multiplier (configurable via `-MigrationThreshold`)\n- Generate recommendations to move VMs from over-utilized to under-utilized hosts\n- Moves largest VMs first during standard DRS analysis\n\n**Load Balancing Analysis (when `-Balance` is specified):**\n- Count VMs per host, excluding vCLS (vSphere Cluster Services) VMs\n- Calculate ideal distribution for even VM **count** (not resource-weighted) across hosts\n- Generate recommendations to achieve balanced VM distribution regardless of resource utilization\n- **Moves smallest VMs first** to optimize distribution efficiency\n- May conflict with resource-based recommendations from VMware's native DRS\n\n**Rule Compliance:**\n- Respect all VM/Host affinity rules and VM anti-affinity rules unless bypassed\n- Automatically exclude hosts in maintenance mode from all analysis and operations\n\n**Coexistence Considerations:**\n- When VMware DRS is enabled and set to automatic mode, recommendations from this toolset may occasionally conflict with VMware's native DRS decisions\n- Both systems operate independently and may attempt to optimize for different criteria simultaneously\n- Consider VMware DRS automation level and cluster configuration when using this toolset\n\n### 7.2. Rule Compliance\n- **VM/Host Affinity Rules**: VMs required to run on specific host groups are only migrated within those groups\n- **VM/Host Anti-Affinity Rules**: VMs forbidden from specific host groups are never migrated to those hosts\n- **VM Anti-Affinity Rules**: VMs marked to separate are never placed on the same host\n- **Keep Together Rules**: VM groups marked for affinity are migrated as complete units\n\n### 7.3. Safety Features\n- Read-only analysis engine prevents accidental modifications\n- WhatIf support allows previewing all operations\n- Comprehensive rule validation before any migration\n- High vMotion priority for reliable migrations\n- Detailed logging of all operations and failures\n\n### 7.4. Tested Versions\n- **PowerShell 7.5.2** (Primary testing platform)\n- **PowerShell 5.1.26100.4652** (Windows PowerShell compatibility)  \n- **VMware PowerCLI 13.3.0** (build 24145083)\n- **VMware vCenter Server 8.0.3.00500**\n- **VMware ESXi 8.0.3** (build 24674464)\n- **VMware ESXi 7.0.3** (build 24723872)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnerdcopter%2Fopendrs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnerdcopter%2Fopendrs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnerdcopter%2Fopendrs/lists"}