Merge branch 'master' into simplify_license_service_scheduling

Original commit: elastic/x-pack-elasticsearch@faa20465e4
This commit is contained in:
Areek Zillur 2016-07-05 10:51:40 -04:00
commit d88e1ddb27
455 changed files with 4099 additions and 2736 deletions

View File

@ -13,11 +13,11 @@ import org.joda.time.format.ISODateTimeFormat;
public class DateUtils { public class DateUtils {
private final static FormatDateTimeFormatter formatDateOnlyFormatter = Joda.forPattern("yyyy-MM-dd"); private static final FormatDateTimeFormatter formatDateOnlyFormatter = Joda.forPattern("yyyy-MM-dd");
private final static DateTimeFormatter dateOnlyFormatter = formatDateOnlyFormatter.parser().withZoneUTC(); private static final DateTimeFormatter dateOnlyFormatter = formatDateOnlyFormatter.parser().withZoneUTC();
private final static DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime().withZoneUTC(); private static final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime().withZoneUTC();
public static long endOfTheDay(String date) { public static long endOfTheDay(String date) {
try { try {

View File

@ -29,9 +29,9 @@ import java.util.Locale;
* Provides serialization/deserialization & validation methods for license object * Provides serialization/deserialization & validation methods for license object
*/ */
public class License implements ToXContent { public class License implements ToXContent {
public final static int VERSION_START = 1; public static final int VERSION_START = 1;
public final static int VERSION_NO_FEATURE_TYPE = 2; public static final int VERSION_NO_FEATURE_TYPE = 2;
public final static int VERSION_CURRENT = VERSION_NO_FEATURE_TYPE; public static final int VERSION_CURRENT = VERSION_NO_FEATURE_TYPE;
/** /**
* XContent param name to deserialize license(s) with * XContent param name to deserialize license(s) with
@ -51,7 +51,7 @@ public class License implements ToXContent {
*/ */
public static final String LICENSE_VERSION_MODE = "license_version"; public static final String LICENSE_VERSION_MODE = "license_version";
public final static Comparator<License> LATEST_ISSUE_DATE_FIRST = new Comparator<License>() { public static final Comparator<License> LATEST_ISSUE_DATE_FIRST = new Comparator<License>() {
@Override @Override
public int compare(License right, License left) { public int compare(License right, License left) {
return Long.compare(left.issueDate(), right.issueDate()); return Long.compare(left.issueDate(), right.issueDate());
@ -506,7 +506,7 @@ public class License implements ToXContent {
return result; return result;
} }
public final static class Fields { public static final class Fields {
public static final String STATUS = "status"; public static final String STATUS = "status";
public static final String UID = "uid"; public static final String UID = "uid";
public static final String TYPE = "type"; public static final String TYPE = "type";

View File

@ -5,6 +5,8 @@
*/ */
package org.elasticsearch.license.core; package org.elasticsearch.license.core;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
@ -51,7 +53,11 @@ public class LicenseVerifier {
license.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); license.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
Signature rsa = Signature.getInstance("SHA512withRSA"); Signature rsa = Signature.getInstance("SHA512withRSA");
rsa.initVerify(CryptUtils.readEncryptedPublicKey(encryptedPublicKeyData)); rsa.initVerify(CryptUtils.readEncryptedPublicKey(encryptedPublicKeyData));
rsa.update(contentBuilder.bytes().toBytes()); BytesRefIterator iterator = contentBuilder.bytes().iterator();
BytesRef ref;
while((ref = iterator.next()) != null) {
rsa.update(ref.bytes, ref.offset, ref.length);
}
return rsa.verify(signedContent) return rsa.verify(signedContent)
&& Arrays.equals(Base64.getEncoder().encode(encryptedPublicKeyData), signatureHash); && Arrays.equals(Base64.getEncoder().encode(encryptedPublicKeyData), signatureHash);
} catch (IOException | NoSuchAlgorithmException | SignatureException | InvalidKeyException e) { } catch (IOException | NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {

View File

@ -25,9 +25,9 @@ import static org.hamcrest.core.IsEqual.equalTo;
public class TestUtils { public class TestUtils {
private final static FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd"); private static final FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd");
private final static DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter); private static final DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter);
private final static DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer(); private static final DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer();
public static String dateMathString(String time, final long now) { public static String dateMathString(String time, final long now) {
return dateTimeFormatter.print(dateMathParser.parse(time, new Callable<Long>() { return dateTimeFormatter.print(dateMathParser.parse(time, new Callable<Long>() {

View File

@ -5,6 +5,9 @@
*/ */
package org.elasticsearch.license.licensor; package org.elasticsearch.license.licensor;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
@ -30,7 +33,7 @@ import java.util.Collections;
*/ */
public class LicenseSigner { public class LicenseSigner {
private final static int MAGIC_LENGTH = 13; private static final int MAGIC_LENGTH = 13;
private final Path publicKeyPath; private final Path publicKeyPath;
@ -55,7 +58,11 @@ public class LicenseSigner {
try { try {
final Signature rsa = Signature.getInstance("SHA512withRSA"); final Signature rsa = Signature.getInstance("SHA512withRSA");
rsa.initSign(CryptUtils.readEncryptedPrivateKey(Files.readAllBytes(privateKeyPath))); rsa.initSign(CryptUtils.readEncryptedPrivateKey(Files.readAllBytes(privateKeyPath)));
rsa.update(contentBuilder.bytes().toBytes()); final BytesRefIterator iterator = contentBuilder.bytes().iterator();
BytesRef ref;
while((ref = iterator.next()) != null) {
rsa.update(ref.bytes, ref.offset, ref.length);
}
signedContent = rsa.sign(); signedContent = rsa.sign();
} catch (InvalidKeyException | IOException | NoSuchAlgorithmException | SignatureException e) { } catch (InvalidKeyException | IOException | NoSuchAlgorithmException | SignatureException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);

View File

@ -10,7 +10,7 @@ import joptsimple.OptionSpec;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
@ -54,9 +54,9 @@ public class KeyPairGeneratorTool extends Command {
Path publicKeyPath = parsePath(publicKeyPathOption.value(options)); Path publicKeyPath = parsePath(publicKeyPathOption.value(options));
Path privateKeyPath = parsePath(privateKeyPathOption.value(options)); Path privateKeyPath = parsePath(privateKeyPathOption.value(options));
if (Files.exists(privateKeyPath)) { if (Files.exists(privateKeyPath)) {
throw new UserError(ExitCodes.USAGE, privateKeyPath + " already exists"); throw new UserException(ExitCodes.USAGE, privateKeyPath + " already exists");
} else if (Files.exists(publicKeyPath)) { } else if (Files.exists(publicKeyPath)) {
throw new UserError(ExitCodes.USAGE, publicKeyPath + " already exists"); throw new UserException(ExitCodes.USAGE, publicKeyPath + " already exists");
} }
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();

View File

@ -12,7 +12,7 @@ import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.Terminal;
import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
@ -62,9 +62,9 @@ public class LicenseGeneratorTool extends Command {
Path publicKeyPath = parsePath(publicKeyPathOption.value(options)); Path publicKeyPath = parsePath(publicKeyPathOption.value(options));
Path privateKeyPath = parsePath(privateKeyPathOption.value(options)); Path privateKeyPath = parsePath(privateKeyPathOption.value(options));
if (Files.exists(privateKeyPath) == false) { if (Files.exists(privateKeyPath) == false) {
throw new UserError(ExitCodes.USAGE, privateKeyPath + " does not exist"); throw new UserException(ExitCodes.USAGE, privateKeyPath + " does not exist");
} else if (Files.exists(publicKeyPath) == false) { } else if (Files.exists(publicKeyPath) == false) {
throw new UserError(ExitCodes.USAGE, publicKeyPath + " does not exist"); throw new UserException(ExitCodes.USAGE, publicKeyPath + " does not exist");
} }
final License licenseSpec; final License licenseSpec;
@ -73,11 +73,11 @@ public class LicenseGeneratorTool extends Command {
} else if (options.has(licenseFileOption)) { } else if (options.has(licenseFileOption)) {
Path licenseSpecPath = parsePath(licenseFileOption.value(options)); Path licenseSpecPath = parsePath(licenseFileOption.value(options));
if (Files.exists(licenseSpecPath) == false) { if (Files.exists(licenseSpecPath) == false) {
throw new UserError(ExitCodes.USAGE, licenseSpecPath + " does not exist"); throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist");
} }
licenseSpec = License.fromSource(Files.readAllBytes(licenseSpecPath)); licenseSpec = License.fromSource(Files.readAllBytes(licenseSpecPath));
} else { } else {
throw new UserError(ExitCodes.USAGE, "Must specify either --license or --licenseFile"); throw new UserException(ExitCodes.USAGE, "Must specify either --license or --licenseFile");
} }
// sign // sign

View File

@ -12,7 +12,7 @@ import joptsimple.OptionSet;
import joptsimple.OptionSpec; import joptsimple.OptionSpec;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.Terminal;
import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
@ -49,7 +49,7 @@ public class LicenseVerificationTool extends Command {
protected void execute(Terminal terminal, OptionSet options) throws Exception { protected void execute(Terminal terminal, OptionSet options) throws Exception {
Path publicKeyPath = parsePath(publicKeyPathOption.value(options)); Path publicKeyPath = parsePath(publicKeyPathOption.value(options));
if (Files.exists(publicKeyPath) == false) { if (Files.exists(publicKeyPath) == false) {
throw new UserError(ExitCodes.USAGE, publicKeyPath + " does not exist"); throw new UserException(ExitCodes.USAGE, publicKeyPath + " does not exist");
} }
final License licenseSpec; final License licenseSpec;
@ -58,16 +58,16 @@ public class LicenseVerificationTool extends Command {
} else if (options.has(licenseFileOption)) { } else if (options.has(licenseFileOption)) {
Path licenseSpecPath = parsePath(licenseFileOption.value(options)); Path licenseSpecPath = parsePath(licenseFileOption.value(options));
if (Files.exists(licenseSpecPath) == false) { if (Files.exists(licenseSpecPath) == false) {
throw new UserError(ExitCodes.USAGE, licenseSpecPath + " does not exist"); throw new UserException(ExitCodes.USAGE, licenseSpecPath + " does not exist");
} }
licenseSpec = License.fromSource(Files.readAllBytes(licenseSpecPath)); licenseSpec = License.fromSource(Files.readAllBytes(licenseSpecPath));
} else { } else {
throw new UserError(ExitCodes.USAGE, "Must specify either --license or --licenseFile"); throw new UserException(ExitCodes.USAGE, "Must specify either --license or --licenseFile");
} }
// verify // verify
if (LicenseVerifier.verifyLicense(licenseSpec, Files.readAllBytes(publicKeyPath)) == false) { if (LicenseVerifier.verifyLicense(licenseSpec, Files.readAllBytes(publicKeyPath)) == false) {
throw new UserError(ExitCodes.DATA_ERROR, "Invalid License!"); throw new UserException(ExitCodes.DATA_ERROR, "Invalid License!");
} }
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject(); builder.startObject();

View File

@ -36,9 +36,9 @@ public class TestUtils {
public static final String PUBLIC_KEY_RESOURCE = "/public.key"; public static final String PUBLIC_KEY_RESOURCE = "/public.key";
public static final String PRIVATE_KEY_RESOURCE = "/private.key"; public static final String PRIVATE_KEY_RESOURCE = "/private.key";
private final static FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd"); private static final FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd");
private final static DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter); private static final DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter);
private final static DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer(); private static final DateTimeFormatter dateTimeFormatter = formatDateTimeFormatter.printer();
public static String dumpLicense(License license) throws Exception { public static String dumpLicense(License license) throws Exception {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);

View File

@ -11,9 +11,7 @@ import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
@ -27,12 +25,12 @@ public class KeyPairGenerationToolTests extends CommandTestCase {
public void testMissingKeyPaths() throws Exception { public void testMissingKeyPaths() throws Exception {
Path exists = createTempFile("", "existing"); Path exists = createTempFile("", "existing");
Path dne = createTempDir().resolve("dne"); Path dne = createTempDir().resolve("dne");
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", exists.toString(), "--privateKeyPath", dne.toString()); execute("--publicKeyPath", exists.toString(), "--privateKeyPath", dne.toString());
}); });
assertThat(e.getMessage(), containsString("existing")); assertThat(e.getMessage(), containsString("existing"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
e = expectThrows(UserError.class, () -> { e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", dne.toString(), "--privateKeyPath", exists.toString()); execute("--publicKeyPath", dne.toString(), "--privateKeyPath", exists.toString());
}); });
assertThat(e.getMessage(), containsString("existing")); assertThat(e.getMessage(), containsString("existing"));

View File

@ -12,12 +12,9 @@ import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.cli.MockTerminal;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.license.core.License; import org.elasticsearch.license.core.License;
import org.elasticsearch.license.licensor.TestUtils; import org.elasticsearch.license.licensor.TestUtils;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before; import org.junit.Before;
public class LicenseGenerationToolTests extends CommandTestCase { public class LicenseGenerationToolTests extends CommandTestCase {
@ -38,14 +35,14 @@ public class LicenseGenerationToolTests extends CommandTestCase {
public void testMissingKeyPaths() throws Exception { public void testMissingKeyPaths() throws Exception {
Path pub = createTempDir().resolve("pub"); Path pub = createTempDir().resolve("pub");
Path pri = createTempDir().resolve("pri"); Path pri = createTempDir().resolve("pri");
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString()); execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("pri does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pri does not exist"));
assertEquals(ExitCodes.USAGE, e.exitCode); assertEquals(ExitCodes.USAGE, e.exitCode);
Files.createFile(pri); Files.createFile(pri);
e = expectThrows(UserError.class, () -> { e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString()); execute("--publicKeyPath", pub.toString(), "--privateKeyPath", pri.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist"));
@ -53,7 +50,7 @@ public class LicenseGenerationToolTests extends CommandTestCase {
} }
public void testMissingLicenseSpec() throws Exception { public void testMissingLicenseSpec() throws Exception {
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pubKeyPath.toString(), "--privateKeyPath", priKeyPath.toString()); execute("--publicKeyPath", pubKeyPath.toString(), "--privateKeyPath", priKeyPath.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile")); assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile"));

View File

@ -12,7 +12,7 @@ import java.nio.file.Path;
import org.elasticsearch.cli.Command; import org.elasticsearch.cli.Command;
import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.CommandTestCase;
import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.UserError; import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.license.core.License; import org.elasticsearch.license.core.License;
import org.elasticsearch.license.licensor.TestUtils; import org.elasticsearch.license.licensor.TestUtils;
@ -36,7 +36,7 @@ public class LicenseVerificationToolTests extends CommandTestCase {
public void testMissingKeyPath() throws Exception { public void testMissingKeyPath() throws Exception {
Path pub = createTempDir().resolve("pub"); Path pub = createTempDir().resolve("pub");
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pub.toString()); execute("--publicKeyPath", pub.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist")); assertTrue(e.getMessage(), e.getMessage().contains("pub does not exist"));
@ -44,7 +44,7 @@ public class LicenseVerificationToolTests extends CommandTestCase {
} }
public void testMissingLicenseSpec() throws Exception { public void testMissingLicenseSpec() throws Exception {
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pubKeyPath.toString()); execute("--publicKeyPath", pubKeyPath.toString());
}); });
assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile")); assertTrue(e.getMessage(), e.getMessage().contains("Must specify either --license or --licenseFile"));
@ -56,7 +56,7 @@ public class LicenseVerificationToolTests extends CommandTestCase {
License tamperedLicense = License.builder() License tamperedLicense = License.builder()
.fromLicenseSpec(signedLicense, signedLicense.signature()) .fromLicenseSpec(signedLicense, signedLicense.signature())
.expiryDate(signedLicense.expiryDate() + randomIntBetween(1, 1000)).build(); .expiryDate(signedLicense.expiryDate() + randomIntBetween(1, 1000)).build();
UserError e = expectThrows(UserError.class, () -> { UserException e = expectThrows(UserException.class, () -> {
execute("--publicKeyPath", pubKeyPath.toString(), execute("--publicKeyPath", pubKeyPath.toString(),
"--license", TestUtils.dumpLicense(tamperedLicense)); "--license", TestUtils.dumpLicense(tamperedLicense));
}); });

View File

@ -39,11 +39,8 @@ public final class MessyTestUtils {
ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections.singleton(groovyScriptEngineService)); ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections.singleton(groovyScriptEngineService));
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Arrays.asList(ScriptServiceProxy.INSTANCE)); ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Arrays.asList(ScriptServiceProxy.INSTANCE));
ClusterService clusterService = Mockito.mock(ClusterService.class);
Mockito.when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("_name")).build());
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry); ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
return ScriptServiceProxy.of(new ScriptService(settings, new Environment(settings), return ScriptServiceProxy.of(new ScriptService(settings, new Environment(settings),
new ResourceWatcherService(settings, tp), scriptEngineRegistry, scriptContextRegistry, scriptSettings), new ResourceWatcherService(settings, tp), scriptEngineRegistry, scriptContextRegistry, scriptSettings));
clusterService);
} }
} }

View File

@ -14,18 +14,18 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.script.GeneralScriptException; import org.elasticsearch.script.GeneralScriptException;
import org.elasticsearch.script.ScriptException;
import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.internal.InternalSearchResponse; import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.watcher.condition.Condition; import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.condition.script.ExecutableScriptCondition; import org.elasticsearch.xpack.watcher.condition.script.ExecutableScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition; import org.elasticsearch.xpack.watcher.condition.script.ScriptCondition;
import org.elasticsearch.xpack.watcher.condition.script.ScriptConditionFactory; import org.elasticsearch.xpack.watcher.condition.script.ScriptConditionFactory;
import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.watcher.support.Script; import org.elasticsearch.xpack.watcher.support.Script;
import org.elasticsearch.xpack.common.ScriptServiceProxy;
import org.elasticsearch.xpack.watcher.watch.Payload; import org.elasticsearch.xpack.watcher.watch.Payload;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
@ -41,12 +41,10 @@ import static org.elasticsearch.xpack.watcher.support.Exceptions.illegalArgument
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.mockExecutionContext;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
*/
public class ScriptConditionTests extends ESTestCase { public class ScriptConditionTests extends ESTestCase {
ThreadPool tp = null;
private ThreadPool tp = null;
@Before @Before
public void init() { public void init() {
@ -54,8 +52,8 @@ public class ScriptConditionTests extends ESTestCase {
} }
@After @After
public void cleanup() { public void cleanup() throws InterruptedException {
tp.shutdownNow(); terminate(tp);
} }
public void testExecute() throws Exception { public void testExecute() throws Exception {
@ -136,13 +134,8 @@ public class ScriptConditionTests extends ESTestCase {
XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes());
parser.nextToken(); parser.nextToken();
ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser); ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser);
try { GeneralScriptException exception = expectThrows(GeneralScriptException.class,
conditionParser.createExecutable(scriptCondition); () -> conditionParser.createExecutable(scriptCondition));
fail("expected a condition validation exception trying to create an executable with a bad or missing script");
} catch (GeneralScriptException e) {
// TODO add these when the test if fixed
// assertThat(e.getMessage(), is("ASDF"));
}
} }
public void testScriptConditionParser_badLang() throws Exception { public void testScriptConditionParser_badLang() throws Exception {
@ -153,39 +146,30 @@ public class ScriptConditionTests extends ESTestCase {
XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes());
parser.nextToken(); parser.nextToken();
ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser); ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser);
try { GeneralScriptException exception = expectThrows(GeneralScriptException.class,
conditionParser.createExecutable(scriptCondition); () -> conditionParser.createExecutable(scriptCondition));
fail("expected a condition validation exception trying to create an executable with an invalid language"); assertThat(exception.getMessage(), containsString("script_lang not supported [not_a_valid_lang]]"));
} catch (GeneralScriptException e) {
// TODO add these when the test if fixed
// assertThat(e.getMessage(), is("ASDF"));
}
} }
public void testScriptConditionThrowException() throws Exception { public void testScriptConditionThrowException() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition( ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("assert false").build()), logger, scriptService); new ScriptCondition(Script.inline("null.foo").build()), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
ScriptCondition.Result result = condition.execute(ctx); ScriptException exception = expectThrows(ScriptException.class, () -> condition.execute(ctx));
assertThat(result, notNullValue()); assertThat(exception.getMessage(), containsString("Error evaluating null.foo"));
assertThat(result.status(), is(Condition.Result.Status.FAILURE));
assertThat(result.reason(), notNullValue());
assertThat(result.reason(), containsString("Assertion"));
} }
public void testScriptConditionReturnObject() throws Exception { public void testScriptConditionReturnObjectThrowsException() throws Exception {
ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ScriptServiceProxy scriptService = getScriptServiceProxy(tp);
ExecutableScriptCondition condition = new ExecutableScriptCondition( ExecutableScriptCondition condition = new ExecutableScriptCondition(
new ScriptCondition(Script.inline("return new Object()").build()), logger, scriptService); new ScriptCondition(Script.inline("return new Object()").build()), logger, scriptService);
SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500L, new ShardSearchFailure[0]);
WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response));
ScriptCondition.Result result = condition.execute(ctx); Exception exception = expectThrows(GeneralScriptException.class, () -> condition.execute(ctx));
assertThat(result, notNullValue()); assertThat(exception.getMessage(),
assertThat(result.status(), is(Condition.Result.Status.FAILURE)); containsString("condition [script] must return a boolean value (true|false) but instead returned [_name]"));
assertThat(result.reason(), notNullValue());
assertThat(result.reason(), containsString("ScriptException"));
} }
public void testScriptConditionAccessCtx() throws Exception { public void testScriptConditionAccessCtx() throws Exception {

View File

@ -93,7 +93,7 @@ public class SearchInputIT extends ESIntegTestCase {
return types; return types;
} }
private final static String TEMPLATE_QUERY = "{\"query\":{\"bool\":{\"must\":{\"match\":{\"event_type\":{\"query\":\"a\"," + private static final String TEMPLATE_QUERY = "{\"query\":{\"bool\":{\"must\":{\"match\":{\"event_type\":{\"query\":\"a\"," +
"\"type\":\"boolean\"}}},\"filter\":{\"range\":{\"_timestamp\":" + "\"type\":\"boolean\"}}},\"filter\":{\"range\":{\"_timestamp\":" +
"{\"from\":\"{{ctx.trigger.scheduled_time}}||-{{seconds_param}}\",\"to\":\"{{ctx.trigger.scheduled_time}}\"," + "{\"from\":\"{{ctx.trigger.scheduled_time}}||-{{seconds_param}}\",\"to\":\"{{ctx.trigger.scheduled_time}}\"," +
"\"include_lower\":true,\"include_upper\":true}}}}}}"; "\"include_lower\":true,\"include_upper\":true}}}}}}";
@ -362,7 +362,7 @@ public class SearchInputIT extends ESIntegTestCase {
protected WatcherSearchTemplateService watcherSearchTemplateService() { protected WatcherSearchTemplateService watcherSearchTemplateService() {
String master = internalCluster().getMasterName(); String master = internalCluster().getMasterName();
return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(), return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(),
ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master), internalCluster().clusterService(master)), ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master)),
internalCluster().getInstance(IndicesQueriesRegistry.class, master), internalCluster().getInstance(IndicesQueriesRegistry.class, master),
internalCluster().getInstance(AggregatorParsers.class, master), internalCluster().getInstance(AggregatorParsers.class, master),
internalCluster().getInstance(Suggesters.class, master) internalCluster().getInstance(Suggesters.class, master)
@ -370,7 +370,7 @@ public class SearchInputIT extends ESIntegTestCase {
} }
protected ScriptServiceProxy scriptService() { protected ScriptServiceProxy scriptService() {
return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class), internalCluster().clusterService()); return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class));
} }
private XContentSource toXContentSource(SearchInput.Result result) throws IOException { private XContentSource toXContentSource(SearchInput.Result result) throws IOException {

View File

@ -519,7 +519,7 @@ public class SearchTransformIT extends ESIntegTestCase {
protected WatcherSearchTemplateService watcherSearchTemplateService() { protected WatcherSearchTemplateService watcherSearchTemplateService() {
String master = internalCluster().getMasterName(); String master = internalCluster().getMasterName();
return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(), return new WatcherSearchTemplateService(internalCluster().clusterService(master).getSettings(),
ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master), internalCluster().clusterService(master)), ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class, master)),
internalCluster().getInstance(IndicesQueriesRegistry.class, master), internalCluster().getInstance(IndicesQueriesRegistry.class, master),
internalCluster().getInstance(AggregatorParsers.class, master), internalCluster().getInstance(AggregatorParsers.class, master),
internalCluster().getInstance(Suggesters.class, master) internalCluster().getInstance(Suggesters.class, master)
@ -527,7 +527,7 @@ public class SearchTransformIT extends ESIntegTestCase {
} }
protected ScriptServiceProxy scriptService() { protected ScriptServiceProxy scriptService() {
return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class), internalCluster().clusterService()); return ScriptServiceProxy.of(internalCluster().getInstance(ScriptService.class));
} }
private static Map<String, Object> doc(String date, String value) { private static Map<String, Object> doc(String date, String value) {

View File

@ -0,0 +1,32 @@
apply plugin: 'elasticsearch.rest-test'
dependencies {
testCompile project(path: ':x-plugins:elasticsearch:x-pack', configuration: 'runtime')
}
integTest {
cluster {
setting 'script.inline', 'true'
plugin 'x-pack', project(':x-plugins:elasticsearch:x-pack')
extraConfigFile 'x-pack/roles.yml', 'roles.yml'
[
test_admin: 'superuser',
transport_user: 'superuser',
existing: 'superuser',
bob: 'actual_role'
].each { String user, String role ->
setupCommand 'setupUser#' + user,
'bin/x-pack/users', 'useradd', user, '-p', 'changeme', '-r', role
}
waitCondition = { node, ant ->
File tmpFile = new File(node.cwd, 'wait.success')
ant.get(src: "http://${node.httpUri()}",
dest: tmpFile.toString(),
username: 'test_admin',
password: 'changeme',
ignoreerrors: true,
retries: 10)
return tmpFile.exists()
}
}
}

View File

@ -0,0 +1,17 @@
actual_role:
run_as: [ "joe" ]
cluster:
- monitor
indices:
- names: [ "index1", "index2" ]
privileges: [ "read", "write", "create_index", "indices:admin/refresh" ]
fields:
- foo
- bar
query:
bool:
must_not:
match:
hidden: true
- names: "*"
privileges: [ "read" ]

View File

@ -0,0 +1,123 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cli.MockTerminal;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.xpack.security.SecurityTemplateService;
import org.elasticsearch.xpack.security.action.role.GetRolesResponse;
import org.elasticsearch.xpack.security.action.user.GetUsersResponse;
import org.elasticsearch.xpack.security.action.user.PutUserResponse;
import org.elasticsearch.xpack.security.authc.esnative.ESNativeRealmMigrateTool;
import org.elasticsearch.xpack.security.authc.support.SecuredString;
import org.elasticsearch.xpack.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.security.client.SecurityClient;
import org.elasticsearch.xpack.security.user.User;
import org.junit.Before;
import java.util.Arrays;
import java.util.Collections;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.containsString;
/**
* Integration tests for the {@code migrate} shell command
*/
public class MigrateToolIT extends MigrateToolTestCase {
@Before
public void setupUpTest() throws Exception {
Client client = getClient();
SecurityClient c = new SecurityClient(client);
// Add an existing user so the tool will skip it
PutUserResponse pur = c.preparePutUser("existing", "s3kirt".toCharArray(), "role1", "user").get();
assertTrue(pur.created());
}
private static String[] args(String command) {
if (!Strings.hasLength(command)) {
return Strings.EMPTY_ARRAY;
}
return command.split("\\s+");
}
public void testRunMigrateTool() throws Exception {
Settings settings = Settings.builder()
.put("path.home", createTempDir().toAbsolutePath().toString())
.build();
String integHome = System.getProperty("tests.config.dir");
logger.info("--> HOME: {}", integHome);
// Cluster should already be up
String url = "http://" + getHttpURL();
logger.info("--> using URL: {}", url);
MockTerminal t = new MockTerminal();
ESNativeRealmMigrateTool.MigrateUserOrRoles muor = new ESNativeRealmMigrateTool.MigrateUserOrRoles();
OptionParser parser = muor.getParser();
OptionSet options = parser.parse("-u", "test_admin", "-p", "changeme", "-U", url, "-c", integHome);
muor.execute(t, options, settings.getAsMap());
logger.info("--> output:\n{}", t.getOutput());
Client client = getClient();
SecurityClient c = new SecurityClient(client);
// Check that the migrated user can be retrieved
GetUsersResponse resp = c.prepareGetUsers("bob").get();
assertTrue("user 'bob' should exist", resp.hasUsers());
User bob = resp.users()[0];
assertEquals(bob.principal(), "bob");
assertArrayEquals(bob.roles(), new String[]{"actual_role"});
// Make sure the existing user did not change
resp = c.prepareGetUsers("existing").get();
assertTrue("user should exist", resp.hasUsers());
User existing = resp.users()[0];
assertEquals(existing.principal(), "existing");
assertArrayEquals(existing.roles(), new String[]{"role1", "user"});
// Make sure the "actual_role" made it in and is correct
GetRolesResponse roleResp = c.prepareGetRoles().names("actual_role").get();
assertTrue("role should exist", roleResp.hasRoles());
RoleDescriptor rd = roleResp.roles()[0];
assertNotNull(rd);
assertEquals(rd.getName(), "actual_role");
assertArrayEquals(rd.getClusterPrivileges(), new String[]{"monitor"});
assertArrayEquals(rd.getRunAs(), new String[]{"joe"});
RoleDescriptor.IndicesPrivileges[] ips = rd.getIndicesPrivileges();
assertEquals(ips.length, 2);
for (RoleDescriptor.IndicesPrivileges ip : ips) {
if (Arrays.equals(ip.getIndices(), new String[]{"index1", "index2"})) {
assertArrayEquals(ip.getPrivileges(), new String[]{"read", "write", "create_index", "indices:admin/refresh"});
assertArrayEquals(ip.getFields(), new String[]{"foo", "bar"});
assertNotNull(ip.getQuery());
assertThat(ip.getQuery().utf8ToString(), containsString("{\"bool\":{\"must_not\":{\"match\":{\"hidden\":true}}}}"));
} else {
assertArrayEquals(ip.getIndices(), new String[]{"*"});
assertArrayEquals(ip.getPrivileges(), new String[]{"read"});
assertArrayEquals(ip.getFields(), null);
assertNull(ip.getQuery());
}
}
// Check that bob can access the things the "actual_role" says he can
String token = basicAuthHeaderValue("bob", new SecuredString("changeme".toCharArray()));
// Create "index1" index and try to search from it as "bob"
client.filterWithHeader(Collections.singletonMap("Authorization", token)).admin().indices().prepareCreate("index1").get();
SearchResponse searchResp = client.filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("index1").get();
}
}

View File

@ -0,0 +1,177 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.node.internal.InternalSettingsPreparer;
import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.xpack.XPackPlugin;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiOfLength;
import static org.hamcrest.Matchers.notNullValue;
/**
* {@link MigrateToolTestCase} is an abstract base class to run integration
* tests against an external Elasticsearch Cluster.
* <p>
* You can define a list of transport addresses from where you can reach your cluster
* by setting "tests.cluster" system property. It defaults to "localhost:9300".
* <p>
* All tests can be run from maven using mvn install as maven will start an external cluster first.
* <p>
* If you want to debug this module from your IDE, then start an external cluster by yourself
* then run JUnit. If you changed the default port, set "tests.cluster=localhost:PORT" when running
* your test.
*/
@LuceneTestCase.SuppressSysoutChecks(bugUrl = "we log a lot on purpose")
public abstract class MigrateToolTestCase extends LuceneTestCase {
/**
* Key used to eventually switch to using an external cluster and provide its transport addresses
*/
public static final String TESTS_CLUSTER = "tests.cluster";
/**
* Key used to eventually switch to using an external cluster and provide its transport addresses
*/
public static final String TESTS_HTTP_CLUSTER = "tests.rest.cluster";
/**
* Defaults to localhost:9300
*/
public static final String TESTS_CLUSTER_DEFAULT = "localhost:9300";
protected static final ESLogger logger = ESLoggerFactory.getLogger(MigrateToolTestCase.class.getName());
private static final AtomicInteger counter = new AtomicInteger();
private static Client client;
private static String clusterAddresses;
private static String clusterHttpAddresses;
private static Client startClient(Path tempDir, TransportAddress... transportAddresses) {
logger.info("--> Starting Elasticsearch Java TransportClient {}, {}", transportAddresses, tempDir);
Settings clientSettings = Settings.builder()
.put("cluster.name", "qa_migrate_tests_" + counter.getAndIncrement())
.put("client.transport.ignore_cluster_name", true)
.put("path.home", tempDir)
.put(Security.USER_SETTING.getKey(), "transport_user:changeme")
.put("node.mode", "network") // we require network here!
.build();
TransportClient.Builder transportClientBuilder = TransportClient.builder()
.addPlugin(XPackPlugin.class)
.settings(clientSettings);
TransportClient client = transportClientBuilder.build().addTransportAddresses(transportAddresses);
logger.info("--> Elasticsearch Java TransportClient started");
Exception clientException = null;
try {
ClusterHealthResponse health = client.admin().cluster().prepareHealth().get();
logger.info("--> connected to [{}] cluster which is running [{}] node(s).",
health.getClusterName(), health.getNumberOfNodes());
} catch (Exception e) {
clientException = e;
}
assumeNoException("Sounds like your cluster is not running at " + clusterAddresses, clientException);
return client;
}
private static Client startClient() throws UnknownHostException {
String[] stringAddresses = clusterAddresses.split(",");
TransportAddress[] transportAddresses = new TransportAddress[stringAddresses.length];
int i = 0;
for (String stringAddress : stringAddresses) {
int lastColon = stringAddress.lastIndexOf(":");
if (lastColon == -1) {
throw new IllegalArgumentException("address [" + clusterAddresses + "] not valid");
}
String ip = stringAddress.substring(0, lastColon);
String port = stringAddress.substring(lastColon + 1);
try {
transportAddresses[i++] = new InetSocketTransportAddress(InetAddress.getByName(ip), Integer.valueOf(port));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("port is not valid, expected number but was [" + port + "]");
}
}
return startClient(createTempDir(), transportAddresses);
}
public static Client getClient() {
if (client == null) {
try {
client = startClient();
} catch (UnknownHostException e) {
logger.error("could not start the client", e);
}
assertThat(client, notNullValue());
}
return client;
}
public static String getHttpURL() {
return clusterHttpAddresses;
}
@BeforeClass
public static void initializeSettings() throws UnknownHostException {
String port = System.getProperty("integ.http.port");
clusterAddresses = System.getProperty(TESTS_CLUSTER);
clusterHttpAddresses = System.getProperty(TESTS_HTTP_CLUSTER);
if (clusterAddresses == null || clusterAddresses.isEmpty()) {
throw new UnknownHostException("unable to get a cluster address");
}
}
@AfterClass
public static void stopTransportClient() {
if (client != null) {
client.close();
client = null;
}
}
@Before
public void defineIndexName() {
doClean();
}
@After
public void cleanIndex() {
doClean();
}
private void doClean() {
if (client != null) {
try {
client.admin().indices().prepareDelete("_all").get();
} catch (Exception e) {
// We ignore this cleanup exception
}
}
}
}

View File

@ -22,8 +22,8 @@ import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordTok
public class GraphWithSecurityIT extends ESRestTestCase { public class GraphWithSecurityIT extends ESRestTestCase {
private final static String TEST_ADMIN_USERNAME = "test_admin"; private static final String TEST_ADMIN_USERNAME = "test_admin";
private final static String TEST_ADMIN_PASSWORD = "changeme"; private static final String TEST_ADMIN_PASSWORD = "changeme";
public GraphWithSecurityIT(@Name("yaml") RestTestCandidate testCandidate) { public GraphWithSecurityIT(@Name("yaml") RestTestCandidate testCandidate) {
super(testCandidate); super(testCandidate);

View File

@ -174,7 +174,7 @@ integTest {
setupCommand 'setupTestUser', setupCommand 'setupTestUser',
'bin/x-pack/users', 'useradd', 'test_user', '-p', 'changeme', '-r', 'superuser' 'bin/x-pack/users', 'useradd', 'test_user', '-p', 'changeme', '-r', 'superuser'
setupCommand 'setupMarvelUser', setupCommand 'setupMonitoringUser',
'bin/x-pack/users', 'useradd', 'monitoring_agent', '-p', 'changeme', '-r', 'remote_monitoring_agent' 'bin/x-pack/users', 'useradd', 'monitoring_agent', '-p', 'changeme', '-r', 'remote_monitoring_agent'
// Required to detect that the monitoring agent service has started // Required to detect that the monitoring agent service has started

View File

@ -58,9 +58,7 @@ public class WatcherTemplateTests extends ESTestCase {
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, registry); ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, registry);
ScriptService scriptService = new ScriptService(setting, environment, resourceWatcherService, scriptEngineRegistry, ScriptService scriptService = new ScriptService(setting, environment, resourceWatcherService, scriptEngineRegistry,
registry, scriptSettings); registry, scriptSettings);
ClusterService clusterService = Mockito.mock(ClusterService.class); engine = new DefaultTextTemplateEngine(Settings.EMPTY, ScriptServiceProxy.of(scriptService));
Mockito.when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("_name")).build());
engine = new DefaultTextTemplateEngine(Settings.EMPTY, ScriptServiceProxy.of(scriptService, clusterService));
} }
public void testEscaping() throws Exception { public void testEscaping() throws Exception {

View File

@ -27,8 +27,8 @@ import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordTok
public class WatcherWithSecurityIT extends ESRestTestCase { public class WatcherWithSecurityIT extends ESRestTestCase {
private final static String TEST_ADMIN_USERNAME = "test_admin"; private static final String TEST_ADMIN_USERNAME = "test_admin";
private final static String TEST_ADMIN_PASSWORD = "changeme"; private static final String TEST_ADMIN_PASSWORD = "changeme";
public WatcherWithSecurityIT(@Name("yaml") RestTestCandidate testCandidate) { public WatcherWithSecurityIT(@Name("yaml") RestTestCandidate testCandidate) {
super(testCandidate); super(testCandidate);

View File

@ -1,6 +1,8 @@
import org.elasticsearch.gradle.MavenFilteringHack import org.elasticsearch.gradle.MavenFilteringHack
import org.elasticsearch.gradle.test.NodeInfo import org.elasticsearch.gradle.test.NodeInfo
import java.nio.charset.StandardCharsets
group 'org.elasticsearch.plugin' group 'org.elasticsearch.plugin'
apply plugin: 'elasticsearch.esplugin' apply plugin: 'elasticsearch.esplugin'
@ -57,7 +59,7 @@ dependencies {
// we keep the source directories in the original structure of split plugins, // we keep the source directories in the original structure of split plugins,
// in order to facilitate backports to 2.x. TODO: remove after 5.0 release // in order to facilitate backports to 2.x. TODO: remove after 5.0 release
for (String module : ['', 'license-plugin/', 'security/', 'watcher/', 'marvel/', 'graph/']) { for (String module : ['', 'license-plugin/', 'security/', 'watcher/', 'monitoring/', 'graph/']) {
sourceSets { sourceSets {
main { main {
java.srcDir("${module}src/main/java") java.srcDir("${module}src/main/java")
@ -132,15 +134,33 @@ integTest {
systemProperty 'tests.rest.blacklist', 'getting_started/10_monitor_cluster_health/*,bulk/10_basic/*' systemProperty 'tests.rest.blacklist', 'getting_started/10_monitor_cluster_health/*,bulk/10_basic/*'
cluster { cluster {
setting 'xpack.monitoring.agent.interval', '3s' setting 'xpack.monitoring.agent.interval', '3s'
setupCommand 'setupDummyUser', 'bin/x-pack/users', 'useradd', 'test_user', '-p', 'changeme', '-r', 'superuser'
waitCondition = { NodeInfo node, AntBuilder ant -> waitCondition = { NodeInfo node, AntBuilder ant ->
File tmpFile = new File(node.cwd, 'wait.success') File tmpFile = new File(node.cwd, 'wait.success')
ant.get(src: "http://${node.httpUri()}", for (int i = 0; i < 10; i++) {
dest: tmpFile.toString(), // we use custom wait logic here as the elastic user is not available immediately and ant.get will fail when a 401 is returned
username: "test_user", HttpURLConnection httpURLConnection = null;
password: "changeme", try {
ignoreerrors: true, // do not fail on error, so logging buffers can be flushed by the wait task httpURLConnection = (HttpURLConnection) new URL("http://${node.httpUri()}").openConnection();
retries: 10) httpURLConnection.setRequestProperty("Authorization", "Basic " +
Base64.getEncoder().encodeToString("elastic:changeme".getBytes(StandardCharsets.UTF_8)));
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
tmpFile.withWriter StandardCharsets.UTF_8.name(), {
it.write(httpURLConnection.getInputStream().getText(StandardCharsets.UTF_8.name()))
}
}
} catch (Exception e) {
e.printStackTrace()
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
// did not start, so wait a bit before trying again
Thread.sleep(500L);
}
return tmpFile.exists() return tmpFile.exists()
} }
} }

View File

@ -9,12 +9,11 @@ import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ActionPlugin.ActionHandler; import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.graph.action.GraphExploreAction; import org.elasticsearch.xpack.graph.action.GraphExploreAction;
import org.elasticsearch.xpack.graph.action.TransportGraphExploreAction; import org.elasticsearch.xpack.graph.action.TransportGraphExploreAction;
@ -57,19 +56,20 @@ public class Graph extends Plugin implements ActionPlugin {
@Override @Override
public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
if (enabled) { if (false == enabled) {
return singletonList(new ActionHandler<>(GraphExploreAction.INSTANCE, TransportGraphExploreAction.class)); return emptyList();
} }
return emptyList(); return singletonList(new ActionHandler<>(GraphExploreAction.INSTANCE, TransportGraphExploreAction.class));
} }
public void onModule(NetworkModule module) { @Override
if (enabled && transportClientMode == false) { public List<Class<? extends RestHandler>> getRestHandlers() {
module.registerRestHandler(RestGraphAction.class); if (false == enabled) {
return emptyList();
} }
return singletonList(RestGraphAction.class);
} }
@Override @Override
public List<Setting<?>> getSettings() { public List<Setting<?>> getSettings() {
return Collections.singletonList(Setting.boolSetting(XPackPlugin.featureEnabledSetting(NAME), true, Setting.Property.NodeScope)); return Collections.singletonList(Setting.boolSetting(XPackPlugin.featureEnabledSetting(NAME), true, Setting.Property.NodeScope));

View File

@ -420,7 +420,7 @@ public class TransportGraphExploreAction extends HandledTransportAction<GraphExp
// weakest weights. // weakest weights.
// A priority queue is used to trim vertices according to the size settings // A priority queue is used to trim vertices according to the size settings
// requested for each field. // requested for each field.
private final void trimNewAdditions(Hop currentHop, ArrayList<Connection> newConnections, ArrayList<Vertex> newVertices) { private void trimNewAdditions(Hop currentHop, ArrayList<Connection> newConnections, ArrayList<Vertex> newVertices) {
Set<Vertex> evictions = new HashSet<>(); Set<Vertex> evictions = new HashSet<>();
for (int k = 0; k < currentHop.getNumberVertexRequests(); k++) { for (int k = 0; k < currentHop.getNumberVertexRequests(); k++) {
@ -460,7 +460,7 @@ public class TransportGraphExploreAction extends HandledTransportAction<GraphExp
// we can do something server-side here // we can do something server-side here
// Helper method - compute the total signal of all scores in the search results // Helper method - compute the total signal of all scores in the search results
private final double getExpandTotalSignalStrength(Hop lastHop, Hop currentHop, Sampler sample) { private double getExpandTotalSignalStrength(Hop lastHop, Hop currentHop, Sampler sample) {
double totalSignalOutput = 0; double totalSignalOutput = 0;
for (int j = 0; j < lastHop.getNumberVertexRequests(); j++) { for (int j = 0; j < lastHop.getNumberVertexRequests(); j++) {
VertexRequest lastVr = lastHop.getVertexRequest(j); VertexRequest lastVr = lastHop.getVertexRequest(j);
@ -509,7 +509,7 @@ public class TransportGraphExploreAction extends HandledTransportAction<GraphExp
} }
@Override @Override
public void onFailure(Throwable e) { public void onFailure(Exception e) {
listener.onFailure(e); listener.onFailure(e);
} }
}); });
@ -688,7 +688,7 @@ public class TransportGraphExploreAction extends HandledTransportAction<GraphExp
} }
// Helper method - Provides a total signal strength for all terms connected to the initial query // Helper method - Provides a total signal strength for all terms connected to the initial query
private final double getInitialTotalSignalStrength(Hop rootHop, Sampler sample) { private double getInitialTotalSignalStrength(Hop rootHop, Sampler sample) {
double totalSignalStrength = 0; double totalSignalStrength = 0;
for (int i = 0; i < rootHop.getNumberVertexRequests(); i++) { for (int i = 0; i < rootHop.getNumberVertexRequests(); i++) {
if (request.useSignificance()) { if (request.useSignificance()) {
@ -711,13 +711,13 @@ public class TransportGraphExploreAction extends HandledTransportAction<GraphExp
} }
@Override @Override
public void onFailure(Throwable e) { public void onFailure(Exception e) {
listener.onFailure(e); listener.onFailure(e);
} }
}); });
} catch (Throwable t) { } catch (Exception e) {
logger.error("unable to execute the graph query", t); logger.error("unable to execute the graph query", e);
listener.onFailure(t); listener.onFailure(e);
} }
} }

View File

@ -16,7 +16,7 @@ import java.util.Map;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
@ -66,8 +66,8 @@ public class RestGraphAction extends BaseRestHandler {
public static final ParseField TERM_FIELD = new ParseField("term"); public static final ParseField TERM_FIELD = new ParseField("term");
@Inject @Inject
public RestGraphAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { public RestGraphAction(Settings settings, RestController controller, IndicesQueriesRegistry indicesQueriesRegistry) {
super(settings, client); super(settings);
// @deprecated TODO need to add deprecation support as per https://github.com/elastic/x-plugins/issues/1760#issuecomment-217507517 // @deprecated TODO need to add deprecation support as per https://github.com/elastic/x-plugins/issues/1760#issuecomment-217507517
controller.registerHandler(GET, "/{index}/_graph/explore", this); controller.registerHandler(GET, "/{index}/_graph/explore", this);
controller.registerHandler(POST, "/{index}/_graph/explore", this); controller.registerHandler(POST, "/{index}/_graph/explore", this);
@ -82,7 +82,7 @@ public class RestGraphAction extends BaseRestHandler {
} }
@Override @Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws IOException { public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) throws IOException {
GraphExploreRequest graphRequest = new GraphExploreRequest(Strings.splitStringByCommaToArray(request.param("index"))); GraphExploreRequest graphRequest = new GraphExploreRequest(Strings.splitStringByCommaToArray(request.param("index")));
graphRequest.indicesOptions(IndicesOptions.fromRequest(request, graphRequest.indicesOptions())); graphRequest.indicesOptions(IndicesOptions.fromRequest(request, graphRequest.indicesOptions()));
graphRequest.routing(request.param("routing")); graphRequest.routing(request.param("routing"));

View File

@ -13,14 +13,13 @@ import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.ScriptQueryBuilder; import org.elasticsearch.index.query.ScriptQueryBuilder;
import org.elasticsearch.marvel.Monitoring; import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin; import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.AbstractSearchScript; import org.elasticsearch.script.AbstractSearchScript;
import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.NativeScriptFactory; import org.elasticsearch.script.NativeScriptFactory;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.ESSingleNodeTestCase;
@ -271,11 +270,10 @@ public class GraphTests extends ESSingleNodeTestCase {
try { try {
GraphExploreResponse response = grb.get(); GraphExploreResponse response = grb.get();
if (response.getShardFailures().length > 0) { if (response.getShardFailures().length > 0) {
throw ((ShardSearchFailure) response.getShardFailures()[0]).getCause(); expectedError = response.getShardFailures()[0].getCause();
} }
} catch (Throwable rte) { } catch (Exception rte) {
expectedError = rte; expectedError = rte;
} }
assertNotNull(expectedError); assertNotNull(expectedError);
String message = expectedError.toString(); String message = expectedError.toString();

View File

@ -11,7 +11,6 @@ import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.license.plugin.action.delete.DeleteLicenseAction; import org.elasticsearch.license.plugin.action.delete.DeleteLicenseAction;
@ -26,6 +25,7 @@ import org.elasticsearch.license.plugin.rest.RestDeleteLicenseAction;
import org.elasticsearch.license.plugin.rest.RestGetLicenseAction; import org.elasticsearch.license.plugin.rest.RestGetLicenseAction;
import org.elasticsearch.license.plugin.rest.RestPutLicenseAction; import org.elasticsearch.license.plugin.rest.RestPutLicenseAction;
import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.rest.RestHandler;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -53,14 +53,6 @@ public class Licensing implements ActionPlugin {
isTribeNode = isTribeNode(settings); isTribeNode = isTribeNode(settings);
} }
public void onModule(NetworkModule module) {
if (isTransportClient == false && isTribeNode == false) {
module.registerRestHandler(RestPutLicenseAction.class);
module.registerRestHandler(RestGetLicenseAction.class);
module.registerRestHandler(RestDeleteLicenseAction.class);
}
}
@Override @Override
public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
if (isTribeNode) { if (isTribeNode) {
@ -71,6 +63,16 @@ public class Licensing implements ActionPlugin {
new ActionHandler<>(DeleteLicenseAction.INSTANCE, TransportDeleteLicenseAction.class)); new ActionHandler<>(DeleteLicenseAction.INSTANCE, TransportDeleteLicenseAction.class));
} }
@Override
public List<Class<? extends RestHandler>> getRestHandlers() {
if (isTribeNode) {
return emptyList();
}
return Arrays.asList(RestPutLicenseAction.class,
RestGetLicenseAction.class,
RestDeleteLicenseAction.class);
}
public Collection<Class<? extends LifecycleComponent>> nodeServices() { public Collection<Class<? extends LifecycleComponent>> nodeServices() {
if (isTransportClient == false && isTribeNode == false) { if (isTransportClient == false && isTribeNode == false) {
return Collections.<Class<? extends LifecycleComponent>>singletonList(LicensesService.class); return Collections.<Class<? extends LifecycleComponent>>singletonList(LicensesService.class);

View File

@ -59,7 +59,7 @@ public class TransportDeleteLicenseAction extends TransportMasterNodeAction<Dele
} }
@Override @Override
public void onFailure(Throwable e) { public void onFailure(Exception e) {
listener.onFailure(e); listener.onFailure(e);
} }
}); });

View File

@ -14,7 +14,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* A supporting base class for injectable Licensee components. * A supporting base class for injectable Licensee components.
*/ */
public abstract class AbstractLicenseeComponent<T extends AbstractLicenseeComponent<T>> extends AbstractLifecycleComponent<T> public abstract class AbstractLicenseeComponent<T extends AbstractLicenseeComponent<T>> extends AbstractLifecycleComponent
implements Licensee { implements Licensee {
private final String id; private final String id;

View File

@ -18,7 +18,7 @@ public abstract class ExpirationCallback {
public enum Orientation {PRE, POST} public enum Orientation {PRE, POST}
public static abstract class Pre extends ExpirationCallback { public abstract static class Pre extends ExpirationCallback {
/** /**
* Callback schedule prior to license expiry * Callback schedule prior to license expiry
@ -48,7 +48,7 @@ public abstract class ExpirationCallback {
} }
} }
public static abstract class Post extends ExpirationCallback { public abstract static class Post extends ExpirationCallback {
/** /**
* Callback schedule after license expiry * Callback schedule after license expiry

View File

@ -10,7 +10,7 @@ import org.elasticsearch.rest.RestStatus;
public class LicenseUtils { public class LicenseUtils {
public final static String EXPIRED_FEATURE_HEADER = "es.license.expired.feature"; public static final String EXPIRED_FEATURE_HEADER = "es.license.expired.feature";
/** /**
* Exception to be thrown when a feature action requires a valid license, but license * Exception to be thrown when a feature action requires a valid license, but license
@ -21,7 +21,7 @@ public class LicenseUtils {
*/ */
public static ElasticsearchSecurityException newComplianceException(String feature) { public static ElasticsearchSecurityException newComplianceException(String feature) {
ElasticsearchSecurityException e = new ElasticsearchSecurityException("current license is non-compliant for [{}]", ElasticsearchSecurityException e = new ElasticsearchSecurityException("current license is non-compliant for [{}]",
RestStatus.UNAUTHORIZED, feature); RestStatus.FORBIDDEN, feature);
e.addHeader(EXPIRED_FEATURE_HEADER, feature); e.addHeader(EXPIRED_FEATURE_HEADER, feature);
return e; return e;
} }

View File

@ -9,6 +9,7 @@ import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.cluster.AbstractDiffable; import org.elasticsearch.cluster.AbstractDiffable;
import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
@ -186,7 +187,7 @@ public class LicensesMetaData extends AbstractDiffable<MetaData.Custom> implemen
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
license.toXContent(contentBuilder, license.toXContent(contentBuilder,
new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
streamOutput.writeString(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes()))); streamOutput.writeString(Base64.getEncoder().encodeToString(encrypt(BytesReference.toBytes(contentBuilder.bytes()))));
} }
} else { } else {
if (license == LICENSE_TOMBSTONE) { if (license == LICENSE_TOMBSTONE) {
@ -238,7 +239,7 @@ public class LicensesMetaData extends AbstractDiffable<MetaData.Custom> implemen
return new LicensesMetaData(license); return new LicensesMetaData(license);
} }
private final static class Fields { private static final class Fields {
private static final String SIGNED_LICENCES = "signed_licenses"; private static final String SIGNED_LICENCES = "signed_licenses";
private static final String TRIAL_LICENSES = "trial_licenses"; private static final String TRIAL_LICENSES = "trial_licenses";
private static final String LICENSE = "license"; private static final String LICENSE = "license";

View File

@ -77,7 +77,7 @@ import java.util.concurrent.atomic.AtomicReference;
* Registered listeners are notified using {@link #onUpdate(LicensesMetaData)} * Registered listeners are notified using {@link #onUpdate(LicensesMetaData)}
*/ */
@Singleton @Singleton
public class LicensesService extends AbstractLifecycleComponent<LicensesService> implements ClusterStateListener, LicensesManagerService, public class LicensesService extends AbstractLifecycleComponent implements ClusterStateListener, LicensesManagerService,
LicenseeRegistry, SchedulerEngine.Listener { LicenseeRegistry, SchedulerEngine.Listener {
public static final String REGISTER_TRIAL_LICENSE_ACTION_NAME = "internal:plugin/license/cluster/register_trial_license"; public static final String REGISTER_TRIAL_LICENSE_ACTION_NAME = "internal:plugin/license/cluster/register_trial_license";
@ -404,8 +404,8 @@ public class LicensesService extends AbstractLifecycleComponent<LicensesService>
} }
@Override @Override
public void onFailure(String source, @Nullable Throwable t) { public void onFailure(String source, @Nullable Exception e) {
logger.error("unexpected failure during [{}]", t, source); logger.error("unexpected failure during [{}]", e, source);
} }
}); });

View File

@ -5,6 +5,7 @@
*/ */
package org.elasticsearch.license.plugin.core; package org.elasticsearch.license.plugin.core;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
@ -32,7 +33,7 @@ public class TrialLicense {
try { try {
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
spec.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); spec.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
byte[] encrypt = encrypt(contentBuilder.bytes().toBytes()); byte[] encrypt = encrypt(BytesReference.toBytes(contentBuilder.bytes()));
byte[] bytes = new byte[4 + 4 + encrypt.length]; byte[] bytes = new byte[4 + 4 + encrypt.length];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
// always generate license version -VERSION_CURRENT // always generate license version -VERSION_CURRENT

View File

@ -5,7 +5,7 @@
*/ */
package org.elasticsearch.license.plugin.rest; package org.elasticsearch.license.plugin.rest;
import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.license.plugin.action.delete.DeleteLicenseAction; import org.elasticsearch.license.plugin.action.delete.DeleteLicenseAction;
@ -21,13 +21,13 @@ import static org.elasticsearch.rest.RestRequest.Method.DELETE;
public class RestDeleteLicenseAction extends BaseRestHandler { public class RestDeleteLicenseAction extends BaseRestHandler {
@Inject @Inject
public RestDeleteLicenseAction(Settings settings, RestController controller, Client client) { public RestDeleteLicenseAction(Settings settings, RestController controller) {
super(settings, client); super(settings);
controller.registerHandler(DELETE, "/_xpack/license", this); controller.registerHandler(DELETE, "/_xpack/license", this);
} }
@Override @Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) {
client.admin().cluster().execute(DeleteLicenseAction.INSTANCE, new DeleteLicenseRequest(), new AcknowledgedRestListener<>(channel)); client.admin().cluster().execute(DeleteLicenseAction.INSTANCE, new DeleteLicenseRequest(), new AcknowledgedRestListener<>(channel));
} }
} }

View File

@ -5,7 +5,7 @@
*/ */
package org.elasticsearch.license.plugin.rest; package org.elasticsearch.license.plugin.rest;
import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
@ -32,8 +32,8 @@ import static org.elasticsearch.rest.RestStatus.OK;
public class RestGetLicenseAction extends BaseRestHandler { public class RestGetLicenseAction extends BaseRestHandler {
@Inject @Inject
public RestGetLicenseAction(Settings settings, RestController controller, Client client) { public RestGetLicenseAction(Settings settings, RestController controller) {
super(settings, client); super(settings);
controller.registerHandler(GET, "/_xpack/license", this); controller.registerHandler(GET, "/_xpack/license", this);
} }
@ -44,7 +44,7 @@ public class RestGetLicenseAction extends BaseRestHandler {
* The licenses are sorted by latest issue_date * The licenses are sorted by latest issue_date
*/ */
@Override @Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) {
final Map<String, String> overrideParams = new HashMap<>(2); final Map<String, String> overrideParams = new HashMap<>(2);
overrideParams.put(License.REST_VIEW_MODE, "true"); overrideParams.put(License.REST_VIEW_MODE, "true");
overrideParams.put(License.LICENSE_VERSION_MODE, String.valueOf(License.VERSION_CURRENT)); overrideParams.put(License.LICENSE_VERSION_MODE, String.valueOf(License.VERSION_CURRENT));

View File

@ -5,7 +5,7 @@
*/ */
package org.elasticsearch.license.plugin.rest; package org.elasticsearch.license.plugin.rest;
import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
@ -28,16 +28,16 @@ import static org.elasticsearch.rest.RestRequest.Method.PUT;
public class RestPutLicenseAction extends BaseRestHandler { public class RestPutLicenseAction extends BaseRestHandler {
@Inject @Inject
public RestPutLicenseAction(Settings settings, RestController controller, Client client) { public RestPutLicenseAction(Settings settings, RestController controller) {
super(settings, client); super(settings);
controller.registerHandler(PUT, "/_xpack/license", this); controller.registerHandler(PUT, "/_xpack/license", this);
controller.registerHandler(POST, "/_xpack/license", this); controller.registerHandler(POST, "/_xpack/license", this);
} }
@Override @Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client) {
PutLicenseRequest putLicenseRequest = new PutLicenseRequest(); PutLicenseRequest putLicenseRequest = new PutLicenseRequest();
putLicenseRequest.license(request.content().toUtf8()); putLicenseRequest.license(request.content().utf8ToString());
putLicenseRequest.acknowledge(request.paramAsBoolean("acknowledge", false)); putLicenseRequest.acknowledge(request.paramAsBoolean("acknowledge", false));
client.admin().cluster().execute(PutLicenseAction.INSTANCE, putLicenseRequest, client.admin().cluster().execute(PutLicenseAction.INSTANCE, putLicenseRequest,
new RestBuilderListener<PutLicenseResponse>(channel) { new RestBuilderListener<PutLicenseResponse>(channel) {

View File

@ -23,7 +23,7 @@ import org.elasticsearch.license.plugin.core.LicenseState;
import org.elasticsearch.license.plugin.core.LicensesManagerService; import org.elasticsearch.license.plugin.core.LicensesManagerService;
import org.elasticsearch.license.plugin.core.LicensesMetaData; import org.elasticsearch.license.plugin.core.LicensesMetaData;
import org.elasticsearch.license.plugin.core.LicensesStatus; import org.elasticsearch.license.plugin.core.LicensesStatus;
import org.elasticsearch.marvel.Monitoring; import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase;
@ -88,8 +88,8 @@ public abstract class AbstractLicensesIntegrationTestCase extends ESIntegTestCas
} }
@Override @Override
public void onFailure(String source, @Nullable Throwable t) { public void onFailure(String source, @Nullable Exception e) {
logger.error("error on metaData cleanup after test", t); logger.error("error on metaData cleanup after test", e);
} }
}); });
latch.await(); latch.await();

View File

@ -19,7 +19,7 @@ import org.elasticsearch.license.plugin.action.put.PutLicenseAction;
import org.elasticsearch.license.plugin.action.put.PutLicenseRequestBuilder; import org.elasticsearch.license.plugin.action.put.PutLicenseRequestBuilder;
import org.elasticsearch.license.plugin.action.put.PutLicenseResponse; import org.elasticsearch.license.plugin.action.put.PutLicenseResponse;
import org.elasticsearch.license.plugin.core.LicensesStatus; import org.elasticsearch.license.plugin.core.LicensesStatus;
import org.elasticsearch.marvel.Monitoring; import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;

View File

@ -5,8 +5,8 @@
*/ */
package org.elasticsearch.license.plugin; package org.elasticsearch.license.plugin;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
@ -16,7 +16,6 @@ import org.elasticsearch.license.plugin.core.LicensesStatus;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -70,7 +69,7 @@ public class PutLicenseResponseTests extends ESTestCase {
// write it out // write it out
response.writeTo(output); response.writeTo(output);
ByteBufferStreamInput input = new ByteBufferStreamInput(ByteBuffer.wrap(output.bytes().toBytes())); StreamInput input = output.bytes().streamInput();
// read it back in // read it back in
response.readFrom(input); response.readFrom(input);

View File

@ -50,8 +50,8 @@ import static org.junit.Assert.assertThat;
public class TestUtils { public class TestUtils {
private final static FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd"); private static final FormatDateTimeFormatter formatDateTimeFormatter = Joda.forPattern("yyyy-MM-dd");
private final static DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter); private static final DateMathParser dateMathParser = new DateMathParser(formatDateTimeFormatter);
public static long dateMath(String time, final long now) { public static long dateMath(String time, final long now) {
return dateMathParser.parse(time, new Callable<Long>() { return dateMathParser.parse(time, new Callable<Long>() {
@ -162,7 +162,7 @@ public class TestUtils {
} }
@Override @Override
public void onFailure(Throwable e) { public void onFailure(Exception e) {
latch.countDown(); latch.countDown();
} }
}); });

View File

@ -5,6 +5,7 @@
*/ */
package org.elasticsearch.license.plugin; package org.elasticsearch.license.plugin;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
@ -96,7 +97,7 @@ public class TrialLicenseTests extends ESTestCase {
try { try {
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
spec.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); spec.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
byte[] encrypt = encrypt(contentBuilder.bytes().toBytes()); byte[] encrypt = encrypt(BytesReference.toBytes(contentBuilder.bytes()));
byte[] bytes = new byte[4 + 4 + encrypt.length]; byte[] bytes = new byte[4 + 4 + encrypt.length];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.putInt(-spec.version()) byteBuffer.putInt(-spec.version())

View File

@ -16,7 +16,7 @@ import org.elasticsearch.common.settings.Settings;
*/ */
public class EagerLicenseRegistrationConsumerPlugin extends TestConsumerPluginBase { public class EagerLicenseRegistrationConsumerPlugin extends TestConsumerPluginBase {
public final static String NAME = "test_consumer_plugin_1"; public static final String NAME = "test_consumer_plugin_1";
@Inject @Inject
public EagerLicenseRegistrationConsumerPlugin(Settings settings) { public EagerLicenseRegistrationConsumerPlugin(Settings settings) {

View File

@ -21,7 +21,7 @@ import org.elasticsearch.license.plugin.core.LicensesService;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
public abstract class TestPluginServiceBase extends AbstractLifecycleComponent<TestPluginServiceBase> public abstract class TestPluginServiceBase extends AbstractLifecycleComponent
implements ClusterStateListener, Licensee { implements ClusterStateListener, Licensee {
private LicensesService licensesClientService; private LicensesService licensesClientService;

View File

@ -122,7 +122,7 @@ public class LicensesAcknowledgementTests extends AbstractLicenseServiceTestCase
} }
@Override @Override
public void onFailure(Throwable throwable) { public void onFailure(Exception throwable) {
} }
} }
} }

View File

@ -9,8 +9,9 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.RepositoriesMetaData; import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
import org.elasticsearch.cluster.metadata.RepositoryMetaData; import org.elasticsearch.cluster.metadata.RepositoryMetaData;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
@ -24,7 +25,6 @@ import org.elasticsearch.license.plugin.Licensing;
import org.elasticsearch.license.plugin.TestUtils; import org.elasticsearch.license.plugin.TestUtils;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import java.nio.ByteBuffer;
import java.util.Base64; import java.util.Base64;
import java.util.Collections; import java.util.Collections;
import java.util.UUID; import java.util.UUID;
@ -42,9 +42,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startObject("licenses"); builder.startObject("licenses");
licensesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS); licensesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
byte[] serializedBytes = builder.bytes().toBytes(); LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(serializedBytes);
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(license)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(license));
} }
@ -90,9 +88,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startObject("licenses"); builder.startObject("licenses");
licensesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS); licensesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject(); builder.endObject();
byte[] serializedBytes = builder.bytes().toBytes(); LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(serializedBytes);
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(trialLicense)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(trialLicense));
} }
@ -113,13 +109,13 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses"); builder.startArray("trial_licenses");
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes()))); builder.value(Base64.getEncoder().encodeToString(encrypt(BytesReference.toBytes(contentBuilder.bytes()))));
builder.endArray(); builder.endArray();
builder.startArray("signed_licenses"); builder.startArray("signed_licenses");
builder.endArray(); builder.endArray();
builder.endObject(); builder.endObject();
builder.endObject(); builder.endObject();
LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes().toBytes()); LicensesMetaData licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(trialLicense)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(trialLicense));
// signed license // signed license
@ -133,7 +129,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.endArray(); builder.endArray();
builder.endObject(); builder.endObject();
builder.endObject(); builder.endObject();
licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes().toBytes()); licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicense)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicense));
// trial and signed license // trial and signed license
@ -143,14 +139,14 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses"); builder.startArray("trial_licenses");
contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes()))); builder.value(Base64.getEncoder().encodeToString(encrypt(BytesReference.toBytes(contentBuilder.bytes()))));
builder.endArray(); builder.endArray();
builder.startArray("signed_licenses"); builder.startArray("signed_licenses");
signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS); signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endArray(); builder.endArray();
builder.endObject(); builder.endObject();
builder.endObject(); builder.endObject();
licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes().toBytes()); licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicense)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicense));
// license with later issue date is selected // license with later issue date is selected
@ -162,7 +158,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses"); builder.startArray("trial_licenses");
contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes()))); builder.value(Base64.getEncoder().encodeToString(encrypt(BytesReference.toBytes(contentBuilder.bytes()))));
builder.endArray(); builder.endArray();
builder.startArray("signed_licenses"); builder.startArray("signed_licenses");
signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS); signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS);
@ -170,7 +166,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.endArray(); builder.endArray();
builder.endObject(); builder.endObject();
builder.endObject(); builder.endObject();
licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes().toBytes()); licensesMetaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicenseIssuedLater)); assertThat(licensesMetaDataFromXContent.getLicense(), equalTo(signedLicenseIssuedLater));
} }
@ -190,13 +186,12 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
output.writeVInt(1); output.writeVInt(1);
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON); XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true"))); trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
output.writeString(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes()))); output.writeString(Base64.getEncoder().encodeToString(encrypt(BytesReference.toBytes(contentBuilder.bytes()))));
byte[] bytes = output.bytes().toBytes(); try (StreamInput input = output.bytes().streamInput()) {
ByteBufferStreamInput input = new ByteBufferStreamInput(ByteBuffer.wrap(bytes)); input.setVersion(Version.V_2_0_0_beta1);
LicensesMetaData licensesMetaData = LicensesMetaData.PROTO.readFrom(input);
input.setVersion(Version.V_2_0_0_beta1); assertThat(licensesMetaData.getLicense(), equalTo(trialLicense));
LicensesMetaData licensesMetaData = LicensesMetaData.PROTO.readFrom(input); }
assertThat(licensesMetaData.getLicense(), equalTo(trialLicense));
// signed license // signed license
License signedLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(2)); License signedLicense = TestUtils.generateSignedLicense(TimeValue.timeValueHours(2));
@ -204,11 +199,11 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
output.writeVInt(1); output.writeVInt(1);
signedLicense.writeTo(output); signedLicense.writeTo(output);
output.writeVInt(0); output.writeVInt(0);
bytes = output.bytes().toBytes(); try (StreamInput input = output.bytes().streamInput()) {
input = new ByteBufferStreamInput(ByteBuffer.wrap(bytes)); input.setVersion(Version.V_2_0_0_beta1);
input.setVersion(Version.V_2_0_0_beta1); LicensesMetaData licensesMetaData = LicensesMetaData.PROTO.readFrom(input);
licensesMetaData = LicensesMetaData.PROTO.readFrom(input); assertThat(licensesMetaData.getLicense(), equalTo(signedLicense));
assertThat(licensesMetaData.getLicense(), equalTo(signedLicense)); }
} }
public void testLicenseTombstoneFromXContext() throws Exception { public void testLicenseTombstoneFromXContext() throws Exception {
@ -216,11 +211,11 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startObject("licenses"); builder.startObject("licenses");
builder.nullField("license"); builder.nullField("license");
builder.endObject(); builder.endObject();
LicensesMetaData metaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes().toBytes()); LicensesMetaData metaDataFromXContent = getLicensesMetaDataFromXContent(builder.bytes());
assertThat(metaDataFromXContent.getLicense(), equalTo(LicensesMetaData.LICENSE_TOMBSTONE)); assertThat(metaDataFromXContent.getLicense(), equalTo(LicensesMetaData.LICENSE_TOMBSTONE));
} }
private static LicensesMetaData getLicensesMetaDataFromXContent(byte[] bytes) throws Exception { private static LicensesMetaData getLicensesMetaDataFromXContent(BytesReference bytes) throws Exception {
final XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(bytes); final XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(bytes);
parser.nextToken(); // consume null parser.nextToken(); // consume null
parser.nextToken(); // consume "licenses" parser.nextToken(); // consume "licenses"

View File

@ -20,7 +20,7 @@ import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing; import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing;
import org.elasticsearch.marvel.Monitoring; import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import java.util.Locale; import java.util.Locale;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.ActionResponse;
@ -11,15 +11,17 @@ import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.action.MonitoringBulkAction; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.marvel.action.TransportMonitoringBulkAction; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkAction;
import org.elasticsearch.marvel.agent.AgentService; import org.elasticsearch.xpack.monitoring.action.TransportMonitoringBulkAction;
import org.elasticsearch.marvel.agent.collector.CollectorModule; import org.elasticsearch.xpack.monitoring.agent.AgentService;
import org.elasticsearch.marvel.agent.exporter.ExporterModule; import org.elasticsearch.xpack.monitoring.agent.collector.CollectorModule;
import org.elasticsearch.marvel.cleaner.CleanerService; import org.elasticsearch.xpack.monitoring.agent.exporter.ExporterModule;
import org.elasticsearch.marvel.client.MonitoringClientModule; import org.elasticsearch.xpack.monitoring.cleaner.CleanerService;
import org.elasticsearch.marvel.rest.action.RestMonitoringBulkAction; import org.elasticsearch.xpack.monitoring.client.MonitoringClientModule;
import org.elasticsearch.xpack.monitoring.rest.action.RestMonitoringBulkAction;
import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.ActionPlugin;
import org.elasticsearch.rest.RestHandler;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import java.util.ArrayList; import java.util.ArrayList;
@ -83,16 +85,18 @@ public class Monitoring implements ActionPlugin {
@Override @Override
public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() { public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
if (enabled && tribeNode == false) { if (false == enabled || tribeNode) {
return singletonList(new ActionHandler<>(MonitoringBulkAction.INSTANCE, TransportMonitoringBulkAction.class)); return emptyList();
} }
return emptyList(); return singletonList(new ActionHandler<>(MonitoringBulkAction.INSTANCE, TransportMonitoringBulkAction.class));
} }
public void onModule(NetworkModule module) { @Override
if (enabled && transportClientMode == false && tribeNode == false) { public List<Class<? extends RestHandler>> getRestHandlers() {
module.registerRestHandler(RestMonitoringBulkAction.class); if (false == enabled || tribeNode) {
return emptyList();
} }
return singletonList(RestMonitoringBulkAction.class);
} }
public static boolean enabled(Settings settings) { public static boolean enabled(Settings settings) {

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
@ -12,9 +12,9 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.marvel.agent.exporter.Exporter;
import org.elasticsearch.marvel.agent.exporter.Exporters;
import org.elasticsearch.xpack.XPackFeatureSet; import org.elasticsearch.xpack.XPackFeatureSet;
import org.elasticsearch.xpack.monitoring.agent.exporter.Exporter;
import org.elasticsearch.xpack.monitoring.agent.exporter.Exporters;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
@ -82,7 +82,7 @@ public class MonitoringFeatureSet implements XPackFeatureSet {
private static final String ENABLED_EXPORTERS_XFIELD = "enabled_exporters"; private static final String ENABLED_EXPORTERS_XFIELD = "enabled_exporters";
private @Nullable Map<String, Object> exporters; @Nullable private Map<String, Object> exporters;
public Usage(StreamInput in) throws IOException { public Usage(StreamInput in) throws IOException {
super(in); super(in);

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
@ -17,7 +17,7 @@ import org.elasticsearch.license.plugin.core.Licensee;
import org.elasticsearch.license.plugin.core.LicenseeRegistry; import org.elasticsearch.license.plugin.core.LicenseeRegistry;
/** /**
* {@code MarvelLicensee} determines whether certain features of Monitoring are enabled or disabled. * {@code MonitoringLicensee} determines whether certain features of Monitoring are enabled or disabled.
* <p> * <p>
* Once the license expires, the agent will stop: * Once the license expires, the agent will stop:
* <ul> * <ul>

View File

@ -3,13 +3,13 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.util.Providers; import org.elasticsearch.common.inject.util.Providers;
import org.elasticsearch.marvel.agent.AgentService;
import org.elasticsearch.marvel.cleaner.CleanerService;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.monitoring.agent.AgentService;
import org.elasticsearch.xpack.monitoring.cleaner.CleanerService;
public class MonitoringModule extends AbstractModule { public class MonitoringModule extends AbstractModule {

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel; package org.elasticsearch.xpack.monitoring;
import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.component.AbstractComponent;
@ -11,7 +11,6 @@ import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
@ -43,7 +42,7 @@ public class MonitoringSettings extends AbstractComponent {
public static final Setting<Boolean> ENABLED = public static final Setting<Boolean> ENABLED =
new Setting<>(XPackPlugin.featureEnabledSetting(Monitoring.NAME), new Setting<>(XPackPlugin.featureEnabledSetting(Monitoring.NAME),
// By default, marvel is disabled on tribe nodes // By default, monitoring is disabled on tribe nodes
(s) -> String.valueOf(!XPackPlugin.isTribeNode(s) && !XPackPlugin.isTribeClientNode(s)), (s) -> String.valueOf(!XPackPlugin.isTribeNode(s) && !XPackPlugin.isTribeClientNode(s)),
Booleans::parseBooleanExact, Booleans::parseBooleanExact,

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.action.Action; import org.elasticsearch.action.Action;
import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.client.ElasticsearchClient;

View File

@ -3,12 +3,12 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.io.IOException; import java.io.IOException;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionRequestValidationException;
@ -29,7 +29,7 @@ import static org.elasticsearch.action.ValidateActions.addValidationError;
* Every monitoring document added to the request is associated to a monitoring system id and version. If this {id, version} pair is * Every monitoring document added to the request is associated to a monitoring system id and version. If this {id, version} pair is
* supported by the monitoring plugin, the monitoring documents will be indexed in a single batch using a normal bulk request. * supported by the monitoring plugin, the monitoring documents will be indexed in a single batch using a normal bulk request.
* <p> * <p>
* The monitoring {id, version} pair is used by {org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver} to resolve the index, * The monitoring {id, version} pair is used by MonitoringIndexNameResolver to resolve the index,
* type and id of the final document to be indexed. A {@link MonitoringBulkDoc} can also hold its own index/type/id values but there's no * type and id of the final document to be indexed. A {@link MonitoringBulkDoc} can also hold its own index/type/id values but there's no
* guarantee that these information will be effectively used. * guarantee that these information will be effectively used.
*/ */

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.client.ElasticsearchClient;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.ExceptionsHelper;
@ -84,7 +84,7 @@ public class MonitoringBulkResponse extends ActionResponse {
} }
Error(StreamInput in) throws IOException { Error(StreamInput in) throws IOException {
this(in.<Throwable>readThrowable()); this(in.readException());
} }
@Override @Override

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;

View File

@ -3,22 +3,22 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.action; package org.elasticsearch.xpack.monitoring.action;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction; import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.marvel.agent.exporter.Exporters;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.monitoring.agent.exporter.Exporters;
import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -114,8 +114,8 @@ public class TransportMonitoringBulkAction extends HandledTransportAction<Monito
} }
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Exception e) {
listener.onResponse(new MonitoringBulkResponse(buildTookInMillis(startTimeNanos), new MonitoringBulkResponse.Error(t))); listener.onResponse(new MonitoringBulkResponse(buildTookInMillis(startTimeNanos), new MonitoringBulkResponse.Error(e)));
} }
}); });
} }

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent; package org.elasticsearch.xpack.monitoring.agent;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.component.AbstractLifecycleComponent;
@ -16,13 +16,13 @@ import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.CollectionUtils; import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.ReleasableLock; import org.elasticsearch.common.util.concurrent.ReleasableLock;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.collector.Collector; import org.elasticsearch.xpack.monitoring.agent.collector.Collector;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStatsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStatsCollector;
import org.elasticsearch.marvel.agent.exporter.ExportException; import org.elasticsearch.xpack.monitoring.agent.exporter.ExportException;
import org.elasticsearch.marvel.agent.exporter.Exporter; import org.elasticsearch.xpack.monitoring.agent.exporter.Exporter;
import org.elasticsearch.marvel.agent.exporter.Exporters; import org.elasticsearch.xpack.monitoring.agent.exporter.Exporters;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -41,7 +41,7 @@ import java.util.concurrent.locks.ReentrantLock;
* @see #stopCollection() * @see #stopCollection()
* @see #startCollection() * @see #startCollection()
*/ */
public class AgentService extends AbstractLifecycleComponent<AgentService> { public class AgentService extends AbstractLifecycleComponent {
private volatile ExportingWorker exportingWorker; private volatile ExportingWorker exportingWorker;
@ -204,8 +204,8 @@ public class AgentService extends AbstractLifecycleComponent<AgentService> {
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.trace("interrupted"); logger.trace("interrupted");
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} catch (Throwable t) { } catch (Exception e) {
logger.error("background thread had an uncaught exception", t); logger.error("background thread had an uncaught exception", e);
} }
} }
logger.debug("worker shutdown"); logger.debug("worker shutdown");

View File

@ -3,23 +3,23 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector; package org.elasticsearch.xpack.monitoring.agent.collector;
import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoredSystem;
import org.elasticsearch.marvel.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.util.Collection; import java.util.Collection;
public abstract class AbstractCollector<T> extends AbstractLifecycleComponent<T> implements Collector<T> { public abstract class AbstractCollector extends AbstractLifecycleComponent implements Collector {
private final String name; private final String name;
@ -48,9 +48,9 @@ public abstract class AbstractCollector<T> extends AbstractLifecycleComponent<T>
} }
@Override @Override
public T start() { public void start() {
logger.debug("starting collector [{}]", name()); logger.debug("starting collector [{}]", name());
return super.start(); super.start();
} }
@Override @Override
@ -90,9 +90,9 @@ public abstract class AbstractCollector<T> extends AbstractLifecycleComponent<T>
protected abstract Collection<MonitoringDoc> doCollect() throws Exception; protected abstract Collection<MonitoringDoc> doCollect() throws Exception;
@Override @Override
public T stop() { public void stop() {
logger.debug("stopping collector [{}]", name()); logger.debug("stopping collector [{}]", name());
return super.stop(); super.stop();
} }
@Override @Override

View File

@ -3,14 +3,14 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector; package org.elasticsearch.xpack.monitoring.agent.collector;
import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.util.Collection; import java.util.Collection;
public interface Collector<T> extends LifecycleComponent<T> { public interface Collector extends LifecycleComponent {
String name(); String name();

View File

@ -3,17 +3,17 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector; package org.elasticsearch.xpack.monitoring.agent.collector;
import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.Multibinder; import org.elasticsearch.common.inject.multibindings.Multibinder;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStateCollector; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStateCollector;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStatsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStatsCollector;
import org.elasticsearch.marvel.agent.collector.indices.IndexRecoveryCollector; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndexRecoveryCollector;
import org.elasticsearch.marvel.agent.collector.indices.IndexStatsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndexStatsCollector;
import org.elasticsearch.marvel.agent.collector.indices.IndicesStatsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndicesStatsCollector;
import org.elasticsearch.marvel.agent.collector.node.NodeStatsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.node.NodeStatsCollector;
import org.elasticsearch.marvel.agent.collector.shards.ShardsCollector; import org.elasticsearch.xpack.monitoring.agent.collector.shards.ShardsCollector;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View File

@ -3,11 +3,11 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.license.core.License; import org.elasticsearch.license.core.License;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class ClusterInfoMonitoringDoc extends MonitoringDoc { public class ClusterInfoMonitoringDoc extends MonitoringDoc {

View File

@ -3,20 +3,20 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,7 +30,7 @@ import java.util.List;
* This collector runs on the master node only and collects {@link ClusterStateMonitoringDoc} document * This collector runs on the master node only and collects {@link ClusterStateMonitoringDoc} document
* at a given frequency. * at a given frequency.
*/ */
public class ClusterStateCollector extends AbstractCollector<ClusterStateCollector> { public class ClusterStateCollector extends AbstractCollector {
public static final String NAME = "cluster-state-collector"; public static final String NAME = "cluster-state-collector";
@ -72,7 +72,7 @@ public class ClusterStateCollector extends AbstractCollector<ClusterStateCollect
DiscoveryNodes nodes = clusterState.nodes(); DiscoveryNodes nodes = clusterState.nodes();
if (nodes != null) { if (nodes != null) {
for (DiscoveryNode node : nodes) { for (DiscoveryNode node : nodes) {
// Adds a document for every node in the marvel timestamped index (type "nodes") // Adds a document for every node in the monitoring timestamped index (type "nodes")
ClusterStateNodeMonitoringDoc clusterStateNodeDoc = new ClusterStateNodeMonitoringDoc(monitoringId(), monitoringVersion()); ClusterStateNodeMonitoringDoc clusterStateNodeDoc = new ClusterStateNodeMonitoringDoc(monitoringId(), monitoringVersion());
clusterStateNodeDoc.setClusterUUID(clusterUUID);; clusterStateNodeDoc.setClusterUUID(clusterUUID);;
clusterStateNodeDoc.setTimestamp(timestamp); clusterStateNodeDoc.setTimestamp(timestamp);
@ -81,7 +81,7 @@ public class ClusterStateCollector extends AbstractCollector<ClusterStateCollect
clusterStateNodeDoc.setNodeId(node.getId()); clusterStateNodeDoc.setNodeId(node.getId());
results.add(clusterStateNodeDoc); results.add(clusterStateNodeDoc);
// Adds a document for every node in the marvel data index (type "node") // Adds a document for every node in the monitoring data index (type "node")
DiscoveryNodeMonitoringDoc discoveryNodeDoc = new DiscoveryNodeMonitoringDoc(monitoringId(), monitoringVersion()); DiscoveryNodeMonitoringDoc discoveryNodeDoc = new DiscoveryNodeMonitoringDoc(monitoringId(), monitoringVersion());
discoveryNodeDoc.setClusterUUID(clusterUUID); discoveryNodeDoc.setClusterUUID(clusterUUID);
discoveryNodeDoc.setTimestamp(timestamp); discoveryNodeDoc.setTimestamp(timestamp);

View File

@ -3,11 +3,11 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class ClusterStateMonitoringDoc extends MonitoringDoc { public class ClusterStateMonitoringDoc extends MonitoringDoc {

View File

@ -3,9 +3,9 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class ClusterStateNodeMonitoringDoc extends MonitoringDoc { public class ClusterStateNodeMonitoringDoc extends MonitoringDoc {

View File

@ -3,23 +3,22 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.license.plugin.core.LicenseUtils; import org.elasticsearch.license.plugin.core.LicenseUtils;
import org.elasticsearch.license.plugin.core.LicensesManagerService; import org.elasticsearch.license.plugin.core.LicensesManagerService;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import java.util.ArrayList; import java.util.ArrayList;
@ -37,7 +36,7 @@ import java.util.List;
* document; the cluster stats are also indexed in the timestamped index in a * document; the cluster stats are also indexed in the timestamped index in a
* "cluster_stats" document. * "cluster_stats" document.
*/ */
public class ClusterStatsCollector extends AbstractCollector<ClusterStatsCollector> { public class ClusterStatsCollector extends AbstractCollector {
public static final String NAME = "cluster-stats-collector"; public static final String NAME = "cluster-stats-collector";

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class ClusterStatsMonitoringDoc extends MonitoringDoc { public class ClusterStatsMonitoringDoc extends MonitoringDoc {

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.cluster; package org.elasticsearch.xpack.monitoring.agent.collector.cluster;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class DiscoveryNodeMonitoringDoc extends MonitoringDoc { public class DiscoveryNodeMonitoringDoc extends MonitoringDoc {

View File

@ -3,20 +3,20 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse; import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;
@ -32,7 +32,7 @@ import java.util.List;
* This collector runs on the master node only and collects a {@link IndexRecoveryMonitoringDoc} document * This collector runs on the master node only and collects a {@link IndexRecoveryMonitoringDoc} document
* for every index that has on-going shard recoveries. * for every index that has on-going shard recoveries.
*/ */
public class IndexRecoveryCollector extends AbstractCollector<IndexRecoveryCollector> { public class IndexRecoveryCollector extends AbstractCollector {
public static final String NAME = "index-recovery-collector"; public static final String NAME = "index-recovery-collector";

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse; import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class IndexRecoveryMonitoringDoc extends MonitoringDoc { public class IndexRecoveryMonitoringDoc extends MonitoringDoc {

View File

@ -3,22 +3,22 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.stats.IndexStats; import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;
@ -34,7 +34,7 @@ import java.util.List;
* This collector runs on the master node only and collect a {@link IndexStatsMonitoringDoc} document * This collector runs on the master node only and collect a {@link IndexStatsMonitoringDoc} document
* for each existing index in the cluster. * for each existing index in the cluster.
*/ */
public class IndexStatsCollector extends AbstractCollector<IndexStatsCollector> { public class IndexStatsCollector extends AbstractCollector {
public static final String NAME = "index-stats-collector"; public static final String NAME = "index-stats-collector";

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.stats.IndexStats; import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class IndexStatsMonitoringDoc extends MonitoringDoc { public class IndexStatsMonitoringDoc extends MonitoringDoc {

View File

@ -3,20 +3,20 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.Security;
@ -29,7 +29,7 @@ import java.util.Collections;
* <p> * <p>
* This collector runs on the master node only and collect one {@link IndicesStatsMonitoringDoc} document. * This collector runs on the master node only and collect one {@link IndicesStatsMonitoringDoc} document.
*/ */
public class IndicesStatsCollector extends AbstractCollector<IndicesStatsCollector> { public class IndicesStatsCollector extends AbstractCollector {
public static final String NAME = "indices-stats-collector"; public static final String NAME = "indices-stats-collector";

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.indices; package org.elasticsearch.xpack.monitoring.agent.collector.indices;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class IndicesStatsMonitoringDoc extends MonitoringDoc { public class IndicesStatsMonitoringDoc extends MonitoringDoc {

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.node; package org.elasticsearch.xpack.monitoring.agent.collector.node;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest; import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest;
@ -11,16 +11,16 @@ import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags; import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags;
import org.elasticsearch.bootstrap.BootstrapInfo; import org.elasticsearch.bootstrap.BootstrapInfo;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider; import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import java.util.Collection; import java.util.Collection;
@ -32,7 +32,7 @@ import java.util.Collections;
* This collector runs on every non-client node and collect * This collector runs on every non-client node and collect
* a {@link NodeStatsMonitoringDoc} document for each node of the cluster. * a {@link NodeStatsMonitoringDoc} document for each node of the cluster.
*/ */
public class NodeStatsCollector extends AbstractCollector<NodeStatsCollector> { public class NodeStatsCollector extends AbstractCollector {
public static final String NAME = "node-stats-collector"; public static final String NAME = "node-stats-collector";

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.node; package org.elasticsearch.xpack.monitoring.agent.collector.node;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class NodeStatsMonitoringDoc extends MonitoringDoc { public class NodeStatsMonitoringDoc extends MonitoringDoc {

View File

@ -3,10 +3,10 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.shards; package org.elasticsearch.xpack.monitoring.agent.collector.shards;
import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
public class ShardMonitoringDoc extends MonitoringDoc { public class ShardMonitoringDoc extends MonitoringDoc {

View File

@ -3,20 +3,20 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.collector.shards; package org.elasticsearch.xpack.monitoring.agent.collector.shards;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringLicensee;
import org.elasticsearch.marvel.agent.collector.AbstractCollector; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.AbstractCollector;
import org.elasticsearch.marvel.MonitoringLicensee; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -30,7 +30,7 @@ import java.util.List;
* This collector runs on the master node only and collects the {@link ShardMonitoringDoc} documents * This collector runs on the master node only and collects the {@link ShardMonitoringDoc} documents
* for every index shard. * for every index shard.
*/ */
public class ShardsCollector extends AbstractCollector<ShardsCollector> { public class ShardsCollector extends AbstractCollector {
public static final String NAME = "shards-collector"; public static final String NAME = "shards-collector";

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;

View File

@ -3,14 +3,14 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -23,7 +23,8 @@ public abstract class Exporter implements AutoCloseable {
protected final Config config; protected final Config config;
protected final ESLogger logger; protected final ESLogger logger;
protected final @Nullable TimeValue bulkTimeout; @Nullable protected final TimeValue bulkTimeout;
private AtomicBoolean closed = new AtomicBoolean(false); private AtomicBoolean closed = new AtomicBoolean(false);
public Exporter(String type, Config config) { public Exporter(String type, Config config) {
@ -103,7 +104,7 @@ public abstract class Exporter implements AutoCloseable {
} }
} }
public static abstract class Factory<E extends Exporter> { public abstract static class Factory<E extends Exporter> {
private final String type; private final String type;
private final boolean singleton; private final boolean singleton;

View File

@ -3,16 +3,16 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.multibindings.MapBinder; import org.elasticsearch.common.inject.multibindings.MapBinder;
import org.elasticsearch.common.inject.util.Providers; import org.elasticsearch.common.inject.util.Providers;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.Monitoring;
import org.elasticsearch.marvel.agent.exporter.http.HttpExporter;
import org.elasticsearch.marvel.agent.exporter.local.LocalExporter;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.monitoring.Monitoring;
import org.elasticsearch.xpack.monitoring.agent.exporter.http.HttpExporter;
import org.elasticsearch.xpack.monitoring.agent.exporter.local.LocalExporter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.component.AbstractLifecycleComponent;
@ -13,9 +13,9 @@ import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.marvel.MonitoringSettings;
import org.elasticsearch.marvel.agent.exporter.local.LocalExporter;
import org.elasticsearch.node.Node; import org.elasticsearch.node.Node;
import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.xpack.monitoring.agent.exporter.local.LocalExporter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -32,7 +32,7 @@ import static java.util.Collections.emptyMap;
/** /**
* *
*/ */
public class Exporters extends AbstractLifecycleComponent<Exporters> implements Iterable<Exporter> { public class Exporters extends AbstractLifecycleComponent implements Iterable<Exporter> {
private final Map<String, Exporter.Factory> factories; private final Map<String, Exporter.Factory> factories;
private final ClusterService clusterService; private final ClusterService clusterService;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;

View File

@ -3,14 +3,14 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter; package org.elasticsearch.xpack.monitoring.agent.exporter;
import org.elasticsearch.xpack.template.TemplateUtils; import org.elasticsearch.xpack.template.TemplateUtils;
import java.util.Locale; import java.util.Locale;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public final class MarvelTemplateUtils { public final class MonitoringTemplateUtils {
private static final String TEMPLATE_FILE = "/monitoring-%s.json"; private static final String TEMPLATE_FILE = "/monitoring-%s.json";
private static final String TEMPLATE_VERSION_PROPERTY = Pattern.quote("${monitoring.template.version}"); private static final String TEMPLATE_VERSION_PROPERTY = Pattern.quote("${monitoring.template.version}");
@ -18,7 +18,7 @@ public final class MarvelTemplateUtils {
/** Current version of es and data templates **/ /** Current version of es and data templates **/
public static final Integer TEMPLATE_VERSION = 2; public static final Integer TEMPLATE_VERSION = 2;
private MarvelTemplateUtils() { private MonitoringTemplateUtils() {
} }
public static String loadTemplate(String id) { public static String loadTemplate(String id) {

View File

@ -3,8 +3,9 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter.http; package org.elasticsearch.xpack.monitoring.agent.exporter.http;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.SpecialPermission; import org.elasticsearch.SpecialPermission;
@ -21,13 +22,13 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment; import org.elasticsearch.env.Environment;
import org.elasticsearch.marvel.agent.exporter.ExportBulk; import org.elasticsearch.xpack.monitoring.agent.exporter.ExportBulk;
import org.elasticsearch.marvel.agent.exporter.ExportException; import org.elasticsearch.xpack.monitoring.agent.exporter.ExportException;
import org.elasticsearch.marvel.agent.exporter.Exporter; import org.elasticsearch.xpack.monitoring.agent.exporter.Exporter;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.marvel.agent.resolver.ResolversRegistry; import org.elasticsearch.xpack.monitoring.agent.resolver.ResolversRegistry;
import org.elasticsearch.marvel.support.VersionUtils; import org.elasticsearch.xpack.monitoring.support.VersionUtils;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
@ -58,9 +59,6 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
/**
*
*/
public class HttpExporter extends Exporter { public class HttpExporter extends Exporter {
public static final String TYPE = "http"; public static final String TYPE = "http";
@ -216,7 +214,8 @@ public class HttpExporter extends Exporter {
out.write(CONTENT_TYPE.xContent().streamSeparator()); out.write(CONTENT_TYPE.xContent().streamSeparator());
// Render the monitoring document // Render the monitoring document
out.write(resolver.source(doc, CONTENT_TYPE).toBytes()); BytesRef bytesRef = resolver.source(doc, CONTENT_TYPE).toBytesRef();
out.write(bytesRef.bytes, bytesRef.offset, bytesRef.length);
// Adds final bulk separator // Adds final bulk separator
out.write(CONTENT_TYPE.xContent().streamSeparator()); out.write(CONTENT_TYPE.xContent().streamSeparator());
@ -533,7 +532,7 @@ public class HttpExporter extends Exporter {
} }
} }
static private void validateHosts(String[] hosts) { private static void validateHosts(String[] hosts) {
for (String host : hosts) { for (String host : hosts) {
try { try {
HttpExporterUtils.parseHostWithPath(host, ""); HttpExporterUtils.parseHostWithPath(host, "");
@ -662,9 +661,9 @@ public class HttpExporter extends Exporter {
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
// ignore, if closed, good.... // ignore, if closed, good....
} catch (Throwable t) { } catch (Exception e) {
logger.debug("error in keep alive thread, shutting down (will be restarted after a successful connection has been " + logger.debug("error in keep alive thread, shutting down (will be restarted after a successful connection has been " +
"made) {}", ExceptionsHelper.detailedMessage(t)); "made) {}", ExceptionsHelper.detailedMessage(e));
return; return;
} }
} }
@ -718,8 +717,9 @@ public class HttpExporter extends Exporter {
for (MonitoringDoc monitoringDoc : docs) { for (MonitoringDoc monitoringDoc : docs) {
try { try {
render(monitoringDoc, buffer); render(monitoringDoc, buffer);
BytesRef bytesRef = buffer.bytes().toBytesRef();
// write the result to the connection // write the result to the connection
out.write(buffer.bytes().toBytes()); out.write(bytesRef.bytes, bytesRef.offset, bytesRef.length);
} finally { } finally {
buffer.reset(); buffer.reset();
} }

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter.http; package org.elasticsearch.xpack.monitoring.agent.exporter.http;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URISyntaxException; import java.net.URISyntaxException;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter.local; package org.elasticsearch.xpack.monitoring.agent.exporter.local;
import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkRequestBuilder;
@ -11,12 +11,12 @@ import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.marvel.agent.exporter.ExportBulk;
import org.elasticsearch.marvel.agent.exporter.ExportException;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.marvel.agent.resolver.ResolversRegistry;
import org.elasticsearch.xpack.common.init.proxy.ClientProxy; import org.elasticsearch.xpack.common.init.proxy.ClientProxy;
import org.elasticsearch.xpack.monitoring.agent.exporter.ExportBulk;
import org.elasticsearch.xpack.monitoring.agent.exporter.ExportException;
import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.xpack.monitoring.agent.resolver.ResolversRegistry;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.exporter.local; package org.elasticsearch.xpack.monitoring.agent.exporter.local;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
@ -24,13 +24,13 @@ import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.marvel.agent.exporter.ExportBulk;
import org.elasticsearch.marvel.agent.exporter.Exporter;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.marvel.agent.resolver.ResolversRegistry;
import org.elasticsearch.marvel.cleaner.CleanerService;
import org.elasticsearch.xpack.common.init.proxy.ClientProxy; import org.elasticsearch.xpack.common.init.proxy.ClientProxy;
import org.elasticsearch.xpack.monitoring.agent.exporter.ExportBulk;
import org.elasticsearch.xpack.monitoring.agent.exporter.Exporter;
import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.xpack.monitoring.agent.resolver.ResolversRegistry;
import org.elasticsearch.xpack.monitoring.cleaner.CleanerService;
import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.InternalClient;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
@ -211,8 +211,8 @@ public class LocalExporter extends Exporter implements ClusterStateListener, Cle
} }
@Override @Override
public void onFailure(Throwable throwable) { public void onFailure(Exception e) {
logger.error("failed to update monitoring index template [{}]", throwable, template); logger.error("failed to update monitoring index template [{}]", e, template);
} }
}); });
} }
@ -296,7 +296,7 @@ public class LocalExporter extends Exporter implements ClusterStateListener, Cle
} }
@Override @Override
public void onFailure(Throwable e) { public void onFailure(Exception e) {
logger.error("failed to delete indices", e); logger.error("failed to delete indices", e);
} }
}); });

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.resolver; package org.elasticsearch.xpack.monitoring.agent.resolver;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
@ -14,9 +14,9 @@ import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.marvel.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoredSystem;
import org.elasticsearch.marvel.agent.exporter.MarvelTemplateUtils; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringTemplateUtils;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormat;
@ -126,14 +126,14 @@ public abstract class MonitoringIndexNameResolver<T extends MonitoringDoc> {
* Data index name resolvers are used used to index documents in * Data index name resolvers are used used to index documents in
* the monitoring data index (.monitoring-data-{VERSION}) * the monitoring data index (.monitoring-data-{VERSION})
*/ */
public static abstract class Data<T extends MonitoringDoc> extends MonitoringIndexNameResolver<T> { public abstract static class Data<T extends MonitoringDoc> extends MonitoringIndexNameResolver<T> {
public static final String DATA = "data"; public static final String DATA = "data";
private final String index; private final String index;
public Data() { public Data() {
this(MarvelTemplateUtils.TEMPLATE_VERSION); this(MonitoringTemplateUtils.TEMPLATE_VERSION);
} }
// Used in tests // Used in tests
@ -153,12 +153,12 @@ public abstract class MonitoringIndexNameResolver<T extends MonitoringDoc> {
@Override @Override
public String templateName() { public String templateName() {
return String.format(Locale.ROOT, "%s-%s-%d", PREFIX, DATA, MarvelTemplateUtils.TEMPLATE_VERSION); return String.format(Locale.ROOT, "%s-%s-%d", PREFIX, DATA, MonitoringTemplateUtils.TEMPLATE_VERSION);
} }
@Override @Override
public String template() { public String template() {
return MarvelTemplateUtils.loadTemplate(DATA); return MonitoringTemplateUtils.loadTemplate(DATA);
} }
} }
@ -166,7 +166,7 @@ public abstract class MonitoringIndexNameResolver<T extends MonitoringDoc> {
* Timestamped index name resolvers are used used to index documents in * Timestamped index name resolvers are used used to index documents in
* a timestamped index (.monitoring-{ID}-{VERSION}-YYYY.MM.dd) * a timestamped index (.monitoring-{ID}-{VERSION}-YYYY.MM.dd)
*/ */
public static abstract class Timestamped<T extends MonitoringDoc> extends MonitoringIndexNameResolver<T> { public abstract static class Timestamped<T extends MonitoringDoc> extends MonitoringIndexNameResolver<T> {
public static final Setting<String> INDEX_NAME_TIME_FORMAT_SETTING = new Setting<>("index.name.time_format", "YYYY.MM.dd", public static final Setting<String> INDEX_NAME_TIME_FORMAT_SETTING = new Setting<>("index.name.time_format", "YYYY.MM.dd",
Function.identity(), Setting.Property.NodeScope); Function.identity(), Setting.Property.NodeScope);
@ -176,7 +176,7 @@ public abstract class MonitoringIndexNameResolver<T extends MonitoringDoc> {
private final String index; private final String index;
public Timestamped(MonitoredSystem system, Settings settings) { public Timestamped(MonitoredSystem system, Settings settings) {
this(system, settings, MarvelTemplateUtils.TEMPLATE_VERSION); this(system, settings, MonitoringTemplateUtils.TEMPLATE_VERSION);
} }
// Used in tests // Used in tests
@ -209,12 +209,12 @@ public abstract class MonitoringIndexNameResolver<T extends MonitoringDoc> {
@Override @Override
public String templateName() { public String templateName() {
return String.format(Locale.ROOT, "%s-%s-%d", PREFIX, getId(), MarvelTemplateUtils.TEMPLATE_VERSION); return String.format(Locale.ROOT, "%s-%s-%d", PREFIX, getId(), MonitoringTemplateUtils.TEMPLATE_VERSION);
} }
@Override @Override
public String template() { public String template() {
return MarvelTemplateUtils.loadTemplate(getId()); return MonitoringTemplateUtils.loadTemplate(getId());
} }
String getId() { String getId() {

View File

@ -3,36 +3,36 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.resolver; package org.elasticsearch.xpack.monitoring.agent.resolver;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.marvel.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoredSystem;
import org.elasticsearch.marvel.action.MonitoringBulkDoc; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkDoc;
import org.elasticsearch.marvel.action.MonitoringIndex; import org.elasticsearch.xpack.monitoring.action.MonitoringIndex;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterInfoMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterInfoMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStateMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStateMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStateNodeMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStateNodeMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStatsMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterStatsMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.cluster.DiscoveryNodeMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.DiscoveryNodeMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.indices.IndexRecoveryMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndexRecoveryMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.indices.IndexStatsMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndexStatsMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.indices.IndicesStatsMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.indices.IndicesStatsMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.node.NodeStatsMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.node.NodeStatsMonitoringDoc;
import org.elasticsearch.marvel.agent.collector.shards.ShardMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.shards.ShardMonitoringDoc;
import org.elasticsearch.marvel.agent.exporter.MonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.exporter.MonitoringDoc;
import org.elasticsearch.marvel.agent.resolver.bulk.MonitoringBulkDataResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.bulk.MonitoringBulkDataResolver;
import org.elasticsearch.marvel.agent.resolver.bulk.MonitoringBulkTimestampedResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.bulk.MonitoringBulkTimestampedResolver;
import org.elasticsearch.marvel.agent.resolver.cluster.ClusterInfoResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.cluster.ClusterInfoResolver;
import org.elasticsearch.marvel.agent.resolver.cluster.ClusterStateNodeResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.cluster.ClusterStateNodeResolver;
import org.elasticsearch.marvel.agent.resolver.cluster.ClusterStateResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.cluster.ClusterStateResolver;
import org.elasticsearch.marvel.agent.resolver.cluster.ClusterStatsResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.cluster.ClusterStatsResolver;
import org.elasticsearch.marvel.agent.resolver.cluster.DiscoveryNodeResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.cluster.DiscoveryNodeResolver;
import org.elasticsearch.marvel.agent.resolver.indices.IndexRecoveryResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.indices.IndexRecoveryResolver;
import org.elasticsearch.marvel.agent.resolver.indices.IndexStatsResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.indices.IndexStatsResolver;
import org.elasticsearch.marvel.agent.resolver.indices.IndicesStatsResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.indices.IndicesStatsResolver;
import org.elasticsearch.marvel.agent.resolver.node.NodeStatsResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.node.NodeStatsResolver;
import org.elasticsearch.marvel.agent.resolver.shards.ShardsResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.shards.ShardsResolver;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
@ -40,15 +40,13 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.function.Predicate; import java.util.function.Predicate;
import static org.elasticsearch.marvel.MonitoredSystem.ES;
public class ResolversRegistry implements Iterable<MonitoringIndexNameResolver> { public class ResolversRegistry implements Iterable<MonitoringIndexNameResolver> {
private final List<Registration> registrations = new ArrayList<>(); private final List<Registration> registrations = new ArrayList<>();
public ResolversRegistry(Settings settings) { public ResolversRegistry(Settings settings) {
// register built-in defaults resolvers // register built-in defaults resolvers
registerBuiltIn(ES, settings); registerBuiltIn(MonitoredSystem.ES, settings);
// register resolvers for monitored systems // register resolvers for monitored systems
registerMonitoredSystem(MonitoredSystem.KIBANA, settings); registerMonitoredSystem(MonitoredSystem.KIBANA, settings);

View File

@ -3,13 +3,13 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.resolver.bulk; package org.elasticsearch.xpack.monitoring.agent.resolver.bulk;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.marvel.action.MonitoringBulkDoc; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import java.io.IOException; import java.io.IOException;

View File

@ -3,15 +3,15 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.resolver.bulk; package org.elasticsearch.xpack.monitoring.agent.resolver.bulk;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.marvel.MonitoredSystem; import org.elasticsearch.xpack.monitoring.MonitoredSystem;
import org.elasticsearch.marvel.action.MonitoringBulkDoc; import org.elasticsearch.xpack.monitoring.action.MonitoringBulkDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import java.io.IOException; import java.io.IOException;

View File

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License; * or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License. * you may not use this file except in compliance with the Elastic License.
*/ */
package org.elasticsearch.marvel.agent.resolver.cluster; package org.elasticsearch.xpack.monitoring.agent.resolver.cluster;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.collect.MapBuilder;
@ -11,8 +11,8 @@ import org.elasticsearch.common.hash.MessageDigests;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.license.core.License; import org.elasticsearch.license.core.License;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterInfoMonitoringDoc; import org.elasticsearch.xpack.monitoring.agent.collector.cluster.ClusterInfoMonitoringDoc;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver; import org.elasticsearch.xpack.monitoring.agent.resolver.MonitoringIndexNameResolver;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;

Some files were not shown because too many files have changed in this diff Show More