Files
attendance-system.install/configure-host.sh
2026-06-25 16:26:33 -03:00

367 lines
15 KiB
Bash
Executable File

#!/bin/bash
# ==============================================================
# 🛠️ Configure Host
# Configura a máquina host: serviço Docker, limite de log
# e arquivo de observabilidade. Pode ser executado em
# ambientes novos ou já instalados.
# Uso:
# bash configure-host.sh
# ==============================================================
if [ -t 0 ]; then
:
else
exec < /dev/tty
fi
set -e
# ─── Cores ────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
# ─── Sudo ─────────────────────────────────────────────────────
SUDO=""
[ "$EUID" -ne 0 ] && SUDO="sudo"
_SUDO_REQUESTED=false
request_sudo() {
[ "$_SUDO_REQUESTED" = "true" ] && return 0
[ -z "$SUDO" ] && return 0
echo ""
print_warn "Esta etapa requer permissões de superusuário."
if ! sudo -v; then
print_error "Não foi possível obter permissões de superusuário."
exit 1
fi
_SUDO_REQUESTED=true
}
# ─── Utilitários ──────────────────────────────────────────────
print_banner() {
clear
echo -e "${CYAN}"
echo " ╔══════════════════════════════════════════════╗"
echo " ║ 🐳 Docker Service Installer ║"
echo " ║ Registra o Docker como serviço systemd ║"
echo " ╚══════════════════════════════════════════════╝"
echo -e "${NC}"
}
print_step() { echo -e "\n${BLUE}${BOLD}$1${NC}"; }
print_ok() { echo -e " ${GREEN}$1${NC}"; }
print_warn() { echo -e " ${YELLOW}$1${NC}"; }
print_error() { echo -e " ${RED}$1${NC}"; }
confirm() {
echo -ne " ${BOLD}$1${NC} ${CYAN}[s/N]${NC}: "
read -r resp
[[ "$resp" =~ ^[sS]$ ]]
}
# ══════════════════════════════════════════════════════════════
# Validar systemctl
# ══════════════════════════════════════════════════════════════
check_systemctl() {
print_step "Verificando systemctl..."
if ! command -v systemctl &>/dev/null; then
print_error "systemctl não encontrado. Este script requer systemd."
exit 1
fi
print_ok "systemctl encontrado ($(systemctl --version | head -1))"
}
# ══════════════════════════════════════════════════════════════
# Validar Docker instalado
# ══════════════════════════════════════════════════════════════
check_docker_installed() {
print_step "Verificando instalação do Docker..."
if ! command -v docker &>/dev/null; then
print_error "Docker não encontrado. Instale o Docker antes de continuar."
echo -e " ${DIM}Referência: https://docs.docker.com/engine/install/${NC}"
exit 1
fi
print_ok "Docker encontrado ($(docker --version))"
}
# ─── Diretório de instalação ──────────────────────────────────
INSTALL_DIR="attendancesystem"
# ══════════════════════════════════════════════════════════════
# Carregar / inicializar .env.observability
# ══════════════════════════════════════════════════════════════
_observability_defaults() {
local env_file="$1"
cat > "$env_file" <<'EOF'
SeventhLogs__CustomLevel__Warning__0=Microsoft.AspNetCore
SeventhLogs__CustomLevel__Warning__1=Microsoft.AspNetCore.Hosting.Diagnostics
SeventhLogs__CustomLevel__Warning__2=System.Net.Http.HttpClient.OtlpTraceExporter.ClientHandler
SeventhLogs__CustomLevel__Warning__3=System.Net.Http.HttpClient.OtlpTraceExporter.LogicalHandler
EOF
}
load_observability_env() {
local env_file
if [ -d "./${INSTALL_DIR}" ]; then
env_file="${INSTALL_DIR}/.env.observability"
else
env_file="./.env.observability"
fi
if [ ! -f "$env_file" ]; then
_observability_defaults "$env_file"
print_ok ".env.observability criado com configurações padrão"
return
fi
print_warn "Configuração de observabilidade encontrada em ${env_file}"
if confirm "Deseja manter as configurações atuais?"; then
print_ok ".env.observability mantido sem alterações"
return
fi
if confirm "Não manter as configurações atuais do arquivo .env.observability vai redefinir para as configurações padrões, você realmente deseja fazer isso?"; then
print_ok ".env.observability mantido sem alterações"
return
fi
_observability_defaults "$env_file"
print_ok ".env.observability redefinido para as configurações padrão"
}
# ══════════════════════════════════════════════════════════════
# Flags de controle
# ══════════════════════════════════════════════════════════════
NEEDS_SERVICE_CONFIG=false
NEEDS_LOG_CONFIG=false
# ══════════════════════════════════════════════════════════════
# Verificar status atual do serviço e configuração de log
# ══════════════════════════════════════════════════════════════
check_docker_service_status() {
print_step "Verificando status do serviço Docker..."
local enabled active
enabled=$(systemctl is-enabled docker 2>/dev/null || echo "disabled")
active=$(systemctl is-active docker 2>/dev/null || echo "inactive")
echo -e " ${DIM}Habilitado no boot : ${NC}${BOLD}${enabled}${NC}"
echo -e " ${DIM}Status atual : ${NC}${BOLD}${active}${NC}"
if [[ "$enabled" != "enabled" || "$active" != "active" ]]; then
NEEDS_SERVICE_CONFIG=true
fi
local daemon_json="/etc/docker/daemon.json"
if [ -f "$daemon_json" ] && grep -q '"max-size"' "$daemon_json"; then
echo -e " ${DIM}Limite de log : ${NC}${GREEN}${BOLD}configurado${NC}"
else
echo -e " ${DIM}Limite de log : ${NC}${YELLOW}${BOLD}não configurado${NC}"
NEEDS_LOG_CONFIG=true
fi
if [[ "$NEEDS_SERVICE_CONFIG" == "false" && "$NEEDS_LOG_CONFIG" == "false" ]]; then
echo ""
print_ok "Docker já está registrado, rodando e com limite de log configurado."
print_ok "Nenhuma ação necessária."
echo ""
exit 0
fi
}
# ══════════════════════════════════════════════════════════════
# Mostrar resumo antes de aplicar
# ══════════════════════════════════════════════════════════════
show_summary() {
echo ""
echo -e "${CYAN}${BOLD} ┌──────────────────────────────────────────────────────────────┐"
echo -e " │ Ações que serão executadas │"
echo -e " └──────────────────────────────────────────────────────────────┘${NC}"
echo ""
local step=1
if [[ "$NEEDS_SERVICE_CONFIG" == "true" ]]; then
echo -e " ${BOLD}${step}.${NC} Criar drop-in de política de restart:"
echo -e " ${DIM}/etc/systemd/system/docker.service.d/restart-policy.conf${NC}"
echo -e " ${DIM}→ Restart=always | RestartSec=5${NC}"
echo ""
step=$((step + 1))
echo -e " ${BOLD}${step}.${NC} Recarregar o daemon do systemd"
echo -e " ${DIM}→ systemctl daemon-reload${NC}"
echo ""
step=$((step + 1))
echo -e " ${BOLD}${step}.${NC} Habilitar o Docker para iniciar com o SO"
echo -e " ${DIM}→ systemctl enable docker${NC}"
echo ""
step=$((step + 1))
echo -e " ${BOLD}${step}.${NC} Iniciar o serviço Docker imediatamente"
echo -e " ${DIM}→ systemctl start docker${NC}"
echo ""
step=$((step + 1))
fi
if [[ "$NEEDS_LOG_CONFIG" == "true" ]]; then
echo -e " ${BOLD}${step}.${NC} Configurar limite de log em /etc/docker/daemon.json"
echo -e " ${DIM}→ log-driver: json-file | max-size: 100m | max-file: 5${NC}"
echo ""
step=$((step + 1))
echo -e " ${BOLD}${step}.${NC} Reiniciar o Docker para aplicar a configuração de log"
echo -e " ${DIM}→ systemctl restart docker${NC}"
echo ""
fi
echo -e " ──────────────────────────────────────────────────────────────"
echo ""
if ! confirm "Deseja aplicar as configurações acima?"; then
echo ""
print_warn "Operação cancelada. Nenhuma alteração foi feita."
echo ""
exit 0
fi
}
# ══════════════════════════════════════════════════════════════
# Aplicar configuração do serviço systemd
# ══════════════════════════════════════════════════════════════
configure_docker_service() {
[[ "$NEEDS_SERVICE_CONFIG" == "false" ]] && return 0
print_step "Configurando serviço Docker no systemd..."
request_sudo
local override_dir="/etc/systemd/system/docker.service.d"
$SUDO mkdir -p "$override_dir"
$SUDO tee "$override_dir/restart-policy.conf" > /dev/null <<'EOF'
[Service]
Restart=always
RestartSec=5
EOF
print_ok "Drop-in de restart criado em ${override_dir}/restart-policy.conf"
$SUDO systemctl daemon-reload
print_ok "systemctl daemon-reload executado"
$SUDO systemctl enable docker
print_ok "Docker habilitado para iniciar com o SO"
$SUDO systemctl start docker
print_ok "Docker iniciado"
}
# ══════════════════════════════════════════════════════════════
# Configurar limite de log do Docker
# ══════════════════════════════════════════════════════════════
configure_docker_log_limit() {
[[ "$NEEDS_LOG_CONFIG" == "false" ]] && return 0
print_step "Configurando limite de log do Docker..."
request_sudo
local daemon_json="/etc/docker/daemon.json"
if [ -f "$daemon_json" ]; then
$SUDO cp "$daemon_json" "${daemon_json}.bak"
print_warn "Backup do daemon.json criado em ${daemon_json}.bak"
fi
$SUDO mkdir -p "$(dirname "$daemon_json")"
$SUDO tee "$daemon_json" > /dev/null <<'EOF'
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m",
"max-file": "5"
}
}
EOF
print_ok "Limite de log configurado em ${daemon_json} (max-size: 100m, max-file: 5)"
$SUDO systemctl restart docker
print_ok "Docker reiniciado para aplicar a configuração de log"
}
# ══════════════════════════════════════════════════════════════
# Validar resultado final
# ══════════════════════════════════════════════════════════════
verify_result() {
print_step "Validando configuração..."
if ! systemctl is-active --quiet docker; then
print_error "O serviço Docker não está ativo após a configuração."
echo -e " ${DIM}Verifique os logs com: journalctl -u docker --no-pager -n 20${NC}"
exit 1
fi
local daemon_json="/etc/docker/daemon.json"
if [ ! -f "$daemon_json" ] || ! grep -q '"max-size"' "$daemon_json"; then
print_error "Limite de log não encontrado em ${daemon_json} após a configuração."
exit 1
fi
echo ""
echo -e "${GREEN}${BOLD} ╔══════════════════════════════════════════════╗"
echo -e " ║ ✅ Docker configurado com sucesso! ║"
echo -e " ╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e " ${BOLD}Status final:${NC}"
echo -e " Habilitado no boot : ${GREEN}$(systemctl is-enabled docker)${NC}"
echo -e " Rodando agora : ${GREEN}$(systemctl is-active docker)${NC}"
echo -e " Política de restart: ${GREEN}always (RestartSec=5s)${NC}"
echo -e " Limite de log : ${GREEN}max-size=100m, max-file=5${NC}"
echo ""
echo -e " ${DIM}Comandos úteis:"
echo -e " systemctl status docker"
echo -e " journalctl -u docker -f${NC}"
echo ""
}
# ══════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════
main() {
print_banner
load_observability_env
check_systemctl
check_docker_installed
check_docker_service_status
show_summary
configure_docker_service
configure_docker_log_limit
verify_result
}
main "$@"