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.

Cache Management and Clearing on macOS

Manage and clear various types of cache across your MacFleet devices using command-line tools. This tutorial covers system cache, browser cache, application cache, and enterprise-wide cache management policies for optimal performance and storage management.

Understanding macOS Cache System

macOS maintains several types of cache to improve system and application performance:

Cache Types

  • System Cache - Logs, diagnostic reports, temporary system files
  • User Cache - Application-specific temporary files and data
  • Browser Cache - Web browsing data, cookies, session storage
  • Application Cache - App-specific cached data and preferences
  • Font Cache - System and user font cache files

Cache Locations

  • System: /var/log/, /Library/Caches/, /System/Library/Caches/
  • User: ~/Library/Caches/, ~/Library/Application Support/
  • Browser: Browser-specific directories within user library
  • Downloads: ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV*

System Cache Management

Clear System Cache

#!/bin/bash

# Clear system-wide cache files
echo "🧹 Clearing system cache..."

# Clear system logs (with size limit for safety)
echo "Clearing system logs..."
sudo find /var/log -name "*.log" -type f -size +100M -delete 2>/dev/null
sudo find /var/log -name "*.out" -type f -size +50M -delete 2>/dev/null

# Clear system caches
echo "Clearing system caches..."
sudo rm -rf /Library/Caches/* 2>/dev/null
sudo rm -rf /System/Library/Caches/* 2>/dev/null

# Clear temporary files
echo "Clearing temporary files..."
sudo rm -rf /tmp/* 2>/dev/null
sudo rm -rf /var/tmp/* 2>/dev/null

echo "✅ System cache cleared successfully"

Clear User Cache

#!/bin/bash

# Clear current user's cache files
USER=$(whoami)
echo "🗂️ Clearing user cache for: $USER"

# Clear user caches
echo "Clearing user caches..."
rm -rf ~/Library/Caches/* 2>/dev/null

# Clear user logs
echo "Clearing user logs..."
rm -rf ~/Library/Logs/* 2>/dev/null

# Clear QuickLook thumbnails
echo "Clearing QuickLook thumbnails..."
rm -rf ~/Library/Caches/com.apple.QuickLook.thumbnailcache/* 2>/dev/null

# Clear Spotlight cache
echo "Clearing Spotlight cache..."
sudo mdutil -E / 2>/dev/null

echo "✅ User cache cleared successfully"

Browser Cache Management

Clear Safari Cache

#!/bin/bash

# Clear Safari browser cache
echo "🌐 Clearing Safari cache..."

# Check if Safari is running
if pgrep -x "Safari" > /dev/null; then
    echo "⚠️ Safari is running. Please close Safari first."
    read -p "Press Enter to continue after closing Safari..."
fi

# Clear Safari cache files
rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
rm -rf ~/Library/Safari/LocalStorage/* 2>/dev/null
rm -rf ~/Library/Safari/Databases/* 2>/dev/null
rm -rf ~/Library/Safari/WebpageIcons.db 2>/dev/null

# Clear Safari downloads history
sqlite3 ~/Library/Safari/Downloads.plist "DELETE FROM Downloads;" 2>/dev/null

echo "✅ Safari cache cleared successfully"

Clear Chrome Cache

#!/bin/bash

# Clear Google Chrome browser cache
echo "🔍 Clearing Google Chrome cache..."

# Check if Chrome is installed
if [[ ! -d ~/Library/Application\ Support/Google/Chrome ]]; then
    echo "ℹ️ Google Chrome not found on this system"
    exit 0
fi

# Check if Chrome is running
if pgrep -x "Google Chrome" > /dev/null; then
    echo "⚠️ Chrome is running. Please close Chrome first."
    read -p "Press Enter to continue after closing Chrome..."
fi

# Clear Chrome cache files
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Cache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/GPUCache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/*.ldb 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/*.log 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Extension\ State/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Session\ Storage/* 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Current\ Session 2>/dev/null
rm -rf ~/Library/Application\ Support/Google/Chrome/*/Storage/ext/* 2>/dev/null

echo "✅ Chrome cache cleared successfully"

Clear Firefox Cache

#!/bin/bash

# Clear Mozilla Firefox browser cache
echo "🦊 Clearing Firefox cache..."

# Check if Firefox is installed
if [[ ! -d ~/Library/Application\ Support/Firefox ]]; then
    echo "ℹ️ Firefox not found on this system"
    exit 0
fi

# Check if Firefox is running
if pgrep -x "firefox" > /dev/null; then
    echo "⚠️ Firefox is running. Please close Firefox first."
    read -p "Press Enter to continue after closing Firefox..."
fi

# Find Firefox profile directories
for profile in ~/Library/Application\ Support/Firefox/Profiles/*; do
    if [[ -d "$profile" ]]; then
        echo "Clearing Firefox profile: $(basename "$profile")"
        rm -rf "$profile/cache2"/* 2>/dev/null
        rm -rf "$profile/thumbnails"/* 2>/dev/null
        rm -rf "$profile/cookies.sqlite-wal" 2>/dev/null
        rm -rf "$profile/webappsstore.sqlite" 2>/dev/null
    fi
done

echo "✅ Firefox cache cleared successfully"

Clear Opera Cache

#!/bin/bash

# Clear Opera browser cache
echo "🎭 Clearing Opera cache..."

# Check if Opera is installed
if [[ ! -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
    echo "ℹ️ Opera not found on this system"
    exit 0
fi

# Check if Opera is running
if pgrep -x "Opera" > /dev/null; then
    echo "⚠️ Opera is running. Please close Opera first."
    read -p "Press Enter to continue after closing Opera..."
fi

# Clear Opera cache files
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Cache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/GPUCache/* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Session\ Storage/* 2>/dev/null

echo "✅ Opera cache cleared successfully"

Application Cache Management

Clear Application Caches

#!/bin/bash

# Clear application-specific caches
echo "📱 Clearing application caches..."

# Clear application caches in Containers
echo "Clearing containerized application caches..."
for container in ~/Library/Containers/*; do
    if [[ -d "$container/Data/Library/Caches" ]]; then
        app_name=$(basename "$container")
        echo "Clearing cache for: $app_name"
        rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
    fi
done

# Clear Adobe cache
if [[ -d ~/Library/Caches/Adobe ]]; then
    echo "Clearing Adobe cache..."
    rm -rf ~/Library/Caches/Adobe/* 2>/dev/null
fi

# Clear Microsoft Office cache
if [[ -d ~/Library/Caches/Microsoft ]]; then
    echo "Clearing Microsoft Office cache..."
    rm -rf ~/Library/Caches/Microsoft/* 2>/dev/null
fi

# Clear Xcode cache
if [[ -d ~/Library/Developer/Xcode/DerivedData ]]; then
    echo "Clearing Xcode derived data..."
    rm -rf ~/Library/Developer/Xcode/DerivedData/* 2>/dev/null
fi

echo "✅ Application caches cleared successfully"

Clear Download History

#!/bin/bash

# Clear download history and quarantine database
echo "📥 Clearing download history..."

# Clear quarantine events (download history)
sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
    'DELETE FROM LSQuarantineEvent' 2>/dev/null

# Clear recent items
rm -rf ~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.RecentDocuments.sfl* 2>/dev/null
rm -rf ~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.RecentApplications.sfl* 2>/dev/null

echo "✅ Download history cleared successfully"

Clear Terminal History

#!/bin/bash

# Clear terminal command history
echo "💻 Clearing terminal history..."

# Clear bash history
rm -rf ~/.bash_sessions/* 2>/dev/null
rm -rf ~/.bash_history 2>/dev/null

# Clear zsh history
rm -rf ~/.zsh_sessions/* 2>/dev/null
rm -rf ~/.zsh_history 2>/dev/null

# Clear other shell histories
rm -rf ~/.history 2>/dev/null
rm -rf ~/.sh_history 2>/dev/null

echo "✅ Terminal history cleared successfully"

Enterprise Cache Management Script

#!/bin/bash

# MacFleet Cache Management Tool
# Comprehensive cache management for enterprise environments

# Configuration
LOG_FILE="/var/log/macfleet_cache.log"
BACKUP_DIR="/var/backups/macfleet/cache"
REPORT_DIR="/var/reports/macfleet/cache"
CONFIG_FILE="/etc/macfleet/cache_policy.conf"

# Cache policy settings
ENABLE_SYSTEM_CACHE_CLEAR=true
ENABLE_BROWSER_CACHE_CLEAR=true
ENABLE_APP_CACHE_CLEAR=true
ENABLE_DOWNLOAD_HISTORY_CLEAR=false
ENABLE_TERMINAL_HISTORY_CLEAR=false
CACHE_SIZE_THRESHOLD_MB=1000
CACHE_AGE_DAYS=30

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

# Setup directories
setup_directories() {
    for dir in "$BACKUP_DIR" "$REPORT_DIR" "$(dirname "$CONFIG_FILE")"; do
        if [[ ! -d "$dir" ]]; then
            sudo mkdir -p "$dir"
            log_action "Created directory: $dir"
        fi
    done
}

# Calculate cache size
calculate_cache_size() {
    local path="$1"
    if [[ -d "$path" ]]; then
        du -sm "$path" 2>/dev/null | awk '{print $1}'
    else
        echo "0"
    fi
}

# Generate cache report
generate_cache_report() {
    local report_file="$REPORT_DIR/cache_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "📊 Generating cache analysis report..."
    
    {
        echo "MacFleet Cache Analysis Report"
        echo "Generated: $(date)"
        echo "Hostname: $(hostname)"
        echo "User: $(whoami)"
        echo "================================="
        echo ""
        
        echo "=== System Cache Analysis ==="
        echo "System logs size: $(calculate_cache_size /var/log) MB"
        echo "System cache size: $(calculate_cache_size /Library/Caches) MB"
        echo "Temporary files size: $(calculate_cache_size /tmp) MB"
        echo ""
        
        echo "=== User Cache Analysis ==="
        echo "User cache size: $(calculate_cache_size ~/Library/Caches) MB"
        echo "User logs size: $(calculate_cache_size ~/Library/Logs) MB"
        echo "QuickLook cache size: $(calculate_cache_size ~/Library/Caches/com.apple.QuickLook.thumbnailcache) MB"
        echo ""
        
        echo "=== Browser Cache Analysis ==="
        if [[ -d ~/Library/Caches/com.apple.Safari ]]; then
            echo "Safari cache size: $(calculate_cache_size ~/Library/Caches/com.apple.Safari) MB"
        fi
        if [[ -d ~/Library/Application\ Support/Google/Chrome ]]; then
            echo "Chrome cache size: $(calculate_cache_size ~/Library/Application\ Support/Google/Chrome) MB"
        fi
        if [[ -d ~/Library/Application\ Support/Firefox ]]; then
            echo "Firefox cache size: $(calculate_cache_size ~/Library/Application\ Support/Firefox) MB"
        fi
        if [[ -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
            echo "Opera cache size: $(calculate_cache_size ~/Library/Application\ Support/com.operasoftware.Opera) MB"
        fi
        echo ""
        
        echo "=== Application Cache Analysis ==="
        local total_app_cache=0
        for container in ~/Library/Containers/*; do
            if [[ -d "$container/Data/Library/Caches" ]]; then
                local size=$(calculate_cache_size "$container/Data/Library/Caches")
                if [[ $size -gt 10 ]]; then  # Only report if > 10MB
                    echo "$(basename "$container"): ${size} MB"
                    total_app_cache=$((total_app_cache + size))
                fi
            fi
        done
        echo "Total application cache: ${total_app_cache} MB"
        echo ""
        
        echo "=== Disk Usage Summary ==="
        echo "Available disk space: $(df -h / | awk 'NR==2{print $4}')"
        echo "Total cache estimate: $(($(calculate_cache_size ~/Library/Caches) + total_app_cache)) MB"
        
    } > "$report_file"
    
    echo "📊 Report saved to: $report_file"
    log_action "Cache report generated: $report_file"
}

# Selective cache clearing based on policy
clear_cache_selective() {
    echo "🧹 Starting selective cache clearing based on enterprise policy..."
    log_action "Starting selective cache clearing"
    
    local total_cleared=0
    
    # System cache clearing
    if [[ "$ENABLE_SYSTEM_CACHE_CLEAR" == "true" ]]; then
        echo "Clearing system cache..."
        local before_size=$(calculate_cache_size /Library/Caches)
        
        # Clear only old cache files
        find /Library/Caches -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
        sudo find /var/log -name "*.log" -type f -mtime +$CACHE_AGE_DAYS -size +100M -delete 2>/dev/null
        
        local after_size=$(calculate_cache_size /Library/Caches)
        local cleared=$((before_size - after_size))
        total_cleared=$((total_cleared + cleared))
        
        log_action "System cache cleared: ${cleared} MB"
    fi
    
    # User cache clearing
    echo "Clearing user cache..."
    local before_size=$(calculate_cache_size ~/Library/Caches)
    
    # Clear old cache files only
    find ~/Library/Caches -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
    find ~/Library/Logs -type f -mtime +$CACHE_AGE_DAYS -delete 2>/dev/null
    
    local after_size=$(calculate_cache_size ~/Library/Caches)
    local cleared=$((before_size - after_size))
    total_cleared=$((total_cleared + cleared))
    
    log_action "User cache cleared: ${cleared} MB"
    
    # Browser cache clearing
    if [[ "$ENABLE_BROWSER_CACHE_CLEAR" == "true" ]]; then
        echo "Clearing browser caches..."
        clear_browser_caches
        log_action "Browser caches cleared"
    fi
    
    # Application cache clearing
    if [[ "$ENABLE_APP_CACHE_CLEAR" == "true" ]]; then
        echo "Clearing application caches..."
        clear_application_caches
        log_action "Application caches cleared"
    fi
    
    # Download history clearing
    if [[ "$ENABLE_DOWNLOAD_HISTORY_CLEAR" == "true" ]]; then
        echo "Clearing download history..."
        sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
            'DELETE FROM LSQuarantineEvent WHERE LSQuarantineTimeStamp < datetime("now", "-30 days")' 2>/dev/null
        log_action "Download history cleared"
    fi
    
    # Terminal history clearing
    if [[ "$ENABLE_TERMINAL_HISTORY_CLEAR" == "true" ]]; then
        echo "Clearing terminal history..."
        rm -rf ~/.bash_sessions/* 2>/dev/null
        rm -rf ~/.zsh_sessions/* 2>/dev/null
        log_action "Terminal history cleared"
    fi
    
    echo "✅ Cache clearing completed. Total cleared: ${total_cleared} MB"
    log_action "Cache clearing completed: ${total_cleared} MB cleared"
}

# Clear browser caches function
clear_browser_caches() {
    # Safari
    if [[ -d ~/Library/Caches/com.apple.Safari ]]; then
        rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
    fi
    
    # Chrome
    if [[ -d ~/Library/Application\ Support/Google/Chrome ]]; then
        find ~/Library/Application\ Support/Google/Chrome -name "Cache" -type d -exec rm -rf {}/* \; 2>/dev/null
        find ~/Library/Application\ Support/Google/Chrome -name "GPUCache" -type d -exec rm -rf {}/* \; 2>/dev/null
    fi
    
    # Firefox
    for profile in ~/Library/Application\ Support/Firefox/Profiles/*; do
        if [[ -d "$profile/cache2" ]]; then
            rm -rf "$profile/cache2"/* 2>/dev/null
        fi
    done
    
    # Opera
    if [[ -d ~/Library/Application\ Support/com.operasoftware.Opera ]]; then
        rm -rf ~/Library/Application\ Support/com.operasoftware.Opera/Cache/* 2>/dev/null
    fi
}

# Clear application caches function
clear_application_caches() {
    for container in ~/Library/Containers/*; do
        if [[ -d "$container/Data/Library/Caches" ]]; then
            # Only clear if cache size is above threshold
            local cache_size=$(calculate_cache_size "$container/Data/Library/Caches")
            if [[ $cache_size -gt $CACHE_SIZE_THRESHOLD_MB ]]; then
                rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
                log_action "Cleared cache for $(basename "$container"): ${cache_size} MB"
            fi
        fi
    done
}

# Emergency cache clearing
emergency_cache_clear() {
    echo "🚨 Emergency cache clearing - freeing maximum space..."
    log_action "Emergency cache clearing initiated"
    
    # Clear all user caches aggressively
    rm -rf ~/Library/Caches/* 2>/dev/null
    rm -rf ~/Library/Logs/* 2>/dev/null
    
    # Clear all browser data
    rm -rf ~/Library/Application\ Support/Google/Chrome/*/Cache/* 2>/dev/null
    rm -rf ~/Library/Application\ Support/Google/Chrome/*/GPUCache/* 2>/dev/null
    rm -rf ~/Library/Caches/com.apple.Safari/* 2>/dev/null
    rm -rf ~/Library/Application\ Support/Firefox/Profiles/*/cache2/* 2>/dev/null
    
    # Clear all application caches
    for container in ~/Library/Containers/*; do
        rm -rf "$container/Data/Library/Caches"/* 2>/dev/null
    done
    
    # Clear system caches (with sudo)
    sudo rm -rf /Library/Caches/* 2>/dev/null
    sudo rm -rf /tmp/* 2>/dev/null
    
    # Clear font caches
    sudo atsutil databases -remove 2>/dev/null
    
    echo "✅ Emergency cache clearing completed"
    log_action "Emergency cache clearing completed"
}

# Schedule automatic cache clearing
schedule_cache_clearing() {
    local schedule_type="$1"
    
    echo "📅 Setting up automatic cache clearing schedule..."
    
    local plist_file="$HOME/Library/LaunchAgents/com.macfleet.cache-cleaner.plist"
    
    case "$schedule_type" in
        "daily")
            local interval=86400  # 24 hours
            ;;
        "weekly")
            local interval=604800  # 7 days
            ;;
        "monthly")
            local interval=2592000  # 30 days
            ;;
        *)
            echo "❌ Invalid schedule type. Use: daily, weekly, monthly"
            return 1
            ;;
    esac
    
    cat > "$plist_file" << 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>com.macfleet.cache-cleaner</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>$(realpath "$0")</string>
        <string>clear</string>
    </array>
    <key>StartInterval</key>
    <integer>$interval</integer>
    <key>RunAtLoad</key>
    <false/>
</dict>
</plist>
EOF
    
    launchctl load "$plist_file" 2>/dev/null
    
    echo "✅ Automatic cache clearing scheduled ($schedule_type)"
    log_action "Cache clearing scheduled: $schedule_type"
}

# Main execution function
main() {
    local action="${1:-help}"
    local target="${2:-}"
    
    log_action "=== MacFleet Cache Management Started ==="
    
    setup_directories
    
    case "$action" in
        "analyze"|"report")
            generate_cache_report
            ;;
        "clear")
            clear_cache_selective
            ;;
        "emergency")
            emergency_cache_clear
            ;;
        "schedule")
            if [[ -n "$target" ]]; then
                schedule_cache_clearing "$target"
            else
                echo "❌ Please specify schedule type"
                echo "Usage: $0 schedule [daily|weekly|monthly]"
            fi
            ;;
        "system")
            echo "🧹 Clearing system cache only..."
            sudo rm -rf /Library/Caches/* 2>/dev/null
            sudo find /var/log -name "*.log" -type f -size +100M -delete 2>/dev/null
            ;;
        "user")
            echo "🗂️ Clearing user cache only..."
            rm -rf ~/Library/Caches/* 2>/dev/null
            rm -rf ~/Library/Logs/* 2>/dev/null
            ;;
        "browser")
            echo "🌐 Clearing browser cache only..."
            clear_browser_caches
            ;;
        "apps")
            echo "📱 Clearing application cache only..."
            clear_application_caches
            ;;
        "help"|*)
            echo "MacFleet Cache Management Tool"
            echo "Usage: $0 [action] [options]"
            echo ""
            echo "Actions:"
            echo "  analyze           - Generate cache analysis report"
            echo "  clear             - Clear cache based on enterprise policy"
            echo "  emergency         - Emergency cache clearing (maximum space)"
            echo "  schedule [type]   - Schedule automatic cache clearing"
            echo "  system            - Clear system cache only"
            echo "  user              - Clear user cache only"
            echo "  browser           - Clear browser cache only"
            echo "  apps              - Clear application cache only"
            echo "  help              - Show this help message"
            echo ""
            echo "Schedule Types:"
            echo "  daily             - Clear cache daily"
            echo "  weekly            - Clear cache weekly"
            echo "  monthly           - Clear cache monthly"
            ;;
    esac
    
    log_action "=== MacFleet Cache Management Completed ==="
}

# Execute main function
main "$@"

Cache Management Best Practices

Safe Cache Clearing Guidelines

Cache TypeSafety LevelRecommendation
System CacheHigh RiskClear selectively, avoid critical system files
User CacheMedium RiskSafe to clear, may reset preferences
Browser CacheLow RiskSafe to clear, will re-download web content
Application CacheMedium RiskCheck app-specific requirements
Download HistoryLow RiskConsider privacy implications

Performance Impact Assessment

# Measure cache clearing impact
echo "=== Before Cache Clearing ==="
echo "Available space: $(df -h / | awk 'NR==2{print $4}')"
echo "Cache size: $(du -sh ~/Library/Caches | awk '{print $1}')"

# Perform cache clearing
# ... cache clearing commands ...

echo "=== After Cache Clearing ==="
echo "Available space: $(df -h / | awk 'NR==2{print $4}')"
echo "Space recovered: [calculated difference]"

Security Considerations

  • Data Loss Prevention - Always backup important data before clearing caches
  • Application Impact - Some applications may need to rebuild caches after clearing
  • Performance Impact - Initial performance may be slower until caches rebuild
  • Privacy Implications - Clearing browser cache removes saved passwords and settings
  • System Stability - Avoid clearing critical system caches without proper testing

Troubleshooting

Cache Clearing Failures

# Check for locked files
lsof | grep "Library/Caches"

# Force quit applications using cache
sudo pkill -f "application_name"

# Check permissions
ls -la ~/Library/Caches/

Disk Space Not Freed

# Force filesystem update
sync

# Check for hidden files
ls -la ~/Library/Caches/

# Verify actual deletion
du -sh ~/Library/Caches/

Important Notes

  • Backup Important Data before running cache clearing scripts
  • Close Applications before clearing their specific caches
  • Test Scripts on individual devices before fleet deployment
  • Monitor Performance after cache clearing for any issues
  • Schedule Regular Cleaning to maintain optimal performance
  • Document Policies for compliance and auditing purposes

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.