Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4b78e40
Add component template versioning to RuleDataClient
marshallmain Jun 17, 2021
33461c1
Add versioning for index templates
marshallmain Jun 17, 2021
19b9eaf
Address PR comments, add error handling inside rolloverAliasIfNeeded
marshallmain Jun 21, 2021
3a1fe7c
Merge branch 'master' into rule-data-client-index-versioning
kibanamachine Jun 21, 2021
bbd8335
Fix security alerts index name, rollover func param, more robust roll…
marshallmain Jun 23, 2021
4ccf63a
Add empty mapping check to createOrUpdateIndexTemplate
marshallmain Jun 23, 2021
c9c7a87
Fix error path in createWriteTargetIfNeeded to suppress resource_alre…
marshallmain Jun 23, 2021
cd184c3
Merge branch 'rule-data-client-index-versioning' of github.com:marsha…
marshallmain Jun 23, 2021
a45a70a
Add code comments around rollover logic
marshallmain Jun 23, 2021
be0f777
Replace numeric versions with semver
marshallmain Jun 24, 2021
c8e2642
Use optional chaining operator to fetch current write index mapping
marshallmain Jun 24, 2021
7a4bc11
Fix template version number
marshallmain Jun 24, 2021
efcf928
Merge branch 'master' into rule-data-client-index-versioning
kibanamachine Jun 24, 2021
852a8b0
Move mapping updates to plugin startup, remove dependency on componen…
marshallmain Jul 1, 2021
bae03df
Undo changes to lifecycle and persistance rule type factories
marshallmain Jul 1, 2021
5e99679
Merge branch 'master' into rule-data-client-index-versioning
marshallmain Jul 1, 2021
0be60e1
Remove test code
marshallmain Jul 1, 2021
a87dd50
Simplify race mitigation logic
marshallmain Jul 1, 2021
88a4d9e
Remove outdated comment
marshallmain Jul 1, 2021
c1aaa5e
Merge branch 'master' into rule-data-client-index-versioning
kibanamachine Jul 6, 2021
d3f099a
Add unit tests, log unexpected errors instead of rethrowing
marshallmain Jul 6, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions x-pack/plugins/apm/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ export class APMPlugin
const getCoreStart = () =>
core.getStartServices().then(([coreStart]) => coreStart);

const alertsIndexPattern = ruleDataService.getFullAssetName(
'observability-apm*'
);

const initializeRuleDataTemplates = once(async () => {
const componentTemplateName = ruleDataService.getFullAssetName(
'apm-mappings'
Expand Down Expand Up @@ -164,15 +168,16 @@ export class APMPlugin
await ruleDataService.createOrUpdateIndexTemplate({
name: ruleDataService.getFullAssetName('apm-index-template'),
body: {
index_patterns: [
ruleDataService.getFullAssetName('observability-apm*'),
],
index_patterns: [alertsIndexPattern],
composed_of: [
ruleDataService.getFullAssetName(TECHNICAL_COMPONENT_TEMPLATE_NAME),
componentTemplateName,
],
},
});
await ruleDataService.updateIndexMappingsMatchingPattern(
alertsIndexPattern
);
});

// initialize eagerly
Expand Down
23 changes: 3 additions & 20 deletions x-pack/plugins/rule_registry/server/rule_data_client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
* 2.0.
*/

import { isEmpty } from 'lodash';
import type { estypes } from '@elastic/elasticsearch';
import { ResponseError } from '@elastic/elasticsearch/lib/errors';
import { IndexPatternsFetcher } from '../../../../../src/plugins/data/server';
import { RuleDataWriteDisabledError } from '../rule_data_plugin_service/errors';
Expand Down Expand Up @@ -100,7 +98,7 @@ export class RuleDataClient implements IRuleDataClient {
response.body.items.length > 0 &&
response.body.items?.[0]?.index?.error?.type === 'index_not_found_exception'
) {
return this.createOrUpdateWriteTarget({ namespace }).then(() => {
return this.createWriteTargetIfNeeded({ namespace }).then(() => {
return clusterClient.bulk(requestWithDefaultParameters);
});
}
Expand All @@ -113,7 +111,7 @@ export class RuleDataClient implements IRuleDataClient {
};
}

async createOrUpdateWriteTarget({ namespace }: { namespace?: string }) {
async createWriteTargetIfNeeded({ namespace }: { namespace?: string }) {
const alias = getNamespacedAlias({ alias: this.options.alias, namespace });

const clusterClient = await this.getClusterClient();
Expand All @@ -138,25 +136,10 @@ export class RuleDataClient implements IRuleDataClient {
});
} catch (err) {
// something might have created the index already, that sounds OK
if (err?.meta?.body?.type !== 'resource_already_exists_exception') {
if (err?.meta?.body?.error?.type !== 'resource_already_exists_exception') {
throw err;
}
}
}

const { body: simulateResponse } = await clusterClient.transport.request({
method: 'POST',
path: `/_index_template/_simulate_index/${concreteIndexName}`,
});

const mappings: estypes.MappingTypeMapping = simulateResponse.template.mappings;

if (isEmpty(mappings)) {
throw new Error(
'No mappings would be generated for this index, possibly due to failed/misconfigured bootstrapping'
);
}
Comment on lines -155 to -158
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this should be removed. I don't see the same check in rolloverAliasIfNeeded , and I think we should be explicit about this, because teams new to RAC will run into it - I did, too, and it is a little annoying to figure out and repair.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sort of check seems like it belongs with the template bootstrapping logic IMO. At this point we've already created the index, so simulating it seems redundant. Can we move this check so it happens sometime before the index is created, maybe at index template creation time?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine with moving it, but I do would like to keep it, somewhere. But let's figure out first where this all needs to happen.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be always some common mappings specified (currently they are specified in templates installed in init() - TECHNICAL_COMPONENT_TEMPLATE_NAME and ECS_COMPONENT_TEMPLATE_NAME). We just have to make sure that final index templates always reference (composed_of) these common component templates.

I'd say this is a matter of having an API that doesn't provide 100% flexibility in index bootstrapping and makes sure that index template is always created and it always references the common templates - doesn't matter how the client of the library uses it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved this check to index template creation time in 4ccf63a


await clusterClient.indices.putMapping({ index: `${alias}*`, body: mappings });
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface RuleDataWriter {
export interface IRuleDataClient {
getReader(options?: { namespace?: string }): RuleDataReader;
getWriter(options?: { namespace?: string }): RuleDataWriter;
createOrUpdateWriteTarget(options: { namespace?: string }): Promise<void>;
createWriteTargetIfNeeded(options: { namespace?: string }): Promise<void>;
}

export interface RuleDataClientConstructorOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { ClusterPutComponentTemplate } from '@elastic/elasticsearch/api/requestParams';
import { estypes } from '@elastic/elasticsearch';
import { ElasticsearchClient, Logger } from 'kibana/server';
import { get, isEmpty } from 'lodash';
import { technicalComponentTemplate } from '../../common/assets/component_templates/technical_component_template';
import {
DEFAULT_ILM_POLICY_ID,
Expand All @@ -18,6 +19,7 @@ import { defaultLifecyclePolicy } from '../../common/assets/lifecycle_policies/d
import { ClusterPutComponentTemplateBody, PutIndexTemplateRequest } from '../../common/types';
import { RuleDataClient } from '../rule_data_client';
import { RuleDataWriteDisabledError } from './errors';
import { incrementIndexName } from './utils';

const BOOTSTRAP_TIMEOUT = 60000;

Expand Down Expand Up @@ -109,6 +111,14 @@ export class RuleDataPluginService {

const clusterClient = await this.getClusterClient();
this.options.logger.debug(`Installing index template ${template.name}`);
const { body: simulateResponse } = await clusterClient.indices.simulateTemplate(template);
const mappings: estypes.MappingTypeMapping = simulateResponse.template.mappings;

if (isEmpty(mappings)) {
throw new Error(
'No mappings would be generated for this index, possibly due to failed/misconfigured bootstrapping'
);
}
return clusterClient.indices.putIndexTemplate(template);
}

Expand All @@ -120,6 +130,42 @@ export class RuleDataPluginService {
return clusterClient.ilm.putLifecycle(policy);
}

private async updateAliasWriteIndexMapping({ index, alias }: { index: string; alias: string }) {
const clusterClient = await this.getClusterClient();

const simulatedIndexMapping = await clusterClient.indices.simulateIndexTemplate({
name: index,
});
const simulatedMapping = get(simulatedIndexMapping, ['body', 'template', 'mappings']);
try {
await clusterClient.indices.putMapping({
index,
body: simulatedMapping,
});
return;
} catch (err) {
if (err.meta?.body?.error?.type !== 'illegal_argument_exception') {
this.options.logger.error(`Failed to PUT mapping for alias ${alias}: ${err.message}`);
return;
}
const newIndexName = incrementIndexName(index);
if (newIndexName == null) {
this.options.logger.error(`Failed to increment write index name for alias: ${alias}`);
return;
}
try {
await clusterClient.indices.rollover({
alias,
new_index: newIndexName,
});
} catch (e) {
if (e?.meta?.body?.error?.type !== 'resource_already_exists_exception') {
this.options.logger.error(`Failed to rollover index for alias ${alias}: ${e.message}`);
}
}
}
}

async createOrUpdateComponentTemplate(
template: ClusterPutComponentTemplate<ClusterPutComponentTemplateBody>
) {
Expand All @@ -137,6 +183,25 @@ export class RuleDataPluginService {
return this._createOrUpdateLifecyclePolicy(policy);
}

async updateIndexMappingsMatchingPattern(pattern: string) {
await this.wait();
const clusterClient = await this.getClusterClient();
const { body: aliasesResponse } = await clusterClient.indices.getAlias({ index: pattern });
const writeIndicesAndAliases: Array<{ index: string; alias: string }> = [];
Object.entries(aliasesResponse).forEach(([index, aliases]) => {
Object.entries(aliases.aliases).forEach(([aliasName, aliasProperties]) => {
if (aliasProperties.is_write_index) {
writeIndicesAndAliases.push({ index, alias: aliasName });
}
});
});
await Promise.all(
writeIndicesAndAliases.map((indexAndAlias) =>
this.updateAliasWriteIndexMapping(indexAndAlias)
)
);
}

isReady() {
return this.signal.isReady();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { incrementIndexName } from './utils';

describe('incrementIndexName', () => {
it('should increment 000001 to 000002', () => {
const oldIndex = '.alerts-mock-000001';
const newIndex = incrementIndexName(oldIndex);
expect(newIndex).toEqual('.alerts-mock-000002');
});

it('should increment 000010 to 000011', () => {
const oldIndex = '.alerts-mock-000010';
const newIndex = incrementIndexName(oldIndex);
expect(newIndex).toEqual('.alerts-mock-000011');
});

it('should return undefined if oldIndex does not end in a number', () => {
const oldIndex = '.alerts-mock-string';
const newIndex = incrementIndexName(oldIndex);
expect(newIndex).toEqual(undefined);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export function incrementIndexName(oldIndex: string) {
const baseIndexString = oldIndex.slice(0, -6);
const newIndexNumber = Number(oldIndex.slice(-6)) + 1;
if (isNaN(newIndexNumber)) {
return undefined;
}
return baseIndexString + String(newIndexNumber).padStart(6, '0');
}
13 changes: 7 additions & 6 deletions x-pack/plugins/security_solution/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,10 @@ export class Plugin implements IPlugin<PluginSetup, PluginStart, SetupPlugins, S
if (isRuleRegistryEnabled) {
const { ruleDataService } = plugins.ruleRegistry;

const alertsIndexPattern = ruleDataService.getFullAssetName('security.alerts*');

const initializeRuleDataTemplates = once(async () => {
const componentTemplateName = ruleDataService.getFullAssetName(
'security-solution-mappings'
);
const componentTemplateName = ruleDataService.getFullAssetName('security.alerts-mappings');

if (!ruleDataService.isWriteEnabled()) {
return;
Expand All @@ -219,16 +219,17 @@ export class Plugin implements IPlugin<PluginSetup, PluginStart, SetupPlugins, S
});

await ruleDataService.createOrUpdateIndexTemplate({
name: ruleDataService.getFullAssetName('security-solution-index-template'),
name: ruleDataService.getFullAssetName('security.alerts-index-template'),
body: {
index_patterns: [ruleDataService.getFullAssetName('security-solution*')],
index_patterns: [alertsIndexPattern],
composed_of: [
ruleDataService.getFullAssetName(TECHNICAL_COMPONENT_TEMPLATE_NAME),
ruleDataService.getFullAssetName(ECS_COMPONENT_TEMPLATE_NAME),
componentTemplateName,
],
},
});
await ruleDataService.updateIndexMappingsMatchingPattern(alertsIndexPattern);
});

// initialize eagerly
Expand All @@ -237,7 +238,7 @@ export class Plugin implements IPlugin<PluginSetup, PluginStart, SetupPlugins, S
});

ruleDataClient = ruleDataService.getRuleDataClient(
ruleDataService.getFullAssetName('security-solution'),
ruleDataService.getFullAssetName('security.alerts'),
() => initializeRuleDataTemplatesPromise
);

Expand Down