pepr 0.12.2 → 0.13.0
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.
- package/CODE_OF_CONDUCT.md +83 -0
- package/CONTRIBUTING.md +70 -0
- package/README.md +28 -30
- package/dist/cli.js +644 -679
- package/dist/controller.js +13 -81
- package/dist/lib/assets/deploy.d.ts +3 -0
- package/dist/lib/assets/deploy.d.ts.map +1 -0
- package/dist/lib/assets/index.d.ts +18 -0
- package/dist/lib/assets/index.d.ts.map +1 -0
- package/dist/lib/assets/loader.d.ts +14 -0
- package/dist/lib/assets/loader.d.ts.map +1 -0
- package/dist/lib/assets/networking.d.ts +6 -0
- package/dist/lib/assets/networking.d.ts.map +1 -0
- package/dist/lib/assets/pods.d.ts +8 -0
- package/dist/lib/assets/pods.d.ts.map +1 -0
- package/dist/lib/assets/rbac.d.ts +11 -0
- package/dist/lib/assets/rbac.d.ts.map +1 -0
- package/dist/lib/assets/webhooks.d.ts +6 -0
- package/dist/lib/assets/webhooks.d.ts.map +1 -0
- package/dist/lib/assets/yaml.d.ts +4 -0
- package/dist/lib/assets/yaml.d.ts.map +1 -0
- package/dist/lib/capability.d.ts +1 -3
- package/dist/lib/capability.d.ts.map +1 -1
- package/dist/lib/controller.d.ts +45 -10
- package/dist/lib/controller.d.ts.map +1 -1
- package/dist/lib/filter.d.ts +1 -1
- package/dist/lib/filter.d.ts.map +1 -1
- package/dist/lib/k8s/index.d.ts +2 -1
- package/dist/lib/k8s/index.d.ts.map +1 -1
- package/dist/lib/k8s/kinds.d.ts.map +1 -1
- package/dist/lib/k8s/types.d.ts +13 -13
- package/dist/lib/k8s/types.d.ts.map +1 -1
- package/dist/lib/k8s/upstream.d.ts +2 -2
- package/dist/lib/k8s/upstream.d.ts.map +1 -1
- package/dist/lib/logger.d.ts +8 -54
- package/dist/lib/logger.d.ts.map +1 -1
- package/dist/lib/metrics.d.ts +11 -4
- package/dist/lib/metrics.d.ts.map +1 -1
- package/dist/lib/module.d.ts +2 -2
- package/dist/lib/module.d.ts.map +1 -1
- package/dist/lib/mutate-processor.d.ts +5 -0
- package/dist/lib/mutate-processor.d.ts.map +1 -0
- package/dist/lib/{request.d.ts → mutate-request.d.ts} +5 -5
- package/dist/lib/mutate-request.d.ts.map +1 -0
- package/dist/lib/types.d.ts +45 -46
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/validate-processor.d.ts +4 -0
- package/dist/lib/validate-processor.d.ts.map +1 -0
- package/dist/lib/validate-request.d.ts +54 -0
- package/dist/lib/validate-request.d.ts.map +1 -0
- package/dist/lib.d.ts +3 -2
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +502 -302
- package/dist/lib.js.map +4 -4
- package/package.json +15 -12
- package/src/cli.ts +2 -11
- package/src/lib/assets/deploy.ts +179 -0
- package/src/lib/assets/index.ts +46 -0
- package/src/lib/assets/loader.ts +49 -0
- package/src/lib/assets/networking.ts +58 -0
- package/src/lib/assets/pods.ts +148 -0
- package/src/lib/assets/rbac.ts +57 -0
- package/src/lib/assets/webhooks.ts +139 -0
- package/src/lib/assets/yaml.ts +75 -0
- package/src/lib/capability.ts +54 -44
- package/src/lib/controller.ts +171 -89
- package/src/lib/fetch.ts +1 -1
- package/src/lib/filter.ts +1 -3
- package/src/lib/k8s/index.ts +4 -1
- package/src/lib/k8s/kinds.ts +40 -0
- package/src/lib/k8s/types.ts +16 -14
- package/src/lib/k8s/upstream.ts +5 -1
- package/src/lib/logger.ts +14 -125
- package/src/lib/metrics.ts +67 -23
- package/src/lib/module.ts +13 -11
- package/src/lib/{processor.ts → mutate-processor.ts} +37 -28
- package/src/lib/{request.ts → mutate-request.ts} +4 -4
- package/src/lib/types.ts +51 -51
- package/src/lib/validate-processor.ts +68 -0
- package/src/lib/validate-request.ts +94 -0
- package/src/lib.ts +4 -2
- package/src/runtime/controller.ts +1 -1
- package/dist/lib/k8s/webhook.d.ts +0 -37
- package/dist/lib/k8s/webhook.d.ts.map +0 -1
- package/dist/lib/processor.d.ts +0 -5
- package/dist/lib/processor.d.ts.map +0 -1
- package/dist/lib/request.d.ts.map +0 -1
- package/src/lib/k8s/webhook.ts +0 -643
package/dist/cli.js
CHANGED
|
@@ -106,110 +106,11 @@ var banner = `\x1B[0m\x1B[38;2;96;96;96m \x1B[0m\x1B[38;2;96;96;96m \x1B[0m\x1B[
|
|
|
106
106
|
// src/cli/build.ts
|
|
107
107
|
var import_child_process2 = require("child_process");
|
|
108
108
|
var import_esbuild = require("esbuild");
|
|
109
|
-
var
|
|
109
|
+
var import_fs4 = require("fs");
|
|
110
110
|
var import_path = require("path");
|
|
111
111
|
|
|
112
|
-
// src/lib/
|
|
113
|
-
var
|
|
114
|
-
var import_child_process = require("child_process");
|
|
115
|
-
var import_crypto = __toESM(require("crypto"));
|
|
116
|
-
var import_fs = require("fs");
|
|
117
|
-
var import_ramda = require("ramda");
|
|
118
|
-
var import_zlib = require("zlib");
|
|
119
|
-
|
|
120
|
-
// src/lib/logger.ts
|
|
121
|
-
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
122
|
-
LogLevel2[LogLevel2["debug"] = 0] = "debug";
|
|
123
|
-
LogLevel2[LogLevel2["info"] = 1] = "info";
|
|
124
|
-
LogLevel2[LogLevel2["warn"] = 2] = "warn";
|
|
125
|
-
LogLevel2[LogLevel2["error"] = 3] = "error";
|
|
126
|
-
return LogLevel2;
|
|
127
|
-
})(LogLevel || {});
|
|
128
|
-
var Logger = class {
|
|
129
|
-
_logLevel;
|
|
130
|
-
/**
|
|
131
|
-
* Create a new logger instance.
|
|
132
|
-
* @param logLevel - The minimum log level to log messages for.
|
|
133
|
-
*/
|
|
134
|
-
constructor(logLevel) {
|
|
135
|
-
this._logLevel = logLevel;
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Change the log level of the logger.
|
|
139
|
-
* @param logLevel - The log level to log the message at.
|
|
140
|
-
*/
|
|
141
|
-
SetLogLevel(logLevel) {
|
|
142
|
-
this._logLevel = LogLevel[logLevel];
|
|
143
|
-
this.debug(`Log level set to ${logLevel}`);
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Log a debug message.
|
|
147
|
-
* @param message - The message to log.
|
|
148
|
-
*/
|
|
149
|
-
debug(message, prefix) {
|
|
150
|
-
this.log(0 /* debug */, message, prefix);
|
|
151
|
-
}
|
|
152
|
-
/**
|
|
153
|
-
* Log an info message.
|
|
154
|
-
* @param message - The message to log.
|
|
155
|
-
*/
|
|
156
|
-
info(message, prefix) {
|
|
157
|
-
this.log(1 /* info */, message, prefix);
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Log a warning message.
|
|
161
|
-
* @param message - The message to log.
|
|
162
|
-
*/
|
|
163
|
-
warn(message, prefix) {
|
|
164
|
-
this.log(2 /* warn */, message, prefix);
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Log an error message.
|
|
168
|
-
* @param message - The message to log.
|
|
169
|
-
*/
|
|
170
|
-
error(message, prefix) {
|
|
171
|
-
this.log(3 /* error */, message, prefix);
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Log a message at the specified log level.
|
|
175
|
-
* @param logLevel - The log level of the message.
|
|
176
|
-
* @param message - The message to log.
|
|
177
|
-
*/
|
|
178
|
-
log(logLevel, message, callerPrefix = "") {
|
|
179
|
-
const color = {
|
|
180
|
-
[0 /* debug */]: "\x1B[30m" /* FgBlack */,
|
|
181
|
-
[1 /* info */]: "\x1B[36m" /* FgCyan */,
|
|
182
|
-
[2 /* warn */]: "\x1B[33m" /* FgYellow */,
|
|
183
|
-
[3 /* error */]: "\x1B[31m" /* FgRed */
|
|
184
|
-
};
|
|
185
|
-
if (logLevel >= this._logLevel) {
|
|
186
|
-
let prefix = "[" + LogLevel[logLevel] + "] " + callerPrefix;
|
|
187
|
-
prefix = this.colorize(prefix, color[logLevel]);
|
|
188
|
-
if (typeof message !== "string") {
|
|
189
|
-
console.log(prefix);
|
|
190
|
-
console.debug("%o", message);
|
|
191
|
-
} else {
|
|
192
|
-
console.log(prefix + " " + message);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
colorize(text, color) {
|
|
197
|
-
return color + text + "\x1B[0m" /* Reset */;
|
|
198
|
-
}
|
|
199
|
-
};
|
|
200
|
-
var Log = new Logger(1 /* info */);
|
|
201
|
-
if (process.env.LOG_LEVEL) {
|
|
202
|
-
Log.SetLogLevel(process.env.LOG_LEVEL);
|
|
203
|
-
}
|
|
204
|
-
var logger_default = Log;
|
|
205
|
-
|
|
206
|
-
// src/lib/types.ts
|
|
207
|
-
var ErrorBehavior = /* @__PURE__ */ ((ErrorBehavior2) => {
|
|
208
|
-
ErrorBehavior2["ignore"] = "ignore";
|
|
209
|
-
ErrorBehavior2["audit"] = "audit";
|
|
210
|
-
ErrorBehavior2["reject"] = "reject";
|
|
211
|
-
return ErrorBehavior2;
|
|
212
|
-
})(ErrorBehavior || {});
|
|
112
|
+
// src/lib/assets/index.ts
|
|
113
|
+
var import_crypto3 = __toESM(require("crypto"));
|
|
213
114
|
|
|
214
115
|
// src/lib/k8s/tls.ts
|
|
215
116
|
var import_node_forge = __toESM(require("node-forge"));
|
|
@@ -268,529 +169,604 @@ function genCert(key, name, issuer) {
|
|
|
268
169
|
return crt;
|
|
269
170
|
}
|
|
270
171
|
|
|
271
|
-
// src/lib/
|
|
272
|
-
var
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
var
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
this._tls = genTLS(this.host || `${this.name}.pepr-system.svc`);
|
|
284
|
-
this._apiToken = import_crypto.default.randomBytes(32).toString("hex");
|
|
285
|
-
}
|
|
286
|
-
name;
|
|
287
|
-
_tls;
|
|
288
|
-
_apiToken;
|
|
289
|
-
image;
|
|
290
|
-
get tls() {
|
|
291
|
-
return this._tls;
|
|
292
|
-
}
|
|
293
|
-
get apiToken() {
|
|
294
|
-
return this._apiToken;
|
|
295
|
-
}
|
|
296
|
-
/** Generate the pepr-system namespace */
|
|
297
|
-
namespace() {
|
|
298
|
-
return {
|
|
299
|
-
apiVersion: "v1",
|
|
300
|
-
kind: "Namespace",
|
|
301
|
-
metadata: { name: "pepr-system" }
|
|
302
|
-
};
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Grants the controller access to cluster resources beyond the mutating webhook.
|
|
306
|
-
*
|
|
307
|
-
* @todo: should dynamically generate this based on resources used by the module. will also need to explore how this should work for multiple modules.
|
|
308
|
-
* @returns
|
|
309
|
-
*/
|
|
310
|
-
clusterRole() {
|
|
311
|
-
return {
|
|
312
|
-
apiVersion: "rbac.authorization.k8s.io/v1",
|
|
313
|
-
kind: "ClusterRole",
|
|
314
|
-
metadata: { name: this.name },
|
|
315
|
-
rules: [
|
|
316
|
-
{
|
|
317
|
-
// @todo: make this configurable
|
|
318
|
-
apiGroups: ["*"],
|
|
319
|
-
resources: ["*"],
|
|
320
|
-
verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
|
|
321
|
-
}
|
|
322
|
-
]
|
|
323
|
-
};
|
|
324
|
-
}
|
|
325
|
-
clusterRoleBinding() {
|
|
326
|
-
const name = this.name;
|
|
327
|
-
return {
|
|
328
|
-
apiVersion: "rbac.authorization.k8s.io/v1",
|
|
329
|
-
kind: "ClusterRoleBinding",
|
|
330
|
-
metadata: { name },
|
|
331
|
-
roleRef: {
|
|
332
|
-
apiGroup: "rbac.authorization.k8s.io",
|
|
333
|
-
kind: "ClusterRole",
|
|
334
|
-
name
|
|
335
|
-
},
|
|
336
|
-
subjects: [
|
|
337
|
-
{
|
|
338
|
-
kind: "ServiceAccount",
|
|
339
|
-
name,
|
|
340
|
-
namespace: "pepr-system"
|
|
341
|
-
}
|
|
342
|
-
]
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
serviceAccount() {
|
|
346
|
-
return {
|
|
347
|
-
apiVersion: "v1",
|
|
348
|
-
kind: "ServiceAccount",
|
|
349
|
-
metadata: {
|
|
350
|
-
name: this.name,
|
|
351
|
-
namespace: "pepr-system"
|
|
352
|
-
}
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
apiTokenSecret() {
|
|
356
|
-
return {
|
|
357
|
-
apiVersion: "v1",
|
|
358
|
-
kind: "Secret",
|
|
359
|
-
metadata: {
|
|
360
|
-
name: `${this.name}-api-token`,
|
|
361
|
-
namespace: "pepr-system"
|
|
362
|
-
},
|
|
363
|
-
type: "Opaque",
|
|
364
|
-
data: {
|
|
365
|
-
value: Buffer.from(this._apiToken).toString("base64")
|
|
366
|
-
}
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
tlsSecret() {
|
|
370
|
-
return {
|
|
371
|
-
apiVersion: "v1",
|
|
372
|
-
kind: "Secret",
|
|
373
|
-
metadata: {
|
|
374
|
-
name: `${this.name}-tls`,
|
|
375
|
-
namespace: "pepr-system"
|
|
376
|
-
},
|
|
377
|
-
type: "kubernetes.io/tls",
|
|
378
|
-
data: {
|
|
379
|
-
"tls.crt": this._tls.crt,
|
|
380
|
-
"tls.key": this._tls.key
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
generateWebhookRules(path) {
|
|
385
|
-
return new Promise((resolve4, reject) => {
|
|
386
|
-
const rules = [];
|
|
387
|
-
const defaultRule = {
|
|
388
|
-
apiGroups: ["*"],
|
|
389
|
-
apiVersions: ["*"],
|
|
390
|
-
operations: ["CREATE", "UPDATE", "DELETE"],
|
|
391
|
-
resources: ["*/*"]
|
|
392
|
-
};
|
|
393
|
-
const program2 = (0, import_child_process.fork)(path, {
|
|
394
|
-
env: {
|
|
395
|
-
...process.env,
|
|
396
|
-
LOG_LEVEL: "warn",
|
|
397
|
-
PEPR_MODE: "build"
|
|
398
|
-
}
|
|
399
|
-
});
|
|
400
|
-
program2.on("message", (message) => {
|
|
401
|
-
const { capabilities } = message.valueOf();
|
|
402
|
-
for (const capability of capabilities) {
|
|
403
|
-
logger_default.info(`Module ${this.config.uuid} has capability: ${capability._name}`);
|
|
404
|
-
const { _bindings } = capability;
|
|
405
|
-
for (const binding of _bindings) {
|
|
406
|
-
const { event, kind } = binding;
|
|
407
|
-
const operations = [];
|
|
408
|
-
if (event === "CREATEORUPDATE" /* CreateOrUpdate */) {
|
|
409
|
-
operations.push("CREATE" /* Create */, "UPDATE" /* Update */);
|
|
410
|
-
} else {
|
|
411
|
-
operations.push(event);
|
|
412
|
-
}
|
|
413
|
-
const resource = kind.plural || `${kind.kind.toLowerCase()}s`;
|
|
414
|
-
rules.push({
|
|
415
|
-
apiGroups: [kind.group],
|
|
416
|
-
apiVersions: [kind.version || "*"],
|
|
417
|
-
operations,
|
|
418
|
-
resources: [resource]
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
});
|
|
423
|
-
program2.on("exit", (code) => {
|
|
424
|
-
if (code !== 0) {
|
|
425
|
-
reject(new Error(`Child process exited with code ${code}`));
|
|
426
|
-
} else {
|
|
427
|
-
if (rules.length < 1) {
|
|
428
|
-
resolve4([defaultRule]);
|
|
429
|
-
} else {
|
|
430
|
-
const reducedRules = (0, import_ramda.uniqWith)(import_ramda.equals, rules);
|
|
431
|
-
resolve4(reducedRules);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
});
|
|
435
|
-
program2.on("error", (error) => {
|
|
436
|
-
reject(error);
|
|
437
|
-
});
|
|
438
|
-
});
|
|
172
|
+
// src/lib/assets/deploy.ts
|
|
173
|
+
var import_client_node = require("@kubernetes/client-node");
|
|
174
|
+
var import_crypto = __toESM(require("crypto"));
|
|
175
|
+
var import_fs = require("fs");
|
|
176
|
+
|
|
177
|
+
// src/lib/logger.ts
|
|
178
|
+
var import_pino = require("pino");
|
|
179
|
+
var isPrettyLog = process.env.PEPR_PRETTY_LOGS === "true";
|
|
180
|
+
var pretty = {
|
|
181
|
+
target: "pino-pretty",
|
|
182
|
+
options: {
|
|
183
|
+
colorize: true
|
|
439
184
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
185
|
+
};
|
|
186
|
+
var transport = isPrettyLog ? pretty : void 0;
|
|
187
|
+
var Log = (0, import_pino.pino)({
|
|
188
|
+
transport
|
|
189
|
+
});
|
|
190
|
+
if (process.env.LOG_LEVEL) {
|
|
191
|
+
Log.level = process.env.LOG_LEVEL;
|
|
192
|
+
}
|
|
193
|
+
var logger_default = Log;
|
|
194
|
+
|
|
195
|
+
// src/lib/assets/networking.ts
|
|
196
|
+
function apiTokenSecret(name, apiToken) {
|
|
197
|
+
return {
|
|
198
|
+
apiVersion: "v1",
|
|
199
|
+
kind: "Secret",
|
|
200
|
+
metadata: {
|
|
201
|
+
name: `${name}-api-token`,
|
|
202
|
+
namespace: "pepr-system"
|
|
203
|
+
},
|
|
204
|
+
type: "Opaque",
|
|
205
|
+
data: {
|
|
206
|
+
value: Buffer.from(apiToken).toString("base64")
|
|
449
207
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function tlsSecret(name, tls) {
|
|
211
|
+
return {
|
|
212
|
+
apiVersion: "v1",
|
|
213
|
+
kind: "Secret",
|
|
214
|
+
metadata: {
|
|
215
|
+
name: `${name}-tls`,
|
|
216
|
+
namespace: "pepr-system"
|
|
217
|
+
},
|
|
218
|
+
type: "kubernetes.io/tls",
|
|
219
|
+
data: {
|
|
220
|
+
"tls.crt": tls.crt,
|
|
221
|
+
"tls.key": tls.key
|
|
462
222
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function service(name) {
|
|
226
|
+
return {
|
|
227
|
+
apiVersion: "v1",
|
|
228
|
+
kind: "Service",
|
|
229
|
+
metadata: {
|
|
230
|
+
name,
|
|
231
|
+
namespace: "pepr-system"
|
|
232
|
+
},
|
|
233
|
+
spec: {
|
|
234
|
+
selector: {
|
|
235
|
+
app: name
|
|
236
|
+
},
|
|
237
|
+
ports: [
|
|
469
238
|
{
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
clientConfig,
|
|
473
|
-
failurePolicy: "Ignore",
|
|
474
|
-
matchPolicy: "Equivalent",
|
|
475
|
-
timeoutSeconds,
|
|
476
|
-
namespaceSelector: {
|
|
477
|
-
matchExpressions: ignore
|
|
478
|
-
},
|
|
479
|
-
objectSelector: {
|
|
480
|
-
matchExpressions: ignore
|
|
481
|
-
},
|
|
482
|
-
rules,
|
|
483
|
-
// @todo: track side effects state
|
|
484
|
-
sideEffects: "None"
|
|
239
|
+
port: 443,
|
|
240
|
+
targetPort: 3e3
|
|
485
241
|
}
|
|
486
242
|
]
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/lib/assets/pods.ts
|
|
248
|
+
var import_zlib = require("zlib");
|
|
249
|
+
var namespace = {
|
|
250
|
+
apiVersion: "v1",
|
|
251
|
+
kind: "Namespace",
|
|
252
|
+
metadata: { name: "pepr-system" }
|
|
253
|
+
};
|
|
254
|
+
function deployment(assets, hash) {
|
|
255
|
+
const { name, image } = assets;
|
|
256
|
+
const app = name;
|
|
257
|
+
return {
|
|
258
|
+
apiVersion: "apps/v1",
|
|
259
|
+
kind: "Deployment",
|
|
260
|
+
metadata: {
|
|
261
|
+
name,
|
|
262
|
+
namespace: "pepr-system",
|
|
263
|
+
labels: {
|
|
264
|
+
app
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
spec: {
|
|
268
|
+
replicas: 2,
|
|
269
|
+
selector: {
|
|
270
|
+
matchLabels: {
|
|
271
|
+
app
|
|
498
272
|
}
|
|
499
273
|
},
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
app: this.name
|
|
274
|
+
template: {
|
|
275
|
+
metadata: {
|
|
276
|
+
labels: {
|
|
277
|
+
app
|
|
505
278
|
}
|
|
506
279
|
},
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
},
|
|
529
|
-
ports: [
|
|
530
|
-
{
|
|
531
|
-
containerPort: 3e3
|
|
532
|
-
}
|
|
533
|
-
],
|
|
534
|
-
resources: {
|
|
535
|
-
requests: {
|
|
536
|
-
memory: "64Mi",
|
|
537
|
-
cpu: "100m"
|
|
538
|
-
},
|
|
539
|
-
limits: {
|
|
540
|
-
memory: "256Mi",
|
|
541
|
-
cpu: "500m"
|
|
542
|
-
}
|
|
543
|
-
},
|
|
544
|
-
volumeMounts: [
|
|
545
|
-
{
|
|
546
|
-
name: "tls-certs",
|
|
547
|
-
mountPath: "/etc/certs",
|
|
548
|
-
readOnly: true
|
|
549
|
-
},
|
|
550
|
-
{
|
|
551
|
-
name: "api-token",
|
|
552
|
-
mountPath: "/app/api-token",
|
|
553
|
-
readOnly: true
|
|
554
|
-
},
|
|
555
|
-
{
|
|
556
|
-
name: "module",
|
|
557
|
-
mountPath: `/app/load`,
|
|
558
|
-
readOnly: true
|
|
559
|
-
}
|
|
560
|
-
]
|
|
561
|
-
}
|
|
562
|
-
],
|
|
563
|
-
volumes: [
|
|
564
|
-
{
|
|
565
|
-
name: "tls-certs",
|
|
566
|
-
secret: {
|
|
567
|
-
secretName: `${this.name}-tls`
|
|
280
|
+
spec: {
|
|
281
|
+
priorityClassName: "system-node-critical",
|
|
282
|
+
serviceAccountName: name,
|
|
283
|
+
containers: [
|
|
284
|
+
{
|
|
285
|
+
name: "server",
|
|
286
|
+
image,
|
|
287
|
+
imagePullPolicy: "IfNotPresent",
|
|
288
|
+
command: ["node", "/app/node_modules/pepr/dist/controller.js", hash],
|
|
289
|
+
readinessProbe: {
|
|
290
|
+
httpGet: {
|
|
291
|
+
path: "/healthz",
|
|
292
|
+
port: 3e3,
|
|
293
|
+
scheme: "HTTPS"
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
livenessProbe: {
|
|
297
|
+
httpGet: {
|
|
298
|
+
path: "/healthz",
|
|
299
|
+
port: 3e3,
|
|
300
|
+
scheme: "HTTPS"
|
|
568
301
|
}
|
|
569
302
|
},
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
303
|
+
ports: [
|
|
304
|
+
{
|
|
305
|
+
containerPort: 3e3
|
|
306
|
+
}
|
|
307
|
+
],
|
|
308
|
+
env: [
|
|
309
|
+
{
|
|
310
|
+
name: "PEPR_PRETTY_LOG",
|
|
311
|
+
value: "false"
|
|
312
|
+
}
|
|
313
|
+
],
|
|
314
|
+
resources: {
|
|
315
|
+
requests: {
|
|
316
|
+
memory: "64Mi",
|
|
317
|
+
cpu: "100m"
|
|
318
|
+
},
|
|
319
|
+
limits: {
|
|
320
|
+
memory: "256Mi",
|
|
321
|
+
cpu: "500m"
|
|
574
322
|
}
|
|
575
323
|
},
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
324
|
+
volumeMounts: [
|
|
325
|
+
{
|
|
326
|
+
name: "tls-certs",
|
|
327
|
+
mountPath: "/etc/certs",
|
|
328
|
+
readOnly: true
|
|
329
|
+
},
|
|
330
|
+
{
|
|
331
|
+
name: "api-token",
|
|
332
|
+
mountPath: "/app/api-token",
|
|
333
|
+
readOnly: true
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
name: "module",
|
|
337
|
+
mountPath: `/app/load`,
|
|
338
|
+
readOnly: true
|
|
580
339
|
}
|
|
340
|
+
]
|
|
341
|
+
}
|
|
342
|
+
],
|
|
343
|
+
volumes: [
|
|
344
|
+
{
|
|
345
|
+
name: "tls-certs",
|
|
346
|
+
secret: {
|
|
347
|
+
secretName: `${name}-tls`
|
|
581
348
|
}
|
|
582
|
-
|
|
583
|
-
|
|
349
|
+
},
|
|
350
|
+
{
|
|
351
|
+
name: "api-token",
|
|
352
|
+
secret: {
|
|
353
|
+
secretName: `${name}-api-token`
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
{
|
|
357
|
+
name: "module",
|
|
358
|
+
secret: {
|
|
359
|
+
secretName: `${name}-module`
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
]
|
|
584
363
|
}
|
|
585
364
|
}
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function moduleSecret(name, data, hash) {
|
|
369
|
+
const compressed = (0, import_zlib.gzipSync)(data);
|
|
370
|
+
const path = `module-${hash}.js.gz`;
|
|
371
|
+
return {
|
|
372
|
+
apiVersion: "v1",
|
|
373
|
+
kind: "Secret",
|
|
374
|
+
metadata: {
|
|
375
|
+
name: `${name}-module`,
|
|
376
|
+
namespace: "pepr-system"
|
|
377
|
+
},
|
|
378
|
+
type: "Opaque",
|
|
379
|
+
data: {
|
|
380
|
+
[path]: compressed.toString("base64")
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// src/lib/assets/rbac.ts
|
|
386
|
+
function clusterRole(name) {
|
|
387
|
+
return {
|
|
388
|
+
apiVersion: "rbac.authorization.k8s.io/v1",
|
|
389
|
+
kind: "ClusterRole",
|
|
390
|
+
metadata: { name },
|
|
391
|
+
rules: [
|
|
392
|
+
{
|
|
393
|
+
// @todo: make this configurable
|
|
394
|
+
apiGroups: ["*"],
|
|
395
|
+
resources: ["*"],
|
|
396
|
+
verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
|
|
606
397
|
}
|
|
607
|
-
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
398
|
+
]
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
function clusterRoleBinding(name) {
|
|
402
|
+
return {
|
|
403
|
+
apiVersion: "rbac.authorization.k8s.io/v1",
|
|
404
|
+
kind: "ClusterRoleBinding",
|
|
405
|
+
metadata: { name },
|
|
406
|
+
roleRef: {
|
|
407
|
+
apiGroup: "rbac.authorization.k8s.io",
|
|
408
|
+
kind: "ClusterRole",
|
|
409
|
+
name
|
|
410
|
+
},
|
|
411
|
+
subjects: [
|
|
412
|
+
{
|
|
413
|
+
kind: "ServiceAccount",
|
|
414
|
+
name,
|
|
617
415
|
namespace: "pepr-system"
|
|
618
|
-
},
|
|
619
|
-
type: "Opaque",
|
|
620
|
-
data: {
|
|
621
|
-
[path]: compressed.toString("base64")
|
|
622
416
|
}
|
|
623
|
-
|
|
417
|
+
]
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function serviceAccount(name) {
|
|
421
|
+
return {
|
|
422
|
+
apiVersion: "v1",
|
|
423
|
+
kind: "ServiceAccount",
|
|
424
|
+
metadata: {
|
|
425
|
+
name,
|
|
426
|
+
namespace: "pepr-system"
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/lib/assets/webhooks.ts
|
|
432
|
+
var import_ramda = require("ramda");
|
|
433
|
+
var peprIgnoreLabel = {
|
|
434
|
+
key: "pepr.dev",
|
|
435
|
+
operator: "NotIn",
|
|
436
|
+
values: ["ignore"]
|
|
437
|
+
};
|
|
438
|
+
var peprIgnoreNamespaces = ["kube-system", "pepr-system"];
|
|
439
|
+
async function generateWebhookRules(assets, isMutateWebhook) {
|
|
440
|
+
const { config, capabilities } = assets;
|
|
441
|
+
const rules = [];
|
|
442
|
+
for (const capability of capabilities) {
|
|
443
|
+
console.info(`Module ${config.uuid} has capability: ${capability._name}`);
|
|
444
|
+
for (const binding of capability._bindings) {
|
|
445
|
+
const { event, kind, isMutate, isValidate } = binding;
|
|
446
|
+
if (isMutateWebhook && !isMutate) {
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (!isMutateWebhook && !isValidate) {
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const operations = [];
|
|
453
|
+
if (event === "CREATEORUPDATE" /* CreateOrUpdate */) {
|
|
454
|
+
operations.push("CREATE" /* Create */, "UPDATE" /* Update */);
|
|
455
|
+
} else {
|
|
456
|
+
operations.push(event);
|
|
457
|
+
}
|
|
458
|
+
const resource = kind.plural || `${kind.kind.toLowerCase()}s`;
|
|
459
|
+
rules.push({
|
|
460
|
+
apiGroups: [kind.group],
|
|
461
|
+
apiVersions: [kind.version || "*"],
|
|
462
|
+
operations,
|
|
463
|
+
resources: [resource]
|
|
464
|
+
});
|
|
465
|
+
}
|
|
624
466
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
467
|
+
return (0, import_ramda.uniqWith)(import_ramda.equals, rules);
|
|
468
|
+
}
|
|
469
|
+
async function webhookConfig(assets, mutateOrValidate, timeoutSeconds = 10) {
|
|
470
|
+
const ignore = [peprIgnoreLabel];
|
|
471
|
+
const { name, tls, config, apiToken, host } = assets;
|
|
472
|
+
const ignoreNS = (0, import_ramda.concat)(peprIgnoreNamespaces, config.alwaysIgnore.namespaces || []);
|
|
473
|
+
if (ignoreNS) {
|
|
474
|
+
ignore.push({
|
|
475
|
+
key: "kubernetes.io/metadata.name",
|
|
476
|
+
operator: "NotIn",
|
|
477
|
+
values: ignoreNS
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
const clientConfig = {
|
|
481
|
+
caBundle: tls.ca
|
|
482
|
+
};
|
|
483
|
+
const apiPath = `/${mutateOrValidate}/${apiToken}`;
|
|
484
|
+
if (host) {
|
|
485
|
+
clientConfig.url = `https://${host}:3000${apiPath}`;
|
|
486
|
+
} else {
|
|
487
|
+
clientConfig.service = {
|
|
488
|
+
name,
|
|
489
|
+
namespace: "pepr-system",
|
|
490
|
+
path: apiPath
|
|
648
491
|
};
|
|
649
|
-
return (0, import_client_node.dumpYaml)(zarfCfg, { noRefs: true });
|
|
650
492
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const resources = [
|
|
656
|
-
this.namespace(),
|
|
657
|
-
this.clusterRole(),
|
|
658
|
-
this.clusterRoleBinding(),
|
|
659
|
-
this.serviceAccount(),
|
|
660
|
-
this.apiTokenSecret(),
|
|
661
|
-
this.tlsSecret(),
|
|
662
|
-
webhook,
|
|
663
|
-
this.deployment(hash),
|
|
664
|
-
this.service(),
|
|
665
|
-
this.moduleSecret(code, hash)
|
|
666
|
-
];
|
|
667
|
-
return resources.map((r) => (0, import_client_node.dumpYaml)(r, { noRefs: true })).join("---\n");
|
|
493
|
+
const isMutate = mutateOrValidate === "mutate";
|
|
494
|
+
const rules = await generateWebhookRules(assets, isMutate);
|
|
495
|
+
if (rules.length < 1) {
|
|
496
|
+
return null;
|
|
668
497
|
}
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
498
|
+
return {
|
|
499
|
+
apiVersion: "admissionregistration.k8s.io/v1",
|
|
500
|
+
kind: isMutate ? "MutatingWebhookConfiguration" : "ValidatingWebhookConfiguration",
|
|
501
|
+
metadata: { name },
|
|
502
|
+
webhooks: [
|
|
503
|
+
{
|
|
504
|
+
name: `${name}.pepr.dev`,
|
|
505
|
+
admissionReviewVersions: ["v1", "v1beta1"],
|
|
506
|
+
clientConfig,
|
|
507
|
+
failurePolicy: "Ignore",
|
|
508
|
+
matchPolicy: "Equivalent",
|
|
509
|
+
timeoutSeconds,
|
|
510
|
+
namespaceSelector: {
|
|
511
|
+
matchExpressions: ignore
|
|
512
|
+
},
|
|
513
|
+
objectSelector: {
|
|
514
|
+
matchExpressions: ignore
|
|
515
|
+
},
|
|
516
|
+
rules,
|
|
517
|
+
// @todo: track side effects state
|
|
518
|
+
sideEffects: "None"
|
|
519
|
+
}
|
|
520
|
+
]
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/lib/assets/deploy.ts
|
|
525
|
+
async function deploy(assets, webhookTimeout) {
|
|
526
|
+
logger_default.info("Establishing connection to Kubernetes");
|
|
527
|
+
const peprNS = "pepr-system";
|
|
528
|
+
const { name, host, path } = assets;
|
|
529
|
+
const kubeConfig = new import_client_node.KubeConfig();
|
|
530
|
+
kubeConfig.loadFromDefault();
|
|
531
|
+
const coreV1Api = kubeConfig.makeApiClient(import_client_node.CoreV1Api);
|
|
532
|
+
const admissionApi = kubeConfig.makeApiClient(import_client_node.AdmissionregistrationV1Api);
|
|
533
|
+
try {
|
|
534
|
+
logger_default.info("Checking for namespace");
|
|
535
|
+
await coreV1Api.readNamespace(peprNS);
|
|
536
|
+
} catch (e) {
|
|
537
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
538
|
+
logger_default.info("Creating namespace");
|
|
539
|
+
await coreV1Api.createNamespace(namespace);
|
|
540
|
+
}
|
|
541
|
+
const mutateWebhook = await webhookConfig(assets, "mutate", webhookTimeout);
|
|
542
|
+
if (mutateWebhook) {
|
|
686
543
|
try {
|
|
687
544
|
logger_default.info("Creating mutating webhook");
|
|
688
|
-
await admissionApi.createMutatingWebhookConfiguration(
|
|
545
|
+
await admissionApi.createMutatingWebhookConfiguration(mutateWebhook);
|
|
689
546
|
} catch (e) {
|
|
690
547
|
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
691
548
|
logger_default.info("Removing and re-creating mutating webhook");
|
|
692
|
-
await admissionApi.deleteMutatingWebhookConfiguration(
|
|
693
|
-
await admissionApi.createMutatingWebhookConfiguration(
|
|
694
|
-
}
|
|
695
|
-
if (this.host) {
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
if (!path) {
|
|
699
|
-
throw new Error("No code provided");
|
|
549
|
+
await admissionApi.deleteMutatingWebhookConfiguration(mutateWebhook.metadata?.name ?? "");
|
|
550
|
+
await admissionApi.createMutatingWebhookConfiguration(mutateWebhook);
|
|
700
551
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
const rbacApi = kubeConfig.makeApiClient(import_client_node.RbacAuthorizationV1Api);
|
|
705
|
-
const crb = this.clusterRoleBinding();
|
|
552
|
+
}
|
|
553
|
+
const validateWebhook = await webhookConfig(assets, "validate", webhookTimeout);
|
|
554
|
+
if (validateWebhook) {
|
|
706
555
|
try {
|
|
707
|
-
logger_default.info("Creating
|
|
708
|
-
await
|
|
556
|
+
logger_default.info("Creating validating webhook");
|
|
557
|
+
await admissionApi.createValidatingWebhookConfiguration(validateWebhook);
|
|
709
558
|
} catch (e) {
|
|
710
559
|
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
711
|
-
logger_default.info("Removing and re-creating
|
|
712
|
-
await
|
|
713
|
-
await
|
|
560
|
+
logger_default.info("Removing and re-creating validating webhook");
|
|
561
|
+
await admissionApi.deleteValidatingWebhookConfiguration(validateWebhook.metadata?.name ?? "");
|
|
562
|
+
await admissionApi.createValidatingWebhookConfiguration(validateWebhook);
|
|
714
563
|
}
|
|
715
|
-
|
|
564
|
+
}
|
|
565
|
+
if (host) {
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
if (!path) {
|
|
569
|
+
throw new Error("No code provided");
|
|
570
|
+
}
|
|
571
|
+
const code = await import_fs.promises.readFile(path);
|
|
572
|
+
const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
|
|
573
|
+
const appsApi = kubeConfig.makeApiClient(import_client_node.AppsV1Api);
|
|
574
|
+
const rbacApi = kubeConfig.makeApiClient(import_client_node.RbacAuthorizationV1Api);
|
|
575
|
+
const crb = clusterRoleBinding(name);
|
|
576
|
+
try {
|
|
577
|
+
logger_default.info("Creating cluster role binding");
|
|
578
|
+
await rbacApi.createClusterRoleBinding(crb);
|
|
579
|
+
} catch (e) {
|
|
580
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
581
|
+
logger_default.info("Removing and re-creating cluster role binding");
|
|
582
|
+
await rbacApi.deleteClusterRoleBinding(crb.metadata?.name ?? "");
|
|
583
|
+
await rbacApi.createClusterRoleBinding(crb);
|
|
584
|
+
}
|
|
585
|
+
const cr = clusterRole(name);
|
|
586
|
+
try {
|
|
587
|
+
logger_default.info("Creating cluster role");
|
|
588
|
+
await rbacApi.createClusterRole(cr);
|
|
589
|
+
} catch (e) {
|
|
590
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
591
|
+
logger_default.info("Removing and re-creating the cluster role");
|
|
716
592
|
try {
|
|
717
|
-
|
|
593
|
+
await rbacApi.deleteClusterRole(cr.metadata?.name ?? "");
|
|
718
594
|
await rbacApi.createClusterRole(cr);
|
|
719
|
-
} catch (
|
|
720
|
-
logger_default.debug(
|
|
721
|
-
logger_default.info("Removing and re-creating the cluster role");
|
|
722
|
-
try {
|
|
723
|
-
await rbacApi.deleteClusterRole(cr.metadata?.name ?? "");
|
|
724
|
-
await rbacApi.createClusterRole(cr);
|
|
725
|
-
} catch (e2) {
|
|
726
|
-
logger_default.debug(e2 instanceof import_client_node.HttpError ? e2.body : e2);
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
const sa = this.serviceAccount();
|
|
730
|
-
try {
|
|
731
|
-
logger_default.info("Creating service account");
|
|
732
|
-
await coreV1Api.createNamespacedServiceAccount(namespace, sa);
|
|
733
|
-
} catch (e) {
|
|
734
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
735
|
-
logger_default.info("Removing and re-creating service account");
|
|
736
|
-
await coreV1Api.deleteNamespacedServiceAccount(sa.metadata?.name ?? "", namespace);
|
|
737
|
-
await coreV1Api.createNamespacedServiceAccount(namespace, sa);
|
|
738
|
-
}
|
|
739
|
-
const mod = this.moduleSecret(code, hash);
|
|
740
|
-
try {
|
|
741
|
-
logger_default.info("Creating module secret");
|
|
742
|
-
await coreV1Api.createNamespacedSecret(namespace, mod);
|
|
743
|
-
} catch (e) {
|
|
744
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
745
|
-
logger_default.info("Removing and re-creating module secret");
|
|
746
|
-
await coreV1Api.deleteNamespacedSecret(mod.metadata?.name ?? "", namespace);
|
|
747
|
-
await coreV1Api.createNamespacedSecret(namespace, mod);
|
|
748
|
-
}
|
|
749
|
-
const svc = this.service();
|
|
750
|
-
try {
|
|
751
|
-
logger_default.info("Creating service");
|
|
752
|
-
await coreV1Api.createNamespacedService(namespace, svc);
|
|
753
|
-
} catch (e) {
|
|
754
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
755
|
-
logger_default.info("Removing and re-creating service");
|
|
756
|
-
await coreV1Api.deleteNamespacedService(svc.metadata?.name ?? "", namespace);
|
|
757
|
-
await coreV1Api.createNamespacedService(namespace, svc);
|
|
758
|
-
}
|
|
759
|
-
const tls = this.tlsSecret();
|
|
760
|
-
try {
|
|
761
|
-
logger_default.info("Creating TLS secret");
|
|
762
|
-
await coreV1Api.createNamespacedSecret(namespace, tls);
|
|
763
|
-
} catch (e) {
|
|
764
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
765
|
-
logger_default.info("Removing and re-creating TLS secret");
|
|
766
|
-
await coreV1Api.deleteNamespacedSecret(tls.metadata?.name ?? "", namespace);
|
|
767
|
-
await coreV1Api.createNamespacedSecret(namespace, tls);
|
|
768
|
-
}
|
|
769
|
-
const apiToken = this.apiTokenSecret();
|
|
770
|
-
try {
|
|
771
|
-
logger_default.info("Creating API token secret");
|
|
772
|
-
await coreV1Api.createNamespacedSecret(namespace, apiToken);
|
|
773
|
-
} catch (e) {
|
|
774
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
775
|
-
logger_default.info("Removing and re-creating API token secret");
|
|
776
|
-
await coreV1Api.deleteNamespacedSecret(apiToken.metadata?.name ?? "", namespace);
|
|
777
|
-
await coreV1Api.createNamespacedSecret(namespace, apiToken);
|
|
778
|
-
}
|
|
779
|
-
const dep = this.deployment(hash);
|
|
780
|
-
try {
|
|
781
|
-
logger_default.info("Creating deployment");
|
|
782
|
-
await appsApi.createNamespacedDeployment(namespace, dep);
|
|
783
|
-
} catch (e) {
|
|
784
|
-
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
785
|
-
logger_default.info("Removing and re-creating deployment");
|
|
786
|
-
await appsApi.deleteNamespacedDeployment(dep.metadata?.name ?? "", namespace);
|
|
787
|
-
await appsApi.createNamespacedDeployment(namespace, dep);
|
|
595
|
+
} catch (e2) {
|
|
596
|
+
logger_default.debug(e2 instanceof import_client_node.HttpError ? e2.body : e2);
|
|
788
597
|
}
|
|
789
598
|
}
|
|
599
|
+
const sa = serviceAccount(name);
|
|
600
|
+
try {
|
|
601
|
+
logger_default.info("Creating service account");
|
|
602
|
+
await coreV1Api.createNamespacedServiceAccount(peprNS, sa);
|
|
603
|
+
} catch (e) {
|
|
604
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
605
|
+
logger_default.info("Removing and re-creating service account");
|
|
606
|
+
await coreV1Api.deleteNamespacedServiceAccount(sa.metadata?.name ?? "", peprNS);
|
|
607
|
+
await coreV1Api.createNamespacedServiceAccount(peprNS, sa);
|
|
608
|
+
}
|
|
609
|
+
const mod = moduleSecret(name, code, hash);
|
|
610
|
+
try {
|
|
611
|
+
logger_default.info("Creating module secret");
|
|
612
|
+
await coreV1Api.createNamespacedSecret(peprNS, mod);
|
|
613
|
+
} catch (e) {
|
|
614
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
615
|
+
logger_default.info("Removing and re-creating module secret");
|
|
616
|
+
await coreV1Api.deleteNamespacedSecret(mod.metadata?.name ?? "", peprNS);
|
|
617
|
+
await coreV1Api.createNamespacedSecret(peprNS, mod);
|
|
618
|
+
}
|
|
619
|
+
const svc = service(name);
|
|
620
|
+
try {
|
|
621
|
+
logger_default.info("Creating service");
|
|
622
|
+
await coreV1Api.createNamespacedService(peprNS, svc);
|
|
623
|
+
} catch (e) {
|
|
624
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
625
|
+
logger_default.info("Removing and re-creating service");
|
|
626
|
+
await coreV1Api.deleteNamespacedService(svc.metadata?.name ?? "", peprNS);
|
|
627
|
+
await coreV1Api.createNamespacedService(peprNS, svc);
|
|
628
|
+
}
|
|
629
|
+
const tls = tlsSecret(name, assets.tls);
|
|
630
|
+
try {
|
|
631
|
+
logger_default.info("Creating TLS secret");
|
|
632
|
+
await coreV1Api.createNamespacedSecret(peprNS, tls);
|
|
633
|
+
} catch (e) {
|
|
634
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
635
|
+
logger_default.info("Removing and re-creating TLS secret");
|
|
636
|
+
await coreV1Api.deleteNamespacedSecret(tls.metadata?.name ?? "", peprNS);
|
|
637
|
+
await coreV1Api.createNamespacedSecret(peprNS, tls);
|
|
638
|
+
}
|
|
639
|
+
const apiToken = apiTokenSecret(name, assets.apiToken);
|
|
640
|
+
try {
|
|
641
|
+
logger_default.info("Creating API token secret");
|
|
642
|
+
await coreV1Api.createNamespacedSecret(peprNS, apiToken);
|
|
643
|
+
} catch (e) {
|
|
644
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
645
|
+
logger_default.info("Removing and re-creating API token secret");
|
|
646
|
+
await coreV1Api.deleteNamespacedSecret(apiToken.metadata?.name ?? "", peprNS);
|
|
647
|
+
await coreV1Api.createNamespacedSecret(peprNS, apiToken);
|
|
648
|
+
}
|
|
649
|
+
const dep = deployment(assets, hash);
|
|
650
|
+
try {
|
|
651
|
+
logger_default.info("Creating deployment");
|
|
652
|
+
await appsApi.createNamespacedDeployment(peprNS, dep);
|
|
653
|
+
} catch (e) {
|
|
654
|
+
logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
|
|
655
|
+
logger_default.info("Removing and re-creating deployment");
|
|
656
|
+
await appsApi.deleteNamespacedDeployment(dep.metadata?.name ?? "", peprNS);
|
|
657
|
+
await appsApi.createNamespacedDeployment(peprNS, dep);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// src/lib/assets/loader.ts
|
|
662
|
+
var import_child_process = require("child_process");
|
|
663
|
+
function loadCapabilities(path) {
|
|
664
|
+
return new Promise((resolve4, reject) => {
|
|
665
|
+
const program2 = (0, import_child_process.fork)(path, {
|
|
666
|
+
env: {
|
|
667
|
+
...process.env,
|
|
668
|
+
LOG_LEVEL: "warn",
|
|
669
|
+
PEPR_MODE: "build"
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
program2.on("message", (message) => {
|
|
673
|
+
const capabilities = message.valueOf();
|
|
674
|
+
for (const capability of capabilities) {
|
|
675
|
+
console.info(`Registered Pepr Capability "${capability._name}"`);
|
|
676
|
+
}
|
|
677
|
+
resolve4(capabilities);
|
|
678
|
+
});
|
|
679
|
+
program2.on("error", (error) => {
|
|
680
|
+
reject(error);
|
|
681
|
+
});
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// src/lib/assets/yaml.ts
|
|
686
|
+
var import_client_node2 = require("@kubernetes/client-node");
|
|
687
|
+
var import_crypto2 = __toESM(require("crypto"));
|
|
688
|
+
var import_fs2 = require("fs");
|
|
689
|
+
function zarfYaml({ name, image, config }, path) {
|
|
690
|
+
const zarfCfg = {
|
|
691
|
+
kind: "ZarfPackageConfig",
|
|
692
|
+
metadata: {
|
|
693
|
+
name,
|
|
694
|
+
description: `Pepr Module: ${config.description}`,
|
|
695
|
+
url: "https://github.com/defenseunicorns/pepr",
|
|
696
|
+
version: `${config.appVersion || "0.0.1"}`
|
|
697
|
+
},
|
|
698
|
+
components: [
|
|
699
|
+
{
|
|
700
|
+
name: "module",
|
|
701
|
+
required: true,
|
|
702
|
+
manifests: [
|
|
703
|
+
{
|
|
704
|
+
name: "module",
|
|
705
|
+
namespace: "pepr-system",
|
|
706
|
+
files: [path]
|
|
707
|
+
}
|
|
708
|
+
],
|
|
709
|
+
images: [image]
|
|
710
|
+
}
|
|
711
|
+
]
|
|
712
|
+
};
|
|
713
|
+
return (0, import_client_node2.dumpYaml)(zarfCfg, { noRefs: true });
|
|
714
|
+
}
|
|
715
|
+
async function allYaml(assets) {
|
|
716
|
+
const { name, tls, apiToken, path } = assets;
|
|
717
|
+
const code = await import_fs2.promises.readFile(path);
|
|
718
|
+
const hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
|
|
719
|
+
const mutateWebhook = await webhookConfig(assets, "mutate");
|
|
720
|
+
const validateWebhook = await webhookConfig(assets, "validate");
|
|
721
|
+
const resources = [
|
|
722
|
+
namespace,
|
|
723
|
+
clusterRole(name),
|
|
724
|
+
clusterRoleBinding(name),
|
|
725
|
+
serviceAccount(name),
|
|
726
|
+
apiTokenSecret(name, apiToken),
|
|
727
|
+
tlsSecret(name, tls),
|
|
728
|
+
deployment(assets, hash),
|
|
729
|
+
service(name),
|
|
730
|
+
moduleSecret(name, code, hash)
|
|
731
|
+
];
|
|
732
|
+
if (mutateWebhook) {
|
|
733
|
+
resources.push(mutateWebhook);
|
|
734
|
+
}
|
|
735
|
+
if (validateWebhook) {
|
|
736
|
+
resources.push(validateWebhook);
|
|
737
|
+
}
|
|
738
|
+
return resources.map((r) => (0, import_client_node2.dumpYaml)(r, { noRefs: true })).join("---\n");
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// src/lib/assets/index.ts
|
|
742
|
+
var Assets = class {
|
|
743
|
+
constructor(config, path, host) {
|
|
744
|
+
this.config = config;
|
|
745
|
+
this.path = path;
|
|
746
|
+
this.host = host;
|
|
747
|
+
this.name = `pepr-${config.uuid}`;
|
|
748
|
+
this.image = `ghcr.io/defenseunicorns/pepr/controller:v${config.peprVersion}`;
|
|
749
|
+
this.tls = genTLS(this.host || `${this.name}.pepr-system.svc`);
|
|
750
|
+
this.apiToken = import_crypto3.default.randomBytes(32).toString("hex");
|
|
751
|
+
}
|
|
752
|
+
name;
|
|
753
|
+
tls;
|
|
754
|
+
apiToken;
|
|
755
|
+
capabilities;
|
|
756
|
+
image;
|
|
757
|
+
deploy = async (webhookTimeout) => {
|
|
758
|
+
this.capabilities = await loadCapabilities(this.path);
|
|
759
|
+
await deploy(this, webhookTimeout);
|
|
760
|
+
};
|
|
761
|
+
zarfYaml = (path) => zarfYaml(this, path);
|
|
762
|
+
allYaml = async () => {
|
|
763
|
+
this.capabilities = await loadCapabilities(this.path);
|
|
764
|
+
return allYaml(this);
|
|
765
|
+
};
|
|
790
766
|
};
|
|
791
767
|
|
|
792
768
|
// src/cli/init/templates.ts
|
|
793
|
-
var
|
|
769
|
+
var import_client_node3 = require("@kubernetes/client-node");
|
|
794
770
|
var import_util = require("util");
|
|
795
771
|
var import_uuid = require("uuid");
|
|
796
772
|
|
|
@@ -880,6 +856,20 @@ var hello_pepr_samples_default = [
|
|
|
880
856
|
key: "ex-2-val"
|
|
881
857
|
}
|
|
882
858
|
},
|
|
859
|
+
{
|
|
860
|
+
apiVersion: "v1",
|
|
861
|
+
kind: "ConfigMap",
|
|
862
|
+
metadata: {
|
|
863
|
+
name: "example-evil-cm",
|
|
864
|
+
namespace: "pepr-demo",
|
|
865
|
+
annotations: {
|
|
866
|
+
evil: "true"
|
|
867
|
+
}
|
|
868
|
+
},
|
|
869
|
+
data: {
|
|
870
|
+
key: "ex-evil-cm-val"
|
|
871
|
+
}
|
|
872
|
+
},
|
|
883
873
|
{
|
|
884
874
|
apiVersion: "v1",
|
|
885
875
|
kind: "ConfigMap",
|
|
@@ -977,8 +967,8 @@ var hello_pepr_samples_default = [
|
|
|
977
967
|
var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n";
|
|
978
968
|
var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a Kubernetes transformation system\nwritten in Typescript.\n\nThe `capabilities` directory contains all the capabilities for this module. By default,\na capability is a single typescript file in the format of `capability-name.ts` that is\nimported in the root `pepr.ts` file as `import { HelloPepr } from "./capabilities/hello-pepr";`.\nBecause this is typescript, you can organize this however you choose, e.g. creating a sub-folder\nper-capability or common logic in shared files or folders.\n\nExample Structure:\n\n```\nModule Root\n\u251C\u2500\u2500 package.json\n\u251C\u2500\u2500 pepr.ts\n\u2514\u2500\u2500 capabilities\n \u251C\u2500\u2500 example-one.ts\n \u251C\u2500\u2500 example-three.ts\n \u2514\u2500\u2500 example-two.ts\n```\n';
|
|
979
969
|
var peprTS = 'import { PeprModule } from "pepr";\n// cfg loads your pepr configuration from package.json\nimport cfg from "./package.json";\n\n// HelloPepr is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\nimport { HelloPepr } from "./capabilities/hello-pepr";\n\n/**\n * This is the main entrypoint for this Pepr module. It is run when the module is started.\n * This is where you register your Pepr configurations and capabilities.\n */\nnew PeprModule(cfg, [\n // "HelloPepr" is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n';
|
|
980
|
-
var helloPeprTS = 'import {\n Capability,\n Log,\n PeprRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n} from "pepr";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you run `pepr dev`and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new Capability Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Then(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single Capability Action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Then(request =>\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too")\n );\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action does the exact same changes for example-2, except this time it uses\n * the `.ThenSet()` feature. You can stack multiple `.Then()` calls, but only a single `.ThenSet()`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .ThenSet({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Then(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n// This action will log an entry when a CM with the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Then(() => Log.info("CM with label \'change=by-label\' was deleted."));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action show how you can use the `Then()` function to make multiple changes to the\n * same object from different functions. This is useful if you want to keep your Capability Actions\n * small and focused on a single task, or if you want to reuse the same function in multiple\n * Capability Actions.\n *\n * Note that the order of the `.Then()` calls matters. The first call will be executed first,\n * then the second, and so on. Also note the functions are not called until the Capability Action\n * is triggered.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-4")\n .Then(cm => cm.SetLabel("pepr.dev/first", "true"))\n .Then(addSecond)\n .Then(addThird);\n\n//This function uses the complete type definition, but is not required.\nfunction addSecond(cm: PeprRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/second", "true");\n}\n\n// This function has no type definition, so you won\'t have intellisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Then(cm => cm.SetLabel("pepr.dev/first", "true"))\n .Then(addSecond)\n .Then(addThird);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any Capability Action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://api.chucknorris.io/jokes/random?category=dev");\n * const joke = await fetch("https://api.chucknorris.io/jokes/random?category=dev") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://api.chucknorris.io/jokes/random?category=dev")\n * ```\n */\ninterface TheChuckNorrisJoke {\n icon_url: string;\n id: string;\n url: string;\n value: string;\n}\n\nWhen(a.ConfigMap)\n .IsCreated()\n .WithLabel("chuck-norris")\n .Then(async change => {\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(\n "https://api.chucknorris.io/jokes/random?category=dev"\n );\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n // Add the Chuck Norris joke to the configmap\n change.Raw.data["chuck-says"] = response.data.value;\n return;\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the Capability Action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Then(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the Capability Action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .ThenSet({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the Capability Action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all Capability Actions, but we are putting it here for demonstration purposes.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .ThenSet({\n spec: {\n message: "Hello Pepr now with type data!",\n counter: Math.random(),\n },\n });\n';
|
|
981
|
-
var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.
|
|
970
|
+
var helloPeprTS = 'import {\n Capability,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n} from "pepr";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you run `pepr dev`and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 2 different types of actions: \'Mutate\', and \'Validate\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation and finally validate that the ConfigMap has the label\n * `pepr`.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Mutate(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://api.chucknorris.io/jokes/random?category=dev");\n * const joke = await fetch("https://api.chucknorris.io/jokes/random?category=dev") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://api.chucknorris.io/jokes/random?category=dev")\n * ```\n */\ninterface TheChuckNorrisJoke {\n icon_url: string;\n id: string;\n url: string;\n value: string;\n}\n\nWhen(a.ConfigMap)\n .IsCreated()\n .WithLabel("chuck-norris")\n .Mutate(async change => {\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(\n "https://api.chucknorris.io/jokes/random?category=dev",\n );\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n // Add the Chuck Norris joke to the configmap\n change.Raw.data["chuck-says"] = response.data.value;\n return;\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all actions, but we are putting it here for demonstration purposes.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n';
|
|
971
|
+
var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.13.0", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { prebuild: "rm -fr dist/* && node hack/build-template-data.js", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:e2e", "test:unit": "npm run build && tsc -p tsconfig.tests.json && ava dist/**/*.test.js", "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run", "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:e2e:build": "npm run build && npm pack", "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:e2e:run": "ava hack/e2e.test.mjs --sequential --timeout=2m", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@kubernetes/client-node": "0.18.1", express: "4.18.2", "fast-json-patch": "3.1.1", "http-status-codes": "2.2.0", "node-fetch": "2.7.0", pino: "8.15.0", "pino-pretty": "10.2.0", "prom-client": "14.2.0", ramda: "0.29.0" }, devDependencies: { "@types/eslint": "8.44.2", "@types/express": "4.17.17", "@types/node": "18.x.x", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.4", "@types/prettier": "3.0.0", "@types/prompts": "2.4.4", "@types/ramda": "0.29.3", "@types/uuid": "9.0.2", ava: "5.3.1", nock: "13.3.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.4.0", "@typescript-eslint/parser": "6.4.0", commander: "11.0.0", esbuild: "0.19.2", eslint: "8.47.0", "node-forge": "1.3.1", prettier: "3.0.1", prompts: "2.4.2", typescript: "5.1.6", uuid: "9.0.0" }, ava: { failFast: true, verbose: true } };
|
|
982
972
|
|
|
983
973
|
// src/cli/init/templates/pepr.code-snippets.json
|
|
984
974
|
var pepr_code_snippets_default = {
|
|
@@ -993,13 +983,13 @@ var pepr_code_snippets_default = {
|
|
|
993
983
|
" namespaces: [${2:}],",
|
|
994
984
|
"});",
|
|
995
985
|
"",
|
|
996
|
-
"// Use the 'When' function to create a new
|
|
986
|
+
"// Use the 'When' function to create a new action",
|
|
997
987
|
"const { When } = ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};",
|
|
998
988
|
"",
|
|
999
989
|
"// When(a.<Kind>).Is<Event>().Then(change => change.<changes>",
|
|
1000
990
|
"When(${3:})"
|
|
1001
991
|
],
|
|
1002
|
-
description: "Creates a new Pepr capability with a specified description,
|
|
992
|
+
description: "Creates a new Pepr capability with a specified description, optional namespaces, and adds a When statement for the specified value."
|
|
1003
993
|
}
|
|
1004
994
|
};
|
|
1005
995
|
|
|
@@ -1025,7 +1015,7 @@ var tsconfig_module_default = {
|
|
|
1025
1015
|
};
|
|
1026
1016
|
|
|
1027
1017
|
// src/cli/init/utils.ts
|
|
1028
|
-
var
|
|
1018
|
+
var import_fs3 = require("fs");
|
|
1029
1019
|
function sanitizeName(name) {
|
|
1030
1020
|
let sanitized = name.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
|
|
1031
1021
|
sanitized = sanitized.replace(/^-+|-+$/g, "");
|
|
@@ -1034,7 +1024,7 @@ function sanitizeName(name) {
|
|
|
1034
1024
|
}
|
|
1035
1025
|
async function createDir(dir) {
|
|
1036
1026
|
try {
|
|
1037
|
-
await
|
|
1027
|
+
await import_fs3.promises.mkdir(dir);
|
|
1038
1028
|
} catch (err) {
|
|
1039
1029
|
if (err && err.code === "EEXIST") {
|
|
1040
1030
|
throw new Error(`Directory ${dir} already exists`);
|
|
@@ -1047,7 +1037,7 @@ function write(path, data) {
|
|
|
1047
1037
|
if (typeof data !== "string") {
|
|
1048
1038
|
data = JSON.stringify(data, null, 2);
|
|
1049
1039
|
}
|
|
1050
|
-
return
|
|
1040
|
+
return import_fs3.promises.writeFile(path, data);
|
|
1051
1041
|
}
|
|
1052
1042
|
|
|
1053
1043
|
// src/cli/init/templates.ts
|
|
@@ -1109,7 +1099,7 @@ var gitignore = {
|
|
|
1109
1099
|
};
|
|
1110
1100
|
var samplesYaml = {
|
|
1111
1101
|
path: "hello-pepr.samples.yaml",
|
|
1112
|
-
data: hello_pepr_samples_default.map((r) => (0,
|
|
1102
|
+
data: hello_pepr_samples_default.map((r) => (0, import_client_node3.dumpYaml)(r, { noRefs: true })).join("---\n")
|
|
1113
1103
|
};
|
|
1114
1104
|
var snippet = {
|
|
1115
1105
|
path: "pepr.code-snippets",
|
|
@@ -1138,23 +1128,26 @@ function build_default(program2) {
|
|
|
1138
1128
|
).action(async (opts) => {
|
|
1139
1129
|
const { cfg, path, uuid } = await buildModule(void 0, opts.entryPoint);
|
|
1140
1130
|
if (opts.entryPoint !== peprTS2) {
|
|
1141
|
-
|
|
1131
|
+
console.info(`\u2705 Module built successfully at ${path}`);
|
|
1142
1132
|
return;
|
|
1143
1133
|
}
|
|
1144
|
-
const
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1134
|
+
const assets = new Assets(
|
|
1135
|
+
{
|
|
1136
|
+
...cfg.pepr,
|
|
1137
|
+
appVersion: cfg.version,
|
|
1138
|
+
description: cfg.description
|
|
1139
|
+
},
|
|
1140
|
+
path
|
|
1141
|
+
);
|
|
1149
1142
|
const yamlFile = `pepr-module-${uuid}.yaml`;
|
|
1150
1143
|
const yamlPath = (0, import_path.resolve)("dist", yamlFile);
|
|
1151
|
-
const yaml = await
|
|
1144
|
+
const yaml = await assets.allYaml();
|
|
1152
1145
|
const zarfPath = (0, import_path.resolve)("dist", "zarf.yaml");
|
|
1153
|
-
const zarf =
|
|
1154
|
-
await
|
|
1155
|
-
await
|
|
1146
|
+
const zarf = assets.zarfYaml(yamlFile);
|
|
1147
|
+
await import_fs4.promises.writeFile(yamlPath, yaml);
|
|
1148
|
+
await import_fs4.promises.writeFile(zarfPath, zarf);
|
|
1156
1149
|
logger_default.debug(`Module compiled successfully at ${path}`);
|
|
1157
|
-
|
|
1150
|
+
console.info(`\u2705 K8s resource for the module saved to ${yamlPath}`);
|
|
1158
1151
|
});
|
|
1159
1152
|
}
|
|
1160
1153
|
var externalLibs = Object.keys(dependencies);
|
|
@@ -1163,15 +1156,15 @@ async function loadModule(entryPoint = peprTS2) {
|
|
|
1163
1156
|
const cfgPath = (0, import_path.resolve)(".", "package.json");
|
|
1164
1157
|
const input = (0, import_path.resolve)(".", entryPoint);
|
|
1165
1158
|
try {
|
|
1166
|
-
await
|
|
1167
|
-
await
|
|
1159
|
+
await import_fs4.promises.access(cfgPath);
|
|
1160
|
+
await import_fs4.promises.access(input);
|
|
1168
1161
|
} catch (e) {
|
|
1169
|
-
|
|
1162
|
+
console.error(
|
|
1170
1163
|
`Could not find ${cfgPath} or ${input} in the current directory. Please run this command from the root of your module's directory.`
|
|
1171
1164
|
);
|
|
1172
1165
|
process.exit(1);
|
|
1173
1166
|
}
|
|
1174
|
-
const moduleText = await
|
|
1167
|
+
const moduleText = await import_fs4.promises.readFile(cfgPath, { encoding: "utf-8" });
|
|
1175
1168
|
const cfg = JSON.parse(moduleText);
|
|
1176
1169
|
const { uuid } = cfg.pepr;
|
|
1177
1170
|
const name = `pepr-${uuid}.js`;
|
|
@@ -1249,7 +1242,7 @@ async function buildModule(reloader, entryPoint = peprTS2) {
|
|
|
1249
1242
|
out.matchAll(pgkErrMatch);
|
|
1250
1243
|
const conflicts = [...out.matchAll(pgkErrMatch)];
|
|
1251
1244
|
if (conflicts.length < 1) {
|
|
1252
|
-
|
|
1245
|
+
console.warn(
|
|
1253
1246
|
`
|
|
1254
1247
|
One or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.
|
|
1255
1248
|
Try updating your Pepr Capabilities to their latest versions.`,
|
|
@@ -1257,7 +1250,7 @@ async function buildModule(reloader, entryPoint = peprTS2) {
|
|
|
1257
1250
|
);
|
|
1258
1251
|
}
|
|
1259
1252
|
conflicts.forEach((match) => {
|
|
1260
|
-
|
|
1253
|
+
console.warn(
|
|
1261
1254
|
`
|
|
1262
1255
|
Package '${match[1]}' seems to be incompatible with your current version of Pepr.
|
|
1263
1256
|
Try updating to the latest version.`,
|
|
@@ -1285,18 +1278,21 @@ function deploy_default(program2) {
|
|
|
1285
1278
|
}
|
|
1286
1279
|
}
|
|
1287
1280
|
const { cfg, path } = await buildModule();
|
|
1288
|
-
const webhook = new
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1281
|
+
const webhook = new Assets(
|
|
1282
|
+
{
|
|
1283
|
+
...cfg.pepr,
|
|
1284
|
+
description: cfg.description
|
|
1285
|
+
},
|
|
1286
|
+
path
|
|
1287
|
+
);
|
|
1292
1288
|
if (opts.image) {
|
|
1293
1289
|
webhook.image = opts.image;
|
|
1294
1290
|
}
|
|
1295
1291
|
try {
|
|
1296
|
-
await webhook.deploy(
|
|
1297
|
-
|
|
1292
|
+
await webhook.deploy();
|
|
1293
|
+
console.info(`\u2705 Module deployed successfully`);
|
|
1298
1294
|
} catch (e) {
|
|
1299
|
-
|
|
1295
|
+
console.error(`Error deploying module: ${e}`);
|
|
1300
1296
|
process.exit(1);
|
|
1301
1297
|
}
|
|
1302
1298
|
});
|
|
@@ -1304,7 +1300,7 @@ function deploy_default(program2) {
|
|
|
1304
1300
|
|
|
1305
1301
|
// src/cli/dev.ts
|
|
1306
1302
|
var import_child_process3 = require("child_process");
|
|
1307
|
-
var
|
|
1303
|
+
var import_fs5 = require("fs");
|
|
1308
1304
|
var import_prompts2 = __toESM(require("prompts"));
|
|
1309
1305
|
function dev_default(program2) {
|
|
1310
1306
|
program2.command("dev").description("Setup a local webhook development environment").option("-h, --host [host]", "Host to listen on", "host.k3d.internal").option("--confirm", "Skip confirmation prompt").action(async (opts) => {
|
|
@@ -1319,25 +1315,27 @@ function dev_default(program2) {
|
|
|
1319
1315
|
}
|
|
1320
1316
|
}
|
|
1321
1317
|
const { cfg, path } = await loadModule();
|
|
1322
|
-
const webhook = new
|
|
1318
|
+
const webhook = new Assets(
|
|
1323
1319
|
{
|
|
1324
1320
|
...cfg.pepr,
|
|
1325
1321
|
description: cfg.description
|
|
1326
1322
|
},
|
|
1323
|
+
path,
|
|
1327
1324
|
opts.host
|
|
1328
1325
|
);
|
|
1329
|
-
await
|
|
1330
|
-
await
|
|
1326
|
+
await import_fs5.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
|
|
1327
|
+
await import_fs5.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
|
|
1331
1328
|
try {
|
|
1332
1329
|
let program3;
|
|
1333
1330
|
const runFork = async () => {
|
|
1334
|
-
|
|
1335
|
-
await webhook.deploy(
|
|
1331
|
+
console.info(`Running module ${path}`);
|
|
1332
|
+
await webhook.deploy(30);
|
|
1336
1333
|
program3 = (0, import_child_process3.fork)(path, {
|
|
1337
1334
|
env: {
|
|
1338
1335
|
...process.env,
|
|
1339
1336
|
LOG_LEVEL: "debug",
|
|
1340
1337
|
PEPR_API_TOKEN: webhook.apiToken,
|
|
1338
|
+
PEPR_PRETTY_LOGS: "true",
|
|
1341
1339
|
SSL_KEY_PATH: "insecure-tls.key",
|
|
1342
1340
|
SSL_CERT_PATH: "insecure-tls.crt"
|
|
1343
1341
|
}
|
|
@@ -1345,7 +1343,7 @@ function dev_default(program2) {
|
|
|
1345
1343
|
};
|
|
1346
1344
|
await buildModule(async (r) => {
|
|
1347
1345
|
if (r.errors.length > 0) {
|
|
1348
|
-
|
|
1346
|
+
console.error(`Error compiling module: ${r.errors}`);
|
|
1349
1347
|
return;
|
|
1350
1348
|
}
|
|
1351
1349
|
if (program3) {
|
|
@@ -1356,7 +1354,7 @@ function dev_default(program2) {
|
|
|
1356
1354
|
}
|
|
1357
1355
|
});
|
|
1358
1356
|
} catch (e) {
|
|
1359
|
-
|
|
1357
|
+
console.error(`Error deploying module: ${e}`);
|
|
1360
1358
|
process.exit(1);
|
|
1361
1359
|
}
|
|
1362
1360
|
});
|
|
@@ -1364,7 +1362,7 @@ function dev_default(program2) {
|
|
|
1364
1362
|
|
|
1365
1363
|
// src/cli/format.ts
|
|
1366
1364
|
var import_eslint = require("eslint");
|
|
1367
|
-
var
|
|
1365
|
+
var import_fs6 = require("fs");
|
|
1368
1366
|
var import_prettier = require("prettier");
|
|
1369
1367
|
function format_default(program2) {
|
|
1370
1368
|
program2.command("format").description("Lint and format this Pepr module").option("-v, --validate-only", "Do not modify files, only validate formatting").action(async (opts) => {
|
|
@@ -1387,25 +1385,25 @@ function format_default(program2) {
|
|
|
1387
1385
|
await import_eslint.ESLint.outputFixes(results);
|
|
1388
1386
|
}
|
|
1389
1387
|
for (const { filePath } of results) {
|
|
1390
|
-
const content = await
|
|
1388
|
+
const content = await import_fs6.promises.readFile(filePath, "utf8");
|
|
1391
1389
|
const cfg = await (0, import_prettier.resolveConfig)(filePath);
|
|
1392
|
-
const formatted = (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
|
|
1390
|
+
const formatted = await (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
|
|
1393
1391
|
if (opts.validateOnly) {
|
|
1394
1392
|
if (formatted !== content) {
|
|
1395
1393
|
hasFailure = true;
|
|
1396
|
-
|
|
1394
|
+
console.error(`File ${filePath} is not formatted correctly`);
|
|
1397
1395
|
}
|
|
1398
1396
|
} else {
|
|
1399
|
-
await
|
|
1397
|
+
await import_fs6.promises.writeFile(filePath, formatted);
|
|
1400
1398
|
}
|
|
1401
1399
|
}
|
|
1402
1400
|
if (opts.validateOnly && hasFailure) {
|
|
1403
1401
|
process.exit(1);
|
|
1404
1402
|
}
|
|
1405
|
-
|
|
1403
|
+
console.info("\u2705 Module formatted");
|
|
1406
1404
|
} catch (e) {
|
|
1407
1405
|
logger_default.debug(e);
|
|
1408
|
-
|
|
1406
|
+
console.error(e.message);
|
|
1409
1407
|
process.exit(1);
|
|
1410
1408
|
}
|
|
1411
1409
|
});
|
|
@@ -1417,7 +1415,7 @@ var import_path2 = require("path");
|
|
|
1417
1415
|
var import_prompts4 = __toESM(require("prompts"));
|
|
1418
1416
|
|
|
1419
1417
|
// src/cli/init/walkthrough.ts
|
|
1420
|
-
var
|
|
1418
|
+
var import_fs7 = require("fs");
|
|
1421
1419
|
var import_prompts3 = __toESM(require("prompts"));
|
|
1422
1420
|
function walkthrough() {
|
|
1423
1421
|
const askName = {
|
|
@@ -1427,7 +1425,7 @@ function walkthrough() {
|
|
|
1427
1425
|
validate: async (val) => {
|
|
1428
1426
|
try {
|
|
1429
1427
|
const name = sanitizeName(val);
|
|
1430
|
-
await
|
|
1428
|
+
await import_fs7.promises.access(name, import_fs7.promises.constants.F_OK);
|
|
1431
1429
|
return "A directory with this name already exists";
|
|
1432
1430
|
} catch (e) {
|
|
1433
1431
|
return val.length > 2 || "The name must be at least 3 characters long";
|
|
@@ -1442,23 +1440,22 @@ function walkthrough() {
|
|
|
1442
1440
|
const askErrorBehavior = {
|
|
1443
1441
|
type: "select",
|
|
1444
1442
|
name: "errorBehavior",
|
|
1445
|
-
validate: (val) => ErrorBehavior[val],
|
|
1446
1443
|
message: "How do you want Pepr to handle errors encountered during K8s operations?",
|
|
1447
1444
|
choices: [
|
|
1448
1445
|
{
|
|
1449
1446
|
title: "Ignore",
|
|
1450
|
-
value: "ignore"
|
|
1447
|
+
value: "ignore",
|
|
1451
1448
|
description: "Pepr will continue processing and generate an entry in the Pepr Controller log.",
|
|
1452
1449
|
selected: true
|
|
1453
1450
|
},
|
|
1454
1451
|
{
|
|
1455
1452
|
title: "Log an audit event",
|
|
1456
|
-
value: "audit"
|
|
1453
|
+
value: "audit",
|
|
1457
1454
|
description: "Pepr will continue processing and generate an entry in the Pepr Controller log as well as an audit event in the cluster."
|
|
1458
1455
|
},
|
|
1459
1456
|
{
|
|
1460
1457
|
title: "Reject the operation",
|
|
1461
|
-
value: "reject"
|
|
1458
|
+
value: "reject",
|
|
1462
1459
|
description: "Pepr will reject the operation and return an error to the client."
|
|
1463
1460
|
}
|
|
1464
1461
|
]
|
|
@@ -1537,9 +1534,8 @@ function init_default(program2) {
|
|
|
1537
1534
|
console.log(`New Pepr module created at ${dirName}`);
|
|
1538
1535
|
console.log(`Open VSCode or your editor of choice in ${dirName} to get started!`);
|
|
1539
1536
|
} catch (e) {
|
|
1540
|
-
logger_default.debug(e);
|
|
1541
1537
|
if (e instanceof Error) {
|
|
1542
|
-
|
|
1538
|
+
console.error(e.message);
|
|
1543
1539
|
}
|
|
1544
1540
|
process.exit(1);
|
|
1545
1541
|
}
|
|
@@ -1554,7 +1550,7 @@ var RootCmd = class extends import_commander.Command {
|
|
|
1554
1550
|
const cmd = new import_commander.Command(name);
|
|
1555
1551
|
cmd.option("-l, --log-level [level]", "Log level: debug, info, warn, error", "info");
|
|
1556
1552
|
cmd.hook("preAction", (run) => {
|
|
1557
|
-
logger_default.
|
|
1553
|
+
logger_default.level = run.opts().logLevel;
|
|
1558
1554
|
});
|
|
1559
1555
|
return cmd;
|
|
1560
1556
|
}
|
|
@@ -1562,7 +1558,7 @@ var RootCmd = class extends import_commander.Command {
|
|
|
1562
1558
|
|
|
1563
1559
|
// src/cli/update.ts
|
|
1564
1560
|
var import_child_process5 = require("child_process");
|
|
1565
|
-
var
|
|
1561
|
+
var import_fs8 = __toESM(require("fs"));
|
|
1566
1562
|
var import_path3 = require("path");
|
|
1567
1563
|
var import_prompts5 = __toESM(require("prompts"));
|
|
1568
1564
|
function update_default(program2) {
|
|
@@ -1587,11 +1583,11 @@ function update_default(program2) {
|
|
|
1587
1583
|
stdio: "inherit"
|
|
1588
1584
|
});
|
|
1589
1585
|
}
|
|
1590
|
-
console.log(
|
|
1586
|
+
console.log(`\u2705 Module updated successfully`);
|
|
1591
1587
|
} catch (e) {
|
|
1592
1588
|
logger_default.debug(e);
|
|
1593
1589
|
if (e instanceof Error) {
|
|
1594
|
-
|
|
1590
|
+
console.error(e.message);
|
|
1595
1591
|
}
|
|
1596
1592
|
process.exit(1);
|
|
1597
1593
|
}
|
|
@@ -1604,59 +1600,28 @@ function update_default(program2) {
|
|
|
1604
1600
|
await write((0, import_path3.resolve)(tsConfig.path), tsConfig.data);
|
|
1605
1601
|
await write((0, import_path3.resolve)(".vscode", snippet.path), snippet.data);
|
|
1606
1602
|
const samplePath = (0, import_path3.resolve)("capabilities", samplesYaml.path);
|
|
1607
|
-
if (
|
|
1608
|
-
|
|
1603
|
+
if (import_fs8.default.existsSync(samplePath)) {
|
|
1604
|
+
import_fs8.default.unlinkSync(samplePath);
|
|
1609
1605
|
await write(samplePath, samplesYaml.data);
|
|
1610
1606
|
}
|
|
1611
1607
|
const tsPath = (0, import_path3.resolve)("capabilities", helloPepr.path);
|
|
1612
|
-
if (
|
|
1608
|
+
if (import_fs8.default.existsSync(tsPath)) {
|
|
1613
1609
|
await write(tsPath, helloPepr.data);
|
|
1614
1610
|
}
|
|
1615
1611
|
}
|
|
1616
1612
|
} catch (e) {
|
|
1617
1613
|
logger_default.debug(e);
|
|
1618
1614
|
if (e instanceof Error) {
|
|
1619
|
-
|
|
1615
|
+
console.error(e.message);
|
|
1620
1616
|
}
|
|
1621
1617
|
process.exit(1);
|
|
1622
1618
|
}
|
|
1623
1619
|
});
|
|
1624
1620
|
}
|
|
1625
1621
|
|
|
1626
|
-
// src/lib.ts
|
|
1627
|
-
var k8s = __toESM(require("@kubernetes/client-node"));
|
|
1628
|
-
var import_http_status_codes2 = require("http-status-codes");
|
|
1629
|
-
var R = __toESM(require("ramda"));
|
|
1630
|
-
|
|
1631
|
-
// src/lib/k8s/upstream.ts
|
|
1632
|
-
var import_client_node3 = require("@kubernetes/client-node");
|
|
1633
|
-
|
|
1634
|
-
// src/lib/fetch.ts
|
|
1635
|
-
var import_http_status_codes = require("http-status-codes");
|
|
1636
|
-
var import_node_fetch = __toESM(require("node-fetch"));
|
|
1637
|
-
|
|
1638
|
-
// src/lib/module.ts
|
|
1639
|
-
var import_ramda3 = require("ramda");
|
|
1640
|
-
|
|
1641
|
-
// src/lib/controller.ts
|
|
1642
|
-
var import_express = __toESM(require("express"));
|
|
1643
|
-
|
|
1644
|
-
// src/lib/processor.ts
|
|
1645
|
-
var import_fast_json_patch = __toESM(require("fast-json-patch"));
|
|
1646
|
-
|
|
1647
|
-
// src/lib/request.ts
|
|
1648
|
-
var import_ramda2 = require("ramda");
|
|
1649
|
-
|
|
1650
|
-
// src/lib/metrics.ts
|
|
1651
|
-
var import_prom_client = __toESM(require("prom-client"));
|
|
1652
|
-
|
|
1653
1622
|
// src/cli.ts
|
|
1654
1623
|
if (process.env.npm_lifecycle_event !== "npx") {
|
|
1655
|
-
|
|
1656
|
-
"Pepr should be run via `npx pepr <command>` instead of `pepr <command>`.",
|
|
1657
|
-
"npx required"
|
|
1658
|
-
);
|
|
1659
|
-
process.exit(1);
|
|
1624
|
+
console.warn("Pepr should be run via `npx pepr <command>` instead of `pepr <command>`.");
|
|
1660
1625
|
}
|
|
1661
1626
|
var program = new RootCmd();
|
|
1662
1627
|
program.version(version).description(`Pepr (v${version}) - Type safe K8s middleware for humans`).action(() => {
|
|
@@ -1664,7 +1629,7 @@ program.version(version).description(`Pepr (v${version}) - Type safe K8s middlew
|
|
|
1664
1629
|
console.log(banner);
|
|
1665
1630
|
program.help();
|
|
1666
1631
|
} else {
|
|
1667
|
-
|
|
1632
|
+
console.error(`Invalid command '${program.args.join(" ")}'
|
|
1668
1633
|
`);
|
|
1669
1634
|
program.outputHelp();
|
|
1670
1635
|
process.exitCode = 1;
|