Files
dex/install_alloy.ps1
2026-04-09 11:04:36 +02:00

133 lines
6.1 KiB
PowerShell

#requires -RunAsAdministrator
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# ==============================================================================
# Parámetros Globales
# ==============================================================================
$RepoUrl = "https://git.insidemicro.com/panotuco/dex.git"
$RepoLocalPath = "C:\ProgramData\Alloy\repo_config"
$DataPath = "C:\ProgramData\Alloy"
$ScriptsRoot = Join-Path $DataPath "scripts"
$BookmarksPath = Join-Path $DataPath "bookmarks"
$TmpDir = Join-Path $env:TEMP "grafana-alloy-install"
$TaskNameSync = "Sync Alloy Config from Git"
$SyncScriptPath = Join-Path $ScriptsRoot "sync-alloy-git.ps1"
$GitHubLatestApi = "https://api.github.com/repos/grafana/alloy/releases/latest"
# ==============================================================================
# Utilidades
# ==============================================================================
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$line = "[{0}] [{1}] {2}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level, $Message
Write-Host $line
}
function Ensure-Directory {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
New-Item -ItemType Directory -Path $Path -Force | Out-Null
}
}
# ==============================================================================
# Preparación de Directorios
# ==============================================================================
Ensure-Directory -Path $TmpDir
Ensure-Directory -Path $ScriptsRoot
Ensure-Directory -Path $DataPath
Ensure-Directory -Path $BookmarksPath
# ==============================================================================
# 1. Instalación de Grafana Alloy
# ==============================================================================
$installerName = "alloy-installer-windows-amd64.exe"
$installerPath = Join-Path $TmpDir $installerName
Write-Log "Consultando última versión de Grafana Alloy..."
try {
$release = Invoke-RestMethod -Uri $GitHubLatestApi -Headers @{ "Accept" = "application/vnd.github+json" }
$asset = $release.assets | Where-Object { $_.name -eq $installerName } | Select-Object -First 1
$downloadUrl = $asset.browser_download_url
Write-Log "Descargando e instalando Alloy (paciencia...)"
Invoke-WebRequest -Uri $downloadUrl -OutFile $installerPath
$installProcess = Start-Process -FilePath $installerPath -ArgumentList "/S" -Wait -PassThru
} catch {
Write-Log "Error instalando Alloy: $_" -Level "ERROR"
exit 1
}
# Detectar ruta real de instalación
$InstallRoot = Join-Path $env:ProgramFiles "GrafanaLabs\Alloy"
if (-not (Test-Path $InstallRoot)) { $InstallRoot = Join-Path $env:ProgramFiles "Alloy" }
$AlloyConfigPath = Join-Path $InstallRoot "config.alloy"
# ==============================================================================
# 2. Instalación de Git y Refresco de Entorno
# ==============================================================================
if (!(Get-Command git -ErrorAction SilentlyContinue)) {
Write-Log "Git no detectado. Instalando vía winget..."
$process = Start-Process winget -ArgumentList "install --id Git.Git -e --source winget --accept-package-agreements --accept-source-agreements" -Wait -PassThru
# Refrescar el PATH para la sesión actual
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
}
# ==============================================================================
# 3. Clonación del Repositorio
# ==============================================================================
if (!(Test-Path $RepoLocalPath)) {
Write-Log "Clonando repositorio de configuración: $RepoUrl"
git clone $RepoUrl $RepoLocalPath
}
# ==============================================================================
# 4. Creación del Script de Sincronización (GitOps)
# ==============================================================================
# NOTA: Ajustar 'origin/main' por 'origin/master' si tu rama se llama distinto
$SyncScriptContent = @"
Set-Location "$RepoLocalPath"
git fetch origin
`$local = git rev-parse HEAD
`$remote = git rev-parse origin/main
if (`$local -ne `$remote) {
Write-Output "Nueva version detectada. Aplicando cambios..."
git reset --hard origin/main
Copy-Item -Path (Join-Path "$RepoLocalPath" "config.alloy") -Destination "$AlloyConfigPath" -Force
Restart-Service -Name "Alloy" -Force
Write-Output "Configuracion actualizada y servicio reiniciado"
} else {
Write-Output "Todo al dia. No hay cambios."
}
"@
Set-Content -Path $SyncScriptPath -Value $SyncScriptContent -Encoding UTF8
# ==============================================================================
# 5. Registro de Tarea Programada (SYSTEM)
# ==============================================================================
Write-Log "Configurando tarea programada (cada 10 min)..."
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
$actionSync = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$SyncScriptPath`""
$trigger1 = New-ScheduledTaskTrigger -AtStartup
$trigger2 = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName $TaskNameSync -Action $actionSync -Trigger @($trigger1, $trigger2) -Principal $principal -Settings $settings -Force | Out-Null
# ==============================================================================
# 6. Arranque Inicial y Verificación
# ==============================================================================
Write-Log "Ejecutando sincronización inicial..."
& $SyncScriptPath
Write-Log "========================================================="
Write-Log " PROCESO COMPLETADO CON ÉXITO"
Write-Log " Config en: $AlloyConfigPath"
Write-Log " El equipo se sincronizará automáticamente con Git."
Write-Log "========================================================="