pepr 0.44.0 → 0.45.0-nightly.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/README.md +1 -1
- package/dist/cli/build.d.ts +3 -3
- package/dist/cli/build.d.ts.map +1 -1
- package/dist/cli/build.helpers.d.ts +13 -7
- package/dist/cli/build.helpers.d.ts.map +1 -1
- package/dist/cli/deploy.d.ts.map +1 -1
- package/dist/cli/init/templates.d.ts +7 -8
- package/dist/cli/init/templates.d.ts.map +1 -1
- package/dist/cli.js +120 -100
- package/dist/controller.js +1 -1
- package/dist/lib/assets/assets.d.ts +2 -2
- package/dist/lib/assets/assets.d.ts.map +1 -1
- package/dist/lib/assets/index.d.ts +1 -1
- package/dist/lib/assets/index.d.ts.map +1 -1
- package/dist/lib/assets/pods.d.ts +1 -1
- package/dist/lib/assets/pods.d.ts.map +1 -1
- package/dist/lib/assets/rbac.d.ts.map +1 -1
- package/dist/lib/assets/webhooks.d.ts +2 -0
- package/dist/lib/assets/webhooks.d.ts.map +1 -1
- package/dist/lib/assets/yaml/overridesFile.d.ts +2 -4
- package/dist/lib/assets/yaml/overridesFile.d.ts.map +1 -1
- package/dist/lib/controller/index.d.ts +7 -2
- package/dist/lib/controller/index.d.ts.map +1 -1
- package/dist/lib/core/envChecks.d.ts +4 -0
- package/dist/lib/core/envChecks.d.ts.map +1 -0
- package/dist/lib/core/module.d.ts +1 -48
- package/dist/lib/core/module.d.ts.map +1 -1
- package/dist/lib/core/storage.d.ts.map +1 -1
- package/dist/lib/processors/mutate-processor.d.ts +1 -1
- package/dist/lib/processors/mutate-processor.d.ts.map +1 -1
- package/dist/lib/processors/validate-processor.d.ts +1 -1
- package/dist/lib/processors/validate-processor.d.ts.map +1 -1
- package/dist/lib/processors/watch-processor.d.ts.map +1 -1
- package/dist/lib/telemetry/metrics.d.ts.map +1 -1
- package/dist/lib/types.d.ts +45 -0
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib.js +2008 -1990
- package/dist/lib.js.map +4 -4
- package/package.json +16 -13
- package/src/cli/build.helpers.ts +28 -13
- package/src/cli/build.ts +65 -65
- package/src/cli/deploy.ts +32 -26
- package/src/cli/init/index.ts +2 -2
- package/src/cli/init/templates.ts +6 -5
- package/src/cli/init/walkthrough.ts +1 -1
- package/src/lib/assets/assets.ts +2 -2
- package/src/lib/assets/index.ts +1 -2
- package/src/lib/assets/pods.ts +1 -1
- package/src/lib/assets/rbac.ts +1 -2
- package/src/lib/assets/webhooks.ts +1 -1
- package/src/lib/assets/yaml/overridesFile.ts +4 -6
- package/src/lib/controller/index.ts +19 -11
- package/src/lib/core/capability.ts +1 -1
- package/src/lib/core/envChecks.ts +6 -0
- package/src/lib/core/module.ts +20 -69
- package/src/lib/core/schedule.ts +2 -2
- package/src/lib/core/storage.ts +2 -1
- package/src/lib/processors/mutate-processor.ts +2 -2
- package/src/lib/processors/validate-processor.ts +1 -1
- package/src/lib/processors/watch-processor.ts +5 -3
- package/src/lib/telemetry/metrics.ts +4 -6
- package/src/lib/types.ts +48 -0
- package/src/sdk/heredoc.ts +2 -2
package/dist/lib.js
CHANGED
|
@@ -50,8 +50,8 @@ var import_kubernetes_fluent_client8 = require("kubernetes-fluent-client");
|
|
|
50
50
|
var R = __toESM(require("ramda"));
|
|
51
51
|
|
|
52
52
|
// src/lib/core/capability.ts
|
|
53
|
-
var
|
|
54
|
-
var
|
|
53
|
+
var import_kubernetes_fluent_client2 = require("kubernetes-fluent-client");
|
|
54
|
+
var import_ramda2 = require("ramda");
|
|
55
55
|
|
|
56
56
|
// src/lib/telemetry/logger.ts
|
|
57
57
|
var import_pino = require("pino");
|
|
@@ -101,2204 +101,2222 @@ function redactedPatch(patch = {}) {
|
|
|
101
101
|
}
|
|
102
102
|
var logger_default = Log;
|
|
103
103
|
|
|
104
|
-
// src/lib/core/
|
|
105
|
-
var
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
var import_express = __toESM(require("express"));
|
|
109
|
-
var import_fs = __toESM(require("fs"));
|
|
110
|
-
var import_https = __toESM(require("https"));
|
|
104
|
+
// src/lib/core/envChecks.ts
|
|
105
|
+
var isWatchMode = () => process.env.PEPR_WATCH_MODE === "true";
|
|
106
|
+
var isBuildMode = () => process.env.PEPR_MODE === "build";
|
|
107
|
+
var isDevMode = () => process.env.PEPR_MODE === "dev";
|
|
111
108
|
|
|
112
|
-
// src/lib/
|
|
113
|
-
var
|
|
114
|
-
var
|
|
115
|
-
var
|
|
116
|
-
var
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
109
|
+
// src/lib/core/storage.ts
|
|
110
|
+
var import_ramda = require("ramda");
|
|
111
|
+
var import_json_pointer = __toESM(require("json-pointer"));
|
|
112
|
+
var MAX_WAIT_TIME = 15e3;
|
|
113
|
+
var STORE_VERSION_PREFIX = "v2";
|
|
114
|
+
function v2StoreKey(key) {
|
|
115
|
+
return `${STORE_VERSION_PREFIX}-${import_json_pointer.default.escape(key)}`;
|
|
116
|
+
}
|
|
117
|
+
function v2UnescapedStoreKey(key) {
|
|
118
|
+
return `${STORE_VERSION_PREFIX}-${key}`;
|
|
119
|
+
}
|
|
120
|
+
var Storage = class {
|
|
121
|
+
#store = {};
|
|
122
|
+
#send;
|
|
123
|
+
#subscribers = {};
|
|
124
|
+
#subscriberId = 0;
|
|
125
|
+
#readyHandlers = [];
|
|
126
|
+
registerSender = (send) => {
|
|
127
|
+
this.#send = send;
|
|
130
128
|
};
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
this.#registry = new import_prom_client.Registry();
|
|
137
|
-
this.#prefix = prefix;
|
|
138
|
-
this.addCounter(this.#metricNames.errors, "Mutation/Validate errors encountered");
|
|
139
|
-
this.addCounter(this.#metricNames.alerts, "Mutation/Validate bad api token received");
|
|
140
|
-
this.addSummary(this.#metricNames.mutate, "Mutation operation summary");
|
|
141
|
-
this.addSummary(this.#metricNames.validate, "Validation operation summary");
|
|
142
|
-
this.addGauge(this.#metricNames.cacheMiss, "Number of cache misses per window", ["window"]);
|
|
143
|
-
this.addGauge(this.#metricNames.resyncFailureCount, "Number of failures per resync operation", ["count"]);
|
|
144
|
-
}
|
|
145
|
-
#getMetricName = (name2) => `${this.#prefix}_${name2}`;
|
|
146
|
-
#addMetric = (collection, MetricType, name2, help, labelNames) => {
|
|
147
|
-
if (collection.has(this.#getMetricName(name2))) {
|
|
148
|
-
logger_default.debug(`Metric for ${name2} already exists`, loggingPrefix);
|
|
149
|
-
return;
|
|
129
|
+
receive = (data) => {
|
|
130
|
+
this.#store = data || {};
|
|
131
|
+
this.#onReady();
|
|
132
|
+
for (const idx in this.#subscribers) {
|
|
133
|
+
this.#subscribers[idx]((0, import_ramda.clone)(this.#store));
|
|
150
134
|
}
|
|
151
|
-
const metric = new MetricType({
|
|
152
|
-
name: this.#getMetricName(name2),
|
|
153
|
-
help,
|
|
154
|
-
registers: [this.#registry],
|
|
155
|
-
labelNames
|
|
156
|
-
});
|
|
157
|
-
collection.set(this.#getMetricName(name2), metric);
|
|
158
135
|
};
|
|
159
|
-
|
|
160
|
-
this.#
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
136
|
+
getItem = (key) => {
|
|
137
|
+
const result = this.#store[v2UnescapedStoreKey(key)] || null;
|
|
138
|
+
if (result !== null && typeof result !== "function" && typeof result !== "object") {
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
164
142
|
};
|
|
165
|
-
|
|
166
|
-
|
|
143
|
+
clear = () => {
|
|
144
|
+
if (Object.keys(this.#store).length > 0) {
|
|
145
|
+
this.#dispatchUpdate(
|
|
146
|
+
"remove",
|
|
147
|
+
Object.keys(this.#store).map((key) => import_json_pointer.default.escape(key))
|
|
148
|
+
);
|
|
149
|
+
}
|
|
167
150
|
};
|
|
168
|
-
|
|
169
|
-
this.#
|
|
151
|
+
removeItem = (key) => {
|
|
152
|
+
this.#dispatchUpdate("remove", [v2StoreKey(key)]);
|
|
170
153
|
};
|
|
171
|
-
|
|
172
|
-
this.#
|
|
154
|
+
setItem = (key, value) => {
|
|
155
|
+
this.#dispatchUpdate("add", [v2StoreKey(key)], value);
|
|
173
156
|
};
|
|
174
157
|
/**
|
|
175
|
-
*
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
*
|
|
180
|
-
|
|
181
|
-
alert = () => this.incCounter(this.#metricNames.alerts);
|
|
182
|
-
/**
|
|
183
|
-
* Observes the duration since the provided start time and updates the summary.
|
|
184
|
-
* @param startTime - The start time.
|
|
185
|
-
* @param name - The metrics summary to increment.
|
|
158
|
+
* Creates a promise and subscribes to the store, the promise resolves when
|
|
159
|
+
* the key and value are seen in the store.
|
|
160
|
+
*
|
|
161
|
+
* @param key - The key to add into the store
|
|
162
|
+
* @param value - The value of the key
|
|
163
|
+
* @returns
|
|
186
164
|
*/
|
|
187
|
-
|
|
188
|
-
this.#
|
|
165
|
+
setItemAndWait = (key, value) => {
|
|
166
|
+
this.#dispatchUpdate("add", [v2StoreKey(key)], value);
|
|
167
|
+
const record = {};
|
|
168
|
+
return new Promise((resolve, reject) => {
|
|
169
|
+
record.timeout = setTimeout(() => {
|
|
170
|
+
record.unsubscribe();
|
|
171
|
+
return reject(`MAX_WAIT_TIME elapsed: Key ${key} not seen in ${MAX_WAIT_TIME / 1e3}s`);
|
|
172
|
+
}, MAX_WAIT_TIME);
|
|
173
|
+
record.unsubscribe = this.subscribe((data) => {
|
|
174
|
+
if (data[`${v2UnescapedStoreKey(key)}`] === value) {
|
|
175
|
+
record.unsubscribe();
|
|
176
|
+
clearTimeout(record.timeout);
|
|
177
|
+
resolve("ok");
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
});
|
|
189
181
|
};
|
|
190
182
|
/**
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
* Returns the current timestamp from performance.now() method. Useful for start timing an operation.
|
|
197
|
-
* @returns The timestamp.
|
|
198
|
-
*/
|
|
199
|
-
static observeStart() {
|
|
200
|
-
return import_perf_hooks.performance.now();
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Increments the cache miss gauge for a given label.
|
|
204
|
-
* @param label - The label for the cache miss.
|
|
183
|
+
* Creates a promise and subscribes to the store, the promise resolves when
|
|
184
|
+
* the key is removed from the store.
|
|
185
|
+
*
|
|
186
|
+
* @param key - The key to add into the store
|
|
187
|
+
* @returns
|
|
205
188
|
*/
|
|
206
|
-
|
|
207
|
-
this
|
|
189
|
+
removeItemAndWait = (key) => {
|
|
190
|
+
this.#dispatchUpdate("remove", [v2StoreKey(key)]);
|
|
191
|
+
const record = {};
|
|
192
|
+
return new Promise((resolve, reject) => {
|
|
193
|
+
record.timeout = setTimeout(() => {
|
|
194
|
+
record.unsubscribe();
|
|
195
|
+
return reject(`MAX_WAIT_TIME elapsed: Key ${key} still seen after ${MAX_WAIT_TIME / 1e3}s`);
|
|
196
|
+
}, MAX_WAIT_TIME);
|
|
197
|
+
record.unsubscribe = this.subscribe((data) => {
|
|
198
|
+
if (!Object.hasOwn(data, `${v2UnescapedStoreKey(key)}`)) {
|
|
199
|
+
record.unsubscribe();
|
|
200
|
+
clearTimeout(record.timeout);
|
|
201
|
+
resolve("ok");
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
});
|
|
208
205
|
};
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
206
|
+
subscribe = (subscriber) => {
|
|
207
|
+
const idx = this.#subscriberId++;
|
|
208
|
+
this.#subscribers[idx] = subscriber;
|
|
209
|
+
return () => this.unsubscribe(idx);
|
|
210
|
+
};
|
|
211
|
+
onReady = (callback) => {
|
|
212
|
+
this.#readyHandlers.push(callback);
|
|
215
213
|
};
|
|
216
214
|
/**
|
|
217
|
-
*
|
|
218
|
-
* @param
|
|
215
|
+
* Remove a subscriber from the list of subscribers.
|
|
216
|
+
* @param idx - The index of the subscriber to remove.
|
|
219
217
|
*/
|
|
220
|
-
|
|
221
|
-
this.#
|
|
222
|
-
|
|
223
|
-
|
|
218
|
+
unsubscribe = (idx) => {
|
|
219
|
+
delete this.#subscribers[idx];
|
|
220
|
+
};
|
|
221
|
+
#onReady = () => {
|
|
222
|
+
for (const handler of this.#readyHandlers) {
|
|
223
|
+
handler((0, import_ramda.clone)(this.#store));
|
|
224
|
+
}
|
|
225
|
+
this.#onReady = () => {
|
|
226
|
+
};
|
|
224
227
|
};
|
|
225
228
|
/**
|
|
226
|
-
*
|
|
229
|
+
* Dispatch an update to the store and notify all subscribers.
|
|
230
|
+
* @param op - The type of operation to perform.
|
|
231
|
+
* @param keys - The keys to update.
|
|
232
|
+
* @param [value] - The new value.
|
|
227
233
|
*/
|
|
228
|
-
#
|
|
229
|
-
|
|
230
|
-
if (maxCacheMissWindows !== void 0 && this.#cacheMissWindows.size >= maxCacheMissWindows) {
|
|
231
|
-
const firstKey = this.#cacheMissWindows.keys().next().value;
|
|
232
|
-
if (firstKey !== void 0) {
|
|
233
|
-
this.#cacheMissWindows.delete(firstKey);
|
|
234
|
-
}
|
|
235
|
-
this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.remove({ window: firstKey });
|
|
236
|
-
}
|
|
234
|
+
#dispatchUpdate = (op, keys, value) => {
|
|
235
|
+
this.#send(op, keys, value);
|
|
237
236
|
};
|
|
238
237
|
};
|
|
239
|
-
var metricsCollector = new MetricsCollector("pepr");
|
|
240
|
-
|
|
241
|
-
// src/lib/processors/mutate-processor.ts
|
|
242
|
-
var import_fast_json_patch = __toESM(require("fast-json-patch"));
|
|
243
|
-
var import_ramda4 = require("ramda");
|
|
244
|
-
|
|
245
|
-
// src/lib/telemetry/timeUtils.ts
|
|
246
|
-
var getNow = () => performance.now();
|
|
247
238
|
|
|
248
|
-
// src/lib/
|
|
249
|
-
var
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
239
|
+
// src/lib/core/schedule.ts
|
|
240
|
+
var OnSchedule = class {
|
|
241
|
+
intervalId = null;
|
|
242
|
+
store;
|
|
243
|
+
name;
|
|
244
|
+
completions;
|
|
245
|
+
every;
|
|
246
|
+
unit;
|
|
247
|
+
run;
|
|
248
|
+
startTime;
|
|
249
|
+
duration;
|
|
250
|
+
lastTimestamp;
|
|
251
|
+
constructor(schedule) {
|
|
252
|
+
this.name = schedule.name;
|
|
253
|
+
this.run = schedule.run;
|
|
254
|
+
this.every = schedule.every;
|
|
255
|
+
this.unit = schedule.unit;
|
|
256
|
+
this.startTime = schedule?.startTime;
|
|
257
|
+
this.completions = schedule?.completions;
|
|
256
258
|
}
|
|
257
|
-
|
|
258
|
-
this
|
|
259
|
-
this.
|
|
260
|
-
logger_default.info(`Starting timer at ${this.#startTime}`);
|
|
259
|
+
setStore(store) {
|
|
260
|
+
this.store = store;
|
|
261
|
+
this.startInterval();
|
|
261
262
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
263
|
+
startInterval() {
|
|
264
|
+
this.checkStore();
|
|
265
|
+
this.getDuration();
|
|
266
|
+
this.setupInterval();
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Checks the store for this schedule and sets the values if it exists
|
|
270
|
+
* @returns
|
|
271
|
+
*/
|
|
272
|
+
checkStore() {
|
|
273
|
+
const result = this.store && this.store.getItem(this.name);
|
|
274
|
+
if (result) {
|
|
275
|
+
const storedSchedule = JSON.parse(result);
|
|
276
|
+
this.completions = storedSchedule?.completions;
|
|
277
|
+
this.startTime = storedSchedule?.startTime;
|
|
278
|
+
this.lastTimestamp = storedSchedule?.lastTimestamp;
|
|
265
279
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Saves the schedule to the store
|
|
283
|
+
* @returns
|
|
284
|
+
*/
|
|
285
|
+
saveToStore() {
|
|
286
|
+
const schedule = {
|
|
287
|
+
completions: this.completions,
|
|
288
|
+
startTime: this.startTime,
|
|
289
|
+
lastTimestamp: /* @__PURE__ */ new Date(),
|
|
290
|
+
name: this.name
|
|
291
|
+
};
|
|
292
|
+
if (this.store) this.store.setItem(this.name, JSON.stringify(schedule));
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Gets the durations in milliseconds
|
|
296
|
+
*/
|
|
297
|
+
getDuration() {
|
|
298
|
+
switch (this.unit) {
|
|
299
|
+
case "seconds":
|
|
300
|
+
if (this.every < 10) throw new Error("10 Seconds in the smallest interval allowed");
|
|
301
|
+
this.duration = 1e3 * this.every;
|
|
302
|
+
break;
|
|
303
|
+
case "minutes":
|
|
304
|
+
case "minute":
|
|
305
|
+
this.duration = 1e3 * 60 * this.every;
|
|
306
|
+
break;
|
|
307
|
+
case "hours":
|
|
308
|
+
case "hour":
|
|
309
|
+
this.duration = 1e3 * 60 * 60 * this.every;
|
|
310
|
+
break;
|
|
311
|
+
default:
|
|
312
|
+
throw new Error("Invalid time unit");
|
|
271
313
|
}
|
|
272
314
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
var declaredGroup = (0, import_ramda.pipe)(
|
|
282
|
-
(request) => request?.kind?.group,
|
|
283
|
-
(0, import_ramda.defaultTo)("")
|
|
284
|
-
);
|
|
285
|
-
var declaredVersion = (0, import_ramda.pipe)(
|
|
286
|
-
(request) => request?.kind?.version,
|
|
287
|
-
(0, import_ramda.defaultTo)("")
|
|
288
|
-
);
|
|
289
|
-
var declaredKind = (0, import_ramda.pipe)(
|
|
290
|
-
(request) => request?.kind?.kind,
|
|
291
|
-
(0, import_ramda.defaultTo)("")
|
|
292
|
-
);
|
|
293
|
-
var declaredUid = (0, import_ramda.pipe)((request) => request?.uid, (0, import_ramda.defaultTo)(""));
|
|
294
|
-
var carriesDeletionTimestamp = (0, import_ramda.pipe)(
|
|
295
|
-
(kubernetesObject) => !!kubernetesObject.metadata?.deletionTimestamp,
|
|
296
|
-
(0, import_ramda.defaultTo)(false)
|
|
297
|
-
);
|
|
298
|
-
var missingDeletionTimestamp = (0, import_ramda.complement)(carriesDeletionTimestamp);
|
|
299
|
-
var carriedKind = (0, import_ramda.pipe)(
|
|
300
|
-
(kubernetesObject) => kubernetesObject?.kind,
|
|
301
|
-
(0, import_ramda.defaultTo)("not set")
|
|
302
|
-
);
|
|
303
|
-
var carriedVersion = (0, import_ramda.pipe)(
|
|
304
|
-
(kubernetesObject) => kubernetesObject?.metadata?.resourceVersion,
|
|
305
|
-
(0, import_ramda.defaultTo)("not set")
|
|
306
|
-
);
|
|
307
|
-
var carriedName = (0, import_ramda.pipe)(
|
|
308
|
-
(kubernetesObject) => kubernetesObject?.metadata?.name,
|
|
309
|
-
(0, import_ramda.defaultTo)("")
|
|
310
|
-
);
|
|
311
|
-
var carriesName = (0, import_ramda.pipe)(carriedName, (0, import_ramda.equals)(""), import_ramda.not);
|
|
312
|
-
var missingName = (0, import_ramda.complement)(carriesName);
|
|
313
|
-
var carriedNamespace = (0, import_ramda.pipe)(
|
|
314
|
-
(kubernetesObject) => kubernetesObject?.metadata?.namespace,
|
|
315
|
-
(0, import_ramda.defaultTo)("")
|
|
316
|
-
);
|
|
317
|
-
var carriesNamespace = (0, import_ramda.pipe)(carriedNamespace, (0, import_ramda.equals)(""), import_ramda.not);
|
|
318
|
-
var carriedAnnotations = (0, import_ramda.pipe)(
|
|
319
|
-
(kubernetesObject) => kubernetesObject?.metadata?.annotations,
|
|
320
|
-
(0, import_ramda.defaultTo)({})
|
|
321
|
-
);
|
|
322
|
-
var carriesAnnotations = (0, import_ramda.pipe)(carriedAnnotations, (0, import_ramda.equals)({}), import_ramda.not);
|
|
323
|
-
var carriedLabels = (0, import_ramda.pipe)(
|
|
324
|
-
(kubernetesObject) => kubernetesObject?.metadata?.labels,
|
|
325
|
-
(0, import_ramda.defaultTo)({})
|
|
326
|
-
);
|
|
327
|
-
var carriesLabels = (0, import_ramda.pipe)(carriedLabels, (0, import_ramda.equals)({}), import_ramda.not);
|
|
328
|
-
var definesDeletionTimestamp = (0, import_ramda.pipe)(
|
|
329
|
-
(binding) => binding?.filters?.deletionTimestamp ?? false,
|
|
330
|
-
(0, import_ramda.defaultTo)(false)
|
|
331
|
-
);
|
|
332
|
-
var ignoresDeletionTimestamp = (0, import_ramda.complement)(definesDeletionTimestamp);
|
|
333
|
-
var definedName = (0, import_ramda.pipe)((binding) => {
|
|
334
|
-
return binding.filters.name;
|
|
335
|
-
}, (0, import_ramda.defaultTo)(""));
|
|
336
|
-
var definesName = (0, import_ramda.pipe)(definedName, (0, import_ramda.equals)(""), import_ramda.not);
|
|
337
|
-
var ignoresName = (0, import_ramda.complement)(definesName);
|
|
338
|
-
var definedNameRegex = (0, import_ramda.pipe)(
|
|
339
|
-
(binding) => binding.filters?.regexName,
|
|
340
|
-
(0, import_ramda.defaultTo)("")
|
|
341
|
-
);
|
|
342
|
-
var definesNameRegex = (0, import_ramda.pipe)(definedNameRegex, (0, import_ramda.equals)(""), import_ramda.not);
|
|
343
|
-
var definedNamespaces = (0, import_ramda.pipe)((binding) => binding?.filters?.namespaces, (0, import_ramda.defaultTo)([]));
|
|
344
|
-
var definesNamespaces = (0, import_ramda.pipe)(definedNamespaces, (0, import_ramda.equals)([]), import_ramda.not);
|
|
345
|
-
var definedNamespaceRegexes = (0, import_ramda.pipe)((binding) => binding?.filters?.regexNamespaces, (0, import_ramda.defaultTo)([]));
|
|
346
|
-
var definesNamespaceRegexes = (0, import_ramda.pipe)(definedNamespaceRegexes, (0, import_ramda.equals)([]), import_ramda.not);
|
|
347
|
-
var definedAnnotations = (0, import_ramda.pipe)((binding) => binding?.filters?.annotations, (0, import_ramda.defaultTo)({}));
|
|
348
|
-
var definesAnnotations = (0, import_ramda.pipe)(definedAnnotations, (0, import_ramda.equals)({}), import_ramda.not);
|
|
349
|
-
var definedLabels = (0, import_ramda.pipe)((binding) => binding?.filters?.labels, (0, import_ramda.defaultTo)({}));
|
|
350
|
-
var definesLabels = (0, import_ramda.pipe)(definedLabels, (0, import_ramda.equals)({}), import_ramda.not);
|
|
351
|
-
var definedEvent = (binding) => {
|
|
352
|
-
return binding.event;
|
|
353
|
-
};
|
|
354
|
-
var definesDelete = (0, import_ramda.pipe)(definedEvent, (0, import_ramda.equals)("DELETE" /* DELETE */));
|
|
355
|
-
var definedGroup = (0, import_ramda.pipe)((binding) => binding?.kind?.group, (0, import_ramda.defaultTo)(""));
|
|
356
|
-
var definesGroup = (0, import_ramda.pipe)(definedGroup, (0, import_ramda.equals)(""), import_ramda.not);
|
|
357
|
-
var definedVersion = (0, import_ramda.pipe)(
|
|
358
|
-
(binding) => binding?.kind?.version,
|
|
359
|
-
(0, import_ramda.defaultTo)("")
|
|
360
|
-
);
|
|
361
|
-
var definesVersion = (0, import_ramda.pipe)(definedVersion, (0, import_ramda.equals)(""), import_ramda.not);
|
|
362
|
-
var definedKind = (0, import_ramda.pipe)((binding) => binding?.kind?.kind, (0, import_ramda.defaultTo)(""));
|
|
363
|
-
var definesKind = (0, import_ramda.pipe)(definedKind, (0, import_ramda.equals)(""), import_ramda.not);
|
|
364
|
-
var definedCallback = (binding) => {
|
|
365
|
-
return binding.isFinalize ? binding.finalizeCallback : binding.isWatch ? binding.watchCallback : binding.isMutate ? binding.mutateCallback : binding.isValidate ? binding.validateCallback : null;
|
|
366
|
-
};
|
|
367
|
-
var definedCallbackName = (0, import_ramda.pipe)(definedCallback, (0, import_ramda.defaultTo)({ name: "" }), (callback) => callback.name);
|
|
368
|
-
var mismatchedDeletionTimestamp = (0, import_ramda.allPass)([
|
|
369
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesDeletionTimestamp),
|
|
370
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(1), missingDeletionTimestamp)
|
|
371
|
-
]);
|
|
372
|
-
var mismatchedName = (0, import_ramda.allPass)([
|
|
373
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesName),
|
|
374
|
-
(0, import_ramda.pipe)((binding, kubernetesObject) => definedName(binding) !== carriedName(kubernetesObject))
|
|
375
|
-
]);
|
|
376
|
-
var mismatchedNameRegex = (0, import_ramda.allPass)([
|
|
377
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesNameRegex),
|
|
378
|
-
(0, import_ramda.pipe)((binding, kubernetesObject) => new RegExp(definedNameRegex(binding)).test(carriedName(kubernetesObject)), import_ramda.not)
|
|
379
|
-
]);
|
|
380
|
-
var bindsToKind = (0, import_ramda.curry)(
|
|
381
|
-
(0, import_ramda.allPass)([(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definedKind, (0, import_ramda.equals)(""), import_ramda.not), (0, import_ramda.pipe)((binding, kind3) => definedKind(binding) === kind3)])
|
|
382
|
-
);
|
|
383
|
-
var bindsToNamespace = (0, import_ramda.curry)((0, import_ramda.pipe)(bindsToKind(import_ramda.__, "Namespace")));
|
|
384
|
-
var misboundNamespace = (0, import_ramda.allPass)([bindsToNamespace, definesNamespaces]);
|
|
385
|
-
var mismatchedNamespace = (0, import_ramda.allPass)([
|
|
386
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesNamespaces),
|
|
387
|
-
(0, import_ramda.pipe)((binding, kubernetesObject) => definedNamespaces(binding).includes(carriedNamespace(kubernetesObject)), import_ramda.not)
|
|
388
|
-
]);
|
|
389
|
-
var mismatchedNamespaceRegex = (0, import_ramda.allPass)([
|
|
390
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesNamespaceRegexes),
|
|
391
|
-
(0, import_ramda.pipe)(
|
|
392
|
-
(binding, kubernetesObject) => (0, import_ramda.pipe)(
|
|
393
|
-
(0, import_ramda.any)((regEx) => new RegExp(regEx).test(carriedNamespace(kubernetesObject))),
|
|
394
|
-
import_ramda.not
|
|
395
|
-
)(definedNamespaceRegexes(binding))
|
|
396
|
-
)
|
|
397
|
-
]);
|
|
398
|
-
var metasMismatch = (0, import_ramda.pipe)(
|
|
399
|
-
(defined, carried) => {
|
|
400
|
-
const result = { defined, carried, unalike: {} };
|
|
401
|
-
result.unalike = Object.entries(result.defined).map(([key, value]) => {
|
|
402
|
-
const keyMissing = !Object.hasOwn(result.carried, key);
|
|
403
|
-
const noValue = !value;
|
|
404
|
-
const valMissing = !result.carried[key];
|
|
405
|
-
const valDiffers = result.carried[key] !== result.defined[key];
|
|
406
|
-
return keyMissing ? { [key]: value } : noValue ? {} : valMissing ? { [key]: value } : valDiffers ? { [key]: value } : {};
|
|
407
|
-
}).reduce((acc, cur) => ({ ...acc, ...cur }), {});
|
|
408
|
-
return result.unalike;
|
|
409
|
-
},
|
|
410
|
-
(unalike) => Object.keys(unalike).length > 0
|
|
411
|
-
);
|
|
412
|
-
var mismatchedAnnotations = (0, import_ramda.allPass)([
|
|
413
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesAnnotations),
|
|
414
|
-
(0, import_ramda.pipe)((binding, kubernetesObject) => metasMismatch(definedAnnotations(binding), carriedAnnotations(kubernetesObject)))
|
|
415
|
-
]);
|
|
416
|
-
var mismatchedLabels = (0, import_ramda.allPass)([
|
|
417
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesLabels),
|
|
418
|
-
(0, import_ramda.pipe)((binding, kubernetesObject) => metasMismatch(definedLabels(binding), carriedLabels(kubernetesObject)))
|
|
419
|
-
]);
|
|
420
|
-
var uncarryableNamespace = (0, import_ramda.allPass)([
|
|
421
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), import_ramda.length, (0, import_ramda.gt)(import_ramda.__, 0)),
|
|
422
|
-
(0, import_ramda.pipe)((namespaceSelector, kubernetesObject) => {
|
|
423
|
-
if (kubernetesObject?.kind === "Namespace") {
|
|
424
|
-
return namespaceSelector.includes(kubernetesObject?.metadata?.name);
|
|
315
|
+
/**
|
|
316
|
+
* Sets up the interval
|
|
317
|
+
*/
|
|
318
|
+
setupInterval() {
|
|
319
|
+
const now = /* @__PURE__ */ new Date();
|
|
320
|
+
let delay;
|
|
321
|
+
if (this.lastTimestamp && this.startTime) {
|
|
322
|
+
this.startTime = void 0;
|
|
425
323
|
}
|
|
426
|
-
if (
|
|
427
|
-
|
|
324
|
+
if (this.startTime) {
|
|
325
|
+
delay = this.startTime.getTime() - now.getTime();
|
|
326
|
+
} else if (this.lastTimestamp && this.duration) {
|
|
327
|
+
const lastTimestamp = new Date(this.lastTimestamp);
|
|
328
|
+
delay = this.duration - (now.getTime() - lastTimestamp.getTime());
|
|
428
329
|
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
(namespaceSelector, kubernetesObject) => kubernetesObject.kind === "Namespace" ? !namespaceSelector.includes(kubernetesObject.metadata.name) : !carriesNamespace(kubernetesObject)
|
|
436
|
-
)
|
|
437
|
-
]);
|
|
438
|
-
var carriesIgnoredNamespace = (0, import_ramda.allPass)([
|
|
439
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), import_ramda.length, (0, import_ramda.gt)(import_ramda.__, 0)),
|
|
440
|
-
(0, import_ramda.pipe)((namespaceSelector, kubernetesObject) => {
|
|
441
|
-
if (kubernetesObject?.kind === "Namespace") {
|
|
442
|
-
return namespaceSelector.includes(kubernetesObject?.metadata?.name);
|
|
330
|
+
if (delay === void 0 || delay <= 0) {
|
|
331
|
+
this.start();
|
|
332
|
+
} else {
|
|
333
|
+
setTimeout(() => {
|
|
334
|
+
this.start();
|
|
335
|
+
}, delay);
|
|
443
336
|
}
|
|
444
|
-
|
|
445
|
-
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Starts the interval
|
|
340
|
+
*/
|
|
341
|
+
start() {
|
|
342
|
+
this.intervalId = setInterval(() => {
|
|
343
|
+
if (this.completions === 0) {
|
|
344
|
+
this.stop();
|
|
345
|
+
return;
|
|
346
|
+
} else {
|
|
347
|
+
this.run();
|
|
348
|
+
if (this.completions && this.completions !== 0) {
|
|
349
|
+
this.completions -= 1;
|
|
350
|
+
}
|
|
351
|
+
this.saveToStore();
|
|
352
|
+
}
|
|
353
|
+
}, this.duration);
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Stops the interval
|
|
357
|
+
*/
|
|
358
|
+
stop() {
|
|
359
|
+
if (this.intervalId) {
|
|
360
|
+
clearInterval(this.intervalId);
|
|
361
|
+
this.intervalId = null;
|
|
446
362
|
}
|
|
447
|
-
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
var unbindableNamespaces = (0, import_ramda.allPass)([
|
|
451
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), import_ramda.length, (0, import_ramda.gt)(import_ramda.__, 0)),
|
|
452
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(1), definesNamespaces),
|
|
453
|
-
(0, import_ramda.pipe)(
|
|
454
|
-
(namespaceSelector, binding) => (0, import_ramda.difference)(definedNamespaces(binding), namespaceSelector),
|
|
455
|
-
import_ramda.length,
|
|
456
|
-
(0, import_ramda.equals)(0),
|
|
457
|
-
import_ramda.not
|
|
458
|
-
)
|
|
459
|
-
]);
|
|
460
|
-
var misboundDeleteWithDeletionTimestamp = (0, import_ramda.allPass)([definesDelete, definesDeletionTimestamp]);
|
|
461
|
-
var operationMatchesEvent = (0, import_ramda.anyPass)([
|
|
462
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(1), (0, import_ramda.equals)("*" /* ANY */)),
|
|
463
|
-
(0, import_ramda.pipe)((operation, event) => operation.valueOf() === event.valueOf()),
|
|
464
|
-
(0, import_ramda.pipe)((operation, event) => operation ? event.includes(operation) : false)
|
|
465
|
-
]);
|
|
466
|
-
var mismatchedEvent = (0, import_ramda.pipe)(
|
|
467
|
-
(binding, request) => operationMatchesEvent(declaredOperation(request), definedEvent(binding)),
|
|
468
|
-
import_ramda.not
|
|
469
|
-
);
|
|
470
|
-
var mismatchedGroup = (0, import_ramda.allPass)([
|
|
471
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesGroup),
|
|
472
|
-
(0, import_ramda.pipe)((binding, request) => definedGroup(binding) !== declaredGroup(request))
|
|
473
|
-
]);
|
|
474
|
-
var mismatchedVersion = (0, import_ramda.allPass)([
|
|
475
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesVersion),
|
|
476
|
-
(0, import_ramda.pipe)((binding, request) => definedVersion(binding) !== declaredVersion(request))
|
|
477
|
-
]);
|
|
478
|
-
var mismatchedKind = (0, import_ramda.allPass)([
|
|
479
|
-
(0, import_ramda.pipe)((0, import_ramda.nthArg)(0), definesKind),
|
|
480
|
-
(0, import_ramda.pipe)((binding, request) => definedKind(binding) !== declaredKind(request))
|
|
481
|
-
]);
|
|
363
|
+
if (this.store) this.store.removeItem(this.name);
|
|
364
|
+
}
|
|
365
|
+
};
|
|
482
366
|
|
|
483
|
-
// src/lib/
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
() => adjudicateMisboundDeleteWithDeletionTimestamp(binding),
|
|
489
|
-
() => adjudicateMismatchedDeletionTimestamp(binding, obj),
|
|
490
|
-
() => adjudicateMismatchedEvent(binding, req),
|
|
491
|
-
() => adjudicateMismatchedName(binding, obj),
|
|
492
|
-
() => adjudicateMismatchedGroup(binding, req),
|
|
493
|
-
() => adjudicateMismatchedVersion(binding, req),
|
|
494
|
-
() => adjudicateMismatchedKind(binding, req),
|
|
495
|
-
() => adjudicateUnbindableNamespaces(capabilityNamespaces, binding),
|
|
496
|
-
() => adjudicateUncarryableNamespace(capabilityNamespaces, obj),
|
|
497
|
-
() => adjudicateMismatchedNamespace(binding, obj),
|
|
498
|
-
() => adjudicateMismatchedLabels(binding, obj),
|
|
499
|
-
() => adjudicateMismatchedAnnotations(binding, obj),
|
|
500
|
-
() => adjudicateMismatchedNamespaceRegex(binding, obj),
|
|
501
|
-
() => adjudicateMismatchedNameRegex(binding, obj),
|
|
502
|
-
() => adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj),
|
|
503
|
-
() => adjudicateMissingCarriableNamespace(capabilityNamespaces, obj)
|
|
504
|
-
];
|
|
505
|
-
for (const adjudicator of adjudicators) {
|
|
506
|
-
const result = adjudicator();
|
|
507
|
-
if (result) {
|
|
508
|
-
return `${prefix} ${result}`;
|
|
509
|
-
}
|
|
367
|
+
// src/lib/finalizer.ts
|
|
368
|
+
var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
|
|
369
|
+
function addFinalizer(request) {
|
|
370
|
+
if (request.Request.operation === "DELETE" /* DELETE */) {
|
|
371
|
+
return;
|
|
510
372
|
}
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
function filterNoMatchReason(binding, obj, capabilityNamespaces, ignoredNamespaces) {
|
|
514
|
-
const prefix = "Ignoring Watch Callback:";
|
|
515
|
-
const adjudicators = [
|
|
516
|
-
() => adjudicateMismatchedDeletionTimestamp(binding, obj),
|
|
517
|
-
() => adjudicateMismatchedName(binding, obj),
|
|
518
|
-
() => adjudicateMisboundNamespace(binding),
|
|
519
|
-
() => adjudicateMismatchedLabels(binding, obj),
|
|
520
|
-
() => adjudicateMismatchedAnnotations(binding, obj),
|
|
521
|
-
() => adjudicateUncarryableNamespace(capabilityNamespaces, obj),
|
|
522
|
-
() => adjudicateUnbindableNamespaces(capabilityNamespaces, binding),
|
|
523
|
-
() => adjudicateMismatchedNamespace(binding, obj),
|
|
524
|
-
() => adjudicateMismatchedNamespaceRegex(binding, obj),
|
|
525
|
-
() => adjudicateMismatchedNameRegex(binding, obj),
|
|
526
|
-
() => adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj),
|
|
527
|
-
() => adjudicateMissingCarriableNamespace(capabilityNamespaces, obj)
|
|
528
|
-
];
|
|
529
|
-
for (const adjudicator of adjudicators) {
|
|
530
|
-
const result = adjudicator();
|
|
531
|
-
if (result) {
|
|
532
|
-
return `${prefix} ${result}`;
|
|
533
|
-
}
|
|
373
|
+
if (request.Request.operation === "UPDATE" /* UPDATE */ && request.Raw.metadata?.deletionTimestamp) {
|
|
374
|
+
return;
|
|
534
375
|
}
|
|
535
|
-
|
|
376
|
+
const peprFinal = "pepr.dev/finalizer";
|
|
377
|
+
const finalizers = request.Raw.metadata?.finalizers || [];
|
|
378
|
+
if (!finalizers.includes(peprFinal)) {
|
|
379
|
+
finalizers.push(peprFinal);
|
|
380
|
+
}
|
|
381
|
+
request.Merge({ metadata: { finalizers } });
|
|
536
382
|
}
|
|
537
|
-
function
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
}
|
|
561
|
-
function adjudicateUnbindableNamespaces(capabilityNamespaces, binding) {
|
|
562
|
-
return unbindableNamespaces(capabilityNamespaces, binding) ? `Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
563
|
-
}
|
|
564
|
-
function adjudicateUncarryableNamespace(capabilityNamespaces, obj) {
|
|
565
|
-
return uncarryableNamespace(capabilityNamespaces, obj) ? `Object carries namespace '${obj.kind && obj.kind === "Namespace" ? obj.metadata?.name : carriedNamespace(obj)}' but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
566
|
-
}
|
|
567
|
-
function adjudicateMismatchedNamespace(binding, obj) {
|
|
568
|
-
return mismatchedNamespace(binding, obj) ? `Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' but Object carries '${carriedNamespace(obj)}'.` : null;
|
|
569
|
-
}
|
|
570
|
-
function adjudicateMismatchedLabels(binding, obj) {
|
|
571
|
-
return mismatchedLabels(binding, obj) ? `Binding defines labels '${JSON.stringify(definedLabels(binding))}' but Object carries '${JSON.stringify(carriedLabels(obj))}'.` : null;
|
|
572
|
-
}
|
|
573
|
-
function adjudicateMismatchedAnnotations(binding, obj) {
|
|
574
|
-
return mismatchedAnnotations(binding, obj) ? `Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' but Object carries '${JSON.stringify(carriedAnnotations(obj))}'.` : null;
|
|
575
|
-
}
|
|
576
|
-
function adjudicateMismatchedNamespaceRegex(binding, obj) {
|
|
577
|
-
return mismatchedNamespaceRegex(binding, obj) ? `Binding defines namespace regexes '${JSON.stringify(definedNamespaceRegexes(binding))}' but Object carries '${carriedNamespace(obj)}'.` : null;
|
|
578
|
-
}
|
|
579
|
-
function adjudicateMismatchedNameRegex(binding, obj) {
|
|
580
|
-
return mismatchedNameRegex(binding, obj) ? `Binding defines name regex '${definedNameRegex(binding)}' but Object carries '${carriedName(obj)}'.` : null;
|
|
581
|
-
}
|
|
582
|
-
function adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj) {
|
|
583
|
-
return carriesIgnoredNamespace(ignoredNamespaces, obj) ? `Object carries namespace '${obj.kind && obj.kind === "Namespace" ? obj.metadata?.name : carriedNamespace(obj)}' but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.` : null;
|
|
584
|
-
}
|
|
585
|
-
function adjudicateMissingCarriableNamespace(capabilityNamespaces, obj) {
|
|
586
|
-
return missingCarriableNamespace(capabilityNamespaces, obj) ? `Object does not carry a namespace but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
383
|
+
async function removeFinalizer(binding, obj) {
|
|
384
|
+
const peprFinal = "pepr.dev/finalizer";
|
|
385
|
+
const meta = obj.metadata;
|
|
386
|
+
const resource = `${meta.namespace || "ClusterScoped"}/${meta.name}`;
|
|
387
|
+
logger_default.debug({ obj }, `Removing finalizer '${peprFinal}' from '${resource}'`);
|
|
388
|
+
const { model, kind: kind3 } = binding;
|
|
389
|
+
try {
|
|
390
|
+
(0, import_kubernetes_fluent_client.RegisterKind)(model, kind3);
|
|
391
|
+
} catch (e) {
|
|
392
|
+
const expected = e.message === `GVK ${model.name} already registered`;
|
|
393
|
+
if (!expected) {
|
|
394
|
+
logger_default.error({ model, kind: kind3, error: e }, `Error registering "${kind3}" during finalization.`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const finalizers = meta.finalizers?.filter((f) => f !== peprFinal) || [];
|
|
399
|
+
obj = await (0, import_kubernetes_fluent_client.K8s)(model, meta).Patch([
|
|
400
|
+
{
|
|
401
|
+
op: "replace",
|
|
402
|
+
path: `/metadata/finalizers`,
|
|
403
|
+
value: finalizers
|
|
404
|
+
}
|
|
405
|
+
]);
|
|
406
|
+
logger_default.debug({ obj }, `Removed finalizer '${peprFinal}' from '${resource}'`);
|
|
587
407
|
}
|
|
588
408
|
|
|
589
|
-
// src/lib/
|
|
590
|
-
var
|
|
591
|
-
var
|
|
592
|
-
|
|
593
|
-
#
|
|
594
|
-
|
|
595
|
-
|
|
409
|
+
// src/lib/core/capability.ts
|
|
410
|
+
var registerAdmission = isBuildMode() || !isWatchMode();
|
|
411
|
+
var registerWatch = isBuildMode() || isWatchMode() || isDevMode();
|
|
412
|
+
var Capability = class {
|
|
413
|
+
#name;
|
|
414
|
+
#description;
|
|
415
|
+
#namespaces;
|
|
416
|
+
#bindings = [];
|
|
417
|
+
#store = new Storage();
|
|
418
|
+
#scheduleStore = new Storage();
|
|
419
|
+
#registered = false;
|
|
420
|
+
#scheduleRegistered = false;
|
|
421
|
+
hasSchedule;
|
|
422
|
+
/**
|
|
423
|
+
* Run code on a schedule with the capability.
|
|
424
|
+
*
|
|
425
|
+
* @param schedule The schedule to run the code on
|
|
426
|
+
* @returns
|
|
427
|
+
*/
|
|
428
|
+
OnSchedule = (schedule) => {
|
|
429
|
+
const { name: name2, every, unit, run, startTime, completions } = schedule;
|
|
430
|
+
this.hasSchedule = true;
|
|
431
|
+
if (process.env.PEPR_WATCH_MODE === "true" || process.env.PEPR_MODE === "dev") {
|
|
432
|
+
const newSchedule = {
|
|
433
|
+
name: name2,
|
|
434
|
+
every,
|
|
435
|
+
unit,
|
|
436
|
+
run,
|
|
437
|
+
startTime,
|
|
438
|
+
completions
|
|
439
|
+
};
|
|
440
|
+
this.#scheduleStore.onReady(() => {
|
|
441
|
+
new OnSchedule(newSchedule).setStore(this.#scheduleStore);
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
getScheduleStore() {
|
|
446
|
+
return this.#scheduleStore;
|
|
596
447
|
}
|
|
597
|
-
|
|
598
|
-
|
|
448
|
+
/**
|
|
449
|
+
* Store is a key-value data store that can be used to persist data that should be shared
|
|
450
|
+
* between requests. Each capability has its own store, and the data is persisted in Kubernetes
|
|
451
|
+
* in the `pepr-system` namespace.
|
|
452
|
+
*
|
|
453
|
+
* Note: You should only access the store from within an action.
|
|
454
|
+
*/
|
|
455
|
+
Store = {
|
|
456
|
+
clear: this.#store.clear,
|
|
457
|
+
getItem: this.#store.getItem,
|
|
458
|
+
removeItem: this.#store.removeItem,
|
|
459
|
+
removeItemAndWait: this.#store.removeItemAndWait,
|
|
460
|
+
setItem: this.#store.setItem,
|
|
461
|
+
subscribe: this.#store.subscribe,
|
|
462
|
+
onReady: this.#store.onReady,
|
|
463
|
+
setItemAndWait: this.#store.setItemAndWait
|
|
464
|
+
};
|
|
465
|
+
/**
|
|
466
|
+
* ScheduleStore is a key-value data store used to persist schedule data that should be shared
|
|
467
|
+
* between intervals. Each Schedule shares store, and the data is persisted in Kubernetes
|
|
468
|
+
* in the `pepr-system` namespace.
|
|
469
|
+
*
|
|
470
|
+
* Note: There is no direct access to schedule store
|
|
471
|
+
*/
|
|
472
|
+
ScheduleStore = {
|
|
473
|
+
clear: this.#scheduleStore.clear,
|
|
474
|
+
getItem: this.#scheduleStore.getItem,
|
|
475
|
+
removeItemAndWait: this.#scheduleStore.removeItemAndWait,
|
|
476
|
+
removeItem: this.#scheduleStore.removeItem,
|
|
477
|
+
setItemAndWait: this.#scheduleStore.setItemAndWait,
|
|
478
|
+
setItem: this.#scheduleStore.setItem,
|
|
479
|
+
subscribe: this.#scheduleStore.subscribe,
|
|
480
|
+
onReady: this.#scheduleStore.onReady
|
|
481
|
+
};
|
|
482
|
+
get bindings() {
|
|
483
|
+
return this.#bindings;
|
|
599
484
|
}
|
|
600
|
-
get
|
|
601
|
-
return this.#
|
|
485
|
+
get name() {
|
|
486
|
+
return this.#name;
|
|
602
487
|
}
|
|
603
|
-
get
|
|
604
|
-
return this.#
|
|
488
|
+
get description() {
|
|
489
|
+
return this.#description;
|
|
605
490
|
}
|
|
606
|
-
|
|
607
|
-
this.#
|
|
608
|
-
if (input.operation.toUpperCase() === "DELETE" /* DELETE */) {
|
|
609
|
-
this.Raw = (0, import_ramda2.clone)(input.oldObject);
|
|
610
|
-
} else {
|
|
611
|
-
this.Raw = (0, import_ramda2.clone)(input.object);
|
|
612
|
-
}
|
|
613
|
-
if (!this.Raw) {
|
|
614
|
-
throw new Error("Unable to load the request object into PeprRequest.Raw");
|
|
615
|
-
}
|
|
491
|
+
get namespaces() {
|
|
492
|
+
return this.#namespaces || [];
|
|
616
493
|
}
|
|
617
|
-
|
|
618
|
-
this
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
return this;
|
|
633
|
-
};
|
|
634
|
-
RemoveLabel = (key) => {
|
|
635
|
-
if (this.Raw.metadata?.labels?.[key]) {
|
|
636
|
-
delete this.Raw.metadata.labels[key];
|
|
494
|
+
constructor(cfg) {
|
|
495
|
+
this.#name = cfg.name;
|
|
496
|
+
this.#description = cfg.description;
|
|
497
|
+
this.#namespaces = cfg.namespaces;
|
|
498
|
+
this.hasSchedule = false;
|
|
499
|
+
logger_default.info(`Capability ${this.#name} registered`);
|
|
500
|
+
logger_default.debug(cfg);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Register the store with the capability. This is called automatically by the Pepr controller.
|
|
504
|
+
*/
|
|
505
|
+
registerScheduleStore = () => {
|
|
506
|
+
logger_default.info(`Registering schedule store for ${this.#name}`);
|
|
507
|
+
if (this.#scheduleRegistered) {
|
|
508
|
+
throw new Error(`Schedule store already registered for ${this.#name}`);
|
|
637
509
|
}
|
|
638
|
-
|
|
510
|
+
this.#scheduleRegistered = true;
|
|
511
|
+
return this.#scheduleStore;
|
|
639
512
|
};
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
513
|
+
/**
|
|
514
|
+
* Register the store with the capability. This is called automatically by the Pepr controller.
|
|
515
|
+
*
|
|
516
|
+
* @param store
|
|
517
|
+
*/
|
|
518
|
+
registerStore = () => {
|
|
519
|
+
logger_default.info(`Registering store for ${this.#name}`);
|
|
520
|
+
if (this.#registered) {
|
|
521
|
+
throw new Error(`Store already registered for ${this.#name}`);
|
|
643
522
|
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
HasLabel = (key) => {
|
|
647
|
-
return this.Raw.metadata?.labels?.[key] !== void 0;
|
|
648
|
-
};
|
|
649
|
-
HasAnnotation = (key) => {
|
|
650
|
-
return this.Raw.metadata?.annotations?.[key] !== void 0;
|
|
523
|
+
this.#registered = true;
|
|
524
|
+
return this.#store;
|
|
651
525
|
};
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
if (isAscii.test(decoded)) {
|
|
680
|
-
obj.data[key] = decoded;
|
|
681
|
-
} else {
|
|
682
|
-
skip.push(key);
|
|
526
|
+
/**
|
|
527
|
+
* The When method is used to register a action to be executed when a Kubernetes resource is
|
|
528
|
+
* processed by Pepr. The action will be executed if the resource matches the specified kind and any
|
|
529
|
+
* filters that are applied.
|
|
530
|
+
*
|
|
531
|
+
* @param model the KubernetesObject model to match
|
|
532
|
+
* @param kind if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind
|
|
533
|
+
* @returns
|
|
534
|
+
*/
|
|
535
|
+
When = (model, kind3) => {
|
|
536
|
+
const matchedKind = (0, import_kubernetes_fluent_client2.modelToGroupVersionKind)(model.name);
|
|
537
|
+
if (!matchedKind && !kind3) {
|
|
538
|
+
throw new Error(`Kind not specified for ${model.name}`);
|
|
539
|
+
}
|
|
540
|
+
const binding = {
|
|
541
|
+
model,
|
|
542
|
+
// If the kind is not specified, use the matched kind from the model
|
|
543
|
+
kind: kind3 || matchedKind,
|
|
544
|
+
event: "*" /* ANY */,
|
|
545
|
+
filters: {
|
|
546
|
+
name: "",
|
|
547
|
+
namespaces: [],
|
|
548
|
+
regexNamespaces: [],
|
|
549
|
+
regexName: "",
|
|
550
|
+
labels: {},
|
|
551
|
+
annotations: {},
|
|
552
|
+
deletionTimestamp: false
|
|
683
553
|
}
|
|
554
|
+
};
|
|
555
|
+
const bindings = this.#bindings;
|
|
556
|
+
const prefix = `${this.#name}: ${model.name}`;
|
|
557
|
+
const commonChain = { WithLabel, WithAnnotation, WithDeletionTimestamp, Mutate, Validate, Watch, Reconcile, Alias };
|
|
558
|
+
const isNotEmpty = (value) => Object.keys(value).length > 0;
|
|
559
|
+
const log = (message, cbString) => {
|
|
560
|
+
const filteredObj = (0, import_ramda2.pickBy)(isNotEmpty, binding.filters);
|
|
561
|
+
logger_default.info(`${message} configured for ${binding.event}`, prefix);
|
|
562
|
+
logger_default.info(filteredObj, prefix);
|
|
563
|
+
logger_default.debug(cbString, prefix);
|
|
564
|
+
};
|
|
565
|
+
function Validate(validateCallback) {
|
|
566
|
+
if (registerAdmission) {
|
|
567
|
+
log("Validate Action", validateCallback.toString());
|
|
568
|
+
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
569
|
+
bindings.push({
|
|
570
|
+
...binding,
|
|
571
|
+
isValidate: true,
|
|
572
|
+
validateCallback: async (req, logger = aliasLogger) => {
|
|
573
|
+
logger_default.info(`Executing validate action with alias: ${binding.alias || "no alias provided"}`);
|
|
574
|
+
return await validateCallback(req, logger);
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
return { Watch, Reconcile };
|
|
684
579
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
OnError2["IGNORE"] = "ignore";
|
|
700
|
-
OnError2["REJECT"] = "reject";
|
|
701
|
-
return OnError2;
|
|
702
|
-
})(OnError || {});
|
|
703
|
-
|
|
704
|
-
// src/lib/assets/webhooks.ts
|
|
705
|
-
var import_ramda3 = require("ramda");
|
|
706
|
-
function resolveIgnoreNamespaces(ignoredNSConfig = []) {
|
|
707
|
-
const ignoredNSEnv = process.env.PEPR_ADDITIONAL_IGNORED_NAMESPACES;
|
|
708
|
-
if (!ignoredNSEnv) {
|
|
709
|
-
return ignoredNSConfig;
|
|
710
|
-
}
|
|
711
|
-
const namespaces = ignoredNSEnv.split(",").map((ns) => ns.trim());
|
|
712
|
-
if (ignoredNSConfig) {
|
|
713
|
-
namespaces.push(...ignoredNSConfig);
|
|
714
|
-
}
|
|
715
|
-
return namespaces.filter((ns) => ns.length > 0);
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
// src/lib/processors/mutate-processor.ts
|
|
719
|
-
function updateStatus(config, name2, wrapped, status) {
|
|
720
|
-
if (wrapped.Request.operation === "DELETE") {
|
|
721
|
-
return wrapped;
|
|
722
|
-
}
|
|
723
|
-
wrapped.SetAnnotation(`${config.uuid}.pepr.dev/${name2}`, status);
|
|
724
|
-
return wrapped;
|
|
725
|
-
}
|
|
726
|
-
function logMutateErrorMessage(e) {
|
|
727
|
-
try {
|
|
728
|
-
if (e.message && e.message !== "[object Object]") {
|
|
729
|
-
return e.message;
|
|
730
|
-
} else {
|
|
731
|
-
throw new Error("An error occurred in the mutate action.");
|
|
580
|
+
function Mutate(mutateCallback) {
|
|
581
|
+
if (registerAdmission) {
|
|
582
|
+
log("Mutate Action", mutateCallback.toString());
|
|
583
|
+
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
584
|
+
bindings.push({
|
|
585
|
+
...binding,
|
|
586
|
+
isMutate: true,
|
|
587
|
+
mutateCallback: async (req, logger = aliasLogger) => {
|
|
588
|
+
logger_default.info(`Executing mutation action with alias: ${binding.alias || "no alias provided"}`);
|
|
589
|
+
await mutateCallback(req, logger);
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return { Watch, Validate, Reconcile };
|
|
732
594
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
const isSecret = wrapped.Request.kind.version === "v1" && wrapped.Request.kind.kind === "Secret";
|
|
748
|
-
if (isSecret) {
|
|
749
|
-
convertToBase64Map(transformed, skipped);
|
|
750
|
-
}
|
|
751
|
-
return transformed;
|
|
752
|
-
}
|
|
753
|
-
async function processRequest(bindable, wrapped, response) {
|
|
754
|
-
const { binding, actMeta, name: name2, config } = bindable;
|
|
755
|
-
const label = binding.mutateCallback.name;
|
|
756
|
-
logger_default.info(actMeta, `Processing mutation action (${label})`);
|
|
757
|
-
wrapped = updateStatus(config, name2, wrapped, "started");
|
|
758
|
-
try {
|
|
759
|
-
await binding.mutateCallback(wrapped);
|
|
760
|
-
logger_default.info(actMeta, `Mutation action succeeded (${label})`);
|
|
761
|
-
wrapped = updateStatus(config, name2, wrapped, "succeeded");
|
|
762
|
-
} catch (e) {
|
|
763
|
-
wrapped = updateStatus(config, name2, wrapped, "warning");
|
|
764
|
-
response.warnings = response.warnings || [];
|
|
765
|
-
const errorMessage = logMutateErrorMessage(e);
|
|
766
|
-
logger_default.error(actMeta, `Action failed: ${errorMessage}`);
|
|
767
|
-
response.warnings.push(`Action failed: ${errorMessage}`);
|
|
768
|
-
switch (config.onError) {
|
|
769
|
-
case "reject" /* REJECT */:
|
|
770
|
-
response.result = "Pepr module configured to reject on error";
|
|
771
|
-
break;
|
|
772
|
-
case "audit" /* AUDIT */:
|
|
773
|
-
response.auditAnnotations = response.auditAnnotations || {};
|
|
774
|
-
response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;
|
|
775
|
-
break;
|
|
595
|
+
function Watch(watchCallback) {
|
|
596
|
+
if (registerWatch) {
|
|
597
|
+
log("Watch Action", watchCallback.toString());
|
|
598
|
+
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
599
|
+
bindings.push({
|
|
600
|
+
...binding,
|
|
601
|
+
isWatch: true,
|
|
602
|
+
watchCallback: async (update, phase, logger = aliasLogger) => {
|
|
603
|
+
logger_default.info(`Executing watch action with alias: ${binding.alias || "no alias provided"}`);
|
|
604
|
+
await watchCallback(update, phase, logger);
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
return { Finalize };
|
|
776
609
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
(capa) => capa.bindings.map((bind) => ({
|
|
793
|
-
req,
|
|
794
|
-
config,
|
|
795
|
-
name: capa.name,
|
|
796
|
-
namespaces: capa.namespaces,
|
|
797
|
-
binding: bind,
|
|
798
|
-
actMeta: { ...reqMetadata, name: capa.name }
|
|
799
|
-
}))
|
|
800
|
-
);
|
|
801
|
-
bindables = bindables.filter((bind) => {
|
|
802
|
-
if (!bind.binding.mutateCallback) {
|
|
803
|
-
return false;
|
|
610
|
+
function Reconcile(reconcileCallback) {
|
|
611
|
+
if (registerWatch) {
|
|
612
|
+
log("Reconcile Action", reconcileCallback.toString());
|
|
613
|
+
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
614
|
+
bindings.push({
|
|
615
|
+
...binding,
|
|
616
|
+
isWatch: true,
|
|
617
|
+
isQueue: true,
|
|
618
|
+
watchCallback: async (update, phase, logger = aliasLogger) => {
|
|
619
|
+
logger_default.info(`Executing reconcile action with alias: ${binding.alias || "no alias provided"}`);
|
|
620
|
+
await reconcileCallback(update, phase, logger);
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
return { Finalize };
|
|
804
625
|
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
626
|
+
function Finalize(finalizeCallback) {
|
|
627
|
+
log("Finalize Action", finalizeCallback.toString());
|
|
628
|
+
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
629
|
+
if (registerAdmission) {
|
|
630
|
+
const mutateBinding = {
|
|
631
|
+
...binding,
|
|
632
|
+
isMutate: true,
|
|
633
|
+
isFinalize: true,
|
|
634
|
+
event: "*" /* ANY */,
|
|
635
|
+
mutateCallback: addFinalizer
|
|
636
|
+
};
|
|
637
|
+
bindings.push(mutateBinding);
|
|
638
|
+
}
|
|
639
|
+
if (registerWatch) {
|
|
640
|
+
const watchBinding = {
|
|
641
|
+
...binding,
|
|
642
|
+
isWatch: true,
|
|
643
|
+
isFinalize: true,
|
|
644
|
+
event: "UPDATE" /* UPDATE */,
|
|
645
|
+
finalizeCallback: async (update, logger = aliasLogger) => {
|
|
646
|
+
logger_default.info(`Executing finalize action with alias: ${binding.alias || "no alias provided"}`);
|
|
647
|
+
return await finalizeCallback(update, logger);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
bindings.push(watchBinding);
|
|
651
|
+
}
|
|
814
652
|
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
653
|
+
function InNamespace(...namespaces) {
|
|
654
|
+
logger_default.debug(`Add namespaces filter ${namespaces}`, prefix);
|
|
655
|
+
binding.filters.namespaces.push(...namespaces);
|
|
656
|
+
return { ...commonChain, WithName, WithNameRegex };
|
|
657
|
+
}
|
|
658
|
+
function InNamespaceRegex(...namespaces) {
|
|
659
|
+
logger_default.debug(`Add regex namespaces filter ${namespaces}`, prefix);
|
|
660
|
+
binding.filters.regexNamespaces.push(...namespaces.map((regex) => regex.source));
|
|
661
|
+
return { ...commonChain, WithName, WithNameRegex };
|
|
662
|
+
}
|
|
663
|
+
function WithDeletionTimestamp() {
|
|
664
|
+
logger_default.debug("Add deletionTimestamp filter");
|
|
665
|
+
binding.filters.deletionTimestamp = true;
|
|
666
|
+
return commonChain;
|
|
667
|
+
}
|
|
668
|
+
function WithNameRegex(regexName) {
|
|
669
|
+
logger_default.debug(`Add regex name filter ${regexName}`, prefix);
|
|
670
|
+
binding.filters.regexName = regexName.source;
|
|
671
|
+
return commonChain;
|
|
672
|
+
}
|
|
673
|
+
function WithName(name2) {
|
|
674
|
+
logger_default.debug(`Add name filter ${name2}`, prefix);
|
|
675
|
+
binding.filters.name = name2;
|
|
676
|
+
return commonChain;
|
|
677
|
+
}
|
|
678
|
+
function WithLabel(key, value = "") {
|
|
679
|
+
logger_default.debug(`Add label filter ${key}=${value}`, prefix);
|
|
680
|
+
binding.filters.labels[key] = value;
|
|
681
|
+
return commonChain;
|
|
682
|
+
}
|
|
683
|
+
function WithAnnotation(key, value = "") {
|
|
684
|
+
logger_default.debug(`Add annotation filter ${key}=${value}`, prefix);
|
|
685
|
+
binding.filters.annotations[key] = value;
|
|
686
|
+
return commonChain;
|
|
687
|
+
}
|
|
688
|
+
function Alias(alias) {
|
|
689
|
+
logger_default.debug(`Adding prefix alias ${alias}`, prefix);
|
|
690
|
+
binding.alias = alias;
|
|
691
|
+
return commonChain;
|
|
692
|
+
}
|
|
693
|
+
function bindEvent(event) {
|
|
694
|
+
binding.event = event;
|
|
695
|
+
return {
|
|
696
|
+
...commonChain,
|
|
697
|
+
InNamespace,
|
|
698
|
+
InNamespaceRegex,
|
|
699
|
+
WithName,
|
|
700
|
+
WithNameRegex,
|
|
701
|
+
WithDeletionTimestamp,
|
|
702
|
+
Alias
|
|
703
|
+
};
|
|
821
704
|
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
}
|
|
831
|
-
const transformed = reencodeData(wrapped, decoded.skipped);
|
|
832
|
-
const patches = import_fast_json_patch.default.compare(req.object, transformed);
|
|
833
|
-
updateResponsePatchAndWarnings(patches, response);
|
|
834
|
-
logger_default.debug({ ...reqMetadata, patches }, `Patches generated`);
|
|
835
|
-
webhookTimer.stop();
|
|
836
|
-
return response;
|
|
837
|
-
}
|
|
838
|
-
function updateResponsePatchAndWarnings(patches, response) {
|
|
839
|
-
if (patches.length > 0) {
|
|
840
|
-
response.patchType = "JSONPatch";
|
|
841
|
-
response.patch = base64Encode(JSON.stringify(patches));
|
|
842
|
-
}
|
|
843
|
-
if (response.warnings && response.warnings.length < 1) {
|
|
844
|
-
delete response.warnings;
|
|
845
|
-
}
|
|
846
|
-
}
|
|
705
|
+
return {
|
|
706
|
+
IsCreatedOrUpdated: () => bindEvent("CREATEORUPDATE" /* CREATE_OR_UPDATE */),
|
|
707
|
+
IsCreated: () => bindEvent("CREATE" /* CREATE */),
|
|
708
|
+
IsUpdated: () => bindEvent("UPDATE" /* UPDATE */),
|
|
709
|
+
IsDeleted: () => bindEvent("DELETE" /* DELETE */)
|
|
710
|
+
};
|
|
711
|
+
};
|
|
712
|
+
};
|
|
847
713
|
|
|
848
|
-
// src/lib/
|
|
849
|
-
var
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
714
|
+
// src/lib/core/module.ts
|
|
715
|
+
var import_ramda9 = require("ramda");
|
|
716
|
+
|
|
717
|
+
// src/lib/controller/index.ts
|
|
718
|
+
var import_express = __toESM(require("express"));
|
|
719
|
+
var import_fs = __toESM(require("fs"));
|
|
720
|
+
var import_https = __toESM(require("https"));
|
|
721
|
+
|
|
722
|
+
// src/lib/telemetry/metrics.ts
|
|
723
|
+
var import_perf_hooks = require("perf_hooks");
|
|
724
|
+
var import_prom_client = __toESM(require("prom-client"));
|
|
725
|
+
var loggingPrefix = "MetricsCollector";
|
|
726
|
+
var MetricsCollector = class {
|
|
727
|
+
#registry;
|
|
728
|
+
#counters = /* @__PURE__ */ new Map();
|
|
729
|
+
#gauges = /* @__PURE__ */ new Map();
|
|
730
|
+
#summaries = /* @__PURE__ */ new Map();
|
|
731
|
+
#prefix;
|
|
732
|
+
#cacheMissWindows = /* @__PURE__ */ new Map();
|
|
733
|
+
#metricNames = {
|
|
734
|
+
errors: "errors",
|
|
735
|
+
alerts: "alerts",
|
|
736
|
+
mutate: "mutate",
|
|
737
|
+
validate: "validate",
|
|
738
|
+
cacheMiss: "cache_miss",
|
|
739
|
+
resyncFailureCount: "resync_failure_count"
|
|
740
|
+
};
|
|
853
741
|
/**
|
|
854
|
-
*
|
|
855
|
-
* @
|
|
742
|
+
* Creates a MetricsCollector instance with prefixed metrics.
|
|
743
|
+
* @param [prefix='pepr'] - The prefix for the metric names.
|
|
856
744
|
*/
|
|
857
|
-
|
|
858
|
-
|
|
745
|
+
constructor(prefix = "pepr") {
|
|
746
|
+
this.#registry = new import_prom_client.Registry();
|
|
747
|
+
this.#prefix = prefix;
|
|
748
|
+
this.addCounter(this.#metricNames.errors, "Mutation/Validate errors encountered");
|
|
749
|
+
this.addCounter(this.#metricNames.alerts, "Mutation/Validate bad api token received");
|
|
750
|
+
this.addSummary(this.#metricNames.mutate, "Mutation operation summary");
|
|
751
|
+
this.addSummary(this.#metricNames.validate, "Validation operation summary");
|
|
752
|
+
this.addGauge(this.#metricNames.cacheMiss, "Number of cache misses per window", ["window"]);
|
|
753
|
+
this.addGauge(this.#metricNames.resyncFailureCount, "Number of failures per resync operation", ["count"]);
|
|
859
754
|
}
|
|
755
|
+
#getMetricName = (name2) => `${this.#prefix}_${name2}`;
|
|
756
|
+
#addMetric = (collection, MetricType, { name: name2, help, labelNames }) => {
|
|
757
|
+
if (collection.has(this.#getMetricName(name2))) {
|
|
758
|
+
logger_default.debug(`Metric for ${name2} already exists`, loggingPrefix);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
const metric = new MetricType({
|
|
762
|
+
name: this.#getMetricName(name2),
|
|
763
|
+
help,
|
|
764
|
+
registers: [this.#registry],
|
|
765
|
+
labelNames
|
|
766
|
+
});
|
|
767
|
+
collection.set(this.#getMetricName(name2), metric);
|
|
768
|
+
};
|
|
769
|
+
addCounter = (name2, help) => {
|
|
770
|
+
this.#addMetric(this.#counters, import_prom_client.default.Counter, { name: name2, help, labelNames: [] });
|
|
771
|
+
};
|
|
772
|
+
addSummary = (name2, help) => {
|
|
773
|
+
this.#addMetric(this.#summaries, import_prom_client.default.Summary, { name: name2, help, labelNames: [] });
|
|
774
|
+
};
|
|
775
|
+
addGauge = (name2, help, labelNames) => {
|
|
776
|
+
this.#addMetric(this.#gauges, import_prom_client.default.Gauge, { name: name2, help, labelNames });
|
|
777
|
+
};
|
|
778
|
+
incCounter = (name2) => {
|
|
779
|
+
this.#counters.get(this.#getMetricName(name2))?.inc();
|
|
780
|
+
};
|
|
781
|
+
incGauge = (name2, labels, value = 1) => {
|
|
782
|
+
this.#gauges.get(this.#getMetricName(name2))?.inc(labels || {}, value);
|
|
783
|
+
};
|
|
860
784
|
/**
|
|
861
|
-
*
|
|
862
|
-
* @returns The request object containing the Kubernetes resource.
|
|
785
|
+
* Increments the error counter.
|
|
863
786
|
*/
|
|
864
|
-
|
|
865
|
-
return this.#input;
|
|
866
|
-
}
|
|
787
|
+
error = () => this.incCounter(this.#metricNames.errors);
|
|
867
788
|
/**
|
|
868
|
-
*
|
|
869
|
-
* @param input - The request object containing the Kubernetes resource to modify.
|
|
789
|
+
* Increments the alerts counter.
|
|
870
790
|
*/
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
791
|
+
alert = () => this.incCounter(this.#metricNames.alerts);
|
|
792
|
+
/**
|
|
793
|
+
* Observes the duration since the provided start time and updates the summary.
|
|
794
|
+
* @param startTime - The start time.
|
|
795
|
+
* @param name - The metrics summary to increment.
|
|
796
|
+
*/
|
|
797
|
+
observeEnd = (startTime, name2 = this.#metricNames.mutate) => {
|
|
798
|
+
this.#summaries.get(this.#getMetricName(name2))?.observe(import_perf_hooks.performance.now() - startTime);
|
|
799
|
+
};
|
|
800
|
+
/**
|
|
801
|
+
* Fetches the current metrics from the registry.
|
|
802
|
+
* @returns The metrics.
|
|
803
|
+
*/
|
|
804
|
+
getMetrics = () => this.#registry.metrics();
|
|
805
|
+
/**
|
|
806
|
+
* Returns the current timestamp from performance.now() method. Useful for start timing an operation.
|
|
807
|
+
* @returns The timestamp.
|
|
808
|
+
*/
|
|
809
|
+
static observeStart() {
|
|
810
|
+
return import_perf_hooks.performance.now();
|
|
881
811
|
}
|
|
882
812
|
/**
|
|
883
|
-
*
|
|
884
|
-
*
|
|
885
|
-
* @param key the label key to check
|
|
886
|
-
* @returns
|
|
813
|
+
* Increments the cache miss gauge for a given label.
|
|
814
|
+
* @param label - The label for the cache miss.
|
|
887
815
|
*/
|
|
888
|
-
|
|
889
|
-
|
|
816
|
+
incCacheMiss = (window) => {
|
|
817
|
+
this.incGauge(this.#metricNames.cacheMiss, { window });
|
|
890
818
|
};
|
|
891
819
|
/**
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
* @param key the annotation key to check
|
|
895
|
-
* @returns
|
|
820
|
+
* Increments the retry count gauge.
|
|
821
|
+
* @param count - The count to increment by.
|
|
896
822
|
*/
|
|
897
|
-
|
|
898
|
-
|
|
823
|
+
incRetryCount = (count) => {
|
|
824
|
+
this.incGauge(this.#metricNames.resyncFailureCount, { count });
|
|
899
825
|
};
|
|
900
826
|
/**
|
|
901
|
-
*
|
|
902
|
-
*
|
|
903
|
-
* @returns The validation response.
|
|
827
|
+
* Initializes the cache miss gauge for a given label.
|
|
828
|
+
* @param label - The label for the cache miss.
|
|
904
829
|
*/
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
830
|
+
initCacheMissWindow = (window) => {
|
|
831
|
+
this.#rollCacheMissWindows();
|
|
832
|
+
this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.set({ window }, 0);
|
|
833
|
+
this.#cacheMissWindows.set(window, 0);
|
|
909
834
|
};
|
|
910
835
|
/**
|
|
911
|
-
*
|
|
912
|
-
*
|
|
913
|
-
* @param statusMessage Optional status message to return to the user.
|
|
914
|
-
* @param statusCode Optional status code to return to the user.
|
|
915
|
-
* @returns The validation response.
|
|
836
|
+
* Manages the size of the cache miss gauge map.
|
|
916
837
|
*/
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
838
|
+
#rollCacheMissWindows = () => {
|
|
839
|
+
const maxCacheMissWindows = process.env.PEPR_MAX_CACHE_MISS_WINDOWS ? parseInt(process.env.PEPR_MAX_CACHE_MISS_WINDOWS, 10) : void 0;
|
|
840
|
+
if (maxCacheMissWindows !== void 0 && this.#cacheMissWindows.size >= maxCacheMissWindows) {
|
|
841
|
+
const firstKey = this.#cacheMissWindows.keys().next().value;
|
|
842
|
+
if (firstKey !== void 0) {
|
|
843
|
+
this.#cacheMissWindows.delete(firstKey);
|
|
844
|
+
}
|
|
845
|
+
this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.remove({ window: firstKey });
|
|
846
|
+
}
|
|
923
847
|
};
|
|
924
848
|
};
|
|
849
|
+
var metricsCollector = new MetricsCollector("pepr");
|
|
925
850
|
|
|
926
|
-
// src/lib/processors/
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
message: callbackResp.statusMessage || `Validation failed for ${name}`
|
|
942
|
-
};
|
|
943
|
-
}
|
|
944
|
-
logger_default.info(actionMetadata, `Validation action complete (${label}): ${callbackResp.allowed ? "allowed" : "denied"}`);
|
|
945
|
-
return valResp;
|
|
946
|
-
} catch (e) {
|
|
947
|
-
logger_default.error(actionMetadata, `Action failed: ${JSON.stringify(e)}`);
|
|
948
|
-
valResp.allowed = false;
|
|
949
|
-
valResp.status = {
|
|
950
|
-
code: 500,
|
|
951
|
-
message: `Action failed with error: ${JSON.stringify(e)}`
|
|
952
|
-
};
|
|
953
|
-
return valResp;
|
|
851
|
+
// src/lib/processors/mutate-processor.ts
|
|
852
|
+
var import_fast_json_patch = __toESM(require("fast-json-patch"));
|
|
853
|
+
var import_ramda6 = require("ramda");
|
|
854
|
+
|
|
855
|
+
// src/lib/telemetry/timeUtils.ts
|
|
856
|
+
var getNow = () => performance.now();
|
|
857
|
+
|
|
858
|
+
// src/lib/telemetry/webhookTimeouts.ts
|
|
859
|
+
var MeasureWebhookTimeout = class {
|
|
860
|
+
#startTime = null;
|
|
861
|
+
#webhookType;
|
|
862
|
+
timeout = 0;
|
|
863
|
+
constructor(webhookType) {
|
|
864
|
+
this.#webhookType = webhookType;
|
|
865
|
+
metricsCollector.addCounter(`${webhookType}_timeouts`, `Number of ${webhookType} webhook timeouts`);
|
|
954
866
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
const wrapped = new PeprValidateRequest(req);
|
|
960
|
-
const response = [];
|
|
961
|
-
if (req.kind.version === "v1" && req.kind.kind === "Secret") {
|
|
962
|
-
convertFromBase64Map(wrapped.Raw);
|
|
867
|
+
start(timeout = 10) {
|
|
868
|
+
this.#startTime = getNow();
|
|
869
|
+
this.timeout = timeout;
|
|
870
|
+
logger_default.info(`Starting timer at ${this.#startTime}`);
|
|
963
871
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
req,
|
|
974
|
-
namespaces,
|
|
975
|
-
resolveIgnoreNamespaces(config?.alwaysIgnore?.namespaces)
|
|
976
|
-
);
|
|
977
|
-
if (shouldSkip !== "") {
|
|
978
|
-
logger_default.debug(shouldSkip);
|
|
979
|
-
continue;
|
|
980
|
-
}
|
|
981
|
-
const resp = await processRequest2(binding, actionMetadata, wrapped);
|
|
982
|
-
response.push(resp);
|
|
872
|
+
stop() {
|
|
873
|
+
if (this.#startTime === null) {
|
|
874
|
+
throw new Error("Timer was not started before calling stop.");
|
|
875
|
+
}
|
|
876
|
+
const elapsedTime = getNow() - this.#startTime;
|
|
877
|
+
logger_default.info(`Webhook ${this.#startTime} took ${elapsedTime}ms`);
|
|
878
|
+
this.#startTime = null;
|
|
879
|
+
if (elapsedTime > this.timeout) {
|
|
880
|
+
metricsCollector.incCounter(`${this.#webhookType}_timeouts`);
|
|
983
881
|
}
|
|
984
882
|
}
|
|
985
|
-
|
|
986
|
-
return response;
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
// src/lib/controller/store.ts
|
|
990
|
-
var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
|
|
991
|
-
var import_ramda6 = require("ramda");
|
|
883
|
+
};
|
|
992
884
|
|
|
993
|
-
// src/lib/
|
|
994
|
-
var
|
|
995
|
-
var
|
|
885
|
+
// src/lib/filter/adjudicators/adjudicators.ts
|
|
886
|
+
var import_ramda3 = require("ramda");
|
|
887
|
+
var declaredOperation = (0, import_ramda3.pipe)(
|
|
888
|
+
(request) => request?.operation,
|
|
889
|
+
(0, import_ramda3.defaultTo)("")
|
|
890
|
+
);
|
|
891
|
+
var declaredGroup = (0, import_ramda3.pipe)(
|
|
892
|
+
(request) => request?.kind?.group,
|
|
893
|
+
(0, import_ramda3.defaultTo)("")
|
|
894
|
+
);
|
|
895
|
+
var declaredVersion = (0, import_ramda3.pipe)(
|
|
896
|
+
(request) => request?.kind?.version,
|
|
897
|
+
(0, import_ramda3.defaultTo)("")
|
|
898
|
+
);
|
|
899
|
+
var declaredKind = (0, import_ramda3.pipe)(
|
|
900
|
+
(request) => request?.kind?.kind,
|
|
901
|
+
(0, import_ramda3.defaultTo)("")
|
|
902
|
+
);
|
|
903
|
+
var declaredUid = (0, import_ramda3.pipe)((request) => request?.uid, (0, import_ramda3.defaultTo)(""));
|
|
904
|
+
var carriesDeletionTimestamp = (0, import_ramda3.pipe)(
|
|
905
|
+
(kubernetesObject) => !!kubernetesObject.metadata?.deletionTimestamp,
|
|
906
|
+
(0, import_ramda3.defaultTo)(false)
|
|
907
|
+
);
|
|
908
|
+
var missingDeletionTimestamp = (0, import_ramda3.complement)(carriesDeletionTimestamp);
|
|
909
|
+
var carriedKind = (0, import_ramda3.pipe)(
|
|
910
|
+
(kubernetesObject) => kubernetesObject?.kind,
|
|
911
|
+
(0, import_ramda3.defaultTo)("not set")
|
|
912
|
+
);
|
|
913
|
+
var carriedVersion = (0, import_ramda3.pipe)(
|
|
914
|
+
(kubernetesObject) => kubernetesObject?.metadata?.resourceVersion,
|
|
915
|
+
(0, import_ramda3.defaultTo)("not set")
|
|
916
|
+
);
|
|
917
|
+
var carriedName = (0, import_ramda3.pipe)(
|
|
918
|
+
(kubernetesObject) => kubernetesObject?.metadata?.name,
|
|
919
|
+
(0, import_ramda3.defaultTo)("")
|
|
920
|
+
);
|
|
921
|
+
var carriesName = (0, import_ramda3.pipe)(carriedName, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
922
|
+
var missingName = (0, import_ramda3.complement)(carriesName);
|
|
923
|
+
var carriedNamespace = (0, import_ramda3.pipe)(
|
|
924
|
+
(kubernetesObject) => kubernetesObject?.metadata?.namespace,
|
|
925
|
+
(0, import_ramda3.defaultTo)("")
|
|
926
|
+
);
|
|
927
|
+
var carriesNamespace = (0, import_ramda3.pipe)(carriedNamespace, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
928
|
+
var carriedAnnotations = (0, import_ramda3.pipe)(
|
|
929
|
+
(kubernetesObject) => kubernetesObject?.metadata?.annotations,
|
|
930
|
+
(0, import_ramda3.defaultTo)({})
|
|
931
|
+
);
|
|
932
|
+
var carriesAnnotations = (0, import_ramda3.pipe)(carriedAnnotations, (0, import_ramda3.equals)({}), import_ramda3.not);
|
|
933
|
+
var carriedLabels = (0, import_ramda3.pipe)(
|
|
934
|
+
(kubernetesObject) => kubernetesObject?.metadata?.labels,
|
|
935
|
+
(0, import_ramda3.defaultTo)({})
|
|
936
|
+
);
|
|
937
|
+
var carriesLabels = (0, import_ramda3.pipe)(carriedLabels, (0, import_ramda3.equals)({}), import_ramda3.not);
|
|
938
|
+
var definesDeletionTimestamp = (0, import_ramda3.pipe)(
|
|
939
|
+
(binding) => binding?.filters?.deletionTimestamp ?? false,
|
|
940
|
+
(0, import_ramda3.defaultTo)(false)
|
|
941
|
+
);
|
|
942
|
+
var ignoresDeletionTimestamp = (0, import_ramda3.complement)(definesDeletionTimestamp);
|
|
943
|
+
var definedName = (0, import_ramda3.pipe)((binding) => {
|
|
944
|
+
return binding.filters.name;
|
|
945
|
+
}, (0, import_ramda3.defaultTo)(""));
|
|
946
|
+
var definesName = (0, import_ramda3.pipe)(definedName, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
947
|
+
var ignoresName = (0, import_ramda3.complement)(definesName);
|
|
948
|
+
var definedNameRegex = (0, import_ramda3.pipe)(
|
|
949
|
+
(binding) => binding.filters?.regexName,
|
|
950
|
+
(0, import_ramda3.defaultTo)("")
|
|
951
|
+
);
|
|
952
|
+
var definesNameRegex = (0, import_ramda3.pipe)(definedNameRegex, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
953
|
+
var definedNamespaces = (0, import_ramda3.pipe)((binding) => binding?.filters?.namespaces, (0, import_ramda3.defaultTo)([]));
|
|
954
|
+
var definesNamespaces = (0, import_ramda3.pipe)(definedNamespaces, (0, import_ramda3.equals)([]), import_ramda3.not);
|
|
955
|
+
var definedNamespaceRegexes = (0, import_ramda3.pipe)((binding) => binding?.filters?.regexNamespaces, (0, import_ramda3.defaultTo)([]));
|
|
956
|
+
var definesNamespaceRegexes = (0, import_ramda3.pipe)(definedNamespaceRegexes, (0, import_ramda3.equals)([]), import_ramda3.not);
|
|
957
|
+
var definedAnnotations = (0, import_ramda3.pipe)((binding) => binding?.filters?.annotations, (0, import_ramda3.defaultTo)({}));
|
|
958
|
+
var definesAnnotations = (0, import_ramda3.pipe)(definedAnnotations, (0, import_ramda3.equals)({}), import_ramda3.not);
|
|
959
|
+
var definedLabels = (0, import_ramda3.pipe)((binding) => binding?.filters?.labels, (0, import_ramda3.defaultTo)({}));
|
|
960
|
+
var definesLabels = (0, import_ramda3.pipe)(definedLabels, (0, import_ramda3.equals)({}), import_ramda3.not);
|
|
961
|
+
var definedEvent = (binding) => {
|
|
962
|
+
return binding.event;
|
|
996
963
|
};
|
|
997
|
-
var
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
964
|
+
var definesDelete = (0, import_ramda3.pipe)(definedEvent, (0, import_ramda3.equals)("DELETE" /* DELETE */));
|
|
965
|
+
var definedGroup = (0, import_ramda3.pipe)((binding) => binding?.kind?.group, (0, import_ramda3.defaultTo)(""));
|
|
966
|
+
var definesGroup = (0, import_ramda3.pipe)(definedGroup, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
967
|
+
var definedVersion = (0, import_ramda3.pipe)(
|
|
968
|
+
(binding) => binding?.kind?.version,
|
|
969
|
+
(0, import_ramda3.defaultTo)("")
|
|
970
|
+
);
|
|
971
|
+
var definesVersion = (0, import_ramda3.pipe)(definedVersion, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
972
|
+
var definedKind = (0, import_ramda3.pipe)((binding) => binding?.kind?.kind, (0, import_ramda3.defaultTo)(""));
|
|
973
|
+
var definesKind = (0, import_ramda3.pipe)(definedKind, (0, import_ramda3.equals)(""), import_ramda3.not);
|
|
974
|
+
var definedCallback = (binding) => {
|
|
975
|
+
return binding.isFinalize ? binding.finalizeCallback : binding.isWatch ? binding.watchCallback : binding.isMutate ? binding.mutateCallback : binding.isValidate ? binding.validateCallback : null;
|
|
1001
976
|
};
|
|
1002
|
-
(0,
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
var
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
977
|
+
var definedCallbackName = (0, import_ramda3.pipe)(definedCallback, (0, import_ramda3.defaultTo)({ name: "" }), (callback) => callback.name);
|
|
978
|
+
var mismatchedDeletionTimestamp = (0, import_ramda3.allPass)([
|
|
979
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesDeletionTimestamp),
|
|
980
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(1), missingDeletionTimestamp)
|
|
981
|
+
]);
|
|
982
|
+
var mismatchedName = (0, import_ramda3.allPass)([
|
|
983
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesName),
|
|
984
|
+
(0, import_ramda3.pipe)((binding, kubernetesObject) => definedName(binding) !== carriedName(kubernetesObject))
|
|
985
|
+
]);
|
|
986
|
+
var mismatchedNameRegex = (0, import_ramda3.allPass)([
|
|
987
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesNameRegex),
|
|
988
|
+
(0, import_ramda3.pipe)((binding, kubernetesObject) => new RegExp(definedNameRegex(binding)).test(carriedName(kubernetesObject)), import_ramda3.not)
|
|
989
|
+
]);
|
|
990
|
+
var bindsToKind = (0, import_ramda3.curry)(
|
|
991
|
+
(0, import_ramda3.allPass)([(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definedKind, (0, import_ramda3.equals)(""), import_ramda3.not), (0, import_ramda3.pipe)((binding, kind3) => definedKind(binding) === kind3)])
|
|
992
|
+
);
|
|
993
|
+
var bindsToNamespace = (0, import_ramda3.curry)((0, import_ramda3.pipe)(bindsToKind(import_ramda3.__, "Namespace")));
|
|
994
|
+
var misboundNamespace = (0, import_ramda3.allPass)([bindsToNamespace, definesNamespaces]);
|
|
995
|
+
var mismatchedNamespace = (0, import_ramda3.allPass)([
|
|
996
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesNamespaces),
|
|
997
|
+
(0, import_ramda3.pipe)((binding, kubernetesObject) => definedNamespaces(binding).includes(carriedNamespace(kubernetesObject)), import_ramda3.not)
|
|
998
|
+
]);
|
|
999
|
+
var mismatchedNamespaceRegex = (0, import_ramda3.allPass)([
|
|
1000
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesNamespaceRegexes),
|
|
1001
|
+
(0, import_ramda3.pipe)(
|
|
1002
|
+
(binding, kubernetesObject) => (0, import_ramda3.pipe)(
|
|
1003
|
+
(0, import_ramda3.any)((regEx) => new RegExp(regEx).test(carriedNamespace(kubernetesObject))),
|
|
1004
|
+
import_ramda3.not
|
|
1005
|
+
)(definedNamespaceRegexes(binding))
|
|
1006
|
+
)
|
|
1007
|
+
]);
|
|
1008
|
+
var metasMismatch = (0, import_ramda3.pipe)(
|
|
1009
|
+
(defined, carried) => {
|
|
1010
|
+
const result = { defined, carried, unalike: {} };
|
|
1011
|
+
result.unalike = Object.entries(result.defined).map(([key, value]) => {
|
|
1012
|
+
const keyMissing = !Object.hasOwn(result.carried, key);
|
|
1013
|
+
const noValue = !value;
|
|
1014
|
+
const valMissing = !result.carried[key];
|
|
1015
|
+
const valDiffers = result.carried[key] !== result.defined[key];
|
|
1016
|
+
return keyMissing ? { [key]: value } : noValue ? {} : valMissing ? { [key]: value } : valDiffers ? { [key]: value } : {};
|
|
1017
|
+
}).reduce((acc, cur) => ({ ...acc, ...cur }), {});
|
|
1018
|
+
return result.unalike;
|
|
1019
|
+
},
|
|
1020
|
+
(unalike) => Object.keys(unalike).length > 0
|
|
1021
|
+
);
|
|
1022
|
+
var mismatchedAnnotations = (0, import_ramda3.allPass)([
|
|
1023
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesAnnotations),
|
|
1024
|
+
(0, import_ramda3.pipe)((binding, kubernetesObject) => metasMismatch(definedAnnotations(binding), carriedAnnotations(kubernetesObject)))
|
|
1025
|
+
]);
|
|
1026
|
+
var mismatchedLabels = (0, import_ramda3.allPass)([
|
|
1027
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesLabels),
|
|
1028
|
+
(0, import_ramda3.pipe)((binding, kubernetesObject) => metasMismatch(definedLabels(binding), carriedLabels(kubernetesObject)))
|
|
1029
|
+
]);
|
|
1030
|
+
var uncarryableNamespace = (0, import_ramda3.allPass)([
|
|
1031
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), import_ramda3.length, (0, import_ramda3.gt)(import_ramda3.__, 0)),
|
|
1032
|
+
(0, import_ramda3.pipe)((namespaceSelector, kubernetesObject) => {
|
|
1033
|
+
if (kubernetesObject?.kind === "Namespace") {
|
|
1034
|
+
return namespaceSelector.includes(kubernetesObject?.metadata?.name);
|
|
1014
1035
|
}
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1036
|
+
if (carriesNamespace(kubernetesObject)) {
|
|
1037
|
+
return namespaceSelector.includes(carriedNamespace(kubernetesObject));
|
|
1038
|
+
}
|
|
1039
|
+
return true;
|
|
1040
|
+
}, import_ramda3.not)
|
|
1041
|
+
]);
|
|
1042
|
+
var missingCarriableNamespace = (0, import_ramda3.allPass)([
|
|
1043
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), import_ramda3.length, (0, import_ramda3.gt)(import_ramda3.__, 0)),
|
|
1044
|
+
(0, import_ramda3.pipe)(
|
|
1045
|
+
(namespaceSelector, kubernetesObject) => kubernetesObject.kind === "Namespace" ? !namespaceSelector.includes(kubernetesObject.metadata.name) : !carriesNamespace(kubernetesObject)
|
|
1046
|
+
)
|
|
1047
|
+
]);
|
|
1048
|
+
var carriesIgnoredNamespace = (0, import_ramda3.allPass)([
|
|
1049
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), import_ramda3.length, (0, import_ramda3.gt)(import_ramda3.__, 0)),
|
|
1050
|
+
(0, import_ramda3.pipe)((namespaceSelector, kubernetesObject) => {
|
|
1051
|
+
if (kubernetesObject?.kind === "Namespace") {
|
|
1052
|
+
return namespaceSelector.includes(kubernetesObject?.metadata?.name);
|
|
1053
|
+
}
|
|
1054
|
+
if (carriesNamespace(kubernetesObject)) {
|
|
1055
|
+
return namespaceSelector.includes(carriedNamespace(kubernetesObject));
|
|
1056
|
+
}
|
|
1057
|
+
return false;
|
|
1058
|
+
})
|
|
1059
|
+
]);
|
|
1060
|
+
var unbindableNamespaces = (0, import_ramda3.allPass)([
|
|
1061
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), import_ramda3.length, (0, import_ramda3.gt)(import_ramda3.__, 0)),
|
|
1062
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(1), definesNamespaces),
|
|
1063
|
+
(0, import_ramda3.pipe)(
|
|
1064
|
+
(namespaceSelector, binding) => (0, import_ramda3.difference)(definedNamespaces(binding), namespaceSelector),
|
|
1065
|
+
import_ramda3.length,
|
|
1066
|
+
(0, import_ramda3.equals)(0),
|
|
1067
|
+
import_ramda3.not
|
|
1068
|
+
)
|
|
1069
|
+
]);
|
|
1070
|
+
var misboundDeleteWithDeletionTimestamp = (0, import_ramda3.allPass)([definesDelete, definesDeletionTimestamp]);
|
|
1071
|
+
var operationMatchesEvent = (0, import_ramda3.anyPass)([
|
|
1072
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(1), (0, import_ramda3.equals)("*" /* ANY */)),
|
|
1073
|
+
(0, import_ramda3.pipe)((operation, event) => operation.valueOf() === event.valueOf()),
|
|
1074
|
+
(0, import_ramda3.pipe)((operation, event) => operation ? event.includes(operation) : false)
|
|
1075
|
+
]);
|
|
1076
|
+
var mismatchedEvent = (0, import_ramda3.pipe)(
|
|
1077
|
+
(binding, request) => operationMatchesEvent(declaredOperation(request), definedEvent(binding)),
|
|
1078
|
+
import_ramda3.not
|
|
1079
|
+
);
|
|
1080
|
+
var mismatchedGroup = (0, import_ramda3.allPass)([
|
|
1081
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesGroup),
|
|
1082
|
+
(0, import_ramda3.pipe)((binding, request) => definedGroup(binding) !== declaredGroup(request))
|
|
1083
|
+
]);
|
|
1084
|
+
var mismatchedVersion = (0, import_ramda3.allPass)([
|
|
1085
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesVersion),
|
|
1086
|
+
(0, import_ramda3.pipe)((binding, request) => definedVersion(binding) !== declaredVersion(request))
|
|
1087
|
+
]);
|
|
1088
|
+
var mismatchedKind = (0, import_ramda3.allPass)([
|
|
1089
|
+
(0, import_ramda3.pipe)((0, import_ramda3.nthArg)(0), definesKind),
|
|
1090
|
+
(0, import_ramda3.pipe)((binding, request) => definedKind(binding) !== declaredKind(request))
|
|
1091
|
+
]);
|
|
1092
|
+
|
|
1093
|
+
// src/lib/filter/filter.ts
|
|
1094
|
+
function shouldSkipRequest(binding, req, capabilityNamespaces, ignoredNamespaces) {
|
|
1095
|
+
const obj = req.operation === "DELETE" /* DELETE */ ? req.oldObject : req.object;
|
|
1096
|
+
const prefix = "Ignoring Admission Callback:";
|
|
1097
|
+
const adjudicators = [
|
|
1098
|
+
() => adjudicateMisboundDeleteWithDeletionTimestamp(binding),
|
|
1099
|
+
() => adjudicateMismatchedDeletionTimestamp(binding, obj),
|
|
1100
|
+
() => adjudicateMismatchedEvent(binding, req),
|
|
1101
|
+
() => adjudicateMismatchedName(binding, obj),
|
|
1102
|
+
() => adjudicateMismatchedGroup(binding, req),
|
|
1103
|
+
() => adjudicateMismatchedVersion(binding, req),
|
|
1104
|
+
() => adjudicateMismatchedKind(binding, req),
|
|
1105
|
+
() => adjudicateUnbindableNamespaces(capabilityNamespaces, binding),
|
|
1106
|
+
() => adjudicateUncarryableNamespace(capabilityNamespaces, obj),
|
|
1107
|
+
() => adjudicateMismatchedNamespace(binding, obj),
|
|
1108
|
+
() => adjudicateMismatchedLabels(binding, obj),
|
|
1109
|
+
() => adjudicateMismatchedAnnotations(binding, obj),
|
|
1110
|
+
() => adjudicateMismatchedNamespaceRegex(binding, obj),
|
|
1111
|
+
() => adjudicateMismatchedNameRegex(binding, obj),
|
|
1112
|
+
() => adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj),
|
|
1113
|
+
() => adjudicateMissingCarriableNamespace(capabilityNamespaces, obj)
|
|
1114
|
+
];
|
|
1115
|
+
for (const adjudicator of adjudicators) {
|
|
1116
|
+
const result = adjudicator();
|
|
1117
|
+
if (result) {
|
|
1118
|
+
return `${prefix} ${result}`;
|
|
1023
1119
|
}
|
|
1024
1120
|
}
|
|
1025
|
-
return
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
const
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1121
|
+
return "";
|
|
1122
|
+
}
|
|
1123
|
+
function filterNoMatchReason(binding, obj, capabilityNamespaces, ignoredNamespaces) {
|
|
1124
|
+
const prefix = "Ignoring Watch Callback:";
|
|
1125
|
+
const adjudicators = [
|
|
1126
|
+
() => adjudicateMismatchedDeletionTimestamp(binding, obj),
|
|
1127
|
+
() => adjudicateMismatchedName(binding, obj),
|
|
1128
|
+
() => adjudicateMisboundNamespace(binding),
|
|
1129
|
+
() => adjudicateMismatchedLabels(binding, obj),
|
|
1130
|
+
() => adjudicateMismatchedAnnotations(binding, obj),
|
|
1131
|
+
() => adjudicateUncarryableNamespace(capabilityNamespaces, obj),
|
|
1132
|
+
() => adjudicateUnbindableNamespaces(capabilityNamespaces, binding),
|
|
1133
|
+
() => adjudicateMismatchedNamespace(binding, obj),
|
|
1134
|
+
() => adjudicateMismatchedNamespaceRegex(binding, obj),
|
|
1135
|
+
() => adjudicateMismatchedNameRegex(binding, obj),
|
|
1136
|
+
() => adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj),
|
|
1137
|
+
() => adjudicateMissingCarriableNamespace(capabilityNamespaces, obj)
|
|
1138
|
+
];
|
|
1139
|
+
for (const adjudicator of adjudicators) {
|
|
1140
|
+
const result = adjudicator();
|
|
1141
|
+
if (result) {
|
|
1142
|
+
return `${prefix} ${result}`;
|
|
1036
1143
|
}
|
|
1037
|
-
const cacheIndex = [op, path].join(":");
|
|
1038
|
-
cache[cacheIndex] = { op, path };
|
|
1039
|
-
} else {
|
|
1040
|
-
throw new Error(`Unsupported operation: ${op}`);
|
|
1041
1144
|
}
|
|
1042
|
-
return
|
|
1043
|
-
}
|
|
1044
|
-
function
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1145
|
+
return "";
|
|
1146
|
+
}
|
|
1147
|
+
function adjudicateMisboundNamespace(binding) {
|
|
1148
|
+
return misboundNamespace(binding) ? "Cannot use namespace filter on a namespace object." : null;
|
|
1149
|
+
}
|
|
1150
|
+
function adjudicateMisboundDeleteWithDeletionTimestamp(binding) {
|
|
1151
|
+
return misboundDeleteWithDeletionTimestamp(binding) ? "Cannot use deletionTimestamp filter on a DELETE operation." : null;
|
|
1152
|
+
}
|
|
1153
|
+
function adjudicateMismatchedDeletionTimestamp(binding, obj) {
|
|
1154
|
+
return mismatchedDeletionTimestamp(binding, obj) ? "Binding defines deletionTimestamp but Object does not carry it." : null;
|
|
1155
|
+
}
|
|
1156
|
+
function adjudicateMismatchedEvent(binding, req) {
|
|
1157
|
+
return mismatchedEvent(binding, req) ? `Binding defines event '${definedEvent(binding)}' but Request declares '${declaredOperation(req)}'.` : null;
|
|
1158
|
+
}
|
|
1159
|
+
function adjudicateMismatchedName(binding, obj) {
|
|
1160
|
+
return mismatchedName(binding, obj) ? `Binding defines name '${definedName(binding)}' but Object carries '${carriedName(obj)}'.` : null;
|
|
1161
|
+
}
|
|
1162
|
+
function adjudicateMismatchedGroup(binding, req) {
|
|
1163
|
+
return mismatchedGroup(binding, req) ? `Binding defines group '${definedGroup(binding)}' but Request declares '${declaredGroup(req)}'.` : null;
|
|
1164
|
+
}
|
|
1165
|
+
function adjudicateMismatchedVersion(binding, req) {
|
|
1166
|
+
return mismatchedVersion(binding, req) ? `Binding defines version '${definedVersion(binding)}' but Request declares '${declaredVersion(req)}'.` : null;
|
|
1167
|
+
}
|
|
1168
|
+
function adjudicateMismatchedKind(binding, req) {
|
|
1169
|
+
return mismatchedKind(binding, req) ? `Binding defines kind '${definedKind(binding)}' but Request declares '${declaredKind(req)}'.` : null;
|
|
1170
|
+
}
|
|
1171
|
+
function adjudicateUnbindableNamespaces(capabilityNamespaces, binding) {
|
|
1172
|
+
return unbindableNamespaces(capabilityNamespaces, binding) ? `Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
1173
|
+
}
|
|
1174
|
+
function adjudicateUncarryableNamespace(capabilityNamespaces, obj) {
|
|
1175
|
+
return uncarryableNamespace(capabilityNamespaces, obj) ? `Object carries namespace '${obj.kind && obj.kind === "Namespace" ? obj.metadata?.name : carriedNamespace(obj)}' but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
1176
|
+
}
|
|
1177
|
+
function adjudicateMismatchedNamespace(binding, obj) {
|
|
1178
|
+
return mismatchedNamespace(binding, obj) ? `Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' but Object carries '${carriedNamespace(obj)}'.` : null;
|
|
1179
|
+
}
|
|
1180
|
+
function adjudicateMismatchedLabels(binding, obj) {
|
|
1181
|
+
return mismatchedLabels(binding, obj) ? `Binding defines labels '${JSON.stringify(definedLabels(binding))}' but Object carries '${JSON.stringify(carriedLabels(obj))}'.` : null;
|
|
1182
|
+
}
|
|
1183
|
+
function adjudicateMismatchedAnnotations(binding, obj) {
|
|
1184
|
+
return mismatchedAnnotations(binding, obj) ? `Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' but Object carries '${JSON.stringify(carriedAnnotations(obj))}'.` : null;
|
|
1185
|
+
}
|
|
1186
|
+
function adjudicateMismatchedNamespaceRegex(binding, obj) {
|
|
1187
|
+
return mismatchedNamespaceRegex(binding, obj) ? `Binding defines namespace regexes '${JSON.stringify(definedNamespaceRegexes(binding))}' but Object carries '${carriedNamespace(obj)}'.` : null;
|
|
1188
|
+
}
|
|
1189
|
+
function adjudicateMismatchedNameRegex(binding, obj) {
|
|
1190
|
+
return mismatchedNameRegex(binding, obj) ? `Binding defines name regex '${definedNameRegex(binding)}' but Object carries '${carriedName(obj)}'.` : null;
|
|
1191
|
+
}
|
|
1192
|
+
function adjudicateCarriesIgnoredNamespace(ignoredNamespaces, obj) {
|
|
1193
|
+
return carriesIgnoredNamespace(ignoredNamespaces, obj) ? `Object carries namespace '${obj.kind && obj.kind === "Namespace" ? obj.metadata?.name : carriedNamespace(obj)}' but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.` : null;
|
|
1194
|
+
}
|
|
1195
|
+
function adjudicateMissingCarriableNamespace(capabilityNamespaces, obj) {
|
|
1196
|
+
return missingCarriableNamespace(capabilityNamespaces, obj) ? `Object does not carry a namespace but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.` : null;
|
|
1051
1197
|
}
|
|
1052
1198
|
|
|
1053
|
-
// src/lib/
|
|
1054
|
-
var
|
|
1055
|
-
var
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1199
|
+
// src/lib/mutate-request.ts
|
|
1200
|
+
var import_ramda4 = require("ramda");
|
|
1201
|
+
var PeprMutateRequest = class {
|
|
1202
|
+
Raw;
|
|
1203
|
+
#input;
|
|
1204
|
+
get PermitSideEffects() {
|
|
1205
|
+
return !this.#input.dryRun;
|
|
1206
|
+
}
|
|
1207
|
+
get IsDryRun() {
|
|
1208
|
+
return this.#input.dryRun;
|
|
1209
|
+
}
|
|
1210
|
+
get OldResource() {
|
|
1211
|
+
return this.#input.oldObject;
|
|
1212
|
+
}
|
|
1213
|
+
get Request() {
|
|
1214
|
+
return this.#input;
|
|
1215
|
+
}
|
|
1216
|
+
constructor(input) {
|
|
1217
|
+
this.#input = input;
|
|
1218
|
+
if (input.operation.toUpperCase() === "DELETE" /* DELETE */) {
|
|
1219
|
+
this.Raw = (0, import_ramda4.clone)(input.oldObject);
|
|
1076
1220
|
} else {
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1221
|
+
this.Raw = (0, import_ramda4.clone)(input.object);
|
|
1222
|
+
}
|
|
1223
|
+
if (!this.Raw) {
|
|
1224
|
+
throw new Error("Unable to load the request object into PeprRequest.Raw");
|
|
1080
1225
|
}
|
|
1081
|
-
setTimeout(
|
|
1082
|
-
() => (0, import_kubernetes_fluent_client3.K8s)(Store).InNamespace(namespace).Get(this.#name).then(async (store) => await this.#migrateAndSetupWatch(store)).catch(this.#createStoreResource),
|
|
1083
|
-
Math.random() * 3e3
|
|
1084
|
-
// Add a jitter to the Store creation to avoid collisions
|
|
1085
|
-
);
|
|
1086
1226
|
}
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
watcher.start().catch((e) => logger_default.error(e, "Error starting Pepr store watch"));
|
|
1227
|
+
Merge = (obj) => {
|
|
1228
|
+
this.Raw = (0, import_ramda4.mergeDeepRight)(this.Raw, obj);
|
|
1090
1229
|
};
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
value: `${Date.now()}`
|
|
1098
|
-
}
|
|
1099
|
-
]);
|
|
1100
|
-
const data = store.data || {};
|
|
1101
|
-
let storeCache = {};
|
|
1102
|
-
for (const name2 of Object.keys(this.#stores)) {
|
|
1103
|
-
const offset = `${name2}-`.length;
|
|
1104
|
-
for (const key of Object.keys(data)) {
|
|
1105
|
-
if ((0, import_ramda6.startsWith)(name2, key) && !(0, import_ramda6.startsWith)(`${name2}-v2`, key)) {
|
|
1106
|
-
storeCache = fillStoreCache(storeCache, name2, "remove", {
|
|
1107
|
-
key: [key.slice(offset)],
|
|
1108
|
-
value: data[key]
|
|
1109
|
-
});
|
|
1110
|
-
storeCache = fillStoreCache(storeCache, name2, "add", {
|
|
1111
|
-
key: [key.slice(offset)],
|
|
1112
|
-
value: data[key],
|
|
1113
|
-
version: "v2"
|
|
1114
|
-
});
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
storeCache = await sendUpdatesAndFlushCache(storeCache, namespace, this.#name);
|
|
1119
|
-
this.#setupWatch();
|
|
1230
|
+
SetLabel = (key, value) => {
|
|
1231
|
+
const ref = this.Raw;
|
|
1232
|
+
ref.metadata = ref.metadata ?? {};
|
|
1233
|
+
ref.metadata.labels = ref.metadata.labels ?? {};
|
|
1234
|
+
ref.metadata.labels[key] = value;
|
|
1235
|
+
return this;
|
|
1120
1236
|
};
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
const filtered = {};
|
|
1128
|
-
for (const key of Object.keys(data)) {
|
|
1129
|
-
if ((0, import_ramda6.startsWith)(name2, key)) {
|
|
1130
|
-
filtered[key.slice(offset)] = data[key];
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
this.#stores[name2].receive(filtered);
|
|
1134
|
-
}
|
|
1135
|
-
if (this.#onReady) {
|
|
1136
|
-
this.#onReady();
|
|
1137
|
-
this.#onReady = void 0;
|
|
1138
|
-
}
|
|
1139
|
-
};
|
|
1140
|
-
clearTimeout(this.#sendDebounce);
|
|
1141
|
-
this.#sendDebounce = setTimeout(debounced, this.#onReady ? 0 : debounceBackoffReceive);
|
|
1237
|
+
SetAnnotation = (key, value) => {
|
|
1238
|
+
const ref = this.Raw;
|
|
1239
|
+
ref.metadata = ref.metadata ?? {};
|
|
1240
|
+
ref.metadata.annotations = ref.metadata.annotations ?? {};
|
|
1241
|
+
ref.metadata.annotations[key] = value;
|
|
1242
|
+
return this;
|
|
1142
1243
|
};
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
setInterval(() => {
|
|
1149
|
-
if (Object.keys(storeCache).length > 0) {
|
|
1150
|
-
logger_default.debug(redactedPatch(storeCache), "Sending updates to Pepr store");
|
|
1151
|
-
void sendUpdatesAndFlushCache(storeCache, namespace, this.#name);
|
|
1152
|
-
}
|
|
1153
|
-
}, debounceBackoffSend);
|
|
1154
|
-
return sender;
|
|
1244
|
+
RemoveLabel = (key) => {
|
|
1245
|
+
if (this.Raw.metadata?.labels?.[key]) {
|
|
1246
|
+
delete this.Raw.metadata.labels[key];
|
|
1247
|
+
}
|
|
1248
|
+
return this;
|
|
1155
1249
|
};
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
try {
|
|
1160
|
-
await (0, import_kubernetes_fluent_client3.K8s)(Store).Apply({
|
|
1161
|
-
metadata: {
|
|
1162
|
-
name: this.#name,
|
|
1163
|
-
namespace,
|
|
1164
|
-
labels: {
|
|
1165
|
-
"pepr.dev-cacheID": `${Date.now()}`
|
|
1166
|
-
}
|
|
1167
|
-
},
|
|
1168
|
-
data: {
|
|
1169
|
-
// JSON Patch will die if the data is empty, so we need to add a placeholder
|
|
1170
|
-
__pepr_do_not_delete__: "k-thx-bye"
|
|
1171
|
-
}
|
|
1172
|
-
});
|
|
1173
|
-
this.#setupWatch();
|
|
1174
|
-
} catch (err) {
|
|
1175
|
-
logger_default.error(err, "Failed to create Pepr store");
|
|
1250
|
+
RemoveAnnotation = (key) => {
|
|
1251
|
+
if (this.Raw.metadata?.annotations?.[key]) {
|
|
1252
|
+
delete this.Raw.metadata.annotations[key];
|
|
1176
1253
|
}
|
|
1254
|
+
return this;
|
|
1255
|
+
};
|
|
1256
|
+
HasLabel = (key) => {
|
|
1257
|
+
return this.Raw.metadata?.labels?.[key] !== void 0;
|
|
1258
|
+
};
|
|
1259
|
+
HasAnnotation = (key) => {
|
|
1260
|
+
return this.Raw.metadata?.annotations?.[key] !== void 0;
|
|
1177
1261
|
};
|
|
1178
1262
|
};
|
|
1179
1263
|
|
|
1180
|
-
// src/lib/
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1264
|
+
// src/lib/utils.ts
|
|
1265
|
+
var utils_exports = {};
|
|
1266
|
+
__export(utils_exports, {
|
|
1267
|
+
base64Decode: () => base64Decode,
|
|
1268
|
+
base64Encode: () => base64Encode,
|
|
1269
|
+
convertFromBase64Map: () => convertFromBase64Map,
|
|
1270
|
+
convertToBase64Map: () => convertToBase64Map,
|
|
1271
|
+
isAscii: () => isAscii
|
|
1272
|
+
});
|
|
1273
|
+
var isAscii = /^[\s\x20-\x7E]*$/;
|
|
1274
|
+
function convertToBase64Map(obj, skip) {
|
|
1275
|
+
obj.data = obj.data ?? {};
|
|
1276
|
+
for (const key in obj.data) {
|
|
1277
|
+
const value = obj.data[key];
|
|
1278
|
+
obj.data[key] = skip.includes(key) ? value : base64Encode(value);
|
|
1279
|
+
}
|
|
1187
1280
|
}
|
|
1188
|
-
function
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1281
|
+
function convertFromBase64Map(obj) {
|
|
1282
|
+
const skip = [];
|
|
1283
|
+
obj.data = obj.data ?? {};
|
|
1284
|
+
for (const key in obj.data) {
|
|
1285
|
+
if (obj.data[key] === void 0) {
|
|
1286
|
+
obj.data[key] = "";
|
|
1287
|
+
} else {
|
|
1288
|
+
const decoded = base64Decode(obj.data[key]);
|
|
1289
|
+
if (isAscii.test(decoded)) {
|
|
1290
|
+
obj.data[key] = decoded;
|
|
1291
|
+
} else {
|
|
1292
|
+
skip.push(key);
|
|
1293
|
+
}
|
|
1200
1294
|
}
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1295
|
+
}
|
|
1296
|
+
logger_default.debug(`Non-ascii data detected in keys: ${skip}, skipping automatic base64 decoding`);
|
|
1297
|
+
return skip;
|
|
1298
|
+
}
|
|
1299
|
+
function base64Decode(data) {
|
|
1300
|
+
return Buffer.from(data, "base64").toString("utf-8");
|
|
1301
|
+
}
|
|
1302
|
+
function base64Encode(data) {
|
|
1303
|
+
return Buffer.from(data).toString("base64");
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
// src/cli/init/enums.ts
|
|
1307
|
+
var OnError = /* @__PURE__ */ ((OnError2) => {
|
|
1308
|
+
OnError2["AUDIT"] = "audit";
|
|
1309
|
+
OnError2["IGNORE"] = "ignore";
|
|
1310
|
+
OnError2["REJECT"] = "reject";
|
|
1311
|
+
return OnError2;
|
|
1312
|
+
})(OnError || {});
|
|
1313
|
+
|
|
1314
|
+
// src/lib/assets/webhooks.ts
|
|
1315
|
+
var import_ramda5 = require("ramda");
|
|
1316
|
+
function resolveIgnoreNamespaces(ignoredNSConfig = []) {
|
|
1317
|
+
const ignoredNSEnv = process.env.PEPR_ADDITIONAL_IGNORED_NAMESPACES;
|
|
1318
|
+
if (!ignoredNSEnv) {
|
|
1319
|
+
return ignoredNSConfig;
|
|
1320
|
+
}
|
|
1321
|
+
const namespaces = ignoredNSEnv.split(",").map((ns) => ns.trim());
|
|
1322
|
+
if (ignoredNSConfig) {
|
|
1323
|
+
namespaces.push(...ignoredNSConfig);
|
|
1324
|
+
}
|
|
1325
|
+
return namespaces.filter((ns) => ns.length > 0);
|
|
1207
1326
|
}
|
|
1208
1327
|
|
|
1209
|
-
// src/lib/
|
|
1210
|
-
|
|
1211
|
-
|
|
1328
|
+
// src/lib/processors/mutate-processor.ts
|
|
1329
|
+
function updateStatus(config, name2, wrapped, status) {
|
|
1330
|
+
if (wrapped.Request.operation === "DELETE") {
|
|
1331
|
+
return wrapped;
|
|
1332
|
+
}
|
|
1333
|
+
wrapped.SetAnnotation(`${config.uuid}.pepr.dev/${name2}`, status);
|
|
1334
|
+
return wrapped;
|
|
1212
1335
|
}
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
#token = "";
|
|
1220
|
-
// The express app instance
|
|
1221
|
-
#app = (0, import_express.default)();
|
|
1222
|
-
// Initialized with the constructor
|
|
1223
|
-
#config;
|
|
1224
|
-
#capabilities;
|
|
1225
|
-
#beforeHook;
|
|
1226
|
-
#afterHook;
|
|
1227
|
-
constructor(config, capabilities, beforeHook, afterHook, onReady) {
|
|
1228
|
-
this.#config = config;
|
|
1229
|
-
this.#capabilities = capabilities;
|
|
1230
|
-
new StoreController(capabilities, `pepr-${config.uuid}-store`, () => {
|
|
1231
|
-
this.#bindEndpoints();
|
|
1232
|
-
onReady && onReady();
|
|
1233
|
-
logger_default.info("\u2705 Controller startup complete");
|
|
1234
|
-
new StoreController(capabilities, `pepr-${config.uuid}-schedule`, () => {
|
|
1235
|
-
logger_default.info("\u2705 Scheduling processed");
|
|
1236
|
-
});
|
|
1237
|
-
});
|
|
1238
|
-
this.#app.use(_Controller.#logger);
|
|
1239
|
-
this.#app.use(import_express.default.json({ limit: "2mb" }));
|
|
1240
|
-
if (beforeHook) {
|
|
1241
|
-
logger_default.info(`Using beforeHook: ${beforeHook}`);
|
|
1242
|
-
this.#beforeHook = beforeHook;
|
|
1336
|
+
function logMutateErrorMessage(e) {
|
|
1337
|
+
try {
|
|
1338
|
+
if (e.message && e.message !== "[object Object]") {
|
|
1339
|
+
return e.message;
|
|
1340
|
+
} else {
|
|
1341
|
+
throw new Error("An error occurred in the mutate action.");
|
|
1243
1342
|
}
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1343
|
+
} catch {
|
|
1344
|
+
return "An error occurred with the mutate action.";
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
function decodeData(wrapped) {
|
|
1348
|
+
let skipped = [];
|
|
1349
|
+
const isSecret = wrapped.Request.kind.version === "v1" && wrapped.Request.kind.kind === "Secret";
|
|
1350
|
+
if (isSecret) {
|
|
1351
|
+
skipped = convertFromBase64Map(wrapped.Raw);
|
|
1352
|
+
}
|
|
1353
|
+
return { skipped, wrapped };
|
|
1354
|
+
}
|
|
1355
|
+
function reencodeData(wrapped, skipped) {
|
|
1356
|
+
const transformed = (0, import_ramda6.clone)(wrapped.Raw);
|
|
1357
|
+
const isSecret = wrapped.Request.kind.version === "v1" && wrapped.Request.kind.kind === "Secret";
|
|
1358
|
+
if (isSecret) {
|
|
1359
|
+
convertToBase64Map(transformed, skipped);
|
|
1360
|
+
}
|
|
1361
|
+
return transformed;
|
|
1362
|
+
}
|
|
1363
|
+
async function processRequest(bindable, wrapped, response) {
|
|
1364
|
+
const { binding, actMeta, name: name2, config } = bindable;
|
|
1365
|
+
const label = binding.mutateCallback.name;
|
|
1366
|
+
logger_default.info(actMeta, `Processing mutation action (${label})`);
|
|
1367
|
+
wrapped = updateStatus(config, name2, wrapped, "started");
|
|
1368
|
+
try {
|
|
1369
|
+
await binding.mutateCallback(wrapped);
|
|
1370
|
+
logger_default.info(actMeta, `Mutation action succeeded (${label})`);
|
|
1371
|
+
wrapped = updateStatus(config, name2, wrapped, "succeeded");
|
|
1372
|
+
} catch (e) {
|
|
1373
|
+
wrapped = updateStatus(config, name2, wrapped, "warning");
|
|
1374
|
+
response.warnings = response.warnings || [];
|
|
1375
|
+
const errorMessage = logMutateErrorMessage(e);
|
|
1376
|
+
logger_default.error(actMeta, `Action failed: ${errorMessage}`);
|
|
1377
|
+
response.warnings.push(`Action failed: ${errorMessage}`);
|
|
1378
|
+
switch (config.onError) {
|
|
1379
|
+
case "reject" /* REJECT */:
|
|
1380
|
+
response.result = "Pepr module configured to reject on error";
|
|
1381
|
+
break;
|
|
1382
|
+
case "audit" /* AUDIT */:
|
|
1383
|
+
response.auditAnnotations = response.auditAnnotations || {};
|
|
1384
|
+
response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;
|
|
1385
|
+
break;
|
|
1247
1386
|
}
|
|
1248
1387
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1388
|
+
return { wrapped, response };
|
|
1389
|
+
}
|
|
1390
|
+
async function mutateProcessor(config, capabilities, req, reqMetadata) {
|
|
1391
|
+
const webhookTimer = new MeasureWebhookTimeout("mutate" /* MUTATE */);
|
|
1392
|
+
webhookTimer.start(config.webhookTimeout);
|
|
1393
|
+
let response = {
|
|
1394
|
+
uid: req.uid,
|
|
1395
|
+
warnings: [],
|
|
1396
|
+
allowed: false
|
|
1397
|
+
};
|
|
1398
|
+
const decoded = decodeData(new PeprMutateRequest(req));
|
|
1399
|
+
let wrapped = decoded.wrapped;
|
|
1400
|
+
logger_default.info(reqMetadata, `Processing request`);
|
|
1401
|
+
let bindables = capabilities.flatMap(
|
|
1402
|
+
(capa) => capa.bindings.map((bind) => ({
|
|
1403
|
+
req,
|
|
1404
|
+
config,
|
|
1405
|
+
name: capa.name,
|
|
1406
|
+
namespaces: capa.namespaces,
|
|
1407
|
+
binding: bind,
|
|
1408
|
+
actMeta: { ...reqMetadata, name: capa.name }
|
|
1409
|
+
}))
|
|
1410
|
+
);
|
|
1411
|
+
bindables = bindables.filter((bind) => {
|
|
1412
|
+
if (!bind.binding.mutateCallback) {
|
|
1413
|
+
return false;
|
|
1253
1414
|
}
|
|
1254
|
-
const
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
}
|
|
1415
|
+
const shouldSkip = shouldSkipRequest(
|
|
1416
|
+
bind.binding,
|
|
1417
|
+
bind.req,
|
|
1418
|
+
bind.namespaces,
|
|
1419
|
+
resolveIgnoreNamespaces(bind.config?.alwaysIgnore?.namespaces)
|
|
1420
|
+
);
|
|
1421
|
+
if (shouldSkip !== "") {
|
|
1422
|
+
logger_default.debug(shouldSkip);
|
|
1423
|
+
return false;
|
|
1264
1424
|
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
if (e.code === "EADDRINUSE") {
|
|
1272
|
-
logger_default.info(
|
|
1273
|
-
`Address in use, retrying in 2 seconds. If this persists, ensure ${port} is not in use, e.g. "lsof -i :${port}"`
|
|
1274
|
-
);
|
|
1275
|
-
setTimeout(() => {
|
|
1276
|
-
server.close();
|
|
1277
|
-
server.listen(port);
|
|
1278
|
-
}, 2e3);
|
|
1279
|
-
}
|
|
1280
|
-
});
|
|
1281
|
-
process.on("SIGTERM", () => {
|
|
1282
|
-
logger_default.info("Received SIGTERM, closing server");
|
|
1283
|
-
server.close(() => {
|
|
1284
|
-
logger_default.info("Server closed");
|
|
1285
|
-
process.exit(0);
|
|
1286
|
-
});
|
|
1287
|
-
});
|
|
1288
|
-
};
|
|
1289
|
-
#bindEndpoints = () => {
|
|
1290
|
-
this.#app.get("/healthz", _Controller.#healthz);
|
|
1291
|
-
this.#app.get("/metrics", this.#metrics);
|
|
1292
|
-
if (isWatchMode()) {
|
|
1293
|
-
return;
|
|
1425
|
+
return true;
|
|
1426
|
+
});
|
|
1427
|
+
for (const bindable of bindables) {
|
|
1428
|
+
({ wrapped, response } = await processRequest(bindable, wrapped, response));
|
|
1429
|
+
if (config.onError === "reject" /* REJECT */ && response?.warnings.length > 0) {
|
|
1430
|
+
return response;
|
|
1294
1431
|
}
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1432
|
+
}
|
|
1433
|
+
response.allowed = true;
|
|
1434
|
+
if (bindables.length === 0) {
|
|
1435
|
+
logger_default.info(reqMetadata, `No matching actions found`);
|
|
1436
|
+
return response;
|
|
1437
|
+
}
|
|
1438
|
+
if (req.operation === "DELETE") {
|
|
1439
|
+
return response;
|
|
1440
|
+
}
|
|
1441
|
+
const transformed = reencodeData(wrapped, decoded.skipped);
|
|
1442
|
+
const patches = import_fast_json_patch.default.compare(req.object, transformed);
|
|
1443
|
+
updateResponsePatchAndWarnings(patches, response);
|
|
1444
|
+
logger_default.debug({ ...reqMetadata, patches }, `Patches generated`);
|
|
1445
|
+
webhookTimer.stop();
|
|
1446
|
+
return response;
|
|
1447
|
+
}
|
|
1448
|
+
function updateResponsePatchAndWarnings(patches, response) {
|
|
1449
|
+
if (patches.length > 0) {
|
|
1450
|
+
response.patchType = "JSONPatch";
|
|
1451
|
+
response.patch = base64Encode(JSON.stringify(patches));
|
|
1452
|
+
}
|
|
1453
|
+
if (response.warnings && response.warnings.length < 1) {
|
|
1454
|
+
delete response.warnings;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
// src/lib/validate-request.ts
|
|
1459
|
+
var import_ramda7 = require("ramda");
|
|
1460
|
+
var PeprValidateRequest = class {
|
|
1461
|
+
Raw;
|
|
1462
|
+
#input;
|
|
1299
1463
|
/**
|
|
1300
|
-
*
|
|
1301
|
-
*
|
|
1302
|
-
* @param req The incoming request
|
|
1303
|
-
* @param res The outgoing response
|
|
1304
|
-
* @param next The next middleware function
|
|
1305
|
-
* @returns
|
|
1464
|
+
* Provides access to the old resource in the request if available.
|
|
1465
|
+
* @returns The old Kubernetes resource object or null if not available.
|
|
1306
1466
|
*/
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
const err = `Unauthorized: invalid token '${token.replace(/[^\w]/g, "_")}'`;
|
|
1311
|
-
logger_default.info(err);
|
|
1312
|
-
res.status(401).send(err);
|
|
1313
|
-
this.#metricsCollector.alert();
|
|
1314
|
-
return;
|
|
1315
|
-
}
|
|
1316
|
-
next();
|
|
1317
|
-
};
|
|
1467
|
+
get OldResource() {
|
|
1468
|
+
return this.#input.oldObject;
|
|
1469
|
+
}
|
|
1318
1470
|
/**
|
|
1319
|
-
*
|
|
1320
|
-
*
|
|
1321
|
-
* @param req the incoming request
|
|
1322
|
-
* @param res the outgoing response
|
|
1471
|
+
* Provides access to the request object.
|
|
1472
|
+
* @returns The request object containing the Kubernetes resource.
|
|
1323
1473
|
*/
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1474
|
+
get Request() {
|
|
1475
|
+
return this.#input;
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Creates a new instance of the Action class.
|
|
1479
|
+
* @param input - The request object containing the Kubernetes resource to modify.
|
|
1480
|
+
*/
|
|
1481
|
+
constructor(input) {
|
|
1482
|
+
this.#input = input;
|
|
1483
|
+
if (input.operation.toUpperCase() === "DELETE" /* DELETE */) {
|
|
1484
|
+
this.Raw = (0, import_ramda7.clone)(input.oldObject);
|
|
1485
|
+
} else {
|
|
1486
|
+
this.Raw = (0, import_ramda7.clone)(input.object);
|
|
1331
1487
|
}
|
|
1332
|
-
|
|
1488
|
+
if (!this.Raw) {
|
|
1489
|
+
throw new Error("unable to load the request object into PeprRequest.Raw");
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1333
1492
|
/**
|
|
1334
|
-
*
|
|
1493
|
+
* Check if a label exists on the Kubernetes resource.
|
|
1335
1494
|
*
|
|
1336
|
-
* @param
|
|
1337
|
-
* @returns
|
|
1495
|
+
* @param key the label key to check
|
|
1496
|
+
* @returns
|
|
1338
1497
|
*/
|
|
1339
|
-
|
|
1340
|
-
return
|
|
1341
|
-
const startTime = MetricsCollector.observeStart();
|
|
1342
|
-
try {
|
|
1343
|
-
const request = req.body?.request || {};
|
|
1344
|
-
const { name: name2, namespace: namespace2, gvk } = {
|
|
1345
|
-
name: request?.name ? `/${request.name}` : "",
|
|
1346
|
-
namespace: request?.namespace || "",
|
|
1347
|
-
gvk: request?.kind || { group: "", version: "", kind: "" }
|
|
1348
|
-
};
|
|
1349
|
-
const reqMetadata = { uid: request.uid, namespace: namespace2, name: name2 };
|
|
1350
|
-
logger_default.info({ ...reqMetadata, gvk, operation: request.operation, admissionKind }, "Incoming request");
|
|
1351
|
-
logger_default.debug({ ...reqMetadata, request }, "Incoming request body");
|
|
1352
|
-
this.#beforeHook && this.#beforeHook(request || {});
|
|
1353
|
-
const response = admissionKind === "Mutate" ? await mutateProcessor(this.#config, this.#capabilities, request, reqMetadata) : await validateProcessor(this.#config, this.#capabilities, request, reqMetadata);
|
|
1354
|
-
[response].flat().map((res2) => {
|
|
1355
|
-
this.#afterHook && this.#afterHook(res2);
|
|
1356
|
-
logger_default.info({ ...reqMetadata, res: res2 }, "Check response");
|
|
1357
|
-
});
|
|
1358
|
-
const kar = admissionKind === "Mutate" ? karForMutate(response) : karForValidate(request, response);
|
|
1359
|
-
logger_default.debug({ ...reqMetadata, kubeAdmissionResponse: kar.response }, "Outgoing response");
|
|
1360
|
-
res.send(kar);
|
|
1361
|
-
this.#metricsCollector.observeEnd(startTime, admissionKind);
|
|
1362
|
-
} catch (err) {
|
|
1363
|
-
logger_default.error(err, `Error processing ${admissionKind} request`);
|
|
1364
|
-
res.status(500).send("Internal Server Error");
|
|
1365
|
-
this.#metricsCollector.error();
|
|
1366
|
-
}
|
|
1367
|
-
};
|
|
1498
|
+
HasLabel = (key) => {
|
|
1499
|
+
return this.Raw.metadata?.labels?.[key] !== void 0;
|
|
1368
1500
|
};
|
|
1369
1501
|
/**
|
|
1370
|
-
*
|
|
1502
|
+
* Check if an annotation exists on the Kubernetes resource.
|
|
1371
1503
|
*
|
|
1372
|
-
* @param
|
|
1373
|
-
* @
|
|
1374
|
-
* @param next the next middleware function
|
|
1504
|
+
* @param key the annotation key to check
|
|
1505
|
+
* @returns
|
|
1375
1506
|
*/
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
const excludedRoutes = ["/healthz", "/metrics"];
|
|
1380
|
-
if (excludedRoutes.includes(req.originalUrl)) {
|
|
1381
|
-
return;
|
|
1382
|
-
}
|
|
1383
|
-
const elapsedTime = Date.now() - startTime;
|
|
1384
|
-
const message = {
|
|
1385
|
-
uid: req.body?.request?.uid,
|
|
1386
|
-
method: req.method,
|
|
1387
|
-
url: req.originalUrl,
|
|
1388
|
-
status: res.statusCode,
|
|
1389
|
-
duration: `${elapsedTime} ms`
|
|
1390
|
-
};
|
|
1391
|
-
logger_default.info(message);
|
|
1392
|
-
});
|
|
1393
|
-
next();
|
|
1394
|
-
}
|
|
1507
|
+
HasAnnotation = (key) => {
|
|
1508
|
+
return this.Raw.metadata?.annotations?.[key] !== void 0;
|
|
1509
|
+
};
|
|
1395
1510
|
/**
|
|
1396
|
-
*
|
|
1511
|
+
* Create a validation response that allows the request.
|
|
1397
1512
|
*
|
|
1398
|
-
* @
|
|
1399
|
-
* @param res the outgoing response
|
|
1513
|
+
* @returns The validation response.
|
|
1400
1514
|
*/
|
|
1401
|
-
|
|
1402
|
-
try {
|
|
1403
|
-
res.send("OK");
|
|
1404
|
-
} catch (err) {
|
|
1405
|
-
logger_default.error(err, `Error processing health check`);
|
|
1406
|
-
res.status(500).send("Internal Server Error");
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
};
|
|
1410
|
-
|
|
1411
|
-
// src/lib/errors.ts
|
|
1412
|
-
var ErrorList = Object.values(OnError);
|
|
1413
|
-
function ValidateError(error = "") {
|
|
1414
|
-
if (!ErrorList.includes(error)) {
|
|
1415
|
-
throw new Error(`Invalid error: ${error}. Must be one of: ${ErrorList.join(", ")}`);
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
// src/lib/processors/watch-processor.ts
|
|
1420
|
-
var import_kubernetes_fluent_client5 = require("kubernetes-fluent-client");
|
|
1421
|
-
|
|
1422
|
-
// src/lib/core/queue.ts
|
|
1423
|
-
var import_node_crypto = require("node:crypto");
|
|
1424
|
-
var Queue = class {
|
|
1425
|
-
#name;
|
|
1426
|
-
#uid;
|
|
1427
|
-
#queue = [];
|
|
1428
|
-
#pendingPromise = false;
|
|
1429
|
-
constructor(name2) {
|
|
1430
|
-
this.#name = name2;
|
|
1431
|
-
this.#uid = `${Date.now()}-${(0, import_node_crypto.randomBytes)(2).toString("hex")}`;
|
|
1432
|
-
}
|
|
1433
|
-
label() {
|
|
1434
|
-
return { name: this.#name, uid: this.#uid };
|
|
1435
|
-
}
|
|
1436
|
-
stats() {
|
|
1515
|
+
Approve = () => {
|
|
1437
1516
|
return {
|
|
1438
|
-
|
|
1439
|
-
stats: {
|
|
1440
|
-
length: this.#queue.length
|
|
1441
|
-
}
|
|
1517
|
+
allowed: true
|
|
1442
1518
|
};
|
|
1443
|
-
}
|
|
1519
|
+
};
|
|
1444
1520
|
/**
|
|
1445
|
-
*
|
|
1446
|
-
* reconciled.
|
|
1521
|
+
* Create a validation response that denies the request.
|
|
1447
1522
|
*
|
|
1448
|
-
* @param
|
|
1449
|
-
* @param
|
|
1450
|
-
* @
|
|
1451
|
-
* @returns A promise that resolves when the object is reconciled
|
|
1523
|
+
* @param statusMessage Optional status message to return to the user.
|
|
1524
|
+
* @param statusCode Optional status code to return to the user.
|
|
1525
|
+
* @returns The validation response.
|
|
1452
1526
|
*/
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
namespace: item.metadata?.namespace,
|
|
1459
|
-
resourceVersion: item.metadata?.resourceVersion
|
|
1460
|
-
}
|
|
1527
|
+
Deny = (statusMessage, statusCode) => {
|
|
1528
|
+
return {
|
|
1529
|
+
allowed: false,
|
|
1530
|
+
statusCode,
|
|
1531
|
+
statusMessage
|
|
1461
1532
|
};
|
|
1462
|
-
|
|
1463
|
-
return new Promise((resolve, reject) => {
|
|
1464
|
-
this.#queue.push({ item, phase, callback: reconcile, resolve, reject });
|
|
1465
|
-
logger_default.debug(this.stats(), "Queue stats - push");
|
|
1466
|
-
return this.#dequeue();
|
|
1467
|
-
});
|
|
1468
|
-
}
|
|
1469
|
-
/**
|
|
1470
|
-
* Dequeue reconciles the next item in the queue
|
|
1471
|
-
*
|
|
1472
|
-
* @returns A promise that resolves when the webapp is reconciled
|
|
1473
|
-
*/
|
|
1474
|
-
async #dequeue() {
|
|
1475
|
-
if (this.#pendingPromise) {
|
|
1476
|
-
logger_default.debug("Pending promise, not dequeuing");
|
|
1477
|
-
return false;
|
|
1478
|
-
}
|
|
1479
|
-
const element = this.#queue.shift();
|
|
1480
|
-
if (!element) {
|
|
1481
|
-
logger_default.debug("No element, not dequeuing");
|
|
1482
|
-
return false;
|
|
1483
|
-
}
|
|
1484
|
-
try {
|
|
1485
|
-
this.#pendingPromise = true;
|
|
1486
|
-
const note = {
|
|
1487
|
-
queue: this.label(),
|
|
1488
|
-
item: {
|
|
1489
|
-
name: element.item.metadata?.name,
|
|
1490
|
-
namespace: element.item.metadata?.namespace,
|
|
1491
|
-
resourceVersion: element.item.metadata?.resourceVersion
|
|
1492
|
-
}
|
|
1493
|
-
};
|
|
1494
|
-
logger_default.debug(note, "Reconciling");
|
|
1495
|
-
await element.callback(element.item, element.phase);
|
|
1496
|
-
logger_default.debug(note, "Reconciled");
|
|
1497
|
-
element.resolve();
|
|
1498
|
-
} catch (e) {
|
|
1499
|
-
logger_default.debug(`Error reconciling ${element.item.metadata.name}`, { error: e });
|
|
1500
|
-
element.reject(e);
|
|
1501
|
-
} finally {
|
|
1502
|
-
logger_default.debug(this.stats(), "Queue stats - shift");
|
|
1503
|
-
logger_default.debug("Resetting pending promise and dequeuing");
|
|
1504
|
-
this.#pendingPromise = false;
|
|
1505
|
-
await this.#dequeue();
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1533
|
+
};
|
|
1508
1534
|
};
|
|
1509
1535
|
|
|
1510
|
-
// src/lib/processors/
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
}
|
|
1519
|
-
if (request.Request.operation === "UPDATE" /* UPDATE */ && request.Raw.metadata?.deletionTimestamp) {
|
|
1520
|
-
return;
|
|
1521
|
-
}
|
|
1522
|
-
const peprFinal = "pepr.dev/finalizer";
|
|
1523
|
-
const finalizers = request.Raw.metadata?.finalizers || [];
|
|
1524
|
-
if (!finalizers.includes(peprFinal)) {
|
|
1525
|
-
finalizers.push(peprFinal);
|
|
1526
|
-
}
|
|
1527
|
-
request.Merge({ metadata: { finalizers } });
|
|
1528
|
-
}
|
|
1529
|
-
async function removeFinalizer(binding, obj) {
|
|
1530
|
-
const peprFinal = "pepr.dev/finalizer";
|
|
1531
|
-
const meta = obj.metadata;
|
|
1532
|
-
const resource = `${meta.namespace || "ClusterScoped"}/${meta.name}`;
|
|
1533
|
-
logger_default.debug({ obj }, `Removing finalizer '${peprFinal}' from '${resource}'`);
|
|
1534
|
-
const { model, kind: kind3 } = binding;
|
|
1535
|
-
try {
|
|
1536
|
-
(0, import_kubernetes_fluent_client4.RegisterKind)(model, kind3);
|
|
1537
|
-
} catch (e) {
|
|
1538
|
-
const expected = e.message === `GVK ${model.name} already registered`;
|
|
1539
|
-
if (!expected) {
|
|
1540
|
-
logger_default.error({ model, kind: kind3, error: e }, `Error registering "${kind3}" during finalization.`);
|
|
1541
|
-
return;
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
const finalizers = meta.finalizers?.filter((f) => f !== peprFinal) || [];
|
|
1545
|
-
obj = await (0, import_kubernetes_fluent_client4.K8s)(model, meta).Patch([
|
|
1546
|
-
{
|
|
1547
|
-
op: "replace",
|
|
1548
|
-
path: `/metadata/finalizers`,
|
|
1549
|
-
value: finalizers
|
|
1550
|
-
}
|
|
1551
|
-
]);
|
|
1552
|
-
logger_default.debug({ obj }, `Removed finalizer '${peprFinal}' from '${resource}'`);
|
|
1553
|
-
}
|
|
1554
|
-
|
|
1555
|
-
// src/lib/processors/watch-processor.ts
|
|
1556
|
-
var queues = {};
|
|
1557
|
-
function queueKey(obj) {
|
|
1558
|
-
const options = ["kind", "kindNs", "kindNsName", "global"];
|
|
1559
|
-
const d3fault = "kind";
|
|
1560
|
-
let strat = process.env.PEPR_RECONCILE_STRATEGY || d3fault;
|
|
1561
|
-
strat = options.includes(strat) ? strat : d3fault;
|
|
1562
|
-
const ns = obj.metadata?.namespace ?? "cluster-scoped";
|
|
1563
|
-
const kind3 = obj.kind ?? "UnknownKind";
|
|
1564
|
-
const name2 = obj.metadata?.name ?? "Unnamed";
|
|
1565
|
-
const lookup = {
|
|
1566
|
-
kind: `${kind3}`,
|
|
1567
|
-
kindNs: `${kind3}/${ns}`,
|
|
1568
|
-
kindNsName: `${kind3}/${ns}/${name2}`,
|
|
1569
|
-
global: "global"
|
|
1536
|
+
// src/lib/processors/validate-processor.ts
|
|
1537
|
+
async function processRequest2(binding, actionMetadata, peprValidateRequest) {
|
|
1538
|
+
const label = binding.validateCallback.name;
|
|
1539
|
+
logger_default.info(actionMetadata, `Processing validation action (${label})`);
|
|
1540
|
+
const valResp = {
|
|
1541
|
+
uid: peprValidateRequest.Request.uid,
|
|
1542
|
+
allowed: true
|
|
1543
|
+
// Assume it's allowed until a validation check fails
|
|
1570
1544
|
};
|
|
1571
|
-
|
|
1545
|
+
try {
|
|
1546
|
+
const callbackResp = await binding.validateCallback(peprValidateRequest);
|
|
1547
|
+
valResp.allowed = callbackResp.allowed;
|
|
1548
|
+
if (callbackResp.statusCode || callbackResp.statusMessage) {
|
|
1549
|
+
valResp.status = {
|
|
1550
|
+
code: callbackResp.statusCode || 400,
|
|
1551
|
+
message: callbackResp.statusMessage || `Validation failed for ${name}`
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
logger_default.info(actionMetadata, `Validation action complete (${label}): ${callbackResp.allowed ? "allowed" : "denied"}`);
|
|
1555
|
+
return valResp;
|
|
1556
|
+
} catch (e) {
|
|
1557
|
+
logger_default.error(actionMetadata, `Action failed: ${JSON.stringify(e)}`);
|
|
1558
|
+
valResp.allowed = false;
|
|
1559
|
+
valResp.status = {
|
|
1560
|
+
code: 500,
|
|
1561
|
+
message: `Action failed with error: ${JSON.stringify(e)}`
|
|
1562
|
+
};
|
|
1563
|
+
return valResp;
|
|
1564
|
+
}
|
|
1572
1565
|
}
|
|
1573
|
-
function
|
|
1574
|
-
const
|
|
1575
|
-
|
|
1576
|
-
|
|
1566
|
+
async function validateProcessor(config, capabilities, req, reqMetadata) {
|
|
1567
|
+
const webhookTimer = new MeasureWebhookTimeout("validate" /* VALIDATE */);
|
|
1568
|
+
webhookTimer.start(config.webhookTimeout);
|
|
1569
|
+
const wrapped = new PeprValidateRequest(req);
|
|
1570
|
+
const response = [];
|
|
1571
|
+
if (req.kind.version === "v1" && req.kind.kind === "Secret") {
|
|
1572
|
+
convertFromBase64Map(wrapped.Raw);
|
|
1577
1573
|
}
|
|
1578
|
-
|
|
1574
|
+
logger_default.info(reqMetadata, `Processing validation request`);
|
|
1575
|
+
for (const { name: name2, bindings, namespaces } of capabilities) {
|
|
1576
|
+
const actionMetadata = { ...reqMetadata, name: name2 };
|
|
1577
|
+
for (const binding of bindings) {
|
|
1578
|
+
if (!binding.validateCallback) {
|
|
1579
|
+
continue;
|
|
1580
|
+
}
|
|
1581
|
+
const shouldSkip = shouldSkipRequest(
|
|
1582
|
+
binding,
|
|
1583
|
+
req,
|
|
1584
|
+
namespaces,
|
|
1585
|
+
resolveIgnoreNamespaces(config?.alwaysIgnore?.namespaces)
|
|
1586
|
+
);
|
|
1587
|
+
if (shouldSkip !== "") {
|
|
1588
|
+
logger_default.debug(shouldSkip);
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
const resp = await processRequest2(binding, actionMetadata, wrapped);
|
|
1592
|
+
response.push(resp);
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
webhookTimer.stop();
|
|
1596
|
+
return response;
|
|
1579
1597
|
}
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1598
|
+
|
|
1599
|
+
// src/lib/controller/store.ts
|
|
1600
|
+
var import_kubernetes_fluent_client5 = require("kubernetes-fluent-client");
|
|
1601
|
+
var import_ramda8 = require("ramda");
|
|
1602
|
+
|
|
1603
|
+
// src/lib/k8s.ts
|
|
1604
|
+
var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
|
|
1605
|
+
var Store = class extends import_kubernetes_fluent_client3.GenericKind {
|
|
1585
1606
|
};
|
|
1586
|
-
var
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
["DELETE" /* DELETE */]: [import_types.WatchPhase.Deleted],
|
|
1591
|
-
["*" /* ANY */]: [import_types.WatchPhase.Added, import_types.WatchPhase.Modified, import_types.WatchPhase.Deleted]
|
|
1607
|
+
var peprStoreGVK = {
|
|
1608
|
+
kind: "PeprStore",
|
|
1609
|
+
version: "v1",
|
|
1610
|
+
group: "pepr.dev"
|
|
1592
1611
|
};
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
async
|
|
1599
|
-
const
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
if (
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
if (filterMatch !== "") {
|
|
1606
|
-
logger_default.debug(filterMatch);
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
if (binding.isFinalize) {
|
|
1610
|
-
await handleFinalizerRemoval(kubernetesObject);
|
|
1611
|
-
} else {
|
|
1612
|
-
await binding.watchCallback?.(kubernetesObject, phase);
|
|
1613
|
-
}
|
|
1614
|
-
} catch (e) {
|
|
1615
|
-
logger_default.error(e, "Error executing watch callback");
|
|
1616
|
-
}
|
|
1617
|
-
}
|
|
1618
|
-
};
|
|
1619
|
-
const handleFinalizerRemoval = async (kubernetesObject) => {
|
|
1620
|
-
if (!kubernetesObject.metadata?.deletionTimestamp) {
|
|
1621
|
-
return;
|
|
1622
|
-
}
|
|
1623
|
-
let shouldRemoveFinalizer = true;
|
|
1624
|
-
try {
|
|
1625
|
-
shouldRemoveFinalizer = await binding.finalizeCallback?.(kubernetesObject);
|
|
1626
|
-
} finally {
|
|
1627
|
-
const peprFinal = "pepr.dev/finalizer";
|
|
1628
|
-
const meta = kubernetesObject.metadata;
|
|
1629
|
-
const resource = `${meta.namespace || "ClusterScoped"}/${meta.name}`;
|
|
1630
|
-
shouldRemoveFinalizer === false ? logger_default.debug({ obj: kubernetesObject }, `Skipping removal of finalizer '${peprFinal}' from '${resource}'`) : await removeFinalizer(binding, kubernetesObject);
|
|
1612
|
+
(0, import_kubernetes_fluent_client3.RegisterKind)(Store, peprStoreGVK);
|
|
1613
|
+
|
|
1614
|
+
// src/lib/controller/storeCache.ts
|
|
1615
|
+
var import_kubernetes_fluent_client4 = require("kubernetes-fluent-client");
|
|
1616
|
+
var import_http_status_codes = require("http-status-codes");
|
|
1617
|
+
var sendUpdatesAndFlushCache = async (cache, namespace2, name2) => {
|
|
1618
|
+
const indexes = Object.keys(cache);
|
|
1619
|
+
const payload = Object.values(cache);
|
|
1620
|
+
try {
|
|
1621
|
+
if (payload.length > 0) {
|
|
1622
|
+
await (0, import_kubernetes_fluent_client4.K8s)(Store, { namespace: namespace2, name: name2 }).Patch(updateCacheID(payload));
|
|
1623
|
+
Object.keys(cache).forEach((key) => delete cache[key]);
|
|
1631
1624
|
}
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
const queue = getOrCreateQueue(obj);
|
|
1637
|
-
await queue.enqueue(obj, phase, watchCallback);
|
|
1625
|
+
} catch (err) {
|
|
1626
|
+
logger_default.error(err, "Pepr store update failure");
|
|
1627
|
+
if (err.status === import_http_status_codes.StatusCodes.UNPROCESSABLE_ENTITY) {
|
|
1628
|
+
Object.keys(cache).forEach((key) => delete cache[key]);
|
|
1638
1629
|
} else {
|
|
1639
|
-
|
|
1630
|
+
indexes.forEach((index) => {
|
|
1631
|
+
cache[index] = payload[Number(index)];
|
|
1632
|
+
});
|
|
1640
1633
|
}
|
|
1641
|
-
}, watchCfg);
|
|
1642
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.GIVE_UP, (err) => {
|
|
1643
|
-
logger_default.error(err, "Watch failed after 5 attempts, giving up");
|
|
1644
|
-
process.exit(1);
|
|
1645
|
-
});
|
|
1646
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.CONNECT, (url) => logEvent(import_kubernetes_fluent_client5.WatchEvent.CONNECT, url));
|
|
1647
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.DATA_ERROR, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.DATA_ERROR, err.message));
|
|
1648
|
-
watcher.events.on(
|
|
1649
|
-
import_kubernetes_fluent_client5.WatchEvent.RECONNECT,
|
|
1650
|
-
(retryCount) => logEvent(import_kubernetes_fluent_client5.WatchEvent.RECONNECT, `Reconnecting after ${retryCount} attempt${retryCount === 1 ? "" : "s"}`)
|
|
1651
|
-
);
|
|
1652
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.RECONNECT_PENDING, () => logEvent(import_kubernetes_fluent_client5.WatchEvent.RECONNECT_PENDING));
|
|
1653
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.GIVE_UP, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.GIVE_UP, err.message));
|
|
1654
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.ABORT, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.ABORT, err.message));
|
|
1655
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.OLD_RESOURCE_VERSION, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.OLD_RESOURCE_VERSION, err));
|
|
1656
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.NETWORK_ERROR, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.NETWORK_ERROR, err.message));
|
|
1657
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.LIST_ERROR, (err) => logEvent(import_kubernetes_fluent_client5.WatchEvent.LIST_ERROR, err.message));
|
|
1658
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.LIST, (list) => logEvent(import_kubernetes_fluent_client5.WatchEvent.LIST, JSON.stringify(list, void 0, 2)));
|
|
1659
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.CACHE_MISS, (windowName) => {
|
|
1660
|
-
metricsCollector.incCacheMiss(windowName);
|
|
1661
|
-
});
|
|
1662
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.INIT_CACHE_MISS, (windowName) => {
|
|
1663
|
-
metricsCollector.initCacheMissWindow(windowName);
|
|
1664
|
-
});
|
|
1665
|
-
watcher.events.on(import_kubernetes_fluent_client5.WatchEvent.INC_RESYNC_FAILURE_COUNT, (retryCount) => {
|
|
1666
|
-
metricsCollector.incRetryCount(retryCount);
|
|
1667
|
-
});
|
|
1668
|
-
try {
|
|
1669
|
-
await watcher.start();
|
|
1670
|
-
} catch (err) {
|
|
1671
|
-
logger_default.error(err, "Error starting watch");
|
|
1672
|
-
process.exit(1);
|
|
1673
1634
|
}
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1635
|
+
return cache;
|
|
1636
|
+
};
|
|
1637
|
+
var fillStoreCache = (cache, capabilityName, op, cacheItem) => {
|
|
1638
|
+
const path = [`/data/${capabilityName}`, cacheItem.version, cacheItem.key].filter((str) => str !== "" && str !== void 0).join("-");
|
|
1639
|
+
if (op === "add") {
|
|
1640
|
+
const value = cacheItem.value || "";
|
|
1641
|
+
const cacheIdx = [op, path, value].join(":");
|
|
1642
|
+
cache[cacheIdx] = { op, path, value };
|
|
1643
|
+
} else if (op === "remove") {
|
|
1644
|
+
if (cacheItem.key.length < 1) {
|
|
1645
|
+
throw new Error(`Key is required for REMOVE operation`);
|
|
1646
|
+
}
|
|
1647
|
+
const cacheIndex = [op, path].join(":");
|
|
1648
|
+
cache[cacheIndex] = { op, path };
|
|
1679
1649
|
} else {
|
|
1680
|
-
|
|
1650
|
+
throw new Error(`Unsupported operation: ${op}`);
|
|
1681
1651
|
}
|
|
1652
|
+
return cache;
|
|
1653
|
+
};
|
|
1654
|
+
function updateCacheID(payload) {
|
|
1655
|
+
payload.push({
|
|
1656
|
+
op: "replace",
|
|
1657
|
+
path: "/metadata/labels/pepr.dev-cacheID",
|
|
1658
|
+
value: `${Date.now()}`
|
|
1659
|
+
});
|
|
1660
|
+
return payload;
|
|
1682
1661
|
}
|
|
1683
1662
|
|
|
1684
|
-
// src/lib/
|
|
1685
|
-
var
|
|
1686
|
-
var
|
|
1687
|
-
var
|
|
1688
|
-
var
|
|
1689
|
-
#
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
if (
|
|
1702
|
-
|
|
1703
|
-
|
|
1663
|
+
// src/lib/controller/store.ts
|
|
1664
|
+
var namespace = "pepr-system";
|
|
1665
|
+
var debounceBackoffReceive = 1e3;
|
|
1666
|
+
var debounceBackoffSend = 4e3;
|
|
1667
|
+
var StoreController = class {
|
|
1668
|
+
#name;
|
|
1669
|
+
#stores = {};
|
|
1670
|
+
#sendDebounce;
|
|
1671
|
+
#onReady;
|
|
1672
|
+
constructor(capabilities, name2, onReady) {
|
|
1673
|
+
this.#onReady = onReady;
|
|
1674
|
+
this.#name = name2;
|
|
1675
|
+
const setStorageInstance = (registrationFunction, name3) => {
|
|
1676
|
+
const scheduleStore = registrationFunction();
|
|
1677
|
+
scheduleStore.registerSender(this.#send(name3));
|
|
1678
|
+
this.#stores[name3] = scheduleStore;
|
|
1679
|
+
};
|
|
1680
|
+
if (name2.includes("schedule")) {
|
|
1681
|
+
for (const { name: name3, registerScheduleStore, hasSchedule } of capabilities) {
|
|
1682
|
+
if (hasSchedule === true) {
|
|
1683
|
+
setStorageInstance(registerScheduleStore, name3);
|
|
1684
|
+
}
|
|
1704
1685
|
}
|
|
1705
|
-
|
|
1706
|
-
for (const
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1686
|
+
} else {
|
|
1687
|
+
for (const { name: name3, registerStore } of capabilities) {
|
|
1688
|
+
setStorageInstance(registerStore, name3);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
setTimeout(
|
|
1692
|
+
() => (0, import_kubernetes_fluent_client5.K8s)(Store).InNamespace(namespace).Get(this.#name).then(async (store) => await this.#migrateAndSetupWatch(store)).catch(this.#createStoreResource),
|
|
1693
|
+
Math.random() * 3e3
|
|
1694
|
+
// Add a jitter to the Store creation to avoid collisions
|
|
1695
|
+
);
|
|
1696
|
+
}
|
|
1697
|
+
#setupWatch = () => {
|
|
1698
|
+
const watcher = (0, import_kubernetes_fluent_client5.K8s)(Store, { name: this.#name, namespace }).Watch(this.#receive);
|
|
1699
|
+
watcher.start().catch((e) => logger_default.error(e, "Error starting Pepr store watch"));
|
|
1700
|
+
};
|
|
1701
|
+
#migrateAndSetupWatch = async (store) => {
|
|
1702
|
+
logger_default.debug(redactedStore(store), "Pepr Store migration");
|
|
1703
|
+
await (0, import_kubernetes_fluent_client5.K8s)(Store, { namespace, name: this.#name }).Patch([
|
|
1704
|
+
{
|
|
1705
|
+
op: "add",
|
|
1706
|
+
path: "/metadata/labels/pepr.dev-cacheID",
|
|
1707
|
+
value: `${Date.now()}`
|
|
1714
1708
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
}
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1709
|
+
]);
|
|
1710
|
+
const data = store.data || {};
|
|
1711
|
+
let storeCache = {};
|
|
1712
|
+
for (const name2 of Object.keys(this.#stores)) {
|
|
1713
|
+
const offset = `${name2}-`.length;
|
|
1714
|
+
for (const key of Object.keys(data)) {
|
|
1715
|
+
if ((0, import_ramda8.startsWith)(name2, key) && !(0, import_ramda8.startsWith)(`${name2}-v2`, key)) {
|
|
1716
|
+
storeCache = fillStoreCache(storeCache, name2, "remove", {
|
|
1717
|
+
key: [key.slice(offset)],
|
|
1718
|
+
value: data[key]
|
|
1719
|
+
});
|
|
1720
|
+
storeCache = fillStoreCache(storeCache, name2, "add", {
|
|
1721
|
+
key: [key.slice(offset)],
|
|
1722
|
+
value: data[key],
|
|
1723
|
+
version: "v2"
|
|
1724
|
+
});
|
|
1725
1725
|
}
|
|
1726
1726
|
}
|
|
1727
|
-
});
|
|
1728
|
-
if (opts.deferStart) {
|
|
1729
|
-
return;
|
|
1730
1727
|
}
|
|
1731
|
-
this
|
|
1732
|
-
|
|
1733
|
-
/**
|
|
1734
|
-
* Start the Pepr runtime manually.
|
|
1735
|
-
* Normally this is called automatically when the Pepr module is instantiated, but can be called manually if `deferStart` is set to `true` in the constructor.
|
|
1736
|
-
*
|
|
1737
|
-
* @param port
|
|
1738
|
-
*/
|
|
1739
|
-
start = (port = 3e3) => {
|
|
1740
|
-
this.#controller.startServer(port);
|
|
1728
|
+
storeCache = await sendUpdatesAndFlushCache(storeCache, namespace, this.#name);
|
|
1729
|
+
this.#setupWatch();
|
|
1741
1730
|
};
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
this.#
|
|
1731
|
+
#receive = (store) => {
|
|
1732
|
+
logger_default.debug(redactedStore(store), "Pepr Store update");
|
|
1733
|
+
const debounced = () => {
|
|
1734
|
+
const data = store.data || {};
|
|
1735
|
+
for (const name2 of Object.keys(this.#stores)) {
|
|
1736
|
+
const offset = `${name2}-`.length;
|
|
1737
|
+
const filtered = {};
|
|
1738
|
+
for (const key of Object.keys(data)) {
|
|
1739
|
+
if ((0, import_ramda8.startsWith)(name2, key)) {
|
|
1740
|
+
filtered[key.slice(offset)] = data[key];
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
this.#stores[name2].receive(filtered);
|
|
1744
|
+
}
|
|
1745
|
+
if (this.#onReady) {
|
|
1746
|
+
this.#onReady();
|
|
1747
|
+
this.#onReady = void 0;
|
|
1748
|
+
}
|
|
1749
|
+
};
|
|
1750
|
+
clearTimeout(this.#sendDebounce);
|
|
1751
|
+
this.#sendDebounce = setTimeout(debounced, this.#onReady ? 0 : debounceBackoffReceive);
|
|
1763
1752
|
};
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1753
|
+
#send = (capabilityName) => {
|
|
1754
|
+
let storeCache = {};
|
|
1755
|
+
const sender = async (op, key, value) => {
|
|
1756
|
+
storeCache = fillStoreCache(storeCache, capabilityName, op, { key, value });
|
|
1757
|
+
};
|
|
1758
|
+
setInterval(() => {
|
|
1759
|
+
if (Object.keys(storeCache).length > 0) {
|
|
1760
|
+
logger_default.debug(redactedPatch(storeCache), "Sending updates to Pepr store");
|
|
1761
|
+
void sendUpdatesAndFlushCache(storeCache, namespace, this.#name);
|
|
1762
|
+
}
|
|
1763
|
+
}, debounceBackoffSend);
|
|
1764
|
+
return sender;
|
|
1770
1765
|
};
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1766
|
+
#createStoreResource = async (e) => {
|
|
1767
|
+
logger_default.info(`Pepr store not found, creating...`);
|
|
1768
|
+
logger_default.debug(e);
|
|
1769
|
+
try {
|
|
1770
|
+
await (0, import_kubernetes_fluent_client5.K8s)(Store).Apply({
|
|
1771
|
+
metadata: {
|
|
1772
|
+
name: this.#name,
|
|
1773
|
+
namespace,
|
|
1774
|
+
labels: {
|
|
1775
|
+
"pepr.dev-cacheID": `${Date.now()}`
|
|
1776
|
+
}
|
|
1777
|
+
},
|
|
1778
|
+
data: {
|
|
1779
|
+
// JSON Patch will die if the data is empty, so we need to add a placeholder
|
|
1780
|
+
__pepr_do_not_delete__: "k-thx-bye"
|
|
1781
|
+
}
|
|
1782
|
+
});
|
|
1783
|
+
this.#setupWatch();
|
|
1784
|
+
} catch (err) {
|
|
1785
|
+
logger_default.error(err, "Failed to create Pepr store");
|
|
1775
1786
|
}
|
|
1776
|
-
return null;
|
|
1777
1787
|
};
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1788
|
+
};
|
|
1789
|
+
|
|
1790
|
+
// src/lib/controller/index.util.ts
|
|
1791
|
+
function karForMutate(mr) {
|
|
1792
|
+
return {
|
|
1793
|
+
apiVersion: "admission.k8s.io/v1",
|
|
1794
|
+
kind: "AdmissionReview",
|
|
1795
|
+
response: mr
|
|
1783
1796
|
};
|
|
1784
|
-
|
|
1785
|
-
|
|
1797
|
+
}
|
|
1798
|
+
function karForValidate(ar, vr) {
|
|
1799
|
+
const isAllowed = vr.filter((r) => !r.allowed).length === 0;
|
|
1800
|
+
const resp = vr.length === 0 ? {
|
|
1801
|
+
uid: ar.uid,
|
|
1802
|
+
allowed: true,
|
|
1803
|
+
status: { code: 200, message: "no in-scope validations -- allowed!" }
|
|
1804
|
+
} : {
|
|
1805
|
+
uid: vr[0].uid,
|
|
1806
|
+
allowed: isAllowed,
|
|
1807
|
+
status: {
|
|
1808
|
+
code: isAllowed ? 200 : 422,
|
|
1809
|
+
message: vr.filter((rl) => !rl.allowed).map((curr) => curr.status?.message).join("; ")
|
|
1810
|
+
}
|
|
1786
1811
|
};
|
|
1787
|
-
|
|
1788
|
-
|
|
1812
|
+
return {
|
|
1813
|
+
apiVersion: "admission.k8s.io/v1",
|
|
1814
|
+
kind: "AdmissionReview",
|
|
1815
|
+
response: resp
|
|
1789
1816
|
};
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1817
|
+
}
|
|
1818
|
+
|
|
1819
|
+
// src/lib/controller/index.ts
|
|
1820
|
+
if (!process.env.PEPR_NODE_WARNINGS) {
|
|
1821
|
+
process.removeAllListeners("warning");
|
|
1822
|
+
}
|
|
1823
|
+
var Controller = class _Controller {
|
|
1824
|
+
// Track whether the server is running
|
|
1825
|
+
#running = false;
|
|
1826
|
+
// Metrics collector
|
|
1827
|
+
#metricsCollector = metricsCollector;
|
|
1828
|
+
// The token used to authenticate requests
|
|
1829
|
+
#token = "";
|
|
1830
|
+
// The express app instance
|
|
1831
|
+
#app = (0, import_express.default)();
|
|
1832
|
+
// Initialized with the constructor
|
|
1833
|
+
#config;
|
|
1834
|
+
#capabilities;
|
|
1835
|
+
#beforeHook;
|
|
1836
|
+
#afterHook;
|
|
1837
|
+
constructor(config, capabilities, hooks = {}) {
|
|
1838
|
+
const { beforeHook, afterHook, onReady } = hooks;
|
|
1839
|
+
this.#config = config;
|
|
1840
|
+
this.#capabilities = capabilities;
|
|
1841
|
+
new StoreController(capabilities, `pepr-${config.uuid}-store`, () => {
|
|
1842
|
+
this.#bindEndpoints();
|
|
1843
|
+
if (typeof onReady === "function") {
|
|
1844
|
+
onReady();
|
|
1845
|
+
}
|
|
1846
|
+
logger_default.info("\u2705 Controller startup complete");
|
|
1847
|
+
new StoreController(capabilities, `pepr-${config.uuid}-schedule`, () => {
|
|
1848
|
+
logger_default.info("\u2705 Scheduling processed");
|
|
1812
1849
|
});
|
|
1813
1850
|
});
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1851
|
+
this.#app.use(_Controller.#logger);
|
|
1852
|
+
this.#app.use(import_express.default.json({ limit: "2mb" }));
|
|
1853
|
+
if (beforeHook) {
|
|
1854
|
+
logger_default.info(`Using beforeHook: ${beforeHook}`);
|
|
1855
|
+
this.#beforeHook = beforeHook;
|
|
1856
|
+
}
|
|
1857
|
+
if (afterHook) {
|
|
1858
|
+
logger_default.info(`Using afterHook: ${afterHook}`);
|
|
1859
|
+
this.#afterHook = afterHook;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
/** Start the webhook server */
|
|
1863
|
+
startServer = (port) => {
|
|
1864
|
+
if (this.#running) {
|
|
1865
|
+
throw new Error("Cannot start Pepr module: Pepr module was not instantiated with deferStart=true");
|
|
1866
|
+
}
|
|
1867
|
+
const options = {
|
|
1868
|
+
key: import_fs.default.readFileSync(process.env.SSL_KEY_PATH || "/etc/certs/tls.key"),
|
|
1869
|
+
cert: import_fs.default.readFileSync(process.env.SSL_CERT_PATH || "/etc/certs/tls.crt")
|
|
1870
|
+
};
|
|
1871
|
+
if (!isWatchMode()) {
|
|
1872
|
+
this.#token = process.env.PEPR_API_TOKEN || import_fs.default.readFileSync("/app/api-token/value").toString().trim();
|
|
1873
|
+
logger_default.info(`Using API token: ${this.#token}`);
|
|
1874
|
+
if (!this.#token) {
|
|
1875
|
+
throw new Error("API token not found");
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
const server = import_https.default.createServer(options, this.#app).listen(port);
|
|
1879
|
+
server.on("listening", () => {
|
|
1880
|
+
logger_default.info(`Server listening on port ${port}`);
|
|
1881
|
+
this.#running = true;
|
|
1882
|
+
});
|
|
1883
|
+
server.on("error", (e) => {
|
|
1884
|
+
if (e.code === "EADDRINUSE") {
|
|
1885
|
+
logger_default.info(
|
|
1886
|
+
`Address in use, retrying in 2 seconds. If this persists, ensure ${port} is not in use, e.g. "lsof -i :${port}"`
|
|
1887
|
+
);
|
|
1888
|
+
setTimeout(() => {
|
|
1889
|
+
server.close();
|
|
1890
|
+
server.listen(port);
|
|
1891
|
+
}, 2e3);
|
|
1892
|
+
}
|
|
1893
|
+
});
|
|
1894
|
+
process.on("SIGTERM", () => {
|
|
1895
|
+
logger_default.info("Received SIGTERM, closing server");
|
|
1896
|
+
server.close(() => {
|
|
1897
|
+
logger_default.info("Server closed");
|
|
1898
|
+
process.exit(0);
|
|
1836
1899
|
});
|
|
1837
1900
|
});
|
|
1838
1901
|
};
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
this.#
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
onReady = (callback) => {
|
|
1845
|
-
this.#readyHandlers.push(callback);
|
|
1846
|
-
};
|
|
1847
|
-
/**
|
|
1848
|
-
* Remove a subscriber from the list of subscribers.
|
|
1849
|
-
* @param idx - The index of the subscriber to remove.
|
|
1850
|
-
*/
|
|
1851
|
-
unsubscribe = (idx) => {
|
|
1852
|
-
delete this.#subscribers[idx];
|
|
1853
|
-
};
|
|
1854
|
-
#onReady = () => {
|
|
1855
|
-
for (const handler of this.#readyHandlers) {
|
|
1856
|
-
handler((0, import_ramda8.clone)(this.#store));
|
|
1902
|
+
#bindEndpoints = () => {
|
|
1903
|
+
this.#app.get("/healthz", _Controller.#healthz);
|
|
1904
|
+
this.#app.get("/metrics", this.#metrics);
|
|
1905
|
+
if (isWatchMode()) {
|
|
1906
|
+
return;
|
|
1857
1907
|
}
|
|
1858
|
-
this.#
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
/**
|
|
1862
|
-
* Dispatch an update to the store and notify all subscribers.
|
|
1863
|
-
* @param op - The type of operation to perform.
|
|
1864
|
-
* @param keys - The keys to update.
|
|
1865
|
-
* @param [value] - The new value.
|
|
1866
|
-
*/
|
|
1867
|
-
#dispatchUpdate = (op, keys, value) => {
|
|
1868
|
-
this.#send(op, keys, value);
|
|
1908
|
+
this.#app.use(["/mutate/:token", "/validate/:token"], this.#validateToken);
|
|
1909
|
+
this.#app.post("/mutate/:token", this.#admissionReq("Mutate"));
|
|
1910
|
+
this.#app.post("/validate/:token", this.#admissionReq("Validate"));
|
|
1869
1911
|
};
|
|
1870
|
-
};
|
|
1871
|
-
|
|
1872
|
-
// src/lib/core/schedule.ts
|
|
1873
|
-
var OnSchedule = class {
|
|
1874
|
-
intervalId = null;
|
|
1875
|
-
store;
|
|
1876
|
-
name;
|
|
1877
|
-
completions;
|
|
1878
|
-
every;
|
|
1879
|
-
unit;
|
|
1880
|
-
run;
|
|
1881
|
-
startTime;
|
|
1882
|
-
duration;
|
|
1883
|
-
lastTimestamp;
|
|
1884
|
-
constructor(schedule) {
|
|
1885
|
-
this.name = schedule.name;
|
|
1886
|
-
this.run = schedule.run;
|
|
1887
|
-
this.every = schedule.every;
|
|
1888
|
-
this.unit = schedule.unit;
|
|
1889
|
-
this.startTime = schedule?.startTime;
|
|
1890
|
-
this.completions = schedule?.completions;
|
|
1891
|
-
}
|
|
1892
|
-
setStore(store) {
|
|
1893
|
-
this.store = store;
|
|
1894
|
-
this.startInterval();
|
|
1895
|
-
}
|
|
1896
|
-
startInterval() {
|
|
1897
|
-
this.checkStore();
|
|
1898
|
-
this.getDuration();
|
|
1899
|
-
this.setupInterval();
|
|
1900
|
-
}
|
|
1901
|
-
/**
|
|
1902
|
-
* Checks the store for this schedule and sets the values if it exists
|
|
1903
|
-
* @returns
|
|
1904
|
-
*/
|
|
1905
|
-
checkStore() {
|
|
1906
|
-
const result = this.store && this.store.getItem(this.name);
|
|
1907
|
-
if (result) {
|
|
1908
|
-
const storedSchedule = JSON.parse(result);
|
|
1909
|
-
this.completions = storedSchedule?.completions;
|
|
1910
|
-
this.startTime = storedSchedule?.startTime;
|
|
1911
|
-
this.lastTimestamp = storedSchedule?.lastTimestamp;
|
|
1912
|
-
}
|
|
1913
|
-
}
|
|
1914
1912
|
/**
|
|
1915
|
-
*
|
|
1913
|
+
* Validate the token in the request path
|
|
1914
|
+
*
|
|
1915
|
+
* @param req The incoming request
|
|
1916
|
+
* @param res The outgoing response
|
|
1917
|
+
* @param next The next middleware function
|
|
1916
1918
|
* @returns
|
|
1917
1919
|
*/
|
|
1918
|
-
|
|
1919
|
-
const
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
}
|
|
1927
|
-
/**
|
|
1928
|
-
* Gets the durations in milliseconds
|
|
1929
|
-
*/
|
|
1930
|
-
getDuration() {
|
|
1931
|
-
switch (this.unit) {
|
|
1932
|
-
case "seconds":
|
|
1933
|
-
if (this.every < 10) throw new Error("10 Seconds in the smallest interval allowed");
|
|
1934
|
-
this.duration = 1e3 * this.every;
|
|
1935
|
-
break;
|
|
1936
|
-
case "minutes":
|
|
1937
|
-
case "minute":
|
|
1938
|
-
this.duration = 1e3 * 60 * this.every;
|
|
1939
|
-
break;
|
|
1940
|
-
case "hours":
|
|
1941
|
-
case "hour":
|
|
1942
|
-
this.duration = 1e3 * 60 * 60 * this.every;
|
|
1943
|
-
break;
|
|
1944
|
-
default:
|
|
1945
|
-
throw new Error("Invalid time unit");
|
|
1920
|
+
#validateToken = (req, res, next) => {
|
|
1921
|
+
const { token } = req.params;
|
|
1922
|
+
if (token !== this.#token) {
|
|
1923
|
+
const err = `Unauthorized: invalid token '${token.replace(/[^\w]/g, "_")}'`;
|
|
1924
|
+
logger_default.info(err);
|
|
1925
|
+
res.status(401).send(err);
|
|
1926
|
+
this.#metricsCollector.alert();
|
|
1927
|
+
return;
|
|
1946
1928
|
}
|
|
1947
|
-
|
|
1929
|
+
next();
|
|
1930
|
+
};
|
|
1948
1931
|
/**
|
|
1949
|
-
*
|
|
1932
|
+
* Metrics endpoint handler
|
|
1933
|
+
*
|
|
1934
|
+
* @param req the incoming request
|
|
1935
|
+
* @param res the outgoing response
|
|
1950
1936
|
*/
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
delay = this.startTime.getTime() - now.getTime();
|
|
1959
|
-
} else if (this.lastTimestamp && this.duration) {
|
|
1960
|
-
const lastTimestamp = new Date(this.lastTimestamp);
|
|
1961
|
-
delay = this.duration - (now.getTime() - lastTimestamp.getTime());
|
|
1962
|
-
}
|
|
1963
|
-
if (delay === void 0 || delay <= 0) {
|
|
1964
|
-
this.start();
|
|
1965
|
-
} else {
|
|
1966
|
-
setTimeout(() => {
|
|
1967
|
-
this.start();
|
|
1968
|
-
}, delay);
|
|
1937
|
+
#metrics = async (req, res) => {
|
|
1938
|
+
try {
|
|
1939
|
+
res.set("Content-Type", "text/plain; version=0.0.4");
|
|
1940
|
+
res.send(await this.#metricsCollector.getMetrics());
|
|
1941
|
+
} catch (err) {
|
|
1942
|
+
logger_default.error(err, `Error getting metrics`);
|
|
1943
|
+
res.status(500).send("Internal Server Error");
|
|
1969
1944
|
}
|
|
1970
|
-
}
|
|
1945
|
+
};
|
|
1971
1946
|
/**
|
|
1972
|
-
*
|
|
1947
|
+
* Admission request handler for both mutate and validate requests
|
|
1948
|
+
*
|
|
1949
|
+
* @param admissionKind the type of admission request
|
|
1950
|
+
* @returns the request handler
|
|
1973
1951
|
*/
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1952
|
+
#admissionReq = (admissionKind) => {
|
|
1953
|
+
return async (req, res) => {
|
|
1954
|
+
const startTime = MetricsCollector.observeStart();
|
|
1955
|
+
try {
|
|
1956
|
+
const request = req.body?.request || {};
|
|
1957
|
+
const { name: name2, namespace: namespace2, gvk } = {
|
|
1958
|
+
name: request?.name ? `/${request.name}` : "",
|
|
1959
|
+
namespace: request?.namespace || "",
|
|
1960
|
+
gvk: request?.kind || { group: "", version: "", kind: "" }
|
|
1961
|
+
};
|
|
1962
|
+
const reqMetadata = { uid: request.uid, namespace: namespace2, name: name2 };
|
|
1963
|
+
logger_default.info({ ...reqMetadata, gvk, operation: request.operation, admissionKind }, "Incoming request");
|
|
1964
|
+
logger_default.debug({ ...reqMetadata, request }, "Incoming request body");
|
|
1965
|
+
if (typeof this.#beforeHook === "function") {
|
|
1966
|
+
this.#beforeHook(request || {});
|
|
1983
1967
|
}
|
|
1984
|
-
this
|
|
1968
|
+
const response = admissionKind === "Mutate" ? await mutateProcessor(this.#config, this.#capabilities, request, reqMetadata) : await validateProcessor(this.#config, this.#capabilities, request, reqMetadata);
|
|
1969
|
+
[response].flat().map((res2) => {
|
|
1970
|
+
if (typeof this.#afterHook === "function") {
|
|
1971
|
+
this.#afterHook(res2);
|
|
1972
|
+
}
|
|
1973
|
+
logger_default.info({ ...reqMetadata, res: res2 }, "Check response");
|
|
1974
|
+
});
|
|
1975
|
+
const kar = admissionKind === "Mutate" ? karForMutate(response) : karForValidate(request, response);
|
|
1976
|
+
logger_default.debug({ ...reqMetadata, kubeAdmissionResponse: kar.response }, "Outgoing response");
|
|
1977
|
+
res.send(kar);
|
|
1978
|
+
this.#metricsCollector.observeEnd(startTime, admissionKind);
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
logger_default.error(err, `Error processing ${admissionKind} request`);
|
|
1981
|
+
res.status(500).send("Internal Server Error");
|
|
1982
|
+
this.#metricsCollector.error();
|
|
1985
1983
|
}
|
|
1986
|
-
}
|
|
1987
|
-
}
|
|
1988
|
-
/**
|
|
1989
|
-
* Stops the interval
|
|
1990
|
-
*/
|
|
1991
|
-
stop() {
|
|
1992
|
-
if (this.intervalId) {
|
|
1993
|
-
clearInterval(this.intervalId);
|
|
1994
|
-
this.intervalId = null;
|
|
1995
|
-
}
|
|
1996
|
-
this.store && this.store.removeItem(this.name);
|
|
1997
|
-
}
|
|
1998
|
-
};
|
|
1999
|
-
|
|
2000
|
-
// src/lib/core/capability.ts
|
|
2001
|
-
var registerAdmission = isBuildMode() || !isWatchMode();
|
|
2002
|
-
var registerWatch = isBuildMode() || isWatchMode() || isDevMode();
|
|
2003
|
-
var Capability = class {
|
|
2004
|
-
#name;
|
|
2005
|
-
#description;
|
|
2006
|
-
#namespaces;
|
|
2007
|
-
#bindings = [];
|
|
2008
|
-
#store = new Storage();
|
|
2009
|
-
#scheduleStore = new Storage();
|
|
2010
|
-
#registered = false;
|
|
2011
|
-
#scheduleRegistered = false;
|
|
2012
|
-
hasSchedule;
|
|
2013
|
-
/**
|
|
2014
|
-
* Run code on a schedule with the capability.
|
|
2015
|
-
*
|
|
2016
|
-
* @param schedule The schedule to run the code on
|
|
2017
|
-
* @returns
|
|
2018
|
-
*/
|
|
2019
|
-
OnSchedule = (schedule) => {
|
|
2020
|
-
const { name: name2, every, unit, run, startTime, completions } = schedule;
|
|
2021
|
-
this.hasSchedule = true;
|
|
2022
|
-
if (process.env.PEPR_WATCH_MODE === "true" || process.env.PEPR_MODE === "dev") {
|
|
2023
|
-
const newSchedule = {
|
|
2024
|
-
name: name2,
|
|
2025
|
-
every,
|
|
2026
|
-
unit,
|
|
2027
|
-
run,
|
|
2028
|
-
startTime,
|
|
2029
|
-
completions
|
|
2030
|
-
};
|
|
2031
|
-
this.#scheduleStore.onReady(() => {
|
|
2032
|
-
new OnSchedule(newSchedule).setStore(this.#scheduleStore);
|
|
2033
|
-
});
|
|
2034
|
-
}
|
|
1984
|
+
};
|
|
2035
1985
|
};
|
|
2036
|
-
getScheduleStore() {
|
|
2037
|
-
return this.#scheduleStore;
|
|
2038
|
-
}
|
|
2039
1986
|
/**
|
|
2040
|
-
*
|
|
2041
|
-
* between requests. Each capability has its own store, and the data is persisted in Kubernetes
|
|
2042
|
-
* in the `pepr-system` namespace.
|
|
1987
|
+
* Middleware for logging requests
|
|
2043
1988
|
*
|
|
2044
|
-
*
|
|
1989
|
+
* @param req the incoming request
|
|
1990
|
+
* @param res the outgoing response
|
|
1991
|
+
* @param next the next middleware function
|
|
2045
1992
|
*/
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
1993
|
+
static #logger(req, res, next) {
|
|
1994
|
+
const startTime = Date.now();
|
|
1995
|
+
res.on("finish", () => {
|
|
1996
|
+
const excludedRoutes = ["/healthz", "/metrics"];
|
|
1997
|
+
if (excludedRoutes.includes(req.originalUrl)) {
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
const elapsedTime = Date.now() - startTime;
|
|
2001
|
+
const message = {
|
|
2002
|
+
uid: req.body?.request?.uid,
|
|
2003
|
+
method: req.method,
|
|
2004
|
+
url: req.originalUrl,
|
|
2005
|
+
status: res.statusCode,
|
|
2006
|
+
duration: `${elapsedTime} ms`
|
|
2007
|
+
};
|
|
2008
|
+
logger_default.info(message);
|
|
2009
|
+
});
|
|
2010
|
+
next();
|
|
2011
|
+
}
|
|
2056
2012
|
/**
|
|
2057
|
-
*
|
|
2058
|
-
* between intervals. Each Schedule shares store, and the data is persisted in Kubernetes
|
|
2059
|
-
* in the `pepr-system` namespace.
|
|
2013
|
+
* Health check endpoint handler
|
|
2060
2014
|
*
|
|
2061
|
-
*
|
|
2015
|
+
* @param req the incoming request
|
|
2016
|
+
* @param res the outgoing response
|
|
2062
2017
|
*/
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
subscribe: this.#scheduleStore.subscribe,
|
|
2071
|
-
onReady: this.#scheduleStore.onReady
|
|
2072
|
-
};
|
|
2073
|
-
get bindings() {
|
|
2074
|
-
return this.#bindings;
|
|
2018
|
+
static #healthz(req, res) {
|
|
2019
|
+
try {
|
|
2020
|
+
res.send("OK");
|
|
2021
|
+
} catch (err) {
|
|
2022
|
+
logger_default.error(err, `Error processing health check`);
|
|
2023
|
+
res.status(500).send("Internal Server Error");
|
|
2024
|
+
}
|
|
2075
2025
|
}
|
|
2076
|
-
|
|
2077
|
-
|
|
2026
|
+
};
|
|
2027
|
+
|
|
2028
|
+
// src/lib/errors.ts
|
|
2029
|
+
var ErrorList = Object.values(OnError);
|
|
2030
|
+
function ValidateError(error = "") {
|
|
2031
|
+
if (!ErrorList.includes(error)) {
|
|
2032
|
+
throw new Error(`Invalid error: ${error}. Must be one of: ${ErrorList.join(", ")}`);
|
|
2078
2033
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// src/lib/processors/watch-processor.ts
|
|
2037
|
+
var import_kubernetes_fluent_client6 = require("kubernetes-fluent-client");
|
|
2038
|
+
|
|
2039
|
+
// src/lib/core/queue.ts
|
|
2040
|
+
var import_node_crypto = require("node:crypto");
|
|
2041
|
+
var Queue = class {
|
|
2042
|
+
#name;
|
|
2043
|
+
#uid;
|
|
2044
|
+
#queue = [];
|
|
2045
|
+
#pendingPromise = false;
|
|
2046
|
+
constructor(name2) {
|
|
2047
|
+
this.#name = name2;
|
|
2048
|
+
this.#uid = `${Date.now()}-${(0, import_node_crypto.randomBytes)(2).toString("hex")}`;
|
|
2081
2049
|
}
|
|
2082
|
-
|
|
2083
|
-
return this.#
|
|
2050
|
+
label() {
|
|
2051
|
+
return { name: this.#name, uid: this.#uid };
|
|
2084
2052
|
}
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2053
|
+
stats() {
|
|
2054
|
+
return {
|
|
2055
|
+
queue: this.label(),
|
|
2056
|
+
stats: {
|
|
2057
|
+
length: this.#queue.length
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2092
2060
|
}
|
|
2093
2061
|
/**
|
|
2094
|
-
*
|
|
2062
|
+
* Enqueue adds an item to the queue and returns a promise that resolves when the item is
|
|
2063
|
+
* reconciled.
|
|
2064
|
+
*
|
|
2065
|
+
* @param item The object to reconcile
|
|
2066
|
+
* @param type The watch phase requested for reconcile
|
|
2067
|
+
* @param reconcile The callback to enqueue for reconcile
|
|
2068
|
+
* @returns A promise that resolves when the object is reconciled
|
|
2095
2069
|
*/
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2070
|
+
enqueue(item, phase, reconcile) {
|
|
2071
|
+
const note = {
|
|
2072
|
+
queue: this.label(),
|
|
2073
|
+
item: {
|
|
2074
|
+
name: item.metadata?.name,
|
|
2075
|
+
namespace: item.metadata?.namespace,
|
|
2076
|
+
resourceVersion: item.metadata?.resourceVersion
|
|
2077
|
+
}
|
|
2078
|
+
};
|
|
2079
|
+
logger_default.debug(note, "Enqueueing");
|
|
2080
|
+
return new Promise((resolve, reject) => {
|
|
2081
|
+
this.#queue.push({ item, phase, callback: reconcile, resolve, reject });
|
|
2082
|
+
logger_default.debug(this.stats(), "Queue stats - push");
|
|
2083
|
+
return this.#dequeue();
|
|
2084
|
+
});
|
|
2085
|
+
}
|
|
2104
2086
|
/**
|
|
2105
|
-
*
|
|
2087
|
+
* Dequeue reconciles the next item in the queue
|
|
2106
2088
|
*
|
|
2107
|
-
* @
|
|
2089
|
+
* @returns A promise that resolves when the webapp is reconciled
|
|
2108
2090
|
*/
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2091
|
+
async #dequeue() {
|
|
2092
|
+
if (this.#pendingPromise) {
|
|
2093
|
+
logger_default.debug("Pending promise, not dequeuing");
|
|
2094
|
+
return false;
|
|
2095
|
+
}
|
|
2096
|
+
const element = this.#queue.shift();
|
|
2097
|
+
if (!element) {
|
|
2098
|
+
logger_default.debug("No element, not dequeuing");
|
|
2099
|
+
return false;
|
|
2100
|
+
}
|
|
2101
|
+
try {
|
|
2102
|
+
this.#pendingPromise = true;
|
|
2103
|
+
const note = {
|
|
2104
|
+
queue: this.label(),
|
|
2105
|
+
item: {
|
|
2106
|
+
name: element.item.metadata?.name,
|
|
2107
|
+
namespace: element.item.metadata?.namespace,
|
|
2108
|
+
resourceVersion: element.item.metadata?.resourceVersion
|
|
2109
|
+
}
|
|
2110
|
+
};
|
|
2111
|
+
logger_default.debug(note, "Reconciling");
|
|
2112
|
+
await element.callback(element.item, element.phase);
|
|
2113
|
+
logger_default.debug(note, "Reconciled");
|
|
2114
|
+
element.resolve();
|
|
2115
|
+
} catch (e) {
|
|
2116
|
+
logger_default.debug(`Error reconciling ${element.item.metadata.name}`, { error: e });
|
|
2117
|
+
element.reject(e);
|
|
2118
|
+
} finally {
|
|
2119
|
+
logger_default.debug(this.stats(), "Queue stats - shift");
|
|
2120
|
+
logger_default.debug("Resetting pending promise and dequeuing");
|
|
2121
|
+
this.#pendingPromise = false;
|
|
2122
|
+
await this.#dequeue();
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
|
|
2127
|
+
// src/lib/processors/watch-processor.ts
|
|
2128
|
+
var import_types = require("kubernetes-fluent-client/dist/fluent/types");
|
|
2129
|
+
var queues = {};
|
|
2130
|
+
function queueKey(obj) {
|
|
2131
|
+
const options = ["kind", "kindNs", "kindNsName", "global"];
|
|
2132
|
+
const d3fault = "kind";
|
|
2133
|
+
let strat = process.env.PEPR_RECONCILE_STRATEGY || d3fault;
|
|
2134
|
+
strat = options.includes(strat) ? strat : d3fault;
|
|
2135
|
+
const ns = obj.metadata?.namespace ?? "cluster-scoped";
|
|
2136
|
+
const kind3 = obj.kind ?? "UnknownKind";
|
|
2137
|
+
const name2 = obj.metadata?.name ?? "Unnamed";
|
|
2138
|
+
const lookup = {
|
|
2139
|
+
kind: `${kind3}`,
|
|
2140
|
+
kindNs: `${kind3}/${ns}`,
|
|
2141
|
+
kindNsName: `${kind3}/${ns}/${name2}`,
|
|
2142
|
+
global: "global"
|
|
2143
|
+
};
|
|
2144
|
+
return lookup[strat];
|
|
2145
|
+
}
|
|
2146
|
+
function getOrCreateQueue(obj) {
|
|
2147
|
+
const key = queueKey(obj);
|
|
2148
|
+
if (!queues[key]) {
|
|
2149
|
+
queues[key] = new Queue(key);
|
|
2150
|
+
}
|
|
2151
|
+
return queues[key];
|
|
2152
|
+
}
|
|
2153
|
+
var watchCfg = {
|
|
2154
|
+
resyncFailureMax: process.env.PEPR_RESYNC_FAILURE_MAX ? parseInt(process.env.PEPR_RESYNC_FAILURE_MAX, 10) : 5,
|
|
2155
|
+
resyncDelaySec: process.env.PEPR_RESYNC_DELAY_SECONDS ? parseInt(process.env.PEPR_RESYNC_DELAY_SECONDS, 10) : 5,
|
|
2156
|
+
lastSeenLimitSeconds: process.env.PEPR_LAST_SEEN_LIMIT_SECONDS ? parseInt(process.env.PEPR_LAST_SEEN_LIMIT_SECONDS, 10) : 300,
|
|
2157
|
+
relistIntervalSec: process.env.PEPR_RELIST_INTERVAL_SECONDS ? parseInt(process.env.PEPR_RELIST_INTERVAL_SECONDS, 10) : 600
|
|
2158
|
+
};
|
|
2159
|
+
var eventToPhaseMap = {
|
|
2160
|
+
["CREATE" /* CREATE */]: [import_types.WatchPhase.Added],
|
|
2161
|
+
["UPDATE" /* UPDATE */]: [import_types.WatchPhase.Modified],
|
|
2162
|
+
["CREATEORUPDATE" /* CREATE_OR_UPDATE */]: [import_types.WatchPhase.Added, import_types.WatchPhase.Modified],
|
|
2163
|
+
["DELETE" /* DELETE */]: [import_types.WatchPhase.Deleted],
|
|
2164
|
+
["*" /* ANY */]: [import_types.WatchPhase.Added, import_types.WatchPhase.Modified, import_types.WatchPhase.Deleted]
|
|
2165
|
+
};
|
|
2166
|
+
function setupWatch(capabilities, ignoredNamespaces) {
|
|
2167
|
+
capabilities.map(
|
|
2168
|
+
(capability) => capability.bindings.filter((binding) => binding.isWatch).forEach((bindingElement) => runBinding(bindingElement, capability.namespaces, ignoredNamespaces))
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
async function runBinding(binding, capabilityNamespaces, ignoredNamespaces) {
|
|
2172
|
+
const phaseMatch = eventToPhaseMap[binding.event] || eventToPhaseMap["*" /* ANY */];
|
|
2173
|
+
logger_default.debug({ watchCfg }, "Effective WatchConfig");
|
|
2174
|
+
const watchCallback = async (kubernetesObject, phase) => {
|
|
2175
|
+
if (phaseMatch.includes(phase)) {
|
|
2176
|
+
try {
|
|
2177
|
+
const filterMatch = filterNoMatchReason(binding, kubernetesObject, capabilityNamespaces, ignoredNamespaces);
|
|
2178
|
+
if (filterMatch !== "") {
|
|
2179
|
+
logger_default.debug(filterMatch);
|
|
2180
|
+
return;
|
|
2181
|
+
}
|
|
2182
|
+
if (binding.isFinalize) {
|
|
2183
|
+
await handleFinalizerRemoval(kubernetesObject);
|
|
2184
|
+
} else {
|
|
2185
|
+
await binding.watchCallback?.(kubernetesObject, phase);
|
|
2186
|
+
}
|
|
2187
|
+
} catch (e) {
|
|
2188
|
+
logger_default.error(e, "Error executing watch callback");
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
const handleFinalizerRemoval = async (kubernetesObject) => {
|
|
2193
|
+
if (!kubernetesObject.metadata?.deletionTimestamp) {
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
let shouldRemoveFinalizer = true;
|
|
2197
|
+
try {
|
|
2198
|
+
shouldRemoveFinalizer = await binding.finalizeCallback?.(kubernetesObject);
|
|
2199
|
+
} finally {
|
|
2200
|
+
const peprFinal = "pepr.dev/finalizer";
|
|
2201
|
+
const meta = kubernetesObject.metadata;
|
|
2202
|
+
const resource = `${meta.namespace || "ClusterScoped"}/${meta.name}`;
|
|
2203
|
+
if (shouldRemoveFinalizer === false) {
|
|
2204
|
+
logger_default.debug({ obj: kubernetesObject }, `Skipping removal of finalizer '${peprFinal}' from '${resource}'`);
|
|
2205
|
+
} else {
|
|
2206
|
+
await removeFinalizer(binding, kubernetesObject);
|
|
2207
|
+
}
|
|
2113
2208
|
}
|
|
2114
|
-
this.#registered = true;
|
|
2115
|
-
return this.#store;
|
|
2116
2209
|
};
|
|
2210
|
+
const watcher = (0, import_kubernetes_fluent_client6.K8s)(binding.model, binding.filters).Watch(async (obj, phase) => {
|
|
2211
|
+
logger_default.debug(obj, `Watch event ${phase} received`);
|
|
2212
|
+
if (binding.isQueue) {
|
|
2213
|
+
const queue = getOrCreateQueue(obj);
|
|
2214
|
+
await queue.enqueue(obj, phase, watchCallback);
|
|
2215
|
+
} else {
|
|
2216
|
+
await watchCallback(obj, phase);
|
|
2217
|
+
}
|
|
2218
|
+
}, watchCfg);
|
|
2219
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.GIVE_UP, (err) => {
|
|
2220
|
+
logger_default.error(err, "Watch failed after 5 attempts, giving up");
|
|
2221
|
+
process.exit(1);
|
|
2222
|
+
});
|
|
2223
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.CONNECT, (url) => logEvent(import_kubernetes_fluent_client6.WatchEvent.CONNECT, url));
|
|
2224
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.DATA_ERROR, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.DATA_ERROR, err.message));
|
|
2225
|
+
watcher.events.on(
|
|
2226
|
+
import_kubernetes_fluent_client6.WatchEvent.RECONNECT,
|
|
2227
|
+
(retryCount) => logEvent(import_kubernetes_fluent_client6.WatchEvent.RECONNECT, `Reconnecting after ${retryCount} attempt${retryCount === 1 ? "" : "s"}`)
|
|
2228
|
+
);
|
|
2229
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.RECONNECT_PENDING, () => logEvent(import_kubernetes_fluent_client6.WatchEvent.RECONNECT_PENDING));
|
|
2230
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.GIVE_UP, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.GIVE_UP, err.message));
|
|
2231
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.ABORT, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.ABORT, err.message));
|
|
2232
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.OLD_RESOURCE_VERSION, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.OLD_RESOURCE_VERSION, err));
|
|
2233
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.NETWORK_ERROR, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.NETWORK_ERROR, err.message));
|
|
2234
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.LIST_ERROR, (err) => logEvent(import_kubernetes_fluent_client6.WatchEvent.LIST_ERROR, err.message));
|
|
2235
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.LIST, (list) => logEvent(import_kubernetes_fluent_client6.WatchEvent.LIST, JSON.stringify(list, void 0, 2)));
|
|
2236
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.CACHE_MISS, (windowName) => {
|
|
2237
|
+
metricsCollector.incCacheMiss(windowName);
|
|
2238
|
+
});
|
|
2239
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.INIT_CACHE_MISS, (windowName) => {
|
|
2240
|
+
metricsCollector.initCacheMissWindow(windowName);
|
|
2241
|
+
});
|
|
2242
|
+
watcher.events.on(import_kubernetes_fluent_client6.WatchEvent.INC_RESYNC_FAILURE_COUNT, (retryCount) => {
|
|
2243
|
+
metricsCollector.incRetryCount(retryCount);
|
|
2244
|
+
});
|
|
2245
|
+
try {
|
|
2246
|
+
await watcher.start();
|
|
2247
|
+
} catch (err) {
|
|
2248
|
+
logger_default.error(err, "Error starting watch");
|
|
2249
|
+
process.exit(1);
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
function logEvent(event, message = "", obj) {
|
|
2253
|
+
const logMessage = `Watch event ${event} received${message ? `. ${message}.` : "."}`;
|
|
2254
|
+
if (obj) {
|
|
2255
|
+
logger_default.debug(obj, logMessage);
|
|
2256
|
+
} else {
|
|
2257
|
+
logger_default.debug(logMessage);
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
// src/lib/core/module.ts
|
|
2262
|
+
var PeprModule = class {
|
|
2263
|
+
#controller;
|
|
2117
2264
|
/**
|
|
2118
|
-
*
|
|
2119
|
-
* processed by Pepr. The action will be executed if the resource matches the specified kind and any
|
|
2120
|
-
* filters that are applied.
|
|
2265
|
+
* Create a new Pepr runtime
|
|
2121
2266
|
*
|
|
2122
|
-
* @param
|
|
2123
|
-
* @param
|
|
2124
|
-
* @
|
|
2267
|
+
* @param config The configuration for the Pepr runtime
|
|
2268
|
+
* @param capabilities The capabilities to be loaded into the Pepr runtime
|
|
2269
|
+
* @param opts Options for the Pepr runtime
|
|
2125
2270
|
*/
|
|
2126
|
-
|
|
2127
|
-
const
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
// If the kind is not specified, use the matched kind from the model
|
|
2134
|
-
kind: kind3 || matchedKind,
|
|
2135
|
-
event: "*" /* ANY */,
|
|
2136
|
-
filters: {
|
|
2137
|
-
name: "",
|
|
2138
|
-
namespaces: [],
|
|
2139
|
-
regexNamespaces: [],
|
|
2140
|
-
regexName: "",
|
|
2141
|
-
labels: {},
|
|
2142
|
-
annotations: {},
|
|
2143
|
-
deletionTimestamp: false
|
|
2144
|
-
}
|
|
2145
|
-
};
|
|
2146
|
-
const bindings = this.#bindings;
|
|
2147
|
-
const prefix = `${this.#name}: ${model.name}`;
|
|
2148
|
-
const commonChain = { WithLabel, WithAnnotation, WithDeletionTimestamp, Mutate, Validate, Watch, Reconcile, Alias };
|
|
2149
|
-
const isNotEmpty = (value) => Object.keys(value).length > 0;
|
|
2150
|
-
const log = (message, cbString) => {
|
|
2151
|
-
const filteredObj = (0, import_ramda9.pickBy)(isNotEmpty, binding.filters);
|
|
2152
|
-
logger_default.info(`${message} configured for ${binding.event}`, prefix);
|
|
2153
|
-
logger_default.info(filteredObj, prefix);
|
|
2154
|
-
logger_default.debug(cbString, prefix);
|
|
2155
|
-
};
|
|
2156
|
-
function Validate(validateCallback) {
|
|
2157
|
-
if (registerAdmission) {
|
|
2158
|
-
log("Validate Action", validateCallback.toString());
|
|
2159
|
-
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
2160
|
-
bindings.push({
|
|
2161
|
-
...binding,
|
|
2162
|
-
isValidate: true,
|
|
2163
|
-
validateCallback: async (req, logger = aliasLogger) => {
|
|
2164
|
-
logger_default.info(`Executing validate action with alias: ${binding.alias || "no alias provided"}`);
|
|
2165
|
-
return await validateCallback(req, logger);
|
|
2166
|
-
}
|
|
2167
|
-
});
|
|
2168
|
-
}
|
|
2169
|
-
return { Watch, Reconcile };
|
|
2170
|
-
}
|
|
2171
|
-
function Mutate(mutateCallback) {
|
|
2172
|
-
if (registerAdmission) {
|
|
2173
|
-
log("Mutate Action", mutateCallback.toString());
|
|
2174
|
-
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
2175
|
-
bindings.push({
|
|
2176
|
-
...binding,
|
|
2177
|
-
isMutate: true,
|
|
2178
|
-
mutateCallback: async (req, logger = aliasLogger) => {
|
|
2179
|
-
logger_default.info(`Executing mutation action with alias: ${binding.alias || "no alias provided"}`);
|
|
2180
|
-
await mutateCallback(req, logger);
|
|
2181
|
-
}
|
|
2182
|
-
});
|
|
2183
|
-
}
|
|
2184
|
-
return { Watch, Validate, Reconcile };
|
|
2185
|
-
}
|
|
2186
|
-
function Watch(watchCallback) {
|
|
2187
|
-
if (registerWatch) {
|
|
2188
|
-
log("Watch Action", watchCallback.toString());
|
|
2189
|
-
const aliasLogger = logger_default.child({ alias: binding.alias || "no alias provided" });
|
|
2190
|
-
bindings.push({
|
|
2191
|
-
...binding,
|
|
2192
|
-
isWatch: true,
|
|
2193
|
-
watchCallback: async (update, phase, logger = aliasLogger) => {
|
|
2194
|
-
logger_default.info(`Executing watch action with alias: ${binding.alias || "no alias provided"}`);
|
|
2195
|
-
await watchCallback(update, phase, logger);
|
|
2196
|
-
}
|
|
2197
|
-
});
|
|
2271
|
+
constructor({ description, pepr }, capabilities = [], opts = {}) {
|
|
2272
|
+
const config = (0, import_ramda9.clone)(pepr);
|
|
2273
|
+
config.description = description;
|
|
2274
|
+
ValidateError(config.onError);
|
|
2275
|
+
if (isBuildMode()) {
|
|
2276
|
+
if (!process.send) {
|
|
2277
|
+
throw new Error("process.send is not defined");
|
|
2198
2278
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
isWatch: true,
|
|
2208
|
-
isQueue: true,
|
|
2209
|
-
watchCallback: async (update, phase, logger = aliasLogger) => {
|
|
2210
|
-
logger_default.info(`Executing reconcile action with alias: ${binding.alias || "no alias provided"}`);
|
|
2211
|
-
await reconcileCallback(update, phase, logger);
|
|
2212
|
-
}
|
|
2279
|
+
const exportedCapabilities = [];
|
|
2280
|
+
for (const capability of capabilities) {
|
|
2281
|
+
exportedCapabilities.push({
|
|
2282
|
+
name: capability.name,
|
|
2283
|
+
description: capability.description,
|
|
2284
|
+
namespaces: capability.namespaces,
|
|
2285
|
+
bindings: capability.bindings,
|
|
2286
|
+
hasSchedule: capability.hasSchedule
|
|
2213
2287
|
});
|
|
2214
2288
|
}
|
|
2215
|
-
|
|
2289
|
+
process.send(exportedCapabilities);
|
|
2290
|
+
return;
|
|
2216
2291
|
}
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
};
|
|
2228
|
-
bindings.push(mutateBinding);
|
|
2229
|
-
}
|
|
2230
|
-
if (registerWatch) {
|
|
2231
|
-
const watchBinding = {
|
|
2232
|
-
...binding,
|
|
2233
|
-
isWatch: true,
|
|
2234
|
-
isFinalize: true,
|
|
2235
|
-
event: "UPDATE" /* UPDATE */,
|
|
2236
|
-
finalizeCallback: async (update, logger = aliasLogger) => {
|
|
2237
|
-
logger_default.info(`Executing finalize action with alias: ${binding.alias || "no alias provided"}`);
|
|
2238
|
-
return await finalizeCallback(update, logger);
|
|
2292
|
+
const controllerHooks = {
|
|
2293
|
+
beforeHook: opts.beforeHook,
|
|
2294
|
+
afterHook: opts.afterHook,
|
|
2295
|
+
onReady: () => {
|
|
2296
|
+
if (isWatchMode() || isDevMode()) {
|
|
2297
|
+
try {
|
|
2298
|
+
setupWatch(capabilities, resolveIgnoreNamespaces(pepr?.alwaysIgnore?.namespaces));
|
|
2299
|
+
} catch (e) {
|
|
2300
|
+
logger_default.error(e, "Error setting up watch");
|
|
2301
|
+
process.exit(1);
|
|
2239
2302
|
}
|
|
2240
|
-
}
|
|
2241
|
-
bindings.push(watchBinding);
|
|
2303
|
+
}
|
|
2242
2304
|
}
|
|
2243
|
-
}
|
|
2244
|
-
function InNamespace(...namespaces) {
|
|
2245
|
-
logger_default.debug(`Add namespaces filter ${namespaces}`, prefix);
|
|
2246
|
-
binding.filters.namespaces.push(...namespaces);
|
|
2247
|
-
return { ...commonChain, WithName, WithNameRegex };
|
|
2248
|
-
}
|
|
2249
|
-
function InNamespaceRegex(...namespaces) {
|
|
2250
|
-
logger_default.debug(`Add regex namespaces filter ${namespaces}`, prefix);
|
|
2251
|
-
binding.filters.regexNamespaces.push(...namespaces.map((regex) => regex.source));
|
|
2252
|
-
return { ...commonChain, WithName, WithNameRegex };
|
|
2253
|
-
}
|
|
2254
|
-
function WithDeletionTimestamp() {
|
|
2255
|
-
logger_default.debug("Add deletionTimestamp filter");
|
|
2256
|
-
binding.filters.deletionTimestamp = true;
|
|
2257
|
-
return commonChain;
|
|
2258
|
-
}
|
|
2259
|
-
function WithNameRegex(regexName) {
|
|
2260
|
-
logger_default.debug(`Add regex name filter ${regexName}`, prefix);
|
|
2261
|
-
binding.filters.regexName = regexName.source;
|
|
2262
|
-
return commonChain;
|
|
2263
|
-
}
|
|
2264
|
-
function WithName(name2) {
|
|
2265
|
-
logger_default.debug(`Add name filter ${name2}`, prefix);
|
|
2266
|
-
binding.filters.name = name2;
|
|
2267
|
-
return commonChain;
|
|
2268
|
-
}
|
|
2269
|
-
function WithLabel(key, value = "") {
|
|
2270
|
-
logger_default.debug(`Add label filter ${key}=${value}`, prefix);
|
|
2271
|
-
binding.filters.labels[key] = value;
|
|
2272
|
-
return commonChain;
|
|
2273
|
-
}
|
|
2274
|
-
function WithAnnotation(key, value = "") {
|
|
2275
|
-
logger_default.debug(`Add annotation filter ${key}=${value}`, prefix);
|
|
2276
|
-
binding.filters.annotations[key] = value;
|
|
2277
|
-
return commonChain;
|
|
2278
|
-
}
|
|
2279
|
-
function Alias(alias) {
|
|
2280
|
-
logger_default.debug(`Adding prefix alias ${alias}`, prefix);
|
|
2281
|
-
binding.alias = alias;
|
|
2282
|
-
return commonChain;
|
|
2283
|
-
}
|
|
2284
|
-
function bindEvent(event) {
|
|
2285
|
-
binding.event = event;
|
|
2286
|
-
return {
|
|
2287
|
-
...commonChain,
|
|
2288
|
-
InNamespace,
|
|
2289
|
-
InNamespaceRegex,
|
|
2290
|
-
WithName,
|
|
2291
|
-
WithNameRegex,
|
|
2292
|
-
WithDeletionTimestamp,
|
|
2293
|
-
Alias
|
|
2294
|
-
};
|
|
2295
|
-
}
|
|
2296
|
-
return {
|
|
2297
|
-
IsCreatedOrUpdated: () => bindEvent("CREATEORUPDATE" /* CREATE_OR_UPDATE */),
|
|
2298
|
-
IsCreated: () => bindEvent("CREATE" /* CREATE */),
|
|
2299
|
-
IsUpdated: () => bindEvent("UPDATE" /* UPDATE */),
|
|
2300
|
-
IsDeleted: () => bindEvent("DELETE" /* DELETE */)
|
|
2301
2305
|
};
|
|
2306
|
+
this.#controller = new Controller(config, capabilities, controllerHooks);
|
|
2307
|
+
if (opts.deferStart) {
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
this.start();
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Start the Pepr runtime manually.
|
|
2314
|
+
* Normally this is called automatically when the Pepr module is instantiated, but can be called manually if `deferStart` is set to `true` in the constructor.
|
|
2315
|
+
*
|
|
2316
|
+
* @param port
|
|
2317
|
+
*/
|
|
2318
|
+
start = (port = 3e3) => {
|
|
2319
|
+
this.#controller.startServer(port);
|
|
2302
2320
|
};
|
|
2303
2321
|
};
|
|
2304
2322
|
|