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.

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

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.