pepr 0.12.2 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CODE_OF_CONDUCT.md +83 -0
- package/CONTRIBUTING.md +70 -0
- package/README.md +28 -30
- package/dist/cli.js +666 -692
- 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 +17 -0
- package/dist/lib/assets/index.d.ts.map +1 -0
- package/dist/lib/assets/loader.d.ts +8 -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 +4 -9
- package/dist/lib/capability.d.ts.map +1 -1
- package/dist/lib/controller.d.ts +4 -15
- package/dist/lib/controller.d.ts.map +1 -1
- package/dist/lib/errors.d.ts +12 -0
- package/dist/lib/errors.d.ts.map +1 -0
- 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 +18 -14
- 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 +10 -9
- package/dist/lib/metrics.d.ts.map +1 -1
- package/dist/lib/module.d.ts +4 -4
- 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} +7 -7
- package/dist/lib/mutate-request.d.ts.map +1 -0
- package/dist/lib/types.d.ts +48 -55
- 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 +610 -354
- package/dist/lib.js.map +4 -4
- package/jest.config.json +4 -0
- package/journey/before.ts +21 -0
- package/journey/k8s.ts +81 -0
- package/journey/pepr-build.ts +69 -0
- package/journey/pepr-deploy.ts +133 -0
- package/journey/pepr-dev.ts +155 -0
- package/journey/pepr-format.ts +13 -0
- package/journey/pepr-init.ts +12 -0
- package/package.json +29 -27
- package/src/cli.ts +2 -11
- package/src/lib/assets/deploy.ts +179 -0
- package/src/lib/assets/index.ts +53 -0
- package/src/lib/assets/loader.ts +41 -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 +80 -68
- package/src/lib/controller.ts +199 -99
- package/src/lib/errors.ts +20 -0
- 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 +21 -15
- package/src/lib/k8s/upstream.ts +5 -1
- package/src/lib/logger.ts +14 -125
- package/src/lib/metrics.ts +86 -29
- package/src/lib/module.ts +32 -16
- package/src/lib/{processor.ts → mutate-processor.ts} +39 -28
- package/src/lib/{request.ts → mutate-request.ts} +26 -13
- package/src/lib/types.ts +54 -60
- package/src/lib/validate-processor.ts +76 -0
- package/src/lib/validate-request.ts +106 -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,609 @@ 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 = 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(
|
|
549
|
+
await admissionApi.deleteMutatingWebhookConfiguration(mutateWebhook.metadata?.name ?? "");
|
|
550
|
+
await admissionApi.createMutatingWebhookConfiguration(mutateWebhook);
|
|
694
551
|
}
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
if (!path) {
|
|
699
|
-
throw new Error("No code provided");
|
|
700
|
-
}
|
|
701
|
-
const code = await import_fs.promises.readFile(path);
|
|
702
|
-
const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
|
|
703
|
-
const appsApi = kubeConfig.makeApiClient(import_client_node.AppsV1Api);
|
|
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.deploy = this.deploy.bind(this);
|
|
748
|
+
this.zarfYaml = this.zarfYaml.bind(this);
|
|
749
|
+
this.allYaml = this.allYaml.bind(this);
|
|
750
|
+
this.name = `pepr-${config.uuid}`;
|
|
751
|
+
this.image = `ghcr.io/defenseunicorns/pepr/controller:v${config.peprVersion}`;
|
|
752
|
+
this.tls = genTLS(this.host || `${this.name}.pepr-system.svc`);
|
|
753
|
+
this.apiToken = import_crypto3.default.randomBytes(32).toString("hex");
|
|
754
|
+
}
|
|
755
|
+
name;
|
|
756
|
+
tls;
|
|
757
|
+
apiToken;
|
|
758
|
+
capabilities;
|
|
759
|
+
image;
|
|
760
|
+
async deploy(webhookTimeout) {
|
|
761
|
+
this.capabilities = await loadCapabilities(this.path);
|
|
762
|
+
await deploy(this, webhookTimeout);
|
|
763
|
+
}
|
|
764
|
+
zarfYaml(path) {
|
|
765
|
+
return zarfYaml(this, path);
|
|
766
|
+
}
|
|
767
|
+
async allYaml() {
|
|
768
|
+
this.capabilities = await loadCapabilities(this.path);
|
|
769
|
+
return allYaml(this);
|
|
770
|
+
}
|
|
790
771
|
};
|
|
791
772
|
|
|
792
773
|
// src/cli/init/templates.ts
|
|
793
|
-
var
|
|
774
|
+
var import_client_node3 = require("@kubernetes/client-node");
|
|
794
775
|
var import_util = require("util");
|
|
795
776
|
var import_uuid = require("uuid");
|
|
796
777
|
|
|
@@ -880,6 +861,20 @@ var hello_pepr_samples_default = [
|
|
|
880
861
|
key: "ex-2-val"
|
|
881
862
|
}
|
|
882
863
|
},
|
|
864
|
+
{
|
|
865
|
+
apiVersion: "v1",
|
|
866
|
+
kind: "ConfigMap",
|
|
867
|
+
metadata: {
|
|
868
|
+
name: "example-evil-cm",
|
|
869
|
+
namespace: "pepr-demo",
|
|
870
|
+
annotations: {
|
|
871
|
+
evil: "true"
|
|
872
|
+
}
|
|
873
|
+
},
|
|
874
|
+
data: {
|
|
875
|
+
key: "ex-evil-cm-val"
|
|
876
|
+
}
|
|
877
|
+
},
|
|
883
878
|
{
|
|
884
879
|
apiVersion: "v1",
|
|
885
880
|
kind: "ConfigMap",
|
|
@@ -977,8 +972,8 @@ var hello_pepr_samples_default = [
|
|
|
977
972
|
var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n";
|
|
978
973
|
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
974
|
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.
|
|
975
|
+
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';
|
|
976
|
+
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.1", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey:build && npm run test:journey:image && npm run test:journey:run", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:journey:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest journey/entrypoint.test.ts", "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: { "@jest/globals": "29.6.4", "@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.3", jest: "29.6.4", nock: "13.3.3", "ts-jest": "29.1.1" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.5.0", "@typescript-eslint/parser": "6.5.0", commander: "11.0.0", esbuild: "0.19.2", eslint: "8.48.0", "node-forge": "1.3.1", prettier: "3.0.3", prompts: "2.4.2", typescript: "5.2.2", uuid: "9.0.0" } };
|
|
982
977
|
|
|
983
978
|
// src/cli/init/templates/pepr.code-snippets.json
|
|
984
979
|
var pepr_code_snippets_default = {
|
|
@@ -993,13 +988,13 @@ var pepr_code_snippets_default = {
|
|
|
993
988
|
" namespaces: [${2:}],",
|
|
994
989
|
"});",
|
|
995
990
|
"",
|
|
996
|
-
"// Use the 'When' function to create a new
|
|
991
|
+
"// Use the 'When' function to create a new action",
|
|
997
992
|
"const { When } = ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};",
|
|
998
993
|
"",
|
|
999
994
|
"// When(a.<Kind>).Is<Event>().Then(change => change.<changes>",
|
|
1000
995
|
"When(${3:})"
|
|
1001
996
|
],
|
|
1002
|
-
description: "Creates a new Pepr capability with a specified description,
|
|
997
|
+
description: "Creates a new Pepr capability with a specified description, optional namespaces, and adds a When statement for the specified value."
|
|
1003
998
|
}
|
|
1004
999
|
};
|
|
1005
1000
|
|
|
@@ -1025,7 +1020,7 @@ var tsconfig_module_default = {
|
|
|
1025
1020
|
};
|
|
1026
1021
|
|
|
1027
1022
|
// src/cli/init/utils.ts
|
|
1028
|
-
var
|
|
1023
|
+
var import_fs3 = require("fs");
|
|
1029
1024
|
function sanitizeName(name) {
|
|
1030
1025
|
let sanitized = name.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
|
|
1031
1026
|
sanitized = sanitized.replace(/^-+|-+$/g, "");
|
|
@@ -1034,7 +1029,7 @@ function sanitizeName(name) {
|
|
|
1034
1029
|
}
|
|
1035
1030
|
async function createDir(dir) {
|
|
1036
1031
|
try {
|
|
1037
|
-
await
|
|
1032
|
+
await import_fs3.promises.mkdir(dir);
|
|
1038
1033
|
} catch (err) {
|
|
1039
1034
|
if (err && err.code === "EEXIST") {
|
|
1040
1035
|
throw new Error(`Directory ${dir} already exists`);
|
|
@@ -1047,7 +1042,7 @@ function write(path, data) {
|
|
|
1047
1042
|
if (typeof data !== "string") {
|
|
1048
1043
|
data = JSON.stringify(data, null, 2);
|
|
1049
1044
|
}
|
|
1050
|
-
return
|
|
1045
|
+
return import_fs3.promises.writeFile(path, data);
|
|
1051
1046
|
}
|
|
1052
1047
|
|
|
1053
1048
|
// src/cli/init/templates.ts
|
|
@@ -1074,7 +1069,7 @@ function genPkgJSON(opts, pgkVerOverride) {
|
|
|
1074
1069
|
}
|
|
1075
1070
|
},
|
|
1076
1071
|
scripts: {
|
|
1077
|
-
"k3d-setup": scripts["test:
|
|
1072
|
+
"k3d-setup": scripts["test:journey:k3d"]
|
|
1078
1073
|
},
|
|
1079
1074
|
dependencies: {
|
|
1080
1075
|
pepr: pgkVerOverride || version
|
|
@@ -1109,7 +1104,7 @@ var gitignore = {
|
|
|
1109
1104
|
};
|
|
1110
1105
|
var samplesYaml = {
|
|
1111
1106
|
path: "hello-pepr.samples.yaml",
|
|
1112
|
-
data: hello_pepr_samples_default.map((r) => (0,
|
|
1107
|
+
data: hello_pepr_samples_default.map((r) => (0, import_client_node3.dumpYaml)(r, { noRefs: true })).join("---\n")
|
|
1113
1108
|
};
|
|
1114
1109
|
var snippet = {
|
|
1115
1110
|
path: "pepr.code-snippets",
|
|
@@ -1138,23 +1133,25 @@ function build_default(program2) {
|
|
|
1138
1133
|
).action(async (opts) => {
|
|
1139
1134
|
const { cfg, path, uuid } = await buildModule(void 0, opts.entryPoint);
|
|
1140
1135
|
if (opts.entryPoint !== peprTS2) {
|
|
1141
|
-
|
|
1136
|
+
console.info(`\u2705 Module built successfully at ${path}`);
|
|
1142
1137
|
return;
|
|
1143
1138
|
}
|
|
1144
|
-
const
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1139
|
+
const assets = new Assets(
|
|
1140
|
+
{
|
|
1141
|
+
...cfg.pepr,
|
|
1142
|
+
appVersion: cfg.version,
|
|
1143
|
+
description: cfg.description
|
|
1144
|
+
},
|
|
1145
|
+
path
|
|
1146
|
+
);
|
|
1149
1147
|
const yamlFile = `pepr-module-${uuid}.yaml`;
|
|
1150
1148
|
const yamlPath = (0, import_path.resolve)("dist", yamlFile);
|
|
1151
|
-
const yaml = await
|
|
1149
|
+
const yaml = await assets.allYaml();
|
|
1152
1150
|
const zarfPath = (0, import_path.resolve)("dist", "zarf.yaml");
|
|
1153
|
-
const zarf =
|
|
1154
|
-
await
|
|
1155
|
-
await
|
|
1156
|
-
|
|
1157
|
-
logger_default.info(`K8s resource for the module saved to ${yamlPath}`);
|
|
1151
|
+
const zarf = assets.zarfYaml(yamlFile);
|
|
1152
|
+
await import_fs4.promises.writeFile(yamlPath, yaml);
|
|
1153
|
+
await import_fs4.promises.writeFile(zarfPath, zarf);
|
|
1154
|
+
console.info(`\u2705 K8s resource for the module saved to ${yamlPath}`);
|
|
1158
1155
|
});
|
|
1159
1156
|
}
|
|
1160
1157
|
var externalLibs = Object.keys(dependencies);
|
|
@@ -1163,15 +1160,15 @@ async function loadModule(entryPoint = peprTS2) {
|
|
|
1163
1160
|
const cfgPath = (0, import_path.resolve)(".", "package.json");
|
|
1164
1161
|
const input = (0, import_path.resolve)(".", entryPoint);
|
|
1165
1162
|
try {
|
|
1166
|
-
await
|
|
1167
|
-
await
|
|
1163
|
+
await import_fs4.promises.access(cfgPath);
|
|
1164
|
+
await import_fs4.promises.access(input);
|
|
1168
1165
|
} catch (e) {
|
|
1169
|
-
|
|
1166
|
+
console.error(
|
|
1170
1167
|
`Could not find ${cfgPath} or ${input} in the current directory. Please run this command from the root of your module's directory.`
|
|
1171
1168
|
);
|
|
1172
1169
|
process.exit(1);
|
|
1173
1170
|
}
|
|
1174
|
-
const moduleText = await
|
|
1171
|
+
const moduleText = await import_fs4.promises.readFile(cfgPath, { encoding: "utf-8" });
|
|
1175
1172
|
const cfg = JSON.parse(moduleText);
|
|
1176
1173
|
const { uuid } = cfg.pepr;
|
|
1177
1174
|
const name = `pepr-${uuid}.js`;
|
|
@@ -1238,18 +1235,18 @@ async function buildModule(reloader, entryPoint = peprTS2) {
|
|
|
1238
1235
|
}
|
|
1239
1236
|
return { ctx, path, cfg, uuid };
|
|
1240
1237
|
} catch (e) {
|
|
1241
|
-
|
|
1238
|
+
console.error(e.message);
|
|
1242
1239
|
if (e.stdout) {
|
|
1243
1240
|
const out = e.stdout.toString();
|
|
1244
1241
|
const err = e.stderr.toString();
|
|
1245
|
-
|
|
1246
|
-
|
|
1242
|
+
console.log(out);
|
|
1243
|
+
console.error(err);
|
|
1247
1244
|
if (out.includes("Types have separate declarations of a private property '_name'.")) {
|
|
1248
1245
|
const pgkErrMatch = /error TS2322: .*? 'import\("\/.*?\/node_modules\/(.*?)\/node_modules/g;
|
|
1249
1246
|
out.matchAll(pgkErrMatch);
|
|
1250
1247
|
const conflicts = [...out.matchAll(pgkErrMatch)];
|
|
1251
1248
|
if (conflicts.length < 1) {
|
|
1252
|
-
|
|
1249
|
+
console.warn(
|
|
1253
1250
|
`
|
|
1254
1251
|
One or more imported Pepr Capabilities seem to be using an incompatible version of Pepr.
|
|
1255
1252
|
Try updating your Pepr Capabilities to their latest versions.`,
|
|
@@ -1257,7 +1254,7 @@ async function buildModule(reloader, entryPoint = peprTS2) {
|
|
|
1257
1254
|
);
|
|
1258
1255
|
}
|
|
1259
1256
|
conflicts.forEach((match) => {
|
|
1260
|
-
|
|
1257
|
+
console.warn(
|
|
1261
1258
|
`
|
|
1262
1259
|
Package '${match[1]}' seems to be incompatible with your current version of Pepr.
|
|
1263
1260
|
Try updating to the latest version.`,
|
|
@@ -1285,18 +1282,21 @@ function deploy_default(program2) {
|
|
|
1285
1282
|
}
|
|
1286
1283
|
}
|
|
1287
1284
|
const { cfg, path } = await buildModule();
|
|
1288
|
-
const webhook = new
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1285
|
+
const webhook = new Assets(
|
|
1286
|
+
{
|
|
1287
|
+
...cfg.pepr,
|
|
1288
|
+
description: cfg.description
|
|
1289
|
+
},
|
|
1290
|
+
path
|
|
1291
|
+
);
|
|
1292
1292
|
if (opts.image) {
|
|
1293
1293
|
webhook.image = opts.image;
|
|
1294
1294
|
}
|
|
1295
1295
|
try {
|
|
1296
|
-
await webhook.deploy(
|
|
1297
|
-
|
|
1296
|
+
await webhook.deploy();
|
|
1297
|
+
console.info(`\u2705 Module deployed successfully`);
|
|
1298
1298
|
} catch (e) {
|
|
1299
|
-
|
|
1299
|
+
console.error(`Error deploying module: ${e}`);
|
|
1300
1300
|
process.exit(1);
|
|
1301
1301
|
}
|
|
1302
1302
|
});
|
|
@@ -1304,7 +1304,7 @@ function deploy_default(program2) {
|
|
|
1304
1304
|
|
|
1305
1305
|
// src/cli/dev.ts
|
|
1306
1306
|
var import_child_process3 = require("child_process");
|
|
1307
|
-
var
|
|
1307
|
+
var import_fs5 = require("fs");
|
|
1308
1308
|
var import_prompts2 = __toESM(require("prompts"));
|
|
1309
1309
|
function dev_default(program2) {
|
|
1310
1310
|
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,33 +1319,36 @@ function dev_default(program2) {
|
|
|
1319
1319
|
}
|
|
1320
1320
|
}
|
|
1321
1321
|
const { cfg, path } = await loadModule();
|
|
1322
|
-
const webhook = new
|
|
1322
|
+
const webhook = new Assets(
|
|
1323
1323
|
{
|
|
1324
1324
|
...cfg.pepr,
|
|
1325
1325
|
description: cfg.description
|
|
1326
1326
|
},
|
|
1327
|
+
path,
|
|
1327
1328
|
opts.host
|
|
1328
1329
|
);
|
|
1329
|
-
await
|
|
1330
|
-
await
|
|
1330
|
+
await import_fs5.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
|
|
1331
|
+
await import_fs5.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
|
|
1331
1332
|
try {
|
|
1332
1333
|
let program3;
|
|
1333
1334
|
const runFork = async () => {
|
|
1334
|
-
|
|
1335
|
-
await webhook.deploy(
|
|
1335
|
+
console.info(`Running module ${path}`);
|
|
1336
|
+
await webhook.deploy(30);
|
|
1336
1337
|
program3 = (0, import_child_process3.fork)(path, {
|
|
1337
1338
|
env: {
|
|
1338
1339
|
...process.env,
|
|
1339
1340
|
LOG_LEVEL: "debug",
|
|
1340
1341
|
PEPR_API_TOKEN: webhook.apiToken,
|
|
1342
|
+
PEPR_PRETTY_LOGS: "true",
|
|
1341
1343
|
SSL_KEY_PATH: "insecure-tls.key",
|
|
1342
1344
|
SSL_CERT_PATH: "insecure-tls.crt"
|
|
1343
|
-
}
|
|
1345
|
+
},
|
|
1346
|
+
stdio: "inherit"
|
|
1344
1347
|
});
|
|
1345
1348
|
};
|
|
1346
1349
|
await buildModule(async (r) => {
|
|
1347
1350
|
if (r.errors.length > 0) {
|
|
1348
|
-
|
|
1351
|
+
console.error(`Error compiling module: ${r.errors}`);
|
|
1349
1352
|
return;
|
|
1350
1353
|
}
|
|
1351
1354
|
if (program3) {
|
|
@@ -1356,7 +1359,7 @@ function dev_default(program2) {
|
|
|
1356
1359
|
}
|
|
1357
1360
|
});
|
|
1358
1361
|
} catch (e) {
|
|
1359
|
-
|
|
1362
|
+
console.error(`Error deploying module: ${e}`);
|
|
1360
1363
|
process.exit(1);
|
|
1361
1364
|
}
|
|
1362
1365
|
});
|
|
@@ -1364,7 +1367,7 @@ function dev_default(program2) {
|
|
|
1364
1367
|
|
|
1365
1368
|
// src/cli/format.ts
|
|
1366
1369
|
var import_eslint = require("eslint");
|
|
1367
|
-
var
|
|
1370
|
+
var import_fs6 = require("fs");
|
|
1368
1371
|
var import_prettier = require("prettier");
|
|
1369
1372
|
function format_default(program2) {
|
|
1370
1373
|
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 +1390,24 @@ function format_default(program2) {
|
|
|
1387
1390
|
await import_eslint.ESLint.outputFixes(results);
|
|
1388
1391
|
}
|
|
1389
1392
|
for (const { filePath } of results) {
|
|
1390
|
-
const content = await
|
|
1393
|
+
const content = await import_fs6.promises.readFile(filePath, "utf8");
|
|
1391
1394
|
const cfg = await (0, import_prettier.resolveConfig)(filePath);
|
|
1392
|
-
const formatted = (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
|
|
1395
|
+
const formatted = await (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
|
|
1393
1396
|
if (opts.validateOnly) {
|
|
1394
1397
|
if (formatted !== content) {
|
|
1395
1398
|
hasFailure = true;
|
|
1396
|
-
|
|
1399
|
+
console.error(`File ${filePath} is not formatted correctly`);
|
|
1397
1400
|
}
|
|
1398
1401
|
} else {
|
|
1399
|
-
await
|
|
1402
|
+
await import_fs6.promises.writeFile(filePath, formatted);
|
|
1400
1403
|
}
|
|
1401
1404
|
}
|
|
1402
1405
|
if (opts.validateOnly && hasFailure) {
|
|
1403
1406
|
process.exit(1);
|
|
1404
1407
|
}
|
|
1405
|
-
|
|
1408
|
+
console.info("\u2705 Module formatted");
|
|
1406
1409
|
} catch (e) {
|
|
1407
|
-
|
|
1408
|
-
logger_default.error(e.message);
|
|
1410
|
+
console.error(e.message);
|
|
1409
1411
|
process.exit(1);
|
|
1410
1412
|
}
|
|
1411
1413
|
});
|
|
@@ -1417,8 +1419,18 @@ var import_path2 = require("path");
|
|
|
1417
1419
|
var import_prompts4 = __toESM(require("prompts"));
|
|
1418
1420
|
|
|
1419
1421
|
// src/cli/init/walkthrough.ts
|
|
1420
|
-
var
|
|
1422
|
+
var import_fs7 = require("fs");
|
|
1421
1423
|
var import_prompts3 = __toESM(require("prompts"));
|
|
1424
|
+
|
|
1425
|
+
// src/lib/errors.ts
|
|
1426
|
+
var Errors = {
|
|
1427
|
+
audit: "audit",
|
|
1428
|
+
ignore: "ignore",
|
|
1429
|
+
reject: "reject"
|
|
1430
|
+
};
|
|
1431
|
+
var ErrorList = Object.values(Errors);
|
|
1432
|
+
|
|
1433
|
+
// src/cli/init/walkthrough.ts
|
|
1422
1434
|
function walkthrough() {
|
|
1423
1435
|
const askName = {
|
|
1424
1436
|
type: "text",
|
|
@@ -1427,7 +1439,7 @@ function walkthrough() {
|
|
|
1427
1439
|
validate: async (val) => {
|
|
1428
1440
|
try {
|
|
1429
1441
|
const name = sanitizeName(val);
|
|
1430
|
-
await
|
|
1442
|
+
await import_fs7.promises.access(name, import_fs7.promises.constants.F_OK);
|
|
1431
1443
|
return "A directory with this name already exists";
|
|
1432
1444
|
} catch (e) {
|
|
1433
1445
|
return val.length > 2 || "The name must be at least 3 characters long";
|
|
@@ -1442,23 +1454,22 @@ function walkthrough() {
|
|
|
1442
1454
|
const askErrorBehavior = {
|
|
1443
1455
|
type: "select",
|
|
1444
1456
|
name: "errorBehavior",
|
|
1445
|
-
validate: (val) => ErrorBehavior[val],
|
|
1446
1457
|
message: "How do you want Pepr to handle errors encountered during K8s operations?",
|
|
1447
1458
|
choices: [
|
|
1448
1459
|
{
|
|
1449
1460
|
title: "Ignore",
|
|
1450
|
-
value:
|
|
1461
|
+
value: Errors.ignore,
|
|
1451
1462
|
description: "Pepr will continue processing and generate an entry in the Pepr Controller log.",
|
|
1452
1463
|
selected: true
|
|
1453
1464
|
},
|
|
1454
1465
|
{
|
|
1455
1466
|
title: "Log an audit event",
|
|
1456
|
-
value:
|
|
1467
|
+
value: Errors.audit,
|
|
1457
1468
|
description: "Pepr will continue processing and generate an entry in the Pepr Controller log as well as an audit event in the cluster."
|
|
1458
1469
|
},
|
|
1459
1470
|
{
|
|
1460
1471
|
title: "Reject the operation",
|
|
1461
|
-
value:
|
|
1472
|
+
value: Errors.reject,
|
|
1462
1473
|
description: "Pepr will reject the operation and return an error to the client."
|
|
1463
1474
|
}
|
|
1464
1475
|
]
|
|
@@ -1537,9 +1548,8 @@ function init_default(program2) {
|
|
|
1537
1548
|
console.log(`New Pepr module created at ${dirName}`);
|
|
1538
1549
|
console.log(`Open VSCode or your editor of choice in ${dirName} to get started!`);
|
|
1539
1550
|
} catch (e) {
|
|
1540
|
-
logger_default.debug(e);
|
|
1541
1551
|
if (e instanceof Error) {
|
|
1542
|
-
|
|
1552
|
+
console.error(e.message);
|
|
1543
1553
|
}
|
|
1544
1554
|
process.exit(1);
|
|
1545
1555
|
}
|
|
@@ -1550,11 +1560,12 @@ function init_default(program2) {
|
|
|
1550
1560
|
// src/cli/root.ts
|
|
1551
1561
|
var import_commander = require("commander");
|
|
1552
1562
|
var RootCmd = class extends import_commander.Command {
|
|
1563
|
+
// eslint-disable-next-line class-methods-use-this
|
|
1553
1564
|
createCommand(name) {
|
|
1554
1565
|
const cmd = new import_commander.Command(name);
|
|
1555
1566
|
cmd.option("-l, --log-level [level]", "Log level: debug, info, warn, error", "info");
|
|
1556
1567
|
cmd.hook("preAction", (run) => {
|
|
1557
|
-
logger_default.
|
|
1568
|
+
logger_default.level = run.opts().logLevel;
|
|
1558
1569
|
});
|
|
1559
1570
|
return cmd;
|
|
1560
1571
|
}
|
|
@@ -1562,7 +1573,7 @@ var RootCmd = class extends import_commander.Command {
|
|
|
1562
1573
|
|
|
1563
1574
|
// src/cli/update.ts
|
|
1564
1575
|
var import_child_process5 = require("child_process");
|
|
1565
|
-
var
|
|
1576
|
+
var import_fs8 = __toESM(require("fs"));
|
|
1566
1577
|
var import_path3 = require("path");
|
|
1567
1578
|
var import_prompts5 = __toESM(require("prompts"));
|
|
1568
1579
|
function update_default(program2) {
|
|
@@ -1587,12 +1598,9 @@ function update_default(program2) {
|
|
|
1587
1598
|
stdio: "inherit"
|
|
1588
1599
|
});
|
|
1589
1600
|
}
|
|
1590
|
-
console.log(
|
|
1601
|
+
console.log(`\u2705 Module updated successfully`);
|
|
1591
1602
|
} catch (e) {
|
|
1592
|
-
|
|
1593
|
-
if (e instanceof Error) {
|
|
1594
|
-
logger_default.error(e.message);
|
|
1595
|
-
}
|
|
1603
|
+
console.error(e.message);
|
|
1596
1604
|
process.exit(1);
|
|
1597
1605
|
}
|
|
1598
1606
|
});
|
|
@@ -1604,59 +1612,25 @@ function update_default(program2) {
|
|
|
1604
1612
|
await write((0, import_path3.resolve)(tsConfig.path), tsConfig.data);
|
|
1605
1613
|
await write((0, import_path3.resolve)(".vscode", snippet.path), snippet.data);
|
|
1606
1614
|
const samplePath = (0, import_path3.resolve)("capabilities", samplesYaml.path);
|
|
1607
|
-
if (
|
|
1608
|
-
|
|
1615
|
+
if (import_fs8.default.existsSync(samplePath)) {
|
|
1616
|
+
import_fs8.default.unlinkSync(samplePath);
|
|
1609
1617
|
await write(samplePath, samplesYaml.data);
|
|
1610
1618
|
}
|
|
1611
1619
|
const tsPath = (0, import_path3.resolve)("capabilities", helloPepr.path);
|
|
1612
|
-
if (
|
|
1620
|
+
if (import_fs8.default.existsSync(tsPath)) {
|
|
1613
1621
|
await write(tsPath, helloPepr.data);
|
|
1614
1622
|
}
|
|
1615
1623
|
}
|
|
1616
1624
|
} catch (e) {
|
|
1617
|
-
|
|
1618
|
-
if (e instanceof Error) {
|
|
1619
|
-
logger_default.error(e.message);
|
|
1620
|
-
}
|
|
1625
|
+
console.error(e.message);
|
|
1621
1626
|
process.exit(1);
|
|
1622
1627
|
}
|
|
1623
1628
|
});
|
|
1624
1629
|
}
|
|
1625
1630
|
|
|
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
1631
|
// src/cli.ts
|
|
1654
1632
|
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);
|
|
1633
|
+
console.warn("Pepr should be run via `npx pepr <command>` instead of `pepr <command>`.");
|
|
1660
1634
|
}
|
|
1661
1635
|
var program = new RootCmd();
|
|
1662
1636
|
program.version(version).description(`Pepr (v${version}) - Type safe K8s middleware for humans`).action(() => {
|
|
@@ -1664,7 +1638,7 @@ program.version(version).description(`Pepr (v${version}) - Type safe K8s middlew
|
|
|
1664
1638
|
console.log(banner);
|
|
1665
1639
|
program.help();
|
|
1666
1640
|
} else {
|
|
1667
|
-
|
|
1641
|
+
console.error(`Invalid command '${program.args.join(" ")}'
|
|
1668
1642
|
`);
|
|
1669
1643
|
program.outputHelp();
|
|
1670
1644
|
process.exitCode = 1;
|