Chat
Ask me anything
Ithy Logo
Sign in to save

Comprehensive Diagnostic Script for macOS on M-Series Chips

Ensure optimal performance and stability with continuous system monitoring

macos m series diagnostics

Key Takeaways

  • Automated Version Validation: Ensures all essential tools are up-to-date, preventing compatibility issues.
  • Robust Network Monitoring: Continuously checks connectivity, DNS resolution, and tracks connection stability.
  • Comprehensive Resource Tracking: Monitors CPU, memory, disk usage, and Docker container statistics to maintain system health.

Introduction

Maintaining the health and performance of your macOS system, especially those running on M-Series chips, is crucial for both personal and professional tasks. This comprehensive diagnostic script is designed to provide continuous monitoring of system versions, network health, connection stability, and resource utilization. By automating these checks at configurable intervals, users can effortlessly ensure their systems are running optimally and address any issues proactively.

Script Overview

Core Components

  • Version Checking: Validates the installation and versions of critical tools like Python, Node.js, and Docker.
  • Network Health Monitoring: Assesses gateway connectivity, DNS resolution, and route stability.
  • Connection Monitoring: Tracks connection loss rates to identify instability.
  • Resource Monitoring: Monitors CPU usage, memory consumption, disk space, and Docker container statistics.
  • Report Generation: Compiles all logs into a comprehensive Markdown report for easy review.

Configuration

Before executing the script, it's essential to configure the intervals for each diagnostic check and specify the directories where logs and reports will be stored. Adjusting these intervals based on your monitoring needs ensures optimal performance without overwhelming system resources.

Script Configuration

#!/bin/bash

# ============================
# System Diagnostic Script
# Designed for macOS on M-Series Chips
# Created on: January 19, 2025
# ============================

# Configuration Section

VERSION_CHECK_INTERVAL=300       # 5 minutes
NETWORK_CHECK_INTERVAL=30        # 30 seconds
CONNECTION_MONITOR_INTERVAL=5    # 5 seconds
RESOURCE_MONITOR_INTERVAL=120    # 2 minutes

TIMESTAMP=$(date '+%Y%m%d%H%M%S')
REPORT_DIR="$HOME/Diagnostics_Report_$TIMESTAMP"

# Log Files
VERSION_LOG="$REPORT_DIR/version_checks.log"
NETWORK_LOG="$REPORT_DIR/network_health.log"
CONNECTION_LOG="$REPORT_DIR/connection_monitor.log"
RESOURCE_LOG="$REPORT_DIR/resource_monitor.log"
MAIN_LOG="$REPORT_DIR/main.log"
REPORT_FILE="$REPORT_DIR/diagnostic_report.md"

# Required Tool Versions
REQUIRED_PYTHON_VERSION="3.10.4"
REQUIRED_NODE_VERSION="16.13.0"
REQUIRED_DOCKER_VERSION="20.10.7"

The initial configuration sets the intervals for each diagnostic check, creates a timestamped directory for storing logs and reports, and defines the required versions for essential tools. Ensure these required versions align with your system's specifications or update them as necessary.

Script Functions

Logging Function

The log_message function is pivotal for recording events and statuses. It appends timestamped messages to the specified log files, facilitating easy tracking and troubleshooting.

# Function to log messages
log_message() {
    local log_file=$1
    local message=$2
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" >> "$log_file"
}

Version Checking

The version checking function validates the installed versions of critical tools against the predefined required versions. If discrepancies are found, it logs appropriate alerts, enabling users to take corrective actions.

# Function to check tool versions
check_versions() {
    log_message "$VERSION_LOG" "Starting version checks..."

    # Python Version Check
    local python_version=$(python3 --version 2>&1)
    log_message "$VERSION_LOG" "Python Version: $python_version"
    if [[ "$python_version" != *"$REQUIRED_PYTHON_VERSION"* ]]; then
        log_message "$VERSION_LOG" "Alert: Python version mismatch. Required: $REQUIRED_PYTHON_VERSION"
    fi

    # Node.js Version Check
    local node_version=$(node --version 2>&1)
    log_message "$VERSION_LOG" "Node.js Version: $node_version"
    if [[ "$node_version" != *"$REQUIRED_NODE_VERSION"* ]]; then
        log_message "$VERSION_LOG" "Alert: Node.js version mismatch. Required: $REQUIRED_NODE_VERSION"
    fi

    # Docker Version Check
    local docker_version=$(docker --version 2>&1)
    log_message "$VERSION_LOG" "Docker Version: $docker_version"
    if [[ "$docker_version" != *"$REQUIRED_DOCKER_VERSION"* ]]; then
        log_message "$VERSION_LOG" "Alert: Docker version mismatch. Required: $REQUIRED_DOCKER_VERSION"
    fi

    log_message "$VERSION_LOG" "Version checks completed."
}

Network Health Monitoring

Ensuring robust network connectivity is essential. This function checks gateway connectivity, DNS resolution, and route stability, logging any issues detected during the process.

# Function to monitor network health
monitor_network_health() {
    log_message "$NETWORK_LOG" "Starting network health checks..."

    # Gateway Connectivity Check
    local gateway=$(netstat -nr | grep '^default' | awk '{print $2}')
    if ping -c 2 "$gateway" &> /dev/null; then
        log_message "$NETWORK_LOG" "Gateway ($gateway) is reachable."
    else
        log_message "$NETWORK_LOG" "Error: Gateway ($gateway) is unreachable."
    fi

    # DNS Resolution Check
    if nslookup google.com &> /dev/null; then
        log_message "$NETWORK_LOG" "DNS resolution is functioning properly."
    else
        log_message "$NETWORK_LOG" "Error: DNS resolution failed."
    fi

    # Route Stability Check
    traceroute -m 5 google.com >> "$NETWORK_LOG" 2>&1
    log_message "$NETWORK_LOG" "Route stability check completed."

    log_message "$NETWORK_LOG" "Network health checks completed."
}

Connection Monitoring

This function tracks connection stability by monitoring connection loss rates. Frequent losses may indicate underlying network issues that need addressing.

# Function to monitor connection stability
monitor_connection() {
    log_message "$CONNECTION_LOG" "Starting connection monitoring..."

    local loss_count=0
    local total_pings=10
    for ((i=1; i<=total_pings; i++)); do
        if ping -c 1 google.com &> /dev/null; then
            log_message "$CONNECTION_LOG" "Ping $i: Success"
        else
            log_message "$CONNECTION_LOG" "Ping $i: Failure"
            ((loss_count++))
        fi
        sleep "$CONNECTION_MONITOR_INTERVAL"
    done

    local loss_percentage=$(( (loss_count * 100) / total_pings ))
    log_message "$CONNECTION_LOG" "Connection Loss Rate: $loss_percentage%"
}

Resource Monitoring

Monitoring system resources helps in identifying potential performance bottlenecks. This function tracks CPU usage, memory consumption, disk space, and Docker container statistics.

# Function to monitor system resources
monitor_resources() {
    log_message "$RESOURCE_LOG" "Starting resource monitoring..."

    # CPU Usage
    local cpu_usage=$(top -l 1 | grep "CPU usage" | awk '{print $3}')
    log_message "$RESOURCE_LOG" "CPU Usage: $cpu_usage"

    # Memory Usage
    local memory_usage=$(vm_stat | perl -ne '/page size of (\d+)/ and $size=$1; /Pages\s+([^:]+)[^\d]+(\d+)/ and printf("%s: %.2f MB\n", "$1", $2 * $size / 1048576);')
    log_message "$RESOURCE_LOG" "Memory Usage:\n$memory_usage"

    # Disk Space
    local disk_usage=$(df -h / | awk 'NR==2 {print $5}')
    log_message "$RESOURCE_LOG" "Disk Usage: $disk_usage"

    # Docker Container Stats
    if command -v docker &> /dev/null; then
        docker stats --no-stream >> "$RESOURCE_LOG" 2>&1
    else
        log_message "$RESOURCE_LOG" "Docker not installed. Skipping container stats."
    fi

    log_message "$RESOURCE_LOG" "Resource monitoring completed."
}

Report Generation

After collecting all necessary data, this function compiles the logs into a structured Markdown report. This report provides a consolidated view of the system's status, making it easier to review and analyze.

# Function to generate the final report
generate_report() {
    log_message "$MAIN_LOG" "Generating final report..."

    echo "# System Diagnostic Report" > "$REPORT_FILE"
    echo "Generated on: $(date '+%Y-%m-%d %H:%M:%S')" >> "$REPORT_FILE"
    echo "" >> "$REPORT_FILE"

    echo "## Version Checks" >> "$REPORT_FILE"
    cat "$VERSION_LOG" >> "$REPORT_FILE"
    echo "" >> "$REPORT_FILE"

    echo "## Network Health Checks" >> "$REPORT_FILE"
    cat "$NETWORK_LOG" >> "$REPORT_FILE"
    echo "" >> "$REPORT_FILE"

    echo "## Connection Monitoring" >> "$REPORT_FILE"
    cat "$CONNECTION_LOG" >> "$REPORT_FILE"
    echo "" >> "$REPORT_FILE"

    echo "## Resource Monitoring" >> "$REPORT_FILE"
    cat "$RESOURCE_LOG" >> "$REPORT_FILE"

    log_message "$MAIN_LOG" "Report generated at $REPORT_FILE."
}

Main Execution Loop

The main loop orchestrates the execution of all diagnostic functions at their respective intervals. It runs continuously in the background, ensuring real-time monitoring of the system.

# Function to create necessary directories and files
initialize() {
    mkdir -p "$REPORT_DIR"
    touch "$VERSION_LOG" "$NETWORK_LOG" "$CONNECTION_LOG" "$RESOURCE_LOG" "$MAIN_LOG" "$REPORT_FILE"
    log_message "$MAIN_LOG" "Diagnostic script initialized."
}

# Initialize the diagnostic script
initialize

# Start background processes for each monitoring function

# Version Checks: Every 5 minutes
(
    while true; do
        check_versions
        sleep "$VERSION_CHECK_INTERVAL"
    done
) &

# Network Health Checks: Every 30 seconds
(
    while true; do
        monitor_network_health
        sleep "$NETWORK_CHECK_INTERVAL"
    done
) &

# Connection Monitoring: Every 5 seconds
(
    while true; do
        monitor_connection
        sleep "$CONNECTION_MONITOR_INTERVAL"
    done
) &

# Resource Monitoring: Every 2 minutes
(
    while true; do
        monitor_resources
        sleep "$RESOURCE_MONITOR_INTERVAL"
    done
) &

# Trap to handle script termination and generate report
trap "generate_report; exit" SIGINT

# Inform the user that the diagnostic script is running
echo "Diagnostic script is running. Press Ctrl+C to stop and generate the report."

# Wait indefinitely until the user stops the script
wait

How to Use the Script

Step-by-Step Instructions

  1. Save the Script: Create a new file named mac_diagnostics.sh and paste the entire script into it.

  2. Make Executable: Open the terminal and navigate to the directory containing the script. Run the following command to make the script executable:

    chmod +x mac_diagnostics.sh
  3. Run the Script: Execute the script by running:

    ./mac_diagnostics.sh

    The script will start running in the background, performing the configured diagnostic checks at specified intervals.

  4. Stop and Generate Report: To stop the script and generate the diagnostic report, press Ctrl+C in the terminal. The report will be saved in the timestamped directory within your home folder.

  5. Review Logs and Report: Navigate to the Diagnostics_Report_YYYYMMDDHHMMSS directory in your home folder. Here, you'll find individual log files for each type of check and a comprehensive diagnostic_report.md summarizing all findings.

Detailed Script Explanation

Configuration Section

This section defines the intervals for each diagnostic check, ensuring that they run at appropriate frequencies without taxing system resources. The TIMESTAMP variable creates a unique identifier for each diagnostic session, organizing logs and reports systematically.

Logging Mechanism

Effective logging is crucial for diagnosing issues. The log_message function ensures that all relevant information is timestamped and written to the appropriate log files. This structured logging facilitates easy navigation and analysis of the system's behavior over time.

Version Checking

Ensuring that essential tools are up-to-date prevents compatibility issues and leverages the latest features and security patches. This function checks the installed versions against the required ones, logging any discrepancies for user attention.

Network Health Monitoring

A stable network connection is vital for seamless operations. This function checks the reachability of the gateway, validates DNS resolution, and assesses route stability using traceroute. Any failures are promptly logged for further investigation.

Connection Monitoring

By pinging a reliable server multiple times, this function calculates the connection loss rate, providing insights into the network's stability. High loss rates may indicate underlying issues that need immediate attention.

Resource Monitoring

Monitoring system resources like CPU, memory, and disk usage helps in identifying performance bottlenecks. Additionally, if Docker is installed, monitoring container statistics ensures that your virtual environments are running smoothly.

Report Generation

After collecting all diagnostic data, this function compiles the information into a structured Markdown report. This report serves as a comprehensive overview of the system's health, making it easier to share and review findings.

Sample Diagnostic Report

Upon stopping the script, a report similar to the one below will be generated:

# System Diagnostic Report
Generated on: 2025-01-19 15:45:30

## Version Checks
2025-01-19 15:40:00 - Starting version checks...
2025-01-19 15:40:00 - Python Version: Python 3.10.4
2025-01-19 15:40:00 - Node.js Version: v16.13.0
2025-01-19 15:40:00 - Docker Version: Docker version 20.10.7, build f0df350
2025-01-19 15:40:00 - Version checks completed.

## Network Health Checks
2025-01-19 15:40:30 - Starting network health checks...
2025-01-19 15:40:30 - Gateway (192.168.1.1) is reachable.
2025-01-19 15:40:30 - DNS resolution is functioning properly.
Traceroute results...
...

## Connection Monitoring
2025-01-19 15:40:35 - Starting connection monitoring...
2025-01-19 15:40:35 - Ping 1: Success
...
2025-01-19 15:40:40 - Connection Loss Rate: 0%

## Resource Monitoring
2025-01-19 15:42:00 - Starting resource monitoring...
2025-01-19 15:42:00 - CPU Usage: 15.0%
2025-01-19 15:42:00 - Memory Usage:
Pages free: 2000 MB
Pages active: 8000 MB
...
2025-01-19 15:42:00 - Disk Usage: 45%
Docker container stats...
...

This report provides a clear and organized summary of all diagnostic checks, allowing users to quickly identify and address any potential issues.

Advantages of Using This Diagnostic Script

Proactive Issue Detection

By continuously monitoring system parameters, the script allows users to detect and address issues before they escalate, ensuring uninterrupted workflow and system stability.

Automated Reporting

The automated generation of detailed reports saves time and provides a comprehensive overview of the system's health, aiding in quick decision-making and troubleshooting.

Customizable Intervals

Users can adjust the intervals for each diagnostic check based on their specific needs, allowing for flexible and tailored monitoring strategies.

Best Practices

Regular Monitoring

Run the diagnostic script regularly to maintain a continuous overview of your system's health, enabling timely interventions.

Update Required Versions

Periodically review and update the required tool versions in the script to align with the latest releases and security patches.

Secure Log Storage

Ensure that the directory storing logs and reports is secure and backed up regularly to prevent data loss and maintain confidentiality.

Troubleshooting

Permission Issues

If you encounter permission-related errors while running the script, ensure that it has executable permissions and that you have the necessary rights to create directories and files in the specified locations.

Tool Not Found Errors

If the script logs indicate that certain tools (e.g., Docker) are not installed, install them using Homebrew or the appropriate package manager to ensure complete monitoring.

Unexpected Script Termination

Ensure that no other processes are interfering with the script's execution. Check for typos or syntax errors in the script if it terminates unexpectedly.

Enhancements and Customizations

Integrate Notification Systems

Enhance the script by integrating email or messaging notifications to alert you in real-time about critical issues detected during monitoring.

Extended Resource Monitoring

Incorporate additional resource checks, such as GPU usage or network bandwidth monitoring, to gain deeper insights into system performance.

Scheduled Reporting

Automate the generation and distribution of reports at scheduled intervals (e.g., daily or weekly) to maintain a consistent overview of system health.

Conclusion

This comprehensive diagnostic script for macOS on M-Series chips serves as an invaluable tool for maintaining system health and performance. By automating essential checks and compiling detailed reports, it empowers users to proactively manage their systems, ensuring optimal functionality and reliability. Customize and enhance the script based on your specific needs to unlock its full potential in safeguarding your macOS environment.

References


Last updated January 19, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI
Download Article
Delete Article