From 560376013645ee71e604f2f66db1fe99ea2e6a80 Mon Sep 17 00:00:00 2001 From: Antonio <34042064+Desvelao@users.noreply.github.com> Date: Wed, 3 Jan 2024 12:24:51 +0100 Subject: [PATCH] Fix refreshing index pattern fields does not include the scripted fields (#6237) * fix: refresh index pattern fields does not include the scripted fields - Replaced custom service logic for a similar one to the Dashboards Management/Index pattern of the platform - Removed the ability to define fields that are not fields from the indices that match the index pattern or scripted fields * changelog: add entry * fix: replace the SavedObjects.refreshIndexPattern method - Use a more low level logic to update the index pattern fields taking in account the scripted fields - The SavedObjects.refreshIndexPattern now throws an error when something fails instead of return the error message - Display a warning in the check fields or when refreshing the index pattern of the default configurated index pattern of the plugins * fix: minor fixes in warning messages of the health check --------- Co-authored-by: Federico Rodriguez --- CHANGELOG.md | 4 + .../check-fields.service.ts | 27 +- .../check-index-pattern-object.service.ts | 164 +++++++++--- .../components/visualize/wz-visualize.js | 9 +- .../public/kibana-integrations/kibana-vis.js | 245 +++++++++++------- .../public/react-services/pattern-handler.js | 12 +- .../public/react-services/saved-objects.js | 53 +--- 7 files changed, 320 insertions(+), 194 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f46e5d1815..06dcd51fd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ All notable changes to the Wazuh app project will be documented in this file. - Develop logic of a new index for the fim module [#6227](https://github.com/wazuh/wazuh-dashboard-plugins/pull/6227) - Allow editing groups for an agent from Endpoints Summary [#6250](https://github.com/wazuh/wazuh-dashboard-plugins/pull/6250) +# Fixed + +- Fixed the scripted fields disappear when the fields of the events index pattern was refreshed [#6237](https://github.com/wazuh/wazuh-dashboard-plugins/pull/6237) + ## Wazuh v4.8.1 - OpenSearch Dashboards 2.10.0 - Revision 00 ### Added diff --git a/plugins/main/public/components/health-check/services/check-index-pattern/check-fields.service.ts b/plugins/main/public/components/health-check/services/check-index-pattern/check-fields.service.ts index 3228c6d235..90b2220b30 100644 --- a/plugins/main/public/components/health-check/services/check-index-pattern/check-fields.service.ts +++ b/plugins/main/public/components/health-check/services/check-index-pattern/check-fields.service.ts @@ -16,15 +16,30 @@ import { AppState, SavedObject } from '../../../../react-services'; import { getDataPlugin } from '../../../../kibana-services'; import { CheckLogger } from '../../types/check_logger'; -export const checkFieldsService = async (appConfig, checkLogger: CheckLogger) => { +export const checkFieldsService = async ( + appConfig, + checkLogger: CheckLogger, +) => { const patternId = AppState.getCurrentPattern(); checkLogger.info(`Index pattern id in cookie: [${patternId}]`); - + checkLogger.info(`Getting index pattern data [${patternId}]...`); const pattern = await getDataPlugin().indexPatterns.get(patternId); checkLogger.info(`Index pattern data found: [${pattern ? 'yes' : 'no'}]`); - - checkLogger.info(`Refreshing index pattern fields: title [${pattern.title}], id [${pattern.id}]...`); - await SavedObject.refreshIndexPattern(pattern, null); - checkLogger.action(`Refreshed index pattern fields: title [${pattern.title}], id [${pattern.id}]`); + + checkLogger.info( + `Refreshing index pattern fields: title [${pattern.title}], id [${pattern.id}]...`, + ); + try { + await SavedObject.refreshIndexPattern(pattern); + checkLogger.action( + `Refreshed index pattern fields: title [${pattern.title}], id [${pattern.id}]`, + ); + } catch (error) { + if (error.message.includes('No indices match pattern')) { + checkLogger.warning( + `Index pattern fields for title [${pattern.title}], id [${pattern.id}] could not be refreshed due to: ${error.message}. This could be an indicator of some problem in the generation, not running server service or configuration to ingest of alerts data.`, + ); + } + } }; diff --git a/plugins/main/public/components/health-check/services/check-index-pattern/check-index-pattern-object.service.ts b/plugins/main/public/components/health-check/services/check-index-pattern/check-index-pattern-object.service.ts index e74a54d513..a481e63876 100644 --- a/plugins/main/public/components/health-check/services/check-index-pattern/check-index-pattern-object.service.ts +++ b/plugins/main/public/components/health-check/services/check-index-pattern/check-index-pattern-object.service.ts @@ -16,45 +16,91 @@ import { getDataPlugin } from '../../../../kibana-services'; import { HEALTH_CHECK } from '../../../../../common/constants'; import { CheckLogger } from '../../types/check_logger'; -export const checkIndexPatternObjectService = async (appConfig, checkLogger: CheckLogger) => { +export const checkIndexPatternObjectService = async ( + appConfig, + checkLogger: CheckLogger, +) => { const patternId: string = AppState.getCurrentPattern(); const defaultPatternId: string = appConfig.data['pattern']; const shouldCreateIndex: boolean = appConfig.data['checks.pattern']; - checkLogger.info(`Index pattern id in cookie: ${patternId ? `yes [${patternId}]` : 'no'}`); + checkLogger.info( + `Index pattern id in cookie: ${patternId ? `yes [${patternId}]` : 'no'}`, + ); const defaultIndexPatterns: string[] = [ defaultPatternId, - ...(patternId && patternId !== defaultPatternId ? [patternId] : []) + ...(patternId && patternId !== defaultPatternId ? [patternId] : []), ]; checkLogger.info(`Getting list of valid index patterns...`); - let listValidIndexPatterns = await SavedObject.getListOfWazuhValidIndexPatterns(defaultIndexPatterns, HEALTH_CHECK); - checkLogger.info(`Valid index patterns found: ${listValidIndexPatterns.length || 0}`); + let listValidIndexPatterns = + await SavedObject.getListOfWazuhValidIndexPatterns( + defaultIndexPatterns, + HEALTH_CHECK, + ); + checkLogger.info( + `Valid index patterns found: ${listValidIndexPatterns.length || 0}`, + ); - const indexPatternDefaultFound = listValidIndexPatterns.find((indexPattern) => indexPattern.title === defaultPatternId); - checkLogger.info(`Found default index pattern with title [${defaultPatternId}]: ${indexPatternDefaultFound ? 'yes' : 'no'}`); + const indexPatternDefaultFound = listValidIndexPatterns.find( + indexPattern => indexPattern.title === defaultPatternId, + ); + checkLogger.info( + `Found default index pattern with title [${defaultPatternId}]: ${ + indexPatternDefaultFound ? 'yes' : 'no' + }`, + ); if (!indexPatternDefaultFound && defaultPatternId) { // if no valid index patterns are found we try to create the wazuh-alerts-* try { - checkLogger.info(`Checking if index pattern [${defaultPatternId}] exists...`); - const existDefaultIndexPattern = await SavedObject.getExistingIndexPattern(defaultPatternId); - checkLogger.info(`Index pattern id [${defaultPatternId}] exists: ${existDefaultIndexPattern ? 'yes' : 'no'}`); + checkLogger.info( + `Checking if index pattern [${defaultPatternId}] exists...`, + ); + const existDefaultIndexPattern = + await SavedObject.getExistingIndexPattern(defaultPatternId); + checkLogger.info( + `Index pattern id [${defaultPatternId}] exists: ${ + existDefaultIndexPattern ? 'yes' : 'no' + }`, + ); if (existDefaultIndexPattern) { - checkLogger.info(`Refreshing index pattern fields [${defaultPatternId}]...`); - await SavedObject.refreshIndexPattern(defaultPatternId); - checkLogger.action(`Refreshed index pattern fields [${defaultPatternId}]`); - } else if(shouldCreateIndex) { + checkLogger.info(`Getting index pattern [${defaultPatternId}]...`); + const pattern = await getDataPlugin().indexPatterns.get( + defaultPatternId, + ); + checkLogger.info( + `Refreshing index pattern fields: title [${pattern.title}], id [${pattern.id}]...`, + ); + try { + await SavedObject.refreshIndexPattern(pattern); + checkLogger.action( + `Refreshed index pattern fields: title [${pattern.title}], id [${pattern.id}]`, + ); + } catch (error) { + if (error.message.includes('No indices match pattern')) { + checkLogger.warning( + `Index pattern fields for title [${pattern.title}], id [${pattern.id}] could not be refreshed due to: ${error.message}. This could be an indicator of some problem in the generation, not running server service or configuration to ingest of alerts data.`, + ); + } + } + } else if (shouldCreateIndex) { checkLogger.info(`Creating index pattern [${defaultPatternId}]...`); await SavedObject.createWazuhIndexPattern(defaultPatternId); checkLogger.action(`Created index pattern [${defaultPatternId}]`); - }else{ + } else { // show error checkLogger.error(`Default index pattern not found`); } checkLogger.info(`Getting list of valid index patterns...`); - listValidIndexPatterns = await SavedObject.getListOfWazuhValidIndexPatterns(defaultIndexPatterns, HEALTH_CHECK); - checkLogger.info(`Valid index patterns found: ${listValidIndexPatterns.length || 0}`); - if(!AppState.getCurrentPattern()){ + listValidIndexPatterns = + await SavedObject.getListOfWazuhValidIndexPatterns( + defaultIndexPatterns, + HEALTH_CHECK, + ); + checkLogger.info( + `Valid index patterns found: ${listValidIndexPatterns.length || 0}`, + ); + if (!AppState.getCurrentPattern()) { // Check the index pattern saved objects can be found using `GET /api/saved_objects/_find` endpoint. // Related issue: https://github.com/wazuh/wazuh-dashboard-plugins/issues/4293 await validateIntegritySavedObjects([defaultPatternId], checkLogger); @@ -71,8 +117,10 @@ export const checkIndexPatternObjectService = async (appConfig, checkLogger: Ch } if (AppState.getCurrentPattern() && listValidIndexPatterns.length) { - const indexPatternToSelect = listValidIndexPatterns.find(item => item.id === AppState.getCurrentPattern()); - if (!indexPatternToSelect){ + const indexPatternToSelect = listValidIndexPatterns.find( + item => item.id === AppState.getCurrentPattern(), + ); + if (!indexPatternToSelect) { const indexPatternID = listValidIndexPatterns[0].id; // Check the index pattern saved objects can be found using `GET /api/saved_objects/_find` endpoint. @@ -83,30 +131,59 @@ export const checkIndexPatternObjectService = async (appConfig, checkLogger: Ch checkLogger.action(`Set index pattern id in cookie: [${indexPatternID}]`); } } - - checkLogger.info(`Checking the app default pattern exists: id [${defaultPatternId}]...`); - const existsDefaultPattern = await SavedObject.existsIndexPattern(defaultPatternId); - checkLogger.info(`Default pattern with id [${defaultPatternId}] exists: ${existsDefaultPattern.status ? 'yes' : 'no'}`); - - existsDefaultPattern.status - && getDataPlugin().indexPatterns.setDefault(defaultPatternId, true) - && checkLogger.action(`Default pattern id [${defaultPatternId}] set as default index pattern`); - patternId && checkLogger.info(`Checking the index pattern id [${patternId}] exists...`); - const patternData = patternId ? (await SavedObject.existsIndexPattern(patternId)) || {} : {} ; - patternId && checkLogger.info(`Index pattern id exists [${patternId}]: ${patternData.status ? 'yes': 'no'}`); + checkLogger.info( + `Checking the app default pattern exists: id [${defaultPatternId}]...`, + ); + const existsDefaultPattern = await SavedObject.existsIndexPattern( + defaultPatternId, + ); + checkLogger.info( + `Default pattern with id [${defaultPatternId}] exists: ${ + existsDefaultPattern.status ? 'yes' : 'no' + }`, + ); + + existsDefaultPattern.status && + getDataPlugin().indexPatterns.setDefault(defaultPatternId, true) && + checkLogger.action( + `Default pattern id [${defaultPatternId}] set as default index pattern`, + ); + + patternId && + checkLogger.info(`Checking the index pattern id [${patternId}] exists...`); + const patternData = patternId + ? (await SavedObject.existsIndexPattern(patternId)) || {} + : {}; + patternId && + checkLogger.info( + `Index pattern id exists [${patternId}]: ${ + patternData.status ? 'yes' : 'no' + }`, + ); if (!patternData.status) { if (listValidIndexPatterns.length) { - const indexPatternDefaultFound = listValidIndexPatterns.find((indexPattern) => indexPattern.title === defaultPatternId); - checkLogger.info(`Index pattern id exists [${defaultPatternId}]: ${indexPatternDefaultFound ? 'yes': 'no'}`); - if(indexPatternDefaultFound){ + const indexPatternDefaultFound = listValidIndexPatterns.find( + indexPattern => indexPattern.title === defaultPatternId, + ); + checkLogger.info( + `Index pattern id exists [${defaultPatternId}]: ${ + indexPatternDefaultFound ? 'yes' : 'no' + }`, + ); + if (indexPatternDefaultFound) { // Check the index pattern saved objects can be found using `GET /api/saved_objects/_find` endpoint. // Related issue: https://github.com/wazuh/wazuh-dashboard-plugins/issues/4293 - await validateIntegritySavedObjects([indexPatternDefaultFound.id], checkLogger); + await validateIntegritySavedObjects( + [indexPatternDefaultFound.id], + checkLogger, + ); AppState.setCurrentPattern(indexPatternDefaultFound.id); - checkLogger.action(`Index pattern set in cookie: [${indexPatternDefaultFound.id}]`); + checkLogger.action( + `Index pattern set in cookie: [${indexPatternDefaultFound.id}]`, + ); } checkLogger.info('Retrying the check...'); return await checkIndexPatternObjectService(appConfig, checkLogger); @@ -118,8 +195,17 @@ export const checkIndexPatternObjectService = async (appConfig, checkLogger: Ch // Check the index pattern saved objects can be found using `GET /api/saved_objects/_find` endpoint. // Related issue: https://github.com/wazuh/wazuh-dashboard-plugins/issues/4293 -const validateIntegritySavedObjects = async (indexPatternSavedObjectIDs: string[], checkLogger: CheckLogger): Promise => { - checkLogger.info(`Checking the integrity of saved objects. Validating ${indexPatternSavedObjectIDs.join(',')} can be found...`); - await SavedObject.validateIndexPatternSavedObjectCanBeFound(indexPatternSavedObjectIDs); +const validateIntegritySavedObjects = async ( + indexPatternSavedObjectIDs: string[], + checkLogger: CheckLogger, +): Promise => { + checkLogger.info( + `Checking the integrity of saved objects. Validating ${indexPatternSavedObjectIDs.join( + ',', + )} can be found...`, + ); + await SavedObject.validateIndexPatternSavedObjectCanBeFound( + indexPatternSavedObjectIDs, + ); checkLogger.info('Integrity of saved objects: [ok]'); }; diff --git a/plugins/main/public/components/visualize/wz-visualize.js b/plugins/main/public/components/visualize/wz-visualize.js index f15baad0eb..61aa5c3585 100644 --- a/plugins/main/public/components/visualize/wz-visualize.js +++ b/plugins/main/public/components/visualize/wz-visualize.js @@ -74,7 +74,6 @@ export const WzVisualize = compose( this.monitoringEnabled = !!(configuration || {})[ 'wazuh.monitoring.enabled' ]; - this.newFields = {}; } async componentDidMount() { @@ -123,19 +122,15 @@ export const WzVisualize = compose( }); }; - refreshKnownFields = async (newField = null) => { - if (newField && newField.name) { - this.newFields[newField.name] = newField; - } + refreshKnownFields = async () => { if (!this.hasRefreshedKnownFields) { // Known fields are refreshed only once per dashboard loading try { this.hasRefreshedKnownFields = true; this.isRefreshing = true; - await PatternHandler.refreshIndexPattern(this.newFields); + await PatternHandler.refreshIndexPattern(); this.isRefreshing = false; this.reloadToast(); - this.newFields = {}; } catch (error) { this.isRefreshing = false; const options = { diff --git a/plugins/main/public/kibana-integrations/kibana-vis.js b/plugins/main/public/kibana-integrations/kibana-vis.js index 3787db48cb..c0aba88086 100644 --- a/plugins/main/public/kibana-integrations/kibana-vis.js +++ b/plugins/main/public/kibana-integrations/kibana-vis.js @@ -33,7 +33,6 @@ import { EuiIcon, EuiFlexItem, EuiFlexGroup, - EuiEmptyPrompt } from '@elastic/eui'; import { getAngularModule, @@ -45,7 +44,6 @@ import { getOverlays, getPlugins, } from '../kibana-services'; -import { KnownFields } from '../utils/known-fields'; import { union } from 'lodash'; import { getFilterWithAuthorizedAgents } from '../react-services/filter-authorization-agents'; import { AUTHORIZED_AGENTS } from '../../common/constants'; @@ -86,7 +84,9 @@ class KibanaVis extends Component { ...services, ...{ visualizationTypes: getVisualizationsPlugin() }, }; - this.savedObjectLoaderVisualize = createSavedVisLoader(servicesForVisualizations); + this.savedObjectLoaderVisualize = createSavedVisLoader( + servicesForVisualizations, + ); this.visID = this.props.visID; this.tab = this.props.tab; } @@ -114,7 +114,7 @@ class KibanaVis extends Component { // componentWillUnmount. // In the renderComplete() the value of the $rootScope // is changed, which affects the entire application. - // + // // Related issue: // https://github.com/wazuh/wazuh-dashboard-plugins/issues/4158 if (this.deadField) { @@ -149,13 +149,14 @@ class KibanaVis extends Component { data.value && data.value.visData && data.value.visData.rows && - this.props.state[this.visID] !== data.value.visData.rows['0']['col-0-1'] + this.props.state[this.visID] !== + data.value.visData.rows['0']['col-0-1'] ) { store.dispatch( this.updateMetric({ name: this.visID, value: data.value.visData.rows['0']['col-0-1'], - }) + }), ); } // This check if data.value.visData.tables exists and dispatch that value as stat @@ -169,13 +170,14 @@ class KibanaVis extends Component { data.value.visData.tables['0'] && data.value.visData.tables['0'].rows && data.value.visData.tables['0'].rows['0'] && - this.props.state[this.visID] !== data.value.visData.tables['0'].rows['0']['col-0-2'] + this.props.state[this.visID] !== + data.value.visData.tables['0'].rows['0']['col-0-2'] ) { store.dispatch( this.updateMetric({ name: this.visID, value: data.value.visData.tables['0'].rows['0']['col-0-2'], - }) + }), ); } } @@ -195,17 +197,18 @@ class KibanaVis extends Component { } }; - setSearchSource = (discoverList) => { + setSearchSource = discoverList => { try { const isCluster = this.visID.includes('Cluster'); if (isCluster) { // Checks for cluster.name or cluster.node filter existence const monitoringFilter = discoverList[1].filter( - (item) => + item => item && item.meta && item.meta.key && - (item.meta.key.includes('cluster.name') || item.meta.key.includes('cluster.node')) + (item.meta.key.includes('cluster.name') || + item.meta.key.includes('cluster.node')), ); // Applying specific filter to cluster monitoring vis @@ -218,12 +221,15 @@ class KibanaVis extends Component { } }; - myRender = async (raw) => { + myRender = async raw => { const timefilter = getDataPlugin().query.timefilter.timefilter; try { const discoverList = this.discoverPendingUpdates.getList(); - const isAgentStatus = this.visID === 'Wazuh-App-Overview-General-Agents-status'; - const timeFilterSeconds = this.calculateTimeFilterSeconds(timefilter.getTime()); + const isAgentStatus = + this.visID === 'Wazuh-App-Overview-General-Agents-status'; + const timeFilterSeconds = this.calculateTimeFilterSeconds( + timefilter.getTime(), + ); const timeRange = isAgentStatus && timeFilterSeconds < 900 ? { from: 'now-15m', to: 'now', mode: 'quick' } @@ -243,8 +249,13 @@ class KibanaVis extends Component { { term: AppState.getClusterInfo().status === 'enabled' - ? { 'cluster.name': AppState.getClusterInfo().cluster } - : { 'manager.keyword': AppState.getClusterInfo().manager }, + ? { + 'cluster.name': AppState.getClusterInfo().cluster, + } + : { + 'manager.keyword': + AppState.getClusterInfo().manager, + }, }, ], }, @@ -257,19 +268,29 @@ class KibanaVis extends Component { : discoverList[1] || []; const query = !isAgentStatus ? discoverList[0] : {}; - const rawVis = raw ? raw.filter((item) => item && item.id === this.visID) : []; + const rawVis = raw + ? raw.filter(item => item && item.id === this.visID) + : []; if (rawVis.length && discoverList.length) { let vizPattern; try { - vizPattern = JSON.parse(rawVis[0].attributes.kibanaSavedObjectMeta.searchSourceJSON) - .index; + vizPattern = JSON.parse( + rawVis[0].attributes.kibanaSavedObjectMeta.searchSourceJSON, + ).index; } catch (ex) { console.warn(`plugin platform-vis exception: ${ex.message || ex}`); } - if (!filters.find((filter) => filter.meta.controlledBy === AUTHORIZED_AGENTS)) { - const agentsFilters = getFilterWithAuthorizedAgents(this.props.allowedAgents, vizPattern); + if ( + !filters.find( + filter => filter.meta.controlledBy === AUTHORIZED_AGENTS, + ) + ) { + const agentsFilters = getFilterWithAuthorizedAgents( + this.props.allowedAgents, + vizPattern, + ); filters = agentsFilters ? union(filters, [agentsFilters]) : filters; } @@ -284,16 +305,21 @@ class KibanaVis extends Component { if (!this.visualization && !this.rendered && !this.renderInProgress) { // There's no visualization object -> create it with proper filters this.renderInProgress = true; - this.visualization = await this.savedObjectLoaderVisualize.get(this.visID, rawVis[0]); - this.visualization.searchSource = await getDataPlugin().search.searchSource.create(); + this.visualization = await this.savedObjectLoaderVisualize.get( + this.visID, + rawVis[0], + ); + this.visualization.searchSource = + await getDataPlugin().search.searchSource.create(); // Visualization doesn't need the "_source" this.visualization.searchSource.setField('source', false); // Visualization doesn't need "hits" this.visualization.searchSource.setField('size', 0); - const visState = await getVisualizationsPlugin().convertToSerializedVis( - this.visualization - ); - + const visState = + await getVisualizationsPlugin().convertToSerializedVis( + this.visualization, + ); + // In Kibana 7.10.2, there is a bug when creating the visualization with `createVis` method of the Visualization plugin that doesn't pass the `visState` parameter to the `Vis` class constructor. // This does the `.params`, `.uiState` and `.id` properties of the visualization are not set correctly in the `Vis` class constructor. This bug causes // that the visualization, for example, doesn't use the defined colors in the `.uiStateJSON` property. @@ -305,16 +331,17 @@ class KibanaVis extends Component { // as is done in the `Vis` class constructor https://github.com/elastic/kibana/blob/v7.10.2/src/plugins/visualizations/public/vis.ts#L99-L104 const vis = await getVisualizationsPlugin().createVis( this.visualization.visState.type, - visState + visState, ); vis.params = vis.getParams(visState.params); vis.uiState = new PersistedState(visState.uiState); vis.id = visState.id; - - this.visHandler = await getVisualizationsPlugin().__LEGACY.createVisEmbeddableFromObject( - vis, - visInput - ); + + this.visHandler = + await getVisualizationsPlugin().__LEGACY.createVisEmbeddableFromObject( + vis, + visInput, + ); await this.visHandler.render($(`[id="${this.visID}"]`)[0]); this.visHandler.handler.data$.subscribe(this.renderComplete()); this.visHandlers.addItem(this.visHandler); @@ -331,10 +358,15 @@ class KibanaVis extends Component { this.visHandler.updateInput(visInput); this.setSearchSource(discoverList); } - if (this.state.visRefreshingIndex) this.setState({ visRefreshingIndex: false }); + if (this.state.visRefreshingIndex) + this.setState({ visRefreshingIndex: false }); } } catch (error) { - if (((error || {}).message || '').includes('not locate that index-pattern-field')) { + if ( + ((error || {}).message || '').includes( + 'not locate that index-pattern-field', + ) + ) { if (this.deadField) { this.tabVisualizations.addDeadVis(); return this.renderComplete(); @@ -349,11 +381,7 @@ class KibanaVis extends Component { this.renderInProgress = false; this.rendered = false; - // if there's a field name it looks for known fields structures - const foundField = - match[1] && KnownFields.find((field) => field.name === match[1].trim()); - - await this.props.refreshKnownFields(foundField); + await this.props.refreshKnownFields(); } this.renderInProgress = false; return this.myRender(raw); @@ -387,8 +415,10 @@ class KibanaVis extends Component { this.loadedVisualizations.addItem(true); const currentLoaded = this.loadedVisualizations.getList().length; - const deadVis = this.props.tab === 'ciscat' ? 0 : this.tabVisualizations.getDeadVis(); - const totalTabVis = this.tabVisualizations.getItem(this.props.tab) - deadVis; + const deadVis = + this.props.tab === 'ciscat' ? 0 : this.tabVisualizations.getDeadVis(); + const totalTabVis = + this.tabVisualizations.getItem(this.props.tab) - deadVis; this.$rootScope.loadingStatus = 'Fetching data...'; if (totalTabVis < 1) { @@ -398,7 +428,9 @@ class KibanaVis extends Component { if (currentCompleted >= 100) { this.$rootScope.rendered = 'true'; if (visId.includes('AWS-geo')) { - const canvas = $('.visChart.leaflet-container .leaflet-control-zoom-in'); + const canvas = $( + '.visChart.leaflet-container .leaflet-control-zoom-in', + ); setTimeout(() => { if (!this.mapClicked) { this.mapClicked = true; @@ -410,23 +442,25 @@ class KibanaVis extends Component { this.$rootScope.rendered = 'false'; } } - if (typeof this.props.onRenderComplete === 'function') this.props.onRenderComplete(); + if (typeof this.props.onRenderComplete === 'function') + this.props.onRenderComplete(); }; showDateRangePicker = () => { - return !this.deadField && !this.state.visRefreshingIndex && this.visID === 'Wazuh-App-Overview-General-Agents-status' - } + return ( + !this.deadField && + !this.state.visRefreshingIndex && + this.visID === 'Wazuh-App-Overview-General-Agents-status' + ); + }; DateRangePickerComponent = () => { return ( - - {}} - /> + + {}} /> - ) - } + ); + }; render() { const isLoading = this.props.resultState === 'loading'; @@ -443,7 +477,7 @@ class KibanaVis extends Component { - + Refreshing Index Pattern. @@ -452,77 +486,90 @@ class KibanaVis extends Component {
- +
No results found   - No alerts were found with the field: {this.deadField} + No alerts were found with the field:{' '} + {this.deadField} } > - +
- { - !this.isLoading && this.showDateRangePicker() && - this.DateRangePickerComponent() - } + {!this.isLoading && + this.showDateRangePicker() && + this.DateRangePickerComponent()}
-
- {(isLoading &&
) - || (this.deadField && !isLoading && !this.state.visRefreshingIndex && ( -
- No results found   - - No alerts were found with the field: {this.deadField} - - } - > - - -
- )) - || (this.state.visRefreshingIndex && ( - - - - - Refreshing Index Pattern. - - )) - } +
+ {(isLoading && ( +
+ +
+ )) || + (this.deadField && + !isLoading && + !this.state.visRefreshingIndex && ( +
+ No results found   + + No alerts were found with the field:{' '} + {this.deadField} + + } + > + + +
+ )) || + (this.state.visRefreshingIndex && ( + + + + + + Refreshing Index Pattern. + + + ))}
) @@ -530,7 +577,7 @@ class KibanaVis extends Component { } } -const mapStateToProps = (state) => { +const mapStateToProps = state => { return { state: state.visualizationsReducers, allowedAgents: state.appStateReducers.allowedAgents, diff --git a/plugins/main/public/react-services/pattern-handler.js b/plugins/main/public/react-services/pattern-handler.js index 9a1682f157..3d944604ef 100644 --- a/plugins/main/public/react-services/pattern-handler.js +++ b/plugins/main/public/react-services/pattern-handler.js @@ -26,8 +26,12 @@ export class PatternHandler { const defaultPatterns = [pattern]; const selectedPattern = AppState.getCurrentPattern(); - if (selectedPattern && selectedPattern !== pattern) defaultPatterns.push(selectedPattern); - let patternList = await SavedObject.getListOfWazuhValidIndexPatterns(defaultPatterns, origin); + if (selectedPattern && selectedPattern !== pattern) + defaultPatterns.push(selectedPattern); + let patternList = await SavedObject.getListOfWazuhValidIndexPatterns( + defaultPatterns, + origin, + ); return patternList; } catch (error) { @@ -54,11 +58,11 @@ export class PatternHandler { * Refresh current pattern for the given pattern * @param newFields */ - static async refreshIndexPattern(newFields = null) { + static async refreshIndexPattern() { try { const currentPattern = AppState.getCurrentPattern(); const pattern = await getDataPlugin().indexPatterns.get(currentPattern); - await SavedObject.refreshIndexPattern(pattern, newFields); + await SavedObject.refreshIndexPattern(pattern); } catch (error) { throw new Error(error); } diff --git a/plugins/main/public/react-services/saved-objects.js b/plugins/main/public/react-services/saved-objects.js index 518875a355..f9818aecdb 100644 --- a/plugins/main/public/react-services/saved-objects.js +++ b/plugins/main/public/react-services/saved-objects.js @@ -22,7 +22,7 @@ import { WAZUH_INDEX_TYPE_MONITORING, WAZUH_INDEX_TYPE_STATISTICS, } from '../../common/constants'; -import { getSavedObjects } from '../kibana-services'; +import { getDataPlugin, getSavedObjects } from '../kibana-services'; import { webDocumentationLink } from '../../common/services/web_documentation'; import { ErrorFactory } from './error-management'; import { WarningError } from './error-management/error-factory/errors/WarningError'; @@ -239,45 +239,20 @@ export class SavedObject { * Refresh an index pattern * Optionally force a new field */ - static async refreshIndexPattern(pattern, newFields = null) { - try { - const fields = await SavedObject.getIndicesFields( - pattern.title, - WAZUH_INDEX_TYPE_ALERTS, - ); - - if (newFields && typeof newFields == 'object') - Object.keys(newFields).forEach(fieldName => { - if (this.isValidField(newFields[fieldName])) - fields.push(newFields[fieldName]); - }); - - await this.refreshFieldsOfIndexPattern(pattern.id, pattern.title, fields); - } catch (error) { - return ((error || {}).data || {}).message || false - ? error.data.message - : error.message || error; - } - } + static async refreshIndexPattern(pattern) { + /* Refresh fields using the same way that the Dashboards Management/Index patterns + https://github.com/opensearch-project/OpenSearch-Dashboards/blob/2.11.0/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx#L136-L137 - /** - * Checks the field has a proper structure - * @param {index-pattern-field} field - */ - static isValidField(field) { - if (field == null || typeof field != 'object') return false; - - const isValid = [ - 'name', - 'type', - 'esTypes', - 'searchable', - 'aggregatable', - 'readFromDocValues', - ].reduce((ok, prop) => { - return ok && Object.keys(field).includes(prop); - }, true); - return isValid; + This approach takes the definition of indexPatterns.refreshFields instead of using it due to + the error management that causes that unwanted toasts are displayed when there are no + indices for the index pattern + */ + const fields = await getDataPlugin().indexPatterns.getFieldsForIndexPattern( + pattern, + ); + const scripted = pattern.getScriptedFields().map(field => field.spec); + pattern.fields.replaceAll([...fields, ...scripted]); + await getDataPlugin().indexPatterns.updateSavedObject(pattern); } /**