@highstate/k8s 0.9.18 → 0.9.20

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