Tutorial

Novas atualizações e melhorias para a Macfleet.

Aviso importante

Os exemplos de código e scripts fornecidos nestes tutoriais são apenas para fins educacionais. A Macfleet não é responsável por quaisquer problemas, danos ou vulnerabilidades de segurança que possam surgir do uso, modificação ou implementação destes exemplos. Sempre revise e teste o código em um ambiente seguro antes de usá-lo em sistemas de produção.

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

Novas atualizações e melhorias para a Macfleet.

Configurando um Runner do GitHub Actions em um Mac Mini (Apple Silicon)

Runner do GitHub Actions

GitHub Actions é uma plataforma poderosa de CI/CD que permite automatizar seus fluxos de trabalho de desenvolvimento de software. Embora o GitHub ofereça runners hospedados, runners auto-hospedados fornecem maior controle e personalização para sua configuração de CI/CD. Este tutorial o guia através da configuração e conexão de um runner auto-hospedado em um Mac mini para executar pipelines do macOS.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um Mac mini (registre-se no Macfleet)
  • Um repositório GitHub com direitos de administrador
  • Um gerenciador de pacotes instalado (preferencialmente Homebrew)
  • Git instalado em seu sistema

Passo 1: Criar uma Conta de Usuário Dedicada

Primeiro, crie uma conta de usuário dedicada para o runner do GitHub Actions:

# Criar a conta de usuário '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

# Definir a senha para o usuário
sudo dscl . -passwd /Users/gh-runner sua_senha

# Adicionar 'gh-runner' ao grupo 'admin'
sudo dscl . -append /Groups/admin GroupMembership gh-runner

Mude para a nova conta de usuário:

su gh-runner

Passo 2: Instalar Software Necessário

Instale Git e Rosetta 2 (se estiver usando Apple Silicon):

# Instalar Git se ainda não estiver instalado
brew install git

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

Passo 3: Configurar o Runner do GitHub Actions

  1. Vá para seu repositório GitHub
  2. Navegue para Configurações > Actions > Runners

Runner do GitHub Actions

  1. Clique em "New self-hosted runner" (https://github.com/<username>/<repository>/settings/actions/runners/new)
  2. Selecione macOS como imagem do runner e ARM64 como arquitetura
  3. Siga os comandos fornecidos para baixar e configurar o runner

Runner do GitHub Actions

Crie um arquivo .env no diretório _work do runner:

# arquivo _work/.env
ImageOS=macos15
XCODE_15_DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
  1. Execute o script run.sh em seu diretório do runner para completar a configuração.
  2. Verifique se o runner está ativo e ouvindo por trabalhos no terminal e verifique as configurações do repositório GitHub para a associação do runner e status Idle.

Runner do GitHub Actions

Passo 4: Configurar Sudoers (Opcional)

Se suas ações requerem privilégios de root, configure o arquivo sudoers:

sudo visudo

Adicione a seguinte linha:

gh-runner ALL=(ALL) NOPASSWD: ALL

Passo 5: Usar o Runner em Fluxos de Trabalho

Configure seu fluxo de trabalho do GitHub Actions para usar o runner auto-hospedado:

name: Fluxo de trabalho de exemplo

on:
  workflow_dispatch:

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

O runner está autenticado em seu repositório e rotulado com self-hosted, macOS, e ARM64. Use-o em seus fluxos de trabalho especificando estes rótulos no campo runs-on:

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

Melhores Práticas

  • Mantenha seu software do runner atualizado
  • Monitore regularmente os logs do runner para problemas
  • Use rótulos específicos para diferentes tipos de runners
  • Implemente medidas de segurança adequadas
  • Considere usar múltiplos runners para balanceamento de carga

Solução de Problemas

Problemas comuns e soluções:

  1. Runner não conectando:

    • Verifique conectividade de rede
    • Verifique validade do token GitHub
    • Certifique-se de permissões adequadas
  2. Falhas de build:

    • Verifique instalação do Xcode
    • Verifique dependências necessárias
    • Revise logs do fluxo de trabalho
  3. Problemas de permissão:

    • Verifique permissões do usuário
    • Verifique configuração sudoers
    • Revise permissões do sistema de arquivos

Conclusão

Agora você tem um runner auto-hospedado do GitHub Actions configurado em seu Mac mini. Esta configuração fornece mais controle sobre seu ambiente CI/CD e permite executar fluxos de trabalho específicos do macOS de forma eficiente.

Lembre-se de manter regularmente seu runner e mantê-lo atualizado com os patches de segurança e versões de software mais recentes.

Aplicativo Nativo

Aplicativo nativo do Macfleet

Guia de Instalação do Macfleet

Macfleet é uma solução poderosa de gerenciamento de frota projetada especificamente para ambientes Mac Mini hospedados na nuvem. Como provedor de hospedagem na nuvem Mac Mini, você pode usar o Macfleet para monitorar, gerenciar e otimizar toda sua frota de instâncias Mac virtualizadas.

Este guia de instalação o conduzirá através da configuração do monitoramento do Macfleet em sistemas macOS, Windows e Linux para garantir supervisão abrangente de sua infraestrutura na nuvem.

🍎 macOS

  • Baixe o arquivo .dmg para Mac aqui
  • Clique duas vezes no arquivo .dmg baixado
  • Arraste o aplicativo Macfleet para a pasta Aplicativos
  • Ejete o arquivo .dmg
  • Abra Preferências do Sistema > Segurança e Privacidade
    • Aba Privacidade > Acessibilidade
    • Marque Macfleet para permitir monitoramento
  • Inicie o Macfleet a partir de Aplicativos
  • O rastreamento inicia automaticamente

🪟 Windows

  • Baixe o arquivo .exe para Windows aqui
  • Clique com o botão direito no arquivo .exe > "Executar como administrador"
  • Siga o assistente de instalação
  • Aceite os termos e condições
  • Permita no Windows Defender se solicitado
  • Conceda permissões de monitoramento de aplicativo
  • Inicie o Macfleet a partir do Menu Iniciar
  • O aplicativo começa o rastreamento automaticamente

🐧 Linux

  • Baixe o pacote .deb (Ubuntu/Debian) ou .rpm (CentOS/RHEL) aqui
  • Instale usando seu gerenciador de pacotes
    • Ubuntu/Debian: sudo dpkg -i Macfleet-linux.deb
    • CentOS/RHEL: sudo rpm -ivh Macfleet-linux.rpm
  • Permita permissões de acesso X11 se solicitado
  • Adicione o usuário aos grupos apropriados se necessário
  • Inicie o Macfleet a partir do menu Aplicativos
  • O aplicativo começa o rastreamento automaticamente

Nota: Após a instalação em todos os sistemas, faça login com suas credenciais do Macfleet para sincronizar dados com seu painel de controle.