Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PeprStore, K8s Fluent API & Watch Action #180

Merged
merged 124 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from 114 commits
Commits
Show all changes
124 commits
Select commit Hold shift + click to select a range
028c990
start some trouble
jeff-mccoy Jul 7, 2023
7ab1a68
simplify observe, change validate from boolean -> resp obj
jeff-mccoy Jul 16, 2023
2e8da69
update deps
jeff-mccoy Jul 22, 2023
562eb0e
update prettier to use promise
jeff-mccoy Jul 22, 2023
f60fe8b
Finish Mutate/validate/Watch bindings
jeff-mccoy Jul 23, 2023
7606a6e
simplify watch code (non-fluent as it wont be user-facing)
jeff-mccoy Jul 23, 2023
68fef05
wip leaderelection things
jeff-mccoy Jul 23, 2023
79d0c46
actually implement the Pepr Store wiring 😭
jeff-mccoy Jul 31, 2023
400a01f
fix global namespace ignores
jeff-mccoy Jul 31, 2023
a91ce1d
add /healthz tests
jeff-mccoy Jul 31, 2023
518ff5b
Merge branch 'main' into shifting-sands
jeff-mccoy Jul 31, 2023
4e2c6f4
lint
jeff-mccoy Jul 31, 2023
e455ff8
leader election -> dedicated pod
jeff-mccoy Aug 1, 2023
d5a316f
Add store subscribe
jeff-mccoy Aug 4, 2023
ca764a4
watcher statefulset -> deployment + more webhook reorg
jeff-mccoy Aug 4, 2023
d481d31
Merge branch 'main' into shifting-sands
jeff-mccoy Aug 5, 2023
a1de123
conditionally generate the watch deployment
jeff-mccoy Aug 5, 2023
d374163
pass errors from store write operations
jeff-mccoy Aug 5, 2023
26f64fd
introduce debounced/throttled read/write sync store + onready handler
jeff-mccoy Aug 6, 2023
855bf01
wip crd madness
jeff-mccoy Aug 6, 2023
51cae98
Merge branch 'main' into shifting-sands
jeff-mccoy Aug 6, 2023
8eda32e
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Aug 6, 2023
7175435
wip: move to Kube() api + PeprStore CRD
jeff-mccoy Aug 7, 2023
bb91655
add jitter for controller store creation
jeff-mccoy Aug 13, 2023
e2c614b
continue cleanup rbac/raw api
jeff-mccoy Aug 13, 2023
d623dd8
update e2e to match capability log changes
jeff-mccoy Aug 14, 2023
d350d2f
add readiness probes to wait for pepr store
jeff-mccoy Aug 14, 2023
02bdb50
Merge branch 'main' into shifting-sands
jeff-mccoy Aug 14, 2023
f9597fa
simplify fluent k8s fluent interfaces
jeff-mccoy Aug 15, 2023
3cef70c
start switching tests to kube fluent api
jeff-mccoy Aug 15, 2023
e340dac
Merge branch 'main' into shifting-sands
jeff-mccoy Aug 15, 2023
714080d
move more k8s imports to k8s from client-node
jeff-mccoy Aug 15, 2023
20d3609
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Aug 15, 2023
1977843
Merge branch 'main' into shifting-sands
jeff-mccoy Aug 24, 2023
501f240
add errors class for onError handling
jeff-mccoy Sep 1, 2023
d22151d
add module.ts unit test
jeff-mccoy Sep 1, 2023
63f3823
add unit test mocks/coverage/ts testing
jeff-mccoy Sep 1, 2023
cd0b737
wip: standardize ES2020 class structure
jeff-mccoy Sep 1, 2023
59117dc
e2e -> journey & class method this binding
jeff-mccoy Sep 2, 2023
4c03a47
lame wildcard issue in npm scripts
jeff-mccoy Sep 2, 2023
89c6d23
convert stdout Buffer -> string again
jeff-mccoy Sep 2, 2023
03b89c8
more journey test cleanup
jeff-mccoy Sep 2, 2023
3fc247a
validate tsx loader in ci
jeff-mccoy Sep 2, 2023
e0addce
try without nyc
jeff-mccoy Sep 2, 2023
f90ea54
but whyyy
jeff-mccoy Sep 3, 2023
88c235e
ava/sinon/nyc -> jest
jeff-mccoy Sep 3, 2023
8f7d408
dep updates
jeff-mccoy Sep 3, 2023
2ae2e0c
add test adr
jeff-mccoy Sep 3, 2023
4a6411b
use json instead of js config due to gitignore
jeff-mccoy Sep 3, 2023
4e221c6
always generate the data.json for unit tests
jeff-mccoy Sep 3, 2023
296421a
standardize private/public class methods
jeff-mccoy Sep 3, 2023
d2934c5
Merge branch 'main' into 235-pepr-always-fails-when-you-select-audit-…
jeff-mccoy Sep 3, 2023
894cb68
remove need for disable node-wide tls verification
jeff-mccoy Sep 4, 2023
ac38bdf
Merge remote-tracking branch 'origin/235-pepr-always-fails-when-you-s…
jeff-mccoy Sep 4, 2023
c27b91e
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 5, 2023
593bf64
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 5, 2023
dc033d4
continue post-merge cleanup
jeff-mccoy Sep 5, 2023
749fc7b
manage delayed controller boot for PeprStore in journey tests
jeff-mccoy Sep 5, 2023
6d205d3
Merge branch 'main' into shifting-sands
Sep 6, 2023
a8b5e66
re-add k8s fluent api for journey tests
jeff-mccoy Sep 7, 2023
817d875
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 7, 2023
347e709
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 7, 2023
c12c91c
cleanup uuid import for templates
jeff-mccoy Sep 10, 2023
6c91e9d
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 10, 2023
23cda48
more unit tests
jeff-mccoy Sep 10, 2023
ecf558d
Kube() refactors + some unit tests
jeff-mccoy Sep 11, 2023
c3f4ec3
revert uuid rename
jeff-mccoy Sep 11, 2023
b170f63
Merge branch 'main' into shifting-sands
Sep 11, 2023
1d67119
more unit tests
jeff-mccoy Sep 13, 2023
d18dfc8
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Sep 13, 2023
49844a2
mock k8s client
jeff-mccoy Sep 14, 2023
482f33e
CreateOrReplace()/Replace() -> Apply()
jeff-mccoy Sep 14, 2023
7356a9b
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 14, 2023
da9c2fa
Remove Kube().Patch(oldObj, newObj) in favor of SSA, Kube().Apply()
jeff-mccoy Sep 14, 2023
2bee372
try to set apiVersion if not passed into the Kube() api in the object
jeff-mccoy Sep 14, 2023
337112e
experiment, maybe terrible but add `given.*` for better Kube() readab…
jeff-mccoy Sep 14, 2023
bc9dd68
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Sep 14, 2023
5d21c67
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 14, 2023
5f5d4da
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Sep 14, 2023
6be71c0
add pepr store journey tests
jeff-mccoy Sep 15, 2023
28cf066
minor hello-pepr cleanup
jeff-mccoy Sep 15, 2023
921a1f8
add logLevel config to package.json
jeff-mccoy Sep 16, 2023
cebe294
add internal-use destroyModule() function
jeff-mccoy Sep 16, 2023
78d992c
properly manage buildMode/watchMode bindings
jeff-mccoy Sep 16, 2023
8767a83
initial pepr watch binding
jeff-mccoy Sep 16, 2023
b38ba91
add phase to hellopepr watch example
jeff-mccoy Sep 16, 2023
fb3ffda
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 19, 2023
c62d07d
remove prettier + update transitive deps
jeff-mccoy Sep 19, 2023
99e0516
readme updates
jeff-mccoy Sep 20, 2023
27397de
move to node-fetch / k8s client node 1
jeff-mccoy Sep 22, 2023
37758bf
move tls files to lib
jeff-mccoy Sep 22, 2023
7026845
merge watch()/kube() + migrate to internal watch logic
jeff-mccoy Sep 22, 2023
aa40641
migrate to kubernetes-fluent-client
jeff-mccoy Sep 25, 2023
26e74c3
remove k8s mock (now in fluent client)
jeff-mccoy Sep 25, 2023
59e2ae2
Merge branch 'main' into shifting-sands
jeff-mccoy Sep 25, 2023
3f573e5
Add Pepr Store readme
jeff-mccoy Sep 25, 2023
393b4a0
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Sep 25, 2023
6f63ace
add fluent client example
jeff-mccoy Sep 25, 2023
c3af6d0
match phases for watch actions
jeff-mccoy Sep 26, 2023
01f04f6
update readme for watch
jeff-mccoy Sep 26, 2023
f956eac
update pepr diagram for watch + store
jeff-mccoy Sep 26, 2023
d8f6b07
fix font color issue in diagram
jeff-mccoy Sep 26, 2023
fdbe7a5
remove async from when() example
jeff-mccoy Sep 26, 2023
92365f6
readme updates
jeff-mccoy Sep 26, 2023
565ad32
readme code sample validation
jeff-mccoy Sep 26, 2023
edf2cd0
lint
jeff-mccoy Sep 26, 2023
db83c42
Update README.md
jeff-mccoy Sep 26, 2023
958ace3
Update docs/actions.md
jeff-mccoy Sep 26, 2023
a23b6d6
Update docs/store.md
Sep 27, 2023
9572c8f
Update README.md
Sep 27, 2023
da99d56
Update docs/actions.md
Sep 27, 2023
2d06b29
Update docs/store.md
jeff-mccoy Sep 27, 2023
c8f3df2
Update docs/store.md
jeff-mccoy Sep 27, 2023
db055f8
Update journey/k8s.ts
jeff-mccoy Sep 29, 2023
ffcbb03
add watch retry / crash handler
jeff-mccoy Sep 30, 2023
f16c0b1
Merge remote-tracking branch 'origin/shifting-sands' into shifting-sands
jeff-mccoy Sep 30, 2023
023d7c1
fix sleep rename in journey tests
jeff-mccoy Sep 30, 2023
23e45a8
add watch processor unit test
jeff-mccoy Sep 30, 2023
3607b30
update deps
jeff-mccoy Oct 1, 2023
d5b853f
delay watch actions until the peprstore is ready
jeff-mccoy Oct 1, 2023
11ca941
add store watch action journey tests
jeff-mccoy Oct 1, 2023
bcb28a1
small readme updates
jeff-mccoy Oct 1, 2023
26c9d1e
fix text escaping on journey test match
jeff-mccoy Oct 1, 2023
0024c29
Merge branch 'main' into shifting-sands
cmwylie19 Oct 2, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"rules": {
"class-methods-use-this": "warn",
"consistent-this":"warn",
"consistent-this": "warn",
"no-invalid-this": "warn",
"@typescript-eslint/no-floating-promises": ["warn"]
},
Expand All @@ -22,7 +22,10 @@
"node_modules",
"dist",
"hack",
"pepr-test-module"
"pepr-test-module",
"build.mjs",
"journey",
"__mocks__"
],
"root": true
}
2 changes: 1 addition & 1 deletion .images/pepr-arch.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 5 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ adr
/docs/
/hack
build.mjs

/journey
/__mocks__
/coverage
jest.config.json
/prettierignore
/dist/cli/**/*.d.*
/dist/fixtures
/dist/test
Expand Down
31 changes: 26 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@

Pepr is on a mission to save Kubernetes from the tyranny of YAML, intimidating glue code, bash scripts, and other makeshift solutions. As a Kubernetes controller, Pepr empowers you to define Kubernetes transformations using TypeScript, without software development expertise thanks to plain-english configurations. Pepr transforms a patchwork of forks, scripts, overlays, and other chaos into a cohesive, well-structured, and maintainable system. With Pepr, you can seamlessly transition IT ops tribal knowledge into code, simplifying documentation, testing, validation, and coordination of changes for a more predictable outcome.

#### _Note: Pepr is still in active development so breaking changes may occur, but will be documented in release notes._

## Features

- Zero-config K8s webhook mutations and validations.
- Zero-config K8s webhook mutations and validations
- Automatic leader-elected K8s resource watching
jeff-mccoy marked this conversation as resolved.
Show resolved Hide resolved
- Lightweight async key-value store backed by K8s for stateful operations with the [Pepr Store](./docs/store.md)
- Human-readable fluent API for generating [Pepr Capabilities](#capability)
- A fluent API for creating/modifying/watching and server-side applying K8s resources via [Kubernetes Fluent Client](https://github.com/defenseunicorns/kubernetes-fluent-client)
- Generate new K8s resources based off of cluster resource changes
- Perform other exec/API calls based off of cluster resources changes or any other arbitrary schedule
- Out of the box airgap support with [Zarf](https://zarf.dev)
Expand All @@ -27,7 +32,7 @@ Pepr is on a mission to save Kubernetes from the tyranny of YAML, intimidating g

## Example Pepr Action

This quick sample shows how to react to a ConfigMap being created or updated in the cluster. It adds a label and annotation to the ConfigMap and adds some data to the ConfigMap. Finally, it logs a message to the Pepr controller logs. For more see [actions](./docs/actions.md).
This quick sample shows how to react to a ConfigMap being created or updated in the cluster. It adds a label and annotation to the ConfigMap and adds some data to the ConfigMap. It also creates a Validating Webhook to make sure the "pepr" label still exists. Finally, after the ConfigMap is created, it logs a message to the Pepr controller and creates or updates a separate ConfigMap with the [kubernetes-fluent-client](https://github.com/defenseunicorns/kubernetes-fluent-client) using server-side apply. For more details see [actions](./docs/actions.md) section.

```ts
When(a.ConfigMap)
Expand All @@ -37,7 +42,9 @@ When(a.ConfigMap)
// Create a Mutate Action for the ConfigMap
.Mutate(request => {
// Add a label and annotation to the ConfigMap
request.SetLabel("pepr", "was-here").SetAnnotation("pepr.dev", "annotations-work-too");
request
.SetLabel("pepr", "was-here")
.SetAnnotation("pepr.dev", "annotations-work-too");

// Add some data to the ConfigMap
request.Raw.data["doug-says"] = "Pepr is awesome!";
Expand All @@ -54,6 +61,21 @@ When(a.ConfigMap)

// Reject the ConfigMap if it doesn't have the label
return request.Deny("ConfigMap must have a unicorn label");
})
// Watch behaves like controller-runtime's Manager.Watch()
.Watch(async (cm, phase) => {
Log.info(cm, `ConfigMap was ${phase}.`);

// Apply the ConfigMap using K8s server-side apply
await K8s(kind.ConfigMap).Apply({
metadata: {
name: "pepr-ssa-demo",
namespace: "pepr-demo-2",
},
data: {
uid: cm.metadata.uid,
},
});
});
```

Expand Down Expand Up @@ -104,7 +126,7 @@ Action is a discrete set of behaviors defined in a single function that acts on

For example, an action could be responsible for adding a specific label to a Kubernetes resource, or for modifying a specific field in a resource's metadata. Actions can be grouped together within a Capability to provide a more comprehensive set of operations that can be performed on Kubernetes resources.

There are both `Mutate()` and `Validate()` Actions that can be used to modify or validate Kubernetes resources.
There are both `Mutate()` and `Validate()` Actions that can be used to modify or validate Kubernetes resources within the admission controller lifecycle. There is also a `Watch()` Action that can be used to watch for changes to Kubernetes resources that already exist.

See [actions](./docs/actions.md) for more details.

Expand All @@ -116,4 +138,3 @@ See [actions](./docs/actions.md) for more details.
## TypeScript

[TypeScript](https://www.typescriptlang.org/) is a strongly typed, object-oriented programming language built on top of JavaScript. It provides optional static typing and a rich type system, allowing developers to write more robust code. TypeScript is transpiled to JavaScript, enabling it to run in any environment that supports JavaScript. Pepr allows you to use JavaScript or TypeScript to write capabilities, but TypeScript is recommended for its type safety and rich type system. You can learn more about TypeScript [here](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html).

10 changes: 10 additions & 0 deletions __mocks__/pino.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { jest } from "@jest/globals";

export const pino = () => {
return {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
};
};
2 changes: 1 addition & 1 deletion build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { analyzeMetafile, build } from "esbuild";
import packageJSON from "./package.json" assert { type: "json" };

const { dependencies, peerDependencies } = packageJSON;
const external = Object.keys(dependencies).concat(Object.keys(peerDependencies));
const external = Object.keys(dependencies).concat(Object.keys(peerDependencies), "@kubernetes/client-node");

const buildOpts = {
bundle: true,
Expand Down
14 changes: 13 additions & 1 deletion docs/actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ An action is a discrete set of behaviors defined in a single function that acts

For example, an action could be responsible for adding a specific label to a Kubernetes resource, or for modifying a specific field in a resource's metadata. Actions can be grouped together within a Capability to provide a more comprehensive set of operations that can be performed on Kubernetes resources.

Actions are either `Mutate()` or `Validate()` actions. Mutate actions are used to modify Kubernetes resources, while Validate actions are used to validate Kubernetes resources.
Actions are `Mutate()`, `Validate()`, or `Watch()`. Both Mutate and Validate actions run during the admission controller lifecycle, while Watch actions run in a separate controller that tracks changes to resources, including existing resources.

Let's look at some example actions that are included in the `HelloPepr` capability that is created for you when you [`pepr init`](./cli.md#pepr-init):

Expand Down Expand Up @@ -52,6 +52,18 @@ When(a.ConfigMap)
});
```

---

In this example, a Watch action on the name and phase of any ConfigMap.

```ts
When(a.ConfigMap)
// Watch() is where we define the actual behavior of this action.
.Watch((cm, phase) => {
Log.info(cm, `ConfigMap ${cm.metadata.name} was ${phase}`);
});
```

```
There are many more examples in the `HelloPepr` capability that you can use as a reference when creating your own actions. Note that each time you run [`pepr update`](./cli.md#pepr-update), Pepr will automatically update the `HelloPepr` capability with the latest examples and best practices for you to reference and test directly in your Pepr Module.
```
42 changes: 42 additions & 0 deletions docs/store.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Pepr Store: A Lightweight Key-Value Store for Pepr Modules

The nature of admission controllers and general watch operations (the `Mutate`, `Validate` and `Watch` actions in Pepr) make some types of complex and long-running operations difficult. There are also times when you need to share data between different actions. While you could manually create your own K8s resources and manage their cleanup, this can be very hard to track and keep performant at scale.

The Pepr Store solves this by exposing a simple, [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage)-compatible mechanism for use within capabilities. Additionally, as Pepr runs multiple replicas of the admission controller along with a watch controller, the Pepr Store provides a unique way to share data between these different instances automatically.

Each Pepr Capability has a `Store` instance that can be used to get, set and delete data as well as subscribe to any changes to the Store. Behind the scenes, all capability store instances in a single Pepr Module are stored within a single CRD in the cluster. This CRD is automatically created when the Pepr Module is deployed. Care is taken to make the read and write operations as efficient as possible by using K8s watches, batch processing and patch operations for writes.

## Key Features

- **Asynchronous Key-Value Store**: Provides an asynchronous interface for storing small amounts of data, making it ideal for sharing information between various actions and capabilities.
- **Web Storage API Compatibility**: The store's API is aligned with the standard [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage), simplifying the learning curve.
- **Real-time Updates**: The `.subscribe()` and `onReady()` methods enable real-time updates, allowing you to react to changes in the data store instantaneously.

- **Automatic CRD Management**: Each Pepr Module has its data stored within a single Custom Resource Definition (CRD) that is automatically created upon deployment.
- **Efficient Operations**: Pepr Store uses Kubernetes watches, batch processing, and patch operations to make read and write operations as efficient as possible.

## Quick Start

```typescript
// Example usage for Pepr Store
Store.setItem("example-1", "was-here");
Store.setItem("example-1-data", JSON.stringify(request.Raw.data));
Store.onReady(data => {
Log.info(data, "Pepr Store Ready");
});
const unsubscribe = Store.subscribe(data => {
Log.info(data, "Pepr Store Updated");
unsubscribe();
});
```

## API Reference

### Methods

- `getItem(key: string)`: Retrieves a value by its key. Returns `null` if the key doesn't exist.
- `setItem(key: string, value: string)`: Sets a value for a given key. Creates a new key-value pair if the key doesn't exist.
- `removeItem(key: string)`: Deletes a key-value pair by its key.
- `clear()`: Clears all key-value pairs from the store.
- `subscribe(listener: DataReceiver)`: Subscribes to store updates.
- `onReady(callback: DataReceiver)`: Executes a callback when the store is ready.
3 changes: 3 additions & 0 deletions journey/entrypoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { peprDev } from "./pepr-dev";
import { peprFormat } from "./pepr-format";
import { peprInit } from "./pepr-init";

// Unmock unit test things
jest.deepUnmock("pino");

// The working directory for the tests after `npx pepr init` is run
export const cwd = "pepr-test-module";

Expand Down
80 changes: 25 additions & 55 deletions journey/k8s.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,50 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { AppsV1Api, CoreV1Api, KubeConfig, V1ConfigMap } from "@kubernetes/client-node";
import { K8s, kind } from "kubernetes-fluent-client";

const kc = new KubeConfig();
kc.loadFromDefault();
import { PeprStore } from "../src/lib/k8s";

const k8sApi = kc.makeApiClient(AppsV1Api);
const k8sCoreApi = kc.makeApiClient(CoreV1Api);

function delay2Secs() {
return new Promise(resolve => setTimeout(resolve, 2000));
}

export async function createOrReplaceConfigMap(cm: V1ConfigMap) {
const ns = cm.metadata?.namespace || "default";
try {
const resp = await k8sCoreApi.createNamespacedConfigMap(ns, cm);
return resp.body;
} catch (error) {
const resp = await k8sCoreApi.replaceNamespacedConfigMap(cm.metadata?.name || "", ns, cm);
return resp.body;
}
export function sleep(seconds: number) {
return new Promise(resolve => setTimeout(resolve, seconds*1000));
}

export async function deleteConfigMap(namespace: string, name: string) {
try {
await k8sCoreApi.deleteNamespacedConfigMap(name, namespace);
await K8s(kind.ConfigMap).InNamespace(namespace).Delete(name);
} catch (error) {
// Do nothing
}
}

export async function waitForDeploymentReady(namespace: string, name: string) {
const deployment = await k8sApi.readNamespacedDeployment(name, namespace);
const replicas = deployment.body.spec?.replicas || 1;
const readyReplicas = deployment.body.status?.readyReplicas || 0;
const deployment = await K8s(kind.Deployment).InNamespace(namespace).Get(name);
const replicas = deployment.spec?.replicas || 1;
const readyReplicas = deployment.status?.readyReplicas || 0;

if (replicas !== readyReplicas) {
await delay2Secs();
return waitForDeploymentReady(namespace, name);
}
}

export async function waitForPeprStoreKey(name: string, matchKey: string) {
try {
const store = await K8s(PeprStore).InNamespace("pepr-system").Get(name);
if (store.data[matchKey]) {
return store.data[matchKey];
}

throw new Error("Key not found");
} catch (error) {
await delay2Secs();
return waitForPeprStoreKey(name, matchKey);
}
}

export async function waitForNamespace(namespace: string) {
try {
const resp = await k8sCoreApi.readNamespace(namespace);
return resp.body;
return await K8s(kind.Namespace).Get(namespace);
} catch (error) {
await delay2Secs();
return waitForNamespace(namespace);
Expand All @@ -55,8 +53,7 @@ export async function waitForNamespace(namespace: string) {

export async function waitForConfigMap(namespace: string, name: string) {
try {
const resp = await k8sCoreApi.readNamespacedConfigMap(name, namespace);
return resp.body;
return await K8s(kind.ConfigMap).InNamespace(namespace).Get(name);
} catch (error) {
await delay2Secs();
return waitForConfigMap(namespace, name);
Expand All @@ -65,36 +62,9 @@ export async function waitForConfigMap(namespace: string, name: string) {

export async function waitForSecret(namespace: string, name: string) {
try {
const resp = await k8sCoreApi.readNamespacedSecret(name, namespace);
return resp.body;
return await K8s(kind.Secret).InNamespace(namespace).Get(name);
} catch (error) {
await delay2Secs();
return waitForSecret(namespace, name);
}
}

export async function getPodLogs(namespace: string, labelSelector: string) {
let allLogs = "";

try {
const res = await k8sCoreApi.listNamespacedPod(
namespace,
undefined,
undefined,
undefined,
undefined,
labelSelector,
);
const pods = res.body.items;

for (const pod of pods) {
const podName = pod.metadata?.name || "unknown";
const log = await k8sCoreApi.readNamespacedPodLog(podName, namespace);
allLogs += log.body;
}
} catch (err) {
console.error("Error: ", err);
}

return allLogs;
}
Loading
Loading