Skip to content

Commit

Permalink
Apply spotless formatting to command-manager classes
Browse files Browse the repository at this point in the history
  • Loading branch information
QU3B1M committed Oct 16, 2024
1 parent 1fde567 commit 301cd26
Show file tree
Hide file tree
Showing 7 changed files with 213 additions and 216 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
Expand All @@ -7,10 +8,6 @@
*/
package com.wazuh.commandmanager;

import com.wazuh.commandmanager.index.CommandIndex;
import com.wazuh.commandmanager.rest.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;
Expand Down Expand Up @@ -38,11 +35,15 @@
import java.util.List;
import java.util.function.Supplier;

import com.wazuh.commandmanager.index.CommandIndex;
import com.wazuh.commandmanager.rest.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/_command_manager";
Expand All @@ -64,8 +65,7 @@ public Collection<Object> createComponents(
NodeEnvironment nodeEnvironment,
NamedWriteableRegistry namedWriteableRegistry,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<RepositoriesService> repositoriesServiceSupplier
) {
Supplier<RepositoriesService> repositoriesServiceSupplier) {
this.commandIndex = new CommandIndex(client, clusterService, threadPool);

// HttpRestClient stuff
Expand All @@ -82,8 +82,7 @@ public List<RestHandler> getRestHandlers(
IndexScopedSettings indexScopedSettings,
SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster
) {
Supplier<DiscoveryNodes> nodesInCluster) {
return Collections.singletonList(new RestPostCommandAction(this.commandIndex));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
Expand All @@ -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;
Expand All @@ -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 log = LogManager.getLogger(CommandIndex.class);
Expand All @@ -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;
Expand All @@ -69,30 +69,31 @@ public CompletableFuture<RestStatus> asyncCreate(Document document) {
} else {
log.info(
"Index template {} already exists. Skipping creation.",
CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME
);
CommandManagerPlugin.COMMAND_MANAGER_INDEX_TEMPLATE_NAME);
}

log.info("Indexing command with id [{}]", document.getId());
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) {
log.error(
"Error indexing command with id [{}] due to {}", document.getId(), e);
log.error("Error indexing command with id [{}] due to {}", document.getId(), e);
}
return future;
}
Expand All @@ -104,10 +105,8 @@ public CompletableFuture<RestStatus> asyncCreate(Document document) {
* @return whether the index template exists.
*/
public boolean indexTemplateExists(String template_name) {
Map<String, IndexTemplateMetadata> templates = this.clusterService
.state()
.metadata()
.templates();
Map<String, IndexTemplateMetadata> templates =
this.clusterService.state().metadata().templates();
log.debug("Existing index templates: {} ", templates);

return templates.containsKey(template_name);
Expand All @@ -124,25 +123,25 @@ public void putIndexTemplate(String templateName) {
// @throws IOException
Map<String, Object> template = IndexTemplateUtils.fromFile(templateName + ".json");

PutIndexTemplateRequest putIndexTemplateRequest = new PutIndexTemplateRequest()
.mapping(IndexTemplateUtils.get(template, "mappings"))
.settings(IndexTemplateUtils.get(template, "settings"))
.name(templateName)
.patterns((List<String>) template.get("index_patterns"));

executor.submit(() -> {
AcknowledgedResponse acknowledgedResponse = this.client
.admin()
.indices()
.putTemplate(putIndexTemplateRequest)
.actionGet();
if (acknowledgedResponse.isAcknowledged()) {
log.info(
"Index template [{}] created successfully",
templateName
);
}
});
PutIndexTemplateRequest putIndexTemplateRequest =
new PutIndexTemplateRequest()
.mapping(IndexTemplateUtils.get(template, "mappings"))
.settings(IndexTemplateUtils.get(template, "settings"))
.name(templateName)
.patterns((List<String>) template.get("index_patterns"));

executor.submit(
() -> {
AcknowledgedResponse acknowledgedResponse =
this.client
.admin()
.indices()
.putTemplate(putIndexTemplateRequest)
.actionGet();
if (acknowledgedResponse.isAcknowledged()) {
log.info("Index template [{}] created successfully", templateName);
}
});

} catch (IOException e) {
log.error("Error reading index template [{}] from filesystem", templateName);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
Expand All @@ -12,11 +13,12 @@
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 java.util.ArrayList;

import reactor.util.annotation.NonNull;

public class Command implements ToXContentObject {
public static final String COMMAND = "command";
public static final String ORDER_ID = "order_id";
Expand All @@ -37,19 +39,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;
Expand All @@ -65,10 +66,11 @@ public Command(
*
* @param parser XContentParser from the Rest Request
* @return instance of Command
* @throws IOException error parsing request content
* @throws IOException error parsing request content
* @throws IllegalArgumentException missing arguments
*/
public static Command parse(XContentParser parser) throws IOException, IllegalArgumentException {
public static Command parse(XContentParser parser)
throws IOException, IllegalArgumentException {
String source = null;
Target target = null;
Integer timeout = null;
Expand Down Expand Up @@ -121,13 +123,7 @@ public static Command parse(XContentParser parser) throws IOException, IllegalAr
if (!nullArguments.isEmpty()) {
throw new IllegalArgumentException("Missing arguments: " + nullArguments);
} else {
return new Command(
source,
target,
timeout,
user,
action
);
return new Command(source, target, timeout, user, action);
}
}

Expand All @@ -148,15 +144,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
+ '}';
}
}
Loading

0 comments on commit 301cd26

Please sign in to comment.