-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathtemplate.go
331 lines (284 loc) · 7.53 KB
/
template.go
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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package template
import (
"fmt"
"sync"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/cfgwarn"
"github.com/elastic/beats/libbeat/common/fmtstr"
"github.com/elastic/go-ucfg/yaml"
)
var (
// Defaults used in the template
defaultDateDetection = false
defaultTotalFieldsLimit = 10000
defaultNumberOfRoutingShards = 30
// Array to store dynamicTemplate parts in
dynamicTemplates []common.MapStr
defaultFields []string
)
type Template struct {
sync.Mutex
name string
pattern string
beatVersion common.Version
beatName string
esVersion common.Version
config TemplateConfig
migration bool
}
// New creates a new template instance
func New(
beatVersion string,
beatName string,
esVersion common.Version,
config TemplateConfig,
migration bool,
) (*Template, error) {
bV, err := common.NewVersion(beatVersion)
if err != nil {
return nil, err
}
name := config.Name
if name == "" {
name = fmt.Sprintf("%s-%s", beatName, bV.String())
}
pattern := config.Pattern
if pattern == "" {
pattern = name + "-*"
}
event := &beat.Event{
Fields: common.MapStr{
// beat object was left in for backward compatibility reason for older configs.
"beat": common.MapStr{
"name": beatName,
"version": bV.String(),
},
"agent": common.MapStr{
"name": beatName,
"version": bV.String(),
},
// For the Beats that have an observer role
"observer": common.MapStr{
"name": beatName,
"version": bV.String(),
},
},
Timestamp: time.Now(),
}
nameFormatter, err := fmtstr.CompileEvent(name)
if err != nil {
return nil, err
}
name, err = nameFormatter.Run(event)
if err != nil {
return nil, err
}
patternFormatter, err := fmtstr.CompileEvent(pattern)
if err != nil {
return nil, err
}
pattern, err = patternFormatter.Run(event)
if err != nil {
return nil, err
}
// In case no esVersion is set, it is assumed the same as beat version
if !esVersion.IsValid() {
esVersion = *bV
}
return &Template{
pattern: pattern,
name: name,
beatVersion: *bV,
esVersion: esVersion,
beatName: beatName,
config: config,
migration: migration,
}, nil
}
func (t *Template) load(fields common.Fields) (common.MapStr, error) {
// Locking to make sure dynamicTemplates and defaultFields is not accessed in parallel
t.Lock()
defer t.Unlock()
dynamicTemplates = nil
defaultFields = nil
var err error
if len(t.config.AppendFields) > 0 {
cfgwarn.Experimental("append_fields is used.")
fields, err = common.ConcatFields(fields, t.config.AppendFields)
if err != nil {
return nil, err
}
}
// Start processing at the root
properties := common.MapStr{}
processor := Processor{EsVersion: t.esVersion, Migration: t.migration}
if err := processor.Process(fields, "", properties); err != nil {
return nil, err
}
output := t.Generate(properties, dynamicTemplates)
return output, nil
}
// LoadFile loads the the template from the given file path
func (t *Template) LoadFile(file string) (common.MapStr, error) {
fields, err := common.LoadFieldsYaml(file)
if err != nil {
return nil, err
}
return t.load(fields)
}
// LoadBytes loads the the template from the given byte array
func (t *Template) LoadBytes(data []byte) (common.MapStr, error) {
fields, err := loadYamlByte(data)
if err != nil {
return nil, err
}
return t.load(fields)
}
// GetName returns the name of the template
func (t *Template) GetName() string {
return t.name
}
// GetPattern returns the pattern of the template
func (t *Template) GetPattern() string {
return t.pattern
}
// Generate generates the full template
// The default values are taken from the default variable.
func (t *Template) Generate(properties common.MapStr, dynamicTemplates []common.MapStr) common.MapStr {
keyPattern, patterns := buildPatternSettings(t.esVersion, t.GetPattern())
return common.MapStr{
keyPattern: patterns,
"mappings": buildMappings(
t.beatVersion, t.esVersion, t.beatName,
properties,
append(dynamicTemplates, buildDynTmpl(t.esVersion)),
common.MapStr(t.config.Settings.Source),
),
"order": 1,
"settings": common.MapStr{
"index": buildIdxSettings(
t.esVersion,
t.config.Settings.Index,
),
},
}
}
func buildPatternSettings(ver common.Version, pattern string) (string, interface{}) {
if ver.Major < 6 {
return "template", pattern
}
return "index_patterns", []string{pattern}
}
func buildMappings(
beatVersion, esVersion common.Version,
beatName string,
properties common.MapStr,
dynTmpls []common.MapStr,
source common.MapStr,
) common.MapStr {
mapping := common.MapStr{
"_meta": common.MapStr{
"version": beatVersion.String(),
"beat": beatName,
},
"date_detection": defaultDateDetection,
"dynamic_templates": dynTmpls,
"properties": properties,
}
if len(source) > 0 {
mapping["_source"] = source
}
major := esVersion.Major
switch {
case major == 2:
mapping.Put("_all.norms.enabled", false)
mapping = common.MapStr{
"_default_": mapping,
}
case major < 6:
mapping = common.MapStr{
"_default_": mapping,
}
case major == 6:
mapping = common.MapStr{
"doc": mapping,
}
case major >= 7:
// keep typeless structure
}
return mapping
}
func buildDynTmpl(ver common.Version) common.MapStr {
strMapping := common.MapStr{
"ignore_above": 1024,
"type": "keyword",
}
if ver.Major == 2 {
strMapping["type"] = "string"
strMapping["index"] = "not_analyzed"
}
return common.MapStr{
"strings_as_keyword": common.MapStr{
"mapping": strMapping,
"match_mapping_type": "string",
},
}
}
func buildIdxSettings(ver common.Version, userSettings common.MapStr) common.MapStr {
indexSettings := common.MapStr{
"refresh_interval": "5s",
"mapping": common.MapStr{
"total_fields": common.MapStr{
"limit": defaultTotalFieldsLimit,
},
},
}
// number_of_routing shards is only supported for ES version >= 6.1
version61, _ := common.NewVersion("6.1.0")
if !ver.LessThan(version61) {
indexSettings.Put("number_of_routing_shards", defaultNumberOfRoutingShards)
}
if ver.Major >= 7 {
// copy defaultFields, as defaultFields is shared global slice.
fields := make([]string, len(defaultFields))
copy(fields, defaultFields)
fields = append(fields, "fields.*")
indexSettings.Put("query.default_field", fields)
}
indexSettings.DeepUpdate(userSettings)
return indexSettings
}
func loadYamlByte(data []byte) (common.Fields, error) {
cfg, err := yaml.NewConfig(data)
if err != nil {
return nil, err
}
var keys []common.Field
err = cfg.Unpack(&keys)
if err != nil {
return nil, err
}
fields := common.Fields{}
for _, key := range keys {
fields = append(fields, key.Fields...)
}
return fields, nil
}