|
|
|
@@ -0,0 +1,499 @@
|
|
|
|
|
#Requires -Version 7.0
|
|
|
|
|
<#
|
|
|
|
|
.SYNOPSIS
|
|
|
|
|
Dang ky them mot gitea-runner tren PC nay (mac dinh: runner chi chay Docker, cho cac nhan
|
|
|
|
|
ubuntu-*) va cho no tu chay khi dang nhap, sau khi Docker Desktop da san sang
|
|
|
|
|
(docs/migration/README.md, D15).
|
|
|
|
|
|
|
|
|
|
.DESCRIPTION
|
|
|
|
|
Script lam, theo thu tu:
|
|
|
|
|
1. Tim runner dang co (exe + config.yaml): qua tien trinh gitea-runner dang chay, neu khong
|
|
|
|
|
thi qua scheduled task -ExistingTaskName (chay exe truc tiep hoac qua script .ps1), hoac
|
|
|
|
|
lay tu -RunnerExe / -ExistingConfig. Khong tim duoc thi in ra nhung gi thay duoc.
|
|
|
|
|
2. Tao -Dir va viet config.yaml rieng cho runner moi: capacity, timeout, nhan, cache.dir va
|
|
|
|
|
host.workdir_parent rieng (hai runner khong dung chung DB cua cache server);
|
|
|
|
|
docker_host va network chep tu config cu neu co (cau hinh Docker Desktop dang chay duoc).
|
|
|
|
|
3. Dang ky runner voi Gitea. Token duoc hoi khi chay, khong luu o dau ca. Bo qua neu -Dir da
|
|
|
|
|
co .runner: chay lai script de doi capacity / nhan / gioi han container la an toan.
|
|
|
|
|
4. Viet run-runner.ps1 (doi 'docker info' thanh cong roi moi chay daemon, log ra runner.log,
|
|
|
|
|
daemon thoat thi 30 giay sau chay lai) va tao scheduled task -TaskName chay luc dang nhap.
|
|
|
|
|
5. Neu co -SplitExistingRunner: bo cac nhan docker (ubuntu-*) khoi config.yaml cua runner cu
|
|
|
|
|
(sao luu truoc), de runner cu chi nhan job windows-latest (host mode), roi khoi dong lai no.
|
|
|
|
|
|
|
|
|
|
Thu muc mac dinh nam trong %LOCALAPPDATA% (chi user nay doc duoc): .runner trong do chua token
|
|
|
|
|
cua runner.
|
|
|
|
|
|
|
|
|
|
Token dang ky: https://git.poli0981.dev/user/settings/actions/runners > Create new runner.
|
|
|
|
|
Dung dan token vao dong lenh (lich su shell giu lai): script se hoi.
|
|
|
|
|
|
|
|
|
|
Khoi dong lai mot runner se NGAT job dang chay tren no: script hoi truoc (bo qua bang -Yes).
|
|
|
|
|
Cap nhat gitea-runner.exe sau nay: dung CA HAI task truoc, vi hai runner dung chung mot exe.
|
|
|
|
|
|
|
|
|
|
Chay -DryRun truoc de xem se lam gi.
|
|
|
|
|
|
|
|
|
|
.EXAMPLE
|
|
|
|
|
.\add-runner.ps1 -DryRun
|
|
|
|
|
.\add-runner.ps1 -Capacity 3
|
|
|
|
|
.\add-runner.ps1 -Capacity 3 -SplitExistingRunner
|
|
|
|
|
.\add-runner.ps1 -Capacity 4 -ContainerOptions '--memory=8g --cpus=4' # chay lai: chi doi config + restart
|
|
|
|
|
#>
|
|
|
|
|
[CmdletBinding()]
|
|
|
|
|
param(
|
|
|
|
|
[string] $Instance = 'https://git.poli0981.dev',
|
|
|
|
|
[string] $Name = "$($env:COMPUTERNAME.ToLowerInvariant())-docker",
|
|
|
|
|
[string] $Dir = (Join-Path $env:LOCALAPPDATA 'gitea-runner-docker'),
|
|
|
|
|
[ValidateRange(1, 16)]
|
|
|
|
|
[int] $Capacity = 3,
|
|
|
|
|
[string[]] $Labels = @(),
|
|
|
|
|
[string] $ContainerOptions = '--memory=8g --cpus=4',
|
|
|
|
|
[string] $Timeout = '3h',
|
|
|
|
|
[string] $TaskName = 'Gitea Runner (Docker)',
|
|
|
|
|
[string] $ExistingTaskName = 'Gitea Runner',
|
|
|
|
|
[string] $RunnerExe = '',
|
|
|
|
|
[string] $ExistingConfig = '',
|
|
|
|
|
[switch] $SplitExistingRunner,
|
|
|
|
|
[switch] $NoTask,
|
|
|
|
|
[switch] $Yes,
|
|
|
|
|
[switch] $DryRun
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
Set-StrictMode -Version Latest
|
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
|
|
|
|
|
|
|
|
# Nhan mac dinh, giong runbook section 1 (Runner labels). Chi dung khi -Labels rong va config cu
|
|
|
|
|
# khong co nhan docker nao de chep.
|
|
|
|
|
$DefaultLabels = @(
|
|
|
|
|
'ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest',
|
|
|
|
|
'ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04',
|
|
|
|
|
'ubuntu-22.04:docker://docker.gitea.com/runner-images:ubuntu-22.04'
|
|
|
|
|
)
|
|
|
|
|
$Utf8NoBom = [System.Text.UTF8Encoding]::new($false)
|
|
|
|
|
|
|
|
|
|
function Write-Step([string]$Msg) { Write-Host "`n==> $Msg" -ForegroundColor Green }
|
|
|
|
|
function Write-Info([string]$Msg) { Write-Host " $Msg" }
|
|
|
|
|
function Write-Warn([string]$Msg) { Write-Host "[!] $Msg" -ForegroundColor Yellow }
|
|
|
|
|
|
|
|
|
|
# Chuoi YAML trong nhay don: dau \ giu nguyen (duong dan Windows), dau ' viet thanh ''.
|
|
|
|
|
function ConvertTo-YamlString([string]$Value) { "'" + ($Value -replace "'", "''") + "'" }
|
|
|
|
|
|
|
|
|
|
function Write-TextFile([string]$Path, [string]$Text) {
|
|
|
|
|
if ($DryRun) { Write-Info "(dry run) se ghi $Path"; return }
|
|
|
|
|
[System.IO.File]::WriteAllText($Path, $Text, $Utf8NoBom)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function Confirm-Step([string]$Question) {
|
|
|
|
|
if ($Yes -or $DryRun) { return $true }
|
|
|
|
|
$answer = Read-Host "$Question (y/N)"
|
|
|
|
|
return ($answer -match '^(y|yes|c|co)$')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Duong dan tuyet doi co that, hoac duong dan tuong doi tim trong cac thu muc goc; khong thay: $null.
|
|
|
|
|
function Resolve-RunnerPath([string]$Path, [string[]]$BaseDirs) {
|
|
|
|
|
if ([string]::IsNullOrWhiteSpace($Path)) { return $null }
|
|
|
|
|
$Path = [Environment]::ExpandEnvironmentVariables($Path.Trim().Trim('"').Trim("'"))
|
|
|
|
|
if ([System.IO.Path]::IsPathRooted($Path)) {
|
|
|
|
|
if (Test-Path -LiteralPath $Path) { return (Resolve-Path -LiteralPath $Path).Path }
|
|
|
|
|
return $null
|
|
|
|
|
}
|
|
|
|
|
foreach ($b in $BaseDirs) {
|
|
|
|
|
if ([string]::IsNullOrWhiteSpace($b)) { continue }
|
|
|
|
|
$c = Join-Path $b $Path
|
|
|
|
|
if (Test-Path -LiteralPath $c) { return (Resolve-Path -LiteralPath $c).Path }
|
|
|
|
|
}
|
|
|
|
|
return $null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Gia tri cua -c / --config trong mot dong lenh gitea-runner.
|
|
|
|
|
function Get-ConfigArg([string]$Line) {
|
|
|
|
|
if ($Line -match '(?:^|\s)(?:-c|--config)(?:\s+|=)(?:"([^"]+)"|''([^'']+)''|(\S+))') {
|
|
|
|
|
foreach ($g in 1..3) { if ($Matches[$g]) { return $Matches[$g] } }
|
|
|
|
|
}
|
|
|
|
|
return $null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function Test-Contains([string]$Text, [string]$Part) {
|
|
|
|
|
if ([string]::IsNullOrEmpty($Text) -or [string]::IsNullOrEmpty($Part)) { return $false }
|
|
|
|
|
return $Text.IndexOf($Part, [System.StringComparison]::OrdinalIgnoreCase) -ge 0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# In ra task va cac tien trinh gitea-runner, khi khong tu tim duoc runner cu.
|
|
|
|
|
function Show-RunnerDiagnostics {
|
|
|
|
|
Write-Warn 'Script thay nhung thu sau (gui lai neu can sua script):'
|
|
|
|
|
$t = Get-ScheduledTask -TaskName $ExistingTaskName -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
|
|
|
if ($t) {
|
|
|
|
|
foreach ($a in @($t.Actions)) { Write-Info "task '$ExistingTaskName': $($a.Execute) $($a.Arguments) (thu muc: $($a.WorkingDirectory))" }
|
|
|
|
|
} else { Write-Info "task '$ExistingTaskName': khong co" }
|
|
|
|
|
foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='gitea-runner.exe' OR Name='act_runner.exe'")) {
|
|
|
|
|
$parent = Get-CimInstance Win32_Process -Filter "ProcessId=$($p.ParentProcessId)" -ErrorAction SilentlyContinue
|
|
|
|
|
Write-Info "tien trinh $($p.ProcessId): $($p.CommandLine)"
|
|
|
|
|
if ($parent) { Write-Info " cha $($parent.ProcessId): $($parent.CommandLine)" }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Tim exe va config cua runner dang co: truoc het qua tien trinh gitea-runner dang chay (khong
|
|
|
|
|
# phai runner moi), roi qua scheduled task -ExistingTaskName (chay exe truc tiep, hoac qua mot
|
|
|
|
|
# script .ps1 / lenh pwsh co goi gitea-runner).
|
|
|
|
|
function Get-ExistingRunner {
|
|
|
|
|
$exe = $null; $cfg = $null; $source = $null
|
|
|
|
|
$task = Get-ScheduledTask -TaskName $ExistingTaskName -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
|
|
|
|
|
|
|
|
$procs = @(Get-CimInstance Win32_Process -Filter "Name='gitea-runner.exe' OR Name='act_runner.exe'" |
|
|
|
|
|
Where-Object { $_.ExecutablePath -and $_.CommandLine -match '\bdaemon\b' -and -not (Test-Contains $_.CommandLine $Dir) })
|
|
|
|
|
if ($procs.Count -gt 1) {
|
|
|
|
|
Write-Warn "Co $($procs.Count) tien trinh gitea-runner dang chay: lay tien trinh $($procs[0].ProcessId). Sai thi chi ro -RunnerExe / -ExistingConfig."
|
|
|
|
|
}
|
|
|
|
|
if ($procs.Count -ge 1) {
|
|
|
|
|
$p = $procs[0]
|
|
|
|
|
$exe = $p.ExecutablePath
|
|
|
|
|
$bases = @(Split-Path -Parent $exe)
|
|
|
|
|
$parent = Get-CimInstance Win32_Process -Filter "ProcessId=$($p.ParentProcessId)" -ErrorAction SilentlyContinue
|
|
|
|
|
if ($parent -and $parent.CommandLine -match '\s-f(?:ile)?\s+"?([^"]+?\.ps1)"?(?:\s|$)') {
|
|
|
|
|
$bases = @(Split-Path -Parent $Matches[1]) + $bases
|
|
|
|
|
}
|
|
|
|
|
$arg = Get-ConfigArg $p.CommandLine
|
|
|
|
|
if ($arg) { $cfg = Resolve-RunnerPath $arg $bases }
|
|
|
|
|
else {
|
|
|
|
|
$cfg = Resolve-RunnerPath 'config.yaml' $bases
|
|
|
|
|
if ($cfg) { Write-Warn "Dong lenh runner cu khong co -c: doan config la $cfg." }
|
|
|
|
|
}
|
|
|
|
|
$source = "tien trinh $($p.ProcessId)"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (-not $exe -and $task) {
|
|
|
|
|
$act = @($task.Actions)[0]
|
|
|
|
|
if ($act) {
|
|
|
|
|
$execute = [Environment]::ExpandEnvironmentVariables("$($act.Execute)").Trim().Trim('"')
|
|
|
|
|
$argLine = [Environment]::ExpandEnvironmentVariables("$($act.Arguments)")
|
|
|
|
|
$wd = [Environment]::ExpandEnvironmentVariables("$($act.WorkingDirectory)").Trim().Trim('"')
|
|
|
|
|
$bases = @($wd)
|
|
|
|
|
$text = $argLine
|
|
|
|
|
if ($execute -match '(gitea-runner|act_runner)(\.exe)?$') {
|
|
|
|
|
$exe = Resolve-RunnerPath $execute $bases
|
|
|
|
|
} elseif ($argLine -match '(?:^|\s)-f(?:ile)?\s+"?([^"]+?\.ps1)"?(?:\s|$)') {
|
|
|
|
|
$scriptPath = Resolve-RunnerPath $Matches[1] $bases
|
|
|
|
|
if ($scriptPath) {
|
|
|
|
|
$text = Get-Content -LiteralPath $scriptPath -Raw
|
|
|
|
|
$bases = @((Split-Path -Parent $scriptPath), $wd)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if ($text -match '(?im)^\s*(?:Set-Location|Push-Location|cd)\s+(?:-(?:Literal)?Path\s+)?["'']?([A-Za-z]:\\[^"''\r\n]+?)["'']?\s*$') {
|
|
|
|
|
$bases = @($Matches[1]) + $bases
|
|
|
|
|
}
|
|
|
|
|
if (-not $exe -and $text) {
|
|
|
|
|
if ($text -match '(?i)([A-Za-z]:\\[^"''\r\n|&;]*?(?:gitea-runner|act_runner)\.exe)') { $exe = Resolve-RunnerPath $Matches[1] $bases }
|
|
|
|
|
elseif ($text -match '(?i)\b(gitea-runner|act_runner)(?:\.exe)?\b') { $exe = Resolve-RunnerPath "$($Matches[1]).exe" $bases }
|
|
|
|
|
}
|
|
|
|
|
if ($exe -and $text) {
|
|
|
|
|
$line = @($text -split "`r?`n" | Where-Object { $_ -match '(?i)(gitea-runner|act_runner)' -and $_ -match '\bdaemon\b' }) | Select-Object -First 1
|
|
|
|
|
if (-not $line) { $line = $text }
|
|
|
|
|
$arg = Get-ConfigArg $line
|
|
|
|
|
$bases = $bases + @(Split-Path -Parent $exe)
|
|
|
|
|
if ($arg) { $cfg = Resolve-RunnerPath $arg $bases } else { $cfg = Resolve-RunnerPath 'config.yaml' $bases }
|
|
|
|
|
}
|
|
|
|
|
$source = "task '$ExistingTaskName'"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($RunnerExe) { $exe = $RunnerExe; $source = '-RunnerExe' }
|
|
|
|
|
if ($ExistingConfig) { $cfg = $ExistingConfig }
|
|
|
|
|
[pscustomobject]@{ Task = $task; Exe = $exe; Config = $cfg; Source = $source }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Gia tri vo huong dau tien cua mot khoa (vd. docker_host), du thut le bat ky.
|
|
|
|
|
function Read-YamlScalar([string[]]$Lines, [string]$Key) {
|
|
|
|
|
foreach ($l in $Lines) {
|
|
|
|
|
if ($l -match "^\s+$([regex]::Escape($Key)):\s*(.*?)\s*$") {
|
|
|
|
|
$v = $Matches[1] -replace '\s+#.*$', ''
|
|
|
|
|
if ($v -eq '' -or $v -like '#*') { return '' }
|
|
|
|
|
return $v.Trim().Trim('"').Trim("'")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Cac muc trong runner.labels: chi so dong + gia tri.
|
|
|
|
|
function Get-ConfigLabels([string[]]$Lines) {
|
|
|
|
|
$out = [System.Collections.Generic.List[object]]::new()
|
|
|
|
|
$inRunner = $false; $inLabels = $false; $labelIndent = -1
|
|
|
|
|
for ($i = 0; $i -lt $Lines.Count; $i++) {
|
|
|
|
|
$l = $Lines[$i]
|
|
|
|
|
if ($l -match '^\s*(#.*)?$') { continue }
|
|
|
|
|
if ($l -match '^\S') {
|
|
|
|
|
$inRunner = ($l -match '^runner:\s*(#.*)?$'); $inLabels = $false; continue
|
|
|
|
|
}
|
|
|
|
|
if (-not $inRunner) { continue }
|
|
|
|
|
if ($l -match '^(\s+)labels:\s*(#.*)?$') { $inLabels = $true; $labelIndent = $Matches[1].Length; continue }
|
|
|
|
|
if (-not $inLabels) { continue }
|
|
|
|
|
if ($l -match '^\s*-\s*(.+?)\s*$') {
|
|
|
|
|
$v = $Matches[1] -replace '\s+#.*$', ''
|
|
|
|
|
$out.Add([pscustomobject]@{ Index = $i; Value = $v.Trim().Trim('"').Trim("'") })
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
$indent = $l.Length - $l.TrimStart().Length
|
|
|
|
|
if ($indent -le $labelIndent) { $inLabels = $false }
|
|
|
|
|
}
|
|
|
|
|
$out.ToArray()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Dung task va tien trinh runner cua no (theo duong dan config, hoac theo exe neu dong lenh
|
|
|
|
|
# khong co config, chi khi -AllowExeMatch), roi chay lai task.
|
|
|
|
|
function Restart-RunnerTask([string]$Task, [string]$ConfigPath, [string]$ExePath, [string]$NotLike, [switch]$AllowExeMatch) {
|
|
|
|
|
if ($DryRun) { Write-Info "(dry run) se khoi dong lai task '$Task'"; return }
|
|
|
|
|
if (-not (Get-ScheduledTask -TaskName $Task -ErrorAction SilentlyContinue)) {
|
|
|
|
|
Write-Warn "Khong co task '$Task': tu khoi dong lai runner do."
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
Stop-ScheduledTask -TaskName $Task -ErrorAction SilentlyContinue
|
|
|
|
|
$procs = @(Get-CimInstance Win32_Process -Filter "Name='gitea-runner.exe' OR Name='act_runner.exe'" |
|
|
|
|
|
Where-Object { $_.CommandLine })
|
|
|
|
|
$mine = @()
|
|
|
|
|
if ($ConfigPath) { $mine = @($procs | Where-Object { Test-Contains $_.CommandLine $ConfigPath }) }
|
|
|
|
|
if ($mine.Count -eq 0 -and $AllowExeMatch -and $ExePath -and $NotLike) {
|
|
|
|
|
$mine = @($procs | Where-Object { $_.ExecutablePath -eq $ExePath -and -not (Test-Contains $_.CommandLine $NotLike) })
|
|
|
|
|
}
|
|
|
|
|
foreach ($p in $mine) {
|
|
|
|
|
Write-Info "Dung tien trinh $($p.ProcessId)"
|
|
|
|
|
Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
|
|
|
|
|
}
|
|
|
|
|
Start-Sleep -Seconds 2
|
|
|
|
|
Start-ScheduledTask -TaskName $Task
|
|
|
|
|
Write-Info "Da chay lai task '$Task'."
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
Write-Step 'Runner dang co'
|
|
|
|
|
$Dir = [System.IO.Path]::GetFullPath($Dir)
|
|
|
|
|
$old = Get-ExistingRunner
|
|
|
|
|
$exe = $old.Exe
|
|
|
|
|
if (-not $exe -or -not (Test-Path -LiteralPath $exe)) {
|
|
|
|
|
Show-RunnerDiagnostics
|
|
|
|
|
throw "Khong tim thay gitea-runner.exe (qua tien trinh dang chay hoac task '$ExistingTaskName'). Chi ro bang -RunnerExe <duong dan> -ExistingConfig <config.yaml>."
|
|
|
|
|
}
|
|
|
|
|
$exe = (Resolve-Path -LiteralPath $exe).Path
|
|
|
|
|
Write-Info "tim qua: $($old.Source)"
|
|
|
|
|
Write-Info "exe: $exe"
|
|
|
|
|
Write-Info "config: $(if ($old.Config) { $old.Config } else { '(khong tim thay)' })"
|
|
|
|
|
try { & $exe --version } catch { Write-Warn "Khong doc duoc phien ban: $($_.Exception.Message)" }
|
|
|
|
|
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { Write-Warn 'Khong thay lenh docker trong PATH: runner moi can Docker Desktop.' }
|
|
|
|
|
|
|
|
|
|
if ($old.Config -and ([System.IO.Path]::GetFullPath((Split-Path -Parent $old.Config)) -eq $Dir)) {
|
|
|
|
|
throw "-Dir trung thu muc cua runner cu ($Dir). Chon thu muc khac."
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$oldLines = @()
|
|
|
|
|
$oldItems = @()
|
|
|
|
|
if ($old.Config -and (Test-Path -LiteralPath $old.Config)) {
|
|
|
|
|
$oldLines = @(Get-Content -LiteralPath $old.Config)
|
|
|
|
|
$oldItems = @(Get-ConfigLabels $oldLines)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Nhan cua runner moi: -Labels, neu khong thi nhan docker cua runner cu, neu khong thi mac dinh.
|
|
|
|
|
if ($Labels.Count -eq 0) {
|
|
|
|
|
$Labels = @($oldItems | Where-Object { $_.Value -match ':docker://' } | ForEach-Object { $_.Value })
|
|
|
|
|
if ($Labels.Count -gt 0) { Write-Info 'Nhan: chep cac nhan docker cua runner cu.' }
|
|
|
|
|
else { $Labels = $DefaultLabels; Write-Info 'Nhan: mac dinh (runbook section 1).' }
|
|
|
|
|
}
|
|
|
|
|
foreach ($l in $Labels) {
|
|
|
|
|
if ($l -notmatch '^[^:\s]+:(docker://\S+|host)$') { throw "Nhan khong hop le: '$l' (dang <nhan>:docker://<image> hoac <nhan>:host)." }
|
|
|
|
|
}
|
|
|
|
|
$dockerHost = if ($oldLines.Count) { Read-YamlScalar $oldLines 'docker_host' } else { $null }
|
|
|
|
|
$network = if ($oldLines.Count) { Read-YamlScalar $oldLines 'network' } else { $null }
|
|
|
|
|
if ($null -eq $dockerHost) { $dockerHost = '' }
|
|
|
|
|
if ($null -eq $network) { $network = '' }
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
Write-Step "config.yaml cho '$Name' trong $Dir"
|
|
|
|
|
$cfgPath = Join-Path $Dir 'config.yaml'
|
|
|
|
|
$runnerFile = Join-Path $Dir '.runner'
|
|
|
|
|
$cacheDir = Join-Path $Dir 'cache'
|
|
|
|
|
$workDir = Join-Path $Dir 'work'
|
|
|
|
|
$labelLines = ($Labels | ForEach-Object { " - $(ConvertTo-YamlString $_)" }) -join "`n"
|
|
|
|
|
$config = @"
|
|
|
|
|
# Viet boi maintainer/add-runner.ps1 ($(Get-Date -Format 'yyyy-MM-dd')).
|
|
|
|
|
# Chay lai script de doi; sua tay thi khoi dong lai task '$TaskName'.
|
|
|
|
|
log:
|
|
|
|
|
level: info
|
|
|
|
|
|
|
|
|
|
runner:
|
|
|
|
|
file: $(ConvertTo-YamlString $runnerFile)
|
|
|
|
|
capacity: $Capacity
|
|
|
|
|
timeout: $Timeout
|
|
|
|
|
fetch_timeout: 5s
|
|
|
|
|
fetch_interval: 2s
|
|
|
|
|
labels:
|
|
|
|
|
$labelLines
|
|
|
|
|
|
|
|
|
|
cache:
|
|
|
|
|
enabled: true
|
|
|
|
|
dir: $(ConvertTo-YamlString $cacheDir)
|
|
|
|
|
host: ''
|
|
|
|
|
port: 0
|
|
|
|
|
|
|
|
|
|
container:
|
|
|
|
|
network: $(ConvertTo-YamlString $network)
|
|
|
|
|
privileged: false
|
|
|
|
|
options: $(ConvertTo-YamlString $ContainerOptions)
|
|
|
|
|
valid_volumes: []
|
|
|
|
|
docker_host: $(ConvertTo-YamlString $dockerHost)
|
|
|
|
|
force_pull: true
|
|
|
|
|
|
|
|
|
|
host:
|
|
|
|
|
workdir_parent: $(ConvertTo-YamlString $workDir)
|
|
|
|
|
"@
|
|
|
|
|
$config = $config -replace "`r`n", "`n"
|
|
|
|
|
Write-Host $config -ForegroundColor DarkGray
|
|
|
|
|
if (-not $DryRun) {
|
|
|
|
|
New-Item -ItemType Directory -Force -Path $Dir, $cacheDir, $workDir | Out-Null
|
|
|
|
|
}
|
|
|
|
|
Write-TextFile $cfgPath ($config + "`n")
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
Write-Step 'Dang ky voi Gitea'
|
|
|
|
|
if (Test-Path -LiteralPath $runnerFile) {
|
|
|
|
|
Write-Info 'Da dang ky (.runner co san): bo qua. Nhan va capacity lay tu config.yaml khi daemon khoi dong.'
|
|
|
|
|
} elseif ($DryRun) {
|
|
|
|
|
Write-Info "(dry run) se chay: gitea-runner -c `"$cfgPath`" register --no-interactive --instance $Instance --name $Name --labels <nhan> --token <hoi khi chay>"
|
|
|
|
|
} else {
|
|
|
|
|
$secure = Read-Host -AsSecureString 'Token dang ky (Gitea > Settings > Actions > Runners > Create new runner)'
|
|
|
|
|
$token = [System.Net.NetworkCredential]::new('', $secure).Password
|
|
|
|
|
if ([string]::IsNullOrWhiteSpace($token)) { throw 'Token rong.' }
|
|
|
|
|
Push-Location $Dir
|
|
|
|
|
try {
|
|
|
|
|
& $exe -c $cfgPath register --no-interactive --instance $Instance --token $token --name $Name --labels ($Labels -join ',')
|
|
|
|
|
if ($LASTEXITCODE -ne 0) { throw "register that bai (exit $LASTEXITCODE)." }
|
|
|
|
|
} finally {
|
|
|
|
|
Pop-Location
|
|
|
|
|
$token = $null
|
|
|
|
|
}
|
|
|
|
|
if (-not (Test-Path -LiteralPath $runnerFile)) { throw "Dang ky xong nhung khong thay $runnerFile." }
|
|
|
|
|
Write-Info "Da dang ky '$Name'."
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
Write-Step 'run-runner.ps1'
|
|
|
|
|
$wrapper = Join-Path $Dir 'run-runner.ps1'
|
|
|
|
|
$wrapperText = @'
|
|
|
|
|
# Viet boi maintainer/add-runner.ps1: doi Docker san sang, chay gitea-runner daemon, va chay lai
|
|
|
|
|
# 30 giay sau neu daemon thoat (Docker Desktop khoi dong lai, mat mang...). Dung han: dung task,
|
|
|
|
|
# roi dung tien trinh gitea-runner.exe co duong dan config nay trong dong lenh.
|
|
|
|
|
param(
|
|
|
|
|
[Parameter(Mandatory)] [string] $Exe,
|
|
|
|
|
[Parameter(Mandatory)] [string] $Config
|
|
|
|
|
)
|
|
|
|
|
$ErrorActionPreference = 'Continue'
|
|
|
|
|
$dir = Split-Path -Parent $Config
|
|
|
|
|
Set-Location -LiteralPath $dir
|
|
|
|
|
$log = Join-Path $dir 'runner.log'
|
|
|
|
|
while ($true) {
|
|
|
|
|
while ($true) {
|
|
|
|
|
$global:LASTEXITCODE = 1
|
|
|
|
|
try { & docker info *> $null } catch { }
|
|
|
|
|
if ($LASTEXITCODE -eq 0) { break }
|
|
|
|
|
Start-Sleep -Seconds 10
|
|
|
|
|
}
|
|
|
|
|
foreach ($f in @($log, "$log.out")) {
|
|
|
|
|
if (Test-Path -LiteralPath $f) { Move-Item -LiteralPath $f -Destination "$f.old" -Force }
|
|
|
|
|
}
|
|
|
|
|
Start-Process -FilePath $Exe -ArgumentList @('-c', "`"$Config`"", 'daemon') -WorkingDirectory $dir `
|
|
|
|
|
-NoNewWindow -Wait -RedirectStandardError $log -RedirectStandardOutput "$log.out"
|
|
|
|
|
Start-Sleep -Seconds 30
|
|
|
|
|
}
|
|
|
|
|
'@
|
|
|
|
|
Write-TextFile $wrapper (($wrapperText -replace "`r`n", "`n") + "`n")
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
if ($NoTask) {
|
|
|
|
|
Write-Step 'Bo qua scheduled task (-NoTask)'
|
|
|
|
|
Write-Info "Chay tay: pwsh -File `"$wrapper`" -Exe `"$exe`" -Config `"$cfgPath`""
|
|
|
|
|
} else {
|
|
|
|
|
Write-Step "Scheduled task '$TaskName'"
|
|
|
|
|
$user = "$env:USERDOMAIN\$env:USERNAME"
|
|
|
|
|
$shell = (Get-Process -Id $PID).Path
|
|
|
|
|
if ($shell -like '*\Program Files\WindowsApps\*') {
|
|
|
|
|
# Ban PowerShell tu Microsoft Store: duong dan nay doi theo phien ban; dung alias on dinh.
|
|
|
|
|
$alias = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps\pwsh.exe'
|
|
|
|
|
if (Test-Path -LiteralPath $alias) { $shell = $alias }
|
|
|
|
|
else {
|
|
|
|
|
$cmd = Get-Command pwsh.exe -ErrorAction SilentlyContinue | Where-Object { $_.Source -notlike '*\Program Files\WindowsApps\*' } | Select-Object -First 1
|
|
|
|
|
if ($cmd) { $shell = $cmd.Source } else { Write-Warn "Task se goi $shell, duong dan nay doi khi PowerShell cap nhat." }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
$argLine = "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$wrapper`" -Exe `"$exe`" -Config `"$cfgPath`""
|
|
|
|
|
$existed = [bool](Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue)
|
|
|
|
|
if ($DryRun) {
|
|
|
|
|
Write-Info "(dry run) se tao task: $shell $argLine"
|
|
|
|
|
Write-Info "(dry run) trigger: dang nhap ($user); chay lai sau 1 phut khi loi; khong gioi han thoi gian"
|
|
|
|
|
} else {
|
|
|
|
|
$action = New-ScheduledTaskAction -Execute $shell -Argument $argLine -WorkingDirectory $Dir
|
|
|
|
|
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
|
|
|
|
|
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 `
|
|
|
|
|
-RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew -StartWhenAvailable `
|
|
|
|
|
-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
|
|
|
|
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
|
|
|
try {
|
|
|
|
|
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings `
|
|
|
|
|
-Principal $principal -Description "gitea-runner '$Name' ($Dir). Viet boi maintainer/add-runner.ps1." -Force | Out-Null
|
|
|
|
|
} catch {
|
|
|
|
|
throw "Khong tao duoc task: $($_.Exception.Message) Thu chay lai trong PowerShell 7 (Run as administrator)."
|
|
|
|
|
}
|
|
|
|
|
Write-Info "Da $(if ($existed) { 'cap nhat' } else { 'tao' }) task."
|
|
|
|
|
}
|
|
|
|
|
if ($existed) {
|
|
|
|
|
if (Confirm-Step "Khoi dong lai '$TaskName' de nhan config moi? Job dang chay tren runner nay se bi ngat") {
|
|
|
|
|
Restart-RunnerTask -Task $TaskName -ConfigPath $cfgPath
|
|
|
|
|
} else { Write-Warn "Chua khoi dong lai: config moi co hieu luc o lan chay sau cua '$TaskName'." }
|
|
|
|
|
} elseif (-not $DryRun) {
|
|
|
|
|
Start-ScheduledTask -TaskName $TaskName
|
|
|
|
|
Write-Info 'Da chay task. Log: runner.log trong thu muc runner.'
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
if ($SplitExistingRunner -and $NoTask) {
|
|
|
|
|
Write-Warn 'Tach runner cu khi chua co task cho runner moi: job ubuntu-* se doi den khi ban tu chay runner moi.'
|
|
|
|
|
}
|
|
|
|
|
if ($SplitExistingRunner) {
|
|
|
|
|
Write-Step "Runner cu: chi giu nhan host (windows-latest)"
|
|
|
|
|
$dockerItems = @($oldItems | Where-Object { $_.Value -match ':docker://' })
|
|
|
|
|
$keepItems = @($oldItems | Where-Object { $_.Value -notmatch ':docker://' })
|
|
|
|
|
if (-not $old.Config -or $oldLines.Count -eq 0) {
|
|
|
|
|
Write-Warn 'Khong doc duoc config cua runner cu (-ExistingConfig). Khong sua gi.'
|
|
|
|
|
} elseif ($oldItems.Count -eq 0) {
|
|
|
|
|
Write-Warn "config cu khong liet ke runner.labels (runner dung nhan trong .runner). Them vao config do:"
|
|
|
|
|
Write-Info " labels:"
|
|
|
|
|
Write-Info " - 'windows-latest:host'"
|
|
|
|
|
Write-Info " - 'windows:host'"
|
|
|
|
|
Write-Info "roi khoi dong lai task '$ExistingTaskName'. Script khong tu sua."
|
|
|
|
|
} elseif ($dockerItems.Count -eq 0) {
|
|
|
|
|
Write-Info 'Runner cu da khong con nhan docker: khong can sua.'
|
|
|
|
|
} elseif ($keepItems.Count -eq 0) {
|
|
|
|
|
Write-Warn 'Bo nhan docker thi runner cu khong con nhan nao. Khong sua gi.'
|
|
|
|
|
} else {
|
|
|
|
|
Write-Info "Bo: $(($dockerItems | ForEach-Object { $_.Value }) -join ', ')"
|
|
|
|
|
Write-Info "Giu: $(($keepItems | ForEach-Object { $_.Value }) -join ', ')"
|
|
|
|
|
$drop = [System.Collections.Generic.HashSet[int]]::new()
|
|
|
|
|
foreach ($d in $dockerItems) { [void]$drop.Add($d.Index) }
|
|
|
|
|
$newLines = for ($i = 0; $i -lt $oldLines.Count; $i++) { if (-not $drop.Contains($i)) { $oldLines[$i] } }
|
|
|
|
|
$raw = [System.IO.File]::ReadAllText($old.Config)
|
|
|
|
|
$nl = if ($raw.Contains("`r`n")) { "`r`n" } else { "`n" }
|
|
|
|
|
$backup = "$($old.Config).bak-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
|
|
|
|
|
if ($DryRun) {
|
|
|
|
|
Write-Info "(dry run) se sao luu thanh $backup va ghi lai $($old.Config)"
|
|
|
|
|
} else {
|
|
|
|
|
Copy-Item -LiteralPath $old.Config -Destination $backup
|
|
|
|
|
[System.IO.File]::WriteAllText($old.Config, (($newLines -join $nl) + $nl), $Utf8NoBom)
|
|
|
|
|
Write-Info "Sao luu: $backup"
|
|
|
|
|
}
|
|
|
|
|
if ($old.Task) {
|
|
|
|
|
if (Confirm-Step "Khoi dong lai '$ExistingTaskName'? Job dang chay tren runner cu se bi ngat") {
|
|
|
|
|
Restart-RunnerTask -Task $ExistingTaskName -ConfigPath $old.Config -ExePath $exe -NotLike $Dir -AllowExeMatch
|
|
|
|
|
} else { Write-Warn "Chua khoi dong lai '$ExistingTaskName': nhan moi co hieu luc o lan chay sau." }
|
|
|
|
|
} else {
|
|
|
|
|
Write-Warn 'Khong co task cua runner cu: tu khoi dong lai no.'
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Write-Step 'Xong'
|
|
|
|
|
Write-Info "Kiem tra: $Instance/user/settings/actions/runners (runner '$Name' Idle, dung nhan)."
|
|
|
|
|
Write-Info "Log runner moi: $(Join-Path $Dir 'runner.log')"
|