Skip to main content

Practical Applications of cvpysdk

This blog post will dive deep into cvpysdk, exploring its capabilities and showcasing advanced examples to supercharge your Commvault automation efforts.

Key Benefits of Using cvpysdk

  • Simplified Automation: Easily create scripts for complex, repetitive tasks.
  • Integration Capabilities: Seamlessly integrate Commvault operations into your existing Python applications or workflows.
  • Customization: Build custom tools and reports tailored to your organization's specific needs.
  • Efficiency: Perform bulk operations and complex queries with ease.

Practical Examples

Let's explore some practical examples that showcase how cvpysdk can be used to simplify common Commvault administration tasks.

1. Bulk Client Backup

This script performs a backup for all clients with a specific OS type:

from cvpysdk.commcell import Commcell

def backup_all_clients_by_os_and_agent(commcell, os_type, agent_type):
clients = commcell.clients.all_clients
for client_name in clients:
client_obj = commcell.clients.get(client_name)
if os_type.lower() in client_obj.os_info.lower():
print(f"Starting backup for client: {client_name}")
try:
agent = client_obj.agents.get(agent_type)
backupset = agent.backupsets.get('defaultBackupSet')
backupset.backup()
print(f"Backup initiated successfully for {client_name}")
except Exception as e:
print(f"Failed to start backup for {client_name}. Error: {str(e)}")

# Usage
commcell = Commcell("server_hostname", "username", "password")
backup_all_clients_by_os_and_agent(commcell, "windows", "File System")

This script iterates through all clients, checks their OS type, and initiates a backup for matching clients.

2.Check Readiness Report

This example generates a simple report of check readiness of all clients:

from cvpysdk.commcell import Commcell

def check_client_readiness(commcell):
"""Retrieve and display formatted readiness details for all clients."""
print("Client Readiness Details")
print("-------------------------")
try:
clients = commcell.clients.all_clients
for client_name in clients:
client_obj = commcell.clients.get(client_name)
readiness_details = client_obj.readiness_details.get_detail()

print(f"Client Name: {client_name}")
print(" Readiness Details:")
for detail in readiness_details:
print(f" Compression: {detail['Compression']}")
print(f" MediaAgent: {detail['MediaAgent']}")
print(f" Deduplication: {detail['Deduplication']}")
print(f" Readiness Status: {detail['ReadinessStatus'].strip()}")
print(f" Storage Policy: {detail['StoragePolicy']}")
subclient_info = detail['Subclient']
print(f" Subclient: {subclient_info['entityName']}")
print()

except Exception as e:
print(f"Failed to retrieve client readiness details. Error: {str(e)}")

# Usage
commcell = Commcell("server_name", "username", "password")
check_client_readiness(commcell)

This example demonstrates how to use the cvpysdk to retrieve and display detailed readiness information for clients, which helps in understanding their configuration and operational status within the Commvault infrastructure.

3. Find Subclients Without Recent Backups

This example identifies subclients that haven't had a successful backup in the last 24 hours:

from cvpysdk.commcell import Commcell
from datetime import datetime, timedelta

def find_subclients_without_recent_backups(commcell, hours=24):
print(f"Subclients without successful backups in the last {hours} hours:")
print("---------------------------------------------------------------")

check_time = datetime.now() - timedelta(hours=hours)

try:
all_jobs = commcell.job_controller.all_jobs() # Get all jobs

for client_name in commcell.clients.all_clients:
client = commcell.clients.get(client_name)
for agent_name in client.agents.all_agents:
agent = client.agents.get(agent_name)
for backupset_name in agent.backupsets.all_backupsets:
backupset = agent.backupsets.get(backupset_name)
for subclient_name in backupset.subclients.all_subclients:
subclient = backupset.subclients.get(subclient_name)
subclient_jobs = [
job for job_id, job in all_jobs.items()
if job["client_name"] == client_name and
job["status"].lower() == "completed" and
datetime.fromtimestamp(job["job_start_time"]) > check_time
]
if not subclient_jobs:
print(f"Client: {client_name}")
print(f" Agent: {agent_name}")
print(f" Backupset: {backupset_name}")
print(f" Subclient: {subclient_name}")
print()

except Exception as e:
print(f"Failed to retrieve subclient backup history. Error: {str(e)}")

# Usage
commcell = Commcell("server_name", "username", "password")
find_subclients_without_recent_backups(commcell, hours=24)

This script helps identify potential backup issues by listing subclients that haven't had a successful backup recently.

4. Job Monitoring and Management

This example demonstrates how to use the jobs module in cvpysdk to monitor and manage jobs in a Commvault environment. It includes functions to list recent jobs, monitor active jobs, and perform actions on jobs such as suspending and restarting.

from cvpysdk.commcell import Commcell
from cvpysdk.job import Job
from cvpysdk.exception import SDKException
import time

def list_recent_jobs(commcell, limit=10):
"""List the most recent jobs."""
print(f"\nLast {limit} jobs:")
print("-----------------")
jobs = commcell.job_controller.all_jobs(
days=1, # Jobs from the last 24 hours
limit=limit,
lookup_time=0 # 0 for start time, 1 for end time
)

for job in jobs:
print(f"Job ID: {job['jobId']}")
print(f" Job Type: {job['jobType']}")
print(f" Status: {job['status']}")
print(f" Start Time: {job['startTime']}")
print(f" End Time: {job['endTime'] if job['endTime'] else 'Still running'}")
print()

def monitor_active_jobs(commcell, interval=30, duration=300):
"""Monitor active jobs for a specified duration."""
print("\nMonitoring active jobs:")
print("------------------------")
end_time = time.time() + duration

while time.time() < end_time:
active_jobs = commcell.job_controller.active_jobs
print(f"\nActive jobs as of {time.ctime()}:")
for job in active_jobs:
print(f"Job ID: {job['jobId']}, Type: {job['jobType']}, Status: {job['status']}")

time.sleep(interval)

def manage_job(commcell, job_id, action):
"""Manage a specific job (suspend, resume, or kill)."""
try:
job = Job(commcell, job_id)
if action == "suspend":
job.suspend()
print(f"Job {job_id} suspended successfully.")
elif action == "resume":
job.resume()
print(f"Job {job_id} resumed successfully.")
elif action == "kill":
job.kill()
print(f"Job {job_id} killed successfully.")
else:
print("Invalid action. Choose 'suspend', 'resume', or 'kill'.")
except SDKException as e:
print(f"Error managing job {job_id}: {str(e)}")

# Usage
commcell = Commcell("server_name", "username", "password")

# List recent jobs
list_recent_jobs(commcell, limit=5)

# Monitor active jobs for 2 minutes, checking every 30 seconds
monitor_active_jobs(commcell, interval=30, duration=120)

# Manage a specific job (replace job_id with an actual job ID from your environment)
# manage_job(commcell, job_id=123456, action="suspend")
# time.sleep(10) # Wait for 10 seconds
# manage_job(commcell, job_id=123456, action="resume")

Conclusion

These practical examples demonstrate how the Commvault Python SDK (cvpysdk) can be used to automate common administrative tasks and generate useful reports. By leveraging cvpysdk, you can:

  1. Perform bulk operations across multiple clients
  2. Generate reports on storage usage and backup status
  3. Identify potential issues in your backup environment

These scripts can be easily modified and expanded to suit your specific needs. As you become more comfortable with cvpysdk, you'll find many more ways to streamline your Commvault administration tasks and improve your overall data protection strategy.

Remember to always follow best practices for error handling, logging, and security when developing scripts for production use. Happy scripting!