diff --git a/.github/workflows/windows-portable.yml b/.github/workflows/windows-portable.yml index 82e7146e..bf8d9578 100644 --- a/.github/workflows/windows-portable.yml +++ b/.github/workflows/windows-portable.yml @@ -18,6 +18,9 @@ jobs: distribution: temurin java-version: '21' - uses: gradle/actions/setup-gradle@v6 + - name: Test startup cache preparation + shell: pwsh + run: python scripts/tests/test_startup_cache.py - name: Test and package portable Windows app shell: pwsh run: ./scripts/build-windows.ps1 -JavaHome $env:JAVA_HOME diff --git a/WINDOWS.md b/WINDOWS.md index ba3a4745..bd199aee 100644 --- a/WINDOWS.md +++ b/WINDOWS.md @@ -65,15 +65,22 @@ Java AOT startup cache. .\gradlew.bat optimizeWindowsStartup -PdesktopOnly=true ``` -For an existing extracted image, use the Zulu 25 JDK used to build it. +For an existing extracted image, use the Zulu 25 JDK used to build it. If the +Java launcher cannot find its runtime DLLs under a Unicode path, extract the +image to an ASCII path such as `C:\Tools\KittyTune` and prepare it there. ```powershell .\scripts\optimize-windows-startup.ps1 -AppImage 'C:\path\to\KittyTune' -JavaHome 'C:\path\to\Zulu-25' ``` -The preparation opens the real home screen with a temporary guest profile and +The preparation keeps its guest profile and extracted native libraries in a +short path under the Windows temporary directory. It opens the home screen and closes it automatically. Open `KittyTune.exe` as usual afterwards. The cache -uses about 100 MB on disk. HotSpot checks JAR timestamps, so prepare it again +uses about 100 MB on disk. Training can take several minutes on older hardware; +the default timeout is ten minutes per Java process. Override it with +`-TrainingTimeoutSeconds` when running the PowerShell script directly. Locked +temporary files are reported as warnings after preparation. HotSpot checks JAR +timestamps, so prepare it again after updating or re-extracting the app. If the cache is absent or incompatible, the launcher starts normally. diff --git a/experiments/windows-startup-cache/README.md b/experiments/windows-startup-cache/README.md new file mode 100644 index 00000000..d890a6bb --- /dev/null +++ b/experiments/windows-startup-cache/README.md @@ -0,0 +1,57 @@ +# Packaged Windows startup cache + +This measures the same packaged KittyTune executable with Java AOT disabled +and enabled. No application code, UI assets, renderer preferences or features +are changed between variants. This is separate from PR #132's native device +probe change. + +Use a disposable image. The benchmark temporarily rewrites its launcher +configuration, saves `original.cfg` in the output directory, and restores the +configuration on normal completion or a Python exception. If interrupted by +force, restore that file manually. Do not run this against a live installation. + +```powershell +python experiments/windows-startup-cache/copy_image.py C:/KittyTune C:/bench/KittyTune +./scripts/optimize-windows-startup.ps1 -AppImage C:/bench/KittyTune -JavaHome C:/jdk-25 +python experiments/windows-startup-cache/benchmark.py --app-image C:/bench/KittyTune --output C:/bench/results --pairs 10 --disposable-image +``` + +The JDK must match the packaged runtime. Preparing the cache is a one-time +operation and can take several minutes; allow up to ten minutes per JVM. +The archive is about 100 MiB and must be prepared again after changing or +re-extracting the JARs. The normal launcher uses automatic fallback when an +archive is absent or incompatible. The benchmark deliberately uses strict +AOT mode for the candidate so an unused archive cannot appear as a success. + +## Protocol + +- Two excluded warmups, then ten alternating baseline/candidate pairs. + Every measurement is a fresh process; filesystem caches are warm. +- Both variants use the same executable path, runtime, JARs and settings. + The original installation and account profile are not used or modified. +- A synthetic returning guest profile uses a refused loopback HTTP proxy. + Setup and online feed readiness are not measured. +- The endpoint requires the first-draw marker from the actual main screen + and a visible Win32 window titled KittyTune in the launcher's process tree. + Visibility is polled every 25 ms; a blank or hidden window does not count. +- The packaged launcher can start a child JVM. Window ownership and PowerShell + draining therefore cover the entire process tree, not just the launcher. +- Three quiet CPU samples precede each launch. After recording the endpoint, + existing device-probe helpers are allowed to finish before terminating that + benchmark tree. No timing samples are discarded. +- Raw samples and executable/JAR/archive hashes are saved in the output + directory. These tests do not estimate CPU savings or cold-disk startup. + +Record the median, observed range, every paired sample and artifact hashes in +the PR description. Do not extrapolate a result on one GPU to all hardware. + +## Helper tests + +```powershell +python scripts/tests/test_startup_cache.py +``` + +The tests compile a small .NET Framework JVM fixture on Windows and exercise +long arguments, Unicode paths, locked cleanup files, preservation of an +existing cache on assembly failure, and partial timeout diagnostics. They do +not substitute for preparing and opening the actual application with a cache. diff --git a/experiments/windows-startup-cache/benchmark.py b/experiments/windows-startup-cache/benchmark.py new file mode 100644 index 00000000..e9fbe3fb --- /dev/null +++ b/experiments/windows-startup-cache/benchmark.py @@ -0,0 +1,222 @@ +import argparse +import atexit +import ctypes as c +from ctypes import wintypes as w +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time +import zipfile + + +def sha(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +parser = argparse.ArgumentParser() +parser.add_argument('--app-image',type=Path,required=True) +parser.add_argument('--output',type=Path,required=True) +parser.add_argument('--pairs',type=int,default=10) +parser.add_argument('--disposable-image',action='store_true',required=True) +args=parser.parse_args() +out=args.output.resolve() +if out.exists():parser.error('Use a new output directory') +out.mkdir(parents=True) +image=args.app_image.resolve();app=image/'app';exe=image/'KittyTune.exe' +original_cfg=(app/'KittyTune.cfg').read_bytes() +(out/'original.cfg').write_bytes(original_cfg) +atexit.register(lambda: (app/'KittyTune.cfg').write_bytes(original_cfg)) +metadata=dict(executable_sha256=sha(exe), aot_sha256=sha(app/'kittytune-startup.aot'), + default_archives=[p.name for p in (image/'runtime/bin/server').glob('*.jsa')], + app_jars={p.name:sha(p) for p in app.glob('KittyTuneWindows-*.jar')}, + pairs=args.pairs, endpoint='main screen drawn and visible', filesystem_cache='warm') +(out/'metadata.json').write_text(json.dumps(metadata,indent=2),encoding='utf-8') +lines=(app/'KittyTune.cfg').read_text(encoding='utf-8-sig').splitlines() +lines=[x for x in lines if 'AOTCache=' not in x and 'AOTMode=' not in x] +kernel = c.WinDLL('kernel32', use_last_error=True) +user = c.WinDLL('user32', use_last_error=True) +kernel.GetProcessTimes.argtypes = [w.HANDLE] + [c.POINTER(w.FILETIME)] * 4 +callback_type = c.WINFUNCTYPE(w.BOOL, w.HWND, w.LPARAM) +user.EnumWindows.argtypes = [callback_type, w.LPARAM] +user.GetWindowThreadProcessId.argtypes = [w.HWND, c.POINTER(w.DWORD)] +user.GetWindowTextW.argtypes = [w.HWND, w.LPWSTR, c.c_int] +user.IsWindowVisible.argtypes = [w.HWND] + + +class ProcessEntry(c.Structure): + _fields_ = [('size', w.DWORD), ('usage', w.DWORD), ('pid', w.DWORD), + ('heap', c.c_size_t), ('module', w.DWORD), ('threads', w.DWORD), + ('parent', w.DWORD), ('priority', w.LONG), ('flags', w.DWORD), + ('name', w.WCHAR * 260)] + + +kernel.CreateToolhelp32Snapshot.argtypes = [w.DWORD, w.DWORD] +kernel.CreateToolhelp32Snapshot.restype = w.HANDLE +kernel.Process32FirstW.argtypes = [w.HANDLE, c.POINTER(ProcessEntry)] +kernel.Process32NextW.argtypes = [w.HANDLE, c.POINTER(ProcessEntry)] +kernel.CloseHandle.argtypes = [w.HANDLE] + + +def powershell_children(pid): + owned = owned_pids(pid) + snapshot = kernel.CreateToolhelp32Snapshot(2, 0) + if snapshot == w.HANDLE(-1).value: + raise c.WinError() + try: + entry = ProcessEntry() + entry.size = c.sizeof(entry) + more = kernel.Process32FirstW(snapshot, c.byref(entry)) + found = [] + while more: + if entry.parent in owned and entry.name.lower() == 'powershell.exe': + found.append(entry.pid) + more = kernel.Process32NextW(snapshot, c.byref(entry)) + return found + finally: + kernel.CloseHandle(snapshot) + + +def ticks(value): + return value.dwLowDateTime + (value.dwHighDateTime << 32) + + +def system_times(): + idle, kt, ut = w.FILETIME(), w.FILETIME(), w.FILETIME() + if not kernel.GetSystemTimes(c.byref(idle), c.byref(kt), c.byref(ut)): + raise c.WinError() + return ticks(idle), ticks(kt) + ticks(ut) + + +def quiet(): + consecutive = 0 + deadline = time.monotonic() + 120 + while consecutive < 3: + before = system_times() + time.sleep(1) + after = system_times() + busy = 1 - (after[0] - before[0]) / (after[1] - before[1]) + consecutive = consecutive + 1 if busy < 0.20 else 0 + if time.monotonic() > deadline: + raise RuntimeError('Machine stayed busy; stop other builds before benchmarking.') + + +def owned_pids(pid): + snapshot=kernel.CreateToolhelp32Snapshot(2,0) + try: + entry=ProcessEntry();entry.size=c.sizeof(entry);more=kernel.Process32FirstW(snapshot,c.byref(entry));parents={} + while more: + parents[entry.pid]=entry.parent;more=kernel.Process32NextW(snapshot,c.byref(entry)) + owned={pid} + for _ in range(5):owned.update(k for k,v in parents.items() if v in owned) + return owned + finally:kernel.CloseHandle(snapshot) + + +def visible(pid): + owned=owned_pids(pid) + found = [] + @callback_type + def visit(hwnd, unused): + owner = w.DWORD() + user.GetWindowThreadProcessId(hwnd, c.byref(owner)) + if owner.value in owned and user.IsWindowVisible(hwnd): + title = c.create_unicode_buffer(256) + user.GetWindowTextW(hwnd, title, len(title)) + if title.value == 'KittyTune': + found.append(hwnd) + return True + user.EnumWindows(visit, 0) + return bool(found) + + +seed = out / 'seed' +for directory in ['roaming/KittyTune', 'local', 'home', 'temp']: + (seed / directory).mkdir(parents=True) +for name, data in [ + ('prefs.json', dict(has_completed_setup=True, protected_tracks_announced=True, + proxy_enabled=True, proxy_host='127.0.0.1', proxy_port=9, proxy_type='HTTP')), + ('soundtune_auth.json', dict(is_guest_mode=True)), + ('kitty_pet.json', dict(announced=True)), +]: + (seed / 'roaming/KittyTune' / name).write_text(json.dumps(data), encoding='utf-8') +rows = [] + + +def launch(variant, label, warmup=False): + quiet() + folder = out / label + profile = folder / 'profile' + shutil.copytree(seed, profile) + log = profile / 'roaming/KittyTune/startup.log' + log.unlink(missing_ok=True) + extra=['java-options=-Dkittytune.startuplog=true', 'java-options=-XX:AOTMode='+('on' if variant=='candidate' else 'off')] + if variant=='candidate':extra+=['java-options=-XX:AOTCache=$APPDIR/kittytune-startup.aot'] + extra += ['java-options=-Duser.home='+str(profile/'home'), 'java-options=-Djava.io.tmpdir='+str(profile/'temp'), 'java-options=-Xlog:aot=info:file=aot.log'] + config=[] + for line in lines: + config.append(line) + if line=='[JavaOptions]':config.extend(extra) + (app/'KittyTune.cfg').write_bytes(('\n'.join(config)+'\n').encode('utf-8')) + env = os.environ.copy() + env.update(APPDATA=str(profile / 'roaming'), LOCALAPPDATA=str(profile / 'local'), + TEMP=str(profile / 'temp'), TMP=str(profile / 'temp')) + for name in ['JAVA_TOOL_OPTIONS', 'JDK_JAVA_OPTIONS', '_JAVA_OPTIONS', + 'SKIKO_RENDER_API', 'SKIKO_GPU_PRIORITY']: + env.pop(name, None) + with (folder / 'stdout.log').open('w', encoding='utf-8') as stdout, \ + (folder / 'stderr.log').open('w', encoding='utf-8') as stderr: + start = time.perf_counter() + process = subprocess.Popen([str(exe)], + env=env, cwd=folder, stdout=stdout, stderr=stderr) + try: + while time.perf_counter() - start < 60: + text = log.read_text(encoding='utf-8') if log.exists() else '' + if 'window content drawn' in text and visible(process.pid): + break + if process.poll() is not None and len(owned_pids(process.pid))==1: + raise RuntimeError(f'{label}: process exited: {process.returncode}') + time.sleep(0.025) + else: + raise RuntimeError(f'{label}: main window did not draw and become visible') + elapsed = (time.perf_counter() - start) * 1000 + marks = {m.group(2).strip(): int(m.group(1)) for m in re.finditer( + r'\+\s*(\d+) ms process.*?since first mark\s+([^\n]+)', text)} + if 'router: composing main screen' not in marks: + raise RuntimeError('The run did not reach the real main screen.') + row = dict(variant=variant, run=label, warmup=warmup, + drawn_visible_ms=round(elapsed, 3), marks=marks) + rows.append(row) + print(label, round(elapsed), 'ms', flush=True) + finally: + stable = 5 + if process.poll() is None: + deadline = time.monotonic() + 30 + stable = 0 + while stable < 5 and time.monotonic() < deadline: + stable = 0 if powershell_children(process.pid) else stable + 1 + time.sleep(0.1) + cleanup = subprocess.run(['taskkill.exe', '/F', '/T', '/PID', str(process.pid)], + capture_output=True, timeout=10, + creationflags=subprocess.CREATE_NO_WINDOW) + (folder / 'cleanup.log').write_bytes(cleanup.stdout + cleanup.stderr) + process.wait(timeout=10) + if stable < 5: + raise RuntimeError('The old PnP query did not drain; no further launches are comparable.') + (out / 'samples.json').write_text(json.dumps(rows, indent=2), encoding='utf-8') + return profile + + +launch('baseline', 'warmup-baseline', True) +initialized = launch('candidate', 'warmup-candidate', True) +shutil.copytree(initialized, seed, dirs_exist_ok=True) +for pair in range(args.pairs): + order = ['baseline', 'candidate'] if pair % 2 == 0 else ['candidate', 'baseline'] + for variant in order: + launch(variant, f'pair-{pair}-{variant}') + rows[-1]['pair'] = pair + (out / 'samples.json').write_text(json.dumps(rows, indent=2), encoding='utf-8') diff --git a/experiments/windows-startup-cache/copy_image.py b/experiments/windows-startup-cache/copy_image.py new file mode 100644 index 00000000..92ad74a3 --- /dev/null +++ b/experiments/windows-startup-cache/copy_image.py @@ -0,0 +1,19 @@ +import argparse +from pathlib import Path +import shutil + +parser = argparse.ArgumentParser() +parser.add_argument('source', type=Path) +parser.add_argument('destination', type=Path) +args = parser.parse_args() +source = args.source.resolve() +destination = args.destination.resolve() +if destination.exists() or destination.is_relative_to(source): + parser.error('Use a new destination outside the source image.') +if not (source/'KittyTune.exe').is_file(): + parser.error('Source must contain KittyTune.exe, app and runtime.') +destination.mkdir(parents=True) +for directory in ['app', 'runtime']: + shutil.copytree(source/directory, destination/directory, + ignore=shutil.ignore_patterns('startup-training-*', 'kittytune-startup.aot')) +shutil.copy2(source/'KittyTune.exe', destination/'KittyTune.exe') diff --git a/scripts/optimize-windows-startup.ps1 b/scripts/optimize-windows-startup.ps1 index 19e582a3..93180e86 100644 --- a/scripts/optimize-windows-startup.ps1 +++ b/scripts/optimize-windows-startup.ps1 @@ -1,7 +1,8 @@ #Requires -Version 7.2 param( [Parameter(Mandatory)][string]$AppImage, - [Parameter(Mandatory)][string]$JavaHome + [Parameter(Mandatory)][string]$JavaHome, + [ValidateRange(1, 3600)][int]$TrainingTimeoutSeconds = 600 ) $ErrorActionPreference = 'Stop' @@ -28,7 +29,6 @@ foreach ($jar in $classpath) { # Record after extraction: HotSpot checks the actual timestamp of every JAR in the image. $work = Join-Path $app "startup-training-$([Guid]::NewGuid().ToString('N'))" -$profile = Join-Path $work 'roaming/KittyTune' function Invoke-TrainingJvm([string[]]$Arguments) { $start = [Diagnostics.ProcessStartInfo]::new($java) @@ -36,22 +36,30 @@ function Invoke-TrainingJvm([string[]]$Arguments) { $start.RedirectStandardOutput = $true $start.RedirectStandardError = $true $start.CreateNoWindow = $true - foreach ($option in $Arguments) { $start.ArgumentList.Add($option) } + # A packaged classpath can exceed Windows' command-line limit. + $argumentFile = Join-Path $work ("jvm-" + [Guid]::NewGuid().ToString('N') + '.args') + $quoted = foreach ($option in $Arguments) { + '"' + $option.Replace('\', '\\').Replace('"', '\"').Replace("`r", '\r').Replace("`n", '\n').Replace("`t", '\t') + '"' + } + [IO.File]::WriteAllText($argumentFile, ($quoted -join "`n")) + # The Windows Java launcher can lose Unicode characters in the @file path. + $start.ArgumentList.Add('@' + [IO.Path]::GetRelativePath($image, $argumentFile)) foreach ($name in 'JAVA_TOOL_OPTIONS', 'JDK_JAVA_OPTIONS', '_JAVA_OPTIONS', 'KITTYTUNE_STARTUP_LOG') { [void]$start.Environment.Remove($name) } - $start.Environment['APPDATA'] = "$work/roaming" - $start.Environment['LOCALAPPDATA'] = "$work/local" - $start.Environment['TEMP'] = $start.Environment['TMP'] = "$work/temp" - $start.Environment['ProgramData'] = $start.Environment['OneDrive'] = $start.Environment['ALLUSERSPROFILE'] = "$work/home" + $start.Environment['APPDATA'] = "$scratch/roaming" + $start.Environment['LOCALAPPDATA'] = "$scratch/local" + $start.Environment['TEMP'] = $start.Environment['TMP'] = "$scratch/temp" + $start.Environment['ProgramData'] = $start.Environment['OneDrive'] = $start.Environment['ALLUSERSPROFILE'] = "$scratch/home" $process = [Diagnostics.Process]::Start($start) try { $stdout = $process.StandardOutput.ReadToEndAsync() $stderr = $process.StandardError.ReadToEndAsync() - if (!$process.WaitForExit(120000)) { + if (!$process.WaitForExit($TrainingTimeoutSeconds * 1000)) { $process.Kill($true) $process.WaitForExit() - throw 'Java startup cache preparation timed out.' + $output = $stdout.GetAwaiter().GetResult() + $stderr.GetAwaiter().GetResult() + throw "Java startup cache preparation timed out.`n$output" } $output = $stdout.GetAwaiter().GetResult() + $stderr.GetAwaiter().GetResult() if ($process.ExitCode -ne 0) { throw "Java startup cache preparation failed.`n$output" } @@ -62,8 +70,13 @@ function Invoke-TrainingJvm([string[]]$Arguments) { } $copiedJava = $false +$scratch = $null try { - New-Item -ItemType Directory -Path $profile, "$work/local", "$work/temp", "$work/home" | Out-Null + # Native libraries extracted under user.home and java.io.tmpdir need short paths. + # Keep the archive staging directory beside the final cache for same-volume moves. + $scratch = (New-Item -ItemType Directory -Path ([IO.Path]::GetTempPath()) -Name ("kt-" + [IO.Path]::GetRandomFileName())).FullName + $profile = Join-Path $scratch 'roaming/KittyTune' + New-Item -ItemType Directory -Path "$work", $profile, "$scratch/local", "$scratch/temp", "$scratch/home" | Out-Null '{"has_completed_setup":true,"protected_tracks_announced":true}' | Set-Content "$profile/prefs.json" '{"is_guest_mode":true}' | Set-Content "$profile/soundtune_auth.json" '{"announced":true}' | Set-Content "$profile/kitty_pet.json" @@ -72,7 +85,7 @@ try { Copy-Item -LiteralPath (Join-Path $JavaHome 'bin/java.exe') -Destination $java $copiedJava = $true } - $settings = $options + @("-Duser.home=$work/home", "-Djava.io.tmpdir=$work/temp") + $settings = $options + @("-Duser.home=$scratch/home", "-Djava.io.tmpdir=$scratch/temp") $launch = @('-cp', ($classpath -join ';'), 'com.alananasss.kittytune.MainKt') $configuration = Join-Path $work 'recording.aotconfig' $candidate = Join-Path $work 'kittytune-startup.aot' @@ -96,10 +109,21 @@ try { [IO.File]::Move($newConfig, $cfg, $true) Write-Output "Startup cache prepared for $image" } finally { - if ($copiedJava) { Remove-Item -LiteralPath $java } + if ($copiedJava) { + try { Remove-Item -LiteralPath $java } catch { Write-Warning "Could not remove temporary Java launcher: $($_.Exception.Message)" } + } # This directory was generated directly under the resolved app image. $resolved = (Resolve-Path -LiteralPath $work -ErrorAction SilentlyContinue).Path if ($resolved -and [IO.Path]::GetDirectoryName($resolved) -eq $app) { - Remove-Item -LiteralPath $resolved -Recurse -Force + try { Remove-Item -LiteralPath $resolved -Recurse -Force } + catch { Write-Warning "Could not remove startup training files: $($_.Exception.Message)" } + } + if ($scratch) { + $tempRoot = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath()) -ErrorAction SilentlyContinue).Path + $resolved = (Resolve-Path -LiteralPath $scratch -ErrorAction SilentlyContinue).Path + if ($tempRoot -and $resolved -and [IO.Path]::GetDirectoryName($resolved) -eq [IO.Path]::TrimEndingDirectorySeparator($tempRoot)) { + try { Remove-Item -LiteralPath $resolved -Recurse -Force } + catch { Write-Warning "Could not remove the temporary training profile: $($_.Exception.Message)" } + } } } diff --git a/scripts/tests/CacheJvmFixture.cs b/scripts/tests/CacheJvmFixture.cs new file mode 100644 index 00000000..2ec8d672 --- /dev/null +++ b/scripts/tests/CacheJvmFixture.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Linq; +using System.Diagnostics; +using System.Threading; +public class CacheJvmFixture { + public static int Main(string[] args) { + if (args.Length == 1 && args[0].StartsWith("@")) { + string argumentFile = args[0].Substring(1); + if (argumentFile.Any(c => c > 127)) { + Console.Error.WriteLine("Expected an ASCII argument file path for the Windows Java launcher"); + return 10; + } + args = File.ReadAllLines(argumentFile).Select(line => + System.Text.RegularExpressions.Regex.Unescape(line.Substring(1, line.Length - 2))).ToArray(); + } + string argumentLog = Environment.GetEnvironmentVariable("FAKE_ARGUMENT_LOG"); + if (argumentLog != null) File.WriteAllLines(argumentLog, args); + Func option = prefix => args.FirstOrDefault(a => a.StartsWith(prefix)) == null ? null : args.First(a => a.StartsWith(prefix)).Substring(prefix.Length); + string mode = option("-XX:AOTMode="); + if (mode == "record") { + Console.WriteLine("fixture running"); Console.Out.Flush(); + if (Environment.GetEnvironmentVariable("FAKE_DELAY") == "1") Thread.Sleep(5000); + string config = option("-XX:AOTConfiguration="); + File.WriteAllText(config, "recorded"); + Console.WriteLine("KittyTune startup cache training finished"); Console.Out.Flush(); + } else if (mode == "create") { + if(Environment.GetEnvironmentVariable("FAKE_FAIL") == "1") { Console.Error.WriteLine("assembly fixture failure"); return 7; } + File.WriteAllText(option("-XX:AOTCache="), "fresh-cache"); + } else if (mode == "on" && !File.Exists(option("-XX:AOTCache="))) return 8; + if (mode == "on") { + if (Environment.GetEnvironmentVariable("FAKE_HOLD") == "1") { + string path = Path.Combine(Path.GetDirectoryName(option("-XX:AOTCache=")), "locked.tmp"); + File.WriteAllText(path, "locked"); + string ready = Environment.GetEnvironmentVariable("FAKE_LOCK_READY"); + File.WriteAllText(ready, path); + for(int i=0;i<500 && !File.Exists(ready + ".locked");i++) Thread.Sleep(10); + if(!File.Exists(ready + ".locked")) return 9; + } + } + return 0; + } +} diff --git a/scripts/tests/test_startup_cache.py b/scripts/tests/test_startup_cache.py new file mode 100644 index 00000000..e059d64c --- /dev/null +++ b/scripts/tests/test_startup_cache.py @@ -0,0 +1,98 @@ +import threading +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import time +import unittest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = Path(os.environ.get('KITTYTUNE_CACHE_SCRIPT', ROOT/'scripts/optimize-windows-startup.ps1')) +@unittest.skipUnless(os.name == 'nt', 'Windows helper') +class StartupCacheTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tools = tempfile.TemporaryDirectory() + cls.sdk = Path(cls.tools.name) / 'sdk' + (cls.sdk / 'bin').mkdir(parents=True) + compiler = Path(os.environ['WINDIR']) / 'Microsoft.NET/Framework64/v4.0.30319/csc.exe' + subprocess.run([str(compiler), '/nologo', '/out:' + str(cls.sdk/'bin/java.exe'), + str(ROOT/'scripts/tests/CacheJvmFixture.cs')], check=True, creationflags=subprocess.CREATE_NO_WINDOW) + @classmethod + def tearDownClass(cls): cls.tools.cleanup() + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.image = self.root/'image Ω music' + (self.image/'app').mkdir(parents=True) + (self.image/'runtime/bin').mkdir(parents=True) + (self.image/'app/main.jar').write_bytes(b'fixture') + self.cfg = self.image/'app/KittyTune.cfg' + self.original = '[Application]\napp.mainclass=com.alananasss.kittytune.MainKt\napp.classpath=$APPDIR/main.jar\n[JavaOptions]\njava-options=-Xmx512m\n' + self.cfg.write_bytes(self.original.encode()) + self.ready = self.root/'holder.pid' + def tearDown(self): self.temp.cleanup() + def run_helper(self, extra=(), **flags): + env=os.environ.copy() + env.update(flags,FAKE_LOCK_READY=str(self.ready)) + release=threading.Event() + def hold_file(): + deadline=time.monotonic()+10 + while not release.is_set() and time.monotonic()