Untitled

Anonymous
Plain Text
10/17/2025 2:13 AM
10.6 KB
24
Indexable
Never
import argparse
import subprocess
import json
import datetime
import os
from concurrent.futures import ThreadPoolExecutor, as_completed

def run_command(command):
    """Run a shell command and return the output."""
    try:
        output = subprocess.check_output(command, shell=True)
        return output.decode('utf-8').strip()
    except subprocess.CalledProcessError as e:
        print(f"Failed to run command: {command}")
        print(f"Error: {e}")
        return None

def run_command_list(args):
    """Run a command with a list of arguments to avoid shell parsing issues."""
    try:
        output = subprocess.check_output(args)
        return output.decode('utf-8').strip()
    except subprocess.CalledProcessError as e:
        print(f"Failed to run command: {' '.join(args)}")
        print(f"Error: {e}")
        return None

def check_state_history_exists(rack_serial, device_serial):
    """Check if state_history.json exists for a specific rack_serial/device_serial combination."""
    bucket_name = "burninator_orchestrator"
    namespace = "axi697ybxm4m"
    object_name = f"{rack_serial}/{device_serial}/state_history.json"
    cmd = [
        "oci", "os", "object", "head",
        "--bucket-name", bucket_name,
        "--namespace", namespace,
        "--name", object_name,
        "--profile", "BOAT",
        "--auth", "security_token"
    ]
    try:
        subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except subprocess.CalledProcessError:
        return False

def download_state_history(rack_serial, device_serial, save_dir):
    """Download state_history.json file for a specific rack_serial/device_serial combination."""
    bucket_name = "burninator_orchestrator"
    namespace = "axi697ybxm4m"
    object_name = f"{rack_serial}/{device_serial}/state_history.json"
    local_path = os.path.join(save_dir, "state_history.json")
    os.makedirs(save_dir, exist_ok=True)
    cmd = [
        "oci", "os", "object", "get",
        "--bucket-name", bucket_name,
        "--namespace", namespace,
        "--name", object_name,
        "--file", local_path,
        "--profile", "BOAT",
        "--auth", "security_token"
    ]
    try:
        subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        print(f"Downloaded state_history.json for {rack_serial}/{device_serial}")
    except subprocess.CalledProcessError as e:
        print(f"Error downloading {object_name}: {e.stderr}")

def threaded_download_state_histories(download_tasks, max_workers=8):
    """Run downloads in parallel using threads."""
    print(f"Starting threaded download of {len(download_tasks)} state history files...")
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = [
            executor.submit(download_state_history, rack_serial, device_serial, save_dir)
            for (rack_serial, device_serial, save_dir) in download_tasks
        ]
        for future in as_completed(futures):
            try:
                future.result()
            except Exception as e:
                print(f"Exception during threaded download: {e}")
    print("Download completed!")

def get_repair_order_details(repair_order_id):
    """Get repair order details using burninatorOps.py command."""
    repair_json_command = f"python3 ../../burninator_ops/burninatorOps.py repair get -id '{repair_order_id}'"
    repair_json_output = run_command(repair_json_command)

    if repair_json_output is None:
        return None

    try:
        repair_json = json.loads(repair_json_output)
    except json.JSONDecodeError:
        print(f"Failed to parse repair_json output: {repair_json_output}")
        return None

    return repair_json


def get_device_details(device_serial):
    """Get device details using burninatorOps.py command."""
    device_command = f"python3 ../../burninator_ops/burninatorOps.py device get -s '{device_serial}'"
    device_output = run_command(device_command)

    if device_output is None:
        return None

    try:
        device_json = json.loads(device_output)
    except json.JSONDecodeError:
        print(f"Failed to parse device_json output: {device_output}")
        return None

    return device_json


def process_query_results(results):
    """Process query results to extract device serials and rack serials."""
    rack_serial_device_serials = {}
    tickets_processed = 0
    download_tasks = []
    scheduled = set()  # to dedupe (rack_serial, device_serial)
    
    for result in results.split('\n'):
        try:
            if result.startswith('ROMAOPS'):
                fields = result.split(',')
                if len(fields) >= 4:
                    key = fields[0]
                    title = fields[1]
                    rack_position = fields[2]
                    repair_order_id = fields[3].strip()

                    print(f"Processing result: {result}")
                    print(f"Key: {key}, Title: {title}, Rack Position: {rack_position}, Repair Order ID: {repair_order_id}")

                    if repair_order_id:
                        repair_details = get_repair_order_details(repair_order_id)
                        if repair_details:
                            device_serial = repair_details.get('deviceSerial')

                            if device_serial:
                                print(f"Device Serial: {device_serial}")
                                
                                # Get device details to get rack serial
                                device_details = get_device_details(device_serial)
                                if device_details:
                                    rack_serial = device_details.get('rackSerial')
                                    print(f"Rack Serial: {rack_serial}")
                                    
                                    # Store the mapping
                                    if rack_serial in rack_serial_device_serials:
                                        rack_serial_device_serials[rack_serial].append(device_serial)
                                    else:
                                        rack_serial_device_serials[rack_serial] = [device_serial]
                                    
                                    # Check if state history file exists and create download task
                                    if (rack_serial, device_serial) not in scheduled:
                                        if check_state_history_exists(rack_serial, device_serial):
                                            save_dir = os.path.join("state_history_downloads", rack_serial, device_serial)
                                            download_tasks.append((rack_serial, device_serial, save_dir))
                                            scheduled.add((rack_serial, device_serial))
                                            print(f"Added download task for {rack_serial}/{device_serial}")
                                        else:
                                            print(f"State history file not found for {rack_serial}/{device_serial}")
                                    
                                    tickets_processed += 1
                                    print(f"Successfully processed ticket {key}")
                                else:
                                    print(f"Failed to get device details for {device_serial}")
                            else:
                                print("No device serial found in repair order")
                        else:
                            print("Failed to get repair order details")
                    else:
                        print("No repair order ID found in ticket")
                    
                    print("-" * 80)
                else:
                    print(f"Skipping malformed result: {result}")
        except Exception as e:
            print(f"Skipping ticket entry: {result}")
            print(f"Failure cause: {e}")

    print(f"Total tickets processed: {tickets_processed}")
    print(f"Total download tasks collected: {len(download_tasks)}")
    return rack_serial_device_serials, download_tasks


def query_gpu_mismatch_tickets():
    """Query tickets for GPU count mismatch issues using burninatorOps.py directly."""
    query = 'Project = ROMAOPS and ("Searchable Data" ~ "HandedOver" or Title ~ "ROMA_CUSTOMER") and status in ("Resolved", "Closed","Done","Pending Customer") and (Description ~ "gpu_count_mismatch") AND "component" = "ROMA-Ingestion"'
    
    # Use burninatorOps.py command with list of arguments to avoid shell parsing issues
    args = [
        'python3', 
        '../../burninator_ops/burninatorOps.py', 
        'ots', 
        'query', 
        '-q', query,
        '-f', 'key,title,rack_position,repair_order_id,component,status,searchable_data,labels'
    ]
    
    command_str = ' '.join(args)
    print(f"Running query with command: \n    {command_str}")
    results = run_command_list(args)
    
    if results is None:
        print("Failed to get query results")
        return
    
    print("Query results:")
    print(results)
    print("=" * 80)
    
    # Process the results to get device serials and rack serials
    rack_serial_device_serials, download_tasks = process_query_results(results)
    
    # Print summary
    print(f"\nSummary:")
    print(f"Found {len(rack_serial_device_serials)} unique rack serials")
    for rack_serial, device_serials in rack_serial_device_serials.items():
        print(f"Rack Serial: {rack_serial} -> Device Serials: {device_serials}")
    
    # Download state history files for all tickets
    if download_tasks:
        print(f"\nDownloading state history files for {len(download_tasks)} folders...")
        threaded_download_state_histories(download_tasks, max_workers=8)
    else:
        print("\nNo state history files to download.")
    
    return rack_serial_device_serials, download_tasks


def main(csv_file_path):
    print(f"The Script output path: {csv_file_path}")
    # Query tickets for GPU count mismatch issues and get deviceSerial and rackSerial
    result = query_gpu_mismatch_tickets()
    if result:
        rack_serial_device_serials, download_tasks = result
        print(f"\nFinal Summary:")
        print(f"Processed {len(rack_serial_device_serials)} rack serials")
        print(f"Downloaded state history files for {len(download_tasks)} folders")
        print(f"Files saved in: state_history_downloads/")
    else:
        print("No results to process.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='KPI Analysis Script')
    parser.add_argument('--csv_file_path', type=str, help='Path to CSV files', required=True)
    args = parser.parse_args()
    main(args.csv_file_path)
Editor is loading...
Leave a Comment