pepr 0.1.45 → 0.2.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/dist/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "engines": {
10
10
  "node": ">=18.0.0"
11
11
  },
12
- "version": "0.1.45",
12
+ "version": "0.2.1",
13
13
  "main": "dist/index.js",
14
14
  "types": "dist/index.d.ts",
15
15
  "pepr": {
@@ -26,24 +26,23 @@
26
26
  "scripts": {
27
27
  "prebuild": "rm -fr dist/* && node hack/build-template-data.js",
28
28
  "build": "tsc -p tsconfig.build.json",
29
- "test": "npm run build && ava && node dist/cli.js -V",
30
- "test:e2e": "ava hack/e2e.test.js",
31
- "test:e2e-setup": "npm run build && npm uninstall pepr -g && npm install -g .",
32
- "lint": "npx eslint src",
33
- "lint:fix": "npm run lint -- --fix",
34
- "prettier": "npx prettier src --check",
35
- "prettier:fix": "npm run prettier -- --write",
36
- "prepublishOnly": "npm run lint:fix && npm run prettier:fix && npm run test",
37
- "e2e-dev-setup": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'"
29
+ "test:unit": "npm run build && ava",
30
+ "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run",
31
+ "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'",
32
+ "test:e2e:build": "npm run build && npm uninstall pepr -g && npm install -g . && pepr",
33
+ "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev",
34
+ "test:e2e:run": "ava hack/e2e.test.js --sequential",
35
+ "format:check": "eslint src && prettier src --check",
36
+ "format:fix": "eslint src --fix && prettier src --write"
38
37
  },
39
38
  "dependencies": {
40
39
  "@kubernetes/client-node": "^0.18.1",
41
40
  "@rollup/plugin-json": "^6.0.0",
42
- "@rollup/plugin-node-resolve": "^15.0.1",
43
- "@rollup/plugin-typescript": "^11.0.0",
41
+ "@rollup/plugin-node-resolve": "^15.0.2",
42
+ "@rollup/plugin-typescript": "^11.1.0",
44
43
  "@types/ramda": "^0.29.0",
45
44
  "chokidar": "^3.5.3",
46
- "commander": "^10.0.0",
45
+ "commander": "^10.0.1",
47
46
  "express": "^4.18.2",
48
47
  "fast-json-patch": "^3.1.1",
49
48
  "node-fetch": "^2.6.9",
@@ -51,10 +50,10 @@
51
50
  "prettier": "^2.8.7",
52
51
  "prompts": "^2.4.2",
53
52
  "ramda": "^0.29.0",
54
- "rollup": "^3.20.2",
53
+ "rollup": "^3.20.6",
55
54
  "ts-node": "^10.9.1",
56
55
  "tslib": "^2.5.0",
57
- "typescript": "^5.0.2",
56
+ "typescript": "^5.0.4",
58
57
  "uuid": "^9.0.0"
59
58
  },
60
59
  "devDependencies": {
@@ -63,10 +62,10 @@
63
62
  "@types/node-forge": "^1.3.2",
64
63
  "@types/prompts": "^2.4.4",
65
64
  "@types/uuid": "^9.0.1",
66
- "@typescript-eslint/eslint-plugin": "^5.57.0",
67
- "@typescript-eslint/parser": "^5.57.0",
65
+ "@typescript-eslint/eslint-plugin": "^5.59.0",
66
+ "@typescript-eslint/parser": "^5.59.0",
68
67
  "ava": "^5.2.0",
69
- "eslint": "^8.37.0",
68
+ "eslint": "^8.38.0",
70
69
  "nock": "^13.3.0"
71
70
  },
72
71
  "ava": {
package/dist/run.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "./src/cli/run";
package/dist/run.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ require("./src/cli/run");
@@ -1,6 +1,6 @@
1
1
  import { RootCmd } from "./root";
2
2
  export default function (program: RootCmd): void;
3
- export declare function buildModule(moduleDir: string): Promise<{
3
+ export declare function buildModule(): Promise<{
4
4
  path: string;
5
5
  cfg: any;
6
6
  uuid: any;
@@ -19,12 +19,11 @@ function default_1(program) {
19
19
  program
20
20
  .command("build")
21
21
  .description("Build a Pepr Module for deployment")
22
- .option("-d, --dir [directory]", "Pepr module directory", ".")
23
- .action(async (opts) => {
22
+ .action(async () => {
24
23
  // Build the module
25
- const { cfg, path, uuid } = await buildModule(opts.dir);
24
+ const { cfg, path, uuid } = await buildModule();
26
25
  // Read the compiled module code
27
- const code = await fs_1.promises.readFile(path, { encoding: "utf-8" });
26
+ const code = await fs_1.promises.readFile(path);
28
27
  // Generate a secret for the module
29
28
  const webhook = new webhook_1.Webhook({
30
29
  ...cfg.pepr,
@@ -46,12 +45,21 @@ exports.default = default_1;
46
45
  const externalLibs = Object.keys(package_json_1.dependencies).map(dep => new RegExp(`^${dep}.*`));
47
46
  // Add the pepr library to the list of external libraries
48
47
  externalLibs.push("pepr");
49
- async function buildModule(moduleDir) {
48
+ async function buildModule() {
50
49
  try {
51
50
  // Resolve the path to the module's package.json file
52
- const cfgPath = (0, path_1.resolve)(moduleDir, "package.json");
53
- const input = (0, path_1.resolve)(moduleDir, "pepr.ts");
54
- // Read the module's UUID from the package.json filel
51
+ const cfgPath = (0, path_1.resolve)(".", "package.json");
52
+ const input = (0, path_1.resolve)(".", "pepr.ts");
53
+ // Ensure the module's package.json and pepr.ts files exist
54
+ try {
55
+ await fs_1.promises.access(cfgPath);
56
+ await fs_1.promises.access(input);
57
+ }
58
+ catch (e) {
59
+ logger_1.default.error(`Could not find ${cfgPath} or ${input} in the current directory. Please run this command from the root of your module's directory.`);
60
+ process.exit(1);
61
+ }
62
+ // Read the module's UUID from the package.json file
55
63
  const moduleText = await fs_1.promises.readFile(cfgPath, { encoding: "utf-8" });
56
64
  const cfg = JSON.parse(moduleText);
57
65
  const { uuid } = cfg.pepr;
@@ -6,7 +6,6 @@ function default_1(program) {
6
6
  program
7
7
  .command("new")
8
8
  .description("Create a new Pepr Capability")
9
- .option("-d, --dir [directory]", "Pepr module directory", ".")
10
9
  .action(() => {
11
10
  // TODO: Create a new capability
12
11
  console.log("new");
@@ -14,11 +14,10 @@ function default_1(program) {
14
14
  program
15
15
  .command("deploy")
16
16
  .description("Deploy a Pepr Module")
17
- .option("-d, --dir [directory]", "Pepr module directory", ".")
18
17
  .option("-i, --image [image]", "Override the image tag")
19
- .option("-f, --force", "Force redeployment")
18
+ .option("--confirm", "Skip confirmation prompt")
20
19
  .action(async (opts) => {
21
- if (!opts.force) {
20
+ if (!opts.confirm) {
22
21
  // Prompt the user to confirm
23
22
  const confirm = await (0, prompts_1.prompt)({
24
23
  type: "confirm",
@@ -31,9 +30,9 @@ function default_1(program) {
31
30
  }
32
31
  }
33
32
  // Build the module
34
- const { cfg, path } = await (0, build_1.buildModule)(opts.dir);
33
+ const { cfg, path } = await (0, build_1.buildModule)();
35
34
  // Read the compiled module code
36
- const code = await fs_1.promises.readFile(path, { encoding: "utf-8" });
35
+ const code = await fs_1.promises.readFile(path);
37
36
  // Generate a secret for the module
38
37
  const webhook = new webhook_1.Webhook({
39
38
  ...cfg.pepr,
@@ -17,7 +17,6 @@ function default_1(program) {
17
17
  program
18
18
  .command("dev")
19
19
  .description("Setup a local webhook development environment")
20
- .option("-d, --dir [directory]", "Pepr module directory", ".")
21
20
  .option("-h, --host [host]", "Host to listen on", "host.docker.internal")
22
21
  .option("--confirm", "Skip confirmation prompt")
23
22
  .action(async (opts) => {
@@ -34,9 +33,9 @@ function default_1(program) {
34
33
  }
35
34
  }
36
35
  // Build the module
37
- const { cfg, path } = await (0, build_1.buildModule)(opts.dir);
36
+ const { cfg, path } = await (0, build_1.buildModule)();
38
37
  // Read the compiled module code
39
- const code = await fs_1.promises.readFile(path, { encoding: "utf-8" });
38
+ const code = await fs_1.promises.readFile(path);
40
39
  // Generate a secret for the module
41
40
  const webhook = new webhook_1.Webhook({
42
41
  ...cfg.pepr,
@@ -48,9 +47,9 @@ function default_1(program) {
48
47
  try {
49
48
  await webhook.deploy(code);
50
49
  logger_1.default.info(`Module deployed successfully`);
51
- const moduleFiles = (0, path_1.resolve)(opts.dir, "**", "*.ts");
50
+ const moduleFiles = (0, path_1.resolve)(".", "**", "*.ts");
52
51
  const watcher = (0, chokidar_1.watch)(moduleFiles);
53
- const peprTS = (0, path_1.resolve)(opts.dir, "pepr.ts");
52
+ const peprTS = (0, path_1.resolve)(".", "pepr.ts");
54
53
  let program;
55
54
  // Run the module once to start the server
56
55
  runDev(peprTS);
@@ -80,6 +79,7 @@ function runDev(path) {
80
79
  const program = (0, child_process_1.spawn)("./node_modules/.bin/ts-node", [path], {
81
80
  env: {
82
81
  ...process.env,
82
+ LOG_LEVEL: "debug",
83
83
  SSL_KEY_PATH: "insecure-tls.key",
84
84
  SSL_CERT_PATH: "insecure-tls.crt",
85
85
  },
@@ -1 +1 @@
1
- { "gitignore": "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n", "readme": "# 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├── package.json\n├── pepr.ts\n└── capabilities\n ├── example-one.ts\n ├── example-three.ts\n └── example-two.ts\n```\n", "peprTS": "import { PeprModule } from \"pepr\";\nimport { HelloPepr } from \"./capabilities/hello-pepr\";\nimport cfg from \"./package.json\";\n\n/**\n * This is the main entrypoint for the Pepr module. It is the file that is run when the module is started.\n * This is where you register your configurations and capabilities with the module.\n */\nnew PeprModule(cfg, [\n // \"HelloPepr\" is a demo capability that is included with Pepr. You can remove it if you want.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n", "helloPeprTS": "import { Capability, PeprRequest, RegisterKind, a, fetch } 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 can run `pepr dev` or `npm start` 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\"],\n});\n\n// Use the 'When' function to create a new Capability Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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 *\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 exmaple, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivelant 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 *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capabiility 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 *\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 procssed.\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 reuest\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/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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-5\")\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 intelisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel(\"pepr.dev/third\", \"true\");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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 equivelant:\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 const joke = await fetch<TheChuckNorrisJoke>(\n \"https://api.chucknorris.io/jokes/random?category=dev\"\n );\n\n // Add the Chuck Norris joke to the configmap\n change.Raw.data[\"chuck-says\"] = joke.value;\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION *\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 intelisense 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 ot 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 *\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 intelisense\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 ot 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" }
1
+ { "gitignore": "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n", "readme": "# 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├── package.json\n├── pepr.ts\n└── capabilities\n ├── example-one.ts\n ├── example-three.ts\n └── example-two.ts\n```\n", "peprTS": "import { PeprModule } from \"pepr\";\nimport { HelloPepr } from \"./capabilities/hello-pepr\";\nimport cfg from \"./package.json\";\n\n/**\n * This is the main entrypoint for the Pepr module. It is the file that is run when the module is started.\n * This is where you register your configurations and capabilities with the module.\n */\nnew PeprModule(cfg, [\n // \"HelloPepr\" is a demo capability that is included with Pepr. You can remove it if you want.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n", "helloPeprTS": "import { Capability, PeprRequest, RegisterKind, a, fetch } 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 can run `pepr dev` or `npm start` 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\"],\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/**\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 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 const joke = await fetch<TheChuckNorrisJoke>(\n \"https://api.chucknorris.io/jokes/random?category=dev\"\n );\n\n // Add the Chuck Norris joke to the configmap\n change.Raw.data[\"chuck-says\"] = joke.value;\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 ot 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 ot 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" }
@@ -51,10 +51,7 @@
51
51
  "kind": "ConfigMap",
52
52
  "metadata": {
53
53
  "name": "example-4",
54
- "namespace": "pepr-demo",
55
- "labels": {
56
- "chuck-norris": "test"
57
- }
54
+ "namespace": "pepr-demo"
58
55
  },
59
56
  "data": {
60
57
  "key": "ex-4-val"
@@ -65,7 +62,13 @@
65
62
  "kind": "ConfigMap",
66
63
  "metadata": {
67
64
  "name": "example-5",
68
- "namespace": "pepr-demo"
65
+ "namespace": "pepr-demo",
66
+ "labels": {
67
+ "chuck-norris": "test"
68
+ }
69
+ },
70
+ "data": {
71
+ "key": "ex-5-val"
69
72
  }
70
73
  },
71
74
  {
@@ -18,6 +18,7 @@ export declare function genPkgJSON(opts: InitOptions, pgkVerOverride?: string):
18
18
  scripts: {
19
19
  "k3d-setup": string;
20
20
  build: string;
21
+ deploy: string;
21
22
  start: string;
22
23
  };
23
24
  dependencies: {
@@ -39,8 +39,9 @@ function genPkgJSON(opts, pgkVerOverride) {
39
39
  },
40
40
  },
41
41
  scripts: {
42
- "k3d-setup": package_json_1.scripts["e2e-dev-setup"],
42
+ "k3d-setup": package_json_1.scripts["test:e2e:k3d"],
43
43
  build: "pepr build",
44
+ deploy: "pepr deploy",
44
45
  start: "pepr dev",
45
46
  },
46
47
  dependencies: {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ const commander_1 = require("commander");
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const zlib_1 = require("zlib");
12
+ const package_json_1 = require("../../package.json");
13
+ const logger_1 = __importDefault(require("../lib/logger"));
14
+ commander_1.program
15
+ .version(package_json_1.version)
16
+ .description(`Pepr Kubernetes Runtime (v${package_json_1.version})`)
17
+ .argument("<hash>", "Hash of the module to run")
18
+ .option("-l, --log-level [level]", "Log level: debug, info, warn, error", "info")
19
+ .action((expectedHash, opts) => {
20
+ const gzPath = `/app/load/module-${expectedHash}.js.gz`;
21
+ const jsPath = `/app/module-${expectedHash}.js`;
22
+ // Require the has to be 64 characters long
23
+ if (expectedHash.length !== 64) {
24
+ logger_1.default.error("Invalid hash");
25
+ process.exit(1);
26
+ }
27
+ // Check if the path is a valid file
28
+ if (!fs_1.default.existsSync(gzPath)) {
29
+ logger_1.default.error(`File not found: ${gzPath}`);
30
+ process.exit(1);
31
+ }
32
+ // Set the log level
33
+ logger_1.default.SetLogLevel(opts.logLevel);
34
+ try {
35
+ logger_1.default.info(`Loading module ${gzPath}`);
36
+ // Extract the code from the file
37
+ const codeGZ = fs_1.default.readFileSync(gzPath);
38
+ const code = (0, zlib_1.gunzipSync)(codeGZ);
39
+ // Get the hash of the extracted code
40
+ const actualHash = crypto_1.default.createHash("sha256").update(code).digest("hex");
41
+ // If the hash doesn't match, exit
42
+ if (expectedHash !== actualHash) {
43
+ logger_1.default.error(`File hash does not match, expected ${expectedHash} but got ${actualHash}`);
44
+ process.exit(1);
45
+ }
46
+ logger_1.default.info(`File hash matches, running module`);
47
+ // Write the code to a file
48
+ fs_1.default.writeFileSync(jsPath, code);
49
+ // Run the module
50
+ // @todo: evaluate vm (isolate) vs require
51
+ require(jsPath);
52
+ }
53
+ catch (e) {
54
+ logger_1.default.error(`Failed to decompress module: ${e}`);
55
+ process.exit(1);
56
+ }
57
+ });
58
+ commander_1.program.parse();
@@ -16,27 +16,26 @@ function default_1(program) {
16
16
  program
17
17
  .command("test")
18
18
  .description("Test a Pepr Module locally")
19
- .option("-d, --dir [directory]", "Pepr module directory", ".")
20
19
  .option("-w, --watch", "Watch for changes and re-run the test")
21
20
  .action(async (opts) => {
22
21
  logger_1.default.info("Test Module");
23
- await buildAndTest(opts.dir);
22
+ await buildAndTest();
24
23
  if (opts.watch) {
25
- const moduleFiles = (0, path_1.resolve)(opts.dir, "**", "*.ts");
24
+ const moduleFiles = (0, path_1.resolve)(".", "**", "*.ts");
26
25
  const watcher = (0, chokidar_1.watch)(moduleFiles);
27
26
  watcher.on("ready", () => {
28
27
  logger_1.default.info(`Watching for changes in ${moduleFiles}`);
29
28
  watcher.on("all", async (event, path) => {
30
29
  logger_1.default.debug({ event, path }, "File changed");
31
- await buildAndTest(opts.dir);
30
+ await buildAndTest();
32
31
  });
33
32
  });
34
33
  }
35
34
  });
36
35
  }
37
36
  exports.default = default_1;
38
- async function buildAndTest(dir) {
39
- const { path } = await (0, build_1.buildModule)(dir);
37
+ async function buildAndTest() {
38
+ const { path } = await (0, build_1.buildModule)();
40
39
  logger_1.default.info(`Module built successfully at ${path}`);
41
40
  try {
42
41
  const { stdout, stderr } = await exec(`node ${path}`);
@@ -74,7 +74,7 @@ class Capability {
74
74
  };
75
75
  const ThenSet = (merge) => {
76
76
  // Add the new action to the binding
77
- Then(async (req) => req.Merge(merge));
77
+ Then(req => req.Merge(merge));
78
78
  return { Then };
79
79
  };
80
80
  function InNamespace(...namespaces) {
@@ -18,6 +18,10 @@ function shouldSkipRequest(binding, req) {
18
18
  const { group, kind, version } = binding.kind || {};
19
19
  const { namespaces, labels, annotations, name } = binding.filters || {};
20
20
  const { metadata } = req.object || {};
21
+ // Test for matching operation
22
+ if (binding.event && !binding.event.includes(req.operation)) {
23
+ return true;
24
+ }
21
25
  // Test name first, since it's the most specific
22
26
  if (name && name !== req.name) {
23
27
  return true;
@@ -39,7 +43,7 @@ function shouldSkipRequest(binding, req) {
39
43
  logger_1.default.debug("Namespace does not match");
40
44
  return true;
41
45
  }
42
- // Test for matching lables
46
+ // Test for matching labels
43
47
  for (const [key, value] of Object.entries(labels)) {
44
48
  const testKey = metadata?.labels?.[key];
45
49
  // First check if the label exists
@@ -1,5 +1,5 @@
1
1
  import * as kind from "./upstream";
2
- /** a is a colleciton of K8s types to be used within a CapabilityAction: `When(a.Configmap)` */
2
+ /** a is a collection of K8s types to be used within a CapabilityAction: `When(a.Configmap)` */
3
3
  export { kind as a };
4
4
  export { modelToGroupVersionKind, gvkMap, RegisterKind } from "./kinds";
5
5
  export * from "./types";
@@ -6,6 +6,6 @@ export declare function modelToGroupVersionKind(key: string): GroupVersionKind;
6
6
  * Registers a new model and GroupVersionKind with Pepr for use with `When(a.<Kind>)`
7
7
  *
8
8
  * @param model Used to match the GroupVersionKind and define the type-data for the request
9
- * @param groupVersionKind Contains the match paramaters to determine the request should be handled
9
+ * @param groupVersionKind Contains the match parameters to determine the request should be handled
10
10
  */
11
11
  export declare const RegisterKind: (model: GenericClass, groupVersionKind: GroupVersionKind) => void;
@@ -433,7 +433,7 @@ exports.modelToGroupVersionKind = modelToGroupVersionKind;
433
433
  * Registers a new model and GroupVersionKind with Pepr for use with `When(a.<Kind>)`
434
434
  *
435
435
  * @param model Used to match the GroupVersionKind and define the type-data for the request
436
- * @param groupVersionKind Contains the match paramaters to determine the request should be handled
436
+ * @param groupVersionKind Contains the match parameters to determine the request should be handled
437
437
  */
438
438
  const RegisterKind = (model, groupVersionKind) => {
439
439
  const name = model.name;
@@ -28,8 +28,8 @@ export declare class GenericKind {
28
28
  [key: string]: any;
29
29
  }
30
30
  /**
31
- * GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
32
- * to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
31
+ * GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
32
+ * to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
33
33
  **/
34
34
  export interface GroupVersionKind {
35
35
  /** The K8s resource kind, e..g "Pod". */
@@ -38,8 +38,8 @@ export interface GroupVersionKind {
38
38
  readonly version?: string;
39
39
  }
40
40
  /**
41
- * GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion
42
- * to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
41
+ * GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion
42
+ * to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
43
43
  */
44
44
  export interface GroupVersionResource {
45
45
  readonly group: string;
@@ -56,13 +56,13 @@ export interface Request<T = KubernetesObject> {
56
56
  readonly kind: GroupVersionKind;
57
57
  /** Resource is the fully-qualified resource being requested (for example, v1.pods) */
58
58
  readonly resource: GroupVersionResource;
59
- /** SubResource is the subresource being requested, if any (for example, "status" or "scale") */
59
+ /** SubResource is the sub-resource being requested, if any (for example, "status" or "scale") */
60
60
  readonly subResource?: string;
61
61
  /** RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). */
62
62
  readonly requestKind?: GroupVersionKind;
63
63
  /** RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). */
64
64
  readonly requestResource?: GroupVersionResource;
65
- /** RequestSubResource is the subresource of the original API request, if any (for example, "status" or "scale"). */
65
+ /** RequestSubResource is the sub-resource of the original API request, if any (for example, "status" or "scale"). */
66
66
  readonly requestSubResource?: string;
67
67
  /**
68
68
  * Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" />
1
2
  import { V1ClusterRole, V1ClusterRoleBinding, V1Deployment, V1MutatingWebhookConfiguration, V1Namespace, V1NetworkPolicy, V1Secret, V1Service, V1ServiceAccount } from "@kubernetes/client-node";
2
3
  import { ModuleConfig } from "../types";
3
4
  import { TLSOut } from "./tls";
@@ -22,12 +23,12 @@ export declare class Webhook {
22
23
  serviceAccount(): V1ServiceAccount;
23
24
  tlsSecret(): V1Secret;
24
25
  mutatingWebhook(): V1MutatingWebhookConfiguration;
25
- deployment(): V1Deployment;
26
- /** Only permit the */
26
+ deployment(hash: string): V1Deployment;
27
+ /** Only permit the kube-system ns ingress access to the controller */
27
28
  networkPolicy(): V1NetworkPolicy;
28
29
  service(): V1Service;
29
- moduleSecret(data: string): V1Secret;
30
+ moduleSecret(data: Buffer, hash: string): V1Secret;
30
31
  zarfYaml(path: string): string;
31
- allYaml(code: string): string;
32
- deploy(code: string): Promise<void>;
32
+ allYaml(code: Buffer): string;
33
+ deploy(code: Buffer): Promise<void>;
33
34
  }
@@ -7,6 +7,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.Webhook = void 0;
9
9
  const client_node_1 = require("@kubernetes/client-node");
10
+ const crypto_1 = __importDefault(require("crypto"));
10
11
  const zlib_1 = require("zlib");
11
12
  const logger_1 = __importDefault(require("../logger"));
12
13
  const tls_1 = require("./tls");
@@ -160,7 +161,7 @@ class Webhook {
160
161
  ],
161
162
  };
162
163
  }
163
- deployment() {
164
+ deployment(hash) {
164
165
  return {
165
166
  apiVersion: "apps/v1",
166
167
  kind: "Deployment",
@@ -192,6 +193,7 @@ class Webhook {
192
193
  name: "server",
193
194
  image: this.image,
194
195
  imagePullPolicy: "IfNotPresent",
196
+ command: ["node", "/app/node_modules/pepr/dist/run.js", hash, "-l", "debug"],
195
197
  livenessProbe: {
196
198
  httpGet: {
197
199
  path: "/healthz",
@@ -222,7 +224,7 @@ class Webhook {
222
224
  },
223
225
  {
224
226
  name: "module",
225
- mountPath: "/app/module.js.gz",
227
+ mountPath: `/app/load`,
226
228
  readOnly: true,
227
229
  },
228
230
  ],
@@ -247,7 +249,7 @@ class Webhook {
247
249
  },
248
250
  };
249
251
  }
250
- /** Only permit the */
252
+ /** Only permit the kube-system ns ingress access to the controller */
251
253
  networkPolicy() {
252
254
  return {
253
255
  apiVersion: "networking.k8s.io/v1",
@@ -306,9 +308,10 @@ class Webhook {
306
308
  },
307
309
  };
308
310
  }
309
- moduleSecret(data) {
311
+ moduleSecret(data, hash) {
310
312
  // Compress the data
311
313
  const compressed = (0, zlib_1.gzipSync)(data);
314
+ const path = `module-${hash}.js.gz`;
312
315
  return {
313
316
  apiVersion: "v1",
314
317
  kind: "Secret",
@@ -318,7 +321,7 @@ class Webhook {
318
321
  },
319
322
  type: "Opaque",
320
323
  data: {
321
- module: compressed.toString("base64"),
324
+ [path]: compressed.toString("base64"),
322
325
  },
323
326
  };
324
327
  }
@@ -349,6 +352,8 @@ class Webhook {
349
352
  return (0, client_node_1.dumpYaml)(zarfCfg, { noRefs: true });
350
353
  }
351
354
  allYaml(code) {
355
+ // Generate a hash of the code
356
+ const hash = crypto_1.default.createHash("sha256").update(code).digest("hex");
352
357
  const resources = [
353
358
  this.namespace(),
354
359
  this.networkPolicy(),
@@ -357,9 +362,9 @@ class Webhook {
357
362
  this.serviceAccount(),
358
363
  this.tlsSecret(),
359
364
  this.mutatingWebhook(),
360
- this.deployment(),
365
+ this.deployment(hash),
361
366
  this.service(),
362
- this.moduleSecret(code),
367
+ this.moduleSecret(code, hash),
363
368
  ];
364
369
  // Convert the resources to a single YAML string
365
370
  return resources.map(r => (0, client_node_1.dumpYaml)(r, { noRefs: true })).join("---\n");
@@ -367,6 +372,7 @@ class Webhook {
367
372
  async deploy(code) {
368
373
  logger_1.default.info("Establishing connection to Kubernetes");
369
374
  const namespace = "pepr-system";
375
+ const hash = crypto_1.default.createHash("sha256").update(code).digest("hex");
370
376
  // Deploy the resources using the k8s API
371
377
  const kubeConfig = new client_node_1.KubeConfig();
372
378
  kubeConfig.loadFromDefault();
@@ -385,16 +391,6 @@ class Webhook {
385
391
  logger_1.default.info("Creating namespace");
386
392
  await coreV1Api.createNamespace(ns);
387
393
  }
388
- const netpol = this.networkPolicy();
389
- try {
390
- logger_1.default.info("Checking for network policy");
391
- await networkApi.readNamespacedNetworkPolicy(netpol.metadata.name, namespace);
392
- }
393
- catch (e) {
394
- logger_1.default.debug(e.body);
395
- logger_1.default.info("Creating network policy");
396
- await networkApi.createNamespacedNetworkPolicy(namespace, netpol);
397
- }
398
394
  const wh = this.mutatingWebhook();
399
395
  try {
400
396
  logger_1.default.info("Creating mutating webhook");
@@ -406,6 +402,20 @@ class Webhook {
406
402
  await admissionApi.deleteMutatingWebhookConfiguration(wh.metadata.name);
407
403
  await admissionApi.createMutatingWebhookConfiguration(wh);
408
404
  }
405
+ // If a host is specified, we don't need to deploy the rest of the resources
406
+ if (this.host) {
407
+ return;
408
+ }
409
+ const netpol = this.networkPolicy();
410
+ try {
411
+ logger_1.default.info("Checking for network policy");
412
+ await networkApi.readNamespacedNetworkPolicy(netpol.metadata.name, namespace);
413
+ }
414
+ catch (e) {
415
+ logger_1.default.debug(e.body);
416
+ logger_1.default.info("Creating network policy");
417
+ await networkApi.createNamespacedNetworkPolicy(namespace, netpol);
418
+ }
409
419
  const crb = this.clusterRoleBinding();
410
420
  try {
411
421
  logger_1.default.info("Creating cluster role binding");
@@ -444,11 +454,7 @@ class Webhook {
444
454
  await coreV1Api.deleteNamespacedServiceAccount(sa.metadata.name, namespace);
445
455
  await coreV1Api.createNamespacedServiceAccount(namespace, sa);
446
456
  }
447
- // If a host is specified, we don't need to deploy the rest of the resources
448
- if (this.host) {
449
- return;
450
- }
451
- const mod = this.moduleSecret(code);
457
+ const mod = this.moduleSecret(code, hash);
452
458
  try {
453
459
  logger_1.default.info("Creating module secret");
454
460
  await coreV1Api.createNamespacedSecret(namespace, mod);
@@ -481,7 +487,7 @@ class Webhook {
481
487
  await coreV1Api.deleteNamespacedSecret(tls.metadata.name, namespace);
482
488
  await coreV1Api.createNamespacedSecret(namespace, tls);
483
489
  }
484
- const dep = this.deployment();
490
+ const dep = this.deployment(hash);
485
491
  try {
486
492
  logger_1.default.info("Creating deployment");
487
493
  await appsApi.createNamespacedDeployment(namespace, dep);
@@ -119,4 +119,7 @@ class Logger {
119
119
  exports.Logger = Logger;
120
120
  /** Log is an instance of Logger used to generate log entries. */
121
121
  const Log = new Logger(LogLevel.info);
122
+ if (process.env.LOG_LEVEL) {
123
+ Log.SetLogLevel(process.env.LOG_LEVEL);
124
+ }
122
125
  exports.default = Log;
@@ -29,19 +29,26 @@ async function processor(config, capabilities, req) {
29
29
  logger_1.default.info(`Processing matched action ${action.kind.kind}`, prefix);
30
30
  // Add annotations to the request to indicate that the capability started processing
31
31
  // this will allow tracking of failed mutations that were permitted to continue
32
- const { metadata } = wrapped.Raw;
33
- const identifier = `${config.uuid}.pepr.dev/${name}`;
34
- metadata.annotations = metadata.annotations || {};
35
- metadata.annotations[identifier] = "started";
32
+ const updateStatus = (status) => {
33
+ // Only update the status if the request is a CREATE or UPDATE (we don't use CONNECT)
34
+ if (req.operation == "DELETE") {
35
+ return;
36
+ }
37
+ const identifier = `${config.uuid}.pepr.dev/${name}`;
38
+ wrapped.Raw.metadata.annotations = wrapped.Raw.metadata.annotations || {};
39
+ wrapped.Raw.metadata.annotations[identifier] = status;
40
+ };
41
+ updateStatus("started");
36
42
  try {
37
43
  // Run the action
38
44
  await action.callback(wrapped);
45
+ logger_1.default.info(`Action succeeded`, prefix);
39
46
  // Add annotations to the request to indicate that the capability succeeded
40
- metadata.annotations[identifier] = "succeeded";
47
+ updateStatus("succeeded");
41
48
  }
42
49
  catch (e) {
43
50
  response.warnings.push(`Action failed: ${e}`);
44
- // If errors are not allowed, note the failure in the Reponse
51
+ // If errors are not allowed, note the failure in the Response
45
52
  if (config.onError) {
46
53
  logger_1.default.error(`Action failed: ${e}`, prefix);
47
54
  response.result = "Pepr module configured to reject on error";
@@ -49,7 +56,7 @@ async function processor(config, capabilities, req) {
49
56
  }
50
57
  else {
51
58
  logger_1.default.warn(`Action failed: ${e}`, prefix);
52
- metadata.annotations[identifier] = "warning";
59
+ updateStatus("warning");
53
60
  }
54
61
  }
55
62
  }
@@ -15,7 +15,7 @@ export declare enum ErrorBehavior {
15
15
  */
16
16
  export declare enum HookPhase {
17
17
  mutate = "mutate",
18
- valdiate = "validate"
18
+ validate = "validate"
19
19
  }
20
20
  /**
21
21
  * Recursively make all properties in T optional.
@@ -24,13 +24,13 @@ export type DeepPartial<T> = {
24
24
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
25
25
  };
26
26
  /**
27
- * The type of Kubernetes mutating webhook event ethat the capability action is registered for.
27
+ * The type of Kubernetes mutating webhook event that the capability action is registered for.
28
28
  */
29
29
  export declare enum Event {
30
- Create = "create",
31
- Update = "update",
32
- Delete = "delete",
33
- CreateOrUpdate = "createOrUpdate"
30
+ Create = "CREATE",
31
+ Update = "UPDATE",
32
+ Delete = "DELETE",
33
+ CreateOrUpdate = "CREATEORUPDATE"
34
34
  }
35
35
  export interface CapabilityCfg {
36
36
  /**
@@ -155,7 +155,7 @@ export type BindingWithName<T extends GenericClass> = BindingFilter<T> & {
155
155
  WithName: (name: string) => BindingFilter<T>;
156
156
  };
157
157
  export type BindingAll<T extends GenericClass> = BindingWithName<T> & {
158
- /** Only apply the cabability action if the resource is in one of the specified namespaces.*/
158
+ /** Only apply the capability action if the resource is in one of the specified namespaces.*/
159
159
  InNamespace: (...namespaces: string[]) => BindingFilter<T>;
160
160
  };
161
161
  export type BindToAction<T extends GenericClass> = {
@@ -20,15 +20,15 @@ var ErrorBehavior;
20
20
  var HookPhase;
21
21
  (function (HookPhase) {
22
22
  HookPhase["mutate"] = "mutate";
23
- HookPhase["valdiate"] = "validate";
23
+ HookPhase["validate"] = "validate";
24
24
  })(HookPhase = exports.HookPhase || (exports.HookPhase = {}));
25
25
  /**
26
- * The type of Kubernetes mutating webhook event ethat the capability action is registered for.
26
+ * The type of Kubernetes mutating webhook event that the capability action is registered for.
27
27
  */
28
28
  var Event;
29
29
  (function (Event) {
30
- Event["Create"] = "create";
31
- Event["Update"] = "update";
32
- Event["Delete"] = "delete";
33
- Event["CreateOrUpdate"] = "createOrUpdate";
30
+ Event["Create"] = "CREATE";
31
+ Event["Update"] = "UPDATE";
32
+ Event["Delete"] = "DELETE";
33
+ Event["CreateOrUpdate"] = "CREATEORUPDATE";
34
34
  })(Event = exports.Event || (exports.Event = {}));
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "engines": {
10
10
  "node": ">=18.0.0"
11
11
  },
12
- "version": "0.1.45",
12
+ "version": "0.2.1",
13
13
  "main": "dist/index.js",
14
14
  "types": "dist/index.d.ts",
15
15
  "pepr": {
@@ -26,24 +26,23 @@
26
26
  "scripts": {
27
27
  "prebuild": "rm -fr dist/* && node hack/build-template-data.js",
28
28
  "build": "tsc -p tsconfig.build.json",
29
- "test": "npm run build && ava && node dist/cli.js -V",
30
- "test:e2e": "ava hack/e2e.test.js",
31
- "test:e2e-setup": "npm run build && npm uninstall pepr -g && npm install -g .",
32
- "lint": "npx eslint src",
33
- "lint:fix": "npm run lint -- --fix",
34
- "prettier": "npx prettier src --check",
35
- "prettier:fix": "npm run prettier -- --write",
36
- "prepublishOnly": "npm run lint:fix && npm run prettier:fix && npm run test",
37
- "e2e-dev-setup": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'"
29
+ "test:unit": "npm run build && ava",
30
+ "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run",
31
+ "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'",
32
+ "test:e2e:build": "npm run build && npm uninstall pepr -g && npm install -g . && pepr",
33
+ "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev",
34
+ "test:e2e:run": "ava hack/e2e.test.js --sequential",
35
+ "format:check": "eslint src && prettier src --check",
36
+ "format:fix": "eslint src --fix && prettier src --write"
38
37
  },
39
38
  "dependencies": {
40
39
  "@kubernetes/client-node": "^0.18.1",
41
40
  "@rollup/plugin-json": "^6.0.0",
42
- "@rollup/plugin-node-resolve": "^15.0.1",
43
- "@rollup/plugin-typescript": "^11.0.0",
41
+ "@rollup/plugin-node-resolve": "^15.0.2",
42
+ "@rollup/plugin-typescript": "^11.1.0",
44
43
  "@types/ramda": "^0.29.0",
45
44
  "chokidar": "^3.5.3",
46
- "commander": "^10.0.0",
45
+ "commander": "^10.0.1",
47
46
  "express": "^4.18.2",
48
47
  "fast-json-patch": "^3.1.1",
49
48
  "node-fetch": "^2.6.9",
@@ -51,10 +50,10 @@
51
50
  "prettier": "^2.8.7",
52
51
  "prompts": "^2.4.2",
53
52
  "ramda": "^0.29.0",
54
- "rollup": "^3.20.2",
53
+ "rollup": "^3.20.6",
55
54
  "ts-node": "^10.9.1",
56
55
  "tslib": "^2.5.0",
57
- "typescript": "^5.0.2",
56
+ "typescript": "^5.0.4",
58
57
  "uuid": "^9.0.0"
59
58
  },
60
59
  "devDependencies": {
@@ -63,10 +62,10 @@
63
62
  "@types/node-forge": "^1.3.2",
64
63
  "@types/prompts": "^2.4.4",
65
64
  "@types/uuid": "^9.0.1",
66
- "@typescript-eslint/eslint-plugin": "^5.57.0",
67
- "@typescript-eslint/parser": "^5.57.0",
65
+ "@typescript-eslint/eslint-plugin": "^5.59.0",
66
+ "@typescript-eslint/parser": "^5.59.0",
68
67
  "ava": "^5.2.0",
69
- "eslint": "^8.37.0",
68
+ "eslint": "^8.38.0",
70
69
  "nock": "^13.3.0"
71
70
  },
72
71
  "ava": {