Tutorial

Neue Updates und Verbesserungen zu Macfleet.

Wichtiger Hinweis

Die in diesen Tutorials bereitgestellten Codebeispiele und Skripte dienen nur zu Bildungszwecken. Macfleet ist nicht verantwortlich für Probleme, Schäden oder Sicherheitslücken, die durch die Verwendung, Änderung oder Implementierung dieser Beispiele entstehen können. Überprüfen und testen Sie Code immer in einer sicheren Umgebung, bevor Sie ihn in Produktionssystemen verwenden.

Scheduled Restart Management on macOS

Manage and automate system restarts across your MacFleet with enterprise-grade scheduling capabilities. This tutorial covers advanced restart scheduling, maintenance windows, user notifications, and fleet-wide deployment with compliance monitoring.

Understanding macOS Restart Management

Scheduled restarts are essential for:

  • 🔄 System maintenance - Clear memory, apply updates, reset system state
  • 🛡️ Security compliance - Ensure security patches are active after installation
  • ⚡ Performance optimization - Reset resource usage and eliminate memory leaks
  • 🏢 Enterprise scheduling - Coordinate maintenance across entire fleets

Basic Restart Scheduling

Simple Time-Based Restart

#!/bin/bash

# Schedule restart at specific time (24-hour format)
# Replace 0300 with desired restart time (03:00 AM)
sudo shutdown -r 0300

echo "✅ Restart scheduled for 03:00 AM"

Immediate Restart with Delay

#!/bin/bash

# Schedule restart in X minutes from now
MINUTES=30
sudo shutdown -r +$MINUTES

echo "✅ Restart scheduled in $MINUTES minutes"

Cancel Scheduled Restart

#!/bin/bash

# Cancel any pending restart
sudo shutdown -c

echo "✅ Scheduled restart cancelled"

Advanced Restart Scheduling Options

Conditional Restart with System Checks

#!/bin/bash

# Only restart if system meets specific conditions
perform_system_checks() {
    echo "🔍 Performing pre-restart system checks..."
    
    # Check system load
    local load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
    local load_threshold=2.0
    
    if (( $(echo "$load_avg > $load_threshold" | bc -l) )); then
        echo "⚠️ System load too high ($load_avg) - postponing restart"
        return 1
    fi
    
    # Check for critical processes
    local critical_processes=("backup" "sync" "deploy")
    for process in "${critical_processes[@]}"; do
        if pgrep -f "$process" > /dev/null; then
            echo "⚠️ Critical process '$process' running - postponing restart"
            return 1
        fi
    done
    
    # Check available disk space
    local available_space=$(df / | tail -1 | awk '{print $4}')
    local min_space=1048576  # 1GB in KB
    
    if [[ $available_space -lt $min_space ]]; then
        echo "⚠️ Insufficient disk space - postponing restart"
        return 1
    fi
    
    echo "✅ All system checks passed"
    return 0
}

# Schedule restart only if conditions are met
if perform_system_checks; then
    sudo shutdown -r +5
    echo "✅ Restart scheduled in 5 minutes"
else
    echo "❌ Restart postponed due to system conditions"
fi

User-Friendly Restart with Notifications

#!/bin/bash

# Enhanced restart with user notifications and grace period
graceful_restart() {
    local delay_minutes="${1:-15}"
    local restart_time="${2:-$(date -d "+$delay_minutes minutes" "+%H:%M")}"
    
    echo "🔔 Scheduling graceful restart in $delay_minutes minutes"
    
    # Send notification to logged-in users
    local logged_users=$(who | awk '{print $1}' | sort -u)
    
    for user in $logged_users; do
        sudo -u "$user" osascript -e "display notification \"System restart scheduled for $restart_time. Please save your work.\" with title \"MacFleet Maintenance\" sound name \"Glass\""
    done
    
    # Schedule the restart
    sudo shutdown -r "+$delay_minutes"
    
    echo "✅ Restart scheduled for $restart_time with user notifications sent"
}

# Execute graceful restart
graceful_restart 15

Enterprise Maintenance Windows

Weekly Maintenance Schedule

#!/bin/bash

# Schedule restart during maintenance window
schedule_maintenance_restart() {
    local day_of_week=$(date +%u)  # 1=Monday, 7=Sunday
    local current_hour=$(date +%H)
    local maintenance_day=7        # Sunday
    local maintenance_hour=03      # 3 AM
    
    # Calculate time until next maintenance window
    local days_until_maintenance=$(( (maintenance_day - day_of_week) % 7 ))
    if [[ $days_until_maintenance -eq 0 ]] && [[ $current_hour -ge $maintenance_hour ]]; then
        days_until_maintenance=7  # Next week if we've passed today's window
    fi
    
    local restart_date=$(date -d "+$days_until_maintenance days $maintenance_hour:00" "+%Y-%m-%d %H:%M")
    local restart_timestamp=$(date -d "$restart_date" "+%m%d%H%M")
    
    echo "📅 Scheduling restart for next maintenance window: $restart_date"
    
    # Use at command for precise scheduling
    echo "sudo shutdown -r now" | at "$restart_timestamp" 2>/dev/null
    
    if [[ $? -eq 0 ]]; then
        echo "✅ Restart scheduled for maintenance window: $restart_date"
    else
        # Fallback to immediate scheduling if 'at' is not available
        echo "⚠️ 'at' command not available, using immediate scheduling"
        sudo shutdown -r 0300  # 3 AM today/tomorrow
    fi
}

schedule_maintenance_restart

Business Hours Protection

#!/bin/bash

# Prevent restarts during business hours
business_hours_restart() {
    local current_hour=$(date +%H)
    local current_day=$(date +%u)  # 1=Monday, 7=Sunday
    local business_start=9
    local business_end=17
    
    # Check if it's a weekday during business hours
    if [[ $current_day -le 5 ]] && [[ $current_hour -ge $business_start ]] && [[ $current_hour -lt $business_end ]]; then
        echo "🏢 Business hours detected - scheduling restart for after hours"
        
        if [[ $current_hour -lt 12 ]]; then
            # Morning - schedule for evening
            sudo shutdown -r 1800  # 6 PM
            echo "✅ Restart scheduled for 6:00 PM (after business hours)"
        else
            # Afternoon - schedule for next day early morning
            sudo shutdown -r 0600  # 6 AM next day
            echo "✅ Restart scheduled for 6:00 AM tomorrow (before business hours)"
        fi
    else
        echo "✅ Outside business hours - safe to restart"
        sudo shutdown -r +5
        echo "✅ Restart scheduled in 5 minutes"
    fi
}

business_hours_restart

Enterprise Fleet Management Script

#!/bin/bash

# MacFleet Enterprise Restart Management System
# Advanced scheduling, monitoring, and fleet deployment

# Configuration
SCRIPT_NAME="MacFleet Restart Manager"
VERSION="3.0.0"
LOG_FILE="/var/log/macfleet_restart.log"
CONFIG_DIR="/etc/macfleet/restart"
SCHEDULE_DIR="/etc/macfleet/restart/schedules"
POLICY_DIR="/etc/macfleet/restart/policies"
AUDIT_DIR="/etc/macfleet/restart/audit"

# Create necessary directories
mkdir -p "$CONFIG_DIR" "$SCHEDULE_DIR" "$POLICY_DIR" "$AUDIT_DIR"

# Logging function
log_action() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local message="$1"
    echo "[$timestamp] $message" | tee -a "$LOG_FILE"
}

# Audit logging for compliance
log_restart_action() {
    local action="$1"
    local schedule_type="$2"
    local restart_time="$3"
    local user=$(whoami)
    local hostname=$(hostname)
    
    local audit_entry="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"hostname\": \"$hostname\",
        \"user\": \"$user\",
        \"action\": \"$action\",
        \"schedule_type\": \"$schedule_type\",
        \"restart_time\": \"$restart_time\",
        \"script_version\": \"$VERSION\"
    }"
    
    echo "$audit_entry" >> "$AUDIT_DIR/restart_audit.json"
    log_action "Restart action: $action - $schedule_type at $restart_time"
}

# System health assessment
assess_system_health() {
    echo "🏥 Assessing system health for restart readiness..."
    
    local health_score=100
    local issues=()
    
    # Check system load
    local load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
    if (( $(echo "$load_avg > 3.0" | bc -l) )); then
        health_score=$((health_score - 20))
        issues+=("High system load: $load_avg")
    fi
    
    # Check memory usage
    local memory_pressure=$(memory_pressure | grep "System-wide memory free percentage" | awk '{print $5}' | sed 's/%//')
    if [[ $memory_pressure -lt 10 ]]; then
        health_score=$((health_score - 15))
        issues+=("Low memory: ${memory_pressure}% free")
    fi
    
    # Check disk space
    local disk_usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
    if [[ $disk_usage -gt 90 ]]; then
        health_score=$((health_score - 10))
        issues+=("High disk usage: ${disk_usage}%")
    fi
    
    # Check for critical processes
    local critical_procs=$(pgrep -f "(backup|sync|deploy|update)" | wc -l)
    if [[ $critical_procs -gt 0 ]]; then
        health_score=$((health_score - 25))
        issues+=("Critical processes running: $critical_procs")
    fi
    
    # Check network connectivity
    if ! ping -c 1 -W 5 8.8.8.8 >/dev/null 2>&1; then
        health_score=$((health_score - 5))
        issues+=("Network connectivity issue")
    fi
    
    # Generate health report
    local health_report="{
        \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
        \"hostname\": \"$(hostname)\",
        \"health_score\": $health_score,
        \"issues\": [$(printf '\"%s\",' "${issues[@]}" | sed 's/,$//')]
    }"
    
    echo "$health_report" > "$AUDIT_DIR/health_assessment_$(date +%Y%m%d_%H%M%S).json"
    
    echo "📊 System health score: $health_score/100"
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo "⚠️ Issues detected:"
        printf '   - %s\n' "${issues[@]}"
    fi
    
    # Return health score (0 = failure, 1 = success)
    [[ $health_score -ge 70 ]]
}

# Advanced notification system
send_restart_notifications() {
    local restart_time="$1"
    local minutes_until="$2"
    local notification_type="${3:-standard}"
    
    echo "🔔 Sending restart notifications..."
    
    # Get logged-in users
    local logged_users=$(who | awk '{print $1}' | sort -u)
    
    # Notification messages based on type
    case "$notification_type" in
        "emergency")
            local title="EMERGENCY: System Restart Required"
            local message="Critical security update requires immediate restart at $restart_time"
            local sound="Basso"
            ;;
        "maintenance")
            local title="Scheduled Maintenance"
            local message="System restart scheduled for $restart_time as part of routine maintenance"
            local sound="Glass"
            ;;
        *)
            local title="System Restart Notification"
            local message="System restart scheduled for $restart_time. Please save your work."
            local sound="Blow"
            ;;
    esac
    
    # Send notifications to each user
    for user in $logged_users; do
        if [[ -n "$user" ]]; then
            sudo -u "$user" osascript -e "display notification \"$message\" with title \"$title\" sound name \"$sound\"" 2>/dev/null
            
            # Also send terminal message if user has terminal open
            sudo -u "$user" wall "MacFleet Notice: $message" 2>/dev/null
        fi
    done
    
    log_action "Notifications sent to users: $(echo $logged_users | tr '\n' ' ')"
}

# Intelligent restart scheduling
intelligent_restart() {
    local schedule_type="$1"
    local target_time="$2"
    local force="${3:-false}"
    
    echo "🧠 Initiating intelligent restart scheduling..."
    
    # Assess system health unless forced
    if [[ "$force" != "true" ]]; then
        if ! assess_system_health; then
            echo "❌ System health check failed - restart postponed"
            log_restart_action "postponed" "$schedule_type" "$target_time"
            return 1
        fi
    fi
    
    case "$schedule_type" in
        "immediate")
            echo "⚡ Scheduling immediate restart..."
            send_restart_notifications "in 2 minutes" "2" "emergency"
            sudo shutdown -r +2
            ;;
        "maintenance")
            echo "🔧 Scheduling maintenance restart..."
            local delay_minutes=15
            local restart_time=$(date -d "+$delay_minutes minutes" "+%H:%M")
            send_restart_notifications "$restart_time" "$delay_minutes" "maintenance"
            sudo shutdown -r "+$delay_minutes"
            ;;
        "business_safe")
            schedule_business_safe_restart
            ;;
        "weekly")
            schedule_weekly_maintenance
            ;;
        "custom")
            if [[ -n "$target_time" ]]; then
                echo "🎯 Scheduling custom restart for $target_time..."
                send_restart_notifications "$target_time" "custom" "standard"
                sudo shutdown -r "$target_time"
            else
                echo "❌ Custom restart requires target time"
                return 1
            fi
            ;;
        *)
            echo "❌ Invalid schedule type: $schedule_type"
            echo "Available types: immediate, maintenance, business_safe, weekly, custom"
            return 1
            ;;
    esac
    
    log_restart_action "scheduled" "$schedule_type" "${target_time:-auto}"
    echo "✅ Restart successfully scheduled"
}

# Business-safe restart scheduling
schedule_business_safe_restart() {
    local current_hour=$(date +%H)
    local current_day=$(date +%u)
    
    if [[ $current_day -le 5 ]] && [[ $current_hour -ge 9 ]] && [[ $current_hour -lt 17 ]]; then
        echo "🏢 Business hours detected - scheduling for after hours"
        if [[ $current_hour -lt 12 ]]; then
            sudo shutdown -r 1800  # 6 PM
            send_restart_notifications "18:00" "after hours" "maintenance"
        else
            sudo shutdown -r 0600  # 6 AM next day
            send_restart_notifications "06:00 tomorrow" "early morning" "maintenance"
        fi
    else
        echo "✅ Outside business hours - safe to restart"
        send_restart_notifications "in 10 minutes" "10" "maintenance"
        sudo shutdown -r +10
    fi
}

# Weekly maintenance scheduling
schedule_weekly_maintenance() {
    local day_of_week=$(date +%u)
    local maintenance_day=7  # Sunday
    local maintenance_hour=03
    
    local days_until=$(( (maintenance_day - day_of_week) % 7 ))
    if [[ $days_until -eq 0 ]] && [[ $(date +%H) -ge $maintenance_hour ]]; then
        days_until=7
    fi
    
    local restart_date=$(date -d "+$days_until days $maintenance_hour:00" "+%Y-%m-%d %H:%M")
    
    echo "📅 Scheduling for next maintenance window: $restart_date"
    
    # Use launchd for precise scheduling (more reliable than 'at')
    create_maintenance_schedule "$restart_date"
}

# Create launchd job for maintenance scheduling
create_maintenance_schedule() {
    local restart_datetime="$1"
    local plist_name="com.macfleet.maintenance.restart"
    local plist_path="/Library/LaunchDaemons/${plist_name}.plist"
    
    # Calculate start interval from epoch
    local start_time=$(date -j -f "%Y-%m-%d %H:%M" "$restart_datetime" "+%s" 2>/dev/null)
    
    if [[ -n "$start_time" ]]; then
        cat > "$plist_path" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$plist_name</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/sbin/shutdown</string>
        <string>-r</string>
        <string>now</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>3</integer>
        <key>Minute</key>
        <integer>0</integer>
        <key>Weekday</key>
        <integer>0</integer>
    </dict>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
        
        # Load the job
        launchctl load "$plist_path"
        echo "✅ Maintenance schedule created and loaded"
    else
        echo "❌ Failed to parse restart datetime: $restart_datetime"
        return 1
    fi
}

# Fleet deployment
deploy_restart_schedule() {
    local schedule_type="$1"
    local target_time="$2"
    local fleet_file="$CONFIG_DIR/fleet_hosts.txt"
    
    if [[ ! -f "$fleet_file" ]]; then
        echo "❌ Fleet hosts file not found: $fleet_file"
        return 1
    fi
    
    echo "🚀 Deploying restart schedule to fleet..."
    echo "Schedule Type: $schedule_type"
    echo "Target Time: ${target_time:-auto}"
    
    local success_count=0
    local total_count=0
    
    while IFS= read -r host; do
        [[ "$host" =~ ^#.*$ ]] && continue
        [[ -z "$host" ]] && continue
        
        ((total_count++))
        echo "Deploying to: $host"
        
        # Deploy and execute
        if scp "$0" "$host:/tmp/macfleet_restart.sh" >/dev/null 2>&1 && \
           ssh "$host" "chmod +x /tmp/macfleet_restart.sh && sudo /tmp/macfleet_restart.sh --schedule '$schedule_type' ${target_time:+--time '$target_time'}" >/dev/null 2>&1; then
            echo "✅ Successfully deployed to $host"
            ((success_count++))
        else
            echo "❌ Failed to deploy to $host"
        fi
        
    done < "$fleet_file"
    
    echo "📊 Fleet deployment completed: $success_count/$total_count successful"
    log_action "Fleet deployment: $success_count/$total_count hosts successful"
}

# Generate restart compliance report
generate_restart_report() {
    local report_file="$AUDIT_DIR/restart_compliance_$(date +%Y%m%d_%H%M%S).json"
    
    echo "📊 Generating restart compliance report..."
    
    # Gather system information
    local uptime_days=$(uptime | awk '{print $3}' | sed 's/,//')
    local last_restart=$(last reboot | head -1 | awk '{print $3, $4, $5, $6}')
    local pending_restart=$(sudo shutdown -q 2>&1 | grep -o "shutdown.*" || echo "none")
    
    # Check for pending updates
    local pending_updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    
    # Generate report
    local report="{
        \"report_metadata\": {
            \"generated_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
            \"hostname\": \"$(hostname)\",
            \"script_version\": \"$VERSION\",
            \"compliance_frameworks\": [\"NIST\", \"ISO 27001\", \"SOX\", \"HIPAA\"]
        },
        \"system_status\": {
            \"uptime_days\": \"$uptime_days\",
            \"last_restart\": \"$last_restart\",
            \"pending_restart\": \"$pending_restart\",
            \"pending_updates\": $pending_updates
        },
        \"restart_history\": $(tail -10 "$LOG_FILE" 2>/dev/null | jq -R . | jq -s . || echo "[]"),
        \"compliance_score\": $(calculate_restart_compliance_score "$uptime_days" "$pending_updates")
    }"
    
    echo "$report" > "$report_file"
    echo "📋 Compliance report saved: $report_file"
    log_action "Compliance report generated: $report_file"
}

# Calculate restart compliance score
calculate_restart_compliance_score() {
    local uptime_days="$1"
    local pending_updates="$2"
    local score=100
    
    # Deduct points for extended uptime
    if [[ "$uptime_days" =~ ^[0-9]+$ ]]; then
        if [[ $uptime_days -gt 30 ]]; then
            score=$((score - 30))
        elif [[ $uptime_days -gt 14 ]]; then
            score=$((score - 15))
        elif [[ $uptime_days -gt 7 ]]; then
            score=$((score - 5))
        fi
    fi
    
    # Deduct points for pending updates
    if [[ "$pending_updates" =~ ^[0-9]+$ ]] && [[ $pending_updates -gt 0 ]]; then
        score=$((score - (pending_updates * 10)))
    fi
    
    # Ensure score is between 0 and 100
    [[ $score -lt 0 ]] && score=0
    [[ $score -gt 100 ]] && score=100
    
    echo "$score"
}

# Emergency restart capability
emergency_restart() {
    echo "🚨 EMERGENCY RESTART INITIATED"
    
    # Send immediate notifications
    send_restart_notifications "in 60 seconds" "1" "emergency"
    
    # Create emergency log entry
    log_restart_action "emergency" "immediate" "60 seconds"
    
    # Force restart with minimal delay
    sudo shutdown -r +1
    
    echo "⚠️ EMERGENCY RESTART IN 60 SECONDS"
}

# Status check
check_restart_status() {
    echo "=== MacFleet Restart Status ==="
    
    # System uptime
    echo "🕐 System Uptime: $(uptime | awk '{print $3, $4}' | sed 's/,//')"
    
    # Last restart
    echo "📅 Last Restart: $(last reboot | head -1 | awk '{print $3, $4, $5, $6}')"
    
    # Pending restart
    local pending=$(sudo shutdown -q 2>&1 | grep -o "shutdown.*" || echo "none")
    echo "⏰ Pending Restart: $pending"
    
    # System health
    if assess_system_health >/dev/null 2>&1; then
        echo "🟢 System Health: Good"
    else
        echo "🔴 System Health: Issues detected"
    fi
    
    # Pending updates
    local updates=$(softwareupdate -l 2>/dev/null | grep -c "recommended" || echo "0")
    echo "📦 Pending Updates: $updates"
}

# Display usage
show_usage() {
    cat << EOF
$SCRIPT_NAME v$VERSION

Usage: $0 [OPTION]

RESTART SCHEDULING:
    --schedule TYPE [TIME]      Schedule restart (immediate|maintenance|business_safe|weekly|custom)
    --emergency                 Emergency restart (60 second warning)
    --cancel                    Cancel pending restart
    --status                    Show current restart status

FLEET MANAGEMENT:
    --deploy-fleet TYPE [TIME]  Deploy restart schedule to entire fleet
    --generate-report          Generate compliance report

EXAMPLES:
    $0 --schedule immediate
    $0 --schedule maintenance
    $0 --schedule custom 0300
    $0 --deploy-fleet weekly
    $0 --emergency
    $0 --status

Configuration:
    $CONFIG_DIR/fleet_hosts.txt  - Fleet deployment hosts
    
Logs:
    $LOG_FILE                    - Main log file
    $AUDIT_DIR/                  - Audit and compliance logs
EOF
}

# Main function
main() {
    case "$1" in
        --schedule)
            [[ -z "$2" ]] && { echo "❌ Schedule type required"; exit 1; }
            intelligent_restart "$2" "$3"
            ;;
        --emergency)
            emergency_restart
            ;;
        --cancel)
            sudo shutdown -c 2>/dev/null && echo "✅ Restart cancelled" || echo "❌ No restart to cancel"
            ;;
        --status)
            check_restart_status
            ;;
        --deploy-fleet)
            [[ -z "$2" ]] && { echo "❌ Schedule type required for fleet deployment"; exit 1; }
            deploy_restart_schedule "$2" "$3"
            ;;
        --generate-report)
            generate_restart_report
            ;;
        --help|"")
            show_usage
            ;;
        *)
            echo "❌ Invalid option: $1"
            show_usage
            exit 1
            ;;
    esac
}

# Execute main function
main "$@"

Restart Scheduling Policies

Production Environment Policy

#!/bin/bash

# High-availability production restart policy
production_restart_policy() {
    echo "🏭 Applying production restart policy..."
    
    # Only allow restarts during designated maintenance windows
    local current_hour=$(date +%H)
    local current_day=$(date +%u)
    
    # Maintenance windows: Sundays 2-4 AM, Weekdays 2-3 AM
    local maintenance_allowed=false
    
    if [[ $current_day -eq 7 ]] && [[ $current_hour -ge 2 ]] && [[ $current_hour -lt 4 ]]; then
        maintenance_allowed=true
    elif [[ $current_day -le 5 ]] && [[ $current_hour -ge 2 ]] && [[ $current_hour -lt 3 ]]; then
        maintenance_allowed=true
    fi
    
    if [[ "$maintenance_allowed" == "true" ]]; then
        echo "✅ Within maintenance window - restart allowed"
        return 0
    else
        echo "⛔ Outside maintenance window - restart blocked"
        return 1
    fi
}

Development Environment Policy

#!/bin/bash

# Flexible development restart policy
development_restart_policy() {
    echo "💻 Applying development restart policy..."
    
    # More flexible scheduling for development
    local current_hour=$(date +%H)
    
    # Block restarts only during peak development hours (9 AM - 6 PM)
    if [[ $current_hour -ge 9 ]] && [[ $current_hour -lt 18 ]]; then
        echo "⚠️ Peak development hours - requesting confirmation"
        
        # In a real implementation, this could trigger an approval workflow
        echo "Restart will be scheduled for after hours (6 PM)"
        sudo shutdown -r 1800
        return 0
    else
        echo "✅ Outside peak hours - restart allowed"
        return 0
    fi
}

Usage Examples

Schedule Immediate Maintenance Restart

# Emergency restart with user notifications
sudo ./macfleet_restart.sh --schedule immediate

# Maintenance restart with 15-minute grace period
sudo ./macfleet_restart.sh --schedule maintenance

Business-Safe Scheduling

# Automatically avoid business hours
sudo ./macfleet_restart.sh --schedule business_safe

# Weekly maintenance window
sudo ./macfleet_restart.sh --schedule weekly

Fleet Deployment

# Deploy immediate restart to entire fleet
sudo ./macfleet_restart.sh --deploy-fleet immediate

# Deploy weekly maintenance schedule
sudo ./macfleet_restart.sh --deploy-fleet weekly

Custom Scheduling

# Schedule restart for 3:00 AM
sudo ./macfleet_restart.sh --schedule custom 0300

# Schedule restart for 6:00 PM
sudo ./macfleet_restart.sh --schedule custom 1800

Compliance and Monitoring

Restart Compliance Frameworks

NIST Cybersecurity Framework

  • 🛡️ Identify: Track system uptime and restart requirements
  • 🔒 Protect: Ensure security updates are applied via restarts
  • 🔍 Detect: Monitor for missed maintenance windows
  • 🚨 Respond: Automated restart scheduling and enforcement
  • ♻️ Recover: Emergency restart capabilities for incident response

SOX Compliance

  • 📋 Audit trails for all restart activities
  • 🔐 Access controls for restart scheduling
  • 📊 Compliance reporting with system uptime tracking

HIPAA Technical Safeguards

  • 🏥 System maintenance ensuring security patches are active
  • 📝 Audit controls with comprehensive restart logging

Monitoring Metrics

# Key metrics tracked automatically:
# - System uptime duration
# - Last restart timestamp
# - Pending software updates
# - Restart compliance score
# - Failed restart attempts
# - Maintenance window adherence

Important Security Notes

  • 🔐 Requires administrative privileges for restart scheduling
  • 📝 All restart activities are audited and logged for compliance
  • 🔔 User notifications provide grace periods for work saving
  • 🏥 System health checks prevent restarts during critical operations
  • ⏰ Business hours protection prevents disruption to productivity
  • 🚨 Emergency override available for critical security incidents

Troubleshooting

Common Issues

# Check if restart is already scheduled
sudo shutdown -q

# Cancel pending restart
sudo shutdown -c

# Check system logs for restart issues
log show --predicate 'eventMessage contains "shutdown"' --last 1d

# Verify launchd jobs
launchctl list | grep macfleet

Restart Failures

# Check for processes preventing restart
lsof +c 15 | grep COMMAND

# Force restart if system is unresponsive
sudo shutdown -r now

# Check system health before retry
./macfleet_restart.sh --status

Tutorial

Neue Updates und Verbesserungen zu Macfleet.

Konfiguration eines GitHub Actions Runners auf einem Mac Mini (Apple Silicon)

GitHub Actions Runner

GitHub Actions ist eine leistungsstarke CI/CD-Plattform, die es Ihnen ermöglicht, Ihre Software-Entwicklungsworkflows zu automatisieren. Während GitHub gehostete Runner anbietet, bieten selbst-gehostete Runner erhöhte Kontrolle und Anpassung für Ihr CI/CD-Setup. Dieses Tutorial führt Sie durch die Einrichtung, Konfiguration und Verbindung eines selbst-gehosteten Runners auf einem Mac mini zur Ausführung von macOS-Pipelines.

Voraussetzungen

Bevor Sie beginnen, stellen Sie sicher, dass Sie haben:

  • Einen Mac mini (registrieren Sie sich bei Macfleet)
  • Ein GitHub-Repository mit Administratorrechten
  • Einen installierten Paketmanager (vorzugsweise Homebrew)
  • Git auf Ihrem System installiert

Schritt 1: Ein dediziertes Benutzerkonto erstellen

Erstellen Sie zunächst ein dediziertes Benutzerkonto für den GitHub Actions Runner:

# Das 'gh-runner' Benutzerkonto erstellen
sudo dscl . -create /Users/gh-runner
sudo dscl . -create /Users/gh-runner UserShell /bin/bash
sudo dscl . -create /Users/gh-runner RealName "GitHub runner"
sudo dscl . -create /Users/gh-runner UniqueID "1001"
sudo dscl . -create /Users/gh-runner PrimaryGroupID 20
sudo dscl . -create /Users/gh-runner NFSHomeDirectory /Users/gh-runner

# Das Passwort für den Benutzer setzen
sudo dscl . -passwd /Users/gh-runner ihr_passwort

# 'gh-runner' zur 'admin'-Gruppe hinzufügen
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Wechseln Sie zum neuen Benutzerkonto:

su gh-runner

Schritt 2: Erforderliche Software installieren

Installieren Sie Git und Rosetta 2 (wenn Sie Apple Silicon verwenden):

# Git installieren, falls noch nicht installiert
brew install git

# Rosetta 2 für Apple Silicon Macs installieren
softwareupdate --install-rosetta

Schritt 3: Den GitHub Actions Runner konfigurieren

  1. Gehen Sie zu Ihrem GitHub-Repository
  2. Navigieren Sie zu Einstellungen > Actions > Runners

GitHub Actions Runner

  1. Klicken Sie auf "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Wählen Sie macOS als Runner-Image und ARM64 als Architektur
  3. Folgen Sie den bereitgestellten Befehlen, um den Runner herunterzuladen und zu konfigurieren

GitHub Actions Runner

Erstellen Sie eine .env-Datei im _work-Verzeichnis des Runners:

# _work/.env Datei
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Führen Sie das run.sh-Skript in Ihrem Runner-Verzeichnis aus, um die Einrichtung abzuschließen.
  2. Überprüfen Sie, dass der Runner aktiv ist und auf Jobs im Terminal wartet, und überprüfen Sie die GitHub-Repository-Einstellungen für die Runner-Zuordnung und den Idle-Status.

GitHub Actions Runner

Schritt 4: Sudoers konfigurieren (Optional)

Wenn Ihre Actions Root-Privilegien benötigen, konfigurieren Sie die sudoers-Datei:

sudo visudo

Fügen Sie die folgende Zeile hinzu:

gh-runner ALL=(ALL) NOPASSWD: ALL

Schritt 5: Den Runner in Workflows verwenden

Konfigurieren Sie Ihren GitHub Actions Workflow, um den selbst-gehosteten Runner zu verwenden:

name: Beispiel-Workflow

on:
  workflow_dispatch:

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64]
    steps:
      - name: NodeJS installieren
        run: brew install node

Der Runner ist bei Ihrem Repository authentifiziert und mit self-hosted, macOS und ARM64 markiert. Verwenden Sie ihn in Ihren Workflows, indem Sie diese Labels im runs-on-Feld angeben:

runs-on: [self-hosted, macOS, ARM64]

Best Practices

  • Halten Sie Ihre Runner-Software auf dem neuesten Stand
  • Überwachen Sie regelmäßig Runner-Logs auf Probleme
  • Verwenden Sie spezifische Labels für verschiedene Runner-Typen
  • Implementieren Sie angemessene Sicherheitsmaßnahmen
  • Erwägen Sie die Verwendung mehrerer Runner für Lastverteilung

Fehlerbehebung

Häufige Probleme und Lösungen:

  1. Runner verbindet sich nicht:

    • Überprüfen Sie die Netzwerkverbindung
    • Überprüfen Sie die Gültigkeit des GitHub-Tokens
    • Stellen Sie angemessene Berechtigungen sicher
  2. Build-Fehler:

    • Überprüfen Sie die Xcode-Installation
    • Überprüfen Sie erforderliche Abhängigkeiten
    • Überprüfen Sie Workflow-Logs
  3. Berechtigungsprobleme:

    • Überprüfen Sie Benutzerberechtigungen
    • Überprüfen Sie sudoers-Konfiguration
    • Überprüfen Sie Dateisystem-Berechtigungen

Fazit

Sie haben jetzt einen selbst-gehosteten GitHub Actions Runner auf Ihrem Mac mini konfiguriert. Diese Einrichtung bietet Ihnen mehr Kontrolle über Ihre CI/CD-Umgebung und ermöglicht es Ihnen, macOS-spezifische Workflows effizient auszuführen.

Denken Sie daran, Ihren Runner regelmäßig zu warten und ihn mit den neuesten Sicherheitspatches und Software-Versionen auf dem neuesten Stand zu halten.

Native App

Macfleet native App

Macfleet Installationsanleitung

Macfleet ist eine leistungsstarke Flottenmanagement-Lösung, die speziell für Cloud-gehostete Mac Mini-Umgebungen entwickelt wurde. Als Mac Mini Cloud-Hosting-Anbieter können Sie Macfleet verwenden, um Ihre gesamte Flotte virtualisierter Mac-Instanzen zu überwachen, zu verwalten und zu optimieren.

Diese Installationsanleitung führt Sie durch die Einrichtung der Macfleet-Überwachung auf macOS-, Windows- und Linux-Systemen, um eine umfassende Übersicht über Ihre Cloud-Infrastruktur zu gewährleisten.

🍎 macOS

  • Laden Sie die .dmg-Datei für Mac hier herunter
  • Doppelklicken Sie auf die heruntergeladene .dmg-Datei
  • Ziehen Sie die Macfleet-App in den Anwendungsordner
  • Werfen Sie die .dmg-Datei aus
  • Öffnen Sie Systemeinstellungen > Sicherheit & Datenschutz
    • Datenschutz-Tab > Bedienungshilfen
    • Aktivieren Sie Macfleet, um Überwachung zu erlauben
  • Starten Sie Macfleet aus den Anwendungen
  • Die Verfolgung startet automatisch

🪟 Windows

  • Laden Sie die .exe-Datei für Windows hier herunter
  • Rechtsklick auf die .exe-Datei > "Als Administrator ausführen"
  • Folgen Sie dem Installationsassistenten
  • Akzeptieren Sie die Allgemeinen Geschäftsbedingungen
  • Erlauben Sie in Windows Defender, wenn aufgefordert
  • Gewähren Sie Anwendungsüberwachungsberechtigungen
  • Starten Sie Macfleet aus dem Startmenü
  • Die Anwendung beginnt automatisch mit der Verfolgung

🐧 Linux

  • Laden Sie das .deb-Paket (Ubuntu/Debian) oder .rpm (CentOS/RHEL) hier herunter
  • Installieren Sie mit Ihrem Paketmanager
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Erlauben Sie X11-Zugriffsberechtigungen, wenn aufgefordert
  • Fügen Sie den Benutzer zu entsprechenden Gruppen hinzu, falls erforderlich
  • Starten Sie Macfleet aus dem Anwendungsmenü
  • Die Anwendung beginnt automatisch mit der Verfolgung

Hinweis: Nach der Installation auf allen Systemen melden Sie sich mit Ihren Macfleet-Anmeldedaten an, um Daten mit Ihrem Dashboard zu synchronisieren.