This commit is contained in:
2026-04-09 11:01:34 +02:00
parent 0bf2fae6ac
commit 52af6a99e6

View File

@@ -2,9 +2,9 @@
Set-StrictMode -Version Latest Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
# ========================= # ==============================================================================
# Parámetros Globales # Parámetros Globales
# ========================= # ==============================================================================
$RepoUrl = "https://git.insidemicro.com/panotuco/dex.git" $RepoUrl = "https://git.insidemicro.com/panotuco/dex.git"
$RepoLocalPath = "C:\ProgramData\Alloy\repo_config" $RepoLocalPath = "C:\ProgramData\Alloy\repo_config"
$DataPath = "C:\ProgramData\Alloy" $DataPath = "C:\ProgramData\Alloy"
@@ -13,20 +13,17 @@ $BookmarksPath = Join-Path $DataPath "bookmarks"
$TmpDir = Join-Path $env:TEMP "grafana-alloy-install" $TmpDir = Join-Path $env:TEMP "grafana-alloy-install"
$TaskNameSync = "Sync Alloy Config from Git" $TaskNameSync = "Sync Alloy Config from Git"
$TaskNameBoot = "Send Windows Boot Event to Loki"
$SyncScriptPath = Join-Path $ScriptsRoot "sync-alloy-git.ps1" $SyncScriptPath = Join-Path $ScriptsRoot "sync-alloy-git.ps1"
$BootScriptPath = Join-Path $ScriptsRoot "send-boot-event.ps1"
$GitHubLatestApi = "https://api.github.com/repos/grafana/alloy/releases/latest" $GitHubLatestApi = "https://api.github.com/repos/grafana/alloy/releases/latest"
# ========================= # ==============================================================================
# Utilidades # Utilidades
# ========================= # ==============================================================================
function Write-Log { function Write-Log {
param([string]$Message, [string]$Level = "INFO") param([string]$Message, [string]$Level = "INFO")
$line = "[{0}] [{1}] {2}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level, $Message $line = "[{0}] [{1}] {2}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level, $Message
Write-Host $line Write-Host $line -ForegroundColor (If ($Level -eq "ERROR") { "Red" } Else { "White" })
} }
function Ensure-Directory { function Ensure-Directory {
@@ -36,51 +33,62 @@ function Ensure-Directory {
} }
} }
# ========================= # ==============================================================================
# Validaciones e Directorios # Preparación de Directorios
# ========================= # ==============================================================================
Ensure-Directory -Path $TmpDir Ensure-Directory -Path $TmpDir
Ensure-Directory -Path $ScriptsRoot Ensure-Directory -Path $ScriptsRoot
Ensure-Directory -Path $DataPath Ensure-Directory -Path $DataPath
Ensure-Directory -Path $BookmarksPath Ensure-Directory -Path $BookmarksPath
# ========================= # ==============================================================================
# 1. Instalación de Grafana Alloy # 1. Instalación de Grafana Alloy
# ========================= # ==============================================================================
$installerName = "alloy-installer-windows-amd64.exe" $installerName = "alloy-installer-windows-amd64.exe"
$installerPath = Join-Path $TmpDir $installerName $installerPath = Join-Path $TmpDir $installerName
Write-Log "Consultando última release de Grafana Alloy..." Write-Log "Consultando última versión de Grafana Alloy..."
$release = Invoke-RestMethod -Uri $GitHubLatestApi -Headers @{ "Accept" = "application/vnd.github+json" } try {
$asset = $release.assets | Where-Object { $_.name -eq $installerName } | Select-Object -First 1 $release = Invoke-RestMethod -Uri $GitHubLatestApi -Headers @{ "Accept" = "application/vnd.github+json" }
$downloadUrl = $asset.browser_download_url $asset = $release.assets | Where-Object { $_.name -eq $installerName } | Select-Object -First 1
$downloadUrl = $asset.browser_download_url
Write-Log "Descargando e instalando Alloy..." Write-Log "Descargando e instalando Alloy (paciencia...)"
Invoke-WebRequest -Uri $downloadUrl -OutFile $installerPath Invoke-WebRequest -Uri $downloadUrl -OutFile $installerPath
$installProcess = Start-Process -FilePath $installerPath -ArgumentList "/S" -Wait -PassThru $installProcess = Start-Process -FilePath $installerPath -ArgumentList "/S" -Wait -PassThru
} catch {
Write-Log "Error instalando Alloy: $_" -Level "ERROR"
exit 1
}
# Detectar ruta de instalación (normalmente Program Files\GrafanaLabs\Alloy) # Detectar ruta real de instalación
$InstallRoot = Join-Path $env:ProgramFiles "GrafanaLabs\Alloy" $InstallRoot = Join-Path $env:ProgramFiles "GrafanaLabs\Alloy"
if (-not (Test-Path $InstallRoot)) { $InstallRoot = Join-Path $env:ProgramFiles "Alloy" } if (-not (Test-Path $InstallRoot)) { $InstallRoot = Join-Path $env:ProgramFiles "Alloy" }
$AlloyConfigPath = Join-Path $InstallRoot "config.alloy" $AlloyConfigPath = Join-Path $InstallRoot "config.alloy"
# ========================= # ==============================================================================
# 2. Instalación de Git y Clonación # 2. Instalación de Git y Refresco de Entorno
# ========================= # ==============================================================================
if (!(Get-Command git -ErrorAction SilentlyContinue)) { if (!(Get-Command git -ErrorAction SilentlyContinue)) {
Write-Log "Instalando Git vía winget..." Write-Log "Git no detectado. Instalando vía winget..."
winget install --id Git.Git -e --source winget --accept-package-agreements --accept-source-agreements $process = Start-Process winget -ArgumentList "install --id Git.Git -e --source winget --accept-package-agreements --accept-source-agreements" -Wait -PassThru
$env:Path += ";C:\Program Files\Git\cmd"
# 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)) { if (!(Test-Path $RepoLocalPath)) {
Write-Log "Clonando repositorio de configuración..." Write-Log "Clonando repositorio de configuración: $RepoUrl"
git clone $RepoUrl $RepoLocalPath git clone $RepoUrl $RepoLocalPath
} }
# ========================= # ==============================================================================
# 3. Script de Sincronización (GitOps) # 4. Creación del Script de Sincronización (GitOps)
# ========================= # ==============================================================================
# NOTA: Ajustar 'origin/main' por 'origin/master' si tu rama se llama distinto
$SyncScriptContent = @" $SyncScriptContent = @"
Set-Location "$RepoLocalPath" Set-Location "$RepoLocalPath"
git fetch origin git fetch origin
@@ -88,32 +96,38 @@ git fetch origin
`$remote = git rev-parse origin/main `$remote = git rev-parse origin/main
if (`$local -ne `$remote) { if (`$local -ne `$remote) {
Write-Output "Nueva version detectada. Aplicando cambios..."
git reset --hard origin/main git reset --hard origin/main
Copy-Item -Path (Join-Path "$RepoLocalPath" "config.alloy") -Destination "$AlloyConfigPath" -Force Copy-Item -Path (Join-Path "$RepoLocalPath" "config.alloy") -Destination "$AlloyConfigPath" -Force
Restart-Service -Name "Alloy" -Force Restart-Service -Name "Alloy" -Force
Write-Output "Configuracion actualizada y servicio reiniciado" Write-Output "Configuracion actualizada y servicio reiniciado"
} else {
Write-Output "Todo al dia. No hay cambios."
} }
"@ "@
Set-Content -Path $SyncScriptPath -Value $SyncScriptContent -Encoding UTF8 Set-Content -Path $SyncScriptPath -Value $SyncScriptContent -Encoding UTF8
# ==============================================================================
# 5. Registro de Tarea Programada (SYSTEM)
# ========================= # ==============================================================================
# 5. Registro de Tareas Programadas Write-Log "Configurando tarea programada (cada 10 min)..."
# =========================
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
# Tarea Sync (Cada 10 min)
$actionSync = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$SyncScriptPath`"" $actionSync = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$SyncScriptPath`""
$triggerSync = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 10) $trigger1 = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -TaskName $TaskNameSync -Action $actionSync -Trigger $triggerSync -Principal $principal -Settings $settings -Force $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
# ========================= # ==============================================================================
Write-Log "Sincronizando configuración inicial..." # 6. Arranque Inicial y Verificación
# ==============================================================================
Write-Log "Ejecutando sincronización inicial..."
& $SyncScriptPath & $SyncScriptPath
Write-Log "Proceso completado."
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 "========================================================="