-
Notifications
You must be signed in to change notification settings - Fork 268
/
PreferencesConnectionCreationRendering.svelte
468 lines (430 loc) · 14.8 KB
/
PreferencesConnectionCreationRendering.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
<script lang="ts">
import type { IConfigurationPropertyRecordedSchema } from '../../../../main/src/plugin/configuration-registry';
import type { ProviderInfo } from '../../../../main/src/plugin/api/provider-info';
import PreferencesRenderingItemFormat from './PreferencesRenderingItemFormat.svelte';
import TerminalWindow from '../ui/TerminalWindow.svelte';
import { getNormalizedDefaultNumberValue, writeToTerminal, isPropertyValidInContext } from './Util';
import ErrorMessage from '../ui/ErrorMessage.svelte';
import {
clearCreateTask,
type ConnectionCallback,
disconnectUI,
eventCollect,
reconnectUI,
startTask,
} from './preferences-connection-rendering-task';
/* eslint-disable import/no-duplicates */
// https://github.com/import-js/eslint-plugin-import/issues/1479
import { get, type Unsubscriber } from 'svelte/store';
import { onDestroy, onMount } from 'svelte';
/* eslint-enable import/no-duplicates */
import { createConnectionsInfo } from '/@/stores/create-connections';
import { filesize } from 'filesize';
import { router } from 'tinro';
import LinearProgress from '../ui/LinearProgress.svelte';
import Spinner from '../ui/Spinner.svelte';
import Markdown from '../markdown/Markdown.svelte';
import type { Terminal } from 'xterm';
import type { AuditRequestItems, AuditResult } from '@podman-desktop/api';
import AuditMessageBox from '../ui/AuditMessageBox.svelte';
import EmptyScreen from '../ui/EmptyScreen.svelte';
import { faCubes } from '@fortawesome/free-solid-svg-icons';
import Button from '../ui/Button.svelte';
import type { ContextUI } from '/@/lib/context/context';
import { context } from '/@/stores/context';
export let properties: IConfigurationPropertyRecordedSchema[] = [];
export let providerInfo: ProviderInfo;
export let propertyScope: string;
export let callback: (
param: string,
data: any,
handlerKey: symbol,
collect: (key: symbol, eventName: 'log' | 'warn' | 'error' | 'finish', args: string[]) => void,
tokenId?: number,
) => Promise<void>;
export let taskId: number | undefined = undefined;
export let disableEmptyScreen = false;
export let hideProviderImage = false;
export let hideCloseButton = false;
$: configurationValues = new Map<string, string>();
let creationInProgress = false;
let creationStarted = false;
let creationSuccessful = false;
let creationCancelled = false;
let creationFailed = false;
export let pageIsLoading = true;
let showLogs = false;
let tokenId: number | undefined;
const providerDisplayName =
(providerInfo.containerProviderConnectionCreation
? providerInfo.containerProviderConnectionCreationDisplayName || undefined
: providerInfo.kubernetesProviderConnectionCreation
? providerInfo.kubernetesProviderConnectionCreationDisplayName
: undefined) || providerInfo.name;
let osMemory: string;
let osCpu: string;
let osFreeDisk: string;
// get only ContainerProviderConnectionFactory scope fields that are starting by the provider id
let configurationKeys: IConfigurationPropertyRecordedSchema[] = [];
let isValid = true;
let errorMessage: string | undefined = undefined;
let formEl: HTMLFormElement;
let globalContext: ContextUI;
let connectionAuditResult: AuditResult | undefined;
$: connectionAuditResult = undefined;
let contextsUnsubscribe: Unsubscriber;
// reconnect the logger handler
$: if (logsTerminal && loggerHandlerKey) {
try {
reconnectUI(loggerHandlerKey, getLoggerHandler());
} catch (error) {
console.error('error while reconnecting', error);
}
}
onMount(async () => {
osMemory = await window.getOsMemory();
osCpu = await window.getOsCpu();
osFreeDisk = await window.getOsFreeDiskSize();
contextsUnsubscribe = context.subscribe(value => (globalContext = value));
configurationKeys = properties
.filter(property => property.scope === propertyScope)
.filter(property => property.id?.startsWith(providerInfo.id))
.filter(property => isPropertyValidInContext(property.when, globalContext))
.map(property => {
switch (property.maximum) {
case 'HOST_TOTAL_DISKSIZE': {
if (osFreeDisk) {
property.maximum = osFreeDisk;
}
break;
}
case 'HOST_TOTAL_MEMORY': {
if (osMemory) {
property.maximum = osMemory;
}
break;
}
case 'HOST_TOTAL_CPU': {
if (osCpu) {
property.maximum = osCpu;
}
break;
}
default: {
break;
}
}
return property;
});
pageIsLoading = false;
// check if we have an existing create action
const createConnectionInfoMap = get(createConnectionsInfo);
if (taskId && createConnectionInfoMap && createConnectionInfoMap.has(taskId)) {
const value = createConnectionInfoMap.get(taskId);
if (value) {
loggerHandlerKey = value.createKey;
providerInfo = value.providerInfo;
properties = value.properties;
propertyScope = value.propertyScope;
// set the flag as before
creationInProgress = value.creationInProgress;
creationStarted = value.creationStarted;
errorMessage = value.errorMessage;
creationSuccessful = value.creationSuccessful;
tokenId = value.tokenId;
}
}
if (taskId === undefined) {
taskId = createConnectionInfoMap.size + 1;
}
const data: any = {};
for (let field of configurationKeys) {
const id = field.id;
if (id) {
data[id] = field.default;
}
}
try {
connectionAuditResult = await window.auditConnectionParameters(providerInfo.internalId, data);
} catch (e: any) {
console.warn(e.message);
}
});
onDestroy(() => {
if (loggerHandlerKey) {
disconnectUI(loggerHandlerKey);
}
if (contextsUnsubscribe) {
contextsUnsubscribe();
}
});
function handleInvalidComponent() {
isValid = false;
}
async function handleValidComponent() {
isValid = true;
const formData = new FormData(formEl);
const data: { [key: string]: FormDataEntryValue } = {};
for (let field of formData) {
const [key, value] = field;
data[key] = value;
}
try {
connectionAuditResult = await window.auditConnectionParameters(providerInfo.internalId, data as AuditRequestItems);
} catch (err: unknown) {
if (err instanceof Error) {
console.warn(err.message);
} else {
console.warn(String(err));
}
}
}
function setConfigurationValue(id: string, value: string) {
configurationValues.set(id, value);
configurationValues = configurationValues;
}
function getDisplayConfigurationValue(configurationKey: IConfigurationPropertyRecordedSchema, value?: any) {
if (configurationKey.format === 'memory' || configurationKey.format === 'diskSize') {
return value ? filesize(value) : filesize(getNormalizedDefaultNumberValue(configurationKey));
} else if (configurationKey.format === 'cpu') {
return value ? value : getNormalizedDefaultNumberValue(configurationKey);
} else {
return '';
}
}
let logsTerminal: Terminal;
let loggerHandlerKey: symbol | undefined = undefined;
function getLoggerHandler(): ConnectionCallback {
return {
log: args => {
writeToTerminal(logsTerminal, args, '\x1b[37m');
},
warn: args => {
writeToTerminal(logsTerminal, args, '\x1b[33m');
},
error: args => {
creationFailed = true;
writeToTerminal(logsTerminal, args, '\x1b[1;31m');
},
onEnd: () => {
ended();
},
};
}
async function ended() {
creationInProgress = false;
tokenId = undefined;
if (!creationCancelled && !creationFailed) {
window.dispatchEvent(new CustomEvent('provider-lifecycle-change'));
creationSuccessful = true;
}
updateStore();
}
async function cleanup() {
// clear
if (loggerHandlerKey) {
clearCreateTask(loggerHandlerKey);
loggerHandlerKey = undefined;
}
errorMessage = undefined;
showLogs = false;
creationInProgress = false;
creationStarted = false;
creationFailed = false;
creationCancelled = false;
creationSuccessful = false;
updateStore();
logsTerminal?.clear();
}
// store the key
function updateStore() {
createConnectionsInfo.update(map => {
if (taskId && loggerHandlerKey) {
map.set(taskId, {
createKey: loggerHandlerKey,
providerInfo,
properties,
propertyScope,
creationInProgress,
creationSuccessful,
creationStarted,
errorMessage: errorMessage || '',
tokenId,
});
}
return map;
});
}
async function handleOnSubmit(e: any) {
errorMessage = undefined;
const formData = new FormData(e.target);
const data: { [key: string]: FormDataEntryValue } = {};
for (let field of formData) {
const [key, value] = field;
data[key] = value;
}
// send the data to the right provider
creationInProgress = true;
creationStarted = true;
creationFailed = false;
creationCancelled = false;
try {
tokenId = await window.getCancellableTokenSource();
// clear terminal
logsTerminal?.clear();
loggerHandlerKey = startTask(
`Create ${providerDisplayName}`,
`/preferences/provider-task/${providerInfo.internalId}/${taskId}`,
getLoggerHandler(),
);
updateStore();
await callback(providerInfo.internalId, data, loggerHandlerKey, eventCollect, tokenId);
} catch (error: any) {
//display error
tokenId = undefined;
// filter cancellation message to avoid displaying error and allow user to restart the creation
if (error.message && error.message.indexOf('Execution cancelled') >= 0) {
errorMessage = 'Action cancelled. See logs for more details';
return;
}
errorMessage = error;
}
}
async function cancelCreation() {
if (tokenId) {
await window.cancelToken(tokenId);
creationCancelled = true;
tokenId = undefined;
}
window.telemetryTrack('createNewProviderConnectionRequestUserCanceled', {
providerId: providerInfo.id,
name: providerInfo.name,
});
}
async function closePanel() {
cleanup();
}
function closePage() {
router.goto('/preferences/resources');
window.telemetryTrack('createNewProviderConnectionPageUserClosed', {
providerId: providerInfo.id,
name: providerInfo.name,
});
}
</script>
<div class="flex flex-col w-full h-full overflow-hidden">
{#if creationSuccessful && !disableEmptyScreen}
<EmptyScreen icon="{faCubes}" title="Creation" message="Successful operation">
<Button
class="py-3"
on:click="{() => {
cleanup();
router.goto('/preferences/resources');
}}">
Go back to resources
</Button>
</EmptyScreen>
{:else}
{#if !hideProviderImage}
<div class="my-2 px-6" aria-label="main image">
{#if providerInfo?.images?.icon}
{#if typeof providerInfo.images.icon === 'string'}
<img src="{providerInfo.images.icon}" alt="{providerInfo.name}" class="max-h-10" />
<!-- TODO check theme used for image, now use dark by default -->
{:else}
<img src="{providerInfo.images.icon.dark}" alt="{providerInfo.name}" class="max-h-10" />
{/if}
{/if}
</div>
{/if}
<h1 class="font-semibold px-6 pb-2" aria-label="title">
{creationInProgress ? 'Creating' : 'Create a'}
{providerDisplayName}
{creationInProgress ? '...' : ''}
</h1>
<div class="flex flex-col px-6 w-full h-full overflow-auto">
{#if pageIsLoading}
<div class="text-center mt-16 p-2" role="status">
<Spinner size="2em" />
</div>
{:else}
{#if creationStarted}
<div class="w-4/5">
<div class="mt-2 mb-8">
{#if creationInProgress}
<LinearProgress />
{/if}
<div class="mt-2 float-right">
<button
aria-label="Show Logs"
class="text-xs mr-3 hover:underline"
on:click="{() => (showLogs = !showLogs)}"
>Show Logs <i class="fas {showLogs ? 'fa-angle-up' : 'fa-angle-down'}" aria-hidden="true"></i
></button>
<button
aria-label="Cancel creation"
class="text-xs {errorMessage ? 'mr-3' : ''} hover:underline {tokenId ? '' : 'hidden'}"
disabled="{!tokenId}"
on:click="{cancelCreation}">Cancel</button>
<button
class="text-xs hover:underline {creationInProgress ? 'hidden' : ''}"
aria-label="Close panel"
on:click="{closePanel}">Close</button>
</div>
</div>
<div id="log" class="pt-2 h-80 {showLogs ? '' : 'hidden'}">
<div class="w-full h-full">
<TerminalWindow bind:terminal="{logsTerminal}" />
</div>
</div>
</div>
{/if}
{#if errorMessage}
<div class="w-4/5 mt-2">
<ErrorMessage error="{errorMessage}" />
</div>
{/if}
<div class="p-3 mt-2 w-4/5 h-fit {creationInProgress ? 'opacity-40 pointer-events-none' : ''}">
{#if connectionAuditResult && (connectionAuditResult.records?.length || 0) > 0}
<AuditMessageBox auditResult="{connectionAuditResult}" />
{/if}
<form novalidate class="p-2 space-y-7 h-fit" on:submit|preventDefault="{handleOnSubmit}" bind:this="{formEl}">
{#each configurationKeys as configurationKey}
<div class="mb-2.5">
<div class="font-semibold text-xs">
{#if configurationKey.description}
{configurationKey.description}:
{:else if configurationKey.markdownDescription && configurationKey.type !== 'markdown'}
<Markdown>{configurationKey.markdownDescription}:</Markdown>
{/if}
{#if configurationKey.id && configurationValues.has(configurationKey.id)}
{getDisplayConfigurationValue(configurationKey, configurationValues.get(configurationKey.id))}
{:else}
{getDisplayConfigurationValue(configurationKey)}
{/if}
</div>
<PreferencesRenderingItemFormat
invalidRecord="{handleInvalidComponent}"
validRecord="{handleValidComponent}"
record="{configurationKey}"
setRecordValue="{setConfigurationValue}"
enableSlider="{true}" />
</div>
{/each}
<div class="w-full">
<div class="float-right">
{#if !hideCloseButton}
<Button type="link" aria-label="Close page" on:click="{closePage}">Close</Button>
{/if}
<Button
disabled="{!isValid}"
inProgress="{creationInProgress}"
on:click="{() => formEl.requestSubmit()}">Create</Button>
</div>
</div>
</form>
</div>
{/if}
</div>
{/if}
</div>