-
Notifications
You must be signed in to change notification settings - Fork 268
/
podman-install.ts
executable file
·520 lines (461 loc) · 17.2 KB
/
podman-install.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/**********************************************************************
* Copyright (C) 2022 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import * as extensionApi from '@podman-desktop/api';
import { promisify } from 'node:util';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { compare } from 'compare-versions';
import * as podmanTool from './podman.json';
import type { InstalledPodman } from './podman-cli';
import { getPodmanInstallation } from './podman-cli';
import { getAssetsFolder } from './util';
import { getDetectionChecks } from './detection-checks';
import { BaseCheck } from './base-check';
import { MacCPUCheck, MacMemoryCheck, MacPodmanInstallCheck, MacVersionCheck } from './macos-checks';
import {
isRootfulMachineInitSupported,
ROOTFUL_MACHINE_INIT_SUPPORTED_KEY,
isUserModeNetworkingSupported,
USER_MODE_NETWORKING_SUPPORTED_KEY,
} from './extension';
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
export function getBundledPodmanVersion(): string {
return podmanTool.version;
}
export interface PodmanInfo {
podmanVersion: string;
lastUpdateCheck: number;
ignoreVersionUpdate?: string;
}
export class PodmanInfoImpl implements PodmanInfo {
constructor(
private podmanInfo: PodmanInfo,
private readonly storagePath: string,
) {
if (!podmanInfo) {
this.podmanInfo = { lastUpdateCheck: 0 } as PodmanInfo;
}
}
set podmanVersion(version: string) {
if (this.podmanInfo.podmanVersion !== version) {
this.podmanInfo.podmanVersion = version;
this.writeInfo().catch((err: unknown) => console.error('Unable to write Podman Version', err));
}
}
get podmanVersion(): string {
return this.podmanInfo.podmanVersion;
}
set lastUpdateCheck(lastCheck: number) {
if (this.podmanInfo.lastUpdateCheck !== lastCheck) {
this.podmanInfo.lastUpdateCheck = lastCheck;
this.writeInfo().catch((err: unknown) => console.error('Unable to write Podman Version', err));
}
}
get lastUpdateCheck(): number {
return this.podmanInfo.lastUpdateCheck;
}
get ignoreVersionUpdate(): string {
return this.podmanInfo.ignoreVersionUpdate;
}
set ignoreVersionUpdate(version: string) {
if (this.podmanInfo.ignoreVersionUpdate !== version) {
this.podmanInfo.ignoreVersionUpdate = version;
this.writeInfo().catch((err: unknown) => console.error('Unable to write Podman Version', err));
}
}
private async writeInfo(): Promise<void> {
try {
const podmanInfoPath = path.resolve(this.storagePath, 'podman-ext.json');
await writeFile(podmanInfoPath, JSON.stringify(this.podmanInfo));
} catch (err) {
console.error(err);
}
}
}
interface Installer {
getPreflightChecks(): extensionApi.InstallCheck[] | undefined;
getUpdatePreflightChecks(): extensionApi.InstallCheck[] | undefined;
install(): Promise<boolean>;
requireUpdate(installedVersion: string): boolean;
update(): Promise<boolean>;
}
interface UpdateCheck {
hasUpdate: boolean;
installedVersion: string;
bundledVersion: string;
}
export class PodmanInstall {
private podmanInfo: PodmanInfo;
private installers = new Map<NodeJS.Platform, Installer>();
constructor(private readonly storagePath: string) {
this.installers.set('win32', new WinInstaller());
this.installers.set('darwin', new MacOSInstaller());
}
public async doInstallPodman(provider: extensionApi.Provider): Promise<void> {
const dialogResult = await extensionApi.window.showInformationMessage(
`Podman is not installed on this system, would you like to install Podman ${getBundledPodmanVersion()}?`,
'Yes',
'No',
);
if (dialogResult === 'Yes') {
await this.installBundledPodman();
const newInstalledPodman = await getPodmanInstallation();
// write podman version
if (newInstalledPodman) {
this.podmanInfo.podmanVersion = newInstalledPodman.version;
extensionApi.context.setValue(
ROOTFUL_MACHINE_INIT_SUPPORTED_KEY,
isRootfulMachineInitSupported(newInstalledPodman.version),
);
extensionApi.context.setValue(
USER_MODE_NETWORKING_SUPPORTED_KEY,
isUserModeNetworkingSupported(newInstalledPodman.version),
);
}
// update detections checks
provider.updateDetectionChecks(getDetectionChecks(newInstalledPodman));
} else {
return; // exiting as without podman this extension is useless
}
}
public async checkForUpdate(installedPodman: InstalledPodman | undefined): Promise<UpdateCheck> {
const podmanInfoRaw = await this.getLastRunInfo();
this.podmanInfo = new PodmanInfoImpl(podmanInfoRaw, this.storagePath);
let installedVersion = this.podmanInfo.podmanVersion;
if (!installedPodman) {
return { installedVersion: undefined, hasUpdate: false, bundledVersion: undefined };
} else if (this.podmanInfo.podmanVersion !== installedPodman.version) {
installedVersion = installedPodman.version;
}
const installer = this.getInstaller();
const bundledVersion = getBundledPodmanVersion();
if (installer?.requireUpdate(installedVersion) && this.podmanInfo.ignoreVersionUpdate !== bundledVersion) {
return { installedVersion, hasUpdate: true, bundledVersion };
}
return { installedVersion, hasUpdate: false, bundledVersion };
}
public async performUpdate(
provider: extensionApi.Provider,
installedPodman: InstalledPodman | undefined,
): Promise<void> {
const updateInfo = await this.checkForUpdate(installedPodman);
if (updateInfo.hasUpdate) {
const answer = await extensionApi.window.showInformationMessage(
`You have Podman ${updateInfo.installedVersion}.\nDo you want to update to ${updateInfo.bundledVersion}?`,
'Yes',
'No',
'Ignore',
);
if (answer === 'Yes') {
await this.getInstaller().update();
this.podmanInfo.podmanVersion = updateInfo.bundledVersion;
provider.updateDetectionChecks(getDetectionChecks(installedPodman));
provider.updateVersion(updateInfo.bundledVersion);
this.podmanInfo.ignoreVersionUpdate = undefined;
extensionApi.context.setValue(
ROOTFUL_MACHINE_INIT_SUPPORTED_KEY,
isRootfulMachineInitSupported(updateInfo.bundledVersion),
);
extensionApi.context.setValue(
USER_MODE_NETWORKING_SUPPORTED_KEY,
isUserModeNetworkingSupported(updateInfo.bundledVersion),
);
} else if (answer === 'Ignore') {
this.podmanInfo.ignoreVersionUpdate = updateInfo.bundledVersion;
}
}
}
getInstallChecks(): extensionApi.InstallCheck[] | undefined {
const installer = this.getInstaller();
if (installer) {
return installer.getPreflightChecks();
}
return undefined;
}
getUpdatePreflightChecks(): extensionApi.InstallCheck[] | undefined {
const installer = this.getInstaller();
if (installer) {
return installer.getUpdatePreflightChecks();
}
return undefined;
}
isAbleToInstall(): boolean {
return this.installers.has(os.platform());
}
private getInstaller(): Installer | undefined {
return this.installers.get(os.platform());
}
private async installBundledPodman(): Promise<boolean> {
const installer = this.getInstaller();
if (installer) {
return installer.install();
}
return false;
}
async getLastRunInfo(): Promise<PodmanInfo | undefined> {
const podmanInfoPath = path.resolve(this.storagePath, 'podman-ext.json');
if (!fs.existsSync(this.storagePath)) {
await promisify(fs.mkdir)(this.storagePath);
}
if (!fs.existsSync(podmanInfoPath)) {
return undefined;
}
try {
const infoBuffer = await readFile(podmanInfoPath);
return JSON.parse(infoBuffer.toString('utf8'));
} catch (err) {
console.error(err);
}
return undefined;
}
}
abstract class BaseInstaller implements Installer {
abstract install(): Promise<boolean>;
abstract update(): Promise<boolean>;
abstract getUpdatePreflightChecks(): extensionApi.InstallCheck[];
abstract getPreflightChecks(): extensionApi.InstallCheck[];
requireUpdate(installedVersion: string): boolean {
return compare(installedVersion, getBundledPodmanVersion(), '<');
}
}
export class WinInstaller extends BaseInstaller {
getUpdatePreflightChecks(): extensionApi.InstallCheck[] {
return [];
}
getPreflightChecks(): extensionApi.InstallCheck[] {
return [
new WinBitCheck(),
new WinVersionCheck(),
new WinMemoryCheck(),
new VirtualMachinePlatformCheck(),
new WSL2Check(),
];
}
update(): Promise<boolean> {
return this.install();
}
install(): Promise<boolean> {
return extensionApi.window.withProgress({ location: extensionApi.ProgressLocation.APP_ICON }, async progress => {
progress.report({ increment: 5 });
const setupPath = path.resolve(getAssetsFolder(), `podman-${podmanTool.version}-setup.exe`);
try {
if (fs.existsSync(setupPath)) {
try {
await extensionApi.process.exec(setupPath, ['/install', '/norestart']);
progress.report({ increment: 80 });
extensionApi.window.showNotification({ body: 'Podman is successfully installed.' });
} catch (err) {
//check if user cancelled installation see https://learn.microsoft.com/en-us/previous-versions//aa368542(v=vs.85)
if ((err as extensionApi.RunError) && err.exitCode !== 1602 && err.exitCode !== 0) {
throw new Error(err.message);
}
}
return true;
} else {
throw new Error(`Can't find Podman setup package! Path: ${setupPath} doesn't exists.`);
}
} catch (err) {
console.error('Error during install!');
console.error(err);
await extensionApi.window.showErrorMessage('Unexpected error, during Podman installation: ' + err, 'OK');
return false;
} finally {
progress.report({ increment: -1 });
}
});
}
}
class MacOSInstaller extends BaseInstaller {
install(): Promise<boolean> {
return extensionApi.window.withProgress({ location: extensionApi.ProgressLocation.APP_ICON }, async progress => {
progress.report({ increment: 5 });
const pkgArch = process.arch === 'arm64' ? 'aarch64' : 'amd64';
const pkgPath = path.resolve(getAssetsFolder(), `podman-installer-macos-${pkgArch}-v${podmanTool.version}.pkg`);
try {
if (fs.existsSync(pkgPath)) {
try {
await extensionApi.process.exec('open', [pkgPath, '-W']);
} catch (err) {
throw new Error((err as extensionApi.RunError).stderr);
}
progress.report({ increment: 80 });
// we cannot rely on exit code, as installer could be closed and it return '0' exit code
// so just check that podman bin file exist.
if (fs.existsSync('/opt/podman/bin/podman')) {
extensionApi.window.showNotification({ body: 'Podman is successfully installed.' });
return true;
} else {
return false;
}
} else {
throw new Error(`Can't find Podman package! Path: ${pkgPath} doesn't exists.`);
}
} catch (err) {
console.error('Error during install!');
console.error(err);
await extensionApi.window.showErrorMessage('Unexpected error, during Podman installation: ' + err, 'OK');
return false;
}
});
}
update(): Promise<boolean> {
return this.install();
}
getPreflightChecks(): extensionApi.InstallCheck[] {
return [new MacCPUCheck(), new MacMemoryCheck(), new MacVersionCheck()];
}
getUpdatePreflightChecks(): extensionApi.InstallCheck[] {
return [new MacPodmanInstallCheck()];
}
}
class WinBitCheck extends BaseCheck {
title = 'Windows 64bit';
private ARCH_X64 = 'x64';
private ARCH_ARM = 'arm64';
async execute(): Promise<extensionApi.CheckResult> {
const currentArch = process.arch;
if (this.ARCH_X64 === currentArch || this.ARCH_ARM === currentArch) {
return this.createSuccessfulResult();
} else {
return this.createFailureResult(
'WSL2 works only on 64bit OS.',
'https://docs.microsoft.com/en-us/windows/wsl/install-manual#step-2---check-requirements-for-running-wsl-2',
);
}
}
}
class WinVersionCheck extends BaseCheck {
title = 'Windows Version';
private MIN_BUILD = 18362;
async execute(): Promise<extensionApi.CheckResult> {
const winRelease = os.release();
if (winRelease.startsWith('10.0.')) {
const splitRelease = winRelease.split('.');
const winBuild = splitRelease[2];
if (Number.parseInt(winBuild) >= this.MIN_BUILD) {
return { successful: true };
} else {
return this.createFailureResult(
'To be able to run WSL2 you need Windows 10 Build 18362 or later.',
'WSL2 Install Manual',
'https://docs.microsoft.com/en-us/windows/wsl/install-manual#step-2---check-requirements-for-running-wsl-2',
);
}
} else {
return this.createFailureResult(
'WSL2 works only on Windows 10 and newest OS',
'WSL2 Install Manual',
'https://docs.microsoft.com/en-us/windows/wsl/install-manual#step-2---check-requirements-for-running-wsl-2',
);
}
}
}
class WinMemoryCheck extends BaseCheck {
title = 'RAM';
private REQUIRED_MEM = 6 * 1024 * 1024 * 1024; // 6Gb
async execute(): Promise<extensionApi.CheckResult> {
const totalMem = os.totalmem();
if (this.REQUIRED_MEM <= totalMem) {
return this.createSuccessfulResult();
} else {
return this.createFailureResult('You need at least 6GB to run Podman.');
}
}
}
class VirtualMachinePlatformCheck extends BaseCheck {
title = 'Virtual Machine Platform Enabled';
async execute(): Promise<extensionApi.CheckResult> {
try {
// set CurrentUICulture to force output in english
const { stdout: res } = await extensionApi.process.exec('powershell.exe', [
'(Get-WmiObject -Query "Select * from Win32_OptionalFeature where InstallState = \'1\'").Name | select-string VirtualMachinePlatform',
]);
if (res.indexOf('VirtualMachinePlatform') >= 0) {
return this.createSuccessfulResult();
}
} catch (err) {
// ignore error, this means that VirtualMachinePlatform not enabled
}
return this.createFailureResult(
'Virtual Machine Platform should be enabled to be able to run Podman.',
'Enable Virtual Machine Platform',
'https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-3---enable-virtual-machine-feature',
);
}
}
class WSL2Check extends BaseCheck {
title = 'WSL2 Installed';
async execute(): Promise<extensionApi.CheckResult> {
try {
const isAdmin = await this.isUserAdmin();
const isWSL = await this.isWSLPresent();
if (!isWSL) {
if (isAdmin) {
return this.createFailureResult(
'WSL2 is not installed. Call "wsl --install --no-distribution" in a terminal.',
'Install WSL',
'https://learn.microsoft.com/en-us/windows/wsl/install',
);
} else {
return this.createFailureResult(
'WSL2 is not installed or you do not have permissions to run WSL2. Contact your Administrator to setup WSL2.',
'More info',
'https://learn.microsoft.com/en-us/windows/wsl/install',
);
}
}
} catch (err) {
return this.createFailureResult(
'Could not detect WSL2',
'Install WSL',
'https://learn.microsoft.com/en-us/windows/wsl/install',
);
}
return this.createSuccessfulResult();
}
private normalizeOutput(out: string): string {
// this is workaround, wsl2 some time send output in utf16le, but we treat that as utf8,
// this code just eliminate every 'empty' character
let str = '';
for (let i = 0; i < out.length; i++) {
if (out.charCodeAt(i) !== 0) {
str += out.charAt(i);
}
}
return str;
}
private async isUserAdmin(): Promise<boolean> {
const { stdout: res } = await extensionApi.process.exec('powershell.exe', [
'$null -ne (whoami /groups /fo csv | ConvertFrom-Csv | Where-Object {$_.SID -eq "S-1-5-32-544"})',
]);
return res.trim() === 'True';
}
private async isWSLPresent(): Promise<boolean> {
try {
const { stdout: res } = await extensionApi.process.exec('wsl', ['--set-default-version', '2'], {
env: { WSL_UTF8: '1' },
});
const output = this.normalizeOutput(res);
return !!output;
} catch (error) {
return false;
}
}
}