-
Notifications
You must be signed in to change notification settings - Fork 268
/
index.ts
2059 lines (1829 loc) · 74.3 KB
/
index.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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* Copyright (C) 2022-2023 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
***********************************************************************/
/**
* @module preload
*/
import * as os from 'node:os';
import * as path from 'path';
import type * as containerDesktopAPI from '@podman-desktop/api';
import { CommandRegistry } from './command-registry.js';
import { ContainerProviderRegistry } from './container-registry.js';
import { ExtensionLoader } from './extension-loader.js';
import { TrayMenuRegistry } from './tray-menu-registry.js';
import { ProviderRegistry } from './provider-registry.js';
import type { IConfigurationPropertyRecordedSchema } from './configuration-registry.js';
import { ConfigurationRegistry } from './configuration-registry.js';
import { TerminalInit } from './terminal-init.js';
import { ImageRegistry } from './image-registry.js';
import { EventEmitter } from 'node:events';
import type {
PreflightCheckEvent,
PreflightChecksCallback,
ProviderContainerConnectionInfo,
ProviderInfo,
ProviderKubernetesConnectionInfo,
} from './api/provider-info.js';
import type { WebContents } from 'electron';
import { app, ipcMain, BrowserWindow, shell, clipboard } from 'electron';
import type {
ContainerCreateOptions,
ContainerInfo,
SimpleContainerInfo,
VolumeCreateOptions,
} from './api/container-info.js';
import type { ImageInfo } from './api/image-info.js';
import type { PullEvent } from './api/pull-event.js';
import type { ExtensionInfo } from './api/extension-info.js';
import type { ImageInspectInfo } from './api/image-inspect-info.js';
import type { TrayMenu } from '../tray-menu.js';
import { getFreePort, getFreePortRange } from './util/port.js';
import { isLinux, isMac } from '../util.js';
import type { MessageBoxOptions, MessageBoxReturnValue } from './message-box.js';
import { MessageBox } from './message-box.js';
import { ProgressImpl } from './progress-impl.js';
import type { ContributionInfo } from './api/contribution-info.js';
import { ContributionManager } from './contribution-manager.js';
import { DockerDesktopInstallation } from './docker-extension/docker-desktop-installation.js';
import { DockerPluginAdapter } from './docker-extension/docker-plugin-adapter.js';
import { PAGE_EVENT_TYPE, Telemetry } from './telemetry/telemetry.js';
import { StatusBarRegistry } from './statusbar/statusbar-registry.js';
import type { StatusBarEntryDescriptor } from './statusbar/statusbar-registry.js';
import type { IpcMainInvokeEvent } from 'electron/main';
import type { ContainerInspectInfo } from './api/container-inspect-info.js';
import type { HistoryInfo } from './api/history-info.js';
import type { PodInfo, PodInspectInfo } from './api/pod-info.js';
import type { VolumeInspectInfo, VolumeListInfo } from './api/volume-info.js';
import type { ContainerStatsInfo } from './api/container-stats-info.js';
import type {
PlayKubeInfo,
PodCreateOptions,
ContainerCreateOptions as PodmanContainerCreateOptions,
} from './dockerode/libpod-dockerode.js';
import type Dockerode from 'dockerode';
import { AutostartEngine } from './autostart-engine.js';
import { CloseBehavior } from './close-behavior.js';
import { TrayIconColor } from './tray-icon-color.js';
import { KubernetesClient } from './kubernetes-client.js';
import type { V1Pod, V1ConfigMap, V1NamespaceList, V1PodList, V1Service, V1Ingress } from '@kubernetes/client-node';
import type { V1Route } from './api/openshift-types.js';
import type { NetworkInspectInfo } from './api/network-info.js';
import { FilesystemMonitoring } from './filesystem-monitoring.js';
import { Certificates } from './certificates.js';
import { Proxy } from './proxy.js';
import { EditorInit } from './editor-init.js';
import { WelcomeInit } from './welcome/welcome-init.js';
import { ExtensionInstaller } from './install/extension-installer.js';
import { InputQuickPickRegistry } from './input-quickpick/input-quickpick-registry.js';
import type { Menu } from '/@/plugin/menu-registry.js';
import { MenuRegistry } from '/@/plugin/menu-registry.js';
import { CancellationTokenRegistry } from './cancellation-token-registry.js';
import type { UpdateCheckResult } from 'electron-updater';
import { autoUpdater } from 'electron-updater';
import type { ApiSenderType } from './api.js';
import type { AuthenticationProviderInfo } from './authentication.js';
import { AuthenticationImpl } from './authentication.js';
import checkDiskSpacePkg from 'check-disk-space';
// workaround for ESM
const checkDiskSpace: (path: string) => Promise<{ free: number }> = checkDiskSpacePkg as unknown as (
path: string,
) => Promise<{ free: number }>;
import { TaskManager } from '/@/plugin/task-manager.js';
import { Featured } from './featured/featured.js';
import type { FeaturedExtension } from './featured/featured-api.js';
import { ExtensionsCatalog } from './extensions-catalog/extensions-catalog.js';
import { securityRestrictionCurrentHandler } from '../security-restrictions-handler.js';
import { ExtensionsUpdater } from './extensions-updater/extensions-updater.js';
import type { CatalogExtension } from './extensions-catalog/extensions-catalog-api.js';
import { IconRegistry } from './icon-registry.js';
import type { IconInfo } from './api/icon-info.js';
import { Directories } from './directories.js';
import { CustomPickRegistry } from './custompick/custompick-registry.js';
import { ViewRegistry } from './view-registry.js';
import type { ViewInfoUI } from './api/view-info.js';
import { Context } from './context/context.js';
import { OnboardingRegistry } from './onboarding-registry.js';
import type { OnboardingInfo, OnboardingStatus } from './api/onboarding.js';
import { Exec } from './util/exec.js';
import { KubeGeneratorRegistry } from '/@/plugin/kube-generator-registry.js';
import type {
KubernetesGeneratorSelector,
GenerateKubeResult,
KubernetesGeneratorArgument,
} from '/@/plugin/kube-generator-registry.js';
import type { KubernetesGeneratorInfo } from '/@/plugin/api/KubernetesGeneratorInfo.js';
import type { CommandInfo } from './api/command-info.js';
import { CliToolRegistry } from './cli-tool-registry.js';
import type { CliToolInfo } from './api/cli-tool-info.js';
import type { NotificationCard, NotificationCardOptions } from './api/notification.js';
import { NotificationRegistry } from './notification-registry.js';
import { ImageCheckerImpl } from './image-checker.js';
import type { ImageCheckerInfo } from './api/image-checker-info.js';
type LogType = 'log' | 'warn' | 'trace' | 'debug' | 'error';
export const UPDATER_UPDATE_AVAILABLE_ICON = 'fa fa-exclamation-triangle';
export interface LoggerWithEnd extends containerDesktopAPI.Logger {
// when task is finished, this function is called
onEnd: () => void;
}
export class PluginSystem {
// ready is when we've finished to initialize extension system
private isReady = false;
// ready when all extensions have been started
private isExtensionsStarted = false;
// notified when UI is dom-ready
private uiReady = false;
// true if the application is quitting
private isQuitting = false;
// The yet to be init ExtensionLoader
private extensionLoader!: ExtensionLoader;
private validExtList!: ExtensionInfo[];
constructor(private trayMenu: TrayMenu) {
app.on('before-quit', () => {
this.isQuitting = true;
});
}
getWebContentsSender(): WebContents {
const window = BrowserWindow.getAllWindows().find(w => !w.isDestroyed());
if (!window) {
throw new Error('Unable to find the main window');
}
return window.webContents;
}
// encode the error to be sent over IPC
// this is needed because on the client it will display
// a generic error message 'Error invoking remote method' and
// it's not useful for end user
encodeIpcError(e: unknown) {
let builtError;
if (e instanceof Error) {
builtError = { name: e.name, message: e.message, extra: { ...e } };
} else {
builtError = { message: e };
}
return builtError;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ipcHandle(channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<void> | any) {
ipcMain.handle(channel, async (...args) => {
try {
return { result: await Promise.resolve(listener(...args)) };
} catch (e) {
return { error: this.encodeIpcError(e) };
}
});
}
// Create an Error to access stack trace
// Match a regex for the file name and return it
// return nothing if file name not found
async getExtName() {
//Create an error for its stack property
const stack = new Error().stack;
//Create a map for extension path => extension name
const extensions: Map<string, string> = new Map();
//Check if index.ts private member extensionLoader initialized
//If it is grab listExtensions()
if (!this.extensionLoader) return;
const currentExtList = await this.extensionLoader.listExtensions();
//Only loop through if list of extensions is different than last time
if (this.validExtList !== currentExtList) {
this.validExtList = currentExtList;
//start setting path => name
this.validExtList.forEach((extInfo: ExtensionInfo) => {
extensions.set(extInfo.path, extInfo.name);
});
}
if (extensions.size > 0 && stack) {
let toAppend = '';
extensions.forEach((name, extPath) => {
extPath = path.normalize(extPath);
if (stack.includes(extPath)) toAppend = name;
});
if (toAppend !== '') return `[${toAppend}]`;
}
}
// log locally and also send it to the renderer process
// so client can see logs in the developer console
redirectConsole(logType: LogType): void {
// keep original method
const originalConsoleMethod = console[logType];
console[logType] = (...args) => {
this.getExtName()
.then(extName => {
if (extName) args.unshift(extName);
// still display as before by invoking original method
originalConsoleMethod(...args);
// but also send the content remotely
if (!this.isQuitting) {
try {
this.getWebContentsSender().send('console:output', logType, ...args);
} catch (err) {
originalConsoleMethod(err);
}
}
})
.catch((err: unknown) => {
console.error('Error in redirectConsole', err);
});
};
}
// setup pipe/redirect for console.log, console.warn, console.trace, console.debug, console.error
redirectLogging() {
const logTypes: LogType[] = ['log', 'warn', 'trace', 'debug', 'error'];
logTypes.forEach(logType => this.redirectConsole(logType));
}
getApiSender(webContents: WebContents): ApiSenderType {
const queuedEvents: { channel: string; data: string }[] = [];
const flushQueuedEvents = () => {
// flush queued events ?
if (this.uiReady && this.isReady && queuedEvents.length > 0) {
console.log(`Delayed startup, flushing ${queuedEvents.length} events`);
queuedEvents.forEach(({ channel, data }) => {
webContents.send('api-sender', channel, data);
});
queuedEvents.length = 0;
}
};
webContents.on('dom-ready', () => {
console.log('PluginSystem: received dom-ready event from the UI');
this.uiReady = true;
flushQueuedEvents();
});
const eventEmitter = new EventEmitter();
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
send: (channel: string, data: any) => {
// send only when the UI is ready
if (this.uiReady && this.isReady) {
flushQueuedEvents();
webContents.send('api-sender', channel, data);
} else {
// add to the queue
queuedEvents.push({ channel, data });
}
eventEmitter.emit(channel, data);
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
receive: (channel: string, func: any) => {
eventEmitter.on(channel, data => {
func(data);
});
},
};
}
async setupSecurityRestrictionsOnLinks(messageBox: MessageBox) {
// external URLs should be validated by the user
securityRestrictionCurrentHandler.handler = async (url: string) => {
if (!url) {
return false;
}
// if url is a known domain, open it directly
const urlObject = new URL(url);
const validDomains = ['podman-desktop.io', 'podman.io'];
const skipConfirmationUrl = validDomains.some(
domain => urlObject.hostname.endsWith(domain) || urlObject.hostname === domain,
);
if (skipConfirmationUrl) {
await shell.openExternal(url);
return true;
}
const result = await messageBox.showMessageBox({
title: 'Open External Website',
message: 'Are you sure you want to open the external website ?',
detail: url,
type: 'question',
buttons: ['Yes', 'Copy link', 'Cancel'],
cancelId: 2,
});
if (result.response === 0) {
// open externally the URL
await shell.openExternal(url);
return true;
} else if (result.response === 1) {
// copy to clipboard
clipboard.writeText(url);
}
return false;
};
}
// initialize extension loader mechanism
async initExtensions(): Promise<ExtensionLoader> {
this.isReady = false;
this.uiReady = false;
this.ipcHandle('extension-system:isReady', async (): Promise<boolean> => {
return this.isReady;
});
this.ipcHandle('extension-system:isExtensionsStarted', async (): Promise<boolean> => {
return this.isExtensionsStarted;
});
// redirect main process logs to the extension loader
this.redirectLogging();
// init api sender
const apiSender = this.getApiSender(this.getWebContentsSender());
const iconRegistry = new IconRegistry(apiSender);
const directories = new Directories();
const configurationRegistry = new ConfigurationRegistry(apiSender, directories);
configurationRegistry.init();
const proxy = new Proxy(configurationRegistry);
await proxy.init();
const telemetry = new Telemetry(configurationRegistry, proxy);
await telemetry.init();
const exec = new Exec(proxy);
const commandRegistry = new CommandRegistry(apiSender, telemetry);
const menuRegistry = new MenuRegistry(commandRegistry);
const kubeGeneratorRegistry = new KubeGeneratorRegistry();
const certificates = new Certificates();
await certificates.init();
const imageRegistry = new ImageRegistry(apiSender, telemetry, certificates, proxy);
const viewRegistry = new ViewRegistry();
const context = new Context(apiSender);
const containerProviderRegistry = new ContainerProviderRegistry(apiSender, imageRegistry, telemetry);
const cancellationTokenRegistry = new CancellationTokenRegistry();
const providerRegistry = new ProviderRegistry(apiSender, containerProviderRegistry, telemetry);
const trayMenuRegistry = new TrayMenuRegistry(this.trayMenu, commandRegistry, providerRegistry, telemetry);
const statusBarRegistry = new StatusBarRegistry(apiSender);
const inputQuickPickRegistry = new InputQuickPickRegistry(apiSender);
const fileSystemMonitoring = new FilesystemMonitoring();
const customPickRegistry = new CustomPickRegistry(apiSender);
const onboardingRegistry = new OnboardingRegistry(configurationRegistry, context);
const notificationRegistry = new NotificationRegistry(apiSender);
const kubernetesClient = new KubernetesClient(apiSender, configurationRegistry, fileSystemMonitoring, telemetry);
await kubernetesClient.init();
const closeBehaviorConfiguration = new CloseBehavior(configurationRegistry);
await closeBehaviorConfiguration.init();
// Don't show the tray icon options on Mac
if (!isMac()) {
const trayIconColor = new TrayIconColor(configurationRegistry, providerRegistry);
await trayIconColor.init();
}
kubeGeneratorRegistry.registerDefaultKubeGenerator({
name: 'PodmanKube',
types: ['Compose', 'Container', 'Pod'],
generate: async (kubernetesGeneratorArguments: KubernetesGeneratorArgument[]) => {
const results: string[] = await Promise.all(
kubernetesGeneratorArguments.map(argument => {
if (argument.containers)
return containerProviderRegistry.generatePodmanKube(argument.engineId, argument.containers);
else if (argument.compose)
return containerProviderRegistry.generatePodmanKube(argument.engineId, argument.compose);
else if (argument.pods)
return containerProviderRegistry.generatePodmanKube(argument.engineId, argument.pods);
else throw new Error('Either containers, compose or pods property must be defined.');
}),
);
return {
yaml: results.join('\n---\n'),
};
},
});
const autoStartEngine = new AutostartEngine(configurationRegistry, providerRegistry);
providerRegistry.registerAutostartEngine(autoStartEngine);
providerRegistry.addProviderListener((name: string, providerInfo: ProviderInfo) => {
if (name === 'provider:update-status') {
apiSender.send('provider:update-status', providerInfo.name);
}
});
statusBarRegistry.setEntry('help', false, 0, undefined, 'Help', 'fa fa-question-circle', true, 'help', undefined);
statusBarRegistry.setEntry(
'tasks',
false,
0,
undefined,
'Tasks',
'fa fa-bell',
true,
'show-task-manager',
undefined,
);
statusBarRegistry.setEntry(
'troubleshooting',
false,
0,
undefined,
'Troubleshooting',
'fa fa-lightbulb',
true,
'troubleshooting',
undefined,
);
commandRegistry.registerCommand('show-task-manager', () => {
apiSender.send('toggle-task-manager', '');
});
statusBarRegistry.setEntry(
'feedback',
false,
0,
undefined,
'Share your feedback',
'fa fa-comment',
true,
'feedback',
undefined,
);
// Get the current version of our application
const currentVersion = `v${app.getVersion()}`;
// Add version entry to the status bar
const defaultVersionEntry = () => {
statusBarRegistry.setEntry(
'version',
false,
0,
currentVersion,
`Using version ${currentVersion}`,
undefined,
true,
'version',
undefined,
);
};
defaultVersionEntry();
// Show a "No update available" only for macOS and Windows users and on production builds
let detailMessage: string;
if (!isLinux() && import.meta.env.PROD) {
detailMessage = 'No update available';
}
// Register command 'version' that will display the current version and say that no update is available.
// Only show the "no update available" command for macOS and Windows users, not linux users.
commandRegistry.registerCommand('version', async () => {
await messageBox.showMessageBox({
type: 'info',
title: 'Version',
message: `Using version ${currentVersion}`,
detail: detailMessage,
});
});
// Only check on production builds for Windows and macOS users
if (import.meta.env.PROD && !isLinux()) {
// disable auto download
autoUpdater.autoDownload = false;
let updateInProgress = false;
let updateAlreadyDownloaded = false;
// setup the event listeners
autoUpdater.on('update-available', () => {
updateInProgress = false;
updateAlreadyDownloaded = false;
// Update the 'version' entry in the status bar to show that an update is available
// this uses setEntry to update the existing entry
statusBarRegistry.setEntry(
'version',
false,
0,
currentVersion,
'Update available',
UPDATER_UPDATE_AVAILABLE_ICON,
true,
'update',
undefined,
);
});
autoUpdater.on('update-not-available', () => {
updateInProgress = false;
updateAlreadyDownloaded = false;
// Update the 'version' entry in the status bar to show that no update is available
defaultVersionEntry();
});
autoUpdater.on('update-downloaded', () => {
updateAlreadyDownloaded = true;
updateInProgress = false;
messageBox
.showMessageBox({
title: 'Update Downloaded',
message: 'Update downloaded, Do you want to restart Podman Desktop ?',
cancelId: 1,
type: 'info',
buttons: ['Restart', 'Cancel'],
})
.then(result => {
if (result.response === 0) {
setImmediate(() => autoUpdater.quitAndInstall());
}
})
.catch((error: unknown) => {
console.error('unable to show message box', error);
});
});
autoUpdater.on('error', error => {
updateInProgress = false;
// local build not pushed to GitHub so prevent any 'update'
if (error?.message?.includes('No published versions on GitHub')) {
console.log('Cannot check for updates, no published versions on GitHub');
defaultVersionEntry();
return;
}
console.error('unable to check for updates', error);
});
// check for updates now
let updateCheckResult: UpdateCheckResult | null;
try {
updateCheckResult = await autoUpdater.checkForUpdates();
} catch (error) {
console.error('unable to check for updates', error);
}
// Create an interval to check for updates every 12 hours
setInterval(
() => {
autoUpdater
.checkForUpdates()
.then(result => (updateCheckResult = result))
.catch((error: unknown) => {
console.log('unable to check for updates', error);
});
},
1000 * 60 * 60 * 12,
);
// Update will create a standard "autoUpdater" dialog / update process
commandRegistry.registerCommand('update', async () => {
if (updateAlreadyDownloaded) {
const result = await messageBox.showMessageBox({
type: 'info',
title: 'Update',
message: 'There is already an update downloaded. Please Restart Podman Desktop.',
cancelId: 1,
buttons: ['Restart', 'Cancel'],
});
if (result.response === 0) {
setImmediate(() => autoUpdater.quitAndInstall());
}
return;
}
if (updateInProgress) {
await messageBox.showMessageBox({
type: 'info',
title: 'Update',
message: 'There is already an update in progress. Please wait until it is downloaded',
buttons: ['OK'],
});
return;
}
// Get the version of the update
const updateVersion = updateCheckResult?.updateInfo.version ? `v${updateCheckResult?.updateInfo.version}` : '';
const result = await messageBox.showMessageBox({
type: 'info',
title: 'Update Available',
message: `A new version ${updateVersion} of Podman Desktop is available. Do you want to update your current version ${currentVersion}?`,
buttons: ['Update', 'Cancel'],
cancelId: 1,
});
if (result.response === 0) {
updateInProgress = true;
updateAlreadyDownloaded = false;
// Download update and try / catch it and create a dialog if it fails
try {
await autoUpdater.downloadUpdate();
} catch (error) {
console.error('Update error: ', error);
await messageBox.showMessageBox({
type: 'error',
title: 'Update Failed',
message: `An error occurred while trying to update to version ${updateVersion}. See the developer console for more information.`,
buttons: ['OK'],
});
}
}
});
}
commandRegistry.registerCommand('feedback', () => {
apiSender.send('display-feedback', '');
});
commandRegistry.registerCommand('help', () => {
apiSender.send('display-help', '');
});
commandRegistry.registerCommand('troubleshooting', () => {
apiSender.send('display-troubleshooting', '');
});
const terminalInit = new TerminalInit(configurationRegistry);
terminalInit.init();
// init editor configuration
const editorInit = new EditorInit(configurationRegistry);
editorInit.init();
// init welcome configuration
const welcomeInit = new WelcomeInit(configurationRegistry);
welcomeInit.init();
const messageBox = new MessageBox(apiSender);
const authentication = new AuthenticationImpl(apiSender);
const taskManager = new TaskManager(apiSender);
const cliToolRegistry = new CliToolRegistry(apiSender, exec, telemetry);
const imageChecker = new ImageCheckerImpl(apiSender);
this.extensionLoader = new ExtensionLoader(
commandRegistry,
menuRegistry,
providerRegistry,
configurationRegistry,
imageRegistry,
apiSender,
trayMenuRegistry,
messageBox,
new ProgressImpl(taskManager),
statusBarRegistry,
kubernetesClient,
fileSystemMonitoring,
proxy,
containerProviderRegistry,
inputQuickPickRegistry,
customPickRegistry,
authentication,
iconRegistry,
onboardingRegistry,
telemetry,
viewRegistry,
context,
directories,
exec,
kubeGeneratorRegistry,
cliToolRegistry,
notificationRegistry,
imageChecker,
);
await this.extensionLoader.init();
const extensionsCatalog = new ExtensionsCatalog(certificates, proxy);
const featured = new Featured(this.extensionLoader, extensionsCatalog);
// do not wait
featured.init().catch((e: unknown) => {
console.error('Unable to initialized the featured extensions', e);
});
// setup security restrictions on links
await this.setupSecurityRestrictionsOnLinks(messageBox);
const contributionManager = new ContributionManager(apiSender, directories, containerProviderRegistry, exec);
this.ipcHandle('container-provider-registry:listContainers', async (): Promise<ContainerInfo[]> => {
return containerProviderRegistry.listContainers();
});
this.ipcHandle(
'container-provider-registry:listSimpleContainersByLabel',
async (_listener, label: string, key: string): Promise<SimpleContainerInfo[]> => {
return containerProviderRegistry.listSimpleContainersByLabel(label, key);
},
);
this.ipcHandle('container-provider-registry:listSimpleContainers', async (): Promise<SimpleContainerInfo[]> => {
return containerProviderRegistry.listSimpleContainers();
});
this.ipcHandle('container-provider-registry:listImages', async (): Promise<ImageInfo[]> => {
return containerProviderRegistry.listImages();
});
this.ipcHandle('container-provider-registry:listPods', async (): Promise<PodInfo[]> => {
return containerProviderRegistry.listPods();
});
this.ipcHandle('container-provider-registry:listNetworks', async (): Promise<NetworkInspectInfo[]> => {
return containerProviderRegistry.listNetworks();
});
this.ipcHandle(
'container-provider-registry:listVolumes',
async (_listener, fetchUsage: boolean): Promise<VolumeListInfo[]> => {
return containerProviderRegistry.listVolumes(fetchUsage);
},
);
this.ipcHandle('container-provider-registry:reconnectContainerProviders', async (): Promise<void> => {
return containerProviderRegistry.reconnectContainerProviders();
});
this.ipcHandle(
'container-provider-registry:pingContainerEngine',
async (_listener, providerContainerConnectionInfo: ProviderContainerConnectionInfo): Promise<unknown> => {
return containerProviderRegistry.pingContainerEngine(providerContainerConnectionInfo);
},
);
this.ipcHandle(
'container-provider-registry:listContainersFromEngine',
async (
_listener,
providerContainerConnectionInfo: ProviderContainerConnectionInfo,
): Promise<{ Id: string; Names: string[] }[]> => {
return containerProviderRegistry.listContainersFromEngine(providerContainerConnectionInfo);
},
);
this.ipcHandle(
'container-provider-registry:pruneVolumes',
async (_listener, engine: string): Promise<Dockerode.PruneVolumesInfo> => {
return containerProviderRegistry.pruneVolumes(engine);
},
);
this.ipcHandle(
'container-provider-registry:getVolumeInspect',
async (_listener, engine: string, volumeName: string): Promise<VolumeInspectInfo> => {
return containerProviderRegistry.getVolumeInspect(engine, volumeName);
},
);
this.ipcHandle(
'container-provider-registry:removeVolume',
async (_listener, engine: string, volumeName: string): Promise<void> => {
return containerProviderRegistry.removeVolume(engine, volumeName);
},
);
this.ipcHandle(
'container-provider-registry:replicatePodmanContainer',
async (
_listener,
source: { engineId: string; id: string },
target: { engineId: string },
overrideParameters: PodmanContainerCreateOptions,
): Promise<{ Id: string; Warnings: string[] }> => {
return containerProviderRegistry.replicatePodmanContainer(source, target, overrideParameters);
},
);
this.ipcHandle(
'container-provider-registry:createPod',
async (
_listener,
selectedProvider: ProviderContainerConnectionInfo,
createOptions: PodCreateOptions,
): Promise<{ engineId: string; Id: string }> => {
return containerProviderRegistry.createPod(selectedProvider, createOptions);
},
);
this.ipcHandle(
'container-provider-registry:startPod',
async (_listener, engine: string, podId: string): Promise<void> => {
return containerProviderRegistry.startPod(engine, podId);
},
);
this.ipcHandle(
'container-provider-registry:restartPod',
async (_listener, engine: string, podId: string): Promise<void> => {
return containerProviderRegistry.restartPod(engine, podId);
},
);
this.ipcHandle(
'container-provider-registry:stopPod',
async (_listener, engine: string, podId: string): Promise<void> => {
return containerProviderRegistry.stopPod(engine, podId);
},
);
this.ipcHandle(
'container-provider-registry:removePod',
async (_listener, engine: string, podId: string): Promise<void> => {
return containerProviderRegistry.removePod(engine, podId);
},
);
this.ipcHandle(
'container-provider-registry:generatePodmanKube',
async (_listener, engine: string, names: string[]): Promise<string> => {
const kubeGenerator = kubeGeneratorRegistry.getKubeGenerator();
if (!kubeGenerator) throw new Error(`Cannot find default KubeGenerator.`);
return (
await kubeGenerator.generate([
{
engineId: engine,
containers: names,
},
])
).yaml;
},
);
this.ipcHandle(
'kubernetes-generator-registry:generateKube',
async (
_listener,
kubernetesGeneratorArguments: KubernetesGeneratorArgument[],
kubeGeneratorId?: string,
): Promise<GenerateKubeResult> => {
const kubeGenerator = kubeGeneratorRegistry.getKubeGenerator(kubeGeneratorId);
if (!kubeGenerator) throw new Error(`kubeGenerator with id ${kubeGeneratorId} cannot be found.`);
return kubeGenerator.generate(kubernetesGeneratorArguments);
},
);
this.ipcHandle(
'container-provider-registry:playKube',
async (
_listener,
yamlFilePath: string,
selectedProvider: ProviderContainerConnectionInfo,
): Promise<PlayKubeInfo> => {
return containerProviderRegistry.playKube(yamlFilePath, selectedProvider);
},
);
this.ipcHandle(
'container-provider-registry:startContainer',
async (_listener, engine: string, containerId: string): Promise<void> => {
return containerProviderRegistry.startContainer(engine, containerId);
},
);
this.ipcHandle(
'container-provider-registry:stopContainer',
async (_listener, engine: string, containerId: string): Promise<void> => {
return containerProviderRegistry.stopContainer(engine, containerId);
},
);
this.ipcHandle(
'container-provider-registry:deleteContainer',
async (_listener, engine: string, containerId: string): Promise<void> => {
return containerProviderRegistry.deleteContainer(engine, containerId);
},
);
this.ipcHandle(
'container-provider-registry:deleteImage',
async (_listener, engine: string, imageId: string): Promise<void> => {
return containerProviderRegistry.deleteImage(engine, imageId);
},
);
this.ipcHandle(
'container-provider-registry:tagImage',
async (_listener, engine: string, imageTag: string, repo: string, tag?: string): Promise<void> => {
return containerProviderRegistry.tagImage(engine, imageTag, repo, tag);
},
);
this.ipcHandle(
'container-provider-registry:getImageInspect',
async (_listener, engine: string, imageId: string): Promise<ImageInspectInfo> => {
return containerProviderRegistry.getImageInspect(engine, imageId);
},
);
this.ipcHandle(
'container-provider-registry:getImageHistory',
async (_listener, engine: string, imageId: string): Promise<HistoryInfo[]> => {
return containerProviderRegistry.getImageHistory(engine, imageId);
},
);
this.ipcHandle(
'container-provider-registry:getContainerInspect',
async (_listener, engine: string, containerId: string): Promise<ContainerInspectInfo> => {
return containerProviderRegistry.getContainerInspect(engine, containerId);
},
);
this.ipcHandle(
'container-provider-registry:getPodInspect',
async (_listener, engine: string, podId: string): Promise<PodInspectInfo> => {
return containerProviderRegistry.getPodInspect(engine, podId);
},
);
this.ipcHandle(
'container-provider-registry:getContainerStats',
async (_listener, engine: string, containerId: string, onDataId: number): Promise<number> => {
return containerProviderRegistry.getContainerStats(engine, containerId, (stats: ContainerStatsInfo) => {
this.getWebContentsSender().send('container-provider-registry:getContainerStats-onData', onDataId, stats);
});
},
);
this.ipcHandle(
'container-provider-registry:stopContainerStats',
async (_listener, containerStatsId: number): Promise<void> => {
return containerProviderRegistry.stopContainerStats(containerStatsId);
},
);
this.ipcHandle(
'container-provider-registry:pruneContainers',
async (_listener, engine: string): Promise<Dockerode.PruneContainersInfo> => {
return containerProviderRegistry.pruneContainers(engine);
},
);
this.ipcHandle('container-provider-registry:prunePods', async (_listener, engine: string): Promise<void> => {
return containerProviderRegistry.prunePods(engine);
});
this.ipcHandle('container-provider-registry:pruneImages', async (_listener, engine: string): Promise<void> => {
return containerProviderRegistry.pruneImages(engine);
});
this.ipcHandle(
'container-provider-registry:restartContainer',
async (_listener, engine: string, containerId: string): Promise<void> => {
return containerProviderRegistry.restartContainer(engine, containerId);
},
);
this.ipcHandle(
'container-provider-registry:restartContainersByLabel',
async (_listener, engine: string, label: string, key: string): Promise<void> => {