diff --git a/docs/GITEA-MIGRATION.md b/docs/GITEA-MIGRATION.md index 4e2e610..6f3f591 100644 --- a/docs/GITEA-MIGRATION.md +++ b/docs/GITEA-MIGRATION.md @@ -361,6 +361,7 @@ Qodana CLI scan for any stack; replaces `JetBrains/qodana-action`. - `tools/migration-inventory.py`: the read-only inventory of §3.1. - `maintainer/gitea-repo-setup.ps1`: for every repo of `poli0981`, add `renovate-bot` as a Write collaborator and create the labels `dependencies` + `security` (`-DryRun`, `-Only`, `-Exclude`). Token: repository Read and Write, issue Read and Write, user Read. +- `maintainer/add-runner.ps1`: register another gitea-runner on the PC, by default the Docker-only runner of D15 (`ubuntu-*` labels, capacity 3, its own folder under `%LOCALAPPDATA%`), and start it at logon once Docker Desktop answers. `-SplitExistingRunner` leaves the first runner the host (`windows`) labels only; run it again to change capacity, labels or the per-job container limits. `-DryRun` first. - [`migration/`](migration/README.md): per-repo guides, the cron-slot registry, the shared decisions D1–D16 and the `gh` → Gitea API table. --- diff --git a/docs/migration/README.md b/docs/migration/README.md index 65c8cb0..b218055 100644 --- a/docs/migration/README.md +++ b/docs/migration/README.md @@ -126,14 +126,14 @@ D1 is the maintainer's. D2–D16 were decided by the agent on the maintainer's i | D12 | Code that **writes** to a repo at runtime through a GitHub App or token (poli0981-dev admin, free-steam-games-list and free-games-itchio-list Workers) | **The Gitea API with a token of the bot user `poli0981-bot`**, a collaborator with write access on exactly the repos it writes (`poli0981-dev`, `content`, `free-steam-games-list`, `free-games-itchio-list`), token scope `write:repository`, stored as a Worker secret. Several files in one commit: `POST /repos/{owner}/{repo}/contents` with each file's current `sha`, which is the optimistic lock that replaces `createCommitOnBranch`'s `expectedHeadOid` (**VERIFY** that a stale `sha` is refused with 409/422; the Workers' retry loops depend on it). A push by this user is a real user's push, so it starts workflows (ingest jobs) as the GitHub App's did. Commits are unsigned unless Gitea's server-side signing is set up; nothing requires it | | D13 | Code that **reads** repo data at runtime (raw files, commits, releases, activity) | **Gitea without a token**: raw files at `https://git.poli0981.dev/poli0981//raw/branch/main/` (or `GET /repos/{owner}/{repo}/raw/{path}?ref=main`), and the REST API for the rest. The repos are public; the Workers keep their caches, so each new file version is fetched once per data centre | | D14 | Public bug-report endpoints that opened GitHub issues (poli0981-dev, RepoLens) | **Issues on the GitLab mirror** through `POST /api/v4/projects/:id/issues`. The token is a project access token if the GitLab.com plan allows one, else a personal access token of a GitLab bot account with the Reporter role (scope `api`). Either expires within a year: note the date in the hand-off. When the call fails, the endpoint tells the reader to e-mail `code@` instead | -| D15 | Runner time: the two catalog pipelines need about four runner-hours a day, more than one job slot holds inside 13:00–16:00 next to the other repos' schedules | **A second runner registration on the PC with Docker labels only** (`ubuntu-latest`, `ubuntu-24.04`, `ubuntu-22.04`), capacity 1. Host-mode (`windows-latest`) jobs stay one at a time on the first runner; a long data job no longer blocks a Windows build. The data pipelines also run once a day with smaller time budgets (their guides). If the PC is off, the day's runs wait and catch up when it comes back (runbook §7 item 4) | +| D15 | Runner time: the two catalog pipelines need about four runner-hours a day, more than one job slot holds inside 13:00–16:00 next to the other repos' schedules | **A second runner registration on the PC with Docker labels only** (`ubuntu-latest`, `ubuntu-24.04`, `ubuntu-22.04`), capacity 3 by default (raise it with the RAM Docker gets), set up by `maintainer/add-runner.ps1`. Host-mode (`windows-latest`) jobs stay one at a time on the first runner; a long data job no longer blocks a Windows build. The data pipelines also run once a day with smaller time budgets (their guides). If the PC is off, the day's runs wait and catch up when it comes back (runbook §7 item 4) | | D16 | Sites that bundle their data at build time (free-games-itchio-list): a data commit pushed with the job token starts no workflow, so no deploy | **The data workflow dispatches `deploy.yml`** after a successful commit (job token, `actions: write`). `deploy.yml` keeps `push` for code changes | ## Maintainer steps, once for all repos 1. Add your GPG public key to the Gitea account, so `https://git.poli0981.dev/poli0981.gpg` serves it (the pilot's tag check, OmniDeck's OD3). 2. Create the user `poli0981-bot` on Gitea (registration is off: Site Administration), add it as a Write collaborator on the four repos of D12, and create its token (`write:repository`). The token goes into each Worker as a secret during that repo's hand-off. -3. Register the second runner on the PC with Docker labels only (D15). +3. Register the second runner on the PC with Docker labels only (D15): `maintainer/add-runner.ps1 -DryRun`, then `-SplitExistingRunner` so the first runner keeps the `windows` labels only. 4. The GitLab issue token of D14, with its expiry date written down. 5. In the Cloudflare dashboard, disconnect Workers Builds' GitHub integration of every project the migrated repos deploy (D3). 6. The announcement (runbook §7 item 5): one post on poli0981.dev and the Discord announcement. diff --git a/maintainer/add-runner.ps1 b/maintainer/add-runner.ps1 new file mode 100644 index 0000000..2b2856c --- /dev/null +++ b/maintainer/add-runner.ps1 @@ -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 -ExistingConfig ." +} +$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 :docker:// hoac :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 --token " +} 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')"