-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
OpenSearchNode.java
1506 lines (1332 loc) · 60.4 KB
/
OpenSearchNode.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
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
/*
* 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.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.gradle.testclusters;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.opensearch.gradle.Architecture;
import org.opensearch.gradle.DistributionDownloadPlugin;
import org.opensearch.gradle.FileSupplier;
import org.opensearch.gradle.LazyPropertyList;
import org.opensearch.gradle.LazyPropertyMap;
import org.opensearch.gradle.LoggedExec;
import org.opensearch.gradle.OS;
import org.opensearch.gradle.OpenSearchDistribution;
import org.opensearch.gradle.PropertyNormalization;
import org.opensearch.gradle.ReaperService;
import org.opensearch.gradle.Version;
import org.opensearch.gradle.VersionProperties;
import org.opensearch.gradle.info.BuildParams;
import org.gradle.api.Action;
import org.gradle.api.Named;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.file.ArchiveOperations;
import org.gradle.api.file.FileSystemOperations;
import org.gradle.api.file.FileTree;
import org.gradle.api.file.RegularFile;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.util.PatternFilterable;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
public class OpenSearchNode implements TestClusterConfiguration {
private static final Logger LOGGER = Logging.getLogger(OpenSearchNode.class);
private static final int OPENSEARCH_DESTROY_TIMEOUT = 20;
private static final TimeUnit OPENSEARCH_DESTROY_TIMEOUT_UNIT = TimeUnit.SECONDS;
private static final int NODE_UP_TIMEOUT = 2;
private static final TimeUnit NODE_UP_TIMEOUT_UNIT = TimeUnit.MINUTES;
private static final int ADDITIONAL_CONFIG_TIMEOUT = 15;
private static final TimeUnit ADDITIONAL_CONFIG_TIMEOUT_UNIT = TimeUnit.SECONDS;
private static final List<String> OVERRIDABLE_SETTINGS = Arrays.asList("path.repo", "discovery.seed_providers", "discovery.seed_hosts");
private static final int TAIL_LOG_MESSAGES_COUNT = 40;
private static final List<String> MESSAGES_WE_DONT_CARE_ABOUT = Arrays.asList(
"Option UseConcMarkSweepGC was deprecated",
"is a pre-release version of OpenSearch",
"max virtual memory areas vm.max_map_count"
);
private static final String HOSTNAME_OVERRIDE = "LinuxDarwinHostname";
private static final String COMPUTERNAME_OVERRIDE = "WindowsComputername";
private final String path;
private final String name;
private final Project project;
private final ReaperService reaper;
private final FileSystemOperations fileSystemOperations;
private final ArchiveOperations archiveOperations;
private final AtomicBoolean configurationFrozen = new AtomicBoolean(false);
private final Path workingDir;
private final LinkedHashMap<String, Predicate<TestClusterConfiguration>> waitConditions = new LinkedHashMap<>();
private final Map<String, Configuration> pluginAndModuleConfigurations = new HashMap<>();
private final List<Provider<File>> plugins = new ArrayList<>();
private final List<Provider<File>> modules = new ArrayList<>();
private boolean extensionsEnabled = false;
final LazyPropertyMap<String, CharSequence> settings = new LazyPropertyMap<>("Settings", this);
private final LazyPropertyMap<String, CharSequence> keystoreSettings = new LazyPropertyMap<>("Keystore", this);
private final LazyPropertyMap<String, File> keystoreFiles = new LazyPropertyMap<>("Keystore files", this, FileEntry::new);
private final LazyPropertyList<CliEntry> cliSetup = new LazyPropertyList<>("CLI setup commands", this);
private final LazyPropertyMap<String, CharSequence> systemProperties = new LazyPropertyMap<>("System properties", this);
private final LazyPropertyMap<String, CharSequence> environment = new LazyPropertyMap<>("Environment", this);
private final LazyPropertyList<CharSequence> jvmArgs = new LazyPropertyList<>("JVM arguments", this);
private final LazyPropertyMap<String, File> extraConfigFiles = new LazyPropertyMap<>("Extra config files", this, FileEntry::new);
private final LazyPropertyList<File> extraJarFiles = new LazyPropertyList<>("Extra jar files", this);
private final List<Map<String, String>> credentials = new ArrayList<>();
final LinkedHashMap<String, String> defaultConfig = new LinkedHashMap<>();
private final Path confPathRepo;
private final Path confPathLogs;
private final Path transportPortFile;
private final Path httpPortsFile;
private final Path tmpDir;
private boolean secure = false;
private int currentDistro = 0;
private TestDistribution testDistribution;
private final List<OpenSearchDistribution> distributions = new ArrayList<>();
private volatile Process opensearchProcess;
private Function<String, String> nameCustomization = Function.identity();
private boolean isWorkingDirConfigured = false;
private String httpPort = "0";
private String transportPort = "0";
private Path confPathData;
private String keystorePassword = "";
private boolean preserveDataDir = false;
private final Path configFile;
private final Path stdoutFile;
private final Path stderrFile;
private final Path stdinFile;
private final String zone;
OpenSearchNode(
String path,
String name,
Project project,
ReaperService reaper,
FileSystemOperations fileSystemOperations,
ArchiveOperations archiveOperations,
File workingDirBase,
String zone
) {
this.path = path;
this.name = name;
this.project = project;
this.reaper = reaper;
this.fileSystemOperations = fileSystemOperations;
this.archiveOperations = archiveOperations;
workingDir = workingDirBase.toPath().resolve(safeName(name)).toAbsolutePath();
confPathRepo = workingDir.resolve("repo");
confPathData = workingDir.resolve("data");
confPathLogs = workingDir.resolve("logs");
transportPortFile = confPathLogs.resolve("transport.ports");
httpPortsFile = confPathLogs.resolve("http.ports");
tmpDir = workingDir.resolve("tmp");
configFile = workingDir.resolve("config/opensearch.yml");
stdoutFile = confPathLogs.resolve("opensearch.stdout.log");
stderrFile = confPathLogs.resolve("opensearch.stderr.log");
stdinFile = workingDir.resolve("opensearch.stdin");
waitConditions.put("ports files", this::checkPortsFilesExistWithDelay);
setTestDistribution(TestDistribution.INTEG_TEST);
setVersion(VersionProperties.getOpenSearch());
this.zone = zone;
this.credentials.add(new HashMap<>());
}
@Input
@Optional
public String getName() {
return nameCustomization.apply(name);
}
@Internal
public boolean isSecure() {
return secure;
}
@Internal
public Version getVersion() {
return Version.fromString(distributions.get(currentDistro).getVersion());
}
@Override
public void setVersion(String version) {
requireNonNull(version, "null version passed when configuring test cluster `" + this + "`");
checkFrozen();
distributions.clear();
doSetVersion(version);
}
@Override
public void setVersions(List<String> versions) {
requireNonNull(versions, "null version list passed when configuring test cluster `" + this + "`");
distributions.clear();
for (String version : versions) {
doSetVersion(version);
}
}
private void doSetVersion(String version) {
String distroName = "testclusters" + path.replace(":", "-") + "-" + this.name + "-" + version + "-";
NamedDomainObjectContainer<OpenSearchDistribution> container = DistributionDownloadPlugin.getContainer(project);
if (container.findByName(distroName) == null) {
container.create(distroName);
}
OpenSearchDistribution distro = container.getByName(distroName);
distro.setVersion(version);
distro.setArchitecture(Architecture.current());
setDistributionType(distro, testDistribution);
distributions.add(distro);
}
@Internal
public TestDistribution getTestDistribution() {
return testDistribution;
}
// package private just so test clusters plugin can access to wire up task dependencies
@Internal
List<OpenSearchDistribution> getDistributions() {
return distributions;
}
@Override
public void setTestDistribution(TestDistribution testDistribution) {
requireNonNull(testDistribution, "null distribution passed when configuring test cluster `" + this + "`");
checkFrozen();
this.testDistribution = testDistribution;
for (OpenSearchDistribution distribution : distributions) {
setDistributionType(distribution, testDistribution);
}
}
private void setDistributionType(OpenSearchDistribution distribution, TestDistribution testDistribution) {
if (testDistribution == TestDistribution.INTEG_TEST) {
distribution.setType(OpenSearchDistribution.Type.INTEG_TEST_ZIP);
// we change the underlying distribution when changing the test distribution of the cluster.
distribution.setPlatform(null);
distribution.setBundledJdk(null);
} else {
distribution.setType(OpenSearchDistribution.Type.ARCHIVE);
}
}
// package protected so only TestClustersAware can access
@Internal
Collection<Configuration> getPluginAndModuleConfigurations() {
return pluginAndModuleConfigurations.values();
}
// creates a configuration to depend on the given plugin project, then wraps that configuration
// to grab the zip as a file provider
private Provider<RegularFile> maybeCreatePluginOrModuleDependency(String path) {
Configuration configuration = pluginAndModuleConfigurations.computeIfAbsent(
path,
key -> project.getConfigurations().detachedConfiguration(project.getDependencies().project(new HashMap<String, String>() {
{
put("path", path);
put("configuration", "zip");
}
}))
);
Provider<File> fileProvider = configuration.getElements()
.map(
s -> s.stream()
.findFirst()
.orElseThrow(() -> new IllegalStateException("zip configuration of project " + path + " had no files"))
.getAsFile()
);
return project.getLayout().file(fileProvider);
}
@Override
public void plugin(Provider<RegularFile> plugin) {
checkFrozen();
this.plugins.add(plugin.map(RegularFile::getAsFile));
}
@Override
public void upgradePlugin(List<Provider<RegularFile>> plugins) {
this.plugins.clear();
for (Provider<RegularFile> plugin : plugins) {
this.plugins.add(plugin.map(RegularFile::getAsFile));
}
}
@Override
public void plugin(String pluginProjectPath) {
plugin(maybeCreatePluginOrModuleDependency(pluginProjectPath));
}
@Override
public void module(Provider<RegularFile> module) {
checkFrozen();
this.modules.add(module.map(RegularFile::getAsFile));
}
@Override
public void module(String moduleProjectPath) {
module(maybeCreatePluginOrModuleDependency(moduleProjectPath));
}
@Override
public void extension(boolean extensionsEnabled) {
this.extensionsEnabled = extensionsEnabled;
}
@Override
public void keystore(String key, String value) {
keystoreSettings.put(key, value);
}
@Override
public void keystore(String key, Supplier<CharSequence> valueSupplier) {
keystoreSettings.put(key, valueSupplier);
}
@Override
public void keystore(String key, File value) {
keystoreFiles.put(key, value);
}
@Override
public void keystore(String key, File value, PropertyNormalization normalization) {
keystoreFiles.put(key, value, normalization);
}
@Override
public void keystore(String key, FileSupplier valueSupplier) {
keystoreFiles.put(key, valueSupplier);
}
@Override
public void keystorePassword(String password) {
keystorePassword = password;
}
@Override
public void cliSetup(String binTool, CharSequence... args) {
cliSetup.add(new CliEntry(binTool, args));
}
@Override
public void setting(String key, String value) {
settings.put(key, value);
}
@Override
public void setting(String key, String value, PropertyNormalization normalization) {
settings.put(key, value, normalization);
}
@Override
public void setting(String key, Supplier<CharSequence> valueSupplier) {
settings.put(key, valueSupplier);
}
@Override
public void setting(String key, Supplier<CharSequence> valueSupplier, PropertyNormalization normalization) {
settings.put(key, valueSupplier, normalization);
}
@Override
public void systemProperty(String key, String value) {
systemProperties.put(key, value);
}
@Override
public void systemProperty(String key, Supplier<CharSequence> valueSupplier) {
systemProperties.put(key, valueSupplier);
}
@Override
public void systemProperty(String key, Supplier<CharSequence> valueSupplier, PropertyNormalization normalization) {
systemProperties.put(key, valueSupplier, normalization);
}
@Override
public void environment(String key, String value) {
environment.put(key, value);
}
@Override
public void environment(String key, Supplier<CharSequence> valueSupplier) {
environment.put(key, valueSupplier);
}
@Override
public void environment(String key, Supplier<CharSequence> valueSupplier, PropertyNormalization normalization) {
environment.put(key, valueSupplier, normalization);
}
public void jvmArgs(String... values) {
jvmArgs.addAll(Arrays.asList(values));
}
@Internal
public Path getConfigDir() {
return configFile.getParent();
}
@Override
@Input
public boolean isPreserveDataDir() {
return preserveDataDir;
}
@Override
public void setPreserveDataDir(boolean preserveDataDir) {
this.preserveDataDir = preserveDataDir;
}
@Override
public void setSecure(boolean secure) {
this.secure = secure;
}
@Override
public void freeze() {
requireNonNull(testDistribution, "null testDistribution passed when configuring test cluster `" + this + "`");
LOGGER.info("Locking configuration of `{}`", this);
configurationFrozen.set(true);
}
/**
* Returns a stream of lines in the generated logs similar to Files.lines
*
* @return stream of log lines
*/
public Stream<String> logLines() throws IOException {
return Files.lines(stdoutFile, StandardCharsets.UTF_8);
}
@Override
public synchronized void start() {
LOGGER.info("Starting `{}`", this);
if (System.getProperty("tests.opensearch.secure") != null
&& System.getProperty("tests.opensearch.secure").equalsIgnoreCase("true")) {
secure = true;
}
if (System.getProperty("tests.opensearch.username") != null) {
this.credentials.get(0).put("username", System.getProperty("tests.opensearch.username"));
LOGGER.info("Overwriting username to: " + this.getCredentials().get(0).get("username"));
}
if (System.getProperty("tests.opensearch.password") != null) {
this.credentials.get(0).put("password", System.getProperty("tests.opensearch.password"));
LOGGER.info("Overwriting password to: " + this.getCredentials().get(0).get("password"));
}
if (Files.exists(getExtractedDistributionDir()) == false) {
throw new TestClustersException("Can not start " + this + ", missing: " + getExtractedDistributionDir());
}
if (Files.isDirectory(getExtractedDistributionDir()) == false) {
throw new TestClustersException("Can not start " + this + ", is not a directory: " + getExtractedDistributionDir());
}
try {
if (isWorkingDirConfigured == false) {
logToProcessStdout("Configuring working directory: " + workingDir);
// make sure we always start fresh
if (Files.exists(workingDir)) {
if (preserveDataDir) {
Files.list(workingDir)
.filter(path -> path.equals(confPathData) == false)
.forEach(path -> fileSystemOperations.delete(d -> d.delete(path)));
} else {
fileSystemOperations.delete(d -> d.delete(workingDir));
}
}
isWorkingDirConfigured = true;
}
setupNodeDistribution(getExtractedDistributionDir());
createWorkingDir();
} catch (IOException e) {
throw new UncheckedIOException("Failed to create working directory for " + this, e);
}
copyExtraJars();
copyExtraConfigFiles();
createConfiguration();
final List<String> pluginsToInstall = new ArrayList<>();
if (plugins.isEmpty() == false) {
pluginsToInstall.addAll(plugins.stream().map(Provider::get).map(p -> p.toURI().toString()).collect(Collectors.toList()));
}
if (pluginsToInstall.isEmpty() == false) {
logToProcessStdout("installing " + pluginsToInstall.size() + " plugins in a single transaction");
final String[] arguments = Stream.concat(Stream.of("install", "--batch"), pluginsToInstall.stream()).toArray(String[]::new);
runOpenSearchBinScript("opensearch-plugin", arguments);
logToProcessStdout("installed plugins");
}
logToProcessStdout("Creating opensearch keystore with password set to [" + keystorePassword + "]");
if (keystorePassword.length() > 0) {
runOpenSearchBinScriptWithInput(keystorePassword + "\n" + keystorePassword, "opensearch-keystore", "create", "-p");
} else {
runOpenSearchBinScript("opensearch-keystore", "-v", "create");
}
if (keystoreSettings.isEmpty() == false || keystoreFiles.isEmpty() == false) {
logToProcessStdout("Adding " + keystoreSettings.size() + " keystore settings and " + keystoreFiles.size() + " keystore files");
keystoreSettings.forEach((key, value) -> runKeystoreCommandWithPassword(keystorePassword, value.toString(), "add", "-x", key));
for (Map.Entry<String, File> entry : keystoreFiles.entrySet()) {
File file = entry.getValue();
requireNonNull(file, "supplied keystoreFile was null when configuring " + this);
if (file.exists() == false) {
throw new TestClustersException("supplied keystore file " + file + " does not exist, require for " + this);
}
runKeystoreCommandWithPassword(keystorePassword, "", "add-file", entry.getKey(), file.getAbsolutePath());
}
}
installModules();
if (cliSetup.isEmpty() == false) {
logToProcessStdout("Running " + cliSetup.size() + " setup commands");
for (CliEntry entry : cliSetup) {
runOpenSearchBinScript(entry.executable, entry.args);
}
}
logToProcessStdout("Starting OpenSearch process");
startOpenSearchProcess();
}
private boolean canUseSharedDistribution() {
// using original location can be too long due to MAX_PATH restrictions on windows CI
// TODO revisit when moving to shorter paths on CI by using Teamcity
return OS.current() != OS.WINDOWS && extraJarFiles.size() == 0 && modules.size() == 0 && plugins.size() == 0;
}
private void logToProcessStdout(String message) {
try {
if (Files.exists(stdoutFile.getParent()) == false) {
Files.createDirectories(stdoutFile.getParent());
}
Files.write(
stdoutFile,
("[" + Instant.now().toString() + "] [BUILD] " + message + "\n").getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void restart() {
LOGGER.info("Restarting {}", this);
stop(false);
start();
}
void goToNextVersion() {
if (currentDistro + 1 >= distributions.size()) {
throw new TestClustersException("Ran out of versions to go to for " + this);
}
logToProcessStdout("Switch version from " + getVersion() + " to " + distributions.get(currentDistro + 1).getVersion());
currentDistro += 1;
setting("node.attr.upgraded", "true");
}
private void copyExtraConfigFiles() {
if (extraConfigFiles.isEmpty() == false) {
logToProcessStdout("Setting up " + extraConfigFiles.size() + " additional config files");
}
extraConfigFiles.forEach((destination, from) -> {
if (Files.exists(from.toPath()) == false) {
throw new TestClustersException("Can't create extra config file from " + from + " for " + this + " as it does not exist");
}
Path dst = configFile.getParent().resolve(destination);
try {
Files.createDirectories(dst.getParent());
Files.copy(from.toPath(), dst, StandardCopyOption.REPLACE_EXISTING);
LOGGER.info("Added extra config file {} for {}", destination, this);
} catch (IOException e) {
throw new UncheckedIOException("Can't create extra config file for", e);
}
});
}
/**
* Copies extra jars to the `/lib` directory.
* //TODO: Remove this when system modules are available
*/
private void copyExtraJars() {
if (extraJarFiles.isEmpty() == false) {
logToProcessStdout("Setting up " + extraJarFiles.size() + " additional jar dependencies");
}
extraJarFiles.forEach(from -> {
Path destination = getDistroDir().resolve("lib").resolve(from.getName());
try {
Files.copy(from.toPath(), destination, StandardCopyOption.REPLACE_EXISTING);
LOGGER.info("Added extra jar {} to {}", from.getName(), destination);
} catch (IOException e) {
throw new UncheckedIOException("Can't copy extra jar dependency " + from.getName() + " to " + destination, e);
}
});
}
private void installModules() {
if (testDistribution == TestDistribution.INTEG_TEST) {
logToProcessStdout("Installing " + modules.size() + "modules");
for (Provider<File> module : modules) {
Path destination = getDistroDir().resolve("modules")
.resolve(module.get().getName().replace(".zip", "").replace("-" + getVersion(), "").replace("-SNAPSHOT", ""));
// only install modules that are not already bundled with the integ-test distribution
if (Files.exists(destination) == false) {
fileSystemOperations.copy(spec -> {
if (module.get().getName().toLowerCase().endsWith(".zip")) {
spec.from(archiveOperations.zipTree(module));
} else if (module.get().isDirectory()) {
spec.from(module);
} else {
throw new IllegalArgumentException("Not a valid module " + module + " for " + this);
}
spec.into(destination);
});
}
}
} else {
LOGGER.info("Not installing " + modules.size() + "(s) since the " + distributions + " distribution already " + "has them");
}
}
@Override
public void extraConfigFile(String destination, File from) {
if (destination.contains("..")) {
throw new IllegalArgumentException("extra config file destination can't be relative, was " + destination + " for " + this);
}
extraConfigFiles.put(destination, from);
}
@Override
public void extraConfigFile(String destination, File from, PropertyNormalization normalization) {
if (destination.contains("..")) {
throw new IllegalArgumentException("extra config file destination can't be relative, was " + destination + " for " + this);
}
extraConfigFiles.put(destination, from, normalization);
}
@Override
public void extraJarFile(File from) {
if (from.toString().endsWith(".jar") == false) {
throw new IllegalArgumentException("extra jar file " + from.toString() + " doesn't appear to be a JAR");
}
extraJarFiles.add(from);
}
@Override
public void user(Map<String, String> userSpec) {}
private void runOpenSearchBinScriptWithInput(String input, String tool, CharSequence... args) {
if (Files.exists(getDistroDir().resolve("bin").resolve(tool)) == false
&& Files.exists(getDistroDir().resolve("bin").resolve(tool + ".bat")) == false) {
throw new TestClustersException(
"Can't run bin script: `" + tool + "` does not exist. Is this the distribution you expect it to be ?"
);
}
try (InputStream byteArrayInputStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
LoggedExec.exec(project, spec -> {
spec.setEnvironment(getOpenSearchEnvironment());
spec.workingDir(getDistroDir());
spec.executable(OS.conditionalString().onUnix(() -> "./bin/" + tool).onWindows(() -> "cmd").supply());
spec.args(OS.<List<CharSequence>>conditional().onWindows(() -> {
ArrayList<CharSequence> result = new ArrayList<>();
result.add("/c");
result.add("bin\\" + tool + ".bat");
result.addAll(Arrays.asList(args));
return result;
}).onUnix(() -> Arrays.asList(args)).supply());
spec.setStandardInput(byteArrayInputStream);
});
} catch (IOException e) {
throw new UncheckedIOException("Failed to run " + tool + " for " + this, e);
}
}
private void runKeystoreCommandWithPassword(String keystorePassword, String input, CharSequence... args) {
final String actualInput = keystorePassword.length() > 0 ? keystorePassword + "\n" + input : input;
runOpenSearchBinScriptWithInput(actualInput, "opensearch-keystore", args);
}
private void runOpenSearchBinScript(String tool, CharSequence... args) {
runOpenSearchBinScriptWithInput("", tool, args);
}
private Map<String, String> getOpenSearchEnvironment() {
Map<String, String> defaultEnv = new HashMap<>();
getRequiredJavaHome().ifPresent(javaHome -> defaultEnv.put("JAVA_HOME", javaHome));
defaultEnv.put("OPENSEARCH_PATH_CONF", configFile.getParent().toString());
String systemPropertiesString = "";
if (systemProperties.isEmpty() == false) {
systemPropertiesString = " "
+ systemProperties.entrySet()
.stream()
.map(entry -> "-D" + entry.getKey() + "=" + entry.getValue())
// OPENSEARCH_PATH_CONF is also set as an environment variable and for a reference to ${OPENSEARCH_PATH_CONF}
// to work OPENSEARCH_JAVA_OPTS, we need to make sure that OPENSEARCH_PATH_CONF before OPENSEARCH_JAVA_OPTS. Instead,
// we replace the reference with the actual value in other environment variables
.map(p -> p.replace("${OPENSEARCH_PATH_CONF}", configFile.getParent().toString()))
.collect(Collectors.joining(" "));
}
String jvmArgsString = "";
if (jvmArgs.isEmpty() == false) {
jvmArgsString = " " + jvmArgs.stream().peek(argument -> {
if (argument.toString().startsWith("-D")) {
throw new TestClustersException(
"Invalid jvm argument `" + argument + "` configure as systemProperty instead for " + this
);
}
}).collect(Collectors.joining(" "));
}
String heapSize = System.getProperty("tests.heap.size", "512m");
defaultEnv.put(
"OPENSEARCH_JAVA_OPTS",
"-Xms" + heapSize + " -Xmx" + heapSize + " -ea -esa " + systemPropertiesString + " " + jvmArgsString + " " +
// Support passing in additional JVM arguments
System.getProperty("tests.jvm.argline", "")
);
defaultEnv.put("OPENSEARCH_TMPDIR", tmpDir.toString());
// Windows requires this as it defaults to `c:\windows` despite OPENSEARCH_TMPDIR
defaultEnv.put("TMP", tmpDir.toString());
// Override the system hostname variables for testing
defaultEnv.put("HOSTNAME", HOSTNAME_OVERRIDE);
defaultEnv.put("COMPUTERNAME", COMPUTERNAME_OVERRIDE);
Set<String> commonKeys = new HashSet<>(environment.keySet());
commonKeys.retainAll(defaultEnv.keySet());
if (commonKeys.isEmpty() == false) {
throw new IllegalStateException("testcluster does not allow overwriting the following env vars " + commonKeys + " for " + this);
}
environment.forEach((key, value) -> defaultEnv.put(key, value.toString()));
return defaultEnv;
}
private java.util.Optional<String> getRequiredJavaHome() {
// If we are testing the current version of OpenSearch, use the configured runtime Java
if (getTestDistribution() == TestDistribution.INTEG_TEST || getVersion().equals(VersionProperties.getOpenSearchVersion())) {
return java.util.Optional.of(BuildParams.getRuntimeJavaHome()).map(File::getAbsolutePath);
} else { // otherwise use the bundled JDK
return java.util.Optional.empty();
}
}
private void startOpenSearchProcess() {
final ProcessBuilder processBuilder = new ProcessBuilder();
Path effectiveDistroDir = getDistroDir();
List<String> command = OS.<List<String>>conditional()
.onUnix(() -> List.of(effectiveDistroDir.resolve("./bin/opensearch").toString()))
.onWindows(() -> Arrays.asList("cmd", "/c", effectiveDistroDir.resolve("bin\\opensearch.bat").toString()))
.supply();
processBuilder.command(command);
processBuilder.directory(workingDir.toFile());
Map<String, String> environment = processBuilder.environment();
// Don't inherit anything from the environment for as that would lack reproducibility
environment.clear();
environment.putAll(getOpenSearchEnvironment());
if (extensionsEnabled) {
environment.put("OPENSEARCH_JAVA_OPTS", "-Dopensearch.experimental.feature.extensions.enabled=true");
}
// don't buffer all in memory, make sure we don't block on the default pipes
processBuilder.redirectError(ProcessBuilder.Redirect.appendTo(stderrFile.toFile()));
processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(stdoutFile.toFile()));
if (keystorePassword != null && keystorePassword.length() > 0) {
try {
Files.write(stdinFile, (keystorePassword + "\n").getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
processBuilder.redirectInput(stdinFile.toFile());
} catch (IOException e) {
throw new TestClustersException("Failed to set the keystore password for " + this, e);
}
}
LOGGER.info("Running `{}` in `{}` for {} env: {}", command, workingDir, this, environment);
try {
opensearchProcess = processBuilder.start();
} catch (IOException e) {
throw new TestClustersException("Failed to start opensearch process for " + this, e);
}
reaper.registerPid(toString(), opensearchProcess.pid());
}
@Internal
public Path getDistroDir() {
return canUseSharedDistribution()
? getExtractedDistributionDir().toFile().listFiles()[0].toPath()
: workingDir.resolve("distro").resolve(getVersion() + "-" + testDistribution);
}
@Override
@Internal
public String getHttpSocketURI() {
return getHttpPortInternal().get(0);
}
@Override
@Internal
public String getTransportPortURI() {
return getTransportPortInternal().get(0);
}
@Override
@Internal
public List<String> getAllHttpSocketURI() {
waitForAllConditions();
return getHttpPortInternal();
}
@Override
@Internal
public List<String> getAllTransportPortURI() {
waitForAllConditions();
return getTransportPortInternal();
}
@Internal
public File getServerLog() {
return confPathLogs.resolve(defaultConfig.get("cluster.name") + "_server.json").toFile();
}
@Internal
public File getAuditLog() {
return confPathLogs.resolve(defaultConfig.get("cluster.name") + "_audit.json").toFile();
}
@Override
public synchronized void stop(boolean tailLogs) {
logToProcessStdout("Stopping node");
try {
if (Files.exists(httpPortsFile)) {
Files.delete(httpPortsFile);
}
if (Files.exists(transportPortFile)) {
Files.delete(transportPortFile);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (opensearchProcess == null && tailLogs) {
// This is a special case. If start() throws an exception the plugin will still call stop
// Another exception here would eat the orriginal.
return;
}
LOGGER.info("Stopping `{}`, tailLogs: {}", this, tailLogs);
requireNonNull(opensearchProcess, "Can't stop `" + this + "` as it was not started or already stopped.");
// Test clusters are not reused, don't spend time on a graceful shutdown
stopProcess(opensearchProcess.toHandle(), true);
reaper.unregister(toString());
if (tailLogs) {
logFileContents("Standard output of node", stdoutFile);
logFileContents("Standard error of node", stderrFile);
}
opensearchProcess = null;
// Clean up the ports file in case this is started again.
try {
if (Files.exists(httpPortsFile)) {
Files.delete(httpPortsFile);
}
if (Files.exists(transportPortFile)) {
Files.delete(transportPortFile);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void setNameCustomization(Function<String, String> nameCustomizer) {
this.nameCustomization = nameCustomizer;
}
private void stopProcess(ProcessHandle processHandle, boolean forcibly) {
// No-op if the process has already exited by itself.
if (processHandle.isAlive() == false) {
LOGGER.info("Process was not running when we tried to terminate it.");
return;
}
// Stop all children last - if the ML processes are killed before the OpenSearch JVM then
// they'll be recorded as having failed and won't restart when the cluster restarts.
// OpenSearch could actually be a child when there's some wrapper process like on Windows,
// and in that case the ML processes will be grandchildren of the wrapper.
List<ProcessHandle> children = processHandle.children().collect(Collectors.toList());
try {
logProcessInfo("Terminating opensearch process" + (forcibly ? " forcibly " : "gracefully") + ":", processHandle.info());
if (forcibly) {
processHandle.destroyForcibly();
} else {
processHandle.destroy();
waitForProcessToExit(processHandle);
if (processHandle.isAlive() == false) {
return;
}
LOGGER.info(
"process did not terminate after {} {}, stopping it forcefully",
OPENSEARCH_DESTROY_TIMEOUT,
OPENSEARCH_DESTROY_TIMEOUT_UNIT
);
processHandle.destroyForcibly();
}
waitForProcessToExit(processHandle);
if (processHandle.isAlive()) {
throw new TestClustersException("Was not able to terminate opensearch process for " + this);
}
} finally {
children.forEach(each -> stopProcess(each, forcibly));
}
waitForProcessToExit(processHandle);
if (processHandle.isAlive()) {
throw new TestClustersException("Was not able to terminate opensearch process for " + this);
}
}
private void logProcessInfo(String prefix, ProcessHandle.Info info) {
LOGGER.info(
prefix + " commandLine:`{}` command:`{}` args:`{}`",
info.commandLine().orElse("-"),
info.command().orElse("-"),
Arrays.stream(info.arguments().orElse(new String[] {})).map(each -> "'" + each + "'").collect(Collectors.joining(" "))
);
}
private void logFileContents(String description, Path from) {
final Map<String, Integer> errorsAndWarnings = new LinkedHashMap<>();
LinkedList<String> ring = new LinkedList<>();
try (LineNumberReader reader = new LineNumberReader(Files.newBufferedReader(from))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
final String lineToAdd;
if (ring.isEmpty()) {
lineToAdd = line;
} else {
if (line.startsWith("[")) {
lineToAdd = line;
// check to see if the previous message (possibly combined from multiple lines) was an error or
// warning as we want to show all of them
String previousMessage = normalizeLogLine(ring.getLast());
if (MESSAGES_WE_DONT_CARE_ABOUT.stream().noneMatch(previousMessage::contains)