-
Notifications
You must be signed in to change notification settings - Fork 275
/
ContainerList.svelte
529 lines (463 loc) · 17.7 KB
/
ContainerList.svelte
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
<script lang="ts">
import { faPlusCircle, faTrash } from '@fortawesome/free-solid-svg-icons';
import { Button, FilteredEmptyScreen, Modal, NavPage, Table, TableColumn, TableRow } from '@podman-desktop/ui-svelte';
import { ContainerIcon } from '@podman-desktop/ui-svelte/icons';
import moment from 'moment';
import { onDestroy, onMount } from 'svelte';
import { get, type Unsubscriber } from 'svelte/store';
import { router } from 'tinro';
import type { ContainerInfo } from '/@api/container-info';
import type { ViewInfoUI } from '/@api/view-info';
import type { PodInfo } from '../../../../main/src/plugin/api/pod-info';
import { containerGroupsInfo } from '../../stores/containerGroups';
import { containersInfos } from '../../stores/containers';
import { context } from '../../stores/context';
import { podCreationHolder } from '../../stores/creation-from-containers-store';
import { podsInfos } from '../../stores/pods';
import { providerInfos } from '../../stores/providers';
import { findMatchInLeaves } from '../../stores/search-util';
import { viewsContributions } from '../../stores/views';
import type { ContextUI } from '../context/context';
import type { EngineInfoUI } from '../engine/EngineInfoUI';
import Prune from '../engine/Prune.svelte';
import NoContainerEngineEmptyScreen from '../image/NoContainerEngineEmptyScreen.svelte';
import SolidPodIcon from '../images/SolidPodIcon.svelte';
import { PodUtils } from '../pod/pod-utils';
import { CONTAINER_LIST_VIEW } from '../view/views';
import { ContainerUtils } from './container-utils';
import ContainerColumnActions from './ContainerColumnActions.svelte';
import ContainerColumnAge from './ContainerColumnAge.svelte';
import ContainerColumnEnvironment from './ContainerColumnEnvironment.svelte';
import ContainerColumnImage from './ContainerColumnImage.svelte';
import ContainerColumnName from './ContainerColumnName.svelte';
import ContainerColumnStatus from './ContainerColumnStatus.svelte';
import ContainerEmptyScreen from './ContainerEmptyScreen.svelte';
import { ContainerGroupInfoTypeUI, type ContainerGroupInfoUI, type ContainerInfoUI } from './ContainerInfoUI';
const containerUtils = new ContainerUtils();
let openChoiceModal = false;
let enginesList: EngineInfoUI[];
// groups of containers that will be displayed
let containerGroups: ContainerGroupInfoUI[] = [];
let viewContributions: ViewInfoUI[] = [];
let globalContext: ContextUI;
let containersInfo: ContainerInfo[] = [];
export let searchTerm = '';
$: updateContainers(containersInfo, globalContext, viewContributions, searchTerm);
function fromExistingImage(): void {
openChoiceModal = false;
window.location.href = '#/images';
}
$: providerConnections = $providerInfos
.map(provider => provider.containerConnections)
.flat()
.filter(providerContainerConnection => providerContainerConnection.status === 'started');
let refreshTimeouts: NodeJS.Timeout[] = [];
const SECOND = 1000;
function refreshUptime(): void {
containerGroups = containerGroups.map(containerGroupUiInfo => {
containerGroupUiInfo.containers = containerGroupUiInfo.containers.map(containerUiInfo => {
return { ...containerUiInfo, uptime: containerUtils.refreshUptime(containerUiInfo) };
});
return containerGroupUiInfo;
});
// compute new interval
const newInterval = computeInterval();
refreshTimeouts.forEach(timeout => clearTimeout(timeout));
refreshTimeouts.length = 0;
if (newInterval > 0) {
refreshTimeouts.push(setTimeout(refreshUptime, newInterval));
}
}
function computeInterval(): number {
const allContainers = containerGroups.map(group => group.containers).flat();
// no container running, no refresh
if (!allContainers.some(container => container.state === 'RUNNING')) {
return -1;
}
// limit to containers running
const runningContainers = allContainers.filter(container => container.state === 'RUNNING');
// do we have containers that have been started in less than 1 minute
// if so, need to update every second
const containersStartedInLessThan1Mn = runningContainers.filter(
container => moment().diff(container.startedAt, 'minutes') < 1,
);
if (containersStartedInLessThan1Mn.length > 0) {
return 2 * SECOND;
}
// every minute for containers started less than 1 hour
const containersStartedInLessThan1Hour = runningContainers.filter(
container => moment().diff(container.startedAt, 'hours') < 1,
);
if (containersStartedInLessThan1Hour.length > 0) {
// every minute
return 60 * SECOND;
}
// every hour for containers started less than 1 day
const containersStartedInLessThan1Day = runningContainers.filter(
container => moment().diff(container.startedAt, 'days') < 1,
);
if (containersStartedInLessThan1Day.length > 0) {
// every hour
return 60 * 60 * SECOND;
}
// every day
return 60 * 60 * 24 * SECOND;
}
// delete the items selected in the list
let bulkDeleteInProgress = false;
async function deleteSelectedContainers(): Promise<void> {
const podGroups = containerGroups
.filter(group => group.type === ContainerGroupInfoTypeUI.POD)
.filter(pod => pod.selected);
const selectedContainers = containerGroups
.filter(group => group.type !== ContainerGroupInfoTypeUI.POD)
.map(group => group.containers)
.flat()
.filter(container => container.selected);
if (podGroups.length + selectedContainers.length === 0) {
return;
}
// mark pods and containers for deletion
bulkDeleteInProgress = true;
podGroups.forEach(pod => (pod.status = 'DELETING'));
selectedContainers.forEach(container => (container.state = 'DELETING'));
containerGroups = [...containerGroups];
// delete pods first if any
if (podGroups.length > 0) {
await Promise.all(
podGroups.map(async podGroup => {
if (podGroup.engineId && podGroup.id) {
try {
await window.removePod(podGroup.engineId, podGroup.id);
} catch (e) {
console.error('error while removing pod', e);
}
}
}),
);
}
// then containers (that are not inside a pod)
if (selectedContainers.length > 0) {
await Promise.all(
selectedContainers.map(async container => {
container.actionInProgress = true;
// reset error when starting task
container.actionError = '';
containerGroups = [...containerGroups];
try {
await window.deleteContainer(container.engineId, container.id);
} catch (e) {
console.log('error while removing container', e);
container.actionError = String(e);
container.state = 'ERROR';
} finally {
container.actionInProgress = false;
containerGroups = [...containerGroups];
}
}),
);
}
bulkDeleteInProgress = false;
}
function createPodFromContainers(): void {
const selectedContainers = containerGroups
.map(group => group.containers)
.flat()
.filter(container => container.selected);
const podUtils = new PodUtils();
const podCreation = {
name: podUtils.calculateNewPodName(pods),
containers: selectedContainers.map(container => {
return { id: container.id, name: container.name, engineId: container.engineId, ports: container.ports };
}),
};
// update the store
podCreationHolder.set(podCreation);
// redirect to pod creation page
router.goto('/pod-create-from-containers');
}
let containersUnsubscribe: Unsubscriber;
let contextsUnsubscribe: Unsubscriber;
let podUnsubscribe: Unsubscriber;
let viewsUnsubscribe: Unsubscriber;
let pods: PodInfo[];
onMount(async () => {
// grab previous groups
containerGroups = get(containerGroupsInfo);
contextsUnsubscribe = context.subscribe(value => {
globalContext = value;
if (containersInfo.length > 0) {
updateContainers(containersInfo, globalContext, viewContributions, searchTerm);
}
});
viewsUnsubscribe = viewsContributions.subscribe(value => {
viewContributions = value.filter(view => view.viewId === CONTAINER_LIST_VIEW) || [];
if (containersInfo.length > 0) {
updateContainers(containersInfo, globalContext, viewContributions, searchTerm);
}
});
containersUnsubscribe = containersInfos.subscribe(value => {
updateContainers(value, globalContext, viewContributions, searchTerm);
});
podUnsubscribe = podsInfos.subscribe(podInfos => {
pods = podInfos;
});
});
/* updateContainers updates the variables:
- containersInfo with the value of containers
- containerGroups based on the containers and their groups
- multipleEngines and enginesList based on the engines of containers
*/
function updateContainers(
containers: ContainerInfo[],
globalContext: ContextUI,
viewContributions: ViewInfoUI[],
searchTerm: string,
): void {
containersInfo = containers;
const currentContainers = containers.map((containerInfo: ContainerInfo) => {
return containerUtils.getContainerInfoUI(containerInfo, globalContext, viewContributions);
});
// Map engineName, engineId and engineType from currentContainers to EngineInfoUI[]
const engines = currentContainers.map(container => {
return {
name: container.engineName,
id: container.engineId,
};
});
// Remove duplicates from engines by name
const uniqueEngines = engines.filter((engine, index, self) => index === self.findIndex(t => t.name === engine.name));
// Set the engines to the global variable for the Prune functionality button
enginesList = uniqueEngines;
// create groups
let computedContainerGroups = containerUtils.getContainerGroups(currentContainers);
// Filter containers in groups
computedContainerGroups.forEach(group => {
group.containers = group.containers
.filter(containerInfo =>
findMatchInLeaves(containerInfo, containerUtils.filterSearchTerm(searchTerm).toLowerCase()),
)
.filter(containerInfo => {
if (containerUtils.filterIsRunning(searchTerm)) {
return containerInfo.state === 'RUNNING';
}
if (containerUtils.filterIsStopped(searchTerm)) {
return containerInfo.state !== 'RUNNING';
}
return true;
});
});
// Remove groups with all containers filtered
computedContainerGroups = computedContainerGroups.filter(group => group.containers.length > 0);
// update selected items based on current selected items
computedContainerGroups.forEach(group => {
const matchingGroup = containerGroups.find(currentGroup => currentGroup.name === group.name);
if (matchingGroup) {
group.selected = matchingGroup.selected;
group.expanded = matchingGroup.expanded;
group.containers.forEach(container => {
const matchingContainer = matchingGroup.containers.find(
currentContainer => currentContainer.id === container.id,
);
if (matchingContainer) {
container.actionError = matchingContainer.actionError;
container.selected = matchingContainer.selected;
}
});
}
});
// update the value
containerGroups = computedContainerGroups;
// compute refresh interval
const interval = computeInterval();
refreshTimeouts.push(setTimeout(refreshUptime, interval));
}
onDestroy(() => {
// store current groups for later
containerGroupsInfo.set(containerGroups);
// kill timers
refreshTimeouts.forEach(timeout => clearTimeout(timeout));
refreshTimeouts.length = 0;
// unsubscribe from the store
if (containersUnsubscribe) {
containersUnsubscribe();
}
if (contextsUnsubscribe) {
contextsUnsubscribe();
}
if (podUnsubscribe) {
podUnsubscribe();
}
if (viewsUnsubscribe) {
viewsUnsubscribe();
}
});
function keydownChoice(e: KeyboardEvent): void {
e.stopPropagation();
if (e.key === 'Escape') {
toggleCreateContainer();
}
}
function toggleCreateContainer(): void {
openChoiceModal = !openChoiceModal;
}
function fromDockerfile(): void {
openChoiceModal = false;
router.goto('/images/build');
}
function resetRunningFilter(): void {
searchTerm = containerUtils.filterResetRunning(searchTerm);
}
function setRunningFilter(): void {
searchTerm = containerUtils.filterSetRunning(searchTerm);
}
function setStoppedFilter(): void {
searchTerm = containerUtils.filterSetStopped(searchTerm);
}
let selectedItemsNumber: number;
let table: Table;
let statusColumn = new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Status', {
align: 'center',
width: '70px',
renderer: ContainerColumnStatus,
});
let nameColumn = new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Name', {
width: '2fr',
renderer: ContainerColumnName,
comparator: (a, b) => a.name.localeCompare(b.name),
});
let envColumn = new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Environment', {
renderer: ContainerColumnEnvironment,
});
let imageColumn = new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Image', {
width: '3fr',
renderer: ContainerColumnImage,
});
let ageColumn = new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Age', {
renderer: ContainerColumnAge,
});
const columns: TableColumn<ContainerInfoUI | ContainerGroupInfoUI>[] = [
statusColumn,
nameColumn,
envColumn,
imageColumn,
ageColumn,
new TableColumn<ContainerInfoUI | ContainerGroupInfoUI>('Actions', {
align: 'right',
width: '150px',
renderer: ContainerColumnActions,
overflow: true,
}),
];
const row = new TableRow<ContainerGroupInfoUI | ContainerInfoUI>({
selectable: _container => true,
children: object => {
if ('type' in object && object.type !== ContainerGroupInfoTypeUI.STANDALONE) {
return object.containers;
} else {
return [];
}
},
});
let containersAndGroups: (ContainerGroupInfoUI | ContainerInfoUI)[];
$: containersAndGroups = containerGroups.map(group =>
group?.type === ContainerGroupInfoTypeUI.STANDALONE ? group.containers[0] : group,
);
</script>
<NavPage bind:searchTerm="{searchTerm}" title="containers">
<svelte:fragment slot="additional-actions">
<!-- Only show if there are containers-->
{#if $containersInfos.length > 0}
<Prune type="containers" engines="{enginesList}" />
{/if}
<Button on:click="{() => toggleCreateContainer()}" icon="{faPlusCircle}" title="Create a container">Create</Button>
</svelte:fragment>
<svelte:fragment slot="bottom-additional-actions">
{#if selectedItemsNumber > 0}
<div class="inline-flex space-x-2">
<Button
on:click="{() => deleteSelectedContainers()}"
aria-label="Delete selected containers and pods"
title="Delete {selectedItemsNumber} selected items"
bind:inProgress="{bulkDeleteInProgress}"
icon="{faTrash}">
</Button>
<Button
on:click="{() => createPodFromContainers()}"
title="Create Pod with {selectedItemsNumber} selected items"
icon="{SolidPodIcon}">
Create Pod
</Button>
</div>
<span>On {selectedItemsNumber} selected items.</span>
{/if}
</svelte:fragment>
<svelte:fragment slot="tabs">
<Button type="tab" on:click="{() => resetRunningFilter()}" selected="{containerUtils.filterIsAll(searchTerm)}"
>All</Button>
<Button type="tab" on:click="{() => setRunningFilter()}" selected="{containerUtils.filterIsRunning(searchTerm)}"
>Running</Button>
<Button type="tab" on:click="{() => setStoppedFilter()}" selected="{containerUtils.filterIsStopped(searchTerm)}"
>Stopped</Button>
</svelte:fragment>
<div class="flex min-w-full h-full" slot="content">
<Table
kind="container"
bind:this="{table}"
bind:selectedItemsNumber="{selectedItemsNumber}"
data="{containersAndGroups}"
columns="{columns}"
row="{row}"
defaultSortColumn="Name"
on:update="{() => (containerGroups = [...containerGroups])}">
</Table>
{#if providerConnections.length === 0}
<NoContainerEngineEmptyScreen />
{:else if containerGroups.length === 0}
{#if containerUtils.filterSearchTerm(searchTerm)}
<FilteredEmptyScreen
icon="{ContainerIcon}"
kind="containers"
on:resetFilter="{e => {
searchTerm = containerUtils.filterResetSearchTerm(searchTerm);
e.preventDefault();
}}"
searchTerm="{containerUtils.filterSearchTerm(searchTerm)}" />
{:else}
<ContainerEmptyScreen
runningOnly="{containerUtils.filterIsRunning(searchTerm)}"
stoppedOnly="{containerUtils.filterIsStopped(searchTerm)}" />
{/if}
{/if}
</div>
</NavPage>
{#if openChoiceModal}
<Modal
on:close="{() => {
openChoiceModal = false;
}}">
<div
role="presentation"
class="inline-block w-full overflow-hidden text-left transition-all"
on:keydown="{keydownChoice}">
<div
class="flex items-center justify-between text-[var(--pd-modal-header-text)] bg-[var(--pd-modal-header-bg)] px-5 py-4 border-b-2 border-[var(--pd-modal-header-divider)]">
<h1 class="text-xl font-bold">Create a new container</h1>
<button class="hover:text-[var(--pd-modal-text-hover)] px-2 py-1" on:click="{() => toggleCreateContainer()}">
<i class="fas fa-times" aria-hidden="true"></i>
</button>
</div>
<div class="p-5 h-full flex flex-col justify-items-center text-[var(--pd-modal-text)]">
<span class="pb-3">Choose the following:</span>
<ul class="list-disc ml-8 space-y-2">
<li>Create a container from a Containerfile</li>
<li>Create a container from an existing image stored in the local registry</li>
</ul>
<div class="pt-5 grid grid-cols-2 gap-10 place-content-center w-full">
<Button type="primary" on:click="{() => fromDockerfile()}">Containerfile or Dockerfile</Button>
<Button type="secondary" on:click="{() => fromExistingImage()}">Existing image</Button>
</div>
</div>
</div>
</Modal>
{/if}