diff --git a/src/cli/command/init-tool.spec.ts b/src/cli/command/init-tool.spec.ts index 1cf8ee358d..762185d174 100644 --- a/src/cli/command/init-tool.spec.ts +++ b/src/cli/command/init-tool.spec.ts @@ -4,6 +4,7 @@ import { logger } from '../utils/index.ts'; import { registerCommands } from './index.ts'; const mocks = vi.hoisted(() => ({ + setupVolume: vi.fn(), installTool: vi.fn(), prepareTools: vi.fn(), initializeTools: vi.fn(), @@ -23,6 +24,19 @@ describe('cli/command/init-tool', () => { false, ); + // a single tool and a dry run leave the volume alone + expect(mocks.setupVolume).not.toHaveBeenCalled(); + expect(await cli.run(['init', 'tool', 'all', '-d'])).toBe(0); + expect(mocks.setupVolume).not.toHaveBeenCalled(); + + // `all` sets up the volume first + mocks.initializeTools.mockClear(); + expect(await cli.run(['init', 'tool', 'all'])).toBe(0); + expect(mocks.setupVolume).toHaveBeenCalledOnce(); + expect(mocks.setupVolume.mock.invocationCallOrder[0]).toBeLessThan( + mocks.initializeTools.mock.invocationCallOrder[0]!, + ); + mocks.initializeTools.mockRejectedValueOnce(new Error('test')); expect(await cli.run(['init', 'tool', 'node'])).toBe(1); diff --git a/src/cli/command/init-tool.ts b/src/cli/command/init-tool.ts index ec6533eddc..e1428cb745 100644 --- a/src/cli/command/init-tool.ts +++ b/src/cli/command/init-tool.ts @@ -1,5 +1,6 @@ import { Command, Option } from 'clipanion'; import prettyMilliseconds from 'pretty-ms'; +import { setupVolume } from '../install-tool/index.ts'; import { initializeTools } from '../prepare-tool/index.ts'; import { logger } from '../utils/index.ts'; import { command } from './utils.ts'; @@ -21,12 +22,19 @@ export class InitToolCommand extends Command { dryRun = Option.Boolean('-d,--dry-run', false); - /** Initializes the passed tools, or all prepared tools for `all`. */ + /** + * Initializes the passed tools, or all prepared tools for `all`. For `all` + * it first sets up an empty or older `/opt/containerbase` from the + * build-time list of the image. + */ async execute(): Promise { const start = Date.now(); let error = false; logger.info(`Initializing tools ${this.tools.join(', ')}...`); try { + if (!this.dryRun && this.tools.length === 1 && this.tools[0] === 'all') { + await setupVolume(); + } return await initializeTools(this.tools, this.dryRun); } catch (err) { error = true; diff --git a/src/cli/install-tool/index.spec.ts b/src/cli/install-tool/index.spec.ts index b8a7b70b22..f74ccc7321 100644 --- a/src/cli/install-tool/index.spec.ts +++ b/src/cli/install-tool/index.spec.ts @@ -9,6 +9,8 @@ import { vi, } from 'vitest'; import { + BuildListService, + DataService, IpcServer, PathService, ToolVersionsService, @@ -38,9 +40,11 @@ import { linkTool, listSupportedTools, resolveVersion, + setupVolume, uninstallTool, } from './index.ts'; import { V2ToolInstallService } from './install-legacy-tool.service.ts'; +import { InstallToolService } from './install-tool.service.ts'; import { scope } from '~test/http-mock.ts'; import { ensurePaths, rootPath } from '~test/path.ts'; @@ -68,6 +72,11 @@ describe('cli/install-tool/index', () => { 'opt/containerbase/bin', 'opt/containerbase/data', 'opt/containerbase/links', + // the files of the recorded parent versions, so they aren't installed again + 'opt/containerbase/tools/node/1.0.0', + 'opt/containerbase/tools/node/1.0.1', + 'opt/containerbase/tools/python/1.0.0', + 'opt/containerbase/tools/ruby/1.0.0', 'tmp/containerbase/tool.init.d', 'usr/local/containerbase/tools/v2', 'var/lib/containerbase/tool.prep.d', @@ -732,6 +741,59 @@ describe('cli/install-tool/index', () => { }); }); + describe('setupVolume', () => { + test('does nothing when the volume has the list of the image', async () => { + vi.spyOn(BuildListService.prototype, 'changed').mockResolvedValue(false); + const spy = vi.spyOn(InstallToolService.prototype, 'setupVolume'); + + await expect(setupVolume()).resolves.toBeUndefined(); + + expect(spy).not.toHaveBeenCalled(); + }); + + test('sets up the volume from a different list', async () => { + vi.spyOn(BuildListService.prototype, 'changed').mockResolvedValue(true); + const spy = vi + .spyOn(InstallToolService.prototype, 'setupVolume') + .mockResolvedValue(); + + await expect(setupVolume()).resolves.toBeUndefined(); + + expect(spy).toHaveBeenCalledOnce(); + }); + + test('creates the base folders before the databases load', async () => { + vi.spyOn(BuildListService.prototype, 'changed').mockResolvedValue(true); + const ensure = vi.spyOn(PathService.prototype, 'ensureBasePaths'); + const setup = vi + .spyOn(InstallToolService.prototype, 'setupVolume') + .mockResolvedValue(); + const load = vi.spyOn(DataService.prototype, 'load'); + + await expect(setupVolume()).resolves.toBeUndefined(); + + expect(ensure.mock.invocationCallOrder[0]).toBeLessThan( + load.mock.invocationCallOrder[0]!, + ); + expect(setup).toHaveBeenCalledOnce(); + }); + + test('only warns when the setup fails', async () => { + const err = new Error('failed'); + vi.spyOn(BuildListService.prototype, 'changed').mockResolvedValue(true); + vi.spyOn(InstallToolService.prototype, 'setupVolume').mockRejectedValue( + err, + ); + + await expect(setupVolume()).resolves.toBeUndefined(); + + expect(logger.warn).toHaveBeenCalledWith( + { err }, + 'cannot set up the volume', + ); + }); + }); + describe('ensureTool', () => { test('fails first when the folders are not writable', async () => { const pathSvc = await createContainer().getAsync(PathService); diff --git a/src/cli/install-tool/index.ts b/src/cli/install-tool/index.ts index 0d054b5a81..db9dd1d6b6 100644 --- a/src/cli/install-tool/index.ts +++ b/src/cli/install-tool/index.ts @@ -1,6 +1,7 @@ import { Container, injectFromHierarchy, injectable } from 'inversify'; import type { ShellWrapperConfig } from '../services/index.ts'; import { + BuildListService, DataService, IpcClient, LinkToolService, @@ -500,6 +501,30 @@ export async function uninstallTool({ return svc.uninstall(tool, version, dryRun, recursive); } +/** + * Sets up `/opt/containerbase` from the build-time list of the image, when it + * differs from the copy on the volume, see `InstallToolService.setupVolume`. + * Without a difference, eg. in an image without a volume, it only reads two + * small files. A failure is only logged, as the shims install what is missing. + */ +export async function setupVolume(): Promise { + try { + const base = createContainer(); + const list = await base.getAsync(BuildListService); + if (!(await list.changed())) { + return; + } + logger.debug('setting up the volume from the build-time list'); + // before the databases load, which would create `data` with the owner and + // mode of the running process + await (await base.getAsync(PathService)).ensureBasePaths(); + const container = await prepareInstallContainer(); + await (await container.getAsync(InstallToolService)).setupVolume(); + } catch (err) { + logger.warn({ err }, 'cannot set up the volume'); + } +} + /** * Makes a command of an installed tool run again, see * `InstallToolService.ensure`. Generic install services are registered for diff --git a/src/cli/install-tool/install-tool.service.spec.ts b/src/cli/install-tool/install-tool.service.spec.ts index 780c94c8a8..4fde7ecbd7 100644 --- a/src/cli/install-tool/install-tool.service.spec.ts +++ b/src/cli/install-tool/install-tool.service.spec.ts @@ -10,6 +10,7 @@ import { import { beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'; import { initializeTools, prepareTools } from '../prepare-tool/index.ts'; import { + type BuildListEntry, BuildListService, CacheService, EnvService, @@ -220,6 +221,31 @@ class StuckInstallService extends TestInstallService { override readonly parent = 'root-only'; } +/** `jq`, which is restored at once when a volume is set up */ +@injectable() +@injectFromHierarchy() +class JqInstallService extends TestInstallService { + override readonly name = 'jq'; + + /** Creates the versioned tool path. */ + override async install(version: string): Promise { + await this.pathSvc.createVersionedToolPath(this.name, version); + } + + /** Links `jq`. */ + override async link(_version: string): Promise { + await this.shellwrapper({ srcDir: '/bin/bash' }); + } +} + +/** `git`, which apt installs, so there is nothing to restore */ +@injectable() +@injectFromHierarchy() +class GitInstallService extends TestInstallService { + override readonly name = 'git'; + override readonly canUninstall = false; +} + /** a npm package, which is listed with its type */ @injectable() @injectFromHierarchy() @@ -236,6 +262,17 @@ class DotnetTypedInstallService extends TestInstallService { override readonly type = 'dotnet'; } +/** + * The error code of looking up the path without following links, so a + * dangling link counts as existing. + */ +function lookup(path: string): Promise { + return fs.lstat(path).then( + () => undefined, + (err: NodeJS.ErrnoException) => err.code, + ); +} + /** The pointer of a command. */ function linkPath(name: string): string { return rootPath(`opt/containerbase/links/${name}`); @@ -259,6 +296,8 @@ describe('cli/install-tool/install-tool.service', () => { parent.bind(INSTALL_TOOL_TOKEN).to(ChildInstallService); parent.bind(INSTALL_TOOL_TOKEN).to(OrphanInstallService); parent.bind(INSTALL_TOOL_TOKEN).to(StuckInstallService); + parent.bind(INSTALL_TOOL_TOKEN).to(JqInstallService); + parent.bind(INSTALL_TOOL_TOKEN).to(GitInstallService); parent.bind(INSTALL_TOOL_TOKEN).to(NpmTypedInstallService); parent.bind(INSTALL_TOOL_TOKEN).to(DotnetTypedInstallService); @@ -566,6 +605,64 @@ describe('cli/install-tool/install-tool.service', () => { ).toHaveLength(1); }); + test('installs a parent version again first when its files are missing', async () => { + const pathSvc = await child.getAsync(PathService); + expect(await install.install('multi', '61.0.0')).toBeUndefined(); + await fs.rm(pathSvc.versionedToolPath('multi', '61.0.0'), { + recursive: true, + }); + const multi = vi.spyOn(MultiInstallService.prototype, 'install'); + const childSvc = vi.spyOn(ChildInstallService.prototype, 'install'); + + expect(await install.install('child', '3.6.0')).toBeUndefined(); + + expect(multi).toHaveBeenCalledExactlyOnceWith('61.0.0'); + expect(multi.mock.invocationCallOrder[0]).toBeLessThan( + childSvc.mock.invocationCallOrder[0]!, + ); + expect( + await pathExists(pathSvc.versionedToolPath('multi', '61.0.0')), + ).toBe(true); + }); + + test('the links of a parent which is installed again are not stored for the child', async () => { + const pathSvc = await child.getAsync(PathService); + const ver = await child.getAsync(VersionService); + const link = await child.getAsync(LinkToolService); + expect(await install.install('multi', '63.0.0')).toBeUndefined(); + await fs.rm(pathSvc.versionedToolPath('multi', '63.0.0'), { + recursive: true, + }); + + expect(await install.install('child', '3.8.0')).toBeUndefined(); + + // without the clear after the restore, the commands of the parent are + // among the links stored for the child + expect(link.links).toEqual(['child']); + expect(await ver.findLink('multi')).toMatchObject({ + tool: { name: 'multi', version: '63.0.0' }, + }); + }); + + test('stops when a missing parent version cannot be installed again', async () => { + const pathSvc = await child.getAsync(PathService); + expect(await install.install('multi', '62.0.0')).toBeUndefined(); + await fs.rm(pathSvc.versionedToolPath('multi', '62.0.0'), { + recursive: true, + }); + // only the parent needs its init, which fails + vi.spyOn( + ChildInstallService.prototype, + 'isInitialized', + ).mockResolvedValue(true); + vi.mocked(initializeTools).mockResolvedValueOnce(1); + const childSvc = vi.spyOn(ChildInstallService.prototype, 'install'); + + expect(await install.install('child', '3.7.0')).toBe(1); + + expect(childSvc).not.toHaveBeenCalled(); + }); + test.each(['no-uninstall', 'shell-tool'])( 'keeps a recorded version of %s, which has no files to check', async (tool) => { @@ -947,6 +1044,325 @@ describe('cli/install-tool/install-tool.service', () => { }); }); + describe('setupVolume', () => { + const multi = (version: string): BuildListEntry[] => [ + { kind: 'i', type: 'tool', tool: 'multi', version }, + { kind: 'c', alias: 'multi', tool: 'multi', version }, + { kind: 'l', command: 'multi', tool: 'multi', version }, + { + kind: 'l', + command: `multi${version.split('.')[0]}`, + tool: 'multi', + version, + }, + ]; + + /** Lets the list of the image have the entries. */ + function listOf(...entries: BuildListEntry[]): void { + vi.spyOn(BuildListService.prototype, 'read').mockResolvedValue(entries); + vi.spyOn(BuildListService.prototype, 'copyToVolume').mockResolvedValue(); + } + + test('sets up the databases, shims and version files', async () => { + const ver = await child.getAsync(VersionService); + const pathSvc = await child.getAsync(PathService); + const wrapper = join( + pathSvc.versionedToolPath('multi', '40.0.0'), + '.wrappers/multi40', + ); + await fs.mkdir(join(wrapper, '..'), { recursive: true }); + await fs.writeFile(wrapper, ''); + await fs.symlink('/stale', linkPath('multi')); + // a version installed at runtime, the image wins + await ver.setCurrent({ + name: 'multi', + tool: { name: 'multi', version: '99.0.0' }, + }); + listOf( + ...multi('40.0.0'), + { + kind: 'i', + type: 'tool', + tool: 'child', + version: '7.0.0', + parent: { name: 'multi', version: '40.0.0' }, + }, + { + kind: 'c', + alias: 'child', + tool: 'child', + version: '7.0.0', + parent: { name: 'multi', version: '40.0.0' }, + }, + ...multi('41.0.0'), + { kind: 'i', type: 'npm', tool: 'dyn-pkg', version: '1.0.0' }, + // a tool with an install service keeps its type + { kind: 'i', type: 'npm', tool: 'npm-typed', version: '1.0.0' }, + ); + const copy = vi.mocked(BuildListService.prototype.copyToVolume); + + await install.setupVolume(); + + expect(await ver.getCurrent('multi')).toMatchObject({ + tool: { name: 'multi', version: '41.0.0' }, + }); + expect(await ver.getCurrent('child')).toMatchObject({ + tool: { name: 'child', version: '7.0.0' }, + parent: { name: 'multi', version: '40.0.0' }, + }); + expect(await ver.findLink('multi')).toMatchObject({ + tool: { name: 'multi', version: '41.0.0' }, + }); + expect(await ver.findLink('multi40')).toMatchObject({ + tool: { name: 'multi', version: '40.0.0' }, + }); + // both versions are recorded, once, also for the parent + expect(await ver.isInstalled({ name: 'multi', version: '40.0.0' })).toBe( + true, + ); + expect( + await ver.isInstalled({ + name: 'child', + version: '7.0.0', + parent: { name: 'multi', version: '40.0.0' }, + }), + ).toBe(true); + expect(await ver.getType('dyn-pkg')).toBe('npm'); + expect(await ver.getType('npm-typed')).toBeUndefined(); + expect( + await fs.readFile(rootPath('opt/containerbase/versions/multi'), 'utf8'), + ).toBe('41.0.0'); + // the shims are written, a pointer of a version without a wrapper is + // removed, one with a wrapper is linked + expect(await fs.readFile(binPath('multi'), 'utf8')).toContain( + 'ensure multi ', + ); + expect(await lookup(linkPath('multi'))).toBe('ENOENT'); + expect(await fs.readlink(linkPath('multi40'))).toBe(wrapper); + expect(copy).toHaveBeenCalledOnce(); + }); + + test('only a current line makes a version current', async () => { + const ver = await child.getAsync(VersionService); + const jq = vi.spyOn(JqInstallService.prototype, 'install'); + listOf( + { kind: 'i', type: 'npm', tool: 'dyn-uncurrent', version: '1.0.0' }, + { kind: 'i', type: 'npm', tool: 'dyn-current', version: '1.0.0' }, + { kind: 'i', type: 'npm', tool: 'dyn-current', version: '2.0.0' }, + { + kind: 'c', + alias: 'dyn-current', + tool: 'dyn-current', + version: '1.0.0', + }, + { kind: 'i', type: 'tool', tool: 'jq', version: '1.3.0' }, + ); + + await install.setupVolume(); + + expect(await ver.getCurrent('dyn-uncurrent')).toBeNull(); + expect(await ver.getCurrent('dyn-current')).toMatchObject({ + tool: { name: 'dyn-current', version: '1.0.0' }, + }); + expect( + await ver.isInstalled({ name: 'dyn-uncurrent', version: '1.0.0' }), + ).toBe(true); + // a version without a current line is not restored + expect(jq).not.toHaveBeenCalled(); + }); + + describe('the parent of a linked child tool', () => { + /** Writes the wrapper of the child for a parent version. */ + async function wrapperFor( + version: string, + parent: string, + ): Promise { + const pathSvc = await child.getAsync(PathService); + const wrapper = join( + pathSvc.versionedToolPath('child', version), + parent, + '.wrappers/child', + ); + await fs.mkdir(join(wrapper, '..'), { recursive: true }); + await fs.writeFile(wrapper, ''); + return wrapper; + } + + /** Lists the child for the parent 47.0.0, its link before its `c` line. */ + function childList(version: string): BuildListEntry[] { + const parent = { name: 'multi', version: '47.0.0' }; + return [ + { kind: 'i', type: 'tool', tool: 'multi', version: '47.0.0' }, + { kind: 'c', alias: 'multi', tool: 'multi', version: '47.0.0' }, + { kind: 'i', type: 'tool', tool: 'child', version, parent }, + { kind: 'l', command: 'child', tool: 'child', version }, + { kind: 'c', alias: 'child', tool: 'child', version, parent }, + ]; + } + + test('an old parent wrapper of the volume is not used', async () => { + const ver = await child.getAsync(VersionService); + // the volume has the child for an older parent, with its wrapper + const old = await wrapperFor('8.0.0', '46.0.0'); + await ver.addInstalled({ + name: 'child', + version: '8.0.0', + parent: { name: 'multi', version: '46.0.0' }, + }); + await fs.rm(linkPath('child'), { force: true }); + await fs.symlink(old, linkPath('child')); + listOf(...childList('8.0.0')); + + await install.setupVolume(); + + // the wrapper for the listed parent is missing, the shim installs it + expect(await lookup(linkPath('child'))).toBe('ENOENT'); + }); + + test('the wrapper of the listed parent is used', async () => { + const ver = await child.getAsync(VersionService); + await wrapperFor('8.1.0', '46.0.0'); + const listed = await wrapperFor('8.1.0', '47.0.0'); + await ver.addInstalled({ + name: 'child', + version: '8.1.0', + parent: { name: 'multi', version: '46.0.0' }, + }); + listOf(...childList('8.1.0')); + + await install.setupVolume(); + + expect(await fs.readlink(linkPath('child'))).toBe(listed); + }); + }); + + test('a link of a version which is not current uses its listed parents, the newest first', async () => { + const pathSvc = await child.getAsync(PathService); + const wrapper = async (parent: string): Promise => { + const file = join( + pathSvc.versionedToolPath('child', '8.2.0'), + parent, + '.wrappers/child', + ); + await fs.mkdir(join(file, '..'), { recursive: true }); + await fs.writeFile(file, ''); + return file; + }; + await wrapper('46.0.0'); + const listed = await wrapper('47.0.0'); + const parent = { name: 'multi', version: '47.0.0' }; + listOf( + { + kind: 'i', + type: 'tool', + tool: 'child', + version: '8.2.0', + parent: { name: 'multi', version: '46.0.0' }, + }, + { kind: 'i', type: 'tool', tool: 'child', version: '8.2.0', parent }, + { kind: 'i', type: 'tool', tool: 'child', version: '8.3.0', parent }, + { kind: 'c', alias: 'child', tool: 'child', version: '8.3.0', parent }, + { kind: 'l', command: 'child', tool: 'child', version: '8.2.0' }, + ); + + await install.setupVolume(); + + expect(await fs.readlink(linkPath('child'))).toBe(listed); + }); + + test('warns about a pointer it cannot remove', async () => { + const remove = vi.spyOn(LinkToolService.prototype, 'removeStalePointer'); + // no wrapper of this version exists, so the pointer is removed + listOf(...multi('45.0.0')); + + await install.setupVolume(); + + expect(remove).toHaveBeenCalledWith('multi', true); + expect(remove).toHaveBeenCalledWith('multi45', true); + }); + + test('clears the initialized markers', async () => { + const pathSvc = await child.getAsync(PathService); + await pathSvc.ensureBasePaths(); + await pathSvc.setInitialized('node'); + listOf(...multi('44.0.0')); + + await install.setupVolume(); + + expect(await pathSvc.isInitialized('node')).toBe(false); + }); + + test('records a version once and installs nothing but jq', async () => { + const ver = await child.getAsync(VersionService); + listOf(...multi('42.0.0')); + const add = vi.spyOn(VersionService.prototype, 'addInstalled'); + const installSpy = vi.spyOn(MultiInstallService.prototype, 'install'); + + await install.setupVolume(); + await install.setupVolume(); + + expect(add).toHaveBeenCalledOnce(); + expect(installSpy).not.toHaveBeenCalled(); + expect( + (await ver.findInstalled('multi')).filter( + (v) => v.version === '42.0.0', + ), + ).toHaveLength(1); + }); + + test('restores jq at once, and git has nothing to restore', async () => { + const jq = vi.spyOn(JqInstallService.prototype, 'install'); + const git = vi.spyOn(GitInstallService.prototype, 'install'); + listOf( + { kind: 'i', type: 'tool', tool: 'git', version: '2.0.0' }, + { kind: 'c', alias: 'git', tool: 'git', version: '2.0.0' }, + { kind: 'i', type: 'tool', tool: 'jq', version: '1.0.0' }, + { kind: 'c', alias: 'jq', tool: 'jq', version: '1.0.0' }, + { kind: 'l', command: 'jq', tool: 'jq', version: '1.0.0' }, + ); + + await install.setupVolume(); + + expect(jq).toHaveBeenCalledExactlyOnceWith('1.0.0'); + expect(git).not.toHaveBeenCalled(); + expect(await pathExists(linkPath('jq'), 'file')).toBe(true); + }); + + test('only warns when jq cannot be restored', async () => { + const err = new Error('install failed'); + vi.spyOn(JqInstallService.prototype, 'install').mockRejectedValueOnce( + err, + ); + listOf( + { kind: 'i', type: 'tool', tool: 'jq', version: '1.1.0' }, + { kind: 'c', alias: 'jq', tool: 'jq', version: '1.1.0' }, + ); + + await expect(install.setupVolume()).resolves.toBeUndefined(); + + expect(logger.warn).toHaveBeenCalledWith( + { err, tool: 'jq' }, + 'cannot restore the tool, the shim retries', + ); + // the list is copied anyway, the shim restores jq on its first call + expect(BuildListService.prototype.copyToVolume).toHaveBeenCalledOnce(); + }); + + test('skips jq without an install service', async () => { + const bare = createContainer(); + bare.bind(InstallToolService).toSelf(); + bare.bind(V1ToolInstallService).toSelf(); + listOf( + { kind: 'i', type: 'tool', tool: 'jq', version: '1.2.0' }, + { kind: 'c', alias: 'jq', tool: 'jq', version: '1.2.0' }, + ); + + await expect( + (await bare.getAsync(InstallToolService)).setupVolume(), + ).resolves.toBeUndefined(); + }); + }); + describe('links', () => { test('a command keeps the version which linked it last', async () => { const pathSvc = await child.getAsync(PathService); @@ -1155,6 +1571,56 @@ describe('cli/install-tool/install-tool.service', () => { expect(initializeTools).not.toHaveBeenCalled(); }); + describe('a child tool with a wrapper for an older parent', () => { + /** + * Installs the child for the parent 50.0.0, which is current, and leaves + * a record and a wrapper for the older parent 49.0.0, like an older + * volume. The pointer of the command is removed. + */ + async function setup(): Promise<{ old: string; selected: string }> { + const pathSvc = await child.getAsync(PathService); + const ver = await child.getAsync(VersionService); + expect(await install.install('multi', '50.0.0')).toBeUndefined(); + expect(await install.install('child', '9.5.0')).toBeUndefined(); + const dir = pathSvc.versionedToolPath('child', '9.5.0'); + const old = join(dir, '49.0.0', '.wrappers/child'); + await fs.mkdir(join(old, '..'), { recursive: true }); + await fs.writeFile(old, ''); + const record = { + name: 'child', + version: '9.5.0', + parent: { name: 'multi', version: '49.0.0' }, + }; + if (!(await ver.isInstalled(record))) { + await ver.addInstalled(record); + } + await fs.rm(linkPath('child'), { force: true }); + return { old, selected: join(dir, '50.0.0', '.wrappers/child') }; + } + + test('installs the version when the wrapper of the current parent is missing', async () => { + const { old, selected } = await setup(); + await fs.rm(join(selected, '../..'), { recursive: true }); + const spy = vi.spyOn(ChildInstallService.prototype, 'install'); + + expect(await install.ensure('child')).toBeUndefined(); + + expect(spy).toHaveBeenCalledExactlyOnceWith('9.5.0'); + expect(await fs.readlink(linkPath('child'))).toBe(selected); + expect(await fs.readlink(linkPath('child'))).not.toBe(old); + }); + + test('points at the wrapper of the current parent without an install', async () => { + const { selected } = await setup(); + const spy = vi.spyOn(ChildInstallService.prototype, 'install'); + + expect(await install.ensure('child')).toBeUndefined(); + + expect(spy).not.toHaveBeenCalled(); + expect(await fs.readlink(linkPath('child'))).toBe(selected); + }); + }); + test('installs the missing parent first', async () => { expect(await install.install('multi', '9.0.0')).toBeUndefined(); expect(await install.install('child', '3.0.0')).toBeUndefined(); diff --git a/src/cli/install-tool/install-tool.service.ts b/src/cli/install-tool/install-tool.service.ts index 74db41884a..4d3a06a76c 100644 --- a/src/cli/install-tool/install-tool.service.ts +++ b/src/cli/install-tool/install-tool.service.ts @@ -5,6 +5,10 @@ import { deleteAsync } from 'del'; import { inject, injectable, multiInject, optional } from 'inversify'; import { initializeTools, prepareTools } from '../prepare-tool/index.ts'; import { + type BuildListCurrent, + type BuildListEntry, + type BuildListInstall, + type BuildListLink, BuildListService, CacheService, EnvService, @@ -37,6 +41,34 @@ import { export const INSTALL_TOOL_TOKEN = Symbol('INSTALL_TOOL_TOKEN'); +/** + * The parent versions the list has for the version a link points at: only the + * parent of the `c` line when it is the current version of the tool, none for + * a tool without a parent. A link to a version which isn't current falls back + * to the parents on the `i` lines of that version, the newest first like + * `VersionService.findParentVersions`. + */ +function listedParents( + entries: readonly BuildListEntry[], + currents: ReadonlyMap, + { tool, version }: BuildListLink, +): string[] { + const current = currents.get(tool); + if (current?.version === version) { + return current.parent ? [current.parent.version] : []; + } + return entries + .flatMap((entry) => + entry.kind === 'i' && + entry.tool === tool && + entry.version === version && + entry.parent + ? [entry.parent.version] + : [], + ) + .toReversed(); +} + @injectable() export class InstallToolService { @inject(V1ToolInstallService) @@ -64,11 +96,14 @@ export class InstallToolService { /** * Runs the install lifecycle of a tool: prepare, initialize, validate, - * install, link and test. Afterwards the oldest files are evicted from the - * download cache when the disk is too full, see `CacheService.evict`. A - * failing eviction is only logged. + * install, link and test. Before the install it installs the current parent + * version again when its files are missing, see `restoreMissingParent`. + * Afterwards the oldest files are evicted from the download cache when the + * disk is too full, see `CacheService.evict`. A failing eviction is only + * logged. * - * @returns an exit code when the tool could not be installed + * @returns an exit code when the tool could not be installed, which can also + * be the one of the parent version which could not be installed again */ async install( tool: string, @@ -147,6 +182,10 @@ export class InstallToolService { logger.info(`Dry run: install tool ${tool} ...`); return; } else { + const res = await this.restoreMissingParent(parent); + if (res) { + return res; + } logger.debug({ tool }, 'install tool'); await toolSvc.install(version); if (!missing) { @@ -189,6 +228,37 @@ export class InstallToolService { } } + /** + * Installs the current parent version of a tool again when its files are + * missing, eg. on a volume set up from the build-time list, as the tools of + * a child, like npm packages, call the parent by its path and not through + * its shim. The link state is cleared afterwards, as the restore sets its + * own. + * + * @returns an exit code when the parent can't be installed + */ + private async restoreMissingParent( + parent: ToolState | null, + ): Promise { + const parentSvc = parent + ? this.toolSvcs.find((t) => t.name === parent.tool.name) + : undefined; + if ( + !parent || + !parentSvc || + !(await this.isMissing(parentSvc, parent.tool.version)) + ) { + return; + } + logger.info( + { tool: parentSvc.name, version: parent.tool.version }, + 'parent tool version missing, installing', + ); + const res = await this.restore(parentSvc, parent.tool.version); + this._link.clear(); + return res; + } + /** * Cleans up after an install: the apt files as root, on a docker build the * tmp files and the caches, then the oldest files are evicted from the @@ -432,7 +502,9 @@ export class InstallToolService { * the pointer of the command is missing or dangling. It never changes which * version any command runs: it recreates the pointer when the per-version * wrapper exists, else it installs the version the command points at again, - * after its parent, and writes the per-version wrappers. After an install + * after its parent, and writes the per-version wrappers. When the version is + * the current one of a tool with a parent, only the wrapper for the parent of + * the current record counts, else any recorded parent does. After an install * it only evicts the download cache, it removes no apt, tmp or cache files, * as it runs inside the command which called the shim. * @@ -453,18 +525,22 @@ export class InstallToolService { } const { name: tool, version } = link.tool; + const toolSvc = this.toolSvcs.find((t) => t.name === tool); if ( await this._link.restorePointer( command, link.tool, - await this.versionSvc.findParentVersions(link.tool), + // a parent version of an older volume must not win over the current one + await this.versionSvc.findSelectedParents( + link.tool, + toolSvc?.alias ?? tool, + ), ) ) { logger.debug({ command, tool, version }, 'pointer restored'); return; } - const toolSvc = this.toolSvcs.find((t) => t.name === tool); if (!toolSvc || toolSvc instanceof V2ToolInstallService) { logger.error({ command, tool }, 'tool cannot be installed again'); return NotSupported; @@ -472,6 +548,109 @@ export class InstallToolService { return await this.restore(toolSvc, version); } + /** + * Sets up an empty or older `/opt/containerbase` from the build-time list of + * the image: the version records, the types of the packages, the current + * versions, the links with their shims and the legacy version files. The + * versions of the image win over the ones installed at runtime, as they are + * recorded last, and only the `c` lines make a version current. Nothing is + * removed, and no tool is installed, the shims install a version on its + * first call, see `ensure`. Only jq is restored at once, as the other tools + * and the shell utils need it early, git is installed by apt and never + * restored. The initialized markers in the temp folder are cleared, as they + * outlive the volume, so the init which follows runs every initialize step + * again. At last the list is copied to the volume, so the next init has + * nothing to do. + */ + async setupVolume(): Promise { + await this.pathSvc.ensureBasePaths(); + await this.pathSvc.clearInitialized(); + + // the whole list first, so a link knows the current parent of its tool + // wherever the `c` line is + const entries = await this._list.read(); + const currents = new Map(); + for (const entry of entries) { + if (entry.kind === 'c') { + currents.set(entry.tool, entry); + } + } + + for (const entry of entries) { + if (entry.kind === 'i') { + await this.replayInstall(entry); + } else if (entry.kind === 'c') { + await this.replayCurrent(entry); + } else { + await this.replayLink(entry, listedParents(entries, currents, entry)); + } + } + + const jqVersion = currents.get('jq')?.version; + const jqSvc = this.toolSvcs.find((t) => t.name === 'jq'); + if (jqVersion && jqSvc && (await this.isMissing(jqSvc, jqVersion))) { + try { + await this.restore(jqSvc, jqVersion); + } catch (err) { + logger.warn( + { err, tool: 'jq' }, + 'cannot restore the tool, the shim retries', + ); + } + } + + await this._list.copyToVolume(); + } + + /** Records a listed install in the databases, and the type of a package. */ + private async replayInstall(entry: BuildListInstall): Promise { + const { tool, version, parent } = entry; + const record = { name: tool, version, ...(parent && { parent }) }; + if (!(await this.versionSvc.isInstalled(record))) { + await this.versionSvc.addInstalled(record); + } + if (entry.type !== 'tool' && !this.toolSvcs.some((t) => t.name === tool)) { + // a package without an install service of its own + await this.versionSvc.setType(tool, entry.type); + } + } + + /** + * Makes a listed version the current one of its tool and writes its legacy + * version file. + */ + private async replayCurrent(entry: BuildListCurrent): Promise { + const { alias, tool, version, parent } = entry; + await this.versionSvc.setCurrent({ + name: alias, + tool: { name: tool, version }, + ...(parent && { parent }), + }); + await this.versionSvc.update(tool, version); + } + + /** + * Records a listed link, writes the shim of the command and points it at + * the wrapper of its version for one of the listed parent versions, when + * that exists, or else removes the pointer, so the shim installs the + * version on its first call. Parent versions recorded on the volume are + * not used, as the image may list another one. + * + * @param parents - the parent versions the list has for the linked version + */ + private async replayLink( + entry: BuildListLink, + parents: readonly string[], + ): Promise { + const { command, tool, version } = entry; + const link = { name: tool, version }; + await this.versionSvc.setLink({ name: command, tool: link }); + await this._link.writeShim(command); + if (!(await this._link.restorePointer(command, link, parents))) { + await this._link.removeStalePointer(command, true); + } + } + /** * Installs the version again, after the current parent version when its * files are missing too, and writes only the per-version wrappers. The @@ -505,16 +684,9 @@ export class InstallToolService { ); return MissingParent; } - const parentSvc = this.toolSvcs.find((t) => t.name === parent!.tool.name); - if (parentSvc && (await this.isMissing(parentSvc, parent.tool.version))) { - logger.info( - { tool: parentSvc.name, version: parent.tool.version }, - 'parent tool version missing, installing', - ); - const res = await this.restore(parentSvc, parent.tool.version); - if (res) { - return res; - } + const res = await this.restoreMissingParent(parent); + if (res) { + return res; } } diff --git a/src/cli/prepare-tool/index.spec.ts b/src/cli/prepare-tool/index.spec.ts index 32169dcfe6..718b280a83 100644 --- a/src/cli/prepare-tool/index.spec.ts +++ b/src/cli/prepare-tool/index.spec.ts @@ -114,6 +114,59 @@ describe('cli/prepare-tool/index', () => { expect(await pathExists(join(links, 'ptr-legacy'))).toBe(false); }); + describe('a child with a wrapper for an older parent', () => { + const child = { name: 'ptr-child', version: '2.0.0' }; + + /** + * Records the child for the parents 49.0.0, with a wrapper, and 50.0.0, + * which is the current one. The pointer of the command is missing. + */ + async function setup(): Promise { + const verSvc = await createContainer().getAsync(VersionService); + const dir = rootPath('opt/containerbase/tools/ptr-child/2.0.0'); + const old = join(dir, '49.0.0/.wrappers'); + await fs.mkdir(old, { recursive: true }); + await fs.writeFile(join(old, 'ptr-child'), ''); + for (const version of ['49.0.0', '50.0.0']) { + const record = { ...child, parent: { name: 'ptr', version } }; + if (!(await verSvc.isInstalled(record))) { + await verSvc.addInstalled(record); + } + } + await verSvc.setLink({ name: 'ptr-child', tool: child }); + await verSvc.setCurrent({ + name: 'ptr-child', + tool: child, + parent: { name: 'ptr', version: '50.0.0' }, + }); + await ensurePaths('opt/containerbase/links'); + const pointer = rootPath('opt/containerbase/links/ptr-child'); + await fs.rm(pointer, { force: true }); + return pointer; + } + + test('init tool all does not point at the old parent', async () => { + const pointer = await setup(); + + expect(await initializeTools(['all'])).toBeUndefined(); + + expect(await pathExists(pointer)).toBe(false); + }); + + test('init tool all points at the wrapper of the current parent', async () => { + const pointer = await setup(); + const wrappers = rootPath( + 'opt/containerbase/tools/ptr-child/2.0.0/50.0.0/.wrappers', + ); + await fs.mkdir(wrappers, { recursive: true }); + await fs.writeFile(join(wrappers, 'ptr-child'), ''); + + expect(await initializeTools(['all'])).toBeUndefined(); + + expect(await fs.readlink(pointer)).toBe(join(wrappers, 'ptr-child')); + }); + }); + test('init tool all only warns when a pointer cannot be written', async () => { await linkCommands('ptr-c'); vi.spyOn(fs, 'symlink').mockRejectedValue(new Error('EROFS')); diff --git a/src/cli/prepare-tool/index.ts b/src/cli/prepare-tool/index.ts index 23a7000d9b..30fbf6565f 100644 --- a/src/cli/prepare-tool/index.ts +++ b/src/cli/prepare-tool/index.ts @@ -128,7 +128,7 @@ async function restorePointers(container: Container): Promise { await linkSvc.restorePointer( name, tool, - await versionSvc.findParentVersions(tool), + await versionSvc.findSelectedParents(tool), ); } catch (err) { logger.warn({ err, command: name }, 'cannot restore the pointer'); diff --git a/src/cli/services/build-list.service.spec.ts b/src/cli/services/build-list.service.spec.ts index c1d9ac8cde..199f5bf733 100644 --- a/src/cli/services/build-list.service.spec.ts +++ b/src/cli/services/build-list.service.spec.ts @@ -241,6 +241,55 @@ describe('cli/services/build-list.service', () => { ]); }); + test('changed compares the list of the image with the copy', async () => { + // no list in the image + expect(await svc.changed()).toBe(false); + await fs.writeFile(pathSvc.volumeToolInstPath, 'i tool node 22.0.0\n'); + expect(await svc.changed()).toBe(false); + + // a new volume + await fs.writeFile(pathSvc.toolInstPath, 'i tool node 22.0.0\n'); + await fs.rm(pathSvc.volumeToolInstPath); + expect(await svc.changed()).toBe(true); + + // an older volume + await fs.writeFile(pathSvc.volumeToolInstPath, 'i tool node 20.0.0\n'); + expect(await svc.changed()).toBe(true); + + // the same list + await fs.writeFile(pathSvc.volumeToolInstPath, 'i tool node 22.0.0\n'); + expect(await svc.changed()).toBe(false); + }); + + test('copyToVolume only writes the copy', async () => { + await fs.writeFile(pathSvc.toolInstPath, 'i tool node 22.0.0\n'); + const write = vi.spyOn(fs, 'writeFile'); + + await svc.copyToVolume(); + + expect(await fs.readFile(pathSvc.volumeToolInstPath, 'utf8')).toBe( + 'i tool node 22.0.0\n', + ); + expect(write).toHaveBeenCalledExactlyOnceWith( + pathSvc.volumeToolInstPath, + 'i tool node 22.0.0\n', + ); + expect(await svc.changed()).toBe(false); + }); + + test('copyToVolume only warns when the copy cannot be written', async () => { + await fs.writeFile(pathSvc.toolInstPath, 'i tool node 22.0.0\n'); + const err = new Error('EROFS'); + vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(err); + + await expect(svc.copyToVolume()).resolves.toBeUndefined(); + + expect(logger.warn).toHaveBeenCalledWith( + { err }, + 'cannot copy the build-time tool list', + ); + }); + describe('an unreadable list', () => { const err = Object.assign(new Error('EACCES'), { code: 'EACCES' }); diff --git a/src/cli/services/build-list.service.ts b/src/cli/services/build-list.service.ts index 79c8ef2dce..634c93c176 100644 --- a/src/cli/services/build-list.service.ts +++ b/src/cli/services/build-list.service.ts @@ -78,6 +78,35 @@ export class BuildListService { .filter((entry) => entry !== null); } + /** + * Whether the image has a list which differs from the copy in + * `/opt/containerbase`, which is the case for a new or an older volume. + * An image without a list never differs. + */ + async changed(): Promise { + const image = await readText(this.pathSvc.toolInstPath); + return ( + image !== '' && + image !== (await readText(this.pathSvc.volumeToolInstPath)) + ); + } + + /** + * Copies the list of the image to `/opt/containerbase`, so the volume knows + * its state. A failure is only logged, the next init tries again. The list + * in `/var/lib/containerbase` is never written. + */ + async copyToVolume(): Promise { + try { + await this.pathSvc.writeFile( + this.pathSvc.volumeToolInstPath, + await readText(this.pathSvc.toolInstPath), + ); + } catch (err) { + logger.warn({ err }, 'cannot copy the build-time tool list'); + } + } + /** * Records an install which is linked, so it replaces an earlier record of * the same version, the current version of the `alias` and the earlier links @@ -189,6 +218,11 @@ async function readMissingAsEmpty(file: string): Promise { } } +/** The text of a list file, empty when it can't be read. */ +function readText(file: string): Promise { + return fs.readFile(file, 'utf8').catch(() => ''); +} + /** One line of the list. */ function formatLine(entry: BuildListEntry): string { if (entry.kind === 'l') { diff --git a/src/cli/services/link-tool.service.spec.ts b/src/cli/services/link-tool.service.spec.ts index d955e1ff8c..3fc64889cc 100644 --- a/src/cli/services/link-tool.service.spec.ts +++ b/src/cli/services/link-tool.service.spec.ts @@ -3,7 +3,7 @@ import { codeBlock } from 'common-tags'; import { beforeAll, describe, expect, test, vi } from 'vitest'; import { ensurePaths, rootPath } from '../../../test/path.ts'; import { createContainer } from '../services/index.ts'; -import { pathExists } from '../utils/index.ts'; +import { logger, pathExists } from '../utils/index.ts'; import { LinkToolService } from './link-tool.service.ts'; /** @@ -424,6 +424,31 @@ describe('cli/services/link-tool.service', async () => { }, ); + test.each(['EROFS', 'EACCES'])( + 'removeStalePointer warns about a pointer which cannot be removed on request: %s', + async (code) => { + const pointer = `${links}/warn-cmd`; + const err = Object.assign(new Error(code), { code }); + const rm = fs.rm; + vi.spyOn(fs, 'rm').mockImplementation((path, options) => + path === pointer ? Promise.reject(err) : rm(path, options), + ); + + await svc.removeStalePointer('warn-cmd'); + expect(logger.warn).not.toHaveBeenCalled(); + expect(logger.debug).toHaveBeenCalledWith( + { err, name: 'warn-cmd' }, + 'cannot remove the pointer', + ); + + await svc.removeStalePointer('warn-cmd', true); + expect(logger.warn).toHaveBeenCalledExactlyOnceWith( + { err, name: 'warn-cmd' }, + 'cannot remove the pointer of the command, the old version stays linked', + ); + }, + ); + test('legacy links fail on other errors removing the pointer', async () => { const pointer = `${links}/broken-cmd`; const rm = fs.rm; diff --git a/src/cli/services/link-tool.service.ts b/src/cli/services/link-tool.service.ts index 392a1a6691..81bb123e7f 100644 --- a/src/cli/services/link-tool.service.ts +++ b/src/cli/services/link-tool.service.ts @@ -242,12 +242,16 @@ export class LinkToolService { } /** - * Removes a pointer a legacy link replaces. A missing pointer is fine, and + * Removes a pointer a legacy link replaces, or which points at a version + * the command doesn't run any more. A missing pointer is fine, and * so is one in a folder which can't be written, eg. when only `bin` is * writable: the link then keeps its full wrapper, which wins over the * pointer, as `bin` isn't a shim any more. + * + * @param warn - log a pointer which can't be removed as a warning, as the + * old version stays linked, instead of at debug level */ - private async removeStalePointer(name: string): Promise { + async removeStalePointer(name: string, warn = false): Promise { try { await fs.rm(this.pointerPath(name), { force: true }); } catch (err) { @@ -255,7 +259,14 @@ export class LinkToolService { if (code !== 'EROFS' && code !== 'EACCES') { throw err; } - logger.debug({ err, name }, 'cannot remove the pointer'); + if (warn) { + logger.warn( + { err, name }, + 'cannot remove the pointer of the command, the old version stays linked', + ); + } else { + logger.debug({ err, name }, 'cannot remove the pointer'); + } } } @@ -288,7 +299,7 @@ export class LinkToolService { * Writes the shim of the command into the global bin folder, replacing * whatever is there, unless it already is the shim. */ - private async writeShim(name: string): Promise { + async writeShim(name: string): Promise { const tgt = join(this.pathSvc.binDir, name); const content = this.shim(name); if ((await readText(tgt)) === content) { diff --git a/src/cli/services/path.service.spec.ts b/src/cli/services/path.service.spec.ts index e88c82f1d1..26ed2e326c 100644 --- a/src/cli/services/path.service.spec.ts +++ b/src/cli/services/path.service.spec.ts @@ -1502,6 +1502,23 @@ describe('cli/services/path.service', () => { expect(await pathSvc.isInitialized('node')).toBe(true); }); + test('clearInitialized: forgets every initialized tool', async () => { + await pathSvc.ensureBasePaths(); + await pathSvc.setInitialized('node'); + await pathSvc.setInitialized('java'); + + await pathSvc.clearInitialized(); + + expect(await pathSvc.isInitialized('node')).toBe(false); + expect(await pathSvc.isInitialized('java')).toBe(false); + }); + + test('clearInitialized: ignores a missing folder', async () => { + vi.spyOn(fs, 'readdir').mockRejectedValueOnce(new Error('ENOENT')); + + await expect(pathSvc.clearInitialized()).resolves.toBeUndefined(); + }); + test('toolPrepare', async () => { expect(pathSvc.toolPreparePath('node')).toBe( rootPath('var/lib/containerbase/tool.prep.d/node'), diff --git a/src/cli/services/path.service.ts b/src/cli/services/path.service.ts index 3919c8469a..3342f91887 100644 --- a/src/cli/services/path.service.ts +++ b/src/cli/services/path.service.ts @@ -839,6 +839,17 @@ export class PathService { await this.setOwner({ path }); } + /** + * Forgets that any tool was initialized in this container, so the next init + * runs every initialize step again. + */ + async clearInitialized(): Promise { + const dir = this._toolInitPath; + for (const file of await fs.readdir(dir).catch(() => [])) { + await fs.rm(join(dir, file), { force: true }); + } + } + /** Marks the tool as prepared and adds it to the list of prepared tools. */ async setPrepared(tool: string): Promise { await fs.writeFile(this.toolPreparePath(tool), ''); diff --git a/src/cli/services/version.service.ts b/src/cli/services/version.service.ts index 0a78c1a11a..8e8c81361f 100644 --- a/src/cli/services/version.service.ts +++ b/src/cli/services/version.service.ts @@ -175,6 +175,27 @@ export class VersionService { return versions; } + /** + * The parent versions whose wrapper may be the pointer of a command of the + * tool version. When it is the current version of the tool and its record + * has a parent, only that parent counts, so a parent version left by an + * older volume is never selected. Else, eg. without a current record, it + * is `findParentVersions`. + * + * @param alias - the name the tool is current as, the tool name by default + */ + async findSelectedParents(tool: Tool, alias = tool.name): Promise { + const current = await this.getCurrent(alias); + if ( + current?.parent && + current.tool.name === tool.name && + current.tool.version === tool.version + ) { + return [current.parent.version]; + } + return await this.findParentVersions(tool); + } + /** * Points a shell wrapper name at a tool version, replacing whatever it * pointed at before. diff --git a/src/usr/local/containerbase/bin/docker-entrypoint.sh b/src/usr/local/containerbase/bin/docker-entrypoint.sh index 3005ca5613..25ca39b6fe 100755 --- a/src/usr/local/containerbase/bin/docker-entrypoint.sh +++ b/src/usr/local/containerbase/bin/docker-entrypoint.sh @@ -37,6 +37,13 @@ elif [[ "${tmp_dir}" == /* && "${tmp_dir}" != *//* && "${tmp_dir}" != */./* && " fi fi +# a volume at /opt/containerbase without the build-time tool list of the image, which is a new +# volume or one of an older image, needs the init too, which sets it up +if [[ "${run_init}" != true && -s /var/lib/containerbase/tool.inst ]] \ + && ! cmp -s /var/lib/containerbase/tool.inst /opt/containerbase/.tool.inst; then + run_init=true +fi + if [[ "${run_init}" == true ]]; then # initialize all prepared tools, also checks and links a configured tmp dir containerbase-cli init tool all