-
Notifications
You must be signed in to change notification settings - Fork 27
/
jolokiaService.ts
392 lines (347 loc) · 12.8 KB
/
jolokiaService.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
/// <reference path="../jvmPlugin.ts"/>
namespace JVM {
export enum JolokiaListMethod {
// constant meaning that general LIST+EXEC Jolokia operations should be used
LIST_GENERAL = "list",
// constant meaning that optimized hawtio:type=security,name=RBACRegistry may be used
LIST_OPTIMISED = "list_optimised",
// when we get this status, we have to try checking again after logging in
LIST_CANT_DETERMINE = "cant_determine"
}
/**
* This is really a MBean that provides an optimised Jolokia list operation,
* with optionally decorated RBAC info on the result.
*/
const OPTIMISED_JOLOKIA_LIST_MBEAN = "hawtio:type=security,name=RBACRegistry";
export const DEFAULT_MAX_DEPTH = 7;
export const DEFAULT_MAX_COLLECTION_SIZE = 50000;
const urlCandidates = ['/hawtio/jolokia', '/jolokia', 'jolokia'];
let discoveredUrl = null;
hawtioPluginLoader.registerPreBootstrapTask({
name: 'JvmParseLocation',
task: (next) => {
let uri = new URI();
let query = uri.query(true);
log.debug("query: ", query);
let jolokiaUrl = query['jolokiaUrl'];
if (jolokiaUrl) {
delete query['sub-tab'];
delete query['main-tab'];
jolokiaUrl = URI.decode(jolokiaUrl);
let jolokiaURI = new URI(jolokiaUrl);
let name = query['title'] || 'Unknown Connection';
let token = query['token'] || Core.trimLeading(uri.hash(), '#');
let options = createConnectOptions({
jolokiaUrl: jolokiaUrl,
name: name,
scheme: jolokiaURI.protocol(),
host: jolokiaURI.hostname(),
port: Core.parseIntValue(jolokiaURI.port()),
path: Core.trimLeading(jolokiaURI.pathname(), '/')
});
if (!Core.isBlank(token)) {
options['token'] = token;
}
_.merge(options, jolokiaURI.query(true));
_.assign(options, query);
log.debug("options: ", options);
const connections = loadConnections().filter(connection => connection.name !== name);
connections.push(options);
saveConnections(connections);
uri.hash("").query({
con: name
});
window.location.replace(uri.toString());
// don't allow bootstrap to continue
return;
}
let connectionName = query['con'];
if (connectionName) {
log.debug("Not discovering jolokia");
// a connection name is set, no need to discover a jolokia instance
next();
return;
}
function maybeCheckNext(candidates) {
if (candidates.length === 0) {
next();
} else {
checkNext(candidates.pop());
}
}
function checkNext(url) {
log.debug("Trying URL:", url);
$.ajax(url).always((data, statusText, jqXHR) => {
// for $.ajax().always(), the xhr is flipped on fail
if (statusText !== 'success') {
jqXHR = data;
}
if (jqXHR.status === 200) {
try {
let resp = angular.fromJson(data);
//log.debug("Got response: ", resp);
if ('value' in resp && 'agent' in resp.value) {
discoveredUrl = url;
log.debug("Found jolokia agent at:", url, "version:", resp.value.agent);
next();
} else {
maybeCheckNext(urlCandidates);
}
} catch (e) {
maybeCheckNext(urlCandidates);
}
} else if (jqXHR.status === 401 || jqXHR.status === 403) {
// I guess this could be it...
discoveredUrl = url;
log.debug("Using URL:", url, "assuming it could be an agent but got return code:", jqXHR.status);
next();
} else {
maybeCheckNext(urlCandidates);
}
});
}
checkNext(urlCandidates.pop());
}
});
export let ConnectionName: string = null;
export function getConnectionName(reset = false) {
if (!Core.isBlank(ConnectionName) && !reset) {
return ConnectionName;
}
ConnectionName = '';
let search = new URI().search(true) as any;
if ('con' in window) {
ConnectionName = window['con'] as string;
log.debug("Using connection name from window:", ConnectionName);
} else if ('con' in search) {
ConnectionName = search['con'];
log.debug("Using connection name from URL:", ConnectionName);
} else {
log.debug("No connection name found, using direct connection to JVM");
}
return ConnectionName;
}
const connectOptions: ConnectOptions = (function () {
let name = getConnectionName();
if (Core.isBlank(name)) {
// this will fail any if (ConnectOptions) check
return null;
}
let answer = getConnectOptions(name);
// load saved credentials when connecting to remote server
answer.userName = sessionStorage.getItem('username');
answer.password = sessionStorage.getItem('password');
return answer;
})();
export function getJolokiaUrl(): string | boolean {
let answer = undefined;
let documentBase = HawtioCore.documentBase();
if (!connectOptions || !connectOptions.name) {
log.debug("Using discovered URL");
answer = discoveredUrl;
} else {
answer = createServerConnectionUrl(connectOptions);
log.debug("Using configured URL");
}
if (!answer) {
// this will force a dummy jolokia instance
return false;
}
// build full URL
let windowURI = new URI();
let jolokiaURI = undefined;
if (_.startsWith(answer, '/') || _.startsWith(answer, 'http')) {
jolokiaURI = new URI(answer);
} else {
jolokiaURI = new URI(UrlHelpers.join(documentBase, answer));
}
if (!connectOptions || !connectOptions.jolokiaUrl) {
if (!jolokiaURI.protocol()) {
jolokiaURI.protocol(windowURI.protocol());
}
if (!jolokiaURI.hostname()) {
jolokiaURI.host(windowURI.hostname());
}
if (!jolokiaURI.port()) {
jolokiaURI.port(windowURI.port());
}
}
answer = jolokiaURI.toString();
log.debug("Complete jolokia URL:", answer);
return answer;
}
_module.service('ConnectionName', () => (reset = false) => getConnectionName(reset));
_module.service('ConnectOptions', () => connectOptions);
// the jolokia URL we're connected to
_module.factory('jolokiaUrl', (): string | boolean => getJolokiaUrl());
// holds the status returned from the last jolokia call and hints for jolokia.list optimization
_module.factory('jolokiaStatus', createJolokiaStatus);
_module.factory('jolokia', createJolokia);
function createJolokiaStatus(): JolokiaStatus {
'ngInject';
return {
xhr: null,
listMethod: JolokiaListMethod.LIST_GENERAL,
listMBean: OPTIMISED_JOLOKIA_LIST_MBEAN
};
}
function createJolokia(
$location: ng.ILocationService,
localStorage: Storage,
jolokiaStatus: JolokiaStatus,
jolokiaParams: Jolokia.IParams,
jolokiaUrl: string,
userDetails: Core.AuthService,
postLoginTasks: Core.Tasks,
$timeout: ng.ITimeoutService,
$cookies: ng.cookies.ICookiesService): Jolokia.IJolokia {
'ngInject';
let jolokia: Jolokia.IJolokia = null;
if (jolokiaUrl) {
// hawtio-oauth may have already set up jQuery beforeSend
if (!$.ajaxSettings.beforeSend) {
log.debug("Setting up jQuery beforeSend");
$.ajaxSetup({ beforeSend: getBeforeSend(userDetails, $cookies) });
}
// execute post-login tasks in case they are not yet executed
// TODO: Where is the right place to execute post-login tasks for unauthenticated hawtio app?
postLoginTasks.execute();
if (!jolokiaParams.ajaxError) {
const errorThreshold = 2;
let errorCount = 0;
jolokiaParams.ajaxError = (xhr: JQueryXHR, textStatus: string, error: any) => {
if (xhr.status === 401 || xhr.status === 403) {
// If window was opened to connect to remote Jolokia endpoint
if (isRemoteConnection()) {
// ... and not showing the login modal
if ($location.path() !== '/jvm/connect-login') {
jolokia.stop();
const redirectUrl = $location.absUrl();
$location.path('/jvm/connect-login').search('redirect', redirectUrl);
}
} else {
// just logout
if (userDetails.loggedIn) {
userDetails.logout();
}
}
} else {
errorCount++;
const validityPeriod = localStorage['updateRate'] * (errorThreshold + 1);
$timeout(() => errorCount--, validityPeriod);
if (errorCount > errorThreshold) {
Core.notification('danger', 'Connection lost. Retrying...', localStorage['updateRate']);
}
}
}
}
jolokia = new Jolokia(jolokiaParams);
jolokia.stop();
// let's check if we can call faster jolokia.list()
checkJolokiaOptimization(jolokia, jolokiaStatus);
} else {
log.debug("Use dummy Jolokia");
jolokia = new DummyJolokia();
}
return jolokia;
}
function getBeforeSend(userDetails: Core.AuthService, $cookies: ng.cookies.ICookiesService): (xhr: JQueryXHR) => any {
// Just set Authorization for now...
let header = 'Authorization';
if (userDetails.loggedIn && userDetails.token) {
log.debug("Setting authorization header to token");
return (xhr: JQueryXHR) => {
if (userDetails.token) {
xhr.setRequestHeader(header, 'Bearer ' + userDetails.token);
}
}
} else if (connectOptions && connectOptions['token']) {
return (xhr: JQueryXHR) =>
xhr.setRequestHeader(header, 'Bearer ' + connectOptions['token']);
} else if (connectOptions && connectOptions.userName && connectOptions.password) {
log.debug("Setting authorization header to username/password");
return (xhr: JQueryXHR) =>
xhr.setRequestHeader(
header,
Core.getBasicAuthHeader(connectOptions.userName, connectOptions.password));
} else if ($cookies.get('XSRF-TOKEN')) {
// For CSRF protection with Spring Security
log.debug("Setting XSRF token header from cookies");
return (xhr: JQueryXHR) =>
xhr.setRequestHeader('X-XSRF-TOKEN', $cookies.get('XSRF-TOKEN'));
} else {
log.debug("Not setting any authorization header");
return (xhr: JQueryXHR) => { };
}
}
/**
* Queries available server-side MBean to check if we can call optimized jolokia.list() operation
* @param jolokia {Jolokia.IJolokia}
* @param jolokiaStatus {JolokiaStatus}
*/
function checkJolokiaOptimization(jolokia: Jolokia.IJolokia, jolokiaStatus: JolokiaStatus): void {
log.debug("Checking if we can call optimized jolokia.list() operation");
// NOTE: Sync XHR call to Jolokia is required here to resolve the available list method immediately
let response = jolokia.list(Core.escapeMBeanPath(jolokiaStatus.listMBean), Core.onSuccess(null));
if (response && _.isObject(response['op'])) {
jolokiaStatus.listMethod = JolokiaListMethod.LIST_OPTIMISED;
} else {
// we could get 403 error, mark the method as special case, equal in practice with LIST_GENERAL
jolokiaStatus.listMethod = JolokiaListMethod.LIST_CANT_DETERMINE;
}
log.debug("Jolokia list method:", jolokiaStatus.listMethod);
}
export interface JolokiaStatus {
xhr: JQueryXHR;
listMethod: JolokiaListMethod,
listMBean: string
}
/**
* Empty jolokia that returns nothing
*/
export class DummyJolokia implements Jolokia.IJolokia {
isDummy: boolean = true;
private running: boolean = false;
request(...args) { return null; }
getAttribute(mbean, attribute, path?, opts?) { return null; }
setAttribute(mbean, attribute, value, path?, opts?) { };
execute(mbean, operation, ...args) { return null; }
search(mBeanPatter, opts?) { return null; }
list(path, opts?) { return null; }
version(opts?) { return null; }
register(params, ...request) { return null; }
unregister(handle) { }
jobs() { return []; }
start(period) { this.running = true; }
stop() { this.running = false; }
isRunning() { return this.running; }
}
export interface ConnectOptions {
name?: string;
scheme?: string;
host?: string;
port?: number;
path?: string;
useProxy?: boolean;
jolokiaUrl?: string;
userName?: string;
password?: string;
reachable?: boolean;
returnTo?: string;
}
export function createConnectOptions(options: ConnectOptions = {}): ConnectOptions {
const defaults: ConnectOptions = {
name: null,
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
reachable: true
};
return angular.extend(defaults, options);
}
}