Total Pageviews

Saturday, August 22, 2026

Update Java using python script (Python 2.6.6 compatible script)

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import csv
import tarfile
import shutil
import subprocess
from datetime import datetime

# ============================================================
# CONFIGURATION
# ============================================================
CSV_FILE = "/home/oracle/Desktop/jdk_servers.csv"
JDK_TAR = "/home/oracle/Desktop/jdk-8u501-linux-x64.tar.gz"
LOG_FILE = "/home/oracle/Desktop/jdk_upgrade.log"

# ============================================================
# Logging
# ============================================================
def log(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    msg = "[{0}] {1}".format(timestamp, message)
    print msg
    try:
        logfile = open(LOG_FILE, "a")
        logfile.write(msg + "\n")
        logfile.close()
    except Exception:
        pass

# ============================================================
# Execute local command
# ============================================================
def execute_command(command):
    log("Executing: {0}".format(command))
    process = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    output = process.communicate()[0]
    try:
        output = output.decode("utf-8")
    except Exception:
        pass
    output = output.strip()
    if output:
        log(output)
    return process.returncode, output

# ============================================================
# Check JDK tar file
# ============================================================
def check_jdk_tar():
    log("Checking JDK package...")
    if not os.path.isfile(JDK_TAR):
        log("ERROR: JDK package not found:")
        log(JDK_TAR)
        return False
    log("JDK package found: {0}".format(JDK_TAR))
    try:
        tar = tarfile.open(JDK_TAR, "r:gz")
        tar.close()
    except Exception as error:
        log(
            "ERROR: Invalid JDK tar file: {0}".format(error)
        )
        return False
    return True

# ============================================================
# Check current JDK
# ============================================================
def check_current_jdk(jdk_path):
    java_path = os.path.join(
        jdk_path,
        "bin",
        "java"
    )
    if not os.path.isfile(java_path):
        log(
            "ERROR: Java binary not found: {0}".format(
                java_path
            )
        )
        return False, "UNKNOWN"
    log("Current JDK version:")
    returncode, output = execute_command(
        "{0} -version".format(java_path)
    )
    if returncode != 0:
        return False, "UNKNOWN"
    return True, output

# ============================================================
# Get ownership
# ============================================================
def get_ownership(jdk_path):
    returncode, output = execute_command(
        "stat -c '%U:%G' '{0}'".format(jdk_path)
    )
    if returncode != 0:
        return None
    return output.strip()

# ============================================================
# Backup existing JDK
# ============================================================
def backup_jdk(jdk_path, backup_path):
    log("Backing up existing JDK...")
    if not os.path.isdir(jdk_path):
        log(
            "ERROR: JDK directory does not exist: {0}".format(
                jdk_path
            )
        )
        return False
    try:
        os.rename(
            jdk_path,
            backup_path
        )
        log(
            "JDK backup created: {0}".format(
                backup_path
            )
        )
        return True
    except Exception as error:
        log(
            "ERROR: Unable to backup JDK: {0}".format(
                error
            )
        )
        return False

# ============================================================
# Extract new JDK
# ============================================================
def extract_jdk(temp_path):
    log("Creating temporary directory:")
    log(temp_path)
    try:
        os.makedirs(temp_path)
    except Exception as error:
        log(
            "ERROR: Unable to create directory: {0}".format(
                error
            )
        )
        return False
    log("Extracting JDK...")
    try:
        tar = tarfile.open(
            JDK_TAR,
            "r:gz"
        )
        tar.extractall(
            temp_path
        )
        tar.close()
    except Exception as error:
        log(
            "ERROR: JDK extraction failed: {0}".format(
                error
            )
        )
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
        return False
    # --------------------------------------------------------
    # Handle top-level directory inside tar
    # --------------------------------------------------------
    try:
        contents = os.listdir(
            temp_path
        )
        if len(contents) == 1:
            first_item = os.path.join(
                temp_path,
                contents[0]
            )
            if os.path.isdir(first_item):
                log(
                    "JDK archive contains top-level directory: {0}".format(
                        contents[0]
                    )
                )
                items = os.listdir(first_item)
                for item in items:
                    source = os.path.join(
                        first_item,
                        item
                    )
                    destination = os.path.join(
                        temp_path,
                        item
                    )
                    shutil.move(
                        source,
                        destination
                    )
                os.rmdir(
                    first_item
                )
    except Exception as error:
        log(
            "ERROR processing extracted JDK: {0}".format(
                error
            )
        )
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
        return False
    return True

# ============================================================
# Verify extracted JDK BEFORE activation
# ============================================================
def verify_new_jdk(temp_path):
    java_path = os.path.join(
        temp_path,
        "bin",
        "java"
    )
    if not os.path.isfile(java_path):
        log(
            "ERROR: New Java binary not found."
        )
        return False, ""
    log("Checking NEW JDK before activation:")
    returncode, output = execute_command(
        "{0} -version".format(java_path)
    )
    if returncode != 0:
        log(
            "ERROR: New JDK Java execution failed."
        )
        return False, output
    # --------------------------------------------------------
    # Check that this is JDK 8u501
    # --------------------------------------------------------
    if "1.8.0_501" not in output:
        log(
            "WARNING: Expected JDK version 1.8.0_501."
        )
        log(
            "Actual version output:"
        )
        log(output)
        return False, output
    log(
        "New JDK version 1.8.0_501 verified."
    )
    return True, output

# ============================================================
# Set ownership
# ============================================================
def set_ownership(path, ownership):
    if not ownership:
        return True
    log(
        "Setting ownership {0} on {1}".format(
            ownership,
            path
        )
    )
    returncode, output = execute_command(
        "chown -R {0} '{1}'".format(
            ownership,
            path
        )
    )
    return returncode == 0

# ============================================================
# Activate JDK
# ============================================================
def activate_jdk(temp_path, jdk_path):
    log("Activating new JDK...")
    try:
        os.rename(
            temp_path,
            jdk_path
        )
    except Exception as error:
        log(
            "ERROR: Unable to activate new JDK: {0}".format(
                error
            )
        )
        return False
    log(
        "New JDK installed at: {0}".format(
            jdk_path
        )
    )
    return True

# ============================================================
# Rollback
# ============================================================
def rollback(
    jdk_path,
    backup_path,
    temp_path
):
    log("==============================================")
    log("STARTING ROLLBACK")
    log("==============================================")
    # Remove failed/new JDK
    if os.path.exists(jdk_path):
        failed_path = (
            jdk_path +
            "_failed_" +
            datetime.now().strftime(
                "%Y%m%d_%H%M%S"
            )
        )
        try:
            os.rename(
                jdk_path,
                failed_path
            )
            log(
                "Failed JDK moved to: {0}".format(
                    failed_path
                )
            )
        except Exception:
            shutil.rmtree(
                jdk_path,
                ignore_errors=True
            )
    # Remove temporary directory
    if os.path.exists(temp_path):
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
    # Restore backup
    if os.path.exists(backup_path):
        try:
            os.rename(
                backup_path,
                jdk_path
            )
            log(
                "Old JDK restored successfully."
            )
        except Exception as error:
            log(
                "CRITICAL: Unable to restore backup: {0}".format(
                    error
                )
            )
            return False
    else:
        log(
            "CRITICAL: Backup JDK not found!"
        )
        return False
    return True

# ============================================================
# Upgrade one JDK
# ============================================================
def upgrade_jdk(server, jdk_path):
    log("")
    log("==============================================")
    log(
        "Processing server: {0}".format(server)
    )
    log(
        "JDK path: {0}".format(jdk_path)
    )
    log("==============================================")
    # --------------------------------------------------------
    # Validate JDK
    # --------------------------------------------------------
    valid, old_version = check_current_jdk(
        jdk_path
    )
    if not valid:
        return (
            "FAILED",
            old_version,
            "",
            "Current JDK validation failed"
        )
    # --------------------------------------------------------
    # Get ownership
    # --------------------------------------------------------
    ownership = get_ownership(
        jdk_path
    )
    if ownership:
        log(
            "Current ownership: {0}".format(
                ownership
            )
        )
    # --------------------------------------------------------
    # Timestamp
    # --------------------------------------------------------
    timestamp = datetime.now().strftime(
        "%Y%m%d_%H%M%S"
    )
    backup_path = (
        jdk_path +
        "_backup_" +
        timestamp
    )
    temp_path = (
        jdk_path +
        "_new_" +
        timestamp
    )
    # --------------------------------------------------------
    # Backup
    # --------------------------------------------------------
    if not backup_jdk(
        jdk_path,
        backup_path
    ):
        return (
            "FAILED",
            old_version,
            "",
            "JDK backup failed"
        )
    # --------------------------------------------------------
    # Extract
    # --------------------------------------------------------
    if not extract_jdk(
        temp_path
    ):
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            "",
            "JDK extraction failed"
        )
    # --------------------------------------------------------
    # Set ownership
    # --------------------------------------------------------
    if ownership:
        if not set_ownership(
            temp_path,
            ownership
        ):
            rollback(
                jdk_path,
                backup_path,
                temp_path
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "Ownership update failed"
            )
    # --------------------------------------------------------
    # Verify BEFORE activation
    # --------------------------------------------------------
    valid, new_version = verify_new_jdk(
        temp_path
    )
    if not valid:
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            new_version,
            "New JDK verification failed"
        )
    # --------------------------------------------------------
    # Activate
    # --------------------------------------------------------
    if not activate_jdk(
        temp_path,
        jdk_path
    ):
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            new_version,
            "JDK activation failed"
        )
    # --------------------------------------------------------
    # Final verification
    # --------------------------------------------------------
    valid, final_version = check_current_jdk(
        jdk_path
    )
    if not valid:
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            final_version,
            "Final Java verification failed"
        )
    log("==============================================")
    log("JDK UPGRADE SUCCESSFUL")
    log("==============================================")
    log(
        "Old JDK backup: {0}".format(
            backup_path
        )
    )
    log(
        "New JDK: {0}".format(
            jdk_path
        )
    )
    return (
        "SUCCESS",
        old_version,
        final_version,
        "Backup: {0}".format(backup_path)
    )

# ============================================================
# Main
# ============================================================
def main():
    log("==============================================")
    log("Oracle JDK 8u501 Upgrade")
    log("Python 2.6.6 Compatible Script")
    log("==============================================")
    # --------------------------------------------------------
    # Check CSV
    # --------------------------------------------------------
    if not os.path.isfile(CSV_FILE):
        log(
            "ERROR: CSV file not found: {0}".format(
                CSV_FILE
            )
        )
        sys.exit(1)
    # --------------------------------------------------------
    # Check JDK package
    # --------------------------------------------------------
    if not check_jdk_tar():
        sys.exit(1)
    results = []
    # --------------------------------------------------------
    # Read CSV
    # --------------------------------------------------------
    csvfile = open(
        CSV_FILE,
        "r"
    )
    reader = csv.DictReader(
        csvfile
    )
    for row in reader:
        server = row["server"].strip()
        jdk_path = row["oracle_home"].strip()
        status, old_version, new_version, remarks = (
            upgrade_jdk(
                server,
                jdk_path
            )
        )
        results.append({
            "server": server,
            "jdk_path": jdk_path,
            "old_version": old_version,
            "new_version": new_version,
            "status": status,
            "remarks": remarks
        })
    csvfile.close()
    # --------------------------------------------------------
    # Result CSV
    # --------------------------------------------------------
    result_file = (
        "/home/oracle/Desktop/"
        "jdk_upgrade_result_" +
        datetime.now().strftime(
            "%Y%m%d_%H%M%S"
        ) +
        ".csv"
    )
    outfile = open(
        result_file,
        "wb"
    )
    fieldnames = [
        "server",
        "jdk_path",
        "old_version",
        "new_version",
        "status",
        "remarks"
    ]
    writer = csv.DictWriter(
        outfile,
        fieldnames=fieldnames
    )
    writer.writeheader()
    for result in results:
        writer.writerow(
            result
        )
    outfile.close()
    log("")
    log("==============================================")
    log("JDK UPGRADE PROCESS COMPLETED")
    log("==============================================")
    log(
        "Result CSV: {0}".format(
            result_file
        )
    )

if __name__ == "__main__":
    main()

No comments:

Post a Comment