@highstate/k8s 0.19.1 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/chunk-23vn2rdc.js +11 -0
  2. package/dist/chunk-2pfx13ay.js +11 -0
  3. package/dist/chunk-46ntav0c.js +299 -0
  4. package/dist/chunk-556pc9e6.js +155 -0
  5. package/dist/chunk-7kgjgcft.js +170 -0
  6. package/dist/{chunk-LGHFSXNT.js → chunk-9hs97f1q.js} +23 -17
  7. package/dist/chunk-aame3x1b.js +11 -0
  8. package/dist/chunk-b05q6fm2.js +37 -0
  9. package/dist/chunk-bmvc9d2d.js +11 -0
  10. package/dist/chunk-de82bbp2.js +7 -0
  11. package/dist/chunk-facs31cb.js +624 -0
  12. package/dist/chunk-h1b79v66.js +1425 -0
  13. package/dist/chunk-k4w9zpn5.js +215 -0
  14. package/dist/chunk-pqc6w52f.js +352 -0
  15. package/dist/chunk-qyshvz32.js +176 -0
  16. package/dist/chunk-tpfyj6fe.js +199 -0
  17. package/dist/chunk-z6bmpnm7.js +180 -0
  18. package/dist/highstate.manifest.json +3 -2
  19. package/dist/impl/dynamic-endpoint-resolver.js +91 -0
  20. package/dist/impl/gateway-route.js +226 -166
  21. package/dist/impl/tls-certificate.js +31 -31
  22. package/dist/index.js +293 -166
  23. package/dist/units/cert-manager/index.js +19 -14
  24. package/dist/units/cluster-patch/index.js +14 -13
  25. package/dist/units/dns01-issuer/index.js +82 -42
  26. package/dist/units/existing-cluster/index.js +59 -26
  27. package/dist/units/gateway-api/index.js +15 -16
  28. package/dist/units/reduced-access-cluster/index.js +32 -36
  29. package/package.json +23 -21
  30. package/src/cluster.ts +12 -8
  31. package/src/config-map.ts +15 -5
  32. package/src/container.ts +4 -2
  33. package/src/cron-job.ts +51 -5
  34. package/src/deployment.ts +49 -18
  35. package/src/gateway/backend.ts +3 -3
  36. package/src/gateway/gateway.ts +12 -56
  37. package/src/helm.ts +354 -22
  38. package/src/impl/dynamic-endpoint-resolver.ts +109 -0
  39. package/src/impl/gateway-route.ts +231 -57
  40. package/src/impl/tls-certificate.ts +8 -3
  41. package/src/index.ts +1 -0
  42. package/src/job.ts +38 -6
  43. package/src/kubectl.ts +166 -0
  44. package/src/namespace.ts +47 -3
  45. package/src/network-policy.ts +1 -1
  46. package/src/pvc.ts +12 -2
  47. package/src/rbac.ts +28 -5
  48. package/src/scripting/bundle.ts +21 -98
  49. package/src/scripting/environment.ts +4 -10
  50. package/src/secret.ts +15 -5
  51. package/src/service.ts +28 -6
  52. package/src/shared.ts +31 -3
  53. package/src/stateful-set.ts +49 -18
  54. package/src/tls.ts +31 -5
  55. package/src/units/cluster-patch/index.ts +5 -5
  56. package/src/units/dns01-issuer/index.ts +56 -12
  57. package/src/units/existing-cluster/index.ts +36 -15
  58. package/src/units/reduced-access-cluster/index.ts +6 -3
  59. package/src/worker.ts +4 -2
  60. package/src/workload.ts +474 -217
  61. package/LICENSE +0 -21
  62. package/dist/chunk-4G6LLC2X.js +0 -240
  63. package/dist/chunk-4G6LLC2X.js.map +0 -1
  64. package/dist/chunk-BR2CLUUD.js +0 -230
  65. package/dist/chunk-BR2CLUUD.js.map +0 -1
  66. package/dist/chunk-DCUMJSO6.js +0 -427
  67. package/dist/chunk-DCUMJSO6.js.map +0 -1
  68. package/dist/chunk-FE4SHRAJ.js +0 -286
  69. package/dist/chunk-FE4SHRAJ.js.map +0 -1
  70. package/dist/chunk-HH2JJELM.js +0 -13
  71. package/dist/chunk-HH2JJELM.js.map +0 -1
  72. package/dist/chunk-KMLRI5UZ.js +0 -155
  73. package/dist/chunk-KMLRI5UZ.js.map +0 -1
  74. package/dist/chunk-LGHFSXNT.js.map +0 -1
  75. package/dist/chunk-MIC2BHGS.js +0 -301
  76. package/dist/chunk-MIC2BHGS.js.map +0 -1
  77. package/dist/chunk-OBDQONMV.js +0 -401
  78. package/dist/chunk-OBDQONMV.js.map +0 -1
  79. package/dist/chunk-P2VOUU7E.js +0 -1626
  80. package/dist/chunk-P2VOUU7E.js.map +0 -1
  81. package/dist/chunk-PZ5AY32C.js +0 -9
  82. package/dist/chunk-PZ5AY32C.js.map +0 -1
  83. package/dist/chunk-RVB4WWZZ.js +0 -267
  84. package/dist/chunk-RVB4WWZZ.js.map +0 -1
  85. package/dist/chunk-TWBMG6TD.js +0 -315
  86. package/dist/chunk-TWBMG6TD.js.map +0 -1
  87. package/dist/chunk-VCXWCZ43.js +0 -279
  88. package/dist/chunk-VCXWCZ43.js.map +0 -1
  89. package/dist/chunk-YIJUVPU2.js +0 -297
  90. package/dist/chunk-YIJUVPU2.js.map +0 -1
  91. package/dist/cron-job-NX4HD4FI.js +0 -8
  92. package/dist/cron-job-NX4HD4FI.js.map +0 -1
  93. package/dist/deployment-O2LJ5WR5.js +0 -8
  94. package/dist/deployment-O2LJ5WR5.js.map +0 -1
  95. package/dist/impl/gateway-route.js.map +0 -1
  96. package/dist/impl/tls-certificate.js.map +0 -1
  97. package/dist/index.js.map +0 -1
  98. package/dist/job-SYME6Y43.js +0 -8
  99. package/dist/job-SYME6Y43.js.map +0 -1
  100. package/dist/stateful-set-VJYKTQ72.js +0 -8
  101. package/dist/stateful-set-VJYKTQ72.js.map +0 -1
  102. package/dist/units/cert-manager/index.js.map +0 -1
  103. package/dist/units/cluster-patch/index.js.map +0 -1
  104. package/dist/units/dns01-issuer/index.js.map +0 -1
  105. package/dist/units/existing-cluster/index.js.map +0 -1
  106. package/dist/units/gateway-api/index.js.map +0 -1
  107. package/dist/units/reduced-access-cluster/index.js.map +0 -1
@@ -1,1626 +0,0 @@
1
- import { isEndpointFromCluster, mapServiceToLabelSelector, Service, mapContainerPortToServicePort } from './chunk-TWBMG6TD.js';
2
- import { Secret } from './chunk-4G6LLC2X.js';
3
- import { commonExtraArgs, NamespacedResource, Namespace, mapMetadata, getProvider, mapSelectorLikeToSelector, getProviderAsync, mapNamespaceNameToSelector, getNamespaceName, images_exports } from './chunk-OBDQONMV.js';
4
- import { z, getOrCreate, trimIndentation } from '@highstate/contract';
5
- import { ComponentResource, toPromise, output as output$1, interpolate as interpolate$1, normalize, normalizeInputs, fileFromString } from '@highstate/pulumi';
6
- import { core, networking } from '@pulumi/kubernetes';
7
- import { output, interpolate } from '@pulumi/pulumi';
8
- import { deepmerge } from 'deepmerge-ts';
9
- import { omit, concat, map, groupBy, isNonNullish, mergeDeep, uniqueBy, flat, merge, filter, unique } from 'remeda';
10
- import { ImplementationMediator, parseEndpoint, addressToCidr, endpointToString, l3EndpointToCidr, AccessPointRoute, mergeEndpoints } from '@highstate/common';
11
- import { sha256 } from 'crypto-hash';
12
-
13
- var ConfigMap = class _ConfigMap extends NamespacedResource {
14
- constructor(type, name, args, opts, metadata, namespace, data) {
15
- super(type, name, args, opts, metadata, namespace);
16
- this.data = data;
17
- }
18
- static apiVersion = "v1";
19
- static kind = "ConfigMap";
20
- /**
21
- * The Highstate config map entity.
22
- */
23
- get entity() {
24
- return output(this.entityBase);
25
- }
26
- /**
27
- * Creates a new config map.
28
- */
29
- static create(name, args, opts) {
30
- return new CreatedConfigMap(name, args, opts);
31
- }
32
- /**
33
- * Creates a new config map or patches an existing one.
34
- *
35
- * @param name The name of the resource. May not be the same as the config map name.
36
- * @param args The arguments to create or patch the config map with.
37
- * @param opts Optional resource options.
38
- */
39
- static createOrPatch(name, args, opts) {
40
- if (args.existing) {
41
- return new ConfigMapPatch(name, {
42
- ...args,
43
- name: output(args.existing).metadata.name
44
- });
45
- }
46
- return new CreatedConfigMap(name, args, opts);
47
- }
48
- /**
49
- * Creates a new config map or gets an existing one.
50
- *
51
- * @param name The name of the resource. May not be the same as the config map name. Will not be used when existing config map is retrieved.
52
- * @param args The arguments to create or get the config map with.
53
- * @param opts Optional resource options.
54
- */
55
- static async createOrGet(name, args, opts) {
56
- if (args.existing) {
57
- return await _ConfigMap.forAsync(args.existing, output(args.namespace).cluster);
58
- }
59
- return new CreatedConfigMap(name, args, opts);
60
- }
61
- /**
62
- * Patches an existing config map.
63
- *
64
- * Will throw an error if the config map does not exist.
65
- *
66
- * @param name The name of the resource. May not be the same as the config map name.
67
- * @param args The arguments to patch the config map with.
68
- * @param opts Optional resource options.
69
- */
70
- static patch(name, args, opts) {
71
- return new ConfigMapPatch(name, args, opts);
72
- }
73
- /**
74
- * Wraps an existing Kubernetes config map.
75
- */
76
- static wrap(name, args, opts) {
77
- return new WrappedConfigMap(name, args, opts);
78
- }
79
- /**
80
- * Gets an existing config map.
81
- *
82
- * Will throw an error if the config map does not exist.
83
- */
84
- static get(name, args, opts) {
85
- return new ExternalConfigMap(name, args, opts);
86
- }
87
- static configMapCache = /* @__PURE__ */ new Map();
88
- /**
89
- * Gets an existing config map for a given entity.
90
- * Prefer this method over `get` when possible.
91
- *
92
- * It automatically names the resource with the following format: `{clusterName}.{namespace}.{name}.{clusterId}`.
93
- *
94
- * This method is idempotent and will return the same instance for the same entity.
95
- *
96
- * @param entity The entity to get the config map for.
97
- * @param cluster The cluster where the config map is located.
98
- */
99
- static for(entity, cluster) {
100
- return getOrCreate(
101
- _ConfigMap.configMapCache,
102
- `${entity.clusterName}.${entity.metadata.namespace}.${entity.metadata.name}.${entity.clusterId}`,
103
- (name) => {
104
- return _ConfigMap.get(name, {
105
- name: entity.metadata.name,
106
- namespace: Namespace.forResource(entity, cluster)
107
- });
108
- }
109
- );
110
- }
111
- /**
112
- * Gets an existing config map for a given entity.
113
- * Prefer this method over `get` when possible.
114
- *
115
- * It automatically names the resource with the following format: `{clusterName}.{namespace}.{name}.{clusterId}`.
116
- *
117
- * This method is idempotent and will return the same instance for the same entity.
118
- *
119
- * @param entity The entity to get the config map for.
120
- * @param cluster The cluster where the config map is located.
121
- */
122
- static async forAsync(entity, cluster) {
123
- const resolvedEntity = await toPromise(entity);
124
- return _ConfigMap.for(resolvedEntity, cluster);
125
- }
126
- };
127
- var CreatedConfigMap = class extends ConfigMap {
128
- constructor(name, args, opts) {
129
- const configMap = output(args.namespace).cluster.apply((cluster) => {
130
- return new core.v1.ConfigMap(
131
- name,
132
- {
133
- metadata: mapMetadata(args, name),
134
- data: args.data
135
- },
136
- {
137
- ...opts,
138
- parent: this,
139
- provider: getProvider(cluster)
140
- }
141
- );
142
- });
143
- super(
144
- "highstate:k8s:ConfigMap",
145
- name,
146
- args,
147
- opts,
148
- configMap.metadata,
149
- output(args.namespace),
150
- configMap.data
151
- );
152
- }
153
- };
154
- var ConfigMapPatch = class extends ConfigMap {
155
- constructor(name, args, opts) {
156
- const configMap = output(args.namespace).cluster.apply((cluster) => {
157
- return new core.v1.ConfigMapPatch(
158
- name,
159
- {
160
- metadata: mapMetadata(args, name),
161
- data: args.data
162
- },
163
- {
164
- ...opts,
165
- parent: this,
166
- provider: getProvider(cluster)
167
- }
168
- );
169
- });
170
- super(
171
- "highstate:k8s:ConfigMapPatch",
172
- name,
173
- args,
174
- opts,
175
- configMap.metadata,
176
- output(args.namespace),
177
- configMap.data
178
- );
179
- }
180
- };
181
- var WrappedConfigMap = class extends ConfigMap {
182
- constructor(name, args, opts) {
183
- super(
184
- "highstate:k8s:WrappedConfigMap",
185
- name,
186
- args,
187
- opts,
188
- output(args.configMap).metadata,
189
- output(args.namespace),
190
- output(args.configMap).data
191
- );
192
- }
193
- };
194
- var ExternalConfigMap = class extends ConfigMap {
195
- constructor(name, args, opts) {
196
- const configMap = output(args.namespace).cluster.apply((cluster) => {
197
- return core.v1.ConfigMap.get(
198
- name,
199
- interpolate`${output(args.namespace).metadata.name}/${args.name}`,
200
- { ...opts, parent: this, provider: getProvider(cluster) }
201
- );
202
- });
203
- super(
204
- "highstate:k8s:ExternalConfigMap",
205
- name,
206
- args,
207
- opts,
208
- configMap.metadata,
209
- output(args.namespace),
210
- configMap.data
211
- );
212
- }
213
- };
214
- var extraPersistentVolumeClaimArgs = [...commonExtraArgs, "size"];
215
- var PersistentVolumeClaim = class _PersistentVolumeClaim extends NamespacedResource {
216
- constructor(type, name, args, opts, metadata, namespace, spec, status) {
217
- super(type, name, args, opts, metadata, namespace);
218
- this.spec = spec;
219
- this.status = status;
220
- }
221
- static apiVersion = "v1";
222
- static kind = "PersistentVolumeClaim";
223
- /**
224
- * The Highstate PVC entity.
225
- */
226
- get entity() {
227
- return output$1(this.entityBase);
228
- }
229
- /**
230
- * Creates a new PVC.
231
- */
232
- static create(name, args, opts) {
233
- return new CreatedPersistentVolumeClaim(name, args, opts);
234
- }
235
- /**
236
- * Creates a new PVC or patches an existing one.
237
- *
238
- * @param name The name of the resource. May not be the same as the PVC name.
239
- * @param args The arguments to create or patch the PVC with.
240
- * @param opts Optional resource options.
241
- */
242
- static createOrPatch(name, args, opts) {
243
- if (args.existing) {
244
- return new PersistentVolumeClaimPatch(name, {
245
- ...args,
246
- name: output$1(args.existing).metadata.name
247
- });
248
- }
249
- return new CreatedPersistentVolumeClaim(name, args, opts);
250
- }
251
- /**
252
- * Creates a new PVC or gets an existing one.
253
- *
254
- * @param name The name of the resource. May not be the same as the PVC name. Will not be used when existing PVC is retrieved.
255
- * @param args The arguments to create or get the PVC with.
256
- * @param opts Optional resource options.
257
- */
258
- static async createOrGet(name, args, opts) {
259
- if (args.existing) {
260
- return await _PersistentVolumeClaim.forAsync(args.existing, output$1(args.namespace).cluster);
261
- }
262
- return new CreatedPersistentVolumeClaim(name, args, opts);
263
- }
264
- /**
265
- * Patches an existing PVC.
266
- *
267
- * Will throw an error if the PVC does not exist.
268
- *
269
- * @param name The name of the resource. May not be the same as the PVC name.
270
- * @param args The arguments to patch the PVC with.
271
- * @param opts Optional resource options.
272
- */
273
- static patch(name, args, opts) {
274
- return new PersistentVolumeClaimPatch(name, args, opts);
275
- }
276
- /**
277
- * Wraps an existing Kubernetes PVC.
278
- */
279
- static wrap(name, args, opts) {
280
- return new WrappedPersistentVolumeClaim(name, args, opts);
281
- }
282
- /**
283
- * Gets an existing PVC.
284
- *
285
- * Will throw an error if the PVC does not exist.
286
- */
287
- static get(name, args, opts) {
288
- return new ExternalPersistentVolumeClaim(name, args, opts);
289
- }
290
- static pvcCache = /* @__PURE__ */ new Map();
291
- /**
292
- * Gets an existing PVC for a given entity.
293
- * Prefer this method over `get` when possible.
294
- *
295
- * It automatically names the resource with the following format: `{clusterName}.{namespace}.{name}.{clusterId}`.
296
- *
297
- * This method is idempotent and will return the same instance for the same entity.
298
- *
299
- * @param entity The entity to get the PVC for.
300
- * @param cluster The cluster where the PVC is located.
301
- */
302
- static for(entity, cluster) {
303
- return getOrCreate(
304
- _PersistentVolumeClaim.pvcCache,
305
- `${entity.clusterName}.${entity.metadata.namespace}.${entity.metadata.name}.${entity.clusterId}`,
306
- (name) => {
307
- return _PersistentVolumeClaim.get(name, {
308
- name: entity.metadata.name,
309
- namespace: Namespace.forResource(entity, cluster)
310
- });
311
- }
312
- );
313
- }
314
- /**
315
- * Gets an existing PVC for a given entity.
316
- * Prefer this method over `get` when possible.
317
- *
318
- * It automatically names the resource with the following format: `{clusterName}.{namespace}.{name}.{clusterId}`.
319
- *
320
- * This method is idempotent and will return the same instance for the same entity.
321
- *
322
- * @param entity The entity to get the PVC for.
323
- * @param cluster The cluster where the PVC is located.
324
- */
325
- static async forAsync(entity, cluster) {
326
- const resolvedEntity = await toPromise(entity);
327
- return _PersistentVolumeClaim.for(resolvedEntity, cluster);
328
- }
329
- };
330
- var CreatedPersistentVolumeClaim = class extends PersistentVolumeClaim {
331
- constructor(name, args, opts) {
332
- const pvc = output$1(args.namespace).cluster.apply((cluster) => {
333
- return new core.v1.PersistentVolumeClaim(
334
- name,
335
- {
336
- metadata: mapMetadata(args, name),
337
- spec: output$1(args).apply((args2) => {
338
- return deepmerge(
339
- {
340
- accessModes: ["ReadWriteOnce"],
341
- resources: {
342
- requests: {
343
- storage: args2.size ?? "100Mi"
344
- }
345
- }
346
- },
347
- omit(args2, extraPersistentVolumeClaimArgs)
348
- );
349
- })
350
- },
351
- {
352
- ...opts,
353
- parent: this,
354
- provider: getProvider(cluster)
355
- }
356
- );
357
- });
358
- super(
359
- "highstate:k8s:PersistentVolumeClaim",
360
- name,
361
- args,
362
- opts,
363
- pvc.metadata,
364
- output$1(args.namespace),
365
- pvc.spec,
366
- pvc.status
367
- );
368
- }
369
- };
370
- var PersistentVolumeClaimPatch = class extends PersistentVolumeClaim {
371
- constructor(name, args, opts) {
372
- const pvc = output$1(args.namespace).cluster.apply((cluster) => {
373
- return new core.v1.PersistentVolumeClaimPatch(
374
- name,
375
- {
376
- metadata: mapMetadata(args, name),
377
- spec: output$1(args).apply((args2) => {
378
- return deepmerge(
379
- {
380
- accessModes: ["ReadWriteOnce"],
381
- resources: {
382
- requests: {
383
- storage: args2.size ?? "100Mi"
384
- }
385
- }
386
- },
387
- omit(args2, extraPersistentVolumeClaimArgs)
388
- );
389
- })
390
- },
391
- {
392
- ...opts,
393
- parent: this,
394
- provider: getProvider(cluster)
395
- }
396
- );
397
- });
398
- super(
399
- "highstate:k8s:PersistentVolumeClaimPatch",
400
- name,
401
- args,
402
- opts,
403
- pvc.metadata,
404
- output$1(args.namespace),
405
- pvc.spec,
406
- pvc.status
407
- );
408
- }
409
- };
410
- var WrappedPersistentVolumeClaim = class extends PersistentVolumeClaim {
411
- constructor(name, args, opts) {
412
- super(
413
- "highstate:k8s:WrappedPersistentVolumeClaim",
414
- name,
415
- args,
416
- opts,
417
- output$1(args.pvc).metadata,
418
- output$1(args.namespace),
419
- output$1(args.pvc).spec,
420
- output$1(args.pvc).status
421
- );
422
- }
423
- };
424
- var ExternalPersistentVolumeClaim = class extends PersistentVolumeClaim {
425
- constructor(name, args, opts) {
426
- const pvc = output$1(args.namespace).cluster.apply((cluster) => {
427
- return core.v1.PersistentVolumeClaim.get(
428
- name,
429
- interpolate$1`${output$1(args.namespace).metadata.name}/${args.name}`,
430
- { ...opts, parent: this, provider: getProvider(cluster) }
431
- );
432
- });
433
- super(
434
- "highstate:k8s:ExternalPersistentVolumeClaim",
435
- name,
436
- args,
437
- opts,
438
- pvc.metadata,
439
- output$1(args.namespace),
440
- pvc.spec,
441
- pvc.status
442
- );
443
- }
444
- };
445
- function getAutoVolumeName(workloadName, index) {
446
- if (index === 0) {
447
- return `${workloadName}-data`;
448
- }
449
- return `${workloadName}-data-${index}`;
450
- }
451
- var containerExtraArgs = [
452
- "port",
453
- "volumeMount",
454
- "volume",
455
- "environment",
456
- "environmentSource",
457
- "environmentSources"
458
- ];
459
- function getFallbackContainerName(name, index) {
460
- if (index === 0) {
461
- return name;
462
- }
463
- return `${name}-${index}`;
464
- }
465
- function mapContainerToRaw(container, cluster, fallbackName) {
466
- const containerName = container.name ?? fallbackName;
467
- const spec = {
468
- ...omit(container, containerExtraArgs),
469
- name: containerName,
470
- ports: normalize(container.port, container.ports),
471
- volumeMounts: map(normalize(container.volumeMount, container.volumeMounts), mapVolumeMount),
472
- env: concat(
473
- container.environment ? mapContainerEnvironment(container.environment) : [],
474
- container.env ?? []
475
- ),
476
- envFrom: concat(
477
- map(
478
- normalize(container.environmentSource, container.environmentSources),
479
- mapEnvironmentSource
480
- ),
481
- container.envFrom ?? []
482
- )
483
- };
484
- if (container.enableTun) {
485
- spec.securityContext ??= {};
486
- spec.securityContext.capabilities ??= {};
487
- spec.securityContext.capabilities.add = ["NET_ADMIN"];
488
- if (cluster.quirks?.tunDevicePolicy?.type === "plugin") {
489
- spec.resources ??= {};
490
- spec.resources.limits ??= {};
491
- spec.resources.limits[cluster.quirks.tunDevicePolicy.resourceName] = cluster.quirks.tunDevicePolicy.resourceValue;
492
- } else {
493
- spec.volumeMounts ??= [];
494
- spec.volumeMounts.push({
495
- name: "tun-device",
496
- mountPath: "/dev/net/tun",
497
- readOnly: false
498
- });
499
- }
500
- }
501
- return spec;
502
- }
503
- function mapContainerEnvironment(environment) {
504
- const envVars = [];
505
- for (const [name, value] of Object.entries(environment)) {
506
- if (!value) {
507
- continue;
508
- }
509
- if (typeof value === "string") {
510
- envVars.push({ name, value });
511
- continue;
512
- }
513
- if ("secret" in value) {
514
- envVars.push({
515
- name,
516
- valueFrom: {
517
- secretKeyRef: {
518
- name: value.secret.metadata.name,
519
- key: value.key
520
- }
521
- }
522
- });
523
- continue;
524
- }
525
- if ("configMap" in value) {
526
- envVars.push({
527
- name,
528
- valueFrom: {
529
- configMapKeyRef: {
530
- name: value.configMap.metadata.name,
531
- key: value.key
532
- }
533
- }
534
- });
535
- continue;
536
- }
537
- envVars.push({ name, valueFrom: value });
538
- }
539
- return envVars;
540
- }
541
- function mapVolumeMount(volumeMount) {
542
- if ("volume" in volumeMount) {
543
- return omit(
544
- {
545
- ...volumeMount,
546
- name: output$1(volumeMount.volume).apply(mapWorkloadVolume).apply((volume) => output$1(volume.name))
547
- },
548
- ["volume"]
549
- );
550
- }
551
- return {
552
- ...volumeMount,
553
- name: volumeMount.name
554
- };
555
- }
556
- function mapEnvironmentSource(envFrom) {
557
- if (envFrom instanceof core.v1.ConfigMap) {
558
- return {
559
- configMapRef: {
560
- name: envFrom.metadata.name
561
- }
562
- };
563
- }
564
- if (envFrom instanceof core.v1.Secret) {
565
- return {
566
- secretRef: {
567
- name: envFrom.metadata.name
568
- }
569
- };
570
- }
571
- return envFrom;
572
- }
573
- function mapWorkloadVolume(volume) {
574
- if (volume instanceof PersistentVolumeClaim) {
575
- return {
576
- name: volume.metadata.name,
577
- persistentVolumeClaim: {
578
- claimName: volume.metadata.name
579
- }
580
- };
581
- }
582
- if (volume instanceof Secret) {
583
- return {
584
- name: volume.metadata.name,
585
- secret: {
586
- secretName: volume.metadata.name
587
- }
588
- };
589
- }
590
- if (volume instanceof ConfigMap) {
591
- return {
592
- name: volume.metadata.name,
593
- configMap: {
594
- name: volume.metadata.name
595
- }
596
- };
597
- }
598
- if (core.v1.PersistentVolumeClaim.isInstance(volume)) {
599
- return {
600
- name: volume.metadata.name,
601
- persistentVolumeClaim: {
602
- claimName: volume.metadata.name
603
- }
604
- };
605
- }
606
- if (core.v1.ConfigMap.isInstance(volume)) {
607
- return {
608
- name: volume.metadata.name,
609
- configMap: {
610
- name: volume.metadata.name
611
- }
612
- };
613
- }
614
- if (core.v1.Secret.isInstance(volume)) {
615
- return {
616
- name: volume.metadata.name,
617
- secret: {
618
- secretName: volume.metadata.name
619
- }
620
- };
621
- }
622
- return volume;
623
- }
624
- function getWorkloadVolumeResourceUuid(volume) {
625
- if (volume instanceof PersistentVolumeClaim) {
626
- return volume.metadata.uid;
627
- }
628
- if (volume instanceof Secret) {
629
- return volume.metadata.uid;
630
- }
631
- if (volume instanceof ConfigMap) {
632
- return volume.metadata.uid;
633
- }
634
- if (core.v1.PersistentVolumeClaim.isInstance(volume)) {
635
- return volume.metadata.uid;
636
- }
637
- if (core.v1.ConfigMap.isInstance(volume)) {
638
- return volume.metadata.uid;
639
- }
640
- if (core.v1.Secret.isInstance(volume)) {
641
- return volume.metadata.uid;
642
- }
643
- return output$1(void 0);
644
- }
645
-
646
- // src/network.ts
647
- function getBestEndpoint(endpoints, cluster) {
648
- if (!endpoints.length) {
649
- return void 0;
650
- }
651
- if (endpoints.length === 1) {
652
- return endpoints[0];
653
- }
654
- if (cluster) {
655
- const clusterEndpoint = endpoints.find(
656
- (endpoint) => isEndpointFromCluster(endpoint, cluster) && endpoint.metadata["k8s.service"].isInternal
657
- );
658
- if (clusterEndpoint) {
659
- return clusterEndpoint;
660
- }
661
- }
662
- const publicEndpoint = endpoints.find((endpoint) => endpoint.metadata["iana.scope"] === "global");
663
- if (publicEndpoint) {
664
- return publicEndpoint;
665
- }
666
- return endpoints[0];
667
- }
668
- function requireBestEndpoint(endpoints, cluster) {
669
- const endpoint = getBestEndpoint(endpoints, cluster);
670
- if (!endpoint) {
671
- throw new Error(`No best endpoint found for cluster "${cluster.name}" (${cluster.id})`);
672
- }
673
- return endpoint;
674
- }
675
- var networkPolicyMediator = new ImplementationMediator(
676
- "network-policy",
677
- z.object({ name: z.string(), args: z.custom() }),
678
- z.instanceof(ComponentResource)
679
- );
680
- var NetworkPolicy = class _NetworkPolicy extends ComponentResource {
681
- /**
682
- * The underlying network policy resource.
683
- */
684
- networkPolicy;
685
- constructor(name, args, opts) {
686
- super("k8s:network-policy", name, args, opts);
687
- const normalizedArgs = output$1(args).apply(async (args2) => {
688
- const ingressRules = normalize(args2.ingressRule, args2.ingressRules);
689
- const egressRules = normalize(args2.egressRule, args2.egressRules);
690
- const cluster = await toPromise(args2.namespace.cluster);
691
- const extraEgressRules = [];
692
- if (args2.allowKubeDns) {
693
- extraEgressRules.push({
694
- namespaces: ["kube-system"],
695
- namespaceSelectors: [],
696
- selectors: [{ matchLabels: { "k8s-app": "kube-dns" } }],
697
- ports: [{ port: 53, protocol: "UDP" }],
698
- all: false,
699
- clusterPods: false,
700
- cidrs: [],
701
- fqdns: [],
702
- services: []
703
- });
704
- }
705
- return {
706
- ...args2,
707
- podSelector: args2.selector ? mapSelectorLikeToSelector(args2.selector) : {},
708
- cluster,
709
- isolateEgress: args2.isolateEgress ?? false,
710
- isolateIngress: args2.isolateIngress ?? false,
711
- allowKubeApiServer: args2.allowKubeApiServer ?? false,
712
- ingressRules: ingressRules.flatMap((rule) => {
713
- const endpoints = normalize(rule?.fromEndpoint, rule?.fromEndpoints);
714
- const parsedEndpoints = endpoints.map((endpoint) => parseEndpoint(endpoint));
715
- const endpointsNamespaces = groupBy(parsedEndpoints, (endpoint) => {
716
- const namespace = isEndpointFromCluster(endpoint, cluster) ? endpoint.metadata["k8s.service"].namespace : "";
717
- return namespace;
718
- });
719
- const l3OnlyRule = endpointsNamespaces[""] ? _NetworkPolicy.getRuleFromEndpoint(void 0, endpointsNamespaces[""], cluster) : void 0;
720
- const otherRules = Object.entries(endpointsNamespaces).filter(([key]) => key !== "").map(([, endpoints2]) => {
721
- return _NetworkPolicy.getRuleFromEndpoint(void 0, endpoints2, cluster);
722
- });
723
- return [
724
- {
725
- all: rule.fromAll ?? false,
726
- clusterPods: rule.fromClusterPods ?? false,
727
- cidrs: normalize(rule.fromCidr, rule.fromCidrs).concat(l3OnlyRule?.cidrs ?? []),
728
- fqdns: [],
729
- services: normalize(rule.fromService, rule.fromServices),
730
- namespaces: normalize(rule.fromNamespace, rule.fromNamespaces),
731
- namespaceSelectors: normalize(
732
- rule.fromNamespaceSelector,
733
- rule.fromNamespaceSelectors
734
- ),
735
- selectors: normalize(rule.fromSelector, rule.fromSelectors),
736
- ports: normalize(rule.toPort, rule.toPorts)
737
- },
738
- ...otherRules
739
- ].filter((rule2) => !_NetworkPolicy.isEmptyRule(rule2));
740
- }),
741
- egressRules: egressRules.flatMap((rule) => {
742
- const endpoints = normalize(rule?.toEndpoint, rule?.toEndpoints);
743
- const parsedEndpoints = endpoints.map((endpoint) => parseEndpoint(endpoint));
744
- const endpointsByPortsAnsNamespaces = groupBy(parsedEndpoints, (endpoint) => {
745
- const namespace = isEndpointFromCluster(endpoint, cluster) ? endpoint.metadata["k8s.service"].namespace : "";
746
- const port = isEndpointFromCluster(endpoint, cluster) ? endpoint.metadata["k8s.service"].targetPort : endpoint.level !== 3 ? endpoint.port : void 0;
747
- return `${port ?? "0"}:${namespace}`;
748
- });
749
- const l3OnlyRule = endpointsByPortsAnsNamespaces["0:"] ? _NetworkPolicy.getRuleFromEndpoint(
750
- void 0,
751
- endpointsByPortsAnsNamespaces["0:"],
752
- cluster
753
- ) : void 0;
754
- const otherRules = Object.entries(endpointsByPortsAnsNamespaces).filter(([key]) => key !== "0:").map(([key, endpoints2]) => {
755
- const [port] = key.split(":");
756
- const portNumber = parseInt(port, 10);
757
- const portValue = Number.isNaN(portNumber) ? port : portNumber;
758
- return _NetworkPolicy.getRuleFromEndpoint(portValue, endpoints2, cluster);
759
- });
760
- return [
761
- {
762
- all: rule.toAll ?? false,
763
- clusterPods: rule.toClusterPods ?? false,
764
- cidrs: normalize(rule.toCidr, rule.toCidrs).concat(l3OnlyRule?.cidrs ?? []),
765
- fqdns: normalize(rule.toFqdn, rule.toFqdns).concat(l3OnlyRule?.fqdns ?? []),
766
- services: normalize(rule.toService, rule.toServices),
767
- namespaces: normalize(rule.toNamespace, rule.toNamespaces),
768
- namespaceSelectors: normalize(rule.toNamespaceSelector, rule.toNamespaceSelectors),
769
- selectors: normalize(rule.toSelector, rule.toSelectors),
770
- ports: normalize(rule.toPort, rule.toPorts)
771
- },
772
- ...otherRules
773
- ].filter((rule2) => !_NetworkPolicy.isEmptyRule(rule2));
774
- }).concat(extraEgressRules)
775
- };
776
- });
777
- this.networkPolicy = output$1(
778
- normalizedArgs.apply(async (args2) => {
779
- const cluster = args2.cluster;
780
- if (cluster.networkPolicyImplRef) {
781
- return networkPolicyMediator.call(cluster.networkPolicyImplRef, {
782
- name,
783
- args: args2
784
- });
785
- }
786
- const nativePolicy = new NativeNetworkPolicy(name, args2, {
787
- ...opts,
788
- parent: this,
789
- provider: await getProviderAsync(output$1(args2.namespace).cluster)
790
- });
791
- return nativePolicy.networkPolicy;
792
- })
793
- );
794
- }
795
- static getRuleFromEndpoint(port, endpoints, cluster) {
796
- const ports = port ? [
797
- {
798
- port,
799
- protocol: endpoints[0].level !== 3 ? endpoints[0].protocol?.toUpperCase() : void 0
800
- }
801
- ] : [];
802
- const cidrs = endpoints.filter((endpoint) => !isEndpointFromCluster(endpoint, cluster)).map((endpoint) => endpoint.address ? addressToCidr(endpoint.address) : null).filter(isNonNullish);
803
- const fqdns = endpoints.filter((endpoint) => endpoint.type === "hostname").map((endpoint) => endpoint.hostname);
804
- const selectors = endpoints.filter((endpoint) => isEndpointFromCluster(endpoint, cluster)).map((endpoint) => endpoint.metadata["k8s.service"].selector);
805
- const namespace = endpoints.filter((endpoint) => isEndpointFromCluster(endpoint, cluster)).map((endpoint) => endpoint.metadata["k8s.service"].namespace)[0];
806
- return {
807
- all: false,
808
- clusterPods: false,
809
- cidrs,
810
- fqdns,
811
- services: [],
812
- namespaces: namespace ? [namespace] : [],
813
- namespaceSelectors: [],
814
- selectors,
815
- ports
816
- };
817
- }
818
- static isEmptyRule(rule) {
819
- return !rule.all && !rule.clusterPods && rule.cidrs.length === 0 && rule.fqdns.length === 0 && rule.services.length === 0 && rule.namespaces.length === 0 && rule.namespaceSelectors.length === 0 && rule.selectors.length === 0 && rule.ports.length === 0;
820
- }
821
- /**
822
- * Creates network policy to isolate the namespace by denying all traffic to/from it.
823
- *
824
- * Automatically names the policy as: `isolate-namespace.{clusterName}.{namespace}.{clusterId}`.
825
- *
826
- * @param namespace The namespace to isolate.
827
- * @param opts Optional resource options.
828
- */
829
- static async isolateNamespace(namespace, opts) {
830
- const name = await toPromise(output$1(namespace).metadata.name);
831
- const cluster = await toPromise(output$1(namespace).cluster);
832
- return new _NetworkPolicy(
833
- `isolate-namespace.${cluster.name}.${name}.${cluster.id}`,
834
- {
835
- namespace,
836
- description: "By default, deny all traffic to/from the namespace.",
837
- isolateEgress: true,
838
- isolateIngress: true
839
- },
840
- opts
841
- );
842
- }
843
- /**
844
- * Creates network policy to allow all traffic inside the namespace (pod to pod within same namespace).
845
- *
846
- * Automatically names the policy as: `allow-inside-namespace.{clusterName}.{namespace}.{clusterId}`.
847
- *
848
- * @param namespace The namespace to create the policy in.
849
- * @param opts Optional resource options.
850
- */
851
- static async allowInsideNamespace(namespace, opts) {
852
- const nsName = await toPromise(output$1(namespace).metadata.name);
853
- const cluster = await toPromise(output$1(namespace).cluster);
854
- return new _NetworkPolicy(
855
- `allow-inside-namespace.${cluster.name}.${nsName}.${cluster.id}`,
856
- {
857
- namespace,
858
- description: "Allow all traffic inside the namespace.",
859
- ingressRule: { fromNamespace: namespace },
860
- egressRule: { toNamespace: namespace }
861
- },
862
- opts
863
- );
864
- }
865
- /**
866
- * Creates network policy to allow traffic from the namespace to the Kubernetes API server.
867
- *
868
- * Automatically names the policy as: `allow-kube-api-server.{clusterName}.{namespace}.{clusterId}`.
869
- *
870
- * @param namespace The namespace to create the policy in.
871
- * @param opts Optional resource options.
872
- */
873
- static async allowKubeApiServer(namespace, opts) {
874
- const nsName = await toPromise(output$1(namespace).metadata.name);
875
- const cluster = await toPromise(output$1(namespace).cluster);
876
- return new _NetworkPolicy(
877
- `allow-kube-api-server.${cluster.name}.${nsName}.${cluster.id}`,
878
- {
879
- namespace,
880
- description: "Allow all traffic to the Kubernetes API server from the namespace.",
881
- allowKubeApiServer: true
882
- },
883
- opts
884
- );
885
- }
886
- /**
887
- * Creates network policy to allow egress DNS traffic (UDP 53) required for name resolution.
888
- *
889
- * Automatically names the policy as: `allow-kube-dns.{clusterName}.{namespace}.{clusterId}`.
890
- *
891
- * @param namespace The namespace to create the policy in.
892
- * @param opts Optional resource options.
893
- */
894
- static async allowKubeDns(namespace, opts) {
895
- const nsName = await toPromise(output$1(namespace).metadata.name);
896
- const cluster = await toPromise(output$1(namespace).cluster);
897
- return new _NetworkPolicy(
898
- `allow-kube-dns.${cluster.name}.${nsName}.${cluster.id}`,
899
- {
900
- namespace,
901
- description: "Allow all traffic to the Kubernetes DNS server from the namespace.",
902
- allowKubeDns: true
903
- },
904
- opts
905
- );
906
- }
907
- /**
908
- * Creates network policy to allow all egress traffic from the namespace.
909
- *
910
- * Automatically names the policy as: `allow-all-egress.{clusterName}.{namespace}.{clusterId}`.
911
- *
912
- * @param namespace The namespace to create the policy in.
913
- * @param opts Optional resource options.
914
- */
915
- static async allowAllEgress(namespace, opts) {
916
- const nsName = await toPromise(output$1(namespace).metadata.name);
917
- const cluster = await toPromise(output$1(namespace).cluster);
918
- return new _NetworkPolicy(
919
- `allow-all-egress.${cluster.name}.${nsName}.${cluster.id}`,
920
- {
921
- namespace,
922
- description: "Allow all egress traffic from the namespace.",
923
- egressRule: { toAll: true }
924
- },
925
- opts
926
- );
927
- }
928
- /**
929
- * Creates network policy to allow all ingress traffic to the namespace.
930
- *
931
- * Automatically names the policy as: `allow-all-ingress.{clusterName}.{namespace}.{clusterId}`.
932
- *
933
- * @param namespace The namespace to create the policy in.
934
- * @param opts Optional resource options.
935
- */
936
- static async allowAllIngress(namespace, opts) {
937
- const nsName = await toPromise(output$1(namespace).metadata.name);
938
- const cluster = await toPromise(output$1(namespace).cluster);
939
- return new _NetworkPolicy(
940
- `allow-all-ingress.${cluster.name}.${nsName}.${cluster.id}`,
941
- {
942
- namespace,
943
- description: "Allow all ingress traffic to the namespace.",
944
- ingressRule: { fromAll: true }
945
- },
946
- opts
947
- );
948
- }
949
- /**
950
- * Creates network policy to allow egress traffic to a specific L3/L4 endpoint.
951
- *
952
- * Automatically names the policy as: `allow-egress-to-<endpoint>.{clusterName}.{namespace}.{clusterId}`.
953
- *
954
- * @param namespace The namespace to create the policy in.
955
- * @param endpoint The endpoint to allow egress to.
956
- * @param opts Optional resource options.
957
- */
958
- static async allowEgressToEndpoint(namespace, endpoint, opts) {
959
- const parsedEndpoint = parseEndpoint(endpoint);
960
- const endpointStr = endpointToString(parsedEndpoint).replace(/:/g, "-");
961
- const nsName = await toPromise(output$1(namespace).metadata.name);
962
- const cluster = await toPromise(output$1(namespace).cluster);
963
- return new _NetworkPolicy(
964
- `allow-egress-to-${endpointStr}.${cluster.name}.${nsName}.${cluster.id}`,
965
- {
966
- namespace,
967
- description: `Allow egress traffic to "${endpointToString(parsedEndpoint)}" from the namespace.`,
968
- egressRule: { toEndpoint: endpoint }
969
- },
970
- opts
971
- );
972
- }
973
- /**
974
- * Creates network policy to allow egress traffic to the best endpoint among provided candidates.
975
- *
976
- * Automatically names the policy as: `allow-egress-to-<bestEndpoint>.{clusterName}.{namespace}.{clusterId}`.
977
- *
978
- * @param namespace The namespace to create the policy in.
979
- * @param endpoints The candidate endpoints to select from.
980
- * @param opts Optional resource options.
981
- */
982
- static async allowEgressToBestEndpoint(namespace, endpoints, opts) {
983
- const cluster = await toPromise(output$1(namespace).cluster);
984
- const resolvedEndpoints = await toPromise(output$1(endpoints));
985
- const bestEndpoint = requireBestEndpoint(
986
- resolvedEndpoints.map((endpoint) => parseEndpoint(endpoint)),
987
- cluster
988
- );
989
- return await _NetworkPolicy.allowEgressToEndpoint(namespace, bestEndpoint, opts);
990
- }
991
- /**
992
- * Creates network policy to allow ingress traffic from a specific L3/L4 endpoint.
993
- *
994
- * Automatically names the policy as: `allow-ingress-from-<endpoint>.{clusterName}.{namespace}.{clusterId}`.
995
- *
996
- * @param namespace The namespace to create the policy in.
997
- * @param endpoint The endpoint to allow ingress from.
998
- * @param opts Optional resource options.
999
- */
1000
- static async allowIngressFromEndpoint(namespace, endpoint, opts) {
1001
- const parsedEndpoint = parseEndpoint(endpoint);
1002
- const endpointStr = endpointToString(parsedEndpoint).replace(/:/g, "-");
1003
- const nsName = await toPromise(output$1(namespace).metadata.name);
1004
- const cluster = await toPromise(output$1(namespace).cluster);
1005
- return new _NetworkPolicy(
1006
- `allow-ingress-from-${endpointStr}.${cluster.name}.${nsName}.${cluster.id}`,
1007
- {
1008
- namespace,
1009
- description: interpolate$1`Allow ingress traffic from "${endpointToString(parsedEndpoint)}" to the namespace.`,
1010
- ingressRule: { fromEndpoint: endpoint }
1011
- },
1012
- opts
1013
- );
1014
- }
1015
- };
1016
- var NativeNetworkPolicy = class _NativeNetworkPolicy extends ComponentResource {
1017
- /**
1018
- * The underlying native network policy resource.
1019
- */
1020
- networkPolicy;
1021
- constructor(name, args, opts) {
1022
- super("k8s:native-network-policy", name, args, opts);
1023
- const ingress = _NativeNetworkPolicy.createIngressRules(args);
1024
- const egress = _NativeNetworkPolicy.createEgressRules(args);
1025
- const policyTypes = [];
1026
- if (ingress.length > 0 || args.isolateIngress) {
1027
- policyTypes.push("Ingress");
1028
- }
1029
- if (egress.length > 0 || args.isolateEgress) {
1030
- policyTypes.push("Egress");
1031
- }
1032
- this.networkPolicy = new networking.v1.NetworkPolicy(
1033
- name,
1034
- {
1035
- metadata: mergeDeep(mapMetadata(args, name), {
1036
- annotations: args.description ? { "kubernetes.io/description": args.description } : void 0
1037
- }),
1038
- spec: {
1039
- podSelector: args.podSelector,
1040
- ingress,
1041
- egress,
1042
- policyTypes
1043
- }
1044
- },
1045
- { ...opts, parent: this }
1046
- );
1047
- }
1048
- static fallbackIpBlock = {
1049
- cidr: "0.0.0.0/0",
1050
- except: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
1051
- };
1052
- static fallbackDnsRule = {
1053
- to: [
1054
- {
1055
- namespaceSelector: { matchLabels: { "kubernetes.io/metadata.name": "kube-system" } },
1056
- podSelector: { matchLabels: { "k8s-app": "kube-dns" } }
1057
- }
1058
- ],
1059
- ports: [{ port: 53, protocol: "UDP" }]
1060
- };
1061
- static createIngressRules(args) {
1062
- return uniqueBy(
1063
- args.ingressRules.map((rule) => ({
1064
- from: rule.all ? [] : rule.clusterPods ? [{ namespaceSelector: {} }] : _NativeNetworkPolicy.createRulePeers(rule),
1065
- ports: _NativeNetworkPolicy.mapPorts(rule.ports)
1066
- })),
1067
- (rule) => JSON.stringify(rule)
1068
- );
1069
- }
1070
- static createEgressRules(args) {
1071
- const extraRules = [];
1072
- const needKubeDns = args.egressRules.some((rule) => rule.fqdns.length > 0);
1073
- if (needKubeDns) {
1074
- extraRules.push(_NativeNetworkPolicy.fallbackDnsRule);
1075
- }
1076
- const needFallback = args.egressRules.some(
1077
- (rule) => rule.fqdns.some((fqdn) => !fqdn.endsWith(".cluster.local"))
1078
- );
1079
- if (needFallback) {
1080
- extraRules.push({ to: [{ ipBlock: _NativeNetworkPolicy.fallbackIpBlock }] });
1081
- }
1082
- if (args.allowKubeApiServer) {
1083
- const { quirks, apiEndpoints } = args.cluster;
1084
- if (quirks?.fallbackKubeApiAccess) {
1085
- extraRules.push({
1086
- to: [{ ipBlock: { cidr: `${quirks?.fallbackKubeApiAccess.serverIp}/32` } }],
1087
- ports: [{ port: quirks?.fallbackKubeApiAccess.serverPort, protocol: "TCP" }]
1088
- });
1089
- } else {
1090
- const rules = apiEndpoints.filter((endpoint) => endpoint.type !== "hostname").map((endpoint) => ({
1091
- to: [{ ipBlock: { cidr: l3EndpointToCidr(endpoint) } }],
1092
- ports: [{ port: endpoint.port, protocol: "TCP" }]
1093
- }));
1094
- extraRules.push(...rules);
1095
- }
1096
- }
1097
- return uniqueBy(
1098
- args.egressRules.map((rule) => {
1099
- return {
1100
- to: rule.all ? [] : rule.clusterPods ? [{ namespaceSelector: {} }] : _NativeNetworkPolicy.createRulePeers(rule),
1101
- ports: _NativeNetworkPolicy.mapPorts(rule.ports)
1102
- };
1103
- }).filter((rule) => rule.to !== void 0).concat(extraRules),
1104
- (rule) => JSON.stringify(rule)
1105
- );
1106
- }
1107
- static createRulePeers(args) {
1108
- const peers = uniqueBy(
1109
- [
1110
- ..._NativeNetworkPolicy.createCidrPeers(args),
1111
- ..._NativeNetworkPolicy.createServicePeers(args),
1112
- ..._NativeNetworkPolicy.createSelectorPeers(args)
1113
- ],
1114
- (peer) => JSON.stringify(peer)
1115
- );
1116
- return peers.length > 0 ? peers : void 0;
1117
- }
1118
- static createCidrPeers(args) {
1119
- return args.cidrs.map((cidr) => ({ ipBlock: { cidr } }));
1120
- }
1121
- static createServicePeers(args) {
1122
- return args.services.map((service) => {
1123
- const selector = mapServiceToLabelSelector(service);
1124
- return {
1125
- namespaceSelector: mapNamespaceNameToSelector(service.metadata.namespace),
1126
- podSelector: selector
1127
- };
1128
- });
1129
- }
1130
- static createSelectorPeers(args) {
1131
- const selectorPeers = args.selectors.map((selector) => ({
1132
- podSelector: mapSelectorLikeToSelector(selector)
1133
- }));
1134
- const namespacePeers = [
1135
- ...args.namespaces.map(_NativeNetworkPolicy.createNamespacePeer),
1136
- ...args.namespaceSelectors.map(_NativeNetworkPolicy.createNamespaceSelectorPeer)
1137
- ];
1138
- if (namespacePeers.length === 0) {
1139
- return selectorPeers;
1140
- }
1141
- if (selectorPeers.length === 0) {
1142
- return namespacePeers;
1143
- }
1144
- return flat(
1145
- selectorPeers.map((selectorPeer) => {
1146
- return namespacePeers.map((namespacePeer) => merge(selectorPeer, namespacePeer));
1147
- })
1148
- );
1149
- }
1150
- static createNamespacePeer(namespace) {
1151
- const namespaceName = getNamespaceName(namespace);
1152
- const namespaceSelector = mapNamespaceNameToSelector(namespaceName);
1153
- return { namespaceSelector };
1154
- }
1155
- static createNamespaceSelectorPeer(selector) {
1156
- return {
1157
- namespaceSelector: mapSelectorLikeToSelector(selector)
1158
- };
1159
- }
1160
- static mapPorts(ports) {
1161
- return ports.map((port) => {
1162
- if ("port" in port) {
1163
- return {
1164
- port: port.port,
1165
- protocol: port.protocol ?? "TCP"
1166
- };
1167
- }
1168
- return {
1169
- port: port.range[0],
1170
- endPort: port.range[1],
1171
- protocol: port.protocol ?? "TCP"
1172
- };
1173
- });
1174
- }
1175
- };
1176
-
1177
- // src/pod.ts
1178
- var podSpecDefaults = {
1179
- automountServiceAccountToken: false
1180
- };
1181
- var workloadExtraArgs = [...commonExtraArgs, "container", "containers"];
1182
- var exposableWorkloadExtraArgs = [
1183
- ...workloadExtraArgs,
1184
- "service",
1185
- "route",
1186
- "routes"
1187
- ];
1188
- function getWorkloadComponents(name, args, parent, opts, isForPatch) {
1189
- const labels = isForPatch ? void 0 : { "app.kubernetes.io/name": name };
1190
- const containers = output(args).apply((args2) => normalize(args2.container, args2.containers));
1191
- const initContainers = output(args).apply(
1192
- (args2) => normalize(args2.initContainer, args2.initContainers)
1193
- );
1194
- const rawVolumes = output({ containers, initContainers }).apply(
1195
- ({ containers: containers2, initContainers: initContainers2 }) => {
1196
- const containerVolumes = [...containers2, ...initContainers2].flatMap(
1197
- (container) => normalize(container.volume, container.volumes)
1198
- );
1199
- const containerVolumeMounts = containers2.flatMap((container) => {
1200
- return normalize(container.volumeMount, container.volumeMounts).map((volumeMount) => {
1201
- return "volume" in volumeMount ? volumeMount.volume : void 0;
1202
- }).filter(Boolean);
1203
- });
1204
- return output([...containerVolumes, ...containerVolumeMounts]);
1205
- }
1206
- );
1207
- const volumes = rawVolumes.apply((rawVolumes2) => {
1208
- return output(rawVolumes2.map(mapWorkloadVolume)).apply(uniqueBy((volume) => volume.name));
1209
- });
1210
- const podSpec = output({
1211
- cluster: output(args.namespace).cluster,
1212
- containers,
1213
- initContainers,
1214
- volumes
1215
- }).apply(({ cluster, containers: containers2, initContainers: initContainers2, volumes: volumes2 }) => {
1216
- const spec = {
1217
- volumes: volumes2,
1218
- containers: containers2.map(
1219
- (container, index) => mapContainerToRaw(container, cluster, getFallbackContainerName(name, index))
1220
- ),
1221
- initContainers: initContainers2.map(
1222
- (container, index) => mapContainerToRaw(container, cluster, getFallbackContainerName(`init-${name}`, index))
1223
- ),
1224
- ...podSpecDefaults
1225
- };
1226
- if (containers2.some((container) => container.enableTun) && cluster.quirks?.tunDevicePolicy?.type !== "plugin") {
1227
- spec.volumes = output(spec.volumes).apply((volumes3) => [
1228
- ...volumes3 ?? [],
1229
- {
1230
- name: "tun-device",
1231
- hostPath: {
1232
- path: "/dev/net/tun"
1233
- }
1234
- }
1235
- ]);
1236
- }
1237
- return spec;
1238
- });
1239
- const dependencyHash = rawVolumes.apply((rawVolumes2) => {
1240
- return output(rawVolumes2.map(getWorkloadVolumeResourceUuid)).apply(filter(isNonNullish)).apply(unique()).apply((ids) => sha256(ids.join(",")));
1241
- });
1242
- const podTemplate = output({ podSpec, dependencyHash }).apply(({ podSpec: podSpec2, dependencyHash: dependencyHash2 }) => {
1243
- return {
1244
- metadata: {
1245
- labels,
1246
- annotations: {
1247
- // to trigger a redeployment when the volumes change
1248
- // we embed a hash as annotation name (not value) to allow patching without conflicts
1249
- [`highstate.io/dependency-hash-${dependencyHash2.slice(32)}`]: "1"
1250
- }
1251
- },
1252
- spec: podSpec2
1253
- };
1254
- });
1255
- const networkPolicy = output({ containers }).apply(({ containers: containers2 }) => {
1256
- if (isForPatch) {
1257
- return output(void 0);
1258
- }
1259
- const allowedEndpoints = containers2.flatMap((container) => container.allowedEndpoints ?? []);
1260
- if (allowedEndpoints.length === 0 && !args.networkPolicy) {
1261
- return output(void 0);
1262
- }
1263
- return output(
1264
- new NetworkPolicy(
1265
- name,
1266
- {
1267
- namespace: args.namespace,
1268
- selector: labels,
1269
- description: `Network policy for "${name}"`,
1270
- ...args.networkPolicy,
1271
- egressRules: output(args.networkPolicy?.egressRules).apply((egressRules) => [
1272
- ...egressRules ?? [],
1273
- ...allowedEndpoints.length > 0 ? [{ toEndpoints: allowedEndpoints }] : []
1274
- ])
1275
- },
1276
- { ...opts, parent: parent() }
1277
- )
1278
- );
1279
- });
1280
- return { labels, containers, volumes, podSpec, podTemplate, networkPolicy };
1281
- }
1282
- function getExposableWorkloadComponents(name, args, parent, opts, isForPatch) {
1283
- const { labels, containers, volumes, podSpec, podTemplate, networkPolicy } = getWorkloadComponents(name, args, parent, opts, isForPatch);
1284
- const service = output({
1285
- existing: args.existing,
1286
- serviceArgs: args.service,
1287
- containers
1288
- }).apply(({ existing, serviceArgs, containers: containers2 }) => {
1289
- if (!args.service && !args.route && !args.routes) {
1290
- return void 0;
1291
- }
1292
- if (existing?.service) {
1293
- return Service.for(existing.service, output(args.namespace).cluster);
1294
- }
1295
- if (existing) {
1296
- return void 0;
1297
- }
1298
- const ports = containers2.flatMap((container) => normalize(container.port, container.ports));
1299
- return Service.create(name, {
1300
- ...serviceArgs,
1301
- selector: labels,
1302
- namespace: args.namespace,
1303
- ports: (
1304
- // allow to completely override the ports
1305
- !serviceArgs?.port && !serviceArgs?.ports ? ports.map(mapContainerPortToServicePort) : serviceArgs?.ports
1306
- )
1307
- });
1308
- });
1309
- const routes = output({
1310
- routesArgs: normalizeInputs(args.route, args.routes),
1311
- service,
1312
- namespace: output(args.namespace)
1313
- }).apply(({ routesArgs, service: service2, namespace }) => {
1314
- if (!routesArgs.length || !service2) {
1315
- return [];
1316
- }
1317
- if (args.existing) {
1318
- return [];
1319
- }
1320
- return routesArgs.map((routeArgs, index) => {
1321
- return new AccessPointRoute(`${name}.${index}`, {
1322
- ...routeArgs,
1323
- endpoints: service2.endpoints,
1324
- // pass the native data to the route to allow implementation to use it
1325
- gatewayNativeData: service2,
1326
- tlsCertificateNativeData: namespace
1327
- });
1328
- });
1329
- });
1330
- return { labels, containers, volumes, podSpec, podTemplate, networkPolicy, service, routes };
1331
- }
1332
- var Workload = class extends NamespacedResource {
1333
- constructor(type, name, args, opts, metadata, namespace, terminalArgs, containers, podTemplate, networkPolicy) {
1334
- super(type, name, args, opts, metadata, namespace);
1335
- this.name = name;
1336
- this.terminalArgs = terminalArgs;
1337
- this.containers = containers;
1338
- this.podTemplate = podTemplate;
1339
- this.networkPolicy = networkPolicy;
1340
- }
1341
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: for pulumi which for some reason tries to copy all properties
1342
- set terminal(_value) {
1343
- }
1344
- /**
1345
- * The instance terminal to interact with the workload's pods.
1346
- */
1347
- get terminal() {
1348
- const containerName = this.podTemplate.spec.containers.apply((containers) => containers[0].name);
1349
- const shell = this.terminalArgs.apply((args) => args.shell ?? "bash");
1350
- const podLabelSelector = this.templateMetadata.apply((meta) => meta.labels ?? {}).apply(
1351
- (labels) => Object.entries(labels).map(([key, value]) => `${key}=${value}`).join(",")
1352
- );
1353
- return output({
1354
- name: this.metadata.name,
1355
- meta: this.getTerminalMeta(),
1356
- spec: {
1357
- image: images_exports["terminal-kubectl"].image,
1358
- command: ["bash", "/welcome.sh"],
1359
- files: {
1360
- "/kubeconfig": fileFromString("kubeconfig", this.cluster.kubeconfig, { isSecret: true }),
1361
- "/welcome.sh": fileFromString(
1362
- "welcome.sh",
1363
- interpolate`
1364
- #!/bin/bash
1365
- set -euo pipefail
1366
-
1367
- NAMESPACE="${this.metadata.namespace}"
1368
- RESOURCE_TYPE="${this.kind.toLowerCase()}"
1369
- RESOURCE_NAME="${this.metadata.name}"
1370
- CONTAINER_NAME="${containerName}"
1371
- SHELL="${shell}"
1372
- LABEL_SELECTOR="${podLabelSelector}"
1373
-
1374
- echo "Connecting to $RESOURCE_TYPE \\"$RESOURCE_NAME\\" in namespace \\"$NAMESPACE\\""
1375
-
1376
- # get all pods for this workload
1377
- PODS=$(kubectl get pods -n "$NAMESPACE" -l "$LABEL_SELECTOR" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null || echo "")
1378
-
1379
- if [ -z "$PODS" ]; then
1380
- echo "No pods found"
1381
- exit 1
1382
- fi
1383
-
1384
- # convert space-separated string to array
1385
- read -ra POD_ARRAY <<< "$PODS"
1386
-
1387
- if [ \${#POD_ARRAY[@]} -eq 1 ]; then
1388
- # single pod found, connect directly
1389
- SELECTED_POD="\${POD_ARRAY[0]}"
1390
- echo "Found single pod: $SELECTED_POD"
1391
- else
1392
- # multiple pods found, use fzf for selection
1393
- echo "Found \${#POD_ARRAY[@]} pods. Please select one."
1394
-
1395
- SELECTED_POD=$(printf '%s\n' "\${POD_ARRAY[@]}" | fzf --prompt="Select pod: " --height 10 --border --info=inline)
1396
-
1397
- if [ -z "$SELECTED_POD" ]; then
1398
- echo "No pod selected"
1399
- exit 1
1400
- fi
1401
-
1402
- echo "Selected pod: $SELECTED_POD"
1403
- fi
1404
-
1405
- # execute into the selected pod
1406
- exec kubectl exec -it -n "$NAMESPACE" "$SELECTED_POD" -c "$CONTAINER_NAME" -- "$SHELL"
1407
- `.apply(trimIndentation)
1408
- )
1409
- },
1410
- env: {
1411
- KUBECONFIG: "/kubeconfig"
1412
- }
1413
- }
1414
- });
1415
- }
1416
- /**
1417
- * Creates a terminal with a custom command.
1418
- *
1419
- * @param meta The metadata for the terminal.
1420
- * @param command The command to run in the terminal.
1421
- * @param spec Additional spec options for the terminal.
1422
- */
1423
- createTerminal(name, meta, command, spec) {
1424
- const containerName = output(this.containers).apply((containers) => {
1425
- return containers[0]?.name ?? this.name;
1426
- });
1427
- return output({
1428
- name,
1429
- meta: output(this.getTerminalMeta()).apply((currentMeta) => ({
1430
- ...currentMeta,
1431
- ...meta
1432
- })),
1433
- spec: {
1434
- image: images_exports["terminal-kubectl"].image,
1435
- command: output(command).apply((command2) => [
1436
- "exec",
1437
- "kubectl",
1438
- "exec",
1439
- "-it",
1440
- "-n",
1441
- this.metadata.namespace,
1442
- `${this.kind.toLowerCase()}/${this.metadata.name}`,
1443
- "-c",
1444
- containerName,
1445
- "--",
1446
- ...command2
1447
- ]),
1448
- files: {
1449
- "/kubeconfig": fileFromString("kubeconfig", this.cluster.kubeconfig, { isSecret: true }),
1450
- ...spec?.files
1451
- },
1452
- env: {
1453
- KUBECONFIG: "/kubeconfig",
1454
- ...spec?.env
1455
- }
1456
- }
1457
- });
1458
- }
1459
- /**
1460
- * Creates a generic workload or patches the existing one.
1461
- */
1462
- static createOrPatchGeneric(name, args, opts) {
1463
- return output(args).apply(async (args2) => {
1464
- if (args2.existing?.kind === "Deployment") {
1465
- const { Deployment } = await import('./deployment-O2LJ5WR5.js');
1466
- return Deployment.patch(
1467
- name,
1468
- {
1469
- ...deepmerge(args2, args2.deployment),
1470
- name: args2.existing.metadata.name,
1471
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1472
- },
1473
- opts
1474
- );
1475
- }
1476
- if (args2.existing?.kind === "StatefulSet") {
1477
- const { StatefulSet } = await import('./stateful-set-VJYKTQ72.js');
1478
- return StatefulSet.patch(
1479
- name,
1480
- {
1481
- ...deepmerge(args2, args2.statefulSet),
1482
- name: args2.existing.metadata.name,
1483
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1484
- },
1485
- opts
1486
- );
1487
- }
1488
- if (args2.existing?.kind === "Job") {
1489
- const { Job } = await import('./job-SYME6Y43.js');
1490
- return Job.patch(
1491
- name,
1492
- {
1493
- ...deepmerge(args2, args2.job),
1494
- name: args2.existing.metadata.name,
1495
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1496
- },
1497
- opts
1498
- );
1499
- }
1500
- if (args2.existing?.kind === "CronJob") {
1501
- const { CronJob } = await import('./cron-job-NX4HD4FI.js');
1502
- return CronJob.patch(
1503
- name,
1504
- {
1505
- ...deepmerge(args2, args2.cronJob),
1506
- name: args2.existing.metadata.name,
1507
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1508
- },
1509
- opts
1510
- );
1511
- }
1512
- if (args2.defaultType === "Deployment") {
1513
- const { Deployment } = await import('./deployment-O2LJ5WR5.js');
1514
- return Deployment.create(name, deepmerge(args2, args2.deployment), opts);
1515
- }
1516
- if (args2.defaultType === "StatefulSet") {
1517
- const { StatefulSet } = await import('./stateful-set-VJYKTQ72.js');
1518
- return StatefulSet.create(name, deepmerge(args2, args2.statefulSet), opts);
1519
- }
1520
- if (args2.defaultType === "Job") {
1521
- const { Job } = await import('./job-SYME6Y43.js');
1522
- return Job.create(name, deepmerge(args2, args2.job), opts);
1523
- }
1524
- if (args2.defaultType === "CronJob") {
1525
- const { CronJob } = await import('./cron-job-NX4HD4FI.js');
1526
- return CronJob.create(name, deepmerge(args2, args2.cronJob), opts);
1527
- }
1528
- throw new Error(`Unknown workload type: ${args2.defaultType}`);
1529
- });
1530
- }
1531
- };
1532
- var ExposableWorkload = class extends Workload {
1533
- constructor(type, name, args, opts, metadata, namespace, terminalArgs, containers, podTemplate, networkPolicy, _service, routes) {
1534
- super(
1535
- type,
1536
- name,
1537
- args,
1538
- opts,
1539
- metadata,
1540
- namespace,
1541
- terminalArgs,
1542
- containers,
1543
- podTemplate,
1544
- networkPolicy
1545
- );
1546
- this._service = _service;
1547
- this.routes = routes;
1548
- }
1549
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: for pulumi which for some reason tries to copy all properties
1550
- set optionalService(_value) {
1551
- }
1552
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: for pulumi which for some reason tries to copy all properties
1553
- set service(_value) {
1554
- }
1555
- /**
1556
- * The service associated with the workload.
1557
- */
1558
- get optionalService() {
1559
- return this._service;
1560
- }
1561
- /**
1562
- * The service associated with the workload.
1563
- *
1564
- * Will throw an error if the service is not available.
1565
- */
1566
- get service() {
1567
- return this._service.apply((service) => {
1568
- if (!service) {
1569
- throw new Error(`The service of the workload "${this.name}" is not available.`);
1570
- }
1571
- return service;
1572
- });
1573
- }
1574
- /**
1575
- * The merged and deduplicated L3 endpoints of all routes.
1576
- */
1577
- get endpoints() {
1578
- return this.routes.apply(
1579
- (routes) => output(routes.map((route) => route.route.endpoints)).apply((endpoints) => flat(endpoints)).apply(mergeEndpoints)
1580
- );
1581
- }
1582
- /**
1583
- * Creates a generic exposable workload or patches the existing one.
1584
- */
1585
- static createOrPatchGeneric(name, args, opts) {
1586
- return output(args).apply(async (args2) => {
1587
- if (args2.existing?.kind === "Deployment") {
1588
- const { Deployment } = await import('./deployment-O2LJ5WR5.js');
1589
- return Deployment.patch(
1590
- name,
1591
- {
1592
- ...deepmerge(args2, args2.deployment),
1593
- name: args2.existing.metadata.name,
1594
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1595
- },
1596
- opts
1597
- );
1598
- }
1599
- if (args2.existing?.kind === "StatefulSet") {
1600
- const { StatefulSet } = await import('./stateful-set-VJYKTQ72.js');
1601
- return StatefulSet.patch(
1602
- name,
1603
- {
1604
- ...deepmerge(args2, args2.statefulSet),
1605
- name: args2.existing.metadata.name,
1606
- namespace: Namespace.forResourceAsync(args2.existing, output(args2.namespace).cluster)
1607
- },
1608
- opts
1609
- );
1610
- }
1611
- if (args2.defaultType === "Deployment") {
1612
- const { Deployment } = await import('./deployment-O2LJ5WR5.js');
1613
- return Deployment.create(name, deepmerge(args2, args2.deployment), opts);
1614
- }
1615
- if (args2.defaultType === "StatefulSet") {
1616
- const { StatefulSet } = await import('./stateful-set-VJYKTQ72.js');
1617
- return StatefulSet.create(name, deepmerge(args2, args2.statefulSet), opts);
1618
- }
1619
- throw new Error(`Unknown workload type: ${args2.defaultType}`);
1620
- });
1621
- }
1622
- };
1623
-
1624
- export { ConfigMap, ExposableWorkload, NativeNetworkPolicy, NetworkPolicy, PersistentVolumeClaim, Workload, exposableWorkloadExtraArgs, getAutoVolumeName, getBestEndpoint, getExposableWorkloadComponents, getFallbackContainerName, getWorkloadComponents, getWorkloadVolumeResourceUuid, mapContainerEnvironment, mapContainerToRaw, mapEnvironmentSource, mapVolumeMount, mapWorkloadVolume, networkPolicyMediator, podSpecDefaults, requireBestEndpoint, workloadExtraArgs };
1625
- //# sourceMappingURL=chunk-P2VOUU7E.js.map
1626
- //# sourceMappingURL=chunk-P2VOUU7E.js.map