Skip to content

Commit

Permalink
Apply format-related changes requested by spotless formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
QU3B1M committed Oct 16, 2024
1 parent 1f439d1 commit 5a308e8
Show file tree
Hide file tree
Showing 23 changed files with 417 additions and 453 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.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;
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.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";
Expand All @@ -63,8 +64,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 @@ -81,8 +81,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 logger = 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 {
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;
}
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();
logger.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()) {
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<String>) 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);
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 @@ -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";
Expand All @@ -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<String> args, String version) {
Expand Down Expand Up @@ -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
+ '\''
+ '}';
}
}
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 @@ -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";
Expand Down Expand Up @@ -63,8 +62,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws

@Override
public String toString() {
return "Agent{" +
"groups=" + groups +
'}';
return "Agent{" + "groups=" + groups + '}';
}
}
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,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";
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
+ '}';
}
}
Loading

0 comments on commit 5a308e8

Please sign in to comment.