-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
template.ts
658 lines (604 loc) · 19.7 KB
/
template.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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/*
* 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 type { ElasticsearchClient, Logger } from '@kbn/core/server';
import type { IndicesIndexSettings } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { Field, Fields } from '../../fields/field';
import type {
RegistryDataStream,
IndexTemplateEntry,
IndexTemplate,
IndexTemplateMappings,
} from '../../../../types';
import { appContextService } from '../../..';
import { getRegistryDataStreamAssetBaseName } from '../../../../../common/services';
import {
FLEET_GLOBALS_COMPONENT_TEMPLATE_NAME,
FLEET_AGENT_ID_VERIFY_COMPONENT_TEMPLATE_NAME,
} from '../../../../constants';
import { getESAssetMetadata } from '../meta';
import { retryTransientEsErrors } from '../retry';
import { getDefaultProperties, histogram, scaledFloat } from './mappings';
interface Properties {
[key: string]: any;
}
interface MultiFields {
[key: string]: object;
}
export interface IndexTemplateMapping {
[key: string]: any;
}
export interface CurrentDataStream {
dataStreamName: string;
replicated: boolean;
indexTemplate: IndexTemplate;
}
const DEFAULT_IGNORE_ABOVE = 1024;
// see discussion in https://github.com/elastic/kibana/issues/88307
const DEFAULT_TEMPLATE_PRIORITY = 200;
const DATASET_IS_PREFIX_TEMPLATE_PRIORITY = 150;
const META_PROP_KEYS = ['metric_type', 'unit'];
/**
* getTemplate retrieves the default template but overwrites the index pattern with the given value.
*
* @param indexPattern String with the index pattern
*/
export function getTemplate({
templateIndexPattern,
pipelineName,
packageName,
composedOfTemplates,
templatePriority,
hidden,
}: {
templateIndexPattern: string;
pipelineName?: string | undefined;
packageName: string;
composedOfTemplates: string[];
templatePriority: number;
hidden?: boolean;
}): IndexTemplate {
const template = getBaseTemplate(
templateIndexPattern,
packageName,
composedOfTemplates,
templatePriority,
hidden
);
if (pipelineName) {
template.template.settings.index.default_pipeline = pipelineName;
}
if (template.template.settings.index.final_pipeline) {
throw new Error(`Error template for ${templateIndexPattern} contains a final_pipeline`);
}
template.composed_of = [
...(template.composed_of || []),
FLEET_GLOBALS_COMPONENT_TEMPLATE_NAME,
...(appContextService.getConfig()?.agentIdVerificationEnabled
? [FLEET_AGENT_ID_VERIFY_COMPONENT_TEMPLATE_NAME]
: []),
];
return template;
}
/**
* Generate mapping takes the given nested fields array and creates the Elasticsearch
* mapping properties out of it.
*
* This assumes that all fields with dotted.names have been expanded in a previous step.
*
* @param fields
*/
export function generateMappings(fields: Field[]): IndexTemplateMappings {
const dynamicTemplates: Array<Record<string, Properties>> = [];
const dynamicTemplateNames = new Set<string>();
const { properties } = _generateMappings(fields, {
addDynamicMapping: (dynamicMapping: {
path: string;
matchingType: string;
pathMatch: string;
properties: string;
}) => {
const name = dynamicMapping.path;
if (dynamicTemplateNames.has(name)) {
return;
}
const dynamicTemplate: Properties = {
mapping: dynamicMapping.properties,
};
if (dynamicMapping.matchingType) {
dynamicTemplate.match_mapping_type = dynamicMapping.matchingType;
}
if (dynamicMapping.pathMatch) {
dynamicTemplate.path_match = dynamicMapping.pathMatch;
}
dynamicTemplateNames.add(name);
dynamicTemplates.push({ [dynamicMapping.path]: dynamicTemplate });
},
});
return dynamicTemplates.length
? {
properties,
dynamic_templates: dynamicTemplates,
}
: { properties };
}
/**
* Generate mapping takes the given nested fields array and creates the Elasticsearch
* mapping properties out of it.
*
* This assumes that all fields with dotted.names have been expanded in a previous step.
*
* @param fields
*/
function _generateMappings(
fields: Field[],
ctx: {
addDynamicMapping: any;
groupFieldName?: string;
}
): {
properties: IndexTemplateMappings['properties'];
hasNonDynamicTemplateMappings: boolean;
} {
let hasNonDynamicTemplateMappings = false;
const props: Properties = {};
// TODO: this can happen when the fields property in fields.yml is present but empty
// Maybe validation should be moved to fields/field.ts
if (fields) {
fields.forEach((field) => {
// If type is not defined, assume keyword
const type = field.type || 'keyword';
if (type === 'object' && field.object_type) {
const path = ctx.groupFieldName ? `${ctx.groupFieldName}.${field.name}` : field.name;
const pathMatch = path.includes('*') ? path : `${path}.*`;
let dynProperties: Properties = getDefaultProperties(field);
let matchingType: string | undefined;
switch (field.object_type) {
case 'histogram':
dynProperties = histogram(field);
matchingType = field.object_type_mapping_type ?? '*';
break;
case 'text':
dynProperties.type = field.object_type;
matchingType = field.object_type_mapping_type ?? 'string';
break;
case 'keyword':
dynProperties.type = field.object_type;
matchingType = field.object_type_mapping_type ?? 'string';
break;
case 'byte':
case 'double':
case 'float':
case 'long':
case 'short':
case 'boolean':
dynProperties = {
type: field.object_type,
};
matchingType = field.object_type_mapping_type ?? field.object_type;
default:
break;
}
if (dynProperties && matchingType) {
ctx.addDynamicMapping({
path,
pathMatch,
matchingType,
properties: dynProperties,
});
}
} else {
let fieldProps = getDefaultProperties(field);
switch (type) {
case 'group':
const mappings = _generateMappings(field.fields!, {
...ctx,
groupFieldName: ctx.groupFieldName
? `${ctx.groupFieldName}.${field.name}`
: field.name,
});
if (!mappings.hasNonDynamicTemplateMappings) {
return;
}
fieldProps = {
properties: mappings.properties,
...generateDynamicAndEnabled(field),
};
break;
case 'group-nested':
fieldProps = {
properties: _generateMappings(field.fields!, {
...ctx,
groupFieldName: ctx.groupFieldName
? `${ctx.groupFieldName}.${field.name}`
: field.name,
}).properties,
...generateNestedProps(field),
type: 'nested',
};
break;
case 'integer':
fieldProps.type = 'long';
break;
case 'scaled_float':
fieldProps = scaledFloat(field);
break;
case 'text':
const textMapping = generateTextMapping(field);
fieldProps = { ...fieldProps, ...textMapping, type: 'text' };
if (field.multi_fields) {
fieldProps.fields = generateMultiFields(field.multi_fields);
}
break;
case 'object':
fieldProps = { ...fieldProps, ...generateDynamicAndEnabled(field), type: 'object' };
break;
case 'keyword':
const keywordMapping = generateKeywordMapping(field);
fieldProps = { ...fieldProps, ...keywordMapping, type: 'keyword' };
if (field.multi_fields) {
fieldProps.fields = generateMultiFields(field.multi_fields);
}
break;
case 'wildcard':
const wildcardMapping = generateWildcardMapping(field);
fieldProps = { ...fieldProps, ...wildcardMapping, type: 'wildcard' };
if (field.multi_fields) {
fieldProps.fields = generateMultiFields(field.multi_fields);
}
break;
case 'constant_keyword':
fieldProps.type = field.type;
if (field.value) {
fieldProps.value = field.value;
}
break;
case 'nested':
fieldProps = { ...fieldProps, ...generateNestedProps(field), type: 'nested' };
break;
case 'array':
// this assumes array fields were validated in an earlier step
// adding an array field with no object_type would result in an error
// when the template is added to ES
if (field.object_type) {
fieldProps.type = field.object_type;
}
break;
case 'alias':
// this assumes alias fields were validated in an earlier step
// adding a path to a field that doesn't exist would result in an error
// when the template is added to ES.
fieldProps.type = 'alias';
fieldProps.path = field.path;
break;
default:
fieldProps.type = type;
}
const fieldHasMetaProps = META_PROP_KEYS.some((key) => key in field);
if (fieldHasMetaProps) {
switch (type) {
case 'group':
case 'group-nested':
break;
default: {
const meta = {};
if ('metric_type' in field) Reflect.set(meta, 'metric_type', field.metric_type);
if ('unit' in field) Reflect.set(meta, 'unit', field.unit);
fieldProps.meta = meta;
}
}
}
props[field.name] = fieldProps;
hasNonDynamicTemplateMappings = true;
}
});
}
return { properties: props, hasNonDynamicTemplateMappings };
}
function generateDynamicAndEnabled(field: Field) {
const props: Properties = {};
if (field.hasOwnProperty('enabled')) {
props.enabled = field.enabled;
}
if (field.hasOwnProperty('dynamic')) {
props.dynamic = field.dynamic;
}
return props;
}
function generateNestedProps(field: Field) {
const props = generateDynamicAndEnabled(field);
if (field.hasOwnProperty('include_in_parent')) {
props.include_in_parent = field.include_in_parent;
}
if (field.hasOwnProperty('include_in_root')) {
props.include_in_root = field.include_in_root;
}
return props;
}
function generateMultiFields(fields: Fields): MultiFields {
const multiFields: MultiFields = {};
if (fields) {
fields.forEach((f: Field) => {
const type = f.type;
switch (type) {
case 'text':
multiFields[f.name] = { ...generateTextMapping(f), type: f.type };
break;
case 'keyword':
multiFields[f.name] = { ...generateKeywordMapping(f), type: f.type };
break;
case 'long':
case 'double':
case 'match_only_text':
multiFields[f.name] = { type: f.type };
break;
}
});
}
return multiFields;
}
function generateKeywordMapping(field: Field): IndexTemplateMapping {
const mapping: IndexTemplateMapping = {
ignore_above: DEFAULT_IGNORE_ABOVE,
};
if (field.ignore_above) {
mapping.ignore_above = field.ignore_above;
}
if (field.normalizer) {
mapping.normalizer = field.normalizer;
}
if (field.dimension) {
mapping.time_series_dimension = field.dimension;
delete mapping.ignore_above;
}
return mapping;
}
function generateTextMapping(field: Field): IndexTemplateMapping {
const mapping: IndexTemplateMapping = {};
if (field.analyzer) {
mapping.analyzer = field.analyzer;
}
if (field.search_analyzer) {
mapping.search_analyzer = field.search_analyzer;
}
return mapping;
}
function generateWildcardMapping(field: Field): IndexTemplateMapping {
const mapping: IndexTemplateMapping = {
ignore_above: DEFAULT_IGNORE_ABOVE,
};
if (field.null_value) {
mapping.null_value = field.null_value;
}
if (field.ignore_above) {
mapping.ignore_above = field.ignore_above;
}
return mapping;
}
/**
* Generates the template name out of the given information
*/
export function generateTemplateName(dataStream: RegistryDataStream): string {
return getRegistryDataStreamAssetBaseName(dataStream);
}
/**
* Given a data stream name, return the indexTemplate name
*/
function dataStreamNameToIndexTemplateName(dataStreamName: string): string {
const [type, dataset] = dataStreamName.split('-'); // ignore namespace at the end
return [type, dataset].join('-');
}
export function generateTemplateIndexPattern(dataStream: RegistryDataStream): string {
// undefined or explicitly set to false
// See also https://github.com/elastic/package-spec/pull/102
if (!dataStream.dataset_is_prefix) {
return getRegistryDataStreamAssetBaseName(dataStream) + '-*';
} else {
return getRegistryDataStreamAssetBaseName(dataStream) + '.*-*';
}
}
// Template priorities are discussed in https://github.com/elastic/kibana/issues/88307
// See also https://www.elastic.co/guide/en/elasticsearch/reference/current/index-templates.html
//
// Built-in templates like logs-*-* and metrics-*-* have priority 100
//
// EPM generated templates for data streams have priority 200 (DEFAULT_TEMPLATE_PRIORITY)
//
// EPM generated templates for data streams with dataset_is_prefix: true have priority 150 (DATASET_IS_PREFIX_TEMPLATE_PRIORITY)
export function getTemplatePriority(dataStream: RegistryDataStream): number {
// undefined or explicitly set to false
// See also https://github.com/elastic/package-spec/pull/102
if (!dataStream.dataset_is_prefix) {
return DEFAULT_TEMPLATE_PRIORITY;
} else {
return DATASET_IS_PREFIX_TEMPLATE_PRIORITY;
}
}
/**
* Returns a map of the data stream path fields to elasticsearch index pattern.
* @param dataStreams an array of RegistryDataStream objects
*/
export function generateESIndexPatterns(
dataStreams: RegistryDataStream[] | undefined
): Record<string, string> {
if (!dataStreams) {
return {};
}
const patterns: Record<string, string> = {};
for (const dataStream of dataStreams) {
patterns[dataStream.path] = generateTemplateIndexPattern(dataStream);
}
return patterns;
}
const flattenFieldsToNameAndType = (
fields: Fields,
path: string = ''
): Array<Pick<Field, 'name' | 'type'>> => {
let newFields: Array<Pick<Field, 'name' | 'type'>> = [];
fields.forEach((field) => {
const fieldName = path ? `${path}.${field.name}` : field.name;
newFields.push({
name: fieldName,
type: field.type,
});
if (field.fields && field.fields.length) {
newFields = newFields.concat(flattenFieldsToNameAndType(field.fields, fieldName));
}
});
return newFields;
};
function getBaseTemplate(
templateIndexPattern: string,
packageName: string,
composedOfTemplates: string[],
templatePriority: number,
hidden?: boolean
): IndexTemplate {
const _meta = getESAssetMetadata({ packageName });
return {
priority: templatePriority,
index_patterns: [templateIndexPattern],
template: {
settings: {
index: {},
},
mappings: {
_meta,
},
},
data_stream: { hidden },
composed_of: composedOfTemplates,
_meta,
};
}
export const updateCurrentWriteIndices = async (
esClient: ElasticsearchClient,
logger: Logger,
templates: IndexTemplateEntry[]
): Promise<void> => {
if (!templates.length) return;
const allIndices = await queryDataStreamsFromTemplates(esClient, templates);
const allUpdatablesIndices = allIndices.filter((indice) => {
if (indice.replicated) {
logger.warn(
`Datastream ${indice.dataStreamName} cannot be updated because this is a replicated datastream.`
);
return false;
}
return true;
});
if (!allUpdatablesIndices.length) return;
return updateAllDataStreams(allUpdatablesIndices, esClient, logger);
};
function isCurrentDataStream(item: CurrentDataStream[] | undefined): item is CurrentDataStream[] {
return item !== undefined;
}
const queryDataStreamsFromTemplates = async (
esClient: ElasticsearchClient,
templates: IndexTemplateEntry[]
): Promise<CurrentDataStream[]> => {
const dataStreamPromises = templates.map((template) => {
return getDataStreams(esClient, template);
});
const dataStreamObjects = await Promise.all(dataStreamPromises);
return dataStreamObjects.filter(isCurrentDataStream).flat();
};
const getDataStreams = async (
esClient: ElasticsearchClient,
template: IndexTemplateEntry
): Promise<CurrentDataStream[] | undefined> => {
const { indexTemplate } = template;
const body = await esClient.indices.getDataStream({
name: indexTemplate.index_patterns.join(','),
});
const dataStreams = body.data_streams;
if (!dataStreams.length) return;
return dataStreams.map((dataStream: any) => ({
dataStreamName: dataStream.name,
replicated: dataStream.replicated,
indexTemplate,
}));
};
const rolloverDataStream = (dataStreamName: string, esClient: ElasticsearchClient) => {
try {
// Do no wrap rollovers in retryTransientEsErrors since it is not idempotent
return esClient.indices.rollover({
alias: dataStreamName,
});
} catch (error) {
throw new Error(`cannot rollover data stream [${dataStreamName}] due to error: ${error}`);
}
};
const updateAllDataStreams = async (
indexNameWithTemplates: CurrentDataStream[],
esClient: ElasticsearchClient,
logger: Logger
): Promise<void> => {
const updatedataStreamPromises = indexNameWithTemplates.map((templateEntry) => {
return updateExistingDataStream({
esClient,
logger,
dataStreamName: templateEntry.dataStreamName,
});
});
await Promise.all(updatedataStreamPromises);
};
const updateExistingDataStream = async ({
dataStreamName,
esClient,
logger,
}: {
dataStreamName: string;
esClient: ElasticsearchClient;
logger: Logger;
}) => {
let settings: IndicesIndexSettings;
try {
const simulateResult = await retryTransientEsErrors(() =>
esClient.indices.simulateTemplate({
name: dataStreamNameToIndexTemplateName(dataStreamName),
})
);
settings = simulateResult.template.settings;
const mappings = simulateResult.template.mappings;
// for now, remove from object so as not to update stream or data stream properties of the index until type and name
// are added in https://github.com/elastic/kibana/issues/66551. namespace value we will continue
// to skip updating and assume the value in the index mapping is correct
if (mappings && mappings.properties) {
delete mappings.properties.stream;
delete mappings.properties.data_stream;
}
await retryTransientEsErrors(
() =>
esClient.indices.putMapping({
index: dataStreamName,
body: mappings || {},
write_index_only: true,
}),
{ logger }
);
// if update fails, rollover data stream
} catch (err) {
await rolloverDataStream(dataStreamName, esClient);
return;
}
// update settings after mappings was successful to ensure
// pointing to the new pipeline is safe
// for now, only update the pipeline
if (!settings?.index?.default_pipeline) return;
try {
await retryTransientEsErrors(
() =>
esClient.indices.putSettings({
index: dataStreamName,
body: { default_pipeline: settings!.index!.default_pipeline },
}),
{ logger }
);
} catch (err) {
throw new Error(`could not update index template settings for ${dataStreamName}`);
}
};