-
Notifications
You must be signed in to change notification settings - Fork 268
/
container-registry.ts
2617 lines (2369 loc) · 91.1 KB
/
container-registry.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-2024 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 crypto from 'node:crypto';
import { EventEmitter } from 'node:events';
import * as fs from 'node:fs';
import path from 'node:path';
import { type Stream, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import type * as containerDesktopAPI from '@podman-desktop/api';
import datejs from 'date.js';
import type { ContainerAttachOptions, ImageBuildOptions } from 'dockerode';
import Dockerode from 'dockerode';
import moment from 'moment';
import StreamValues from 'stream-json/streamers/StreamValues.js';
import type { ProviderRegistry } from '/@/plugin/provider-registry.js';
import { isWindows } from '../util.js';
import type { ApiSenderType } from './api.js';
import type {
ContainerCreateOptions,
ContainerExportOptions,
ContainerImportOptions,
ContainerInfo,
ContainerPortInfo,
ImageLoadOptions,
ImagesSaveOptions,
NetworkCreateOptions,
NetworkCreateResult,
SimpleContainerInfo,
VolumeCreateOptions,
VolumeCreateResponseInfo,
} from './api/container-info.js';
import type { ContainerInspectInfo } from './api/container-inspect-info.js';
import type { ContainerStatsInfo } from './api/container-stats-info.js';
import type { HistoryInfo } from './api/history-info.js';
import type { BuildImageOptions, ImageInfo, ListImagesOptions, PodmanListImagesOptions } from './api/image-info.js';
import type { ImageInspectInfo } from './api/image-inspect-info.js';
import type { ManifestCreateOptions, ManifestInspectInfo } from './api/manifest-info.js';
import type { NetworkInspectInfo } from './api/network-info.js';
import type { PodCreateOptions, PodInfo, PodInspectInfo } from './api/pod-info.js';
import type { ProviderContainerConnectionInfo } from './api/provider-info.js';
import type { PullEvent } from './api/pull-event.js';
import type { VolumeInfo, VolumeInspectInfo, VolumeListInfo } from './api/volume-info.js';
import type { ConfigurationRegistry } from './configuration-registry.js';
import type {
ContainerCreateMountOption,
ContainerCreateNetNSOption,
ContainerCreateOptions as PodmanContainerCreateOptions,
ContainerCreatePortMappingOption,
LibPod,
PlayKubeInfo,
PodInfo as LibpodPodInfo,
} from './dockerode/libpod-dockerode.js';
import { LibpodDockerode } from './dockerode/libpod-dockerode.js';
import { EnvfileParser } from './env-file-parser.js';
import type { Event } from './events/emitter.js';
import { Emitter } from './events/emitter.js';
import type { ImageRegistry } from './image-registry.js';
import { LibpodApiSettings } from './libpod-api-enable/libpod-api-settings.js';
import type { Telemetry } from './telemetry/telemetry.js';
import { Disposable } from './types/disposable.js';
import { guessIsManifest } from './util/manifest.js';
const tar: { pack: (dir: string) => NodeJS.ReadableStream } = require('tar-fs');
export interface InternalContainerProvider {
name: string;
id: string;
connection: containerDesktopAPI.ContainerProviderConnection;
// api not there if status is stopped
api?: Dockerode;
libpodApi?: LibPod;
}
export interface InternalContainerProviderLifecycle {
internal: containerDesktopAPI.ProviderLifecycle;
status: string;
}
interface JSONEvent {
type: string;
status: string;
id: string;
Type?: string;
}
export class ContainerProviderRegistry {
private readonly _onEvent = new Emitter<JSONEvent>();
readonly onEvent: Event<JSONEvent> = this._onEvent.event;
// delay in ms before retrying to connect to the provider when /events connection fails
protected retryDelayEvents: number = 5000;
private envfileParser = new EnvfileParser();
constructor(
private apiSender: ApiSenderType,
private configurationRegistry: ConfigurationRegistry,
private imageRegistry: ImageRegistry,
private telemetryService: Telemetry,
) {
const libPodDockerode = new LibpodDockerode();
libPodDockerode.enhancePrototypeWithLibPod();
// setup listeners
this.setupListeners();
}
protected containerProviders: Map<string, containerDesktopAPI.ContainerProviderConnection> = new Map();
protected internalProviders: Map<string, InternalContainerProvider> = new Map();
// map of streams per container id
protected streamsPerContainerId: Map<string, NodeJS.ReadWriteStream> = new Map();
protected streamsOutputPerContainerId: Map<string, Buffer[]> = new Map();
useLibpodApiForImageList(): boolean {
return this.configurationRegistry
.getConfiguration(LibpodApiSettings.SectionName)
.get<boolean>(LibpodApiSettings.ForImageList, false);
}
handleEvents(api: Dockerode, errorCallback: (error: Error) => void): void {
let nbEvents = 0;
const startDate = performance.now();
const eventEmitter = new EventEmitter();
eventEmitter.on('event', (jsonEvent: JSONEvent) => {
nbEvents++;
console.log('event is', jsonEvent);
this._onEvent.fire(jsonEvent);
if (jsonEvent.status === 'stop' && jsonEvent?.Type === 'container') {
// need to notify that a container has been stopped
this.apiSender.send('container-stopped-event', jsonEvent.id);
} else if (jsonEvent.status === 'init' && jsonEvent?.Type === 'container') {
// need to notify that a container has been started
this.apiSender.send('container-init-event', jsonEvent.id);
} else if (jsonEvent.status === 'create' && jsonEvent?.Type === 'container') {
// need to notify that a container has been created
this.apiSender.send('container-created-event', jsonEvent.id);
} else if (jsonEvent.status === 'start' && jsonEvent?.Type === 'container') {
// need to notify that a container has been started
this.apiSender.send('container-started-event', jsonEvent.id);
} else if (jsonEvent.status === 'destroy' && jsonEvent?.Type === 'container') {
// need to notify that a container has been destroyed
this.apiSender.send('container-stopped-event', jsonEvent.id);
} else if (jsonEvent.status === 'die' && jsonEvent?.Type === 'container') {
this.apiSender.send('container-die-event', jsonEvent.id);
} else if (jsonEvent.status === 'kill' && jsonEvent?.Type === 'container') {
this.apiSender.send('container-kill-event', jsonEvent.id);
} else if (jsonEvent?.Type === 'pod') {
this.apiSender.send('pod-event');
} else if (jsonEvent?.Type === 'volume') {
this.apiSender.send('volume-event');
} else if (jsonEvent.status === 'remove' && jsonEvent?.Type === 'container') {
this.apiSender.send('container-removed-event', jsonEvent.id);
} else if (jsonEvent.status === 'pull' && jsonEvent?.Type === 'image') {
// need to notify that image are being pulled
this.apiSender.send('image-pull-event', jsonEvent.id);
} else if (jsonEvent.status === 'tag' && jsonEvent?.Type === 'image') {
// need to notify that image are being tagged
this.apiSender.send('image-tag-event', jsonEvent.id);
} else if (jsonEvent.status === 'untag' && jsonEvent?.Type === 'image') {
// need to notify that image are being untagged
this.apiSender.send('image-untag-event', jsonEvent.id);
} else if (jsonEvent.status === 'remove' && jsonEvent?.Type === 'image') {
// need to notify that image are being pulled
this.apiSender.send('image-remove-event', jsonEvent.id);
} else if (jsonEvent.status === 'delete' && jsonEvent?.Type === 'image') {
// need to notify that image are being pulled
this.apiSender.send('image-remove-event', jsonEvent.id);
} else if (jsonEvent.status === 'build' && jsonEvent?.Type === 'image') {
// need to notify that image are being pulled
this.apiSender.send('image-build-event', jsonEvent.id);
} else if (jsonEvent.status === 'loadfromarchive' && jsonEvent?.Type === 'image') {
// need to notify that image are being pulled
this.apiSender.send('image-loadfromarchive-event', jsonEvent.id);
}
});
api.getEvents((err, stream) => {
if (err) {
console.log('error is', err);
errorCallback(new Error('Error in handling events', err));
}
stream?.on('error', error => {
console.error('/event stream received an error.', error);
// log why it failed and after how many ms connection dropped
this.telemetryService.track('handleContainerEventsFailure', {
nbEvents,
failureAfter: performance.now() - startDate,
error,
});
// notify the error (do not throw as we're inside handlers/callbacks)
errorCallback(new Error('Error in handling events', error));
});
const pipeline = stream?.pipe(StreamValues.withParser());
pipeline?.on('error', error => {
console.error('Error while parsing events', error);
});
pipeline?.on('data', data => {
if (data?.value !== undefined) {
eventEmitter.emit('event', data.value);
}
});
});
}
setupListeners(): void {
const cleanStreamMap = (containerId: unknown): void => {
this.streamsPerContainerId.delete(String(containerId));
this.streamsOutputPerContainerId.delete(String(containerId));
};
this.apiSender.receive('container-stopped-event', (containerId: unknown) => {
cleanStreamMap(containerId);
});
this.apiSender.receive('container-die-event', (containerId: unknown) => {
cleanStreamMap(containerId);
});
this.apiSender.receive('container-kill-event', (containerId: unknown) => {
cleanStreamMap(containerId);
});
this.apiSender.receive('container-removed-event', (containerId: unknown) => {
cleanStreamMap(containerId);
});
}
reconnectContainerProviders(): void {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const provider of this.internalProviders.values()) {
if (provider.api) this.setupConnectionAPI(provider, provider.connection);
}
}
setupConnectionAPI(
internalProvider: InternalContainerProvider,
containerProviderConnection: containerDesktopAPI.ContainerProviderConnection,
): void {
// abort if connection is stopped
if (containerProviderConnection.status() === 'stopped') {
console.log('Aborting reconnect due to error as connection is now stopped');
return;
}
// abort if connection has been removed
if (containerProviderConnection.status() === undefined) {
console.log('Aborting reconnect due to error as connection has been removed (probably machine has been removed)');
return;
}
internalProvider.api = new Dockerode({ socketPath: containerProviderConnection.endpoint.socketPath });
if (containerProviderConnection.type === 'podman') {
internalProvider.libpodApi = internalProvider.api as unknown as LibPod;
}
// in case of errors reported during handling events like the connection is aborted, etc.
// we need to reconnect the provider
const errorHandler = (error: Error): void => {
console.warn('Error when handling events', error, 'Will reconnect in 5s', error);
internalProvider.api = undefined;
internalProvider.libpodApi = undefined;
// ok we had some errors so we need to reconnect the provider
// delay the reconnection to avoid too many reconnections
// retry in 5 seconds
setTimeout(() => {
this.setupConnectionAPI(internalProvider, containerProviderConnection);
}, this.retryDelayEvents);
};
this.handleEvents(internalProvider.api, errorHandler);
this.apiSender.send('provider-change', {});
}
registerContainerConnection(
provider: containerDesktopAPI.Provider,
containerProviderConnection: containerDesktopAPI.ContainerProviderConnection,
providerRegistry: ProviderRegistry,
): Disposable {
const providerName = containerProviderConnection.name;
const id = `${provider.id}.${providerName}`;
this.containerProviders.set(id, containerProviderConnection);
this.telemetryService.track('registerContainerProviderConnection', {
name: containerProviderConnection.name,
type: containerProviderConnection.type,
total: this.containerProviders.size,
});
const internalProvider: InternalContainerProvider = {
id,
name: provider.name,
connection: containerProviderConnection,
};
let previousStatus = containerProviderConnection.status();
providerRegistry.onBeforeDidUpdateContainerConnection(event => {
if (event.providerId === provider.id && event.connection.name === containerProviderConnection.name) {
const newStatus = event.status;
if (newStatus === 'stopped') {
internalProvider.api = undefined;
internalProvider.libpodApi = undefined;
this.apiSender.send('provider-change', {});
}
if (newStatus === 'started') {
this.setupConnectionAPI(internalProvider, containerProviderConnection);
}
}
previousStatus = event.status;
});
if (containerProviderConnection.status() === 'started') {
this.setupConnectionAPI(internalProvider, containerProviderConnection);
}
// track the status of the provider
const timer = setInterval(() => {
const newStatus = containerProviderConnection.status();
if (newStatus !== previousStatus) {
if (newStatus === 'stopped') {
internalProvider.api = undefined;
internalProvider.libpodApi = undefined;
this.apiSender.send('provider-change', {});
}
if (newStatus === 'started') {
this.setupConnectionAPI(internalProvider, containerProviderConnection);
this.internalProviders.set(id, internalProvider);
}
previousStatus = newStatus;
}
}, 2000);
this.internalProviders.set(id, internalProvider);
this.apiSender.send('provider-change', {});
// listen to events
return Disposable.create(() => {
clearInterval(timer);
this.internalProviders.delete(id);
this.containerProviders.delete(id);
this.apiSender.send('provider-change', {});
});
}
// do not use inspect information
async listSimpleContainers(abortController?: AbortController): Promise<SimpleContainerInfo[]> {
let telemetryOptions = {};
const containers = await Promise.all(
Array.from(this.internalProviders.values()).map(async provider => {
try {
const providerApi = provider.api;
if (!providerApi) {
return [];
}
const containers = await providerApi.listContainers({ all: true, abortSignal: abortController?.signal });
return Promise.all(
containers.map(async container => {
const containerInfo: SimpleContainerInfo = {
...container,
engineName: provider.name,
engineId: provider.id,
engineType: provider.connection.type,
};
return containerInfo;
}),
);
} catch (error) {
console.log('error in engine', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedContainers = containers.flat();
this.telemetryService.track(
'listSimpleContainers',
Object.assign({ total: flattenedContainers.length }, telemetryOptions),
);
return flattenedContainers;
}
// listSimpleContainers by matching label and key
async listSimpleContainersByLabel(
label: string,
key: string,
abortController?: AbortController,
): Promise<SimpleContainerInfo[]> {
// Get all the containers using listSimpleContainers
const containers = await this.listSimpleContainers(abortController);
// Find all the containers that match the label + key
return containers.filter(container => {
const labels = container.Labels;
return labels && labels[label] === key;
});
}
async listContainers(): Promise<ContainerInfo[]> {
let telemetryOptions = {};
const containers = await Promise.all(
Array.from(this.internalProviders.values()).map(async provider => {
try {
const providerApi = provider.api;
if (!providerApi) {
return [];
}
// local type used to convert Podman containers to Dockerode containers
interface CompatContainerInfo {
Id: string;
Names: string[];
Image: string;
ImageID: string;
Command?: string;
Created: number;
Ports: ContainerPortInfo[];
Labels: { [label: string]: string };
State: string;
StartedAt?: string;
Status?: string;
}
// if we have a libpod API, grab containers using Podman API
let containers: CompatContainerInfo[] = [];
if (provider.libpodApi) {
const podmanContainers = await provider.libpodApi.listPodmanContainers({ all: true });
// convert Podman containers to Dockerode containers
containers = podmanContainers.map(podmanContainer => {
// get labels or nothing
const Labels: { [label: string]: string } = {};
if (podmanContainer.Labels) {
// copy all labels
for (const label of Object.keys(podmanContainer.Labels)) {
Labels[label] = podmanContainer.Labels[label];
}
}
// get labels or nothing
let Ports: ContainerPortInfo[] = [];
if (podmanContainer.Ports) {
Ports = podmanContainer.Ports.map(port => {
return {
PrivatePort: port.container_port,
PublicPort: port.host_port,
Type: port.protocol,
IP: port.host_ip,
};
});
}
// convert StartedAt which is a unix timestamp to a iso8601 date
const StartedAt = moment.unix(podmanContainer.StartedAt).toISOString();
return {
Id: podmanContainer.Id,
Names: podmanContainer.Names.map(name => `/${name}`),
ImageID: `sha256:${podmanContainer.ImageID}`,
Image: podmanContainer.Image,
// convert to unix timestamp
Created: moment(podmanContainer.Created).unix(),
State: podmanContainer.State,
StartedAt,
Command: podmanContainer.Command?.length > 0 ? podmanContainer.Command[0] : undefined,
Labels,
Ports,
};
});
} else {
containers = await providerApi.listContainers({ all: true });
containers.forEach(container => {
let StartedAt;
if (container.State.toUpperCase() === 'RUNNING' && !container.StartedAt && container.Status) {
// convert the Status like "Up 2 minutes" to a date
// remove up from the status
const status = container.Status.replace('Up ', '');
// add ago at the end
const statusWithAgo = status.concat(' ago');
try {
StartedAt = new Date(datejs(statusWithAgo)).toISOString();
} catch (error) {
StartedAt = '';
telemetryOptions = { error: error };
}
// update the StartedAt value
container.StartedAt = StartedAt;
}
});
}
let pods: LibpodPodInfo[] = [];
if (provider.libpodApi) {
pods = await provider.libpodApi.listPods();
}
return Promise.all(
containers.map(async container => {
// do we have a matching pod for this container ?
let pod;
const matchingPod = pods.find(pod =>
pod.Containers.find(containerOfPod => containerOfPod.Id === container.Id),
);
if (matchingPod) {
pod = {
id: matchingPod.Id,
name: matchingPod.Name,
status: matchingPod.Status,
engineId: provider.id,
};
}
const containerInfo: ContainerInfo = {
...container,
pod,
engineName: provider.name,
engineId: provider.id,
engineType: provider.connection.type,
StartedAt: container.StartedAt || '',
Status: container.Status,
ImageBase64RepoTag: Buffer.from(container.Image, 'binary').toString('base64'),
};
return containerInfo;
}),
);
} catch (error) {
console.log('error in engine', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedContainers = containers.flat();
this.telemetryService.track(
'listContainers',
Object.assign({ total: flattenedContainers.length }, telemetryOptions),
);
return flattenedContainers;
}
async listImages(options?: ListImagesOptions): Promise<ImageInfo[]> {
let telemetryOptions = {};
let providers: InternalContainerProvider[];
if (options?.provider === undefined) {
providers = Array.from(this.internalProviders.values());
} else {
providers = [this.getMatchingContainerProvider(options?.provider)];
}
const images = await Promise.all(
Array.from(providers).map(async provider => {
try {
if (!provider.api) {
return [];
}
const images = await provider.api.listImages({ all: false });
return images.map(image => {
const imageInfo: ImageInfo = { ...image, engineName: provider.name, engineId: provider.id };
return imageInfo;
});
} catch (error) {
console.log('error in engine', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedImages = images.flat();
this.telemetryService.track('listImages', Object.assign({ total: flattenedImages.length }, telemetryOptions));
return flattenedImages;
}
// Podman list images will prefer to use libpod API of the provider
// before falling back to using the regular API
async podmanListImages(options?: PodmanListImagesOptions): Promise<ImageInfo[]> {
const telemetryOptions = {};
// This gets all the available providers if no provider has been specified
let providers: InternalContainerProvider[];
if (options?.provider === undefined) {
providers = Array.from(this.internalProviders.values());
} else {
providers = [this.getMatchingContainerProvider(options?.provider)];
}
const images = await Promise.all(
providers.map(async provider => {
// Initialize an empty array for the case where neither API is available
// ignore any warning as we are adding engineId and engineName to the image
// and as one of the API uses Dockerode, the other ImageInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let fetchedImages: any[] = [];
// If libpod API is available AND the configuration is set to use libpodApi, use podmanListImages API call.
if (provider.libpodApi && this.useLibpodApiForImageList()) {
fetchedImages = await provider.libpodApi.podmanListImages({
all: options?.all,
filters: options?.filters,
});
} else if (provider.api) {
fetchedImages = await provider.api.listImages({ all: false });
} else {
console.log('Engine does not have an API or a libpod API, returning empty array', provider.name);
return fetchedImages;
}
// Transform fetched images to include engine name and ID
return fetchedImages.map(image => ({
...image,
engineName: provider.name,
engineId: provider.id,
// Using guessIsManifest, determine if the image is a manifest and set isManifest accordingly
// NOTE: This is a workaround until we have a better way to determine if an image is a manifest
// and may result in false positives until issue: https://github.com/containers/podman/issues/22184 is resolved
isManifest: guessIsManifest(image, provider.connection.type),
}));
}),
);
const flattenedImages = images.flat();
this.telemetryService.track('podmanListImages', Object.assign({ total: flattenedImages.length }, telemetryOptions));
return flattenedImages;
}
async pruneImages(engineId: string): Promise<void> {
// We have to use two different API calls for pruning images, because the Podman API does not respect the 'dangling' filter
// and instead uses 'all' and 'external'. See: https://github.com/containers/podman/issues/11576
// so for Dockerode we'll have to call pruneImages with the 'dangling' filter, and for Podman we'll have to call pruneImages
// PODMAN:
// Have to use podman API directly for pruning images
// TODO: Remove this once the Podman API respects the 'dangling' filter: https://github.com/containers/podman/issues/17614
let telemetryOptions = {};
try {
const provider = this.internalProviders.get(engineId);
if (provider?.libpodApi) {
await provider.libpodApi.pruneAllImages(true);
return;
}
// DOCKER:
// Return Promise<void> for this call, because Dockerode does not return anything
await this.getMatchingEngine(engineId).pruneImages({ filters: { dangling: { false: true } } });
} catch (error) {
telemetryOptions = { error: error };
throw error;
} finally {
this.telemetryService.track('pruneImages', telemetryOptions);
}
}
async listPods(): Promise<PodInfo[]> {
let telemetryOptions = {};
const pods = await Promise.all(
Array.from(this.internalProviders.values()).map(async provider => {
try {
if (!provider.libpodApi) {
return [];
}
const pods = await provider.libpodApi.listPods();
return pods.map(pod => {
const podInfo: PodInfo = { ...pod, engineName: provider.name, engineId: provider.id, kind: 'podman' };
return podInfo;
});
} catch (error) {
console.log('error in engine', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedPods = pods.flat();
this.telemetryService.track('listPods', Object.assign({ total: flattenedPods.length }, telemetryOptions));
return flattenedPods;
}
async listNetworks(): Promise<NetworkInspectInfo[]> {
let telemetryOptions = {};
const networks = await Promise.all(
Array.from(this.internalProviders.values()).map(async provider => {
try {
if (!provider.api) {
return [];
}
const networks = await provider.api.listNetworks();
return networks.map(network => {
const networkInfo: NetworkInspectInfo = {
...network,
engineName: provider.name,
engineId: provider.id,
engineType: provider.connection.type,
};
return networkInfo;
});
} catch (error) {
console.log('error in engine when listing networks', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedNetworks = networks.flat();
this.telemetryService.track('listNetworks', Object.assign({ total: flattenedNetworks.length }, telemetryOptions));
return flattenedNetworks;
}
async createNetwork(
providerContainerConnectionInfo: ProviderContainerConnectionInfo | containerDesktopAPI.ContainerProviderConnection,
options: NetworkCreateOptions,
): Promise<NetworkCreateResult> {
let telemetryOptions = {};
try {
const matchingEngine = this.getMatchingEngineFromConnection(providerContainerConnectionInfo);
const network = await matchingEngine.createNetwork(options);
return { Id: network.id };
} catch (error) {
telemetryOptions = { error: error };
throw error;
} finally {
this.telemetryService.track('createNetwork', telemetryOptions);
}
}
async listVolumes(fetchUsage = false): Promise<VolumeListInfo[]> {
let telemetryOptions = {};
const volumes = await Promise.all(
Array.from(this.internalProviders.values()).map(async provider => {
try {
if (!provider.api) {
return [];
}
// grab containers
const containers = await provider.api.listContainers({ all: true });
// any as there is a CreatedAt field missing in the type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const volumeListInfo: any = await provider.api.listVolumes();
let storageDefinition = {
Volumes: [],
};
if (fetchUsage) {
// grab the storage information
storageDefinition = await provider.api.df();
}
const engineName = provider.name;
const engineId = provider.id;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const volumeInfos = volumeListInfo.Volumes.map((volumeList: any) => {
const volumeInfo: VolumeInfo = { ...volumeList, engineName, engineId };
// compute containers using this volume
const containersUsingThisVolume = containers
.filter(container => container.Mounts?.find(mount => mount.Name === volumeInfo.Name))
.map(container => {
return { id: container.Id, names: container.Names };
});
volumeInfo.containersUsage = containersUsingThisVolume;
// no usage data, set to -1 for size and 0 for refCount
if (!volumeInfo.UsageData) {
volumeInfo.UsageData = {
Size: -1,
RefCount: 0,
};
}
// defines the refCount
volumeInfo.UsageData.RefCount = volumeInfo.containersUsage.length;
// do we have a matching volume in storage definition ?
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const matchingVolume: any = (storageDefinition?.Volumes || []).find(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(volumeStorage: any) => volumeStorage.Name === volumeInfo.Name,
);
// update the size if asked and then there is a matching volume
if (matchingVolume) {
volumeInfo.UsageData.Size = matchingVolume.UsageData.Size;
}
return volumeInfo;
});
return { Volumes: volumeInfos, Warnings: volumeListInfo.Warnings, engineName, engineId };
} catch (error) {
console.log('error in engine', provider.name, error);
telemetryOptions = { error: error };
return [];
}
}),
);
const flattenedVolumes: VolumeListInfo[] = volumes.flat();
this.telemetryService.track('listVolumes', Object.assign({ total: flattenedVolumes.length }, telemetryOptions));
return flattenedVolumes;
}
async getVolumeInspect(engineId: string, volumeName: string): Promise<VolumeInspectInfo> {
let telemetryOptions = {};
try {
// need to find the container engine of the container
const provider = this.internalProviders.get(engineId);
if (!provider) {
throw new Error('no engine matching this container');
}
if (!provider.api) {
throw new Error('no running provider for the matching container');
}
const volumeObject = provider.api.getVolume(volumeName);
const volumeInspect = await volumeObject.inspect();
return {
engineName: provider.name,
engineId: provider.id,
...volumeInspect,
};
} catch (error) {
telemetryOptions = { error: error };
throw error;
} finally {
this.telemetryService.track('volumeInspect', telemetryOptions);
}
}
// method like remove Volume but instead of taking engineId/engineName it's taking connection info
async deleteVolume(
volumeName: string,
options?: { provider?: ProviderContainerConnectionInfo | containerDesktopAPI.ContainerProviderConnection },
): Promise<void> {
let telemetryOptions = {};
try {
let matchingContainerProviderApi: Dockerode;
if (options?.provider) {
// grab all connections
matchingContainerProviderApi = this.getMatchingEngineFromConnection(options.provider);
} else {
// Get the first running connection (preference for podman)
matchingContainerProviderApi = this.getFirstRunningConnection()[1];
}
return matchingContainerProviderApi.getVolume(volumeName).remove();
} catch (error) {
telemetryOptions = { error: error };
throw error;
} finally {
this.telemetryService.track('removeVolume', telemetryOptions);
}
}
async removeVolume(engineId: string, volumeName: string): Promise<void> {
let telemetryOptions = {};
try {
return this.getMatchingEngine(engineId).getVolume(volumeName).remove();
} catch (error) {
telemetryOptions = { error: error };
throw error;
} finally {
this.telemetryService.track('removeVolume', telemetryOptions);
}
}
protected getMatchingEngine(engineId: string): Dockerode {
// need to find the container engine of the container
const engine = this.internalProviders.get(engineId);
if (!engine) {
throw new Error('no engine matching this engine');
}
if (!engine.api) {
throw new Error('no running provider for the matching engine');
}
return engine.api;
}
protected getMatchingPodmanEngine(engineId: string): InternalContainerProvider {
// need to find the container engine of the container
const engine = this.internalProviders.get(engineId);
if (!engine) {
throw new Error('no engine matching this engine');
}
if (!engine.api) {
throw new Error('no running provider for the matching engine');
}
if (!engine.libpodApi) {
throw new Error('LibPod is not supported by this engine');
}
return engine;
}
protected getMatchingPodmanEngineLibPod(engineId: string): LibPod {
// need to find the container engine of the container
const engine = this.getMatchingPodmanEngine(engineId);
if (!engine.libpodApi) {
throw new Error('LibPod is not supported by this engine');
}
return engine.libpodApi;
}
// prefer podman over docker
public getFirstRunningConnection(): [ProviderContainerConnectionInfo, Dockerode] {
// grab all connections
const matchingContainerProviders = Array.from(this.internalProviders.entries()).filter(
containerProvider => containerProvider[1].api,
);
if (!matchingContainerProviders || matchingContainerProviders.length === 0) {
throw new Error('No provider with a running engine');
}
// prefer podman over other engines
// sort by podman first as container type
matchingContainerProviders.sort((a, b) => {
if (a[1].connection.type === 'podman' && b[1].connection.type === 'podman') {
return 0;
} else if (a[1].connection.type === 'podman' && b[1].connection.type !== 'podman') {
return -1;
} else {
return 1;
}
});
const matchingConnection = matchingContainerProviders[0];
if (!matchingConnection[1].api) {
throw new Error('No provider with a running engine');
}
const matchingConnectionName = matchingConnection[0];
const matchingConnectionObject = this.containerProviders.get(matchingConnectionName);
if (!matchingConnectionObject) {
throw new Error('Unable to find a running engine');
}
return [
{
name: matchingConnectionObject.name,
endpoint: {
socketPath: matchingConnectionObject.endpoint.socketPath,
},
} as ProviderContainerConnectionInfo,
matchingConnection[1].api,
];
}
/**
* it finds a running podman provider by fetching all internalProviders.
* It filters by checking the libpodApi
* @returns a running podman provider
* @throws if no running podman provider is found
*/
public getFirstRunningPodmanContainerProvider(): InternalContainerProvider {
// grab the first running podman provider
const matchingPodmanContainerProvider = Array.from(this.internalProviders.values()).find(
containerProvider => containerProvider.libpodApi,
);
if (!matchingPodmanContainerProvider) {
throw new Error('No podman provider with a running engine');
}
return matchingPodmanContainerProvider;
}
protected getMatchingEngineFromConnection(
providerContainerConnectionInfo: ProviderContainerConnectionInfo | containerDesktopAPI.ContainerProviderConnection,
): Dockerode {
// grab all connections
const matchingContainerProvider = this.getMatchingContainerProvider(providerContainerConnectionInfo);
if (!matchingContainerProvider?.api) {
throw new Error('no running provider for the matching container');
}
return matchingContainerProvider.api;
}
protected getMatchingContainerProvider(