-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
kube-object.store.ts
383 lines (304 loc) · 10.5 KB
/
kube-object.store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import type { ClusterContext } from "./components/context";
import { action, computed, observable, reaction, when } from "mobx";
import { autobind } from "./utils";
import { KubeObject, KubeStatus } from "./api/kube-object";
import { IKubeWatchEvent } from "./api/kube-watch-api";
import { ItemStore } from "./item.store";
import { apiManager } from "./api/api-manager";
import { IKubeApiQueryParams, KubeApi, parseKubeApi } from "./api/kube-api";
import { KubeJsonApiData } from "./api/kube-json-api";
export interface KubeObjectStoreLoadingParams {
namespaces: string[];
api?: KubeApi;
}
@autobind()
export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemStore<T> {
@observable static defaultContext: ClusterContext; // TODO: support multiple cluster contexts
abstract api: KubeApi<T>;
public readonly limit?: number;
public readonly bufferSize: number = 50000;
private loadedNamespaces: string[] = [];
contextReady = when(() => Boolean(this.context));
constructor() {
super();
this.bindWatchEventsUpdater();
}
get context(): ClusterContext {
return KubeObjectStore.defaultContext;
}
@computed get contextItems(): T[] {
const namespaces = this.context?.contextNamespaces ?? [];
return this.items.filter(item => {
const itemNamespace = item.getNs();
return !itemNamespace /* cluster-wide */ || namespaces.includes(itemNamespace);
});
}
getTotalCount(): number {
return this.contextItems.length;
}
get query(): IKubeApiQueryParams {
const { limit } = this;
if (!limit) {
return {};
}
return { limit };
}
getStatuses?(items: T[]): Record<string, number>;
getAllByNs(namespace: string | string[], strict = false): T[] {
const namespaces: string[] = [].concat(namespace);
if (namespaces.length) {
return this.items.filter(item => namespaces.includes(item.getNs()));
} else if (!strict) {
return this.items;
}
}
getById(id: string) {
return this.items.find(item => item.getId() === id);
}
getByName(name: string, namespace?: string): T {
return this.items.find(item => {
return item.getName() === name && (
namespace ? item.getNs() === namespace : true
);
});
}
getByPath(path: string): T {
return this.items.find(item => item.selfLink === path);
}
getByLabel(labels: string[] | { [label: string]: string }): T[] {
if (Array.isArray(labels)) {
return this.items.filter((item: T) => {
const itemLabels = item.getLabels();
return labels.every(label => itemLabels.includes(label));
});
} else {
return this.items.filter((item: T) => {
const itemLabels = item.metadata.labels || {};
return Object.entries(labels)
.every(([key, value]) => itemLabels[key] === value);
});
}
}
protected async loadItems({ namespaces, api }: KubeObjectStoreLoadingParams): Promise<T[]> {
if (this.context?.cluster.isAllowedResource(api.kind)) {
if (!api.isNamespaced) {
return api.list({}, this.query);
}
const isLoadingAll = this.context.allNamespaces?.length > 1
&& this.context.cluster.accessibleNamespaces.length === 0
&& this.context.allNamespaces.every(ns => namespaces.includes(ns));
if (isLoadingAll) {
this.loadedNamespaces = [];
return api.list({}, this.query);
} else {
this.loadedNamespaces = namespaces;
return Promise // load resources per namespace
.all(namespaces.map(namespace => api.list({ namespace })))
.then(items => items.flat());
}
}
return [];
}
protected filterItemsOnLoad(items: T[]) {
return items;
}
@action
async loadAll(options: { namespaces?: string[], merge?: boolean } = {}): Promise<void | T[]> {
await this.contextReady;
this.isLoading = true;
try {
const {
namespaces = this.context.allNamespaces, // load all namespaces by default
merge = true, // merge loaded items or return as result
} = options;
const items = await this.loadItems({ namespaces, api: this.api });
if (merge) {
this.mergeItems(items, { replace: false });
} else {
this.mergeItems(items, { replace: true });
}
this.isLoaded = true;
this.failedLoading = false;
return items;
} catch (error) {
console.error("Loading store items failed", { error, store: this });
this.resetOnError(error);
this.failedLoading = true;
} finally {
this.isLoading = false;
}
}
@action
reloadAll(opts: { force?: boolean, namespaces?: string[], merge?: boolean } = {}) {
const { force = false, ...loadingOptions } = opts;
if (this.isLoading || (this.isLoaded && !force)) {
return;
}
return this.loadAll(loadingOptions);
}
@action
protected mergeItems(partialItems: T[], { replace = false, updateStore = true, sort = true, filter = true } = {}): T[] {
let items = partialItems;
// update existing items
if (!replace) {
const namespaces = partialItems.map(item => item.getNs());
items = [
...this.items.filter(existingItem => !namespaces.includes(existingItem.getNs())),
...partialItems,
];
}
if (filter) items = this.filterItemsOnLoad(items);
if (sort) items = this.sortItems(items);
if (updateStore) this.items.replace(items);
return items;
}
protected resetOnError(error: any) {
if (error) this.reset();
}
protected async loadItem(params: { name: string; namespace?: string }): Promise<T> {
return this.api.get(params);
}
@action
async load(params: { name: string; namespace?: string }): Promise<T> {
const { name, namespace } = params;
let item = this.getByName(name, namespace);
if (!item) {
item = await this.loadItem(params);
const newItems = this.sortItems([...this.items, item]);
this.items.replace(newItems);
}
return item;
}
@action
async loadFromPath(resourcePath: string) {
const { namespace, name } = parseKubeApi(resourcePath);
return this.load({ name, namespace });
}
protected async createItem(params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> {
return this.api.create(params, data);
}
async create(params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> {
const newItem = await this.createItem(params, data);
const items = this.sortItems([...this.items, newItem]);
this.items.replace(items);
return newItem;
}
async update(item: T, data: Partial<T>): Promise<T> {
const newItem = await item.update<T>(data);
const index = this.items.findIndex(item => item.getId() === newItem.getId());
this.items.splice(index, 1, newItem);
return newItem;
}
async remove(item: T) {
await item.delete();
this.items.remove(item);
this.selectedItemsIds.delete(item.getId());
}
async removeSelectedItems() {
return Promise.all(this.selectedItems.map(this.remove));
}
// collect items from watch-api events to avoid UI blowing up with huge streams of data
protected eventsBuffer = observable.array<IKubeWatchEvent<KubeJsonApiData>>([], { deep: false });
protected bindWatchEventsUpdater(delay = 1000) {
reaction(() => this.eventsBuffer.length, this.updateFromEventsBuffer, {
delay
});
}
getSubscribeApis(): KubeApi[] {
return [this.api];
}
subscribe(apis = this.getSubscribeApis()) {
const abortController = new AbortController();
const namespaces = [...this.loadedNamespaces];
if (this.context.cluster?.isGlobalWatchEnabled && namespaces.length === 0) {
apis.forEach(api => this.watchNamespace(api, "", abortController));
} else {
apis.forEach(api => {
this.loadedNamespaces.forEach((namespace) => {
this.watchNamespace(api, namespace, abortController);
});
});
}
return () => {
abortController.abort();
};
}
private watchNamespace(api: KubeApi<T>, namespace: string, abortController: AbortController) {
let timedRetry: NodeJS.Timeout;
abortController.signal.addEventListener("abort", () => clearTimeout(timedRetry));
const callback = (data: IKubeWatchEvent, error: any) => {
if (!this.isLoaded || abortController.signal.aborted) return;
if (error instanceof Response) {
if (error.status === 404) {
// api has gone, let's not retry
return;
} else { // not sure what to do, best to retry
if (timedRetry) clearTimeout(timedRetry);
timedRetry = setTimeout(() => {
api.watch({
namespace,
abortController,
callback
});
}, 5000);
}
} else if (error instanceof KubeStatus && error.code === 410) {
if (timedRetry) clearTimeout(timedRetry);
// resourceVersion has gone, let's try to reload
timedRetry = setTimeout(() => {
(namespace === "" ? this.loadAll({ merge: false }) : this.loadAll({namespaces: [namespace]})).then(() => {
api.watch({
namespace,
abortController,
callback
});
});
}, 1000);
} else if(error) { // not sure what to do, best to retry
if (timedRetry) clearTimeout(timedRetry);
timedRetry = setTimeout(() => {
api.watch({
namespace,
abortController,
callback
});
}, 5000);
}
if (data) {
this.eventsBuffer.push(data);
}
};
api.watch({
namespace,
abortController,
callback: (data, error) => callback(data, error)
});
}
@action
protected updateFromEventsBuffer() {
const items = this.items.toJS();
for (const { type, object } of this.eventsBuffer.clear()) {
const index = items.findIndex(item => item.getId() === object.metadata?.uid);
const item = items[index];
const api = apiManager.getApiByKind(object.kind, object.apiVersion);
switch (type) {
case "ADDED":
case "MODIFIED":
const newItem = new api.objectConstructor(object);
if (!item) {
items.push(newItem);
} else {
items[index] = newItem;
}
break;
case "DELETED":
if (item) {
items.splice(index, 1);
}
break;
}
}
// update items
this.items.replace(this.sortItems(items.slice(-this.bufferSize)));
}
}