-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy path_index_pattern.js
386 lines (331 loc) · 10.8 KB
/
_index_pattern.js
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
import _ from 'lodash';
import errors from 'ui/errors';
import angular from 'angular';
import getComputedFields from 'ui/index_patterns/_get_computed_fields';
import formatHit from 'ui/index_patterns/_format_hit';
import RegistryFieldFormatsProvider from 'ui/registry/field_formats';
import IndexPatternsGetIdsProvider from 'ui/index_patterns/_get_ids';
import IndexPatternsMapperProvider from 'ui/index_patterns/_mapper';
import IndexPatternsIntervalsProvider from 'ui/index_patterns/_intervals';
import DocSourceProvider from 'ui/courier/data_source/admin_doc_source';
import UtilsMappingSetupProvider from 'ui/utils/mapping_setup';
import IndexPatternsFieldListProvider from 'ui/index_patterns/_field_list';
import IndexPatternsFlattenHitProvider from 'ui/index_patterns/_flatten_hit';
import IndexPatternsCalculateIndicesProvider from 'ui/index_patterns/_calculate_indices';
import IndexPatternsPatternCacheProvider from 'ui/index_patterns/_pattern_cache';
export default function IndexPatternFactory(Private, Notifier, config, kbnIndex, Promise, confirmModalPromise) {
const fieldformats = Private(RegistryFieldFormatsProvider);
const getIds = Private(IndexPatternsGetIdsProvider);
const mapper = Private(IndexPatternsMapperProvider);
const intervals = Private(IndexPatternsIntervalsProvider);
const DocSource = Private(DocSourceProvider);
const mappingSetup = Private(UtilsMappingSetupProvider);
const FieldList = Private(IndexPatternsFieldListProvider);
const flattenHit = Private(IndexPatternsFlattenHitProvider);
const calculateIndices = Private(IndexPatternsCalculateIndicesProvider);
const patternCache = Private(IndexPatternsPatternCacheProvider);
const type = 'index-pattern';
const notify = new Notifier();
const configWatchers = new WeakMap();
const docSources = new WeakMap();
const getRoutes = () => ({
edit: '/management/kibana/indices/{{id}}',
addField: '/management/kibana/indices/{{id}}/create-field',
indexedFields: '/management/kibana/indices/{{id}}?_a=(tab:indexedFields)',
scriptedFields: '/management/kibana/indices/{{id}}?_a=(tab:scriptedFields)',
sourceFilters: '/management/kibana/indices/{{id}}?_a=(tab:sourceFilters)'
});
const mapping = mappingSetup.expandShorthand({
title: 'text',
timeFieldName: 'keyword',
notExpandable: 'boolean',
intervalName: 'keyword',
fields: 'json',
sourceFilters: 'json',
fieldFormatMap: {
type: 'text',
_serialize(map = {}) {
const serialized = _.transform(map, serialize);
return _.isEmpty(serialized) ? undefined : angular.toJson(serialized);
},
_deserialize(map = '{}') {
return _.mapValues(angular.fromJson(map), deserialize);
}
}
});
function serialize(flat, format, field) {
if (format) {
flat[field] = format;
}
}
function deserialize(mapping) {
const FieldFormat = fieldformats.byId[mapping.id];
return FieldFormat && new FieldFormat(mapping.params);
}
function updateFromElasticSearch(indexPattern, response) {
if (!response.found) {
throw new errors.SavedObjectNotFound(type, indexPattern.id);
}
_.forOwn(mapping, (fieldMapping, name) => {
if (!fieldMapping._deserialize) {
return;
}
response._source[name] = fieldMapping._deserialize(
response._source[name], response, name, fieldMapping
);
});
// give index pattern all of the values in _source
_.assign(indexPattern, response._source);
const promise = indexFields(indexPattern);
// any time index pattern in ES is updated, update index pattern object
docSources
.get(indexPattern)
.onUpdate()
.then(response => updateFromElasticSearch(indexPattern, response), notify.fatal);
return promise;
}
function containsFieldCapabilities(fields) {
return _.any(fields, (field) => {
return _.has(field, 'aggregatable') && _.has(field, 'searchable');
});
}
function indexFields(indexPattern) {
let promise = Promise.resolve();
if (!indexPattern.id) {
return promise;
}
if (!indexPattern.fields || !containsFieldCapabilities(indexPattern.fields)) {
promise = indexPattern.refreshFields();
}
return promise.then(() => {initFields(indexPattern);});
}
function setId(indexPattern, id) {
indexPattern.id = id;
return id;
}
function watch(indexPattern) {
if (configWatchers.has(indexPattern)) {
return;
}
const unwatch = config.watchAll(() => {
if (indexPattern.fields) {
initFields(indexPattern); // re-init fields when config changes, but only if we already had fields
}
});
configWatchers.set(indexPattern, { unwatch });
}
function unwatch(indexPattern) {
if (!configWatchers.has(indexPattern)) {
return;
}
configWatchers.get(indexPattern).unwatch();
configWatchers.delete(indexPattern);
}
function initFields(indexPattern, input) {
const oldValue = indexPattern.fields;
const newValue = input || oldValue || [];
indexPattern.fields = new FieldList(indexPattern, newValue);
}
function fetchFields(indexPattern) {
return mapper
.getFieldsForIndexPattern(indexPattern, true)
.then(fields => {
const scripted = indexPattern.getScriptedFields();
const all = fields.concat(scripted);
initFields(indexPattern, all);
});
}
class IndexPattern {
constructor(id) {
setId(this, id);
docSources.set(this, new DocSource());
this.metaFields = config.get('metaFields');
this.getComputedFields = getComputedFields.bind(this);
this.flattenHit = flattenHit(this);
this.formatHit = formatHit(this, fieldformats.getDefaultInstance('string'));
this.formatField = this.formatHit.formatField;
}
get routes() {
return getRoutes();
}
init() {
docSources
.get(this)
.index(kbnIndex)
.type(type)
.id(this.id);
watch(this);
return mappingSetup
.isDefined(type)
.then(defined => {
if (defined) {
return true;
}
return mappingSetup.setup(type, mapping);
})
.then(() => {
if (!this.id) {
return; // no id === no elasticsearch document
}
return docSources.get(this)
.fetch()
.then(response => updateFromElasticSearch(this, response));
})
.then(() => this);
}
// Get the source filtering configuration for that index.
getSourceFiltering() {
return {
excludes: this.sourceFilters && this.sourceFilters.map(filter => filter.value) || []
};
}
addScriptedField(name, script, type = 'string', lang) {
const scriptedFields = this.getScriptedFields();
const names = _.pluck(scriptedFields, 'name');
if (_.contains(names, name)) {
throw new errors.DuplicateField(name);
}
this.fields.push({
name: name,
script: script,
type: type,
scripted: true,
lang: lang
});
this.save();
}
removeScriptedField(name) {
const fieldIndex = _.findIndex(this.fields, {
name: name,
scripted: true
});
this.fields.splice(fieldIndex, 1);
this.save();
}
popularizeField(fieldName, unit = 1) {
const field = _.get(this, ['fields', 'byName', fieldName]);
if (!field) {
return;
}
const count = Math.max((field.count || 0) + unit, 0);
if (field.count === count) {
return;
}
field.count = count;
this.save();
}
getNonScriptedFields() {
return _.where(this.fields, { scripted: false });
}
getScriptedFields() {
return _.where(this.fields, { scripted: true });
}
getInterval() {
return this.intervalName && _.find(intervals, { name: this.intervalName });
}
toIndexList(start, stop, sortDirection) {
return this
.toDetailedIndexList(start, stop, sortDirection)
.then(detailedIndices => {
if (!_.isArray(detailedIndices)) {
return detailedIndices.index;
}
return _.pluck(detailedIndices, 'index');
});
}
toDetailedIndexList(start, stop, sortDirection) {
return Promise.resolve().then(() => {
const interval = this.getInterval();
if (interval) {
return intervals.toIndexList(
this.id, interval, start, stop, sortDirection
);
}
if (this.isWildcard() && this.hasTimeField() && this.canExpandIndices()) {
return calculateIndices(
this.id, this.timeFieldName, start, stop, sortDirection
);
}
return {
index: this.id,
min: -Infinity,
max: Infinity
};
});
}
canExpandIndices() {
return !this.notExpandable;
}
hasTimeField() {
return !!(this.timeFieldName && this.fields.byName[this.timeFieldName]);
}
isWildcard() {
return _.includes(this.id, '*');
}
prepBody() {
const body = {};
// serialize json fields
_.forOwn(mapping, (fieldMapping, fieldName) => {
if (this[fieldName] != null) {
body[fieldName] = (fieldMapping._serialize)
? fieldMapping._serialize(this[fieldName])
: this[fieldName];
}
});
// ensure that the docSource has the current this.id
docSources.get(this).id(this.id);
// clear the indexPattern list cache
getIds.clearCache();
return body;
}
create() {
const body = this.prepBody();
return docSources.get(this)
.doCreate(body)
.then(id => setId(this, id))
.catch(err => {
if (_.get(err, 'origError.status') !== 409) {
return Promise.resolve(false);
}
const confirmMessage = 'Are you sure you want to overwrite this?';
return confirmModalPromise(confirmMessage, { confirmButtonText: 'Overwrite' })
.then(() => Promise
.try(() => {
const cached = patternCache.get(this.id);
if (cached) {
return cached.then(pattern => pattern.destroy());
}
})
.then(() => docSources.get(this).doIndex(body))
.then(id => setId(this, id)),
_.constant(false) // if the user doesn't overwrite, resolve with false
);
});
}
save() {
const body = this.prepBody();
return docSources.get(this)
.doIndex(body)
.then(id => setId(this, id));
}
refreshFields() {
return mapper
.clearCache(this)
.then(() => fetchFields(this))
.then(() => this.save());
}
toJSON() {
return this.id;
}
toString() {
return '' + this.toJSON();
}
destroy() {
unwatch(this);
patternCache.clear(this.id);
docSources.get(this).destroy();
docSources.delete(this);
}
}
return IndexPattern;
}