Tutorial

Nuevas actualizaciones y mejoras para Macfleet.

Aviso importante

Los ejemplos de código y scripts proporcionados en estos tutoriales son solo para propósitos educativos. Macfleet no es responsable de ningún problema, daño o vulnerabilidad de seguridad que pueda surgir del uso, modificación o implementación de estos ejemplos. Siempre revisa y prueba el código en un entorno seguro antes de usarlo en sistemas de producción.

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

Nuevas actualizaciones y mejoras para Macfleet.

Configurando un Runner de GitHub Actions en un Mac Mini (Apple Silicon)

Runner de GitHub Actions

GitHub Actions es una plataforma poderosa de CI/CD que te permite automatizar tus flujos de trabajo de desarrollo de software. Aunque GitHub ofrece runners hospedados, los runners auto-hospedados proporcionan mayor control y personalización para tu configuración de CI/CD. Este tutorial te guía a través de la configuración y conexión de un runner auto-hospedado en un Mac mini para ejecutar pipelines de macOS.

Prerrequisitos

Antes de comenzar, asegúrate de tener:

  • Un Mac mini (regístrate en Macfleet)
  • Un repositorio de GitHub con derechos de administrador
  • Un gestor de paquetes instalado (preferiblemente Homebrew)
  • Git instalado en tu sistema

Paso 1: Crear una Cuenta de Usuario Dedicada

Primero, crea una cuenta de usuario dedicada para el runner de GitHub Actions:

# Crear la cuenta de usuario 'gh-runner'
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

# Establecer la contraseña para el usuario
sudo dscl . -passwd /Users/gh-runner tu_contraseña

# Agregar 'gh-runner' al grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Cambia a la nueva cuenta de usuario:

su gh-runner

Paso 2: Instalar Software Requerido

Instala Git y Rosetta 2 (si usas Apple Silicon):

# Instalar Git si no está ya instalado
brew install git

# Instalar Rosetta 2 para Macs Apple Silicon
softwareupdate --install-rosetta

Paso 3: Configurar el Runner de GitHub Actions

  1. Ve a tu repositorio de GitHub
  2. Navega a Configuración > Actions > Runners

Runner de GitHub Actions

  1. Haz clic en "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecciona macOS como imagen del runner y ARM64 como arquitectura
  3. Sigue los comandos proporcionados para descargar y configurar el runner

Runner de GitHub Actions

Crea un archivo .env en el directorio _work del runner:

# archivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Ejecuta el script run.sh en tu directorio del runner para completar la configuración.
  2. Verifica que el runner esté activo y escuchando trabajos en la terminal y revisa la configuración del repositorio de GitHub para la asociación del runner y el estado Idle.

Runner de GitHub Actions

Paso 4: Configurar Sudoers (Opcional)

Si tus acciones requieren privilegios de root, configura el archivo sudoers:

sudo visudo

Agrega la siguiente línea:

gh-runner ALL=(ALL) NOPASSWD: ALL

Paso 5: Usar el Runner en Flujos de Trabajo

Configura tu flujo de trabajo de GitHub Actions para usar el runner auto-hospedado:

name: Flujo de trabajo de muestra

on:
  workflow_dispatch:

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

El runner está autenticado en tu repositorio y etiquetado con self-hosted, macOS, y ARM64. Úsalo en tus flujos de trabajo especificando estas etiquetas en el campo runs-on:

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

Mejores Prácticas

  • Mantén tu software del runner actualizado
  • Monitorea regularmente los logs del runner para problemas
  • Usa etiquetas específicas para diferentes tipos de runners
  • Implementa medidas de seguridad apropiadas
  • Considera usar múltiples runners para balanceo de carga

Solución de Problemas

Problemas comunes y soluciones:

  1. Runner no conectando:

    • Verifica conectividad de red
    • Verifica validez del token de GitHub
    • Asegúrate de permisos apropiados
  2. Fallas de construcción:

    • Verifica instalación de Xcode
    • Verifica dependencias requeridas
    • Revisa logs del flujo de trabajo
  3. Problemas de permisos:

    • Verifica permisos de usuario
    • Verifica configuración de sudoers
    • Revisa permisos del sistema de archivos

Conclusión

Ahora tienes un runner auto-hospedado de GitHub Actions configurado en tu Mac mini. Esta configuración te proporciona más control sobre tu entorno de CI/CD y te permite ejecutar flujos de trabajo específicos de macOS de manera eficiente.

Recuerda mantener regularmente tu runner y mantenerlo actualizado con los últimos parches de seguridad y versiones de software.

Aplicación Nativa

Aplicación nativa de Macfleet

Guía de Instalación de Macfleet

Macfleet es una solución poderosa de gestión de flota diseñada específicamente para entornos de Mac Mini alojados en la nube. Como proveedor de hosting en la nube de Mac Mini, puedes usar Macfleet para monitorear, gestionar y optimizar toda tu flota de instancias Mac virtualizadas.

Esta guía de instalación te llevará a través de la configuración del monitoreo de Macfleet en sistemas macOS, Windows y Linux para asegurar una supervisión integral de tu infraestructura en la nube.

🍎 macOS

  • Descarga el archivo .dmg para Mac aquí
  • Haz doble clic en el archivo .dmg descargado
  • Arrastra la aplicación Macfleet a la carpeta Aplicaciones
  • Expulsa el archivo .dmg
  • Abre Preferencias del Sistema > Seguridad y Privacidad
    • Pestaña Privacidad > Accesibilidad
    • Marca Macfleet para permitir el monitoreo
  • Inicia Macfleet desde Aplicaciones
  • El seguimiento comienza automáticamente

🪟 Windows

  • Descarga el archivo .exe para Windows aquí
  • Haz clic derecho en el archivo .exe > "Ejecutar como administrador"
  • Sigue el asistente de instalación
  • Acepta los términos y condiciones
  • Permite en Windows Defender si se solicita
  • Concede permisos de monitoreo de aplicaciones
  • Inicia Macfleet desde el Menú Inicio
  • La aplicación comienza el seguimiento automáticamente

🐧 Linux

  • Descarga el paquete .deb (Ubuntu/Debian) o .rpm (CentOS/RHEL) aquí
  • Instala usando tu gestor de paquetes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permite permisos de acceso X11 si se solicita
  • Agrega el usuario a los grupos apropiados si es necesario
  • Inicia Macfleet desde el menú de Aplicaciones
  • La aplicación comienza el seguimiento automáticamente

Nota: Después de la instalación en todos los sistemas, inicia sesión con tus credenciales de Macfleet para sincronizar datos con tu panel de control.