forked from containers/podman-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeployPodToKube.svelte
607 lines (547 loc) · 21.3 KB
/
DeployPodToKube.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
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
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import MonacoEditor from '../editor/MonacoEditor.svelte';
import FormPage from '../ui/FormPage.svelte';
import * as jsYaml from 'js-yaml';
import type { V1Route } from '../../../../main/src/plugin/api/openshift-types';
import type { V1NamespaceList, V1Pod } from '@kubernetes/client-node/dist/api';
import ErrorMessage from '../ui/ErrorMessage.svelte';
import WarningMessage from '../ui/WarningMessage.svelte';
import { ensureRestrictedSecurityContext } from '/@/lib/pod/pod-utils';
import Button from '../ui/Button.svelte';
import { faExternalLink, faRocket } from '@fortawesome/free-solid-svg-icons';
import Link from '../ui/Link.svelte';
import { router } from 'tinro';
export let resourceId: string;
export let engineId: string;
export let type: string;
let kubeDetails: string;
let defaultContextName: string | undefined;
let currentNamespace: string;
let allNamespaces: V1NamespaceList;
let deployStarted = false;
let deployFinished = false;
let deployError = '';
let deployWarning = '';
let updatePodInterval: NodeJS.Timeout;
let openshiftConsoleURL: string | undefined;
let openshiftRouteGroupSupported = false;
let deployUsingServices = true;
let deployUsingRoutes = true;
let deployUsingRestrictedSecurityContext = false;
let createdPod: V1Pod | undefined = undefined;
let bodyPod: any;
let createIngress = false;
let ingressPort: number;
let containerPortArray: string[] = [];
let createdRoutes: V1Route[] = [];
onMount(async () => {
// If type = compose
// we will grab the containers by using the label com.docker.compose.project that matches the resourceId
// we can then pass the array of containers to generatePodmanKube rather than the singular pod id
if (type === 'compose') {
const containers = await window.listSimpleContainersByLabel('com.docker.compose.project', resourceId);
const containerIds = containers.map(container => container.Id);
kubeDetails = await window.generatePodmanKube(engineId, containerIds);
} else {
kubeDetails = await window.generatePodmanKube(engineId, [resourceId]);
}
// parse yaml
bodyPod = jsYaml.load(kubeDetails) as any;
// grab default context
defaultContextName = await window.kubernetesGetCurrentContextName();
// grab current namespace
const grabCurrentNamespace = await window.kubernetesGetCurrentNamespace();
// check that the variable is set to a value, otherwise set to default namespace
if (!grabCurrentNamespace) {
currentNamespace = 'default';
} else {
currentNamespace = grabCurrentNamespace;
}
// check that the variable is set to a value, otherwise set to default namespace
if (!currentNamespace) {
currentNamespace = 'default';
}
// grab all the namespaces (will be useful to provide a drop-down to select the namespace)
try {
allNamespaces = await window.kubernetesListNamespaces();
} catch (error) {
console.debug('Not able to list all namespaces, probably a permission error', error);
}
// check if there is OpenShift and then grab openshift console URL
try {
openshiftRouteGroupSupported = await window.kubernetesIsAPIGroupSupported('route.openshift.io');
const openshiftConfigMap = await window.kubernetesReadNamespacedConfigMap(
'console-public',
'openshift-config-managed',
);
openshiftConsoleURL = openshiftConfigMap?.data?.consoleURL;
} catch (error) {
// probably not OpenShift cluster, ignoring
console.debug('Probably not an OpenShift cluster, so ignoring the error to grab console link', error);
}
// Go through bodyPod.spec.containers and create a string array of port that we'll be exposing
bodyPod.spec.containers.forEach((container: any) => {
container.ports?.forEach((port: any) => {
containerPortArray.push(port.hostPort);
});
container.imagePullPolicy = 'IfNotPresent';
});
});
function openOpenshiftConsole() {
// build link to openOpenshiftConsole
if (createdPod?.metadata?.name) {
const linkToOpen = `${openshiftConsoleURL}/k8s/ns/${currentNamespace}/pods/${createdPod.metadata.name}`;
window.openExternal(linkToOpen);
}
}
async function updatePod() {
if (!createdPod?.metadata?.name || !createdPod?.metadata?.namespace) {
return;
}
const updatedPod = await window.kubernetesReadNamespacedPod(createdPod.metadata.name, createdPod.metadata.namespace);
createdPod = updatedPod;
// stop to monitor once it is running
if (createdPod?.status?.phase === 'Running') {
clearInterval(updatePodInterval);
deployFinished = true;
window.telemetryTrack('deployToKube.running', {
useServices: deployUsingServices,
useRoutes: deployUsingRoutes,
});
}
}
onDestroy(() => {
// reset any timeout
clearInterval(updatePodInterval);
});
function goBackToHistory(): void {
window.history.go(-1);
}
function openPodDetails(): void {
if (!createdPod?.metadata?.name || !defaultContextName) {
return;
}
router.goto(`/pods/kubernetes/${encodeURI(createdPod.metadata.name)}/${encodeURI(defaultContextName)}/logs`);
}
function openRoute(route: V1Route) {
window.openExternal(`https://${route.spec.host}`);
}
async function deployToKube() {
deployStarted = true;
deployFinished = false;
deployError = '';
deployWarning = '';
createdPod = undefined;
// reset any timeout
clearInterval(updatePodInterval);
createdRoutes = [];
let servicesToCreate: any[] = [];
let routesToCreate: any[] = [];
let ingressesToCreate: any[] = [];
// if we deploy using services, we need to get rid of .hostPort and generate kubernetes services object
if (deployUsingServices) {
// collect all ports
bodyPod.spec?.containers?.forEach((container: any) => {
container?.ports?.forEach((port: any) => {
let portName = `${bodyPod.metadata.name}-${port.hostPort}`;
if (port.hostPort) {
// create service
const service = {
apiVersion: 'v1',
kind: 'Service',
metadata: {
name: portName,
namespace: currentNamespace,
},
spec: {
ports: [
{
name: portName,
port: port.hostPort,
protocol: port.protocol || 'TCP',
targetPort: port.containerPort,
},
],
selector: {
app: bodyPod.metadata.name,
},
},
};
servicesToCreate.push(service);
if (openshiftRouteGroupSupported && deployUsingRoutes) {
// Create OpenShift route object
const route = {
apiVersion: 'route.openshift.io/v1',
kind: 'Route',
metadata: {
name: `${bodyPod.metadata.name}-${port.hostPort}`,
namespace: currentNamespace,
},
spec: {
port: {
targetPort: port.containerPort,
},
to: {
kind: 'Service',
name: `${bodyPod.metadata.name}-${port.hostPort}`,
},
tls: {
termination: 'edge',
},
},
};
routesToCreate.push(route);
}
}
});
});
}
// Check if we are deploying an ingress, if so, we need to create an ingress object using ingressPath and ingressDomain.
if (createIngress) {
let serviceName = '';
let servicePort = 0;
// Check that there are services (servicesToCreate), if there aren't. Warn that we can't create an ingress.
// All services are always created with one port (the first one), so we can use that port to create the ingress.
// Must be a number
if (servicesToCreate.length === 0) {
deployWarning = `In order to create an Ingress a Pod must have a Service associated to a port mapping. Check that your container(s) has a port exposed correctly in order to generate a Service.`;
deployStarted = false;
return;
} else if (servicesToCreate.length === 1) {
serviceName = servicesToCreate[0].metadata.name;
servicePort = servicesToCreate[0].spec.ports[0].port;
} else if (servicesToCreate.length > 1) {
// If there was more than one service being created, the user would of had a dialog to pick which port to use
// warn out if the user did not pick anything (we do not do form validation for this as we're using svelte for the form)
if (!ingressPort) {
deployWarning = 'You need to specify a port to create an ingress.';
deployStarted = false;
return;
}
const matchingService = servicesToCreate.find(service => service.spec.ports[0].port === ingressPort);
if (matchingService) {
serviceName = matchingService.metadata.name;
servicePort = matchingService.spec.ports[0].port;
} else {
deployError = 'Unable to find the service that matches the port you want to expose.';
return;
}
}
const ingress = {
apiVersion: 'networking.k8s.io/v1',
kind: 'Ingress',
metadata: {
name: bodyPod.metadata.name,
namespace: currentNamespace,
},
spec: {
defaultBackend: {
service: {
name: serviceName,
port: {
number: servicePort,
},
},
},
},
};
// Support for multiple ingress creation in the future
ingressesToCreate.push(ingress);
}
// https://github.com/kubernetes-client/javascript/issues/487
if (bodyPod?.metadata?.creationTimestamp) {
bodyPod.metadata.creationTimestamp = new Date(bodyPod.metadata.creationTimestamp);
}
const eventProperties: any = {
useServices: deployUsingServices,
useRoutes: deployUsingRoutes,
createIngress: createIngress,
};
if (openshiftRouteGroupSupported) {
eventProperties['isOpenshift'] = true;
}
let previousPod = bodyPod;
try {
// In order to deploy to Kubernetes, we must remove volumes for the pod as we do not support them
// if we are deploying using services, remove the hostPort as well as volumeMounts from the container
if (bodyPod?.spec?.volumes) {
delete bodyPod.spec.volumes;
}
if (deployUsingServices) {
bodyPod.spec?.containers?.forEach((container: any) => {
// UNUSED
// Delete all volume mounts
if (container.volumeMounts) {
delete container.volumeMounts;
}
// UNUSED
// Delete all hostPorts
if (container.ports) {
container.ports.forEach((port: any) => {
delete port.hostPort;
});
}
});
}
if (deployUsingRestrictedSecurityContext) {
ensureRestrictedSecurityContext(bodyPod);
}
// create pod
createdPod = await window.kubernetesCreatePod(currentNamespace, bodyPod);
// create services
for (const service of servicesToCreate) {
await window.kubernetesCreateService(currentNamespace, service);
}
// Create routes
for (const route of routesToCreate) {
const createdRoute = await window.openshiftCreateRoute(currentNamespace, route);
createdRoutes = [...createdRoutes, createdRoute];
}
// Create ingresses
for (const ingress of ingressesToCreate) {
await window.kubernetesCreateIngress(currentNamespace, ingress);
}
// Telemetry
window.telemetryTrack('deployToKube', eventProperties);
// update status
updatePodInterval = setInterval(() => {
updatePod();
}, 2000);
} catch (error: any) {
// Revert back to the previous bodyPod so the user can hit deploy again
// we only update the bodyPod if we successfully create the pod.
bodyPod = previousPod;
window.telemetryTrack('deployToKube', { ...eventProperties, errorMessage: error.message });
deployError = error;
deployStarted = false;
deployFinished = false;
return;
}
}
$: bodyPod && updateKubeResult();
// Update bodyPod.metadata.labels.app to be the same as bodyPod.metadata.name
// If statement required as bodyPod.metadata is undefined when bodyPod is undefined
$: {
if (bodyPod?.metadata?.labels) {
bodyPod.metadata.labels.app = bodyPod.metadata.name;
}
}
function updateKubeResult() {
kubeDetails = jsYaml.dump(bodyPod, { noArrayIndent: true, quotingType: '"', lineWidth: -1 });
}
</script>
<FormPage title="Deploy generated pod to Kubernetes" inProgress="{deployStarted && !deployFinished}">
<i class="fas fa-rocket fa-2x" slot="icon" aria-hidden="true"></i>
<div slot="content" class="p-5 min-w-full h-fit">
<div class="bg-charcoal-600 p-5">
{#if kubeDetails}
<p>Generated Kubernetes YAML:</p>
<div class="h-48 pt-2">
<MonacoEditor content="{kubeDetails}" language="yaml" />
</div>
{/if}
{#if bodyPod}
<div class="pt-2 pb-4">
<label for="contextToUse" class="block mb-1 text-sm font-medium text-gray-400">Pod Name:</label>
<input
type="text"
bind:value="{bodyPod.metadata.name}"
name="podName"
id="podName"
class=" cursor-default w-full p-2 outline-none text-sm bg-charcoal-800 rounded-sm text-gray-700 placeholder-gray-700"
required />
</div>
{/if}
<div class="pt-2 pb-4">
<label for="services" class="block mb-1 text-sm font-medium text-gray-300">Kubernetes Services:</label>
<input
type="checkbox"
bind:checked="{deployUsingServices}"
name="useServices"
id="useServices"
class=""
required />
<span class="text-gray-400 text-sm ml-1"
>Replace .hostPort exposure on containers by Services. It is the recommended way to expose ports, as a cluster
policy may prevent to use hostPort.</span>
</div>
<div class="pt-2 pb-4">
<label for="useRestricted" class="block mb-1 text-sm font-medium text-gray-300"
>Restricted Security Context:</label>
<input
type="checkbox"
bind:checked="{deployUsingRestrictedSecurityContext}"
name="useRestricted"
id="useRestricted"
data-testid="useRestricted"
class=""
required />
<span class="text-gray-400 text-sm ml-1">
Update Kubernetes manifest to respect the Pod security <Link
externalRef="https://kubernetes.io/docs/concepts/security/pod-security-standards#restricted"
>restricted profile</Link
>.</span>
</div>
<!-- Only show for non-OpenShift deployments (we use routes for OpenShift) -->
{#if !openshiftRouteGroupSupported && deployUsingServices}
<div class="pt-2 pb-4">
<label for="createIngress" class="block mb-1 text-sm font-medium text-gray-300"
>Expose Service Locally Using Kubernetes Ingress:</label>
<input
type="checkbox"
bind:checked="{createIngress}"
name="createIngress"
id="createIngress"
class=""
required />
<span class="text-gray-300 text-sm ml-1">
Create an Ingress to get access to the local ports exposed, at the default Ingress Controller location.
Example: On default kind cluster created with Podman Desktop, it will be accessible at 'localhost:9090'.
Requirements: Your cluster must have an Ingress Controller.</span>
</div>
{/if}
{#if createIngress && containerPortArray.length > 1}
<div class="pt-2 pb-4">
<label for="ingress" class="block mb-1 text-sm font-medium text-gray-300">Ingress Host Port:</label>
<select
bind:value="{ingressPort}"
name="serviceName"
id="serviceName"
class=" cursor-default w-full p-2 outline-none text-sm bg-charcoal-800 rounded-sm text-gray-400 placeholder-gray-400"
required>
<option value="" disabled selected>Select a port</option>
{#each containerPortArray as port}
<option value="{port}">{port}</option>
{/each}
</select>
<span class="text-gray-300 text-sm ml-1"
>There are multiple exposed ports available. Select the one you want to expose to '/' with the Ingress.
</span>
</div>
{/if}
<!-- Allow to create routes for OpenShift clusters -->
{#if openshiftRouteGroupSupported}
<div class="pt-2 m-2">
<label for="routes" class="block mb-1 text-sm font-medium text-gray-400">Create OpenShift routes:</label>
<input type="checkbox" bind:checked="{deployUsingRoutes}" name="useRoutes" id="useRoutes" class="" required />
<span class="text-gray-400 text-sm ml-1"
>Create OpenShift routes to get access to the exposed ports of this pod.</span>
</div>
{/if}
{#if defaultContextName}
<div class="pt-2">
<label for="contextToUse" class="block mb-1 text-sm font-medium text-gray-400">Kubernetes Context:</label>
<input
type="text"
bind:value="{defaultContextName}"
name="defaultContextName"
id="defaultContextName"
readonly
class="cursor-default w-full p-2 outline-none text-sm bg-charcoal-800 rounded-sm text-gray-700 placeholder-gray-700"
required />
</div>
{/if}
{#if allNamespaces}
<div class="pt-2">
<label for="namespaceToUse" class="block mb-1 text-sm font-medium text-gray-400">Kubernetes Namespace:</label>
<select
class="w-full p-2 outline-none text-sm bg-charcoal-800 rounded-sm text-gray-700 placeholder-gray-700"
name="namespaceChoice"
bind:value="{currentNamespace}">
{#each allNamespaces.items as namespace}
<option value="{namespace.metadata?.name}">
{namespace.metadata?.name}
</option>
{/each}
</select>
</div>
{/if}
{#if deployWarning}
<WarningMessage class="text-sm" error="{deployWarning}" />
{/if}
{#if deployError}
<ErrorMessage class="text-sm" error="{deployError}" />
{/if}
{#if !deployStarted}
<div class="pt-4">
<Button
on:click="{() => deployToKube()}"
class="w-full"
icon="{faRocket}"
disabled="{bodyPod?.metadata?.name === ''}">
Deploy
</Button>
</div>
{/if}
{#if createdPod}
<div class="bg-charcoal-800 p-5 my-4">
<div class="flex flex-row items-center">
<div>Created pod:</div>
{#if openshiftConsoleURL && createdPod?.metadata?.name}
<div class="justify-end flex flex-1">
<Link class="text-sm" icon="{faExternalLink}" on:click="{() => openOpenshiftConsole()}"
>Open in OpenShift console</Link>
</div>
{/if}
</div>
<div class="text-gray-700">
{#if createdPod.metadata?.name}
<p class="pt-2">Name: {createdPod.metadata.name}</p>
{/if}
{#if createdPod.status?.phase}
<p class="pt-2">Phase: {createdPod.status.phase}</p>
{/if}
{#if createdPod.status?.containerStatuses}
<p class="pt-2">Container statuses:</p>
<ul class="list-disc list-inside">
{#each createdPod.status.containerStatuses as containerStatus}
<li class="pt-2">
{containerStatus.name}
{#if containerStatus.ready}
<span class="text-gray-900">Ready</span>
{/if}
{#if containerStatus.state?.running}
<span class="text-green-400">(Running)</span>
{/if}
{#if containerStatus.state?.terminated}
<span class="text-red-500">(Terminated)</span>
{/if}
{#if containerStatus.state?.waiting}
<span class="text-amber-500">(Waiting)</span>
{#if containerStatus.state.waiting.reason}
<span class="text-amber-500">[{containerStatus.state.waiting.reason}]</span>
{/if}
{/if}
</li>
{/each}
</ul>
{/if}
{#if createdRoutes && createdRoutes.length > 0}
<p class="pt-2">Endpoints:</p>
<ul class="list-disc list-inside">
{#each createdRoutes as createdRoute}
<li class="pt-2">
Port {createdRoute.spec.port?.targetPort} is reachable with route
<Link on:click="{() => openRoute(createdRoute)}">{createdRoute.metadata.name}</Link>
</li>
{/each}
</ul>
{/if}
</div>
<!-- add editor for the result-->
<div class="h-[100px] pt-2">
<MonacoEditor content="{jsYaml.dump(createdPod)}" language="yaml" />
</div>
</div>
{/if}
{#if deployFinished}
<div class="pt-4 flex flex-row space-x-2 justify-end">
<Button on:click="{() => goBackToHistory()}">Done</Button>
<Button on:click="{() => openPodDetails()}" disabled="{!createdPod?.metadata?.name || !defaultContextName}"
>Open Pod</Button>
</div>
{/if}
</div>
</div>
</FormPage>