-
Notifications
You must be signed in to change notification settings - Fork 282
/
IndexResolverReplacer.java
823 lines (717 loc) · 35.6 KB
/
IndexResolverReplacer.java
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
/*
* Copyright 2015-2018 _floragunn_ GmbH
* Licensed 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.
*/
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.security.resolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.greenrobot.eventbus.Subscribe;
import org.opensearch.action.ActionRequest;
import org.opensearch.action.DocWriteRequest;
import org.opensearch.action.IndicesRequest;
import org.opensearch.action.IndicesRequest.Replaceable;
import org.opensearch.action.OriginalIndices;
import org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.admin.indices.datastream.CreateDataStreamAction;
import org.opensearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.opensearch.action.admin.indices.resolve.ResolveIndexAction;
import org.opensearch.action.admin.indices.template.put.PutComponentTemplateAction;
import org.opensearch.action.bulk.BulkRequest;
import org.opensearch.action.bulk.BulkShardRequest;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.fieldcaps.FieldCapabilitiesIndexRequest;
import org.opensearch.action.fieldcaps.FieldCapabilitiesRequest;
import org.opensearch.action.get.MultiGetRequest;
import org.opensearch.action.get.MultiGetRequest.Item;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.main.MainRequest;
import org.opensearch.action.search.ClearScrollRequest;
import org.opensearch.action.search.MultiSearchRequest;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.search.SearchScrollRequest;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.action.support.nodes.BaseNodesRequest;
import org.opensearch.action.support.replication.ReplicationRequest;
import org.opensearch.action.support.single.shard.SingleShardRequest;
import org.opensearch.action.termvectors.MultiTermVectorsRequest;
import org.opensearch.action.termvectors.TermVectorsRequest;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.cluster.ClusterState;
import org.opensearch.cluster.metadata.IndexAbstraction;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.index.Index;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.index.reindex.ReindexRequest;
import org.opensearch.security.OpenSearchSecurityPlugin;
import org.opensearch.security.configuration.ClusterInfoHolder;
import org.opensearch.security.securityconf.DynamicConfigModel;
import org.opensearch.security.support.SnapshotRestoreHelper;
import org.opensearch.security.support.WildcardMatcher;
import org.opensearch.snapshots.SnapshotInfo;
import org.opensearch.snapshots.SnapshotUtils;
import org.opensearch.transport.RemoteClusterService;
import org.opensearch.transport.TransportRequest;
import static org.opensearch.cluster.metadata.IndexAbstraction.Type.ALIAS;
public class IndexResolverReplacer {
private static final Set<String> NULL_SET = new HashSet<>(Collections.singleton(null));
private final Logger log = LogManager.getLogger(this.getClass());
private final IndexNameExpressionResolver resolver;
private final ClusterService clusterService;
private final ClusterInfoHolder clusterInfoHolder;
private volatile boolean respectRequestIndicesOptions = false;
public IndexResolverReplacer(IndexNameExpressionResolver resolver, ClusterService clusterService, ClusterInfoHolder clusterInfoHolder) {
this.resolver = resolver;
this.clusterService = clusterService;
this.clusterInfoHolder = clusterInfoHolder;
}
private static boolean isAllWithNoRemote(final String... requestedPatterns) {
final List<String> patterns = requestedPatterns == null ? null : Arrays.asList(requestedPatterns);
if (IndexNameExpressionResolver.isAllIndices(patterns)) {
return true;
}
if (patterns.size() == 1 && patterns.contains("*")) {
return true;
}
if (new HashSet<String>(patterns).equals(NULL_SET)) {
return true;
}
return false;
}
private static boolean isLocalAll(String... requestedPatterns) {
return isLocalAll(requestedPatterns == null ? null : Arrays.asList(requestedPatterns));
}
private static boolean isLocalAll(Collection<String> patterns) {
if (IndexNameExpressionResolver.isAllIndices(patterns)) {
return true;
}
if (patterns.contains("_all")) {
return true;
}
if (new HashSet<String>(patterns).equals(NULL_SET)) {
return true;
}
return false;
}
private class ResolvedIndicesProvider implements IndicesProvider {
private final ImmutableSet.Builder<String> aliases;
private final ImmutableSet.Builder<String> allIndices;
private final ImmutableSet.Builder<String> originalRequested;
private final ImmutableSet.Builder<String> remoteIndices;
// set of previously resolved index requests to avoid resolving
// the same index more than once while processing bulk requests
private final Set<AlreadyResolvedKey> alreadyResolved;
private final String name;
private final class AlreadyResolvedKey {
private final IndicesOptions indicesOptions;
private final boolean enableCrossClusterResolution;
private final String[] original;
private AlreadyResolvedKey(final IndicesOptions indicesOptions, final boolean enableCrossClusterResolution) {
this(indicesOptions, enableCrossClusterResolution, null);
}
private AlreadyResolvedKey(
final IndicesOptions indicesOptions,
final boolean enableCrossClusterResolution,
final String[] original
) {
this.indicesOptions = indicesOptions;
this.enableCrossClusterResolution = enableCrossClusterResolution;
this.original = original;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AlreadyResolvedKey that = (AlreadyResolvedKey) o;
return enableCrossClusterResolution == that.enableCrossClusterResolution
&& Objects.equals(indicesOptions, that.indicesOptions)
&& Arrays.equals(original, that.original);
}
@Override
public int hashCode() {
int result = Objects.hash(indicesOptions, enableCrossClusterResolution);
result = 31 * result + Arrays.hashCode(original);
return result;
}
}
ResolvedIndicesProvider(Object request) {
aliases = ImmutableSet.builder();
allIndices = ImmutableSet.builder();
originalRequested = ImmutableSet.builder();
remoteIndices = ImmutableSet.builder();
alreadyResolved = new HashSet<>();
name = request.getClass().getSimpleName();
}
private void resolveIndexPatterns(
final String name,
final IndicesOptions indicesOptions,
final boolean enableCrossClusterResolution,
final String[] original
) {
final boolean isTraceEnabled = log.isTraceEnabled();
if (isTraceEnabled) {
log.trace("resolve requestedPatterns: " + Arrays.toString(original));
}
if (isAllWithNoRemote(original)) {
if (isTraceEnabled) {
log.trace(Arrays.toString(original) + " is an ALL pattern without any remote indices");
}
resolveToLocalAll();
return;
}
Set<String> remoteIndices;
final List<String> localRequestedPatterns = new ArrayList<>(Arrays.asList(original));
final RemoteClusterService remoteClusterService = OpenSearchSecurityPlugin.GuiceHolder.getRemoteClusterService();
if (remoteClusterService.isCrossClusterSearchEnabled() && enableCrossClusterResolution) {
remoteIndices = new HashSet<>();
final Map<String, OriginalIndices> remoteClusterIndices = OpenSearchSecurityPlugin.GuiceHolder.getRemoteClusterService()
.groupIndices(indicesOptions, original, idx -> resolver.hasIndexAbstraction(idx, clusterService.state()));
final Set<String> remoteClusters = remoteClusterIndices.keySet()
.stream()
.filter(k -> !RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY.equals(k))
.collect(Collectors.toSet());
for (String remoteCluster : remoteClusters) {
for (String remoteIndex : remoteClusterIndices.get(remoteCluster).indices()) {
remoteIndices.add(RemoteClusterService.buildRemoteIndexName(remoteCluster, remoteIndex));
}
}
final Iterator<String> iterator = localRequestedPatterns.iterator();
while (iterator.hasNext()) {
final String[] split = iterator.next().split(String.valueOf(RemoteClusterService.REMOTE_CLUSTER_INDEX_SEPARATOR), 2);
final WildcardMatcher matcher = WildcardMatcher.from(split[0]);
if (split.length > 1 && matcher.matchAny(remoteClusters)) {
iterator.remove();
}
}
if (isTraceEnabled) {
log.trace(
"CCS is enabled, we found this local patterns "
+ localRequestedPatterns
+ " and this remote patterns: "
+ remoteIndices
);
}
} else {
remoteIndices = Collections.emptySet();
}
final Collection<String> matchingAliases;
Collection<String> matchingAllIndices;
Collection<String> matchingDataStreams = null;
if (isLocalAll(original)) {
if (isTraceEnabled) {
log.trace(Arrays.toString(original) + " is an LOCAL ALL pattern");
}
matchingAliases = Resolved.All_SET;
matchingAllIndices = Resolved.All_SET;
} else if (!remoteIndices.isEmpty() && localRequestedPatterns.isEmpty()) {
if (isTraceEnabled) {
log.trace(Arrays.toString(original) + " is an LOCAL EMPTY request");
}
matchingAllIndices = Collections.emptySet();
matchingAliases = Collections.emptySet();
}
else {
final ClusterState state = clusterService.state();
final Set<String> dateResolvedLocalRequestedPatterns = localRequestedPatterns.stream()
.map(resolver::resolveDateMathExpression)
.collect(Collectors.toSet());
final WildcardMatcher dateResolvedMatcher = WildcardMatcher.from(dateResolvedLocalRequestedPatterns);
// fill matchingAliases
final Map<String, IndexAbstraction> lookup = state.metadata().getIndicesLookup();
matchingAliases = lookup.entrySet()
.stream()
.filter(e -> e.getValue().getType() == ALIAS)
.map(Map.Entry::getKey)
.filter(dateResolvedMatcher)
.collect(Collectors.toSet());
final boolean isDebugEnabled = log.isDebugEnabled();
try {
matchingAllIndices = Arrays.asList(
resolver.concreteIndexNames(state, indicesOptions, localRequestedPatterns.toArray(new String[0]))
);
matchingDataStreams = resolver.dataStreamNames(state, indicesOptions, localRequestedPatterns.toArray(new String[0]));
if (isDebugEnabled) {
log.debug(
"Resolved pattern {} to indices: {} and data-streams: {}",
localRequestedPatterns,
matchingAllIndices,
matchingDataStreams
);
}
} catch (IndexNotFoundException e1) {
if (isDebugEnabled) {
log.debug("No such indices for pattern {}, use raw value", localRequestedPatterns);
}
matchingAllIndices = dateResolvedLocalRequestedPatterns;
}
}
if (matchingDataStreams == null || matchingDataStreams.size() == 0) {
matchingDataStreams = Arrays.asList(NOOP);
}
if (isTraceEnabled) {
log.trace(
"Resolved patterns {} for {} ({}) to [aliases {}, allIndices {}, dataStreams {}, originalRequested{}, remote indices {}]",
original,
name,
this.name,
matchingAliases,
matchingAllIndices,
matchingDataStreams,
Arrays.toString(original),
remoteIndices
);
}
resolveTo(matchingAliases, matchingAllIndices, matchingDataStreams, original, remoteIndices);
}
private void resolveToLocalAll() {
aliases.add(Resolved.ANY);
allIndices.add(Resolved.ANY);
originalRequested.add(Resolved.ANY);
}
private void resolveTo(
Iterable<String> matchingAliases,
Iterable<String> matchingAllIndices,
Iterable<String> matchingDataStreams,
String[] original,
Iterable<String> remoteIndices
) {
aliases.addAll(matchingAliases);
allIndices.addAll(matchingAllIndices);
allIndices.addAll(matchingDataStreams);
originalRequested.add(original);
this.remoteIndices.addAll(remoteIndices);
}
@Override
public String[] provide(String[] original, Object localRequest, boolean supportsReplace) {
final IndicesOptions indicesOptions = indicesOptionsFrom(localRequest);
final boolean enableCrossClusterResolution = localRequest instanceof FieldCapabilitiesRequest
|| localRequest instanceof SearchRequest
|| localRequest instanceof ResolveIndexAction.Request;
// skip the whole thing if we have seen this exact resolveIndexPatterns request
final AlreadyResolvedKey alreadyResolvedKey;
if (original != null) {
alreadyResolvedKey = new AlreadyResolvedKey(indicesOptions, enableCrossClusterResolution, original);
} else {
alreadyResolvedKey = new AlreadyResolvedKey(indicesOptions, enableCrossClusterResolution);
}
if (alreadyResolved.add(alreadyResolvedKey)) {
resolveIndexPatterns(localRequest.getClass().getSimpleName(), indicesOptions, enableCrossClusterResolution, original);
}
return IndicesProvider.NOOP;
}
Resolved resolved(IndicesOptions indicesOptions) {
final Resolved resolved = alreadyResolved.isEmpty()
? Resolved._LOCAL_ALL
: new Resolved(aliases.build(), allIndices.build(), originalRequested.build(), remoteIndices.build(), indicesOptions);
if (log.isTraceEnabled()) {
log.trace("Finally resolved for {}: {}", name, resolved);
}
return resolved;
}
}
// dnfof
public boolean replace(final TransportRequest request, boolean retainMode, String... replacements) {
return getOrReplaceAllIndices(request, new IndicesProvider() {
@Override
public String[] provide(String[] original, Object request, boolean supportsReplace) {
if (supportsReplace) {
if (retainMode && !isAllWithNoRemote(original)) {
final Resolved resolved = resolveRequest(request);
final List<String> retained = WildcardMatcher.from(resolved.getAllIndices())
.getMatchAny(replacements, Collectors.toList());
retained.addAll(resolved.getRemoteIndices());
return retained.toArray(new String[0]);
}
return replacements;
} else {
return NOOP;
}
}
}, false);
}
public Resolved resolveRequest(final Object request) {
if (log.isDebugEnabled()) {
log.debug("Resolve aliases, indices and types from {}", request.getClass().getSimpleName());
}
final ResolvedIndicesProvider resolvedIndicesProvider = new ResolvedIndicesProvider(request);
getOrReplaceAllIndices(request, resolvedIndicesProvider, false);
return resolvedIndicesProvider.resolved(indicesOptionsFrom(request));
}
public final static class Resolved {
private static final String ANY = "*";
private static final ImmutableSet<String> All_SET = ImmutableSet.of(ANY);
private static final Set<String> types = All_SET;
public static final Resolved _LOCAL_ALL = new Resolved(
All_SET,
All_SET,
All_SET,
ImmutableSet.of(),
SearchRequest.DEFAULT_INDICES_OPTIONS
);
private final Set<String> aliases;
private final Set<String> allIndices;
private final Set<String> originalRequested;
private final Set<String> remoteIndices;
private final boolean isLocalAll;
private final IndicesOptions indicesOptions;
public Resolved(
final ImmutableSet<String> aliases,
final ImmutableSet<String> allIndices,
final ImmutableSet<String> originalRequested,
final ImmutableSet<String> remoteIndices,
IndicesOptions indicesOptions
) {
this.aliases = aliases;
this.allIndices = allIndices;
this.originalRequested = originalRequested;
this.remoteIndices = remoteIndices;
this.isLocalAll = IndexResolverReplacer.isLocalAll(originalRequested.toArray(new String[0]))
|| (aliases.contains("*") && allIndices.contains("*"));
this.indicesOptions = indicesOptions;
}
public boolean isLocalAll() {
return isLocalAll;
}
public Set<String> getAliases() {
return aliases;
}
public Set<String> getAllIndices() {
return allIndices;
}
public Set<String> getAllIndicesResolved(ClusterService clusterService, IndexNameExpressionResolver resolver) {
if (isLocalAll) {
return new HashSet<>(Arrays.asList(resolver.concreteIndexNames(clusterService.state(), indicesOptions, "*")));
} else {
return allIndices;
}
}
public boolean isAllIndicesEmpty() {
return allIndices.isEmpty();
}
public Set<String> getTypes() {
return types;
}
public Set<String> getRemoteIndices() {
return remoteIndices;
}
@Override
public String toString() {
return "Resolved [aliases="
+ aliases
+ ", allIndices="
+ allIndices
+ ", types="
+ types
+ ", originalRequested="
+ originalRequested
+ ", remoteIndices="
+ remoteIndices
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aliases == null) ? 0 : aliases.hashCode());
result = prime * result + ((allIndices == null) ? 0 : allIndices.hashCode());
result = prime * result + ((originalRequested == null) ? 0 : originalRequested.hashCode());
result = prime * result + ((remoteIndices == null) ? 0 : remoteIndices.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Resolved other = (Resolved) obj;
if (aliases == null) {
if (other.aliases != null) return false;
} else if (!aliases.equals(other.aliases)) return false;
if (allIndices == null) {
if (other.allIndices != null) return false;
} else if (!allIndices.equals(other.allIndices)) return false;
if (originalRequested == null) {
if (other.originalRequested != null) return false;
} else if (!originalRequested.equals(other.originalRequested)) return false;
if (remoteIndices == null) {
if (other.remoteIndices != null) return false;
} else if (!remoteIndices.equals(other.remoteIndices)) return false;
return true;
}
}
private List<String> renamedIndices(final RestoreSnapshotRequest request, final List<String> filteredIndices) {
try {
final List<String> renamedIndices = new ArrayList<>();
for (final String index : filteredIndices) {
String renamedIndex = index;
if (request.renameReplacement() != null && request.renamePattern() != null) {
renamedIndex = index.replaceAll(request.renamePattern(), request.renameReplacement());
}
renamedIndices.add(renamedIndex);
}
return renamedIndices;
} catch (PatternSyntaxException e) {
log.error("Unable to parse the regular expression denoted in 'rename_pattern'. Please correct the pattern an try again.");
throw e;
}
}
// --
@FunctionalInterface
public interface IndicesProvider {
public static final String[] NOOP = new String[0];
String[] provide(String[] original, Object request, boolean supportsReplace);
}
private boolean checkIndices(Object request, String[] indices, boolean needsToBeSizeOne, boolean allowEmpty) {
if (indices == IndicesProvider.NOOP) {
return false;
}
final boolean isTraceEnabled = log.isTraceEnabled();
if (!allowEmpty && (indices == null || indices.length == 0)) {
if (isTraceEnabled && request != null) {
log.trace("Null or empty indices for " + request.getClass().getName());
}
return false;
}
if (!allowEmpty && needsToBeSizeOne && indices.length != 1) {
if (isTraceEnabled && request != null) {
log.trace("To much indices for " + request.getClass().getName());
}
return false;
}
for (int i = 0; i < indices.length; i++) {
final String index = indices[i];
if (index == null || index.isEmpty()) {
// not allowed
if (isTraceEnabled && request != null) {
log.trace("At least one null or empty index for " + request.getClass().getName());
}
return false;
}
}
return true;
}
/**
* new
* @param request
* @param allowEmptyIndices
* @return
*/
@SuppressWarnings("rawtypes")
private boolean getOrReplaceAllIndices(final Object request, final IndicesProvider provider, boolean allowEmptyIndices) {
final boolean isDebugEnabled = log.isDebugEnabled();
final boolean isTraceEnabled = log.isTraceEnabled();
if (isTraceEnabled) {
log.trace("getOrReplaceAllIndices() for " + request.getClass());
}
boolean result = true;
if (request instanceof BulkRequest) {
for (DocWriteRequest ar : ((BulkRequest) request).requests()) {
result = getOrReplaceAllIndices(ar, provider, false) && result;
}
} else if (request instanceof MultiGetRequest) {
for (ListIterator<Item> it = ((MultiGetRequest) request).getItems().listIterator(); it.hasNext();) {
Item item = it.next();
result = getOrReplaceAllIndices(item, provider, false) && result;
/*if(item.index() == null || item.indices() == null || item.indices().length == 0) {
it.remove();
}*/
}
} else if (request instanceof MultiSearchRequest) {
for (ListIterator<SearchRequest> it = ((MultiSearchRequest) request).requests().listIterator(); it.hasNext();) {
SearchRequest ar = it.next();
result = getOrReplaceAllIndices(ar, provider, false) && result;
/*if(ar.indices() == null || ar.indices().length == 0) {
it.remove();
}*/
}
} else if (request instanceof MultiTermVectorsRequest) {
for (ActionRequest ar : (Iterable<TermVectorsRequest>) () -> ((MultiTermVectorsRequest) request).iterator()) {
result = getOrReplaceAllIndices(ar, provider, false) && result;
}
} else if (request instanceof PutMappingRequest) {
PutMappingRequest pmr = (PutMappingRequest) request;
Index concreteIndex = pmr.getConcreteIndex();
if (concreteIndex != null && (pmr.indices() == null || pmr.indices().length == 0)) {
String[] newIndices = provider.provide(new String[] { concreteIndex.getName() }, request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((PutMappingRequest) request).indices(newIndices);
((PutMappingRequest) request).setConcreteIndex(null);
} else {
String[] newIndices = provider.provide(((PutMappingRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, false, allowEmptyIndices) == false) {
return false;
}
((PutMappingRequest) request).indices(newIndices);
}
} else if (request instanceof RestoreSnapshotRequest) {
if (clusterInfoHolder.isLocalNodeElectedClusterManager() == Boolean.FALSE) {
return true;
}
final RestoreSnapshotRequest restoreRequest = (RestoreSnapshotRequest) request;
final SnapshotInfo snapshotInfo = SnapshotRestoreHelper.getSnapshotInfo(restoreRequest);
if (snapshotInfo == null) {
log.warn(
"snapshot repository '" + restoreRequest.repository() + "', snapshot '" + restoreRequest.snapshot() + "' not found"
);
provider.provide(new String[] { "*" }, request, false);
} else {
final List<String> requestedResolvedIndices = SnapshotUtils.filterIndices(
snapshotInfo.indices(),
restoreRequest.indices(),
restoreRequest.indicesOptions()
);
final List<String> renamedTargetIndices = renamedIndices(restoreRequest, requestedResolvedIndices);
// final Set<String> indices = new HashSet<>(requestedResolvedIndices);
// indices.addAll(renamedTargetIndices);
if (isDebugEnabled) {
log.debug("snapshot: {} contains this indices: {}", snapshotInfo.snapshotId().getName(), renamedTargetIndices);
}
provider.provide(renamedTargetIndices.toArray(new String[0]), request, false);
}
} else if (request instanceof IndicesAliasesRequest) {
for (AliasActions ar : ((IndicesAliasesRequest) request).getAliasActions()) {
result = getOrReplaceAllIndices(ar, provider, false) && result;
}
} else if (request instanceof DeleteRequest) {
String[] newIndices = provider.provide(((DeleteRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((DeleteRequest) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof UpdateRequest) {
String[] newIndices = provider.provide(((UpdateRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((UpdateRequest) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof SingleShardRequest) {
final SingleShardRequest<?> singleShardRequest = (SingleShardRequest<?>) request;
final String index = singleShardRequest.index();
String[] indices = provider.provide(index == null ? null : new String[] { index }, request, true);
if (!checkIndices(request, indices, true, allowEmptyIndices)) {
return false;
}
singleShardRequest.index(indices.length != 1 ? null : indices[0]);
} else if (request instanceof FieldCapabilitiesIndexRequest) {
// FieldCapabilitiesIndexRequest does not support replacing the indexes.
// However, the indexes are always determined by FieldCapabilitiesRequest which will be reduced below
// (implements Replaceable). So IF an index arrives here, we can be sure that we have
// at least privileges for indices:data/read/field_caps
FieldCapabilitiesIndexRequest fieldCapabilitiesRequest = (FieldCapabilitiesIndexRequest) request;
String index = fieldCapabilitiesRequest.index();
String[] newIndices = provider.provide(new String[] { index }, request, true);
if (!checkIndices(request, newIndices, true, allowEmptyIndices)) {
return false;
}
} else if (request instanceof IndexRequest) {
String[] newIndices = provider.provide(((IndexRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((IndexRequest) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof Replaceable) {
String[] newIndices = provider.provide(((Replaceable) request).indices(), request, true);
if (checkIndices(request, newIndices, false, allowEmptyIndices) == false) {
return false;
}
((Replaceable) request).indices(newIndices);
} else if (request instanceof BulkShardRequest) {
provider.provide(((ReplicationRequest) request).indices(), request, false);
// replace not supported?
} else if (request instanceof ReplicationRequest) {
String[] newIndices = provider.provide(((ReplicationRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((ReplicationRequest) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof MultiGetRequest.Item) {
String[] newIndices = provider.provide(((MultiGetRequest.Item) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((MultiGetRequest.Item) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof CreateIndexRequest) {
String[] newIndices = provider.provide(((CreateIndexRequest) request).indices(), request, true);
if (checkIndices(request, newIndices, true, allowEmptyIndices) == false) {
return false;
}
((CreateIndexRequest) request).index(newIndices.length != 1 ? null : newIndices[0]);
} else if (request instanceof CreateDataStreamAction.Request) {
provider.provide(((CreateDataStreamAction.Request) request).indices(), request, false);
} else if (request instanceof ReindexRequest) {
result = getOrReplaceAllIndices(((ReindexRequest) request).getDestination(), provider, false) && result;
result = getOrReplaceAllIndices(((ReindexRequest) request).getSearchRequest(), provider, false) && result;
} else if (request instanceof BaseNodesRequest) {
// do nothing
} else if (request instanceof MainRequest) {
// do nothing
} else if (request instanceof ClearScrollRequest) {
// do nothing
} else if (request instanceof SearchScrollRequest) {
// do nothing
} else if (request instanceof PutComponentTemplateAction.Request) {
// do nothing
} else {
if (isDebugEnabled) {
log.debug(request.getClass() + " not supported (It is likely not a indices related request)");
}
result = false;
}
return result;
}
private IndicesOptions indicesOptionsFrom(Object localRequest) {
if (!respectRequestIndicesOptions) {
return IndicesOptions.fromOptions(false, true, true, false, true);
}
if (IndicesRequest.class.isInstance(localRequest)) {
return ((IndicesRequest) localRequest).indicesOptions();
} else if (RestoreSnapshotRequest.class.isInstance(localRequest)) {
return ((RestoreSnapshotRequest) localRequest).indicesOptions();
} else {
return IndicesOptions.fromOptions(false, true, true, false, true);
}
}
@Subscribe
public void onDynamicConfigModelChanged(DynamicConfigModel dcm) {
respectRequestIndicesOptions = dcm.isRespectRequestIndicesEnabled();
}
}