/
health-check.tsx
506 lines (481 loc) · 18.6 KB
/
health-check.tsx
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
import React, { Component } from 'react';
import { EuiLoadingSpinner, EuiDescriptionList, EuiIcon, EuiCallOut, EuiButtonIcon, EuiSpacer, EuiButton, EuiToolTip } from '@elastic/eui';
import { AppState } from '../../react-services/app-state';
import { PatternHandler } from '../../react-services/pattern-handler';
import { getAngularModule, getToasts, getHttp, getDataPlugin } from '../../kibana-services';
import { WazuhConfig } from '../../react-services/wazuh-config';
import { GenericRequest } from '../../react-services/generic-request';
import { ApiCheck } from '../../react-services/wz-api-check';
import { WzRequest } from '../../react-services/wz-request';
import { SavedObject } from '../../react-services/saved-objects';
import { ErrorHandler } from '../../react-services/error-handler';
import { WAZUH_ERROR_DAEMONS_NOT_READY, WAZUH_INDEX_TYPE_STATISTICS, WAZUH_INDEX_TYPE_MONITORING, HEALTH_CHECK } from '../../../common/constants';
import { checkKibanaSettings, checkKibanaSettingsTimeFilter, checkKibanaSettingsMaxBuckets } from './lib';
import store from '../../redux/store';
import { updateWazuhNotReadyYet } from '../../redux/actions/appStateActions.js';
import { withErrorBoundary } from '../common/hocs';
export const HealthCheck = withErrorBoundary (class HealthCheck extends Component {
checkPatternCount = 0;
constructor(props) {
super(props);
this.state = {
checks: [],
results: [],
errors: []
};
}
async componentDidMount() {
const app = getAngularModule();
this.$rootScope = app.$injector.get('$rootScope');
this.load();
}
showToast = (color, title, text, time) => {
getToasts().add({
color: color,
title: title,
text: text,
toastLifeTimeMs: time
});
};
/**
* Manage an error
*/
handleError(error) {
let errors = this.state.errors;
errors.push(ErrorHandler.handle(error, 'Health Check', { silent: true }));
this.setState({ errors });
}
/**
* Sleep method
* @param time
*/
delay = time => new Promise(res => setTimeout(res, time));
async checkDefaultPattern(defaultPattern) {
if (defaultPattern) {
const patternData = await SavedObject.existsIndexPattern(defaultPattern);
patternData.status && getDataPlugin().indexPatterns.setDefault(defaultPattern, true);
}
}
/**
* This validates a pattern
*/
async checkPatterns() {
this.checkPatternCount++;
if (this.checkPatternCount > 10) return Promise.reject('Error trying to check patterns.');
try {
let patternTitle = '';
let results = this.state.results;
let errors = this.state.errors;
const resultIndex = this.state.results.map(item => item.id).indexOf(2);
const currentPattern = AppState.getCurrentPattern();
if (this.state.checks.pattern) {
//get patters or create default
const patternList = await PatternHandler.getPatternList(HEALTH_CHECK);
// check selected pattern
const wazuhConfig = new WazuhConfig();
const { pattern: defaultPattern } = wazuhConfig.getConfig();
await this.checkDefaultPattern(defaultPattern);
//check selected pattern
let patternData = currentPattern ? await SavedObject.existsIndexPattern(currentPattern) : false;
if (!patternData) patternData = {};
patternTitle = patternData.title;
if (!patternData.status) {
if (patternList.length) {
const indexPatternDefault = patternList.find((indexPattern) => indexPattern.title === defaultPattern);
indexPatternDefault && AppState.setCurrentPattern(indexPatternDefault.id);
await this.delay(3000);
return await this.checkPatterns();
} else {
errors.push('The selected index-pattern is not present.');
results[resultIndex].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
}
} else {
results[resultIndex].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
}
this.setState({ results, errors });
}
if (this.state.checks.template) {
if (!patternTitle) {
var patternData = await SavedObject.existsIndexPattern(currentPattern);
patternTitle = patternData.title;
}
const i = results.map(item => item.id).indexOf(3);
const templateData = await GenericRequest.request(
'GET',
`/elastic/template/${patternTitle}`
);
if (!templateData.data.status) {
errors.push('No template found for the selected index-pattern.');
results[i].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
} else {
results[i].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
}
this.setState({ results, errors });
}
return;
} catch (error) {
this.handleError(error);
}
}
async trySetDefault() {
try {
const response = await GenericRequest.request('GET', '/hosts/apis');
const hosts = response.data;
const errors = [];
const results = this.state.results;
const maxTries = 5;
let apiId = '';
if (hosts.length) {
for (let i = 0; i < hosts.length; i++) {
for (let tries = 0; tries < maxTries; tries++) {
await this.delay(3000);
try {
const API = await ApiCheck.checkApi(hosts[i], true);
if (API && API.data) {
apiId = hosts[i].id;
tries = maxTries;
i = hosts.length
}
} catch (err) {
if (tries) {
results[0].description = <span><EuiLoadingSpinner size="m" /> Retrying {'.'.repeat(tries) }</span>;
results[1].description = <span><EuiLoadingSpinner size="m" /> Retrying {'.'.repeat(tries) }</span>;
this.setState({ results });
} else {
if (err.includes(WAZUH_ERROR_DAEMONS_NOT_READY)) {
const updateNotReadyYet = updateWazuhNotReadyYet(false);
store.dispatch(updateNotReadyYet);
}
errors.push(`Could not connect to API with id: ${hosts[i].id}: ${err.message || err}`);
}
}
}
if (apiId) return apiId;
}
const updateNotReadyYet = updateWazuhNotReadyYet(false);
store.dispatch(updateNotReadyYet);
if (errors.length) {
let err = this.state.errors;
errors.forEach(error => err.push(error));
this.setState({ errors: err })
return Promise.reject('No API available to connect.');
}
}
} catch (err) {
return Promise.reject(`Error connecting to API: ${err}`);
}
}
/**
* This attempts to reconnect with API
*/
reconnectWithAPI() {
let results = this.state.results;
results[0].description = <span><EuiLoadingSpinner size="m" /> Checking...</span>;
results[1].description = <span><EuiLoadingSpinner size="m" /> Checking...</span>;
getToasts().toasts$._value.forEach(toast => {
if (toast.text.includes('3000'))
getToasts().remove(toast.id);
});
const errors = this.state.errors.filter((error: string) => error.indexOf('API') < 0)
this.setState({ results, errors });
this.checkApiConnection();
}
/**
* This attempts to connect with API
*/
async checkApiConnection() {
let results = this.state.results;
let errors = this.state.errors;
let apiChanged = false;
const buttonRestartApi = <div> <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>
{<EuiToolTip
position='top'
content='Try to reconnect to the API'
>
<EuiButtonIcon
display="base"
iconType="refresh"
isLoading
iconSize="l"
onClick={() => this.reconnectWithAPI()}
size="m"
aria-label="Next"
/>
</EuiToolTip>}
</div>;
try {
const currentApi = JSON.parse(AppState.getCurrentAPI() || '{}');
if (this.state.checks.api && currentApi && currentApi.id) {
let data;
try {
data = await ApiCheck.checkStored(currentApi.id);
// Fix when the app endpoint replies with a valid response but the API is really down
if(data.data.data.apiIsDown){
throw 'API is down'
};
} catch (err) {
try {
const newApi = await this.trySetDefault();
data = await ApiCheck.checkStored(newApi, true);
apiChanged = true;
} catch (err2) {
throw err2
};
}
if (apiChanged) {
this.showToast(
'warning',
'Selected Wazuh API has been updated',
'',
3000
);
const api = ((data || {}).data || {}).data || {};
const name = (api.cluster_info || {}).manager || false;
AppState.setCurrentAPI(
JSON.stringify({ name: name, id: api.id })
);
}
//update cluster info
const cluster_info = (((data || {}).data || {}).data || {})
.cluster_info;
if (cluster_info) {
AppState.setClusterInfo(cluster_info);
}
const i = results.map(item => item.id).indexOf(0);
if (data === 3099) {
errors.push('Wazuh not ready yet.');
results[i].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;;
if (this.checks.setup) {
const i = results.map(item => item.id).indexOf(1);
results[i].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
}
this.setState({ results, errors });
} else if (data.data.error || data.data.data.apiIsDown) {
errors.push(data.data.data.apiIsDown ? 'Wazuh API is down.' : `Error connecting to the API.${data.data.error && data.data.error.message ? ` ${data.data.error.message}` : ''}`);
results[i].description = buttonRestartApi;
results[i + 1].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>
this.setState({ results, errors });
} else {
results[i].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
this.setState({ results, errors });
if (this.state.checks.setup) {
const versionData = await WzRequest.apiReq(
'GET',
'//',
{}
);
const apiVersion = versionData.data.data.api_version;
const setupData = await GenericRequest.request(
'GET',
'/api/setup'
);
if (!setupData.data.data['app-version']) {
errors.push('Error fetching app version');
};
if (!apiVersion) {
errors.push('Error fetching Wazuh API version');
};
const api = /v?(?<version>\d+)\.(?<minor>\d+)\.(?<path>\d+)/.exec(apiVersion);
const appSplit = setupData.data.data['app-version'].split('.');
const i = this.state.results.map(item => item.id).indexOf(1);
if (api.groups.version !== appSplit[0] || api.groups.minor !== appSplit[1]) {
errors.push(
'API version mismatch. Expected v' +
setupData.data.data['app-version']
);
results[i].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
this.setState({ results, errors });
} else {
results[i].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
const updateNotReadyYet = updateWazuhNotReadyYet(false);
store.dispatch(updateNotReadyYet);
this.setState({ results, errors });
}
}
}
}
return;
} catch (error) {
results[0].description = buttonRestartApi;
results[1].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
this.setState({ results });
AppState.removeNavigation();
if (error && error.data && error.data.code && error.data.code === 3002) {
return error;
} else {
this.handleError(error);
}
}
}
/**
* This check if the pattern exist then create if not
* @param pattern string
*/
async checkSupportPattern(pattern, itemId, indexType) {
let results = this.state.results;
let errors = this.state.errors;
const result = await SavedObject.existsIndexPattern(pattern);
if (!result.data) {
const toast = getToasts().addWarning(`${pattern} index pattern was not found and it will be created`)
const fields = await SavedObject.getIndicesFields(pattern, indexType);
try {
await SavedObject.createSavedObject(
'index-pattern',
pattern,
{
attributes: {
title: pattern,
timeFieldName: 'timestamp'
}
},
fields
);
getToasts().remove(toast.id);
getToasts().addSuccess(`${pattern} index pattern created successfully`)
results[itemId].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
this.setState({ results });
} catch (error) {
getToasts().remove(toast.id);
errors.push(`Error trying to create ${pattern} index pattern: ${error.message}`);
results[itemId].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
this.setState({ results });
}
} else {
results[itemId].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
this.setState({ results });
}
}
/**
* On controller loads
*/
async load() {
try {
const wazuhConfig = new WazuhConfig();
const configuration = wazuhConfig.getConfig();
checkKibanaSettings(configuration['checks.metaFields']);
checkKibanaSettingsTimeFilter(configuration['checks.timeFilter']);
checkKibanaSettingsMaxBuckets(configuration['checks.maxBuckets']);
AppState.setPatternSelector(configuration['ip.selector']);
let checks = {};
checks.pattern = configuration['checks.pattern'];
checks.template = configuration['checks.template'];
checks.api = configuration['checks.api'];
checks.setup = configuration['checks.setup'];
checks.fields = configuration['checks.fields'];
const results = []
results.push(
{
id: 0,
title: 'Check Wazuh API connection',
description: checks.api ? <span><EuiLoadingSpinner size="m" /> Checking...</span> : 'Disabled'
},
{
id: 1,
title: 'Check for Wazuh API version',
description: checks.setup ? <span><EuiLoadingSpinner size="m" /> Checking...</span> : 'Disabled'
},
{
id: 2,
title: 'Check Elasticsearch index pattern',
description: checks.pattern ? <span><EuiLoadingSpinner size="m" /> Checking...</span> : 'Disabled'
},
{
id: 3,
title: 'Check Elasticsearch template',
description: checks.template ? <span><EuiLoadingSpinner size="m" /> Checking...</span> : 'Disabled'
},
{
id: 4,
title: 'Check index pattern fields',
description: checks.fields ? <span><EuiLoadingSpinner size="m" /> Checking...</span> : 'Disabled'
},
{
id: 5,
title: 'Check Monitoring index pattern',
description: <span><EuiLoadingSpinner size="m" /> Checking...</span>
},
{
id: 6,
title: 'Check Statistics index pattern',
description: <span><EuiLoadingSpinner size="m" /> Checking...</span>
},
);
this.setState({ checks, results },
async () => {
await Promise.all([
this.checkPatterns(),
this.checkApiConnection(),
this.checkSupportPattern(configuration['wazuh.monitoring.pattern'], 5, WAZUH_INDEX_TYPE_MONITORING),
this.checkSupportPattern(`${configuration['cron.prefix']}-${configuration['cron.statistics.index.name']}-*`, 6, WAZUH_INDEX_TYPE_STATISTICS),
]);
if (checks.fields) {
const i = results.map(item => item.id).indexOf(4);
try {
await PatternHandler.refreshIndexPattern();
results[i].description = <span><EuiIcon type="check" color="secondary" ></EuiIcon> Ready</span>;
this.setState({ results });
} catch (error) {
results[i].description = <span><EuiIcon type="alert" color="danger" ></EuiIcon> Error</span>;
this.setState({ results }, () => this.handleError(error));
}
}
if (!this.state.errors || !this.state.errors.length) {
setTimeout(() => {
const params = this.$rootScope.previousParams || {};
var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
const url = 'wazuh#' + (this.$rootScope.previousLocation || '') + '?' + queryString;
window.location.assign(
getHttp().basePath.prepend(url)
);
return;
}, 300);
}
return;
});
} catch (error) {
this.handleError(error);
}
}
goAppSettings() {
window.location.href = '/app/wazuh#/settings';
}
render() {
const logo_url = getHttp().basePath.prepend('/plugins/wazuh/assets/icon_blue.svg');
return (
<div className="health-check">
{!this.state.errors && (
<EuiLoadingSpinner className="health-check-loader" />
)}
<img src={logo_url} className="health-check-logo" alt=""></img>
<div className="margin-top-30">
<EuiDescriptionList
textStyle="reverse"
align="center"
type="column"
listItems={this.state.results}
/>
</div>
<EuiSpacer size="xxl" />
{(this.state.errors || []).map(error => (
<>
<EuiCallOut
title={error}
color="danger"
iconType="alert"
style={{ textAlign: 'left' }}>
</EuiCallOut>
<EuiSpacer size="xs" />
</>
))}
<EuiSpacer size="xxl" />
{!!this.state.errors.length && (
<EuiButton
fill
onClick={() => this.goAppSettings()}>
Go to App
</EuiButton>
)}
</div >
);
}
});