-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathget_indices.ts
267 lines (239 loc) · 7.3 KB
/
get_indices.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
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { sortBy } from 'lodash';
import { HttpStart } from 'kibana/public';
import { map, filter } from 'rxjs/operators';
import { i18n } from '@kbn/i18n';
import { Tag, INDEX_PATTERN_TYPE } from '../types';
import { MatchedItem, ResolveIndexResponse, ResolveIndexResponseItemIndexAttrs } from '../types';
import { MAX_SEARCH_SIZE } from '../constants';
import {
DataPublicPluginStart,
IEsSearchResponse,
isErrorResponse,
isCompleteResponse,
} from '../../../data/public';
const aliasLabel = i18n.translate('indexPatternEditor.aliasLabel', { defaultMessage: 'Alias' });
const dataStreamLabel = i18n.translate('indexPatternEditor.dataStreamLabel', {
defaultMessage: 'Data stream',
});
const indexLabel = i18n.translate('indexPatternEditor.indexLabel', {
defaultMessage: 'Index',
});
const frozenLabel = i18n.translate('indexPatternEditor.frozenLabel', {
defaultMessage: 'Frozen',
});
const rollupLabel = i18n.translate('indexPatternEditor.rollupLabel', {
defaultMessage: 'Rollup',
});
const getIndexTags = (isRollupIndex: (indexName: string) => boolean) => (indexName: string) =>
isRollupIndex(indexName)
? [
{
key: INDEX_PATTERN_TYPE.ROLLUP,
name: rollupLabel,
color: 'primary',
},
]
: [];
export const searchResponseToArray =
(getTags: (indexName: string) => Tag[], showAllIndices: boolean) =>
(response: IEsSearchResponse<any>) => {
const { rawResponse } = response;
if (!rawResponse.aggregations) {
return [];
} else {
// @ts-expect-error @elastic/elasticsearch no way to declare a type for aggregation in the search response
return rawResponse.aggregations.indices.buckets
.map((bucket: { key: string }) => {
return bucket.key;
})
.filter((indexName: string) => {
if (showAllIndices) {
return true;
} else {
return !indexName.startsWith('.');
}
})
.map((indexName: string) => {
return {
name: indexName,
tags: getTags(indexName),
item: {},
};
});
}
};
export const getIndicesViaSearch = async ({
pattern,
searchClient,
showAllIndices,
isRollupIndex,
}: {
pattern: string;
searchClient: DataPublicPluginStart['search']['search'];
showAllIndices: boolean;
isRollupIndex: (indexName: string) => boolean;
}): Promise<MatchedItem[]> =>
searchClient({
params: {
ignoreUnavailable: true,
expand_wildcards: showAllIndices ? 'all' : 'open',
index: pattern,
body: {
size: 0, // no hits
aggs: {
indices: {
terms: {
field: '_index',
size: MAX_SEARCH_SIZE,
},
},
},
},
},
})
.pipe(
filter((resp) => isCompleteResponse(resp) || isErrorResponse(resp)),
map(searchResponseToArray(getIndexTags(isRollupIndex), showAllIndices))
)
.toPromise()
.catch(() => []);
export const getIndicesViaResolve = async ({
http,
pattern,
showAllIndices,
isRollupIndex,
}: {
http: HttpStart;
pattern: string;
showAllIndices: boolean;
isRollupIndex: (indexName: string) => boolean;
}) =>
http
.get<ResolveIndexResponse>(`/internal/index-pattern-management/resolve_index/${pattern}`, {
query: showAllIndices ? { expand_wildcards: 'all' } : undefined,
})
.then((response) => {
if (!response) {
return [];
} else {
return responseToItemArray(response, getIndexTags(isRollupIndex));
}
});
/**
* Takes two MatchedItem[]s and returns a merged set, with the second set prrioritized over the first based on name
*
* @param matchedA
* @param matchedB
*/
export const dedupeMatchedItems = (matchedA: MatchedItem[], matchedB: MatchedItem[]) => {
const mergedMatchedItems = matchedA.reduce((col, item) => {
col[item.name] = item;
return col;
}, {} as Record<string, MatchedItem>);
matchedB.reduce((col, item) => {
col[item.name] = item;
return col;
}, mergedMatchedItems);
return Object.values(mergedMatchedItems).sort((a, b) => {
if (a.name > b.name) return 1;
if (b.name > a.name) return -1;
return 0;
});
};
export async function getIndices({
http,
pattern: rawPattern = '',
showAllIndices = false,
searchClient,
isRollupIndex,
}: {
http: HttpStart;
pattern: string;
showAllIndices?: boolean;
searchClient: DataPublicPluginStart['search']['search'];
isRollupIndex: (indexName: string) => boolean;
}): Promise<MatchedItem[]> {
const pattern = rawPattern.trim();
const isCCS = pattern.indexOf(':') !== -1;
const requests: Array<Promise<MatchedItem[]>> = [];
// Searching for `*:` fails for CCS environments. The search request
// is worthless anyways as the we should only send a request
// for a specific query (where we do not append *) if there is at
// least a single character being searched for.
if (pattern === '*:') {
return [];
}
// This should never match anything so do not bother
if (pattern === '') {
return [];
}
// ES does not like just a `,*` and will throw a `[string_index_out_of_bounds_exception] String index out of range: 0`
if (pattern.startsWith(',')) {
return [];
}
const promiseResolve = getIndicesViaResolve({
http,
pattern,
showAllIndices,
isRollupIndex,
}).catch(() => []);
requests.push(promiseResolve);
if (isCCS) {
// CCS supports ±1 major version. We won't be able to expect resolve endpoint to exist until v9
const promiseSearch = getIndicesViaSearch({
pattern,
searchClient,
showAllIndices,
isRollupIndex,
}).catch(() => []);
requests.push(promiseSearch);
}
const responses = await Promise.all(requests);
if (responses.length === 2) {
const [resolveResponse, searchResponse] = responses;
return dedupeMatchedItems(searchResponse, resolveResponse);
} else {
return responses[0];
}
}
export const responseToItemArray = (
response: ResolveIndexResponse,
getTags: (indexName: string) => Tag[]
): MatchedItem[] => {
const source: MatchedItem[] = [];
(response.indices || []).forEach((index) => {
const tags: MatchedItem['tags'] = [{ key: 'index', name: indexLabel, color: 'default' }];
const isFrozen = (index.attributes || []).includes(ResolveIndexResponseItemIndexAttrs.FROZEN);
tags.push(...getTags(index.name));
if (isFrozen) {
tags.push({ name: frozenLabel, key: 'frozen', color: 'danger' });
}
source.push({
name: index.name,
tags,
item: index,
});
});
(response.aliases || []).forEach((alias) => {
source.push({
name: alias.name,
tags: [{ key: 'alias', name: aliasLabel, color: 'default' }],
item: alias,
});
});
(response.data_streams || []).forEach((dataStream) => {
source.push({
name: dataStream.name,
tags: [{ key: 'data_stream', name: dataStreamLabel, color: 'primary' }],
item: dataStream,
});
});
return sortBy(source, 'name');
};