-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathinstance.ts
More file actions
569 lines (489 loc) · 14.1 KB
/
instance.ts
File metadata and controls
569 lines (489 loc) · 14.1 KB
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
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AxiosError, AxiosInstance } from 'axios';
import saveAs from 'file-saver';
import { Observable, concat, from, ignoreElements } from 'rxjs';
import axios, {
redirectOn401,
registerErrorToastInterceptor,
} from '../utils/axios';
import waitForPolyfill from '../utils/eventsource-polyfill';
import logtail from '../utils/logtail';
import uri from '../utils/uri';
import { useSbaConfig } from '@/sba-config';
import { actuatorMimeTypes } from '@/services/spring-mime-types';
import { transformToJSON } from '@/utils/transformToJSON';
// Extend AxiosRequestConfig to allow suppressToast
declare module 'axios' {
interface AxiosRequestConfig {
suppressToast?: boolean | ((error: AxiosError) => boolean);
}
}
export type FetchMetricOptions = {
suppressToast?: boolean | ((error: AxiosError) => boolean);
};
const isInstanceActuatorRequest = (url: string) =>
url.match(/^instances[/][^/]+[/]actuator([/].*)?$/);
class Instance {
public readonly id: string;
private readonly axios: AxiosInstance;
public registration: Registration;
public endpoints: Endpoint[] = [];
public availableMetrics: string[] = [];
public tags: { [key: string]: string }[];
public statusTimestamp: string;
public buildVersion: string;
public statusInfo: StatusInfo;
constructor({ id, ...instance }: InstanceData) {
Object.assign(this, instance);
this.id = id;
this.axios = axios.create({
withCredentials: true,
baseURL: uri`instances/${this.id}`,
headers: { Accept: actuatorMimeTypes.join(',') },
});
this.axios.interceptors.response.use(
(response) => response,
redirectOn401(
(error) =>
!isInstanceActuatorRequest(error.config.baseURL + error.config.url),
),
);
registerErrorToastInterceptor(this.axios);
}
get metadata() {
return this.registration.metadata;
}
get metadataParsed() {
const metadata = this.registration.metadata || {};
return transformToJSON(metadata, 'LAX');
}
get isUnregisterable() {
return this.registration.source === 'http-api';
}
static async fetchEvents() {
return axios.get(uri`instances/events`, {
headers: { Accept: 'application/json' },
});
}
static getEventStream() {
return concat(
from(waitForPolyfill()).pipe(ignoreElements()),
Observable.create((observer) => {
const eventSource = new EventSource('instances/events');
eventSource.onmessage = (message) =>
observer.next({
...message,
data: JSON.parse(message.data),
});
eventSource.onerror = (err) => observer.error(err);
return () => {
eventSource.close();
};
}),
);
}
static async get(id: string) {
return axios.get(uri`instances/${id}`, {
headers: { Accept: 'application/json' },
transformResponse(data: string) {
if (!data) {
return data;
}
const instance = JSON.parse(data);
return new Instance(instance);
},
});
}
private static _toMBeans(data: string) {
if (!data) {
return data;
}
const raw = JSON.parse(data);
return Object.entries(raw.value).map(([domain, mBeans]) => ({
domain,
mBeans: Object.entries(mBeans as Record<string, any>).map(
([descriptor, mBean]) => ({
descriptor: descriptor,
...mBean,
}),
),
}));
}
showUrl() {
const sbaConfig = useSbaConfig();
if (sbaConfig.uiSettings.hideInstanceUrl) {
return false;
}
const hideUrlMetadata = this.registration.metadata?.['hide-url'];
return hideUrlMetadata !== 'true';
}
isUrlDisabled() {
const sbaConfig = useSbaConfig();
if (sbaConfig.uiSettings.disableInstanceUrl) {
return true;
}
const disableUrl = this.registration.metadata?.['disable-url'];
return disableUrl === 'true';
}
hasEndpoint(endpointId: string): boolean {
return this.endpoints.some((endpoint) => endpoint.id === endpointId);
}
async unregister() {
return this.axios.delete('', {
headers: { Accept: 'application/json' },
});
}
async fetchInfo() {
return this.axios.get(uri`actuator/info`);
}
async fetchMetrics() {
const response = await this.axios.get(uri`actuator/metrics`);
this.availableMetrics = response?.data?.names ?? [];
return response;
}
async fetchMetric(
metric: string,
tags?: Record<string, string>,
options?: FetchMetricOptions,
) {
if (this.availableMetrics.length === 0) {
try {
await this.fetchMetrics();
} catch (e) {
console.error('Available metrics could not be determined.', e);
}
}
if (!this.availableMetrics.includes(metric)) {
console.warn(
`Metric '${metric}' seems not to be available on instance '${this.id}'.`,
);
return;
}
const params = new URLSearchParams();
if (tags) {
let firstElementDuplicated = false;
Object.entries(tags)
.filter(([, value]) => typeof value !== 'undefined' && value !== null)
.forEach(([name, value]) => {
params.append('tag', `${name}:${value}`);
if (!firstElementDuplicated) {
// workaround for tags that contains comma
// take a look at https://github.com/spring-projects/spring-framework/issues/23820#issuecomment-543087878
// If there is single tag specified and name or value contains comma then it will be incorrectly split into several parts
// To bypass it we duplicate first tag.
params.append('tag', `${name}:${value}`);
firstElementDuplicated = true;
}
});
}
return this.axios.get(uri`actuator/metrics/${metric}`, {
params,
suppressToast: options?.suppressToast,
});
}
async fetchHealth() {
return await this.axios.get(uri`actuator/health`, {
validateStatus: null,
});
}
async fetchHealthGroup(groupName: string) {
return await this.axios.get(uri`actuator/health/${groupName}`, {
validateStatus: null,
});
}
async fetchEnv(name?: string) {
return this.axios.get(uri`actuator/env/${name || ''}`);
}
async fetchConfigprops() {
return this.axios.get(uri`actuator/configprops`);
}
async hasEnvManagerSupport() {
const response = await this.axios.options(uri`actuator/env`);
return (
response.headers['allow'] && response.headers['allow'].includes('POST')
);
}
async resetEnv() {
return this.axios.delete(uri`actuator/env`);
}
async setEnv(name: string, value: string) {
return this.axios.post(
uri`actuator/env`,
{ name, value },
{
headers: { 'Content-Type': 'application/json' },
},
);
}
async refreshContext() {
return this.axios.post(uri`actuator/refresh`);
}
async busRefreshContext() {
return this.axios.post(uri`actuator/busrefresh`);
}
async fetchLiquibase() {
return this.axios.get(uri`actuator/liquibase`);
}
async fetchScheduledTasks() {
return this.axios.get(uri`actuator/scheduledtasks`);
}
async fetchGatewayGlobalFilters() {
return this.axios.get(uri`actuator/gateway/globalfilters`);
}
async addGatewayRoute(route: { id: string; [key: string]: any }) {
return this.axios.post(uri`actuator/gateway/routes/${route.id}`, route, {
headers: { 'Content-Type': 'application/json' },
});
}
async fetchGatewayRoutes() {
return this.axios.get(uri`actuator/gateway/routes`);
}
async deleteGatewayRoute(routeId: string) {
return this.axios.delete(uri`actuator/gateway/routes/${routeId}`);
}
async refreshGatewayRoutesCache() {
return this.axios.post(uri`actuator/gateway/refresh`);
}
async fetchCaches() {
return this.axios.get(uri`actuator/caches`);
}
async clearCaches() {
return this.axios.delete(uri`actuator/caches`);
}
async clearCache(name: string, cacheManager?: string) {
return this.axios.delete(uri`actuator/caches/${name}`, {
params: { cacheManager: cacheManager },
});
}
async fetchFlyway() {
return this.axios.get(uri`actuator/flyway`);
}
async fetchLoggers() {
return this.axios.get(uri`actuator/loggers`);
}
async configureLogger(name: string, level: string | null) {
await this.axios.post(
uri`actuator/loggers/${name}`,
level === null ? {} : { configuredLevel: level },
{
headers: { 'Content-Type': 'application/json' },
},
);
}
async fetchHttptrace() {
return this.axios.get(uri`actuator/httptrace`);
}
async fetchHttpExchanges() {
return this.axios.get(uri`actuator/httpexchanges`);
}
async fetchBeans() {
return this.axios.get(uri`actuator/beans`);
}
async fetchConditions() {
return this.axios.get(uri`actuator/conditions`);
}
async fetchThreaddump() {
return this.axios.get(uri`actuator/threaddump`);
}
async downloadThreaddump() {
const res = await this.axios.get(uri`actuator/threaddump`, {
headers: { Accept: 'text/plain' },
});
const blob = new Blob([res.data], { type: 'text/plain;charset=utf-8' });
saveAs(blob, this.registration.name + '-threaddump.txt');
}
async fetchAuditevents({
after,
type,
principal,
}: {
after: Date;
type?: string;
principal?: string;
}) {
return this.axios.get(uri`actuator/auditevents`, {
params: {
after: after.toISOString(),
type: type,
principal: principal,
},
});
}
async fetchSessionsByUsername(username?: string) {
return this.axios.get(uri`actuator/sessions`, {
params: {
username: username,
},
});
}
async fetchSession(sessionId: string) {
return this.axios.get(uri`actuator/sessions/${sessionId}`);
}
async deleteSession(sessionId: string) {
return this.axios.delete(uri`actuator/sessions/${sessionId}`);
}
async fetchStartup() {
const optionsResponse = await this.axios.options(uri`actuator/startup`);
if (
optionsResponse.headers.allow &&
optionsResponse.headers.allow.includes('GET')
) {
return this.axios.get(uri`actuator/startup`);
}
return this.axios.post(uri`actuator/startup`);
}
streamLogfile(interval: number) {
return logtail(
(opt) => this.axios.get(uri`actuator/logfile`, opt),
interval,
);
}
async listMBeans() {
return this.axios.get(uri`actuator/jolokia/list`, {
headers: { Accept: 'application/json' },
params: { canonicalNaming: false },
transformResponse: Instance._toMBeans,
});
}
async readMBeanAttributes(domain: string, mBean: string) {
const body = {
type: 'read',
mbean: `${domain}:${mBean}`,
config: { ignoreErrors: true },
};
return this.axios.post(uri`actuator/jolokia`, body, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
}
async writeMBeanAttribute(
domain: string,
mBean: string,
attribute: string,
value: any,
) {
const body = {
type: 'write',
mbean: `${domain}:${mBean}`,
attribute,
value,
};
return this.axios.post(uri`actuator/jolokia`, body, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
}
async invokeMBeanOperation(
domain: string,
mBean: string,
operation: string,
args: any[],
) {
const body = {
type: 'exec',
mbean: `${domain}:${mBean}`,
operation,
arguments: args,
};
return this.axios.post(uri`actuator/jolokia`, body, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
}
async fetchMappings() {
return this.axios.get(uri`actuator/mappings`);
}
async fetchQuartzJobs() {
return this.axios.get(uri`actuator/quartz/jobs`, {
headers: { Accept: 'application/json' },
});
}
async fetchQuartzJob(group, name) {
return this.axios.get(uri`actuator/quartz/jobs/${group}/${name}`, {
headers: { Accept: 'application/json' },
});
}
async fetchQuartzTriggers() {
return this.axios.get(uri`actuator/quartz/triggers`, {
headers: { Accept: 'application/json' },
});
}
async fetchQuartzTrigger(group, name) {
return this.axios.get(uri`actuator/quartz/triggers/${group}/${name}`, {
headers: { Accept: 'application/json' },
});
}
async fetchSbomIds() {
return this.axios.get(uri`actuator/sbom`, {
headers: { Accept: 'application/json' },
});
}
async fetchSbom(id: string) {
return this.axios.get(uri`actuator/sbom/${id}`, {
headers: { Accept: '*/*' },
});
}
shutdown() {
return this.axios.post(uri`actuator/shutdown`);
}
restart() {
return this.axios.post(uri`actuator/restart`);
}
}
export default Instance;
export type Registration = {
name: string;
managementUrl?: string;
healthUrl: string;
serviceUrl?: string;
source: string;
metadata?: { [key: string]: string }[];
};
type StatusInfo = {
status:
| 'UNKNOWN'
| 'OUT_OF_SERVICE'
| 'UP'
| 'DOWN'
| 'OFFLINE'
| 'RESTRICTED'
| string;
details: { [key: string]: string };
};
type InstanceData = {
id: string;
registration: Registration;
endpoints?: Endpoint[];
availableMetrics?: string[];
tags?: { [key: string]: string }[];
statusTimestamp?: string;
buildVersion?: string;
statusInfo?: StatusInfo;
};
type Endpoint = {
id: string;
url: string;
};
export const DOWN_STATES = ['OUT_OF_SERVICE', 'DOWN', 'OFFLINE', 'RESTRICTED'];
export const UP_STATES = ['UP'];
export const UNKNOWN_STATES = ['UNKNOWN'];