/
apiProxy.ts
1854 lines (1648 loc) · 57.9 KB
/
apiProxy.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This module was originally taken from the K8dash project before modifications.
*
* K8dash is licensed under Apache License 2.0.
*
* Copyright © 2020 Eric Herbrandson
* Copyright © 2020 Kinvolk GmbH
*/
import { OpPatch } from 'json-patch';
import _ from 'lodash';
import { decodeToken } from 'react-jwt';
import helpers, { getHeadlampAPIHeaders, isDebugVerbose } from '../../helpers';
import store from '../../redux/stores/store';
import {
findKubeconfigByClusterName,
getUserIdFromLocalStorage,
storeStatelessClusterKubeconfig,
} from '../../stateless/';
import { getToken, logout, setToken } from '../auth';
import { getCluster } from '../util';
import { KubeMetadata, KubeMetrics, KubeObjectInterface } from './cluster';
import { KubeToken } from './token';
// Uncomment the following lines to enable verbose debug logging in this module.
// import { debugVerbose } from '../../helpers';
// debugVerbose('k8s/apiProxy');
const BASE_HTTP_URL = helpers.getAppUrl();
const BASE_WS_URL = BASE_HTTP_URL.replace('http', 'ws');
const CLUSTERS_PREFIX = 'clusters';
const JSON_HEADERS = { Accept: 'application/json', 'Content-Type': 'application/json' };
const DEFAULT_TIMEOUT = 2 * 60 * 1000; // ms
const MIN_LIFESPAN_FOR_TOKEN_REFRESH = 10; // sec
let isTokenRefreshInProgress = false;
// @todo: Params is a confusing name for options, because params are also query params.
/**
* Options for the request.
*/
export interface RequestParams extends RequestInit {
/** Number of milliseconds to wait for a response. */
timeout?: number;
/** Is the request expected to receive JSON data? */
isJSON?: boolean;
/** Cluster context name. */
cluster?: string | null;
/** Whether to automatically log out the user if there is an authentication error. */
autoLogoutOnAuthError?: boolean;
}
export interface ClusterRequest {
/** The name of the cluster (has to be unique, or it will override an existing cluster) */
name?: string;
/** The cluster URL */
server?: string;
/** Whether the server's certificate should not be checked for validity */
insecureTLSVerify?: boolean;
/** The certificate authority data */
certificateAuthorityData?: string;
/** KubeConfig (base64 encoded)*/
kubeconfig?: string;
}
// @todo: QueryParamaters should be specific to different resources.
// Because some only support some paramaters.
/**
* QueryParamaters is a map of query parameters for the Kubernetes API.
*/
export interface QueryParameters {
/**
* Continue token for paging through large result sets.
*
* The continue option should be set when retrieving more results from the server.
* Since this value is server defined, clients may only use the continue value
* from a previous query result with identical query parameters
* (except for the value of continue) and the server may reject a continue value
* it does not recognize. If the specified continue value is no longer valid
* whether due to expiration (generally five to fifteen minutes) or a
* configuration change on the server, the server will respond with a
* 410 ResourceExpired error together with a continue token. If the client
* needs a consistent list, it must restart their list without the continue field.
* Otherwise, the client may send another list request with the token received
* with the 410 error, the server will respond with a list starting from the next
* key, but from the latest snapshot, which is inconsistent from the previous
* list results - objects that are created, modified, or deleted after the first
* list request will be included in the response, as long as their keys are after
* the "next key".
*
* This field is not supported when watch is true. Clients may start a watch from
* the last resourceVersion value returned by the server and not miss any modifications.
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#retrieving-large-results-sets-in-chunks
*/
continue?: string;
/**
* dryRun causes apiserver to simulate the request, and report whether the object would be modified.
* Can be '' or 'All'
*
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#dry-run
*/
dryRun?: string;
/**
* fieldSeletor restricts the list of returned objects by their fields. Defaults to everything.
*
* @see https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/
*/
fieldSelector?: string;
/**
* labelSelector restricts the list of returned objects by their labels. Defaults to everything.
*
* @see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#api
* @see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
*/
labelSelector?: string;
/**
* limit is a maximum number of responses to return for a list call.
*
* If more items exist, the server will set the continue field on the list
* metadata to a value that can be used with the same initial query to retrieve
* the next set of results. Setting a limit may return fewer than the requested
* amount of items (up to zero items) in the event all requested objects are
* filtered out and clients should only use the presence of the continue field
* to determine whether more results are available. Servers may choose not to
* support the limit argument and will return all of the available results.
* If limit is specified and the continue field is empty, clients may assume
* that no more results are available.
*
* This field is not supported if watch is true.
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#retrieving-large-results-sets-in-chunks
*/
limit?: string | number;
/**
* resourceVersion sets a constraint on what resource versions a request may be served from.
* Defaults to unset
*
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions
*/
resourceVersion?: string;
/**
* allowWatchBookmarks means watch events with type "BOOKMARK" will also be sent.
*
* Can be 'true'
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#watch-bookmarks
*/
allowWatchBookmarks?: string;
/**
* sendInitialEvents controls whether the server will send the events
* for a watch before sending the current list state.
*
* Can be 'true'.
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
*/
sendInitialEvents?: string;
/**
* The resource version to match.
*
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list
*/
resourceVersionMatch?: string;
/**
* If 'true', then the output is pretty printed.
* Can be '' or 'true'
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#output-options
*/
pretty?: string;
/**
* watch instead of a list or get, watch for changes to the requested object(s).
*
* Can be 1.
* @see https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes
*/
watch?: string;
}
/**
* Refreshes the token if it is about to expire.
*
* @param token - The token to refresh. For null token it just does nothing.
*
* @note Sets the token with `setToken` if the token is refreshed.
* @note Uses global `isTokenRefreshInProgress` to prevent multiple token
* refreshes at the same time.
*/
async function refreshToken(token: string | null) {
if (!token || isTokenRefreshInProgress) {
return;
}
// decode token
const decodedToken: any = decodeToken(token);
// return if the token doesn't have an expiry time
if (!decodedToken.exp) {
return;
}
// convert expiry seconds to date object
const expiry = decodedToken.exp;
const now = new Date().valueOf();
const expDate = new Date(0);
expDate.setUTCSeconds(expiry);
// calculate time to expiry in seconds
const diff = (expDate.valueOf() - now) / 1000;
// If the token is not about to expire return
// comparing the time to expiry with the minimum lifespan for a token both in seconds
if (diff > MIN_LIFESPAN_FOR_TOKEN_REFRESH) {
return;
}
const namespace =
(decodedToken && decodedToken['kubernetes.io'] && decodedToken['kubernetes.io']['namespace']) ||
'';
const serviceAccountName =
(decodedToken &&
decodedToken['kubernetes.io'] &&
decodedToken['kubernetes.io']['serviceaccount'] &&
decodedToken['kubernetes.io']['serviceaccount']['name']) ||
{};
const cluster = getCluster();
if (!cluster || namespace === '' || serviceAccountName === '') {
return;
}
if (isDebugVerbose('k8s/apiProxy@refreshToken')) {
console.debug('k8s/apiProxy@refreshToken', 'Refreshing token');
}
isTokenRefreshInProgress = true;
let tokenUrl = combinePath(BASE_HTTP_URL, `/${CLUSTERS_PREFIX}/${cluster}`);
tokenUrl = combinePath(
tokenUrl,
`api/v1/namespaces/${namespace}/serviceaccounts/${serviceAccountName}/token`
);
const tokenData = {
kind: 'TokenRequest',
apiVersion: 'authentication.k8s.io/v1',
metadata: { creationTimestamp: null },
spec: { expirationSeconds: 86400 },
};
try {
const response = await fetch(tokenUrl, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, ...JSON_HEADERS },
body: JSON.stringify(tokenData),
});
if (response.status === 201) {
const token: KubeToken = await response.json();
setToken(cluster, token.status.token);
}
isTokenRefreshInProgress = false;
} catch (err) {
console.error('Error refreshing token', err);
isTokenRefreshInProgress = false;
}
}
/**
* @returns Auth type of the cluster, or an empty string if the cluster is not found.
* It could return 'oidc' or '' for example.
*
* @param cluster - Name of the cluster.
*/
function getClusterAuthType(cluster: string): string {
const state = store.getState();
const authType: string = state.config?.clusters?.[cluster]?.['auth_type'] || '';
return authType;
}
/**
* Sends a request to the backend. If the useCluster parameter is true (which it is, by default), it will be
* treated as a request to the Kubernetes server of the currently defined (in the URL) cluster.
*
* @param path - The path to the API endpoint.
* @param params - Optional parameters for the request.
* @param autoLogoutOnAuthError - Whether to automatically log out the user if there is an authentication error.
* @param useCluster - Whether to use the current cluster for the request.
* @param queryParams - Optional query parameters for the request.
*
* @returns A Promise that resolves to the JSON response from the API server.
* @throws An ApiError if the response status is not ok.
*/
export async function request(
path: string,
params: RequestParams = {},
autoLogoutOnAuthError: boolean = true,
useCluster: boolean = true,
queryParams?: QueryParameters
) {
// @todo: This is a temporary way of getting the current cluster. We should improve it later.
const cluster = (useCluster && getCluster()) || '';
if (isDebugVerbose('k8s/apiProxy@request')) {
console.debug('k8s/apiProxy@request', { path, params, useCluster, queryParams });
}
return clusterRequest(path, { cluster, autoLogoutOnAuthError, ...params }, queryParams);
}
/**
* The options for `clusterRequest`.
*/
export interface ClusterRequestParams extends RequestParams {
cluster?: string | null;
autoLogoutOnAuthError?: boolean;
}
/**
* Sends a request to the backend. If the cluster is required in the params parameter, it will
* be used as a request to the respective Kubernetes server.
*
* @param path - The path to the API endpoint.
* @param params - Optional parameters for the request.
* @param queryParams - Optional query parameters for the k8s request.
*
* @returns A Promise that resolves to the JSON response from the API server.
* @throws An ApiError if the response status is not ok.
*/
export async function clusterRequest(
path: string,
params: ClusterRequestParams = {},
queryParams?: QueryParameters
) {
interface RequestHeaders {
Authorization?: string;
cluster?: string;
autoLogoutOnAuthError?: boolean;
[otherHeader: string]: any;
}
const {
timeout = DEFAULT_TIMEOUT,
cluster: paramsCluster,
autoLogoutOnAuthError = true,
isJSON = true,
...otherParams
} = params;
const userID = getUserIdFromLocalStorage();
const opts: { headers: RequestHeaders } = Object.assign({ headers: {} }, otherParams);
const cluster = paramsCluster || '';
let fullPath = path;
if (cluster) {
const token = getToken(cluster);
const kubeconfig = await findKubeconfigByClusterName(cluster);
if (kubeconfig !== null) {
opts.headers['KUBECONFIG'] = kubeconfig;
opts.headers['X-HEADLAMP-USER-ID'] = userID;
}
// Refresh service account token only if the cluster auth type is not OIDC
if (getClusterAuthType(cluster) !== 'oidc') {
await refreshToken(token);
}
if (!!token) {
opts.headers.Authorization = `Bearer ${token}`;
}
fullPath = combinePath(`/${CLUSTERS_PREFIX}/${cluster}`, path);
}
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
let url = combinePath(BASE_HTTP_URL, fullPath);
url += asQuery(queryParams);
const requestData = { signal: controller.signal, ...opts };
let response: Response = new Response(undefined, { status: 502, statusText: 'Unreachable' });
try {
response = await fetch(url, requestData);
} catch (err) {
if (err instanceof Error) {
if (err.name === 'AbortError') {
response = new Response(undefined, { status: 408, statusText: 'Request timed-out' });
}
}
} finally {
clearTimeout(id);
}
// The backend signals through this header that it wants a reload.
// See plugins.go
const headerVal = response.headers.get('X-Reload');
if (headerVal && headerVal.indexOf('reload') !== -1) {
window.location.reload();
}
// In case of OIDC auth if the token is about to expire the backend
// sends a refreshed token in the response header.
const newToken = response.headers.get('X-Authorization');
if (newToken) {
setToken(cluster, newToken);
}
if (!response.ok) {
const { status, statusText } = response;
if (autoLogoutOnAuthError && status === 401 && opts.headers.Authorization) {
console.error('Logging out due to auth error', { status, statusText, path });
logout();
}
let message = statusText;
try {
if (isJSON) {
const json = await response.json();
message += ` - ${json.message}`;
}
} catch (err) {
console.error(
'Unable to parse error json at url:',
url,
{ err },
'with request data:',
requestData
);
}
const error = new Error(message) as ApiError;
error.status = status;
return Promise.reject(error);
}
if (!isJSON) {
return Promise.resolve(response);
}
return response.json();
}
// @todo: there should be more specific args and types on StreamResultsCb than '...args: any'.
/** The callback that's called when some results are streamed in. */
export type StreamResultsCb = (...args: any[]) => void;
/** The callback that's called when there's an error streaming the results. */
export type StreamErrCb = (err: Error & { status?: number }, cancelStreamFunc?: () => void) => void;
type ApiFactoryReturn = ReturnType<typeof apiFactory> | ReturnType<typeof apiFactoryWithNamespace>;
// @todo: repeatStreamFunc could be improved for performance by remembering when a URL
// is 404 and not trying it again... and again.
/**
* Repeats a streaming function call across multiple API endpoints until a
* successful response is received or all endpoints have been exhausted.
*
* This is especially useful for Kubernetes beta APIs that then stabalize.
* So the APIs are available at different endpoints on different versions of Kubernetes.
*
* @param apiEndpoints - An array of API endpoint objects returned by the `apiFactory` function.
* @param funcName - The name of the streaming function to call on each endpoint.
* @param errCb - A callback function to handle errors that occur during the streaming function call.
* @param args - Additional arguments to pass to the streaming function.
*
* @returns A function that cancels the streaming function call.
*/
async function repeatStreamFunc(
apiEndpoints: ApiFactoryReturn[],
funcName: keyof ApiFactoryReturn,
errCb: StreamErrCb,
...args: any[]
) {
let isCancelled = false;
let streamCancel = () => {};
if (isDebugVerbose('k8s/apiProxy@repeatStreamFunc')) {
console.debug('k8s/apiProxy@repeatStreamFunc', { apiEndpoints, funcName, args });
}
function runStreamFunc(
endpointIndex: number,
funcName: string,
errCb: StreamErrCb,
...args: any[]
) {
const endpoint = apiEndpoints[endpointIndex];
const fullArgs = [...args];
let errCbIndex = 2;
if (endpoint.isNamespaced) {
++errCbIndex;
}
fullArgs.splice(errCbIndex, 0, errCb);
return endpoint[funcName as keyof ApiFactoryReturn](...fullArgs);
}
let endpointIndex = 0;
const cancel: StreamErrCb = async (err, cancelStream) => {
if (isCancelled) {
return;
}
if (err.status === 404 && endpointIndex < apiEndpoints.length) {
// Cancel current stream
if (cancelStream) {
cancelStream();
}
streamCancel = await runStreamFunc(endpointIndex++, funcName, cancel, ...args);
} else if (!!errCb) {
errCb(err, streamCancel);
}
};
streamCancel = await runStreamFunc(endpointIndex++, funcName, cancel, ...args);
return () => {
isCancelled = true;
streamCancel();
};
}
/**
* Repeats a factory method call across multiple API endpoints until a
* successful response is received or all endpoints have been exhausted.
*
* This is especially useful for Kubernetes beta APIs that then stabalize.
* @param apiEndpoints - An array of API endpoint objects returned by the `apiFactory` function.
* @param funcName - The name of the factory method to call on each endpoint.
*
* @returns A function that cancels the factory method call.
*/
function repeatFactoryMethod(apiEndpoints: ApiFactoryReturn[], funcName: keyof ApiFactoryReturn) {
return async (...args: Parameters<ApiFactoryReturn[typeof funcName]>) => {
for (let i = 0; i < apiEndpoints.length; i++) {
try {
const endpoint = apiEndpoints[i];
return await endpoint[funcName](...args);
} catch (err) {
// If the error is 404 and we still have other endpoints, then try the next one
if ((err as ApiError).status === 404 && i !== apiEndpoints.length - 1) {
continue;
}
throw err;
}
}
};
}
// @todo: in apiFactory, and multipleApiFactory use rather than 'args'...
// `group: string, version: string, resource: string`
/**
* Creates an API client for a single or multiple Kubernetes resources.
*
* @param args - The arguments to pass to either `singleApiFactory` or `multipleApiFactory`.
*
* @returns An API client for the specified Kubernetes resource(s).
*/
export function apiFactory(
...args: Parameters<typeof singleApiFactory> | Parameters<typeof multipleApiFactory>
) {
if (isDebugVerbose('k8s/apiProxy@apiFactory')) {
console.debug('k8s/apiProxy@apiFactory', { args });
}
if (args[0] instanceof Array) {
return multipleApiFactory(...(args as Parameters<typeof multipleApiFactory>));
}
return singleApiFactory(...(args as Parameters<typeof singleApiFactory>));
}
/**
* Creates an API endpoint object for multiple API endpoints.
* It first tries the first endpoint, then the second, and so on until it
* gets a successful response.
*
* @param args - An array of arguments to pass to the `singleApiFactory` function.
*
* @returns An API endpoint object.
*/
function multipleApiFactory(
...args: Parameters<typeof singleApiFactory>[]
): ReturnType<typeof singleApiFactory> {
if (isDebugVerbose('k8s/apiProxy@multipleApiFactory')) {
console.debug('k8s/apiProxy@multipleApiFactory', { args });
}
const apiEndpoints: ReturnType<typeof singleApiFactory>[] = args.map(apiArgs =>
singleApiFactory(...apiArgs)
);
return {
list: (
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => {
return repeatStreamFunc(apiEndpoints, 'list', errCb, cb, queryParams, cluster);
},
get: (
name: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => repeatStreamFunc(apiEndpoints, 'get', errCb, name, cb, queryParams, cluster),
post: repeatFactoryMethod(apiEndpoints, 'post'),
patch: repeatFactoryMethod(apiEndpoints, 'patch'),
put: repeatFactoryMethod(apiEndpoints, 'put'),
delete: repeatFactoryMethod(apiEndpoints, 'delete'),
isNamespaced: false,
apiInfo: args.map(apiArgs => ({
group: apiArgs[0],
version: apiArgs[1],
resource: apiArgs[2],
})),
};
}
/**
* Describes the API for a certain resource.
*/
export interface ApiInfo {
/** The API group. */
group: string;
/** The API version. */
version: string;
/** The resource name. */
resource: string;
}
// @todo: singleApiFactory should have a return type rather than just what it returns.
/**
* @returns An object with methods for interacting with a single API endpoint.
*
* @param group - The API group.
* @param version - The API version.
* @param resource - The API resource.
*/
function singleApiFactory(group: string, version: string, resource: string) {
if (isDebugVerbose('k8s/apiProxy@singleApiFactory')) {
console.debug('k8s/apiProxy@singleApiFactory', { group, version, resource });
}
const apiRoot = getApiRoot(group, version);
const url = `${apiRoot}/${resource}`;
return {
list: (
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => {
if (isDebugVerbose('k8s/apiProxy@singleApiFactory list')) {
console.debug('k8s/apiProxy@singleApiFactory list', { cluster, queryParams });
}
return streamResultsForCluster(url, { cb, errCb, cluster }, queryParams);
},
get: (
name: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => streamResult(url, name, cb, errCb, queryParams, cluster),
post: (body: KubeObjectInterface, queryParams?: QueryParameters, cluster?: string) =>
post(url + asQuery(queryParams), body, true, { cluster }),
put: (body: KubeObjectInterface, queryParams?: QueryParameters, cluster?: string) =>
put(`${url}/${body.metadata.name}` + asQuery(queryParams), body, true, { cluster }),
patch: (body: OpPatch[], name: string, queryParams?: QueryParameters, cluster?: string) =>
patch(`${url}/${name}` + asQuery({ ...queryParams, ...{ pretty: 'true' } }), body, true, {
cluster,
}),
delete: (name: string, queryParams?: QueryParameters, cluster?: string) =>
remove(`${url}/${name}` + asQuery(queryParams), { cluster }),
isNamespaced: false,
apiInfo: [{ group, version, resource }],
};
}
// @todo: just use args from simpleApiFactoryWithNamespace, rather than `args`?
// group: string, version: string, resource: string, includeScale: boolean = false
export function apiFactoryWithNamespace(
...args:
| Parameters<typeof simpleApiFactoryWithNamespace>
| Parameters<typeof multipleApiFactoryWithNamespace>
) {
if (args[0] instanceof Array) {
return multipleApiFactoryWithNamespace(
...(args as Parameters<typeof multipleApiFactoryWithNamespace>)
);
}
return simpleApiFactoryWithNamespace(
...(args as Parameters<typeof simpleApiFactoryWithNamespace>)
);
}
function multipleApiFactoryWithNamespace(
...args: Parameters<typeof simpleApiFactoryWithNamespace>[]
): ReturnType<typeof simpleApiFactoryWithNamespace> {
const apiEndpoints: ReturnType<typeof simpleApiFactoryWithNamespace>[] = args.map(apiArgs =>
simpleApiFactoryWithNamespace(...apiArgs)
);
return {
list: (
namespace: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => {
return repeatStreamFunc(apiEndpoints, 'list', errCb, namespace, cb, queryParams, cluster);
},
get: (
namespace: string,
name: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => repeatStreamFunc(apiEndpoints, 'get', errCb, namespace, name, cb, queryParams, cluster),
post: repeatFactoryMethod(apiEndpoints, 'post'),
patch: repeatFactoryMethod(apiEndpoints, 'patch'),
put: repeatFactoryMethod(apiEndpoints, 'put'),
delete: repeatFactoryMethod(apiEndpoints, 'delete'),
isNamespaced: true,
apiInfo: args.map(apiArgs => ({
group: apiArgs[0],
version: apiArgs[1],
resource: apiArgs[2],
})),
};
}
function simpleApiFactoryWithNamespace(
group: string,
version: string,
resource: string,
includeScale: boolean = false
) {
if (isDebugVerbose('k8s/apiProxy@simpleApiFactoryWithNamespace')) {
console.debug('k8s/apiProxy@simpleApiFactoryWithNamespace', {
group,
version,
resource,
includeScale,
});
}
const apiRoot = getApiRoot(group, version);
const results: {
scale?: ReturnType<typeof apiScaleFactory>;
// @todo: Need to write types for these properties instead.
[other: string]: any;
} = {
list: (
namespace: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => {
if (isDebugVerbose('k8s/apiProxy@simpleApiFactoryWithNamespace list')) {
console.debug('k8s/apiProxy@simpleApiFactoryWithNamespace list', { cluster, queryParams });
}
return streamResultsForCluster(url(namespace), { cb, errCb, cluster }, queryParams);
},
get: (
namespace: string,
name: string,
cb: StreamResultsCb,
errCb: StreamErrCb,
queryParams?: QueryParameters,
cluster?: string
) => streamResult(url(namespace), name, cb, errCb, queryParams, cluster),
post: (body: KubeObjectInterface, queryParams?: QueryParameters, cluster?: string) =>
post(url(body.metadata.namespace!) + asQuery(queryParams), body, true, { cluster }),
patch: (
body: OpPatch[],
namespace: string,
name: string,
queryParams?: QueryParameters,
cluster?: string
) =>
patch(
`${url(namespace)}/${name}` + asQuery({ ...queryParams, ...{ pretty: 'true' } }),
body,
true,
{ cluster }
),
put: (body: KubeObjectInterface, queryParams?: QueryParameters, cluster?: string) =>
put(
`${url(body.metadata.namespace!)}/${body.metadata.name}` + asQuery(queryParams),
body,
true,
{ cluster }
),
delete: (namespace: string, name: string, queryParams?: QueryParameters, cluster?: string) =>
remove(`${url(namespace)}/${name}` + asQuery(queryParams), { cluster }),
isNamespaced: true,
apiInfo: [{ group, version, resource }],
};
if (includeScale) {
results.scale = apiScaleFactory(apiRoot, resource);
}
return results;
function url(namespace: string) {
return namespace ? `${apiRoot}/namespaces/${namespace}/${resource}` : `${apiRoot}/${resource}`;
}
}
/**
* Converts k8s queryParams to a URL query string.
*
* @param queryParams - The k8s API query parameters to convert.
* @returns The query string (starting with '?'), or empty string.
*/
function asQuery(queryParams?: QueryParameters): string {
if (queryParams === undefined) {
return '';
}
let newQueryParams;
if (typeof queryParams.limit === 'number' || typeof queryParams.limit === 'string') {
newQueryParams = {
...queryParams,
limit:
typeof queryParams.limit === 'number' ? queryParams.limit.toString() : queryParams.limit,
};
} else {
newQueryParams = { ..._.omit(queryParams, 'limit') };
}
return !!newQueryParams && !!Object.keys(newQueryParams).length
? '?' + new URLSearchParams(newQueryParams).toString()
: '';
}
async function resourceDefToApiFactory(
resourceDef: KubeObjectInterface,
clusterName?: string
): Promise<ApiFactoryReturn> {
interface APIResourceList {
resources: {
kind: string;
namespaced: boolean;
singularName: string;
name: string;
}[];
[other: string]: any;
}
if (isDebugVerbose('k8s/apiProxy@resourceDefToApiFactory')) {
console.debug('k8s/apiProxy@resourceDefToApiFactory', { resourceDef });
}
if (!resourceDef.kind) {
throw new Error(`Cannot handle unknown resource kind: ${resourceDef.kind}`);
}
if (!resourceDef.apiVersion) {
throw new Error(`Definition ${resourceDef.kind} has no apiVersion`);
}
let [apiGroup, apiVersion] = resourceDef.apiVersion.split('/');
// There may not be an API group [1], which means that the apiGroup variable will
// actually hold the apiVersion, so we switch them.
// [1] https://kubernetes.io/docs/reference/using-api/#api-groups
if (!!apiGroup && !apiVersion) {
apiVersion = apiGroup;
apiGroup = '';
}
if (!apiVersion) {
throw new Error(`apiVersion has no version string: ${resourceDef.apiVersion}`);
}
const cluster = clusterName || getCluster() || '';
// Get details about this resource. We could avoid this for known resources, but
// this way we always get the right plural name and we also avoid eventually getting
// the wrong "known" resource because e.g. there can be CustomResources with the same
// kind as a known resource.
const apiPrefix = !!apiGroup ? 'apis' : 'api';
const apiResult: APIResourceList = await clusterRequest(
`/${apiPrefix}/${resourceDef.apiVersion}`,
{
cluster,
autoLogoutOnAuthError: false,
}
);
if (!apiResult) {
throw new Error(`Unkown apiVersion: ${resourceDef.apiVersion}`);
}
// Get resource
const resource = apiResult.resources?.find(({ kind }) => kind === resourceDef.kind);
if (!resource) {
throw new Error(`Unkown resource kind: ${resourceDef.kind}`);
}
const hasNamespace = !!resource.namespaced;
let factoryFunc: typeof apiFactory | typeof apiFactoryWithNamespace = apiFactory;
if (!!hasNamespace) {
factoryFunc = apiFactoryWithNamespace;
}
return factoryFunc(apiGroup, apiVersion, resource.name);
}
function getApiRoot(group: string, version: string) {
return group ? `/apis/${group}/${version}` : `api/${version}`;
}
function apiScaleFactory(apiRoot: string, resource: string) {
return {
get: (namespace: string, name: string, clusterName?: string) => {
const cluster = clusterName || getCluster() || '';
return clusterRequest(url(namespace, name), { cluster });
},
put: (body: { metadata: KubeMetadata; spec: { replicas: number } }, clusterName?: string) => {
const cluster = clusterName || getCluster() || '';
return put(url(body.metadata.namespace!, body.metadata.name), body, undefined, { cluster });
},
};
function url(namespace: string, name: string) {
return `${apiRoot}/namespaces/${namespace}/${resource}/${name}/scale`;
}
}
export function post(
url: string,
json: JSON | object | KubeObjectInterface,
autoLogoutOnAuthError: boolean = true,
options: ClusterRequestParams = {}
) {
const { cluster: clusterName, ...requestOptions } = options;
const body = JSON.stringify(json);
const cluster = clusterName || getCluster() || '';
return clusterRequest(url, {
method: 'POST',
body,
headers: JSON_HEADERS,
cluster,
autoLogoutOnAuthError,
...requestOptions,
});
}
export function patch(
url: string,
json: any,
autoLogoutOnAuthError = true,
options: ClusterRequestParams = {}
) {
const { cluster: clusterName, ...requestOptions } = options;
const body = JSON.stringify(json);
const cluster = clusterName || getCluster() || '';
const opts = {
method: 'PATCH',
body,
headers: { ...JSON_HEADERS, 'Content-Type': 'application/json-patch+json' },
autoLogoutOnAuthError,
cluster,
...requestOptions,
};
return clusterRequest(url, opts);
}
export function put(
url: string,
json: Partial<KubeObjectInterface>,
autoLogoutOnAuthError = true,
requestOptions: ClusterRequestParams = {}
) {
const body = JSON.stringify(json);
const { cluster: clusterName, ...restOptions } = requestOptions;
const opts = {
method: 'PUT',
body,
headers: JSON_HEADERS,
autoLogoutOnAuthError,
cluster: clusterName || getCluster() || '',
...restOptions,
};
return clusterRequest(url, opts);
}
export function remove(url: string, requestOptions: ClusterRequestParams = {}) {
const { cluster: clusterName, ...restOptions } = requestOptions;