okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
14.2 KiB205 linesraw
1# Strata Terminal: one-line installer for Windows (PowerShell 5.1 or newer).
2#
3#     irm -TimeoutSec 120 https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
4#
5# What it does, in order (and nothing else):
6#   1. finds out which computer this is (Windows, processor, graphics card);
7#   2. downloads the Terminal archive named in the release folder's install-manifest.txt and checks its SHA-256 against it;
8#   3. unpacks it into  %LOCALAPPDATA%\Strata\terminal\<version>  (no administrator rights);
9#   4. checks the release's signed feed with the Terminal it just unpacked (`strata update --check`); if that fails it removes what it
10#      unpacked and stops;
11#   5. adds  %LOCALAPPDATA%\Strata\terminal\current\bin  to your user PATH and prints:  Installed. Run: strata launch
12#
13# The engine and the model are not part of this: `strata launch` fetches the engine for your graphics card the first time you choose
14# a model, from the same release folder, signed.
15#
16# <feed> is where the release folder is hosted: GitHub Releases of Niko1221/Strata (the "latest" release's files), built in as the default.
17# Set $env:STRATA_FEED to another folder (a URL) to use that instead, for example a local test feed:  $env:STRATA_FEED='http://127.0.0.1:8099'; irm http://127.0.0.1:8099/install.ps1 | iex
18# Optional: $env:STRATA_DATA_DIR (default %LOCALAPPDATA%\Strata), $env:STRATA_INSTALL_TEST_TRUST='1' (a test feed: trust only its
19# test-trust.json for step 4), $env:STRATA_NO_PATH='1' (do not change the user PATH).
20& {   # a child scope: `irm | iex` runs in the caller's scope, and this script's variables must not overwrite the caller's
21$ErrorActionPreference = 'Stop'
22$ProgressPreference = 'SilentlyContinue'
23
24function Die([string]$msg) { [Console]::Error.WriteLine("strata installer: $msg"); throw "strata installer stopped" }
25# older Windows 10 builds offer only TLS 1.0/1.1 to Windows PowerShell 5.1, and GitHub accepts only 1.2; a company proxy may want the Windows sign-in
26try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { }
27try { if ([Net.WebRequest]::DefaultWebProxy) { [Net.WebRequest]::DefaultWebProxy.Credentials = [Net.CredentialCache]::DefaultNetworkCredentials } } catch { }
28
29$feed = if ($env:STRATA_FEED) { $env:STRATA_FEED } else { 'https://github.com/Niko1221/Strata/releases/latest/download' }
30$feed = $feed.TrimEnd('/')
31$feedHost = try { ([Uri]$feed).Host } catch { '' }
32if (-not $feedHost) { $feedHost = $feed }
33
34# The network rule (strata_control/netpolicy.py): a server that does not answer is given up after 15 s and one more try; once it answers,
35# the download stops only when no byte comes for 60 s (no total cap: a slow line that works is never cut). A refused connection or no DNS
36# answer fails at once. HttpWebRequest works the same in Windows PowerShell 5.1 and PowerShell 7 and never shows a sign-in dialog.
37function Fetch([string]$url, [string]$out) {
38    for ($try = 1; ; $try++) {
39        try {
40            $req = [Net.WebRequest]::Create($url)
41            $req.Timeout = 15000                                   # the connection, TLS and the server's answer (its headers)
42            if ($req -is [Net.HttpWebRequest]) {
43                $req.ReadWriteTimeout = 60000                      # no byte for 60 s ends the download
44                $req.UserAgent = 'strata-installer'
45                if ([Net.WebRequest]::DefaultWebProxy) { $req.Proxy = [Net.WebRequest]::DefaultWebProxy }   # with the Windows sign-in (set above)
46            }
47            $resp = $req.GetResponse()
48            try {
49                $in = $resp.GetResponseStream()
50                $fs = [IO.File]::Create($out)
51                try {
52                    $buf = New-Object byte[] 1048576
53                    while (($n = $in.Read($buf, 0, $buf.Length)) -gt 0) { $fs.Write($buf, 0, $n) }
54                }
55                finally { $fs.Dispose(); $in.Dispose() }
56            }
57            finally { $resp.Dispose() }
58            return
59        }
60        catch {
61            $e = $_.Exception
62            $timedOut = $false
63            while ($e) {
64                if (($e -is [Net.WebException] -and $e.Status -eq [Net.WebExceptionStatus]::Timeout) -or ($e -is [TimeoutException]) -or
65                    ($e -is [IO.IOException] -and $e.Message -match 'timed out|time out|timeout')) { $timedOut = $true }
66                $e = $e.InnerException
67            }
68            if ($try -lt 2 -and $timedOut) { Start-Sleep -Seconds 2; continue }   # one more try, only after a timeout
69            throw
70        }
71    }
72}
73if (-not $feed) {
74    Die 'this installer does not know where the Strata release folder is. Set $env:STRATA_FEED to its address and run it again, for example: $env:STRATA_FEED=''https://example.org/strata'''
75}
76if ([Environment]::OSVersion.Platform -ne 'Win32NT') { Die 'this is the Windows installer; on Linux or macOS use install.sh.' }
77$arch = $env:PROCESSOR_ARCHITEW6432; if (-not $arch) { $arch = $env:PROCESSOR_ARCHITECTURE }
78if ($arch -ne 'AMD64') { Die "this computer ($arch) is a Windows on ARM PC. Strata needs an NVIDIA or AMD graphics card and has no engine for ARM processors, so it could not run a model here. Run this installer on a Windows PC with an Intel or AMD processor (x64) and one of those cards." }
79$platform = 'windows-x86_64'
80$gpu = ''
81# a discrete card is named before a built-in one (a Ryzen's "AMD Radeon(TM) Graphics" is listed first on many PCs); this line is only for the person to read
82try { $cards = @(Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic|Remote' }); $gpu = ($cards | Sort-Object @{ Expression = { if ($_.Name -match 'NVIDIA|GeForce|RTX|GTX|Quadro|Radeon (RX|PRO|AI)|Arc|Instinct') { 0 } else { 1 } } } | Select-Object -First 1 -ExpandProperty Name) } catch { }
83Write-Host 'Strata Terminal installer'
84Write-Host "  This computer: Windows $arch ($platform)$(if ($gpu) { ", graphics: $gpu" })"
85Write-Host "  Release folder: $feed"
86
87if (-not $env:STRATA_DATA_DIR -and -not $env:LOCALAPPDATA) { Die 'Windows did not say where your user folder is. Set $env:STRATA_DATA_DIR to a folder you own, for example $env:STRATA_DATA_DIR=''C:\Strata'', and run this again.' }
88$data = if ($env:STRATA_DATA_DIR) { $env:STRATA_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'Strata' }
89$work = Join-Path ([IO.Path]::GetTempPath()) ("strata-install-" + [Guid]::NewGuid().ToString('N').Substring(0, 8))
90New-Item -ItemType Directory -Path $work | Out-Null
91try {
92    try { Fetch "$feed/install-manifest.txt" (Join-Path $work 'manifest.txt') }
93    catch {
94        [Console]::Error.WriteLine("    $($_.Exception.Message)")   # the reason, as curl prints its own
95        Die "$feedHost did not answer (or this computer is offline), so the installer could not start. Check that this computer can open https://$feedHost, then run the same line again. Nothing was installed. If this PC is behind a company proxy or firewall, ask for the release folder to be allowed."
96    }
97    $line = Get-Content (Join-Path $work 'manifest.txt') | Where-Object { $_ -match "^$platform\s" } | Select-Object -First 1
98    if (-not $line) { Die "this release has no Terminal for $platform." }
99    $f = -split $line
100    $version, $rel, $want, $size = $f[1], $f[2], $f[3].ToLower(), $f[4]
101    Write-Host "  Terminal $version ($([math]::Round([double]$size / 1MB)) MB)"
102    Write-Host 'Downloading...'
103    $zip = Join-Path $work 'terminal.zip'
104    try { Fetch "$feed/$rel" $zip }
105    catch {
106        [Console]::Error.WriteLine("    $($_.Exception.Message)")
107        Die "the download stopped: $feedHost did not answer, or no data came for 60 seconds. Run the same line again; nothing was installed."
108    }
109    $got = (Get-FileHash -Algorithm SHA256 $zip).Hash.ToLower()
110    if ($got -ne $want) { Die "the download does not match the release's checksum (got $got, wanted $want). It was not installed; try again." }
111    Write-Host '  Checksum ok.'
112
113    $dest = Join-Path $data "terminal\$version"
114    $incoming = "$dest.incoming"
115    New-Item -ItemType Directory -Force -Path (Join-Path $data 'terminal') | Out-Null
116    if (Test-Path $incoming) { Remove-Item -Recurse -Force $incoming }
117    $tooLong = 'If it says a path is too long, set $env:STRATA_DATA_DIR to a short folder such as C:\Strata and run this again; otherwise check the free disk space.'
118    try {
119        # tar.exe (Windows 10 1803 and later) handles long paths; Expand-Archive in Windows PowerShell 5.1 does not.
120        # tar.exe receives its arguments through the ANSI/OEM code page, so a folder with an accented letter in its name turns into one with a question mark and the
121        # unpack fails (A04). It is therefore started with ASCII-only, relative arguments from inside the data folder (PowerShell's own cmdlets are Unicode-safe),
122        # unpacks into a folder with an ASCII name, and that folder is renamed to $incoming.
123        # Windows' own bsdtar first: a GNU tar from Git for Windows or MSYS earlier on the PATH cannot read a zip
124        $tar = Get-Command (Join-Path $env:SystemRoot 'System32\tar.exe') -ErrorAction SilentlyContinue
125        if (-not $tar) { $tar = Get-Command tar.exe -ErrorAction SilentlyContinue }
126        if ($tar) {
127            $tag = 'u' + [Guid]::NewGuid().ToString('N').Substring(0, 6)
128            $terminalDir = Join-Path $data 'terminal'
129            Push-Location -LiteralPath $terminalDir
130            try {
131                Copy-Item -LiteralPath $zip -Destination "$tag.zip"
132                New-Item -ItemType Directory -Path $tag | Out-Null
133                $tarOut = & $tar.Source -xf "$tag.zip" -C $tag 2>&1 | Out-String
134                if ($LASTEXITCODE -ne 0) { throw $tarOut.Trim() }
135            }
136            finally {
137                Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath "$tag.zip"
138                Pop-Location
139            }
140            Move-Item -LiteralPath (Join-Path $terminalDir $tag) -Destination $incoming
141            Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -LiteralPath (Join-Path $terminalDir $tag)
142        } else { Expand-Archive -LiteralPath $zip -DestinationPath $incoming -Force }
143    }
144    catch { Remove-Item -Recurse -Force $incoming -ErrorAction SilentlyContinue; Die "the archive could not be unpacked ($($_.Exception.Message)). $tooLong Nothing was installed." }
145    # the archive of a release folder is rooted at the bundle itself (control package) or in one folder (terminal archive)
146    if (-not (Test-Path (Join-Path $incoming 'bin\strata.cmd'))) {
147        $inner = Get-ChildItem $incoming -Directory | Where-Object { Test-Path (Join-Path $_.FullName 'bin\strata.cmd') } | Select-Object -First 1
148        if (-not $inner) { Remove-Item -Recurse -Force $incoming; Die 'the archive does not look like a Strata Terminal.' }
149        $moved = "$dest.moved"; Move-Item $inner.FullName $moved; Remove-Item -Recurse -Force $incoming; Move-Item $moved $incoming
150    }
151
152    if ($env:STRATA_INSTALL_TEST_TRUST -eq '1') {
153        $trust = Join-Path $work 'test-trust.json'
154        try { Fetch "$feed/test-trust.json" $trust } catch { Remove-Item -Recurse -Force $incoming; Die 'the test feed has no test-trust.json' }
155        $env:STRATA_UPDATE_TRUSTED_KEYS = $trust
156    }
157    Write-Host "Checking the release's signature..."
158    $strata = Join-Path $incoming 'bin\strata.cmd'
159    $prevEap = $ErrorActionPreference; $ErrorActionPreference = 'Continue'      # a native program's stderr note must not stop the script
160    $out = & $strata update --check --no-engine --feed $feed 2>&1 | Out-String
161    $code = $LASTEXITCODE
162    $ErrorActionPreference = $prevEap
163    if ($code -ne 0) {
164        ($out -split "`r?`n" | Where-Object { $_.Trim() } | ForEach-Object { "    $_" }) | ForEach-Object { [Console]::Error.WriteLine($_) }
165        Remove-Item -Recurse -Force $incoming
166        Die "the release folder's signed feed could not be verified, so nothing was installed. The reason is printed above; if it names a newer feed already accepted here, use the newest release folder, or follow the step it gives. If you trust this source and see no such reason, ask its owner to publish a signed feed."
167    }
168    Write-Host '  Signature ok.'
169
170    if (Test-Path $dest) {
171        try { Remove-Item -Recurse -Force $dest }
172        catch { Remove-Item -Recurse -Force $incoming -ErrorAction SilentlyContinue; Die "Strata $version is already installed and a program is using it (a Strata window or server is running). Close it (run: strata launch --stop), then run this again. Nothing was changed." }
173    }
174    Move-Item $incoming $dest
175    $current = Join-Path $data 'terminal\current'
176    if (Test-Path $current) { cmd /c rmdir "$current" | Out-Null }
177    cmd /c mklink /J "$current" "$dest" | Out-Null
178    if ($LASTEXITCODE -ne 0 -or -not (Test-Path (Join-Path $current 'bin\strata.cmd'))) {
179        # a drive that cannot hold a junction (not NTFS) or a policy that forbids it: a small launcher in its place does the same job
180        try {
181            if (Test-Path $current) { Remove-Item -Recurse -Force $current -ErrorAction SilentlyContinue }
182            New-Item -ItemType Directory -Force -Path (Join-Path $current 'bin') | Out-Null
183            Set-Content -Encoding Ascii -Path (Join-Path $current 'bin\strata.cmd') -Value @('@echo off', ('"' + (Join-Path $dest 'bin\strata.cmd') + '" %*'))
184            Set-Content -Encoding Ascii -Path (Join-Path $current 'current.txt') -Value $dest
185            Write-Host '  (this drive could not make a link, so a small launcher was used instead)'
186        }
187        catch { Die "Strata was unpacked but its start command could not be set up ($($_.Exception.Message)). Run it directly: $dest\bin\strata.cmd" }
188    }
189    $bin = Join-Path $current 'bin'
190    if ($env:STRATA_NO_PATH -ne '1') {
191        $user = [Environment]::GetEnvironmentVariable('Path', 'User')
192        if (-not $user) { $user = '' }
193        if (($user -split ';') -notcontains $bin) {
194            [Environment]::SetEnvironmentVariable('Path', ($user.TrimEnd(';') + ';' + $bin).TrimStart(';'), 'User')
195        }
196        $env:Path = "$env:Path;$bin"
197    }
198    Write-Host 'Installed. Run: strata launch'
199    if ($env:STRATA_NO_PATH -eq '1') { Write-Host "  (the program is $bin\strata.cmd)" }
200    else { Write-Host '  (open a new terminal window if the command is not found yet)' }
201}
202finally {
203    Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
204}
205}