-
Notifications
You must be signed in to change notification settings - Fork 8k
/
template.ts
1102 lines (1006 loc) · 34 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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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,
MappingTypeMapping,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import pMap from 'p-map';
import { isResponseError } from '@kbn/es-errors';
import type { Field, Fields } from '../../fields/field';
import type {
RegistryDataStream,
IndexTemplateEntry,
IndexTemplate,
IndexTemplateMappings,
RegistryElasticsearch,
} from '../../../../types';
import { appContextService } from '../../..';
import { getRegistryDataStreamAssetBaseName } from '../../../../../common/services';
import {
FLEET_GLOBALS_COMPONENT_TEMPLATE_NAME,
FLEET_AGENT_ID_VERIFY_COMPONENT_TEMPLATE_NAME,
STACK_COMPONENT_TEMPLATE_LOGS_SETTINGS,
STACK_COMPONENT_TEMPLATE_METRICS_SETTINGS,
STACK_COMPONENT_TEMPLATE_METRICS_TSDB_SETTINGS,
} from '../../../../constants';
import { getESAssetMetadata } from '../meta';
import { retryTransientEsErrors } from '../retry';
import { PackageESError, PackageInvalidArchiveError } from '../../../../errors';
import { getDefaultProperties, histogram, keyword, scaledFloat } from './mappings';
interface Properties {
[key: string]: any;
}
interface MultiFields {
[key: string]: object;
}
interface RuntimeFields {
[key: string]: any;
}
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,
packageName,
composedOfTemplates,
templatePriority,
hidden,
registryElasticsearch,
mappings,
isIndexModeTimeSeries,
type,
}: {
templateIndexPattern: string;
packageName: string;
composedOfTemplates: string[];
templatePriority: number;
mappings: IndexTemplateMappings;
type: string;
hidden?: boolean;
registryElasticsearch?: RegistryElasticsearch | undefined;
isIndexModeTimeSeries?: boolean;
}): IndexTemplate {
const template = getBaseTemplate({
templateIndexPattern,
packageName,
composedOfTemplates,
templatePriority,
registryElasticsearch,
hidden,
mappings,
isIndexModeTimeSeries,
});
if (template.template.settings.index.final_pipeline) {
throw new PackageInvalidArchiveError(
`Error template for ${templateIndexPattern} contains a final_pipeline`
);
}
const esBaseComponents = getBaseEsComponents(type, !!isIndexModeTimeSeries);
template.composed_of = [
...esBaseComponents,
...(template.composed_of || []),
FLEET_GLOBALS_COMPONENT_TEMPLATE_NAME,
...(appContextService.getConfig()?.agentIdVerificationEnabled
? [FLEET_AGENT_ID_VERIFY_COMPONENT_TEMPLATE_NAME]
: []),
];
return template;
}
const getBaseEsComponents = (type: string, isIndexModeTimeSeries: boolean): string[] => {
if (type === 'metrics') {
if (isIndexModeTimeSeries) {
return [STACK_COMPONENT_TEMPLATE_METRICS_TSDB_SETTINGS];
}
return [STACK_COMPONENT_TEMPLATE_METRICS_SETTINGS];
} else if (type === 'logs') {
return [STACK_COMPONENT_TEMPLATE_LOGS_SETTINGS];
}
return [];
};
/**
* 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[],
isIndexModeTimeSeries = false
): IndexTemplateMappings {
const dynamicTemplates: Array<Record<string, Properties>> = [];
const dynamicTemplateNames: Record<string, number> = {};
const runtimeFields: RuntimeFields = {};
const { properties } = _generateMappings(
fields,
{
addDynamicMapping: (dynamicMapping: {
path: string;
matchingType: string;
pathMatch: string;
properties: Properties;
runtimeProperties?: Properties;
}) => {
const name = dynamicMapping.path;
if (name in dynamicTemplateNames) {
if (name.includes('*') && dynamicMapping.properties?.type === 'object') {
// This is a conflicting intermediate object, use the last one so
// more specific templates are chosen before.
const index = dynamicTemplateNames[name];
delete dynamicTemplateNames[name];
dynamicTemplates.splice(index, 1);
} else {
return;
}
}
const dynamicTemplate: Properties = {};
if (dynamicMapping.runtimeProperties !== undefined) {
dynamicTemplate.runtime = dynamicMapping.runtimeProperties;
} else {
dynamicTemplate.mapping = dynamicMapping.properties;
}
if (dynamicMapping.matchingType) {
dynamicTemplate.match_mapping_type = dynamicMapping.matchingType;
}
if (dynamicMapping.pathMatch) {
dynamicTemplate.path_match = dynamicMapping.pathMatch;
}
const size = dynamicTemplates.push({ [name]: dynamicTemplate });
dynamicTemplateNames[name] = size - 1;
},
addRuntimeField: (runtimeField: { path: string; properties: Properties }) => {
runtimeFields[`${runtimeField.path}`] = runtimeField.properties;
},
},
isIndexModeTimeSeries
);
const indexTemplateMappings: IndexTemplateMappings = { properties };
if (dynamicTemplates.length > 0) {
indexTemplateMappings.dynamic_templates = dynamicTemplates;
}
if (Object.keys(runtimeFields).length > 0) {
indexTemplateMappings.runtime = runtimeFields;
}
return indexTemplateMappings;
}
/**
* 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;
addRuntimeField: any;
groupFieldName?: string;
},
isIndexModeTimeSeries: boolean
): {
properties: IndexTemplateMappings['properties'];
hasNonDynamicTemplateMappings: boolean;
hasDynamicTemplateMappings: boolean;
} {
let hasNonDynamicTemplateMappings = false;
let hasDynamicTemplateMappings = false;
const props: Properties = {};
function addParentObjectAsStaticProperty(field: Field) {
// Don't add intermediate objects for wildcard names, as it will
// be added for its parent object.
if (field.name.includes('*')) {
return;
}
const fieldProps = {
type: 'object',
dynamic: true,
};
props[field.name] = fieldProps;
hasNonDynamicTemplateMappings = true;
}
function addDynamicMappingWithIntermediateObjects(
path: string,
pathMatch: string,
matchingType: string,
dynProperties: Properties,
fieldProps?: Properties
) {
ctx.addDynamicMapping({
path,
pathMatch,
matchingType,
properties: dynProperties,
runtimeProperties: fieldProps,
});
hasDynamicTemplateMappings = true;
// Add dynamic intermediate objects.
const parts = pathMatch.split('.');
for (let i = parts.length - 1; i > 0; i--) {
const name = parts.slice(0, i).join('.');
if (!name.includes('*')) {
continue;
}
const dynProps: Properties = {
type: 'object',
dynamic: true,
};
ctx.addDynamicMapping({
path: name,
pathMatch: name,
matchingType: 'object',
properties: dynProps,
});
}
}
// 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 (field.runtime !== undefined) {
const path = ctx.groupFieldName ? `${ctx.groupFieldName}.${field.name}` : field.name;
let runtimeFieldProps: Properties = getDefaultProperties(field);
// Is it a dynamic template?
if (type === 'object' && field.object_type) {
const pathMatch = path.includes('*') ? path : `${path}.*`;
const dynProperties: Properties = getDefaultProperties(field);
let matchingType: string | undefined;
switch (field.object_type) {
case 'keyword':
dynProperties.type = field.object_type;
matchingType = field.object_type_mapping_type ?? 'string';
break;
case 'double':
case 'long':
case 'boolean':
dynProperties.type = field.object_type;
if (isIndexModeTimeSeries) {
dynProperties.time_series_metric = field.metric_type;
}
matchingType = field.object_type_mapping_type ?? field.object_type;
default:
break;
}
// get the runtime properies of this field assuming type equals to object_type
const _field = { ...field, type: field.object_type };
const fieldProps = generateRuntimeFieldProps(_field);
if (dynProperties && matchingType) {
addDynamicMappingWithIntermediateObjects(
path,
pathMatch,
matchingType,
dynProperties,
fieldProps
);
// Add the parent object as static property, this is needed for
// index templates not using `"dynamic": true`.
addParentObjectAsStaticProperty(field);
}
return;
}
const fieldProps = generateRuntimeFieldProps(field);
runtimeFieldProps = { ...runtimeFieldProps, ...fieldProps };
ctx.addRuntimeField({ path, properties: runtimeFieldProps });
return; // runtime fields should not be added as a property
}
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 'ip':
case 'keyword':
case 'match_only_text':
case 'text':
case 'wildcard':
dynProperties.type = field.object_type;
matchingType = field.object_type_mapping_type ?? 'string';
break;
case 'scaled_float':
dynProperties = scaledFloat(field);
matchingType = field.object_type_mapping_type ?? '*';
break;
case 'aggregate_metric_double':
dynProperties.type = field.object_type;
dynProperties.metrics = field.metrics;
dynProperties.default_metric = field.default_metric;
matchingType = field.object_type_mapping_type ?? '*';
break;
case 'double':
case 'float':
case 'half_float':
dynProperties.type = field.object_type;
if (isIndexModeTimeSeries) {
dynProperties.time_series_metric = field.metric_type;
}
matchingType = field.object_type_mapping_type ?? 'double';
break;
case 'byte':
case 'long':
case 'short':
case 'unsigned_long':
dynProperties.type = field.object_type;
if (isIndexModeTimeSeries) {
dynProperties.time_series_metric = field.metric_type;
}
matchingType = field.object_type_mapping_type ?? 'long';
break;
case 'integer':
// Map integers as long, as in other cases.
dynProperties.type = 'long';
if (isIndexModeTimeSeries) {
dynProperties.time_series_metric = field.metric_type;
}
matchingType = field.object_type_mapping_type ?? 'long';
break;
case 'boolean':
dynProperties.type = field.object_type;
if (isIndexModeTimeSeries) {
dynProperties.time_series_metric = field.metric_type;
}
matchingType = field.object_type_mapping_type ?? field.object_type;
break;
case 'group':
if (!field?.fields) {
break;
}
const subFields = field.fields.map((subField) => ({
...subField,
type: 'object',
object_type: subField.object_type ?? subField.type,
}));
const mappings = _generateMappings(
subFields,
{
...ctx,
groupFieldName: ctx.groupFieldName
? `${ctx.groupFieldName}.${field.name}`
: field.name,
},
isIndexModeTimeSeries
);
if (mappings.hasDynamicTemplateMappings) {
hasDynamicTemplateMappings = true;
}
break;
case 'flattened':
dynProperties.type = field.object_type;
matchingType = field.object_type_mapping_type ?? 'object';
break;
default:
throw new PackageInvalidArchiveError(
`No dynamic mapping generated for field ${path} of type ${field.object_type}`
);
}
if (dynProperties && matchingType) {
addDynamicMappingWithIntermediateObjects(path, pathMatch, matchingType, dynProperties);
// Add the parent object as static property, this is needed for
// index templates not using `"dynamic": true`.
addParentObjectAsStaticProperty(field);
}
} else {
let fieldProps = getDefaultProperties(field);
switch (type) {
case 'group':
const mappings = _generateMappings(
field.fields!,
{
...ctx,
groupFieldName: ctx.groupFieldName
? `${ctx.groupFieldName}.${field.name}`
: field.name,
},
isIndexModeTimeSeries
);
if (mappings.hasNonDynamicTemplateMappings) {
fieldProps = {
properties:
Object.keys(mappings.properties).length > 0 ? mappings.properties : undefined,
...generateDynamicAndEnabled(field),
};
if (mappings.hasDynamicTemplateMappings) {
fieldProps.type = 'object';
fieldProps.dynamic = true;
}
} else if (mappings.hasDynamicTemplateMappings) {
fieldProps = {
type: 'object',
dynamic: true,
};
hasDynamicTemplateMappings = true;
} else {
return;
}
break;
case 'group-nested':
fieldProps = {
properties: _generateMappings(
field.fields!,
{
...ctx,
groupFieldName: ctx.groupFieldName
? `${ctx.groupFieldName}.${field.name}`
: field.name,
},
isIndexModeTimeSeries
).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':
fieldProps = keyword(field);
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;
case 'date':
const dateMappings = generateDateMapping(field);
fieldProps = { ...fieldProps, ...dateMappings, type: 'date' };
break;
case 'aggregate_metric_double':
fieldProps = {
...fieldProps,
metrics: field.metrics,
default_metric: field.default_metric,
type: 'aggregate_metric_double',
};
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 ('unit' in field) Reflect.set(meta, 'unit', field.unit);
fieldProps.meta = meta;
}
}
}
if ('metric_type' in field && isIndexModeTimeSeries) {
fieldProps.time_series_metric = field.metric_type;
}
if (field.dimension && isIndexModeTimeSeries) {
fieldProps.time_series_dimension = field.dimension;
}
// Even if we don't add the property because it has a wildcard, notify
// the parent that there is some kind of property, so the intermediate object
// is still created.
// This is done for legacy packages that include ambiguous mappings with objects
// without object type. This is not allowed starting on Package Spec v3.
hasNonDynamicTemplateMappings = true;
// Avoid including maps with wildcards, they have generated dynamic mappings.
if (field.name.includes('*')) {
hasDynamicTemplateMappings = true;
return;
}
props[field.name] = fieldProps;
}
});
}
return { properties: props, hasNonDynamicTemplateMappings, hasDynamicTemplateMappings };
}
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] = keyword(f);
break;
case 'long':
case 'double':
case 'match_only_text':
multiFields[f.name] = { type: f.type };
break;
}
});
}
return multiFields;
}
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;
}
function generateDateMapping(field: Field): IndexTemplateMapping {
const mapping: IndexTemplateMapping = {};
if (field.date_format) {
mapping.format = field.date_format;
}
if (field.name === '@timestamp') {
mapping.ignore_malformed = false;
}
return mapping;
}
function generateRuntimeFieldProps(field: Field): IndexTemplateMapping {
let mapping: IndexTemplateMapping = {};
const type = field.type || keyword;
switch (type) {
case 'integer':
mapping.type = 'long';
break;
case 'date':
const dateMappings = generateDateMapping(field);
mapping = { ...mapping, ...dateMappings, type: 'date' };
break;
default:
mapping.type = type;
}
if (typeof field.runtime === 'string') {
const scriptObject = {
source: field.runtime.trim(),
};
mapping.script = scriptObject;
}
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
*/
async function getIndexTemplate(
esClient: ElasticsearchClient,
dataStreamName: string
): Promise<string> {
const dataStream = await esClient.indices.getDataStream({
name: dataStreamName,
expand_wildcards: ['open', 'hidden'],
});
return dataStream.data_streams[0].template;
}
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,
packageName,
composedOfTemplates,
templatePriority,
hidden,
registryElasticsearch,
mappings,
isIndexModeTimeSeries,
}: {
templateIndexPattern: string;
packageName: string;
composedOfTemplates: string[];
templatePriority: number;
hidden?: boolean;
registryElasticsearch: RegistryElasticsearch | undefined;
mappings: IndexTemplateMappings;
isIndexModeTimeSeries?: boolean;
}): IndexTemplate {
const _meta = getESAssetMetadata({ packageName });
let settingsIndex = {};
if (isIndexModeTimeSeries) {
settingsIndex = {
mode: 'time_series',
};
}
return {
priority: templatePriority,
index_patterns: [templateIndexPattern],
template: {
settings: {
index: settingsIndex,
},
mappings: {
_meta,
},
},
data_stream: {
hidden: registryElasticsearch?.['index_template.data_stream']?.hidden || hidden,
},
composed_of: composedOfTemplates,
_meta,
};
}
export const updateCurrentWriteIndices = async (
esClient: ElasticsearchClient,
logger: Logger,
templates: IndexTemplateEntry[],
options?: {
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
}
): 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, options);
};
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(','),
expand_wildcards: ['open', 'hidden'],
});
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 PackageESError(
`Cannot rollover data stream [${dataStreamName}] due to error: ${error}`
);
}
};
const updateAllDataStreams = async (
indexNameWithTemplates: CurrentDataStream[],
esClient: ElasticsearchClient,
logger: Logger,
options?: {
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
}
): Promise<void> => {
await pMap(
indexNameWithTemplates,
(templateEntry) => {
return updateExistingDataStream({
esClient,
logger,
dataStreamName: templateEntry.dataStreamName,
options,
});
},
{
// Limit concurrent putMapping/rollover requests to avoid overhwhelming ES cluster
concurrency: 20,
}
);
};
const updateExistingDataStream = async ({
dataStreamName,
esClient,
logger,
options,
}: {
dataStreamName: string;
esClient: ElasticsearchClient;
logger: Logger;
options?: {
ignoreMappingUpdateErrors?: boolean;
skipDataStreamRollover?: boolean;
};
}) => {
const existingDs = await esClient.indices.get({
index: dataStreamName,
});
const existingDsConfig = Object.values(existingDs);
const currentBackingIndexConfig = existingDsConfig.at(-1);
const currentIndexMode = currentBackingIndexConfig?.settings?.index?.mode;
// @ts-expect-error Property 'mode' does not exist on type 'MappingSourceField'
const currentSourceType = currentBackingIndexConfig.mappings?._source?.mode;
let settings: IndicesIndexSettings;
let mappings: MappingTypeMapping;
let lifecycle: any;
try {
const simulateResult = await retryTransientEsErrors(async () =>
esClient.indices.simulateTemplate({
name: await getIndexTemplate(esClient, dataStreamName),
})
);
settings = simulateResult.template.settings;
mappings = simulateResult.template.mappings;
// @ts-expect-error template is not yet typed with DLM
lifecycle = simulateResult.template.lifecycle;
// 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;