diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java index 073216c..8f218df 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/CommandManagerPlugin.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,10 +8,6 @@ */ package com.wazuh.commandmanager; -import com.wazuh.commandmanager.index.CommandIndex; -import com.wazuh.commandmanager.rest.action.RestPostCommandAction; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClientDemo; import org.opensearch.client.Client; import org.opensearch.cluster.metadata.IndexNameExpressionResolver; import org.opensearch.cluster.node.DiscoveryNodes; @@ -38,11 +35,15 @@ import java.util.List; import java.util.function.Supplier; +import com.wazuh.commandmanager.index.CommandIndex; +import com.wazuh.commandmanager.rest.action.RestPostCommandAction; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClientDemo; + /** - * The Command Manager plugin exposes an HTTP API with a single endpoint to - * receive raw commands from the Wazuh Server. These commands are processed, - * indexed and sent back to the Server for its delivery to, in most cases, the - * Agents. + * The Command Manager plugin exposes an HTTP API with a single endpoint to receive raw commands + * from the Wazuh Server. These commands are processed, indexed and sent back to the Server for its + * delivery to, in most cases, the Agents. */ public class CommandManagerPlugin extends Plugin implements ActionPlugin { public static final String COMMAND_MANAGER_BASE_URI = "/_plugins/_commandmanager"; @@ -63,8 +64,7 @@ public Collection createComponents( NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier repositoriesServiceSupplier - ) { + Supplier repositoriesServiceSupplier) { this.commandIndex = new CommandIndex(client, clusterService, threadPool); // HttpRestClient stuff @@ -81,8 +81,7 @@ public List getRestHandlers( IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier nodesInCluster - ) { + Supplier nodesInCluster) { return Collections.singletonList(new RestPostCommandAction(this.commandIndex)); } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java index d0138da..63394f0 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/index/CommandIndex.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,9 +8,6 @@ */ package com.wazuh.commandmanager.index; -import com.wazuh.commandmanager.CommandManagerPlugin; -import com.wazuh.commandmanager.model.Document; -import com.wazuh.commandmanager.utils.IndexTemplateUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest; @@ -31,9 +29,11 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; -/** - * Class to manage the Command Manager index and index template. - */ +import com.wazuh.commandmanager.CommandManagerPlugin; +import com.wazuh.commandmanager.model.Document; +import com.wazuh.commandmanager.utils.IndexTemplateUtils; + +/** Class to manage the Command Manager index and index template. */ public class CommandIndex implements IndexingOperationListener { private static final Logger logger = LogManager.getLogger(CommandIndex.class); @@ -45,9 +45,9 @@ public class CommandIndex implements IndexingOperationListener { /** * Default constructor * - * @param client OpenSearch client. + * @param client OpenSearch client. * @param clusterService OpenSearch cluster service. - * @param threadPool An OpenSearch ThreadPool. + * @param threadPool An OpenSearch ThreadPool. */ public CommandIndex(Client client, ClusterService clusterService, ThreadPool threadPool) { this.client = client; @@ -69,30 +69,31 @@ public CompletableFuture asyncCreate(Document document) { } else { logger.info( "Index template {} already exists. Skipping creation.", - CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME - ); + CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME); } logger.debug("Indexing command {}", document); try { - IndexRequest request = new IndexRequest() - .index(CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME) - .source(document.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) - .id(document.getId()) - .create(true); + IndexRequest request = + new IndexRequest() + .index(CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME) + .source( + document.toXContent( + XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS)) + .id(document.getId()) + .create(true); executor.submit( () -> { - try (ThreadContext.StoredContext ignored = this.threadPool.getThreadContext().stashContext()) { + try (ThreadContext.StoredContext ignored = + this.threadPool.getThreadContext().stashContext()) { RestStatus restStatus = client.index(request).actionGet().status(); future.complete(restStatus); } catch (Exception e) { future.completeExceptionally(e); } - } - ); + }); } catch (IOException e) { - logger.error( - "Failed to index command with ID {}: {}", document.getId(), e); + logger.error("Failed to index command with ID {}: {}", document.getId(), e); } return future; } @@ -104,10 +105,8 @@ public CompletableFuture asyncCreate(Document document) { * @return whether the index template exists. */ public boolean indexTemplateExists(String template_name) { - Map templates = this.clusterService - .state() - .metadata() - .templates(); + Map templates = + this.clusterService.state().metadata().templates(); logger.debug("Existing index templates: {} ", templates); return templates.containsKey(template_name); @@ -124,25 +123,25 @@ public void putIndexTemplate(String templateName) { // @throws IOException Map template = IndexTemplateUtils.fromFile(templateName + ".json"); - PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest() - .mapping(IndexTemplateUtils.get(template, "mappings")) - .settings(IndexTemplateUtils.get(template, "settings")) - .name(templateName) - .patterns((List) template.get("index_patterns")); - - executor.submit(() -> { - AcknowledgedResponse acknowledgedResponse = this.client - .admin() - .indices() - .putTemplate(putIndexTemplateRequest) - .actionGet(); - if (acknowledgedResponse.isAcknowledged()) { - logger.info( - "Index template created successfully: {}", - templateName - ); - } - }); + PutIndexTemplateRequest putIndexTemplateRequest = + new PutIndexTemplateRequest() + .mapping(IndexTemplateUtils.get(template, "mappings")) + .settings(IndexTemplateUtils.get(template, "settings")) + .name(templateName) + .patterns((List) template.get("index_patterns")); + + executor.submit( + () -> { + AcknowledgedResponse acknowledgedResponse = + this.client + .admin() + .indices() + .putTemplate(putIndexTemplateRequest) + .actionGet(); + if (acknowledgedResponse.isAcknowledged()) { + logger.info("Index template created successfully: {}", templateName); + } + }); } catch (IOException e) { logger.error("Error reading index template from filesystem {}", templateName); diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Action.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Action.java index 71cd038..560c8f5 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Action.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Action.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -14,9 +15,7 @@ import java.io.IOException; import java.util.List; -/** - * Command's action fields. - */ +/** Command's action fields. */ public class Action implements ToXContentObject { public static final String ACTION = "action"; public static final String NAME = "name"; @@ -29,8 +28,8 @@ public class Action implements ToXContentObject { /** * Default constructor. * - * @param name action to be executed on the target, - * @param args actual command. + * @param name action to be executed on the target, + * @param args actual command. * @param version version of the action. */ public Action(String name, List args, String version) { @@ -84,10 +83,15 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Action{" + - "name='" + name + '\'' + - ", args=" + args + - ", version='" + version + '\'' + - '}'; + return "Action{" + + "name='" + + name + + '\'' + + ", args=" + + args + + ", version='" + + version + + '\'' + + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Agent.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Agent.java index 77971cf..4d85e3d 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Agent.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Agent.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -14,9 +15,7 @@ import java.io.IOException; import java.util.List; -/** - * Command's agent fields. - */ +/** Command's agent fields. */ public class Agent implements ToXContentObject { public static final String AGENT = "agent"; public static final String GROUPS = "groups"; @@ -63,8 +62,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Agent{" + - "groups=" + groups + - '}'; + return "Agent{" + "groups=" + groups + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java index 93d39e9..04e6e49 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Command.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -12,10 +13,11 @@ import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import reactor.util.annotation.NonNull; import java.io.IOException; +import reactor.util.annotation.NonNull; + public class Command implements ToXContentObject { public static final String COMMAND = "command"; public static final String ORDER_ID = "order_id"; @@ -36,19 +38,18 @@ public class Command implements ToXContentObject { /** * Default constructor * - * @param source origin of the request. - * @param target {@link Target} + * @param source origin of the request. + * @param target {@link Target} * @param timeout time window in which the command has to be sent to its target. - * @param user the user that originated the request - * @param action {@link Action} + * @param user the user that originated the request + * @param action {@link Action} */ public Command( @NonNull String source, @NonNull Target target, @NonNull Integer timeout, @NonNull String user, - @NonNull Action action - ) { + @NonNull Action action) { this.requestId = UUIDs.base64UUID(); this.orderId = UUIDs.base64UUID(); this.source = source; @@ -100,13 +101,7 @@ public static Command parse(XContentParser parser) throws IOException { } // TODO add proper validation - return new Command( - source, - target, - timeout, - user, - action - ); + return new Command(source, target, timeout, user, action); } @Override @@ -126,15 +121,27 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Command{" + - "orderId='" + orderId + '\'' + - ", requestId='" + requestId + '\'' + - ", source='" + source + '\'' + - ", target=" + target + - ", timeout=" + timeout + - ", user='" + user + '\'' + - ", status=" + status + - ", action=" + action + - '}'; + return "Command{" + + "orderId='" + + orderId + + '\'' + + ", requestId='" + + requestId + + '\'' + + ", source='" + + source + + '\'' + + ", target=" + + target + + ", timeout=" + + timeout + + ", user='" + + user + + '\'' + + ", status=" + + status + + ", action=" + + action + + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Document.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Document.java index 28ec263..b9ec385 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Document.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Document.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -15,9 +16,7 @@ import java.io.IOException; import java.util.List; -/** - * Command's target fields. - */ +/** Command's target fields. */ public class Document implements ToXContentObject { private final Agent agent; private final Command command; @@ -74,9 +73,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Document{" + - "agent=" + agent + - ", command=" + command + - '}'; + return "Document{" + "agent=" + agent + ", command=" + command + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Status.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Status.java index 65b0c38..80c4dbe 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Status.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Status.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Target.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Target.java index 3a7bb82..6e592bd 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Target.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/model/Target.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -13,9 +14,7 @@ import java.io.IOException; -/** - * Command's target fields. - */ +/** Command's target fields. */ public class Target implements ToXContentObject { public static final String TARGET = "target"; public static final String TYPE = "type"; @@ -27,7 +26,7 @@ public class Target implements ToXContentObject { * Default constructor. * * @param type The destination type. One of [`group`, `agent`, `server`] - * @param id Unique identifier of the destination to send the command to. + * @param id Unique identifier of the destination to send the command to. */ public Target(String type, String id) { this.type = type; @@ -72,9 +71,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return "Target{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - '}'; + return "Target{" + "type='" + type + '\'' + ", id='" + id + '\'' + '}'; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/action/RestPostCommandAction.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/action/RestPostCommandAction.java index c27257d..8521595 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/action/RestPostCommandAction.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/rest/action/RestPostCommandAction.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,9 +8,6 @@ */ package com.wazuh.commandmanager.rest.action; -import com.wazuh.commandmanager.CommandManagerPlugin; -import com.wazuh.commandmanager.index.CommandIndex; -import com.wazuh.commandmanager.model.Document; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opensearch.client.node.NodeClient; @@ -25,17 +23,21 @@ import java.util.List; import java.util.Locale; +import com.wazuh.commandmanager.CommandManagerPlugin; +import com.wazuh.commandmanager.index.CommandIndex; +import com.wazuh.commandmanager.model.Document; + import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.rest.RestRequest.Method.POST; /** - * Handles HTTP requests to the POST - * {@value com.wazuh.commandmanager.CommandManagerPlugin#COMMAND_MANAGER_BASE_URI} - * endpoint. + * Handles HTTP requests to the POST {@value + * com.wazuh.commandmanager.CommandManagerPlugin#COMMAND_MANAGER_BASE_URI} endpoint. */ public class RestPostCommandAction extends BaseRestHandler { - public static final String POST_COMMAND_ACTION_REQUEST_DETAILS = "post_command_action_request_details"; + public static final String POST_COMMAND_ACTION_REQUEST_DETAILS = + "post_command_action_request_details"; private static final Logger logger = LogManager.getLogger(RestPostCommandAction.class); private final CommandIndex commandIndex; @@ -46,7 +48,6 @@ public class RestPostCommandAction extends BaseRestHandler { */ public RestPostCommandAction(CommandIndex commandIndex) { this.commandIndex = commandIndex; - } public String getName() { @@ -59,19 +60,12 @@ public List routes() { new Route( POST, String.format( - Locale.ROOT, - "%s", - CommandManagerPlugin.COMMAND_MANAGER_BASE_URI - ) - ) - ); + Locale.ROOT, "%s", CommandManagerPlugin.COMMAND_MANAGER_BASE_URI))); } @Override protected RestChannelConsumer prepareRequest( - final RestRequest restRequest, - final NodeClient client - ) throws IOException { + final RestRequest restRequest, final NodeClient client) throws IOException { // Get request details XContentParser parser = restRequest.contentParser(); ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); @@ -80,23 +74,31 @@ protected RestChannelConsumer prepareRequest( // Send response return channel -> { - this.commandIndex.asyncCreate(document) - .thenAccept(restStatus -> { - try (XContentBuilder builder = channel.newBuilder()) { - builder.startObject(); - builder.field("_index", CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME); - builder.field("_id", document.getId()); - builder.field("result", restStatus.name()); - builder.endObject(); - channel.sendResponse(new BytesRestResponse(restStatus, builder)); - } catch (Exception e) { - logger.error("Error indexing command: ", e); - } - }).exceptionally(e -> { - channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage())); - return null; - }); - + this.commandIndex + .asyncCreate(document) + .thenAccept( + restStatus -> { + try (XContentBuilder builder = channel.newBuilder()) { + builder.startObject(); + builder.field( + "_index", + CommandManagerPlugin.COMMAND_MANAGER_INDEX_NAME); + builder.field("_id", document.getId()); + builder.field("result", restStatus.name()); + builder.endObject(); + channel.sendResponse( + new BytesRestResponse(restStatus, builder)); + } catch (Exception e) { + logger.error("Error indexing command: ", e); + } + }) + .exceptionally( + e -> { + channel.sendResponse( + new BytesRestResponse( + RestStatus.INTERNAL_SERVER_ERROR, e.getMessage())); + return null; + }); }; } } diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/IndexTemplateUtils.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/IndexTemplateUtils.java index bed3434..409b133 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/IndexTemplateUtils.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/IndexTemplateUtils.java @@ -1,43 +1,37 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ - package com.wazuh.commandmanager.utils; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import reactor.util.annotation.NonNull; import java.io.IOException; import java.io.InputStream; import java.util.Map; -/** - * Util functions to parse and manage index templates files. - */ +import reactor.util.annotation.NonNull; + +/** Util functions to parse and manage index templates files. */ public class IndexTemplateUtils { - /** - * Default constructor - */ - public IndexTemplateUtils() { - } + /** Default constructor */ + public IndexTemplateUtils() {} /** - * Read index template file from the resources folder and returns its JSON - * content as a map. + * Read index template file from the resources folder and returns its JSON content as a map. * * @param filename name of the index template to read from the resources folder * @return the JSON index template as a map * @throws IOException file not found or could not be read */ - public static Map fromFile(@NonNull String filename) throws IOException { InputStream is = IndexTemplateUtils.class.getClassLoader().getResourceAsStream(filename); return IndexTemplateUtils.toMap(is); @@ -45,29 +39,29 @@ public static Map fromFile(@NonNull String filename) throws IOEx /** * Convert from a JSON InputStream into a String, Object map. - *

- * Used to convert the JSON index templates to the required format. - *

+ * + *

Used to convert the JSON index templates to the required format. * * @param is: the JSON formatted InputStream * @return a map with the json string contents. - * @throws IOException thrown by {@link JsonXContent#createParser(NamedXContentRegistry, DeprecationHandler, InputStream)} + * @throws IOException thrown by {@link JsonXContent#createParser(NamedXContentRegistry, + * DeprecationHandler, InputStream)} */ public static Map toMap(InputStream is) throws IOException { - XContentParser parser = JsonXContent.jsonXContent.createParser( - NamedXContentRegistry.EMPTY, - DeprecationHandler.THROW_UNSUPPORTED_OPERATION, - is); + XContentParser parser = + JsonXContent.jsonXContent.createParser( + NamedXContentRegistry.EMPTY, + DeprecationHandler.THROW_UNSUPPORTED_OPERATION, + is); parser.nextToken(); return parser.map(); } /** * Cast map's element to a String, Object map. - *

- * Used to retrieve the settings and mappings from the index templates, - * which are a JSON object themselves. - *

+ * + *

Used to retrieve the settings and mappings from the index templates, which are a JSON + * object themselves. * * @param map the index template as a map. * @param key the element's key to retrieve and cast. @@ -76,6 +70,4 @@ public static Map toMap(InputStream is) throws IOException { public static Map get(Map map, String key) { return (Map) map.get(key); } - } - diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpResponseCallback.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpResponseCallback.java index eaf357d..c5f249a 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpResponseCallback.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpResponseCallback.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -18,18 +19,13 @@ public class HttpResponseCallback implements FutureCallback private static final Logger log = LogManager.getLogger(HttpResponseCallback.class); - /** - * The Http get request. - */ + /** The Http get request. */ SimpleHttpRequest httpRequest; - /** - * The Error message. - */ + /** The Error message. */ String errorMessage; - public HttpResponseCallback(SimpleHttpRequest httpRequest, - String errorMessage) { + public HttpResponseCallback(SimpleHttpRequest httpRequest, String errorMessage) { this.httpRequest = httpRequest; this.errorMessage = errorMessage; } @@ -43,7 +39,7 @@ public void completed(SimpleHttpResponse response) { @Override public void failed(Exception ex) { log.error("{}->{}", httpRequest, ex); -// throw new HttpException(errorMessage, ex); + // throw new HttpException(errorMessage, ex); } @Override diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java index f21cd58..41960e0 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClient.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -24,19 +25,14 @@ import java.net.URI; import java.util.concurrent.Future; -/** - * HTTP Rest client. Currently used to perform - * POST requests against the Wazuh Server. - */ +/** HTTP Rest client. Currently used to perform POST requests against the Wazuh Server. */ public class HttpRestClient { private static final Logger log = LogManager.getLogger(HttpRestClient.class); private static HttpRestClient instance; private CloseableHttpAsyncClient httpClient; - /** - * Private default constructor - */ + /** Private default constructor */ private HttpRestClient() { startHttpAsyncClient(); } @@ -53,23 +49,21 @@ public static HttpRestClient getInstance() { return HttpRestClient.instance; } - /** - * Starts http async client. - */ + /** Starts http async client. */ private void startHttpAsyncClient() { if (this.httpClient == null) { try { PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create().build(); - IOReactorConfig ioReactorConfig = IOReactorConfig.custom() - .setSoTimeout(Timeout.ofSeconds(5)) - .build(); + IOReactorConfig ioReactorConfig = + IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build(); - httpClient = HttpAsyncClients.custom() - .setIOReactorConfig(ioReactorConfig) - .setConnectionManager(cm) - .build(); + httpClient = + HttpAsyncClients.custom() + .setIOReactorConfig(ioReactorConfig) + .setConnectionManager(cm) + .build(); httpClient.start(); } catch (Exception e) { @@ -79,9 +73,7 @@ private void startHttpAsyncClient() { } } - /** - * Stop http async client. - */ + /** Stop http async client. */ public void stopHttpAsyncClient() { if (this.httpClient != null) { log.info("Shutting down."); @@ -93,7 +85,7 @@ public void stopHttpAsyncClient() { /** * Sends a POST request. * - * @param uri Well-formed URI + * @param uri Well-formed URI * @param payload data to send * @return HTTP response */ @@ -104,12 +96,12 @@ public SimpleHttpResponse post(URI uri, String payload) { // Create request HttpHost httpHost = HttpHost.create(uri.getHost()); - SimpleHttpRequest httpPostRequest = SimpleRequestBuilder - .post() - .setHttpHost(httpHost) - .setPath(uri.getPath()) - .setBody(payload, ContentType.APPLICATION_JSON) - .build(); + SimpleHttpRequest httpPostRequest = + SimpleRequestBuilder.post() + .setHttpHost(httpHost) + .setPath(uri.getPath()) + .setBody(payload, ContentType.APPLICATION_JSON) + .build(); // log request Future future = @@ -117,10 +109,7 @@ public SimpleHttpResponse post(URI uri, String payload) { SimpleRequestProducer.create(httpPostRequest), SimpleResponseConsumer.create(), new HttpResponseCallback( - httpPostRequest, - "Failed to send data for ID: " + id - ) - ); + httpPostRequest, "Failed to send data for ID: " + id)); return future.get(); } catch (Exception e) { diff --git a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java index 448ece4..ceda59d 100644 --- a/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java +++ b/plugins/command-manager/src/main/java/com/wazuh/commandmanager/utils/httpclient/HttpRestClientDemo.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -17,9 +18,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; -/** - * Demo class to test the {@link HttpRestClient} class. - */ +/** Demo class to test the {@link HttpRestClient} class. */ public class HttpRestClientDemo { private static final Logger log = LogManager.getLogger(HttpRestClientDemo.class); @@ -28,23 +27,23 @@ public class HttpRestClientDemo { * Demo method to test the {@link HttpRestClient} class. * * @param endpoint POST's requests endpoint as a well-formed URI - * @param body POST's request body as a JSON string. + * @param body POST's request body as a JSON string. */ public static void run(String endpoint, String body) { log.info("Executing POST request"); AccessController.doPrivileged( - (PrivilegedAction) () -> { - HttpRestClient httpClient = HttpRestClient.getInstance(); - URI host; - try { - host = new URIBuilder(endpoint).build(); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - SimpleHttpResponse postResponse = httpClient.post(host, body); - log.info(postResponse.getBodyText()); - return postResponse; - } - ); + (PrivilegedAction) + () -> { + HttpRestClient httpClient = HttpRestClient.getInstance(); + URI host; + try { + host = new URIBuilder(endpoint).build(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + SimpleHttpResponse postResponse = httpClient.post(host, body); + log.info(postResponse.getBodyText()); + return postResponse; + }); } } diff --git a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerPluginIT.java b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerPluginIT.java index 0bbf232..ee13d97 100644 --- a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerPluginIT.java +++ b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerPluginIT.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -8,6 +9,7 @@ package com.wazuh.commandmanager; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; + import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; import org.opensearch.client.Request; diff --git a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java index eacd0b1..759c3c4 100644 --- a/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java +++ b/plugins/command-manager/src/test/java/com/wazuh/commandmanager/CommandManagerTests.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,16 +8,17 @@ */ package com.wazuh.commandmanager; -import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; -import org.junit.Assert; import org.opensearch.test.OpenSearchTestCase; +import org.junit.Assert; import java.net.URI; import java.net.URISyntaxException; import java.security.AccessController; import java.security.PrivilegedAction; +import com.wazuh.commandmanager.utils.httpclient.HttpRestClient; + public class CommandManagerTests extends OpenSearchTestCase { // Add unit tests for your plugin @@ -25,26 +27,27 @@ public class CommandManagerTests extends OpenSearchTestCase { public void testPost_success() { try { AccessController.doPrivileged( - (PrivilegedAction) () -> { - this.httpClient = HttpRestClient.getInstance(); - URI uri = null; - try { - uri = new URI("https://httpbin.org/post"); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - String payload = "{\"message\": \"Hello world!\"}"; - SimpleHttpResponse postResponse = this.httpClient.post(uri, payload); - - String responseText = postResponse.getBodyText(); - assertNotEquals(null, postResponse); - assertNotEquals(null, responseText); - assertEquals(200, postResponse.getCode()); - assertNotEquals(0, responseText.length()); - assertTrue(responseText.contains("Hello world!")); - return postResponse; - } - ); + (PrivilegedAction) + () -> { + this.httpClient = HttpRestClient.getInstance(); + URI uri = null; + try { + uri = new URI("https://httpbin.org/post"); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + String payload = "{\"message\": \"Hello world!\"}"; + SimpleHttpResponse postResponse = + this.httpClient.post(uri, payload); + + String responseText = postResponse.getBodyText(); + assertNotEquals(null, postResponse); + assertNotEquals(null, responseText); + assertEquals(200, postResponse.getCode()); + assertNotEquals(0, responseText.length()); + assertTrue(responseText.contains("Hello world!")); + return postResponse; + }); } catch (Exception e) { Assert.fail("Failed to execute HTTP request: " + e); } finally { @@ -52,9 +55,7 @@ public void testPost_success() { } } - public void testPost_badUri() { - } + public void testPost_badUri() {} - public void testPost_badPayload() { - } + public void testPost_badPayload() {} } diff --git a/plugins/command-manager/src/yamlRestTest/java/com/wazuh/commandmanager/CommandManagerClientYamlTestSuiteIT.java b/plugins/command-manager/src/yamlRestTest/java/com/wazuh/commandmanager/CommandManagerClientYamlTestSuiteIT.java index 4a53723..3921d9c 100644 --- a/plugins/command-manager/src/yamlRestTest/java/com/wazuh/commandmanager/CommandManagerClientYamlTestSuiteIT.java +++ b/plugins/command-manager/src/yamlRestTest/java/com/wazuh/commandmanager/CommandManagerClientYamlTestSuiteIT.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -9,13 +10,14 @@ import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; + import org.opensearch.test.rest.yaml.ClientYamlTestCandidate; import org.opensearch.test.rest.yaml.OpenSearchClientYamlSuiteTestCase; - public class CommandManagerClientYamlTestSuiteIT extends OpenSearchClientYamlSuiteTestCase { - public CommandManagerClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { + public CommandManagerClientYamlTestSuiteIT( + @Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); } diff --git a/plugins/setup/src/main/java/com/wazuh/setup/SetupPlugin.java b/plugins/setup/src/main/java/com/wazuh/setup/SetupPlugin.java index 77d95c3..69577ef 100644 --- a/plugins/setup/src/main/java/com/wazuh/setup/SetupPlugin.java +++ b/plugins/setup/src/main/java/com/wazuh/setup/SetupPlugin.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,7 +8,6 @@ */ package com.wazuh.setup; -import com.wazuh.setup.index.WazuhIndices; import org.opensearch.client.Client; import org.opensearch.cluster.metadata.IndexNameExpressionResolver; import org.opensearch.cluster.node.DiscoveryNode; @@ -27,20 +27,18 @@ import java.util.List; import java.util.function.Supplier; +import com.wazuh.setup.index.WazuhIndices; + /** - * Main class of the Indexer Setup plugin. This plugin is responsible for - * the creation of the index templates and indices required by Wazuh to - * work properly. + * Main class of the Indexer Setup plugin. This plugin is responsible for the creation of the index + * templates and indices required by Wazuh to work properly. */ public class SetupPlugin extends Plugin implements ClusterPlugin { private WazuhIndices indices; - /** - * Default constructor - */ - public SetupPlugin() { - } + /** Default constructor */ + public SetupPlugin() {} @Override public Collection createComponents( @@ -54,8 +52,7 @@ public Collection createComponents( NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier repositoriesServiceSupplier - ) { + Supplier repositoriesServiceSupplier) { this.indices = new WazuhIndices(client, clusterService); return List.of(this.indices); } diff --git a/plugins/setup/src/main/java/com/wazuh/setup/index/WazuhIndices.java b/plugins/setup/src/main/java/com/wazuh/setup/index/WazuhIndices.java index 12411c6..860f538 100644 --- a/plugins/setup/src/main/java/com/wazuh/setup/index/WazuhIndices.java +++ b/plugins/setup/src/main/java/com/wazuh/setup/index/WazuhIndices.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,7 +8,6 @@ */ package com.wazuh.setup.index; -import com.wazuh.setup.utils.IndexTemplateUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opensearch.action.admin.indices.create.CreateIndexRequest; @@ -22,25 +22,24 @@ import java.util.List; import java.util.Map; +import com.wazuh.setup.utils.IndexTemplateUtils; + /** - * This class contains the logic to create the index templates and the indices - * required by Wazuh. + * This class contains the logic to create the index templates and the indices required by Wazuh. */ public class WazuhIndices { private static final Logger log = LogManager.getLogger(WazuhIndices.class); - /** - * | Key | value | - * | ------------------- | ---------- | - * | Index template name | index name | - */ + + /** | Key | value | | ------------------- | ---------- | | Index template name | index name | */ public final Map indexTemplates = new HashMap<>(); + private final Client client; private final ClusterService clusterService; /** * Constructor * - * @param client Client + * @param client Client * @param clusterService ClusterService */ public WazuhIndices(Client client, ClusterService clusterService) { @@ -67,23 +66,20 @@ public void putTemplate(String templateName) { // @throws IOException Map template = IndexTemplateUtils.fromFile(templateName + ".json"); - PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest() - .mapping(IndexTemplateUtils.get(template, "mappings")) - .settings(IndexTemplateUtils.get(template, "settings")) - .name(templateName) - .patterns((List) template.get("index_patterns")); + PutIndexTemplateRequest putIndexTemplateRequest = + new PutIndexTemplateRequest() + .mapping(IndexTemplateUtils.get(template, "mappings")) + .settings(IndexTemplateUtils.get(template, "settings")) + .name(templateName) + .patterns((List) template.get("index_patterns")); - AcknowledgedResponse createIndexTemplateResponse = this.client - .admin() - .indices() - .putTemplate(putIndexTemplateRequest) - .actionGet(); + AcknowledgedResponse createIndexTemplateResponse = + this.client.admin().indices().putTemplate(putIndexTemplateRequest).actionGet(); log.info( "Index template created successfully: {} {}", templateName, - createIndexTemplateResponse.isAcknowledged() - ); + createIndexTemplateResponse.isAcknowledged()); } catch (IOException e) { log.error("Error reading index template from filesystem {}", templateName); @@ -98,16 +94,12 @@ public void putTemplate(String templateName) { public void putIndex(String indexName) { if (!indexExists(indexName)) { CreateIndexRequest request = new CreateIndexRequest(indexName); - CreateIndexResponse createIndexResponse = this.client - .admin() - .indices() - .create(request) - .actionGet(); + CreateIndexResponse createIndexResponse = + this.client.admin().indices().create(request).actionGet(); log.info( "Index created successfully: {} {}", createIndexResponse.index(), - createIndexResponse.isAcknowledged() - ); + createIndexResponse.isAcknowledged()); } } @@ -121,16 +113,15 @@ public boolean indexExists(String indexName) { return this.clusterService.state().getRoutingTable().hasIndex(indexName); } - /** - * Creates each index template and index in {@link #indexTemplates}. - */ + /** Creates each index template and index in {@link #indexTemplates}. */ public void initialize() { // 1. Read index templates from files // 2. Upsert index template // 3. Create index - this.indexTemplates.forEach((k, v) -> { - this.putTemplate(k); - this.putIndex(v); - }); + this.indexTemplates.forEach( + (k, v) -> { + this.putTemplate(k); + this.putIndex(v); + }); } } diff --git a/plugins/setup/src/main/java/com/wazuh/setup/utils/IndexTemplateUtils.java b/plugins/setup/src/main/java/com/wazuh/setup/utils/IndexTemplateUtils.java index 3811bba..47f7712 100644 --- a/plugins/setup/src/main/java/com/wazuh/setup/utils/IndexTemplateUtils.java +++ b/plugins/setup/src/main/java/com/wazuh/setup/utils/IndexTemplateUtils.java @@ -1,43 +1,37 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ - package com.wazuh.setup.utils; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import reactor.util.annotation.NonNull; import java.io.IOException; import java.io.InputStream; import java.util.Map; -/** - * Util functions to parse and manage index templates files. - */ +import reactor.util.annotation.NonNull; + +/** Util functions to parse and manage index templates files. */ public class IndexTemplateUtils { - /** - * Default constructor - */ - public IndexTemplateUtils() { - } + /** Default constructor */ + public IndexTemplateUtils() {} /** - * Read index template file from the resources folder and returns its JSON - * content as a map. + * Read index template file from the resources folder and returns its JSON content as a map. * * @param filename name of the index template to read from the resources folder * @return the JSON index template as a map * @throws IOException file not found or could not be read */ - public static Map fromFile(@NonNull String filename) throws IOException { InputStream is = IndexTemplateUtils.class.getClassLoader().getResourceAsStream(filename); return IndexTemplateUtils.toMap(is); @@ -45,29 +39,29 @@ public static Map fromFile(@NonNull String filename) throws IOEx /** * Convert from a JSON InputStream into a String, Object map. - *

- * Used to convert the JSON index templates to the required format. - *

+ * + *

Used to convert the JSON index templates to the required format. * * @param is: the JSON formatted InputStream * @return a map with the json string contents. - * @throws IOException thrown by {@link JsonXContent#createParser(NamedXContentRegistry, DeprecationHandler, InputStream)} + * @throws IOException thrown by {@link JsonXContent#createParser(NamedXContentRegistry, + * DeprecationHandler, InputStream)} */ public static Map toMap(InputStream is) throws IOException { - XContentParser parser = JsonXContent.jsonXContent.createParser( - NamedXContentRegistry.EMPTY, - DeprecationHandler.THROW_UNSUPPORTED_OPERATION, - is); + XContentParser parser = + JsonXContent.jsonXContent.createParser( + NamedXContentRegistry.EMPTY, + DeprecationHandler.THROW_UNSUPPORTED_OPERATION, + is); parser.nextToken(); return parser.map(); } /** * Cast map's element to a String, Object map. - *

- * Used to retrieve the settings and mappings from the index templates, - * which are a JSON object themselves. - *

+ * + *

Used to retrieve the settings and mappings from the index templates, which are a JSON + * object themselves. * * @param map the index template as a map. * @param key the element's key to retrieve and cast. @@ -76,5 +70,4 @@ public static Map toMap(InputStream is) throws IOException { public static Map get(Map map, String key) { return (Map) map.get(key); } - } diff --git a/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginIT.java b/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginIT.java index 9c83dcc..5c2946a 100644 --- a/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginIT.java +++ b/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginIT.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -8,28 +9,27 @@ package com.wazuh.setup; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; + import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; -import org.opensearch.client.Request; -import org.opensearch.client.Response; -import org.opensearch.plugins.Plugin; -import org.opensearch.test.OpenSearchIntegTestCase; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.junit.Assert; import org.opensearch.action.admin.cluster.health.ClusterHealthRequest; import org.opensearch.action.admin.cluster.health.ClusterHealthResponse; import org.opensearch.action.admin.cluster.node.info.NodeInfo; import org.opensearch.action.admin.cluster.node.info.NodesInfoRequest; import org.opensearch.action.admin.cluster.node.info.NodesInfoResponse; import org.opensearch.action.admin.cluster.node.info.PluginsAndModules; +import org.opensearch.client.Request; +import org.opensearch.client.Response; import org.opensearch.cluster.health.ClusterHealthStatus; +import org.opensearch.plugins.Plugin; import org.opensearch.plugins.PluginInfo; +import org.opensearch.test.OpenSearchIntegTestCase; +import org.junit.Assert; -import java.util.Collections; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; @@ -54,36 +54,33 @@ public void testPluginInstalled() throws IOException, ParseException { assertThat(body, containsString("wazuh-indexer-setup")); } - public void testPluginsAreInstalled() { ClusterHealthRequest request = new ClusterHealthRequest(); - ClusterHealthResponse response = OpenSearchIntegTestCase - .client() - .admin(). - cluster() - .health(request) - .actionGet(); + ClusterHealthResponse response = + OpenSearchIntegTestCase.client().admin().cluster().health(request).actionGet(); Assert.assertEquals(ClusterHealthStatus.GREEN, response.getStatus()); NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.addMetric(NodesInfoRequest.Metric.PLUGINS.metricName()); - NodesInfoResponse nodesInfoResponse = OpenSearchIntegTestCase - .client() - .admin() - .cluster(). - nodesInfo(nodesInfoRequest) - .actionGet(); - List pluginInfos = nodesInfoResponse.getNodes() - .stream() - .flatMap((Function>) nodeInfo -> - nodeInfo - .getInfo(PluginsAndModules.class) - .getPluginInfos() - .stream() - ) - .collect(Collectors.toList()); - Assert.assertTrue(pluginInfos.stream().anyMatch( - pluginInfo -> pluginInfo.getName().equals("wazuh-indexer-setup")) - ); + NodesInfoResponse nodesInfoResponse = + OpenSearchIntegTestCase.client() + .admin() + .cluster() + .nodesInfo(nodesInfoRequest) + .actionGet(); + List pluginInfos = + nodesInfoResponse.getNodes().stream() + .flatMap( + (Function>) + nodeInfo -> + nodeInfo + .getInfo(PluginsAndModules.class) + .getPluginInfos() + .stream()) + .collect(Collectors.toList()); + Assert.assertTrue( + pluginInfos.stream() + .anyMatch( + pluginInfo -> pluginInfo.getName().equals("wazuh-indexer-setup"))); } } diff --git a/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginTests.java b/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginTests.java index 3ca708b..65a03c4 100644 --- a/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginTests.java +++ b/plugins/setup/src/test/java/com/wazuh/setup/SetupPluginTests.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,9 +8,6 @@ */ package com.wazuh.setup; -import com.wazuh.setup.index.WazuhIndices; -import org.junit.After; -import org.junit.Before; import org.opensearch.action.admin.indices.create.CreateIndexRequest; import org.opensearch.action.admin.indices.create.CreateIndexResponse; import org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest; @@ -24,9 +22,13 @@ import org.opensearch.test.OpenSearchTestCase; import org.opensearch.threadpool.TestThreadPool; import org.opensearch.threadpool.ThreadPool; +import org.junit.After; +import org.junit.Before; + +import com.wazuh.setup.index.WazuhIndices; -import static org.mockito.Mockito.*; import static org.opensearch.test.ClusterServiceUtils.createClusterService; +import static org.mockito.Mockito.*; public class SetupPluginTests extends OpenSearchTestCase { @@ -36,9 +38,7 @@ public class SetupPluginTests extends OpenSearchTestCase { private ThreadPool threadPool; private Client mockClient; - /** - * Creates the necessary mocks and spies - */ + /** Creates the necessary mocks and spies */ @Before public void setUp() throws Exception { try { @@ -53,18 +53,14 @@ public void setUp() throws Exception { } } - /** - * Shuts the test cluster down properly after tests are done - */ + /** Shuts the test cluster down properly after tests are done */ @After public void testTearDown() { this.threadPool.shutdownNow(); this.clusterService.close(); } - /** - * Tests the putTemplate method - */ + /** Tests the putTemplate method */ @AwaitsFix(bugUrl = "") public void testPutTemplate() { String mockTemplateName = "anIndexTemplateName"; @@ -74,11 +70,15 @@ public void testPutTemplate() { when(this.mockClient.admin()).thenReturn(mockAdminClient); when(mockAdminClient.indices()).thenReturn(mockIndicesAdminClient); - doAnswer(invocation -> { - ActionListener listener = invocation.getArgument(1); - listener.onResponse(new AcknowledgedResponse(true)); - return null; - }).when(mockIndicesAdminClient).putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class)); + doAnswer( + invocation -> { + ActionListener listener = + invocation.getArgument(1); + listener.onResponse(new AcknowledgedResponse(true)); + return null; + }) + .when(mockIndicesAdminClient) + .putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class)); try { this.wazuhIndices.putTemplate(mockTemplateName); @@ -86,11 +86,15 @@ public void testPutTemplate() { fail(e.toString()); } - doAnswer(invocation -> { - ActionListener listener = invocation.getArgument(1); - listener.onFailure(new Exception("Mock exception on putTemplate")); - return null; - }).when(mockIndicesAdminClient).putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class)); + doAnswer( + invocation -> { + ActionListener listener = + invocation.getArgument(1); + listener.onFailure(new Exception("Mock exception on putTemplate")); + return null; + }) + .when(mockIndicesAdminClient) + .putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class)); try { this.wazuhIndices.putTemplate(mockTemplateName); @@ -99,9 +103,7 @@ public void testPutTemplate() { } } - /** - * Tests creating an index - */ + /** Tests creating an index */ @AwaitsFix(bugUrl = "") public void testCreate() { AdminClient mockAdminClient = mock(AdminClient.class); @@ -109,24 +111,29 @@ public void testCreate() { when(this.mockClient.admin()).thenReturn(mockAdminClient); when(mockAdminClient.indices()).thenReturn(mockIndicesAdminClient); - doAnswer(invocation -> { - ActionListener listener = invocation.getArgument(1); - listener.onResponse(new CreateIndexResponse(true, true, INDEX_NAME)); - return null; - }).when(mockIndicesAdminClient).create(any(CreateIndexRequest.class), any(ActionListener.class)); - - ActionListener actionListener = new ActionListener<>() { - @Override - public void onResponse(CreateIndexResponse createIndexResponse) { - logger.info("Mock successful index creation"); - assertTrue(createIndexResponse.isAcknowledged()); - } - - @Override - public void onFailure(Exception e) { - logger.error("Mock error creating index: {}", e.toString()); - } - }; + doAnswer( + invocation -> { + ActionListener listener = + invocation.getArgument(1); + listener.onResponse(new CreateIndexResponse(true, true, INDEX_NAME)); + return null; + }) + .when(mockIndicesAdminClient) + .create(any(CreateIndexRequest.class), any(ActionListener.class)); + + ActionListener actionListener = + new ActionListener<>() { + @Override + public void onResponse(CreateIndexResponse createIndexResponse) { + logger.info("Mock successful index creation"); + assertTrue(createIndexResponse.isAcknowledged()); + } + + @Override + public void onFailure(Exception e) { + logger.error("Mock error creating index: {}", e.toString()); + } + }; try { this.wazuhIndices.putIndex(INDEX_NAME); @@ -134,11 +141,15 @@ public void onFailure(Exception e) { fail(e.toString()); } - doAnswer(invocation -> { - ActionListener listener = invocation.getArgument(1); - listener.onFailure(new Exception("Mock Exception")); - return null; - }).when(mockIndicesAdminClient).create(any(CreateIndexRequest.class), any(ActionListener.class)); + doAnswer( + invocation -> { + ActionListener listener = + invocation.getArgument(1); + listener.onFailure(new Exception("Mock Exception")); + return null; + }) + .when(mockIndicesAdminClient) + .create(any(CreateIndexRequest.class), any(ActionListener.class)); try { this.wazuhIndices.putIndex(INDEX_NAME); @@ -147,9 +158,7 @@ public void onFailure(Exception e) { } } - /** - * Tests the indexExists() method - */ + /** Tests the indexExists() method */ public void testIndexExists() { ClusterState mockClusterState = mock(ClusterState.class); RoutingTable mockRoutingTable = mock(RoutingTable.class); diff --git a/plugins/setup/src/test/java/com/wazuh/setup/index/WazuhIndicesTests.java b/plugins/setup/src/test/java/com/wazuh/setup/index/WazuhIndicesTests.java index 980f20b..90ed211 100644 --- a/plugins/setup/src/test/java/com/wazuh/setup/index/WazuhIndicesTests.java +++ b/plugins/setup/src/test/java/com/wazuh/setup/index/WazuhIndicesTests.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -7,9 +8,6 @@ */ package com.wazuh.setup.index; -import com.wazuh.setup.utils.IndexTemplateUtils; -import org.junit.Before; -import org.mockito.*; import org.opensearch.action.admin.indices.create.CreateIndexRequest; import org.opensearch.action.admin.indices.create.CreateIndexResponse; import org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest; @@ -21,43 +19,38 @@ import org.opensearch.cluster.routing.RoutingTable; import org.opensearch.cluster.service.ClusterService; import org.opensearch.test.OpenSearchTestCase; +import org.junit.Before; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import com.wazuh.setup.utils.IndexTemplateUtils; +import org.mockito.*; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; public class WazuhIndicesTests extends OpenSearchTestCase { - @Mock - private Client client; + @Mock private Client client; - @Mock - private ClusterService clusterService; + @Mock private ClusterService clusterService; - @Mock - private AdminClient adminClient; + @Mock private AdminClient adminClient; - @Mock - private IndicesAdminClient indicesAdminClient; + @Mock private IndicesAdminClient indicesAdminClient; - @Mock - private ClusterState clusterState; + @Mock private ClusterState clusterState; - @Mock - private RoutingTable routingTable; + @Mock private RoutingTable routingTable; - @InjectMocks - private WazuhIndices wazuhIndices; + @InjectMocks private WazuhIndices wazuhIndices; - @Captor - private ArgumentCaptor putIndexTemplateRequestCaptor; + @Captor private ArgumentCaptor putIndexTemplateRequestCaptor; - @Captor - private ArgumentCaptor createIndexRequestCaptor; + @Captor private ArgumentCaptor createIndexRequestCaptor; @Before public void setup() { @@ -76,7 +69,8 @@ public void setup() { this.wazuhIndices = new WazuhIndices(this.client, this.clusterService); } - // FIXME The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks + // FIXME The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static + // mocks // adding mockito-inline seems to have no effect @AwaitsFix(bugUrl = "") public void testPutTemplate_Successful() { @@ -88,8 +82,11 @@ public void testPutTemplate_Successful() { template.put("index_patterns", new HashMap<>()); // Mock the static method call - try (MockedStatic mockedStatic = Mockito.mockStatic(IndexTemplateUtils.class)) { - mockedStatic.when(() -> IndexTemplateUtils.fromFile(eq(templateName + ".json"))).thenReturn(template); + try (MockedStatic mockedStatic = + Mockito.mockStatic(IndexTemplateUtils.class)) { + mockedStatic + .when(() -> IndexTemplateUtils.fromFile(eq(templateName + ".json"))) + .thenReturn(template); when(indicesAdminClient.putTemplate(any(PutIndexTemplateRequest.class)).actionGet()) .thenReturn(mock(AcknowledgedResponse.class)); @@ -107,7 +104,8 @@ public void testPutTemplate_Successful() { } } - // FIXME The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks + // FIXME The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static + // mocks // adding mockito-inline seems to have no effect @AwaitsFix(bugUrl = "") public void testPutTemplate_IOException() { @@ -115,8 +113,11 @@ public void testPutTemplate_IOException() { String templateName = "index-template-agent"; // Mock the static method to throw IOException - try (MockedStatic mockedStatic = Mockito.mockStatic(IndexTemplateUtils.class)) { - mockedStatic.when(() -> IndexTemplateUtils.fromFile(eq(templateName + ".json"))).thenThrow(IOException.class); + try (MockedStatic mockedStatic = + Mockito.mockStatic(IndexTemplateUtils.class)) { + mockedStatic + .when(() -> IndexTemplateUtils.fromFile(eq(templateName + ".json"))) + .thenThrow(IOException.class); // Act wazuhIndices.putTemplate(templateName); @@ -126,16 +127,13 @@ public void testPutTemplate_IOException() { } } - // FIXME the return value of "org.opensearch.client.IndicesAdminClient.create(org.opensearch.action.admin.indices.create.CreateIndexRequest)" is null + // FIXME the return value of + // "org.opensearch.client.IndicesAdminClient.create(org.opensearch.action.admin.indices.create.CreateIndexRequest)" is null @AwaitsFix(bugUrl = "") public void testPutIndex_IndexDoesNotExist() { // Arrange String indexName = ".agents"; - CreateIndexResponse createIndexResponse = new CreateIndexResponse( - true, - true, - indexName - ); + CreateIndexResponse createIndexResponse = new CreateIndexResponse(true, true, indexName); when(routingTable.hasIndex(indexName)).thenReturn(false); when(indicesAdminClient.create(any(CreateIndexRequest.class)).actionGet()) @@ -151,7 +149,6 @@ public void testPutIndex_IndexDoesNotExist() { assertEquals(indexName, capturedRequest.index()); } - public void testPutIndex_IndexExists() { // Arrange String indexName = ".agents"; @@ -164,7 +161,6 @@ public void testPutIndex_IndexExists() { verify(indicesAdminClient, never()).create(any(CreateIndexRequest.class)); } - public void testIndexExists() { // Arrange String indexName = ".agents"; @@ -177,7 +173,6 @@ public void testIndexExists() { assertTrue(exists); } - @AwaitsFix(bugUrl = "") public void testInitialize() throws IOException { // Arrange @@ -204,4 +199,3 @@ public void testInitialize() throws IOException { verify(indicesAdminClient).create(any(CreateIndexRequest.class)); } } - diff --git a/plugins/setup/src/yamlRestTest/java/com/wazuh/setup/SetupPluginClientYamlTestSuiteIT.java b/plugins/setup/src/yamlRestTest/java/com/wazuh/setup/SetupPluginClientYamlTestSuiteIT.java index e80e110..c3608d4 100644 --- a/plugins/setup/src/yamlRestTest/java/com/wazuh/setup/SetupPluginClientYamlTestSuiteIT.java +++ b/plugins/setup/src/yamlRestTest/java/com/wazuh/setup/SetupPluginClientYamlTestSuiteIT.java @@ -1,4 +1,5 @@ /* + * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to @@ -9,10 +10,10 @@ import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; + import org.opensearch.test.rest.yaml.ClientYamlTestCandidate; import org.opensearch.test.rest.yaml.OpenSearchClientYamlSuiteTestCase; - public class SetupPluginClientYamlTestSuiteIT extends OpenSearchClientYamlSuiteTestCase { public SetupPluginClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) {