Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix no permission to create model/task index bug;add security IT for train/predict API #177

Merged
merged 3 commits into from
Mar 9, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@

import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.admin.indices.create.CreateIndexResponse;
import org.opensearch.client.Client;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.common.xcontent.XContentType;

@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
Expand Down Expand Up @@ -87,19 +89,24 @@ public void initMLTaskIndex(ActionListener<Boolean> listener) {

public void initMLIndexIfAbsent(String indexName, String mapping, ActionListener<Boolean> listener) {
if (!clusterService.state().metadata().hasIndex(indexName)) {
CreateIndexRequest request = new CreateIndexRequest(indexName).mapping("_doc", mapping, XContentType.JSON);

client.admin().indices().create(request, ActionListener.wrap(r -> {
if (r.isAcknowledged()) {
log.info("create index:{}", indexName);
listener.onResponse(true);
} else {
listener.onResponse(false);
}
}, e -> {
log.error("Failed to create index " + indexName, e);
try (ThreadContext.StoredContext threadContext = client.threadPool().getThreadContext().stashContext()) {
ActionListener<CreateIndexResponse> actionListener = ActionListener.wrap(r -> {
if (r.isAcknowledged()) {
log.info("create index:{}", indexName);
listener.onResponse(true);
} else {
listener.onResponse(false);
}
}, e -> {
log.error("Failed to create index " + indexName, e);
listener.onFailure(e);
});
CreateIndexRequest request = new CreateIndexRequest(indexName).mapping("_doc", mapping, XContentType.JSON);
client.admin().indices().create(request, ActionListener.runBefore(actionListener, () -> threadContext.restore()));
amitgalitz marked this conversation as resolved.
Show resolved Hide resolved
} catch (Exception e) {
log.error("Failed to init index " + indexName, e);
listener.onFailure(e);
}));
}
} else {
log.info("index:{} is already created", indexName);
listener.onResponse(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,10 +260,10 @@ protected Response ingestIrisData(String indexName) throws IOException {
protected void validateStats(
FunctionName functionName,
ActionName actionName,
int expectedTotalFailureCount,
int expectedTotalAlgoFailureCount,
int expectedMinumnTotalRequestCount,
int expectedTotalAlgoRequestCount
int expectedMinimumTotalFailureCount,
int expectedMinimumTotalAlgoFailureCount,
int expectedMinimumTotalRequestCount,
int expectedMinimumTotalAlgoRequestCount
) throws IOException {
Response statsResponse = TestHelper.makeRequest(client(), "GET", "_plugins/_ml/stats", null, "", null);
HttpEntity entity = statsResponse.getEntity();
Expand Down Expand Up @@ -291,10 +291,10 @@ protected void validateStats(
totalAlgoRequestCount += (Double) nodeStatsMap.get(requestCountStat);
}
}
assertEquals(expectedTotalFailureCount, totalFailureCount);
assertEquals(expectedTotalAlgoFailureCount, totalAlgoFailureCount);
assertTrue(totalRequestCount >= expectedMinumnTotalRequestCount);
assertEquals(expectedTotalAlgoRequestCount, totalAlgoRequestCount);
assertTrue(totalFailureCount >= expectedMinimumTotalFailureCount);
assertTrue(totalAlgoFailureCount >= expectedMinimumTotalAlgoFailureCount);
assertTrue(totalRequestCount >= expectedMinimumTotalRequestCount);
assertTrue(totalAlgoRequestCount >= expectedMinimumTotalAlgoRequestCount);
}

protected Response ingestModelData() throws IOException {
Expand Down Expand Up @@ -464,4 +464,67 @@ public void trainAndPredict(
function.accept(predictionResult);
}
}

public void train(
RestClient client,
FunctionName functionName,
String indexName,
MLAlgoParams params,
SearchSourceBuilder searchSourceBuilder,
Consumer<Map<String, Object>> function,
boolean async
) throws IOException {
MLInputDataset inputData = SearchQueryInputDataset
.builder()
.indices(ImmutableList.of(indexName))
.searchSourceBuilder(searchSourceBuilder)
.build();
MLInput kmeansInput = MLInput.builder().algorithm(functionName).parameters(params).inputDataset(inputData).build();
String endpoint = "/_plugins/_ml/_train/" + functionName.name().toLowerCase(Locale.ROOT);
amitgalitz marked this conversation as resolved.
Show resolved Hide resolved
if (async) {
endpoint += "?async=true";
}
Response response = TestHelper.makeRequest(client, "POST", endpoint, ImmutableMap.of(), TestHelper.toHttpEntity(kmeansInput), null);
verifyResponse(function, response);
}

public void predict(
RestClient client,
FunctionName functionName,
String modelId,
String indexName,
MLAlgoParams params,
SearchSourceBuilder searchSourceBuilder,
Consumer<Map<String, Object>> function
) throws IOException {
MLInputDataset inputData = SearchQueryInputDataset
.builder()
.indices(ImmutableList.of(indexName))
.searchSourceBuilder(searchSourceBuilder)
.build();
MLInput kmeansInput = MLInput.builder().algorithm(functionName).parameters(params).inputDataset(inputData).build();
String endpoint = "/_plugins/_ml/_predict/" + functionName.name().toLowerCase(Locale.ROOT) + "/" + modelId;
Response response = TestHelper.makeRequest(client, "POST", endpoint, ImmutableMap.of(), TestHelper.toHttpEntity(kmeansInput), null);
verifyResponse(function, response);
}

public void getModel(RestClient client, String modelId, Consumer<Map<String, Object>> function) throws IOException {
Response response = TestHelper.makeRequest(client, "GET", "/_plugins/_ml/models/" + modelId, null, "", null);
verifyResponse(function, response);
}

public void getTask(RestClient client, String taskId, Consumer<Map<String, Object>> function) throws IOException {
Response response = TestHelper.makeRequest(client, "GET", "/_plugins/_ml/tasks/" + taskId, null, "", null);
verifyResponse(function, response);
}

private void verifyResponse(Consumer<Map<String, Object>> function, Response response) throws IOException {
ylwu-amzn marked this conversation as resolved.
Show resolved Hide resolved
HttpEntity entity = response.getEntity();
assertNotNull(response);
String entityString = TestHelper.httpEntityToString(entity);
Map<String, Object> map = gson.fromJson(entityString, Map.class);
if (function != null) {
function.accept(map);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opensearch.common.Strings;
import org.opensearch.rest.RestHandler;
Expand All @@ -27,20 +26,17 @@ public void setup() {
restMLGetModelAction = new RestMLGetModelAction();
}

@Test
public void testConstructor() {
RestMLGetModelAction mlGetModelAction = new RestMLGetModelAction();
assertNotNull(mlGetModelAction);
}

@Test
public void testGetName() {
String actionName = restMLGetModelAction.getName();
assertFalse(Strings.isNullOrEmpty(actionName));
assertEquals("ml_get_model_action", actionName);
}

@Test
public void testRoutes() {
List<RestHandler.Route> routes = restMLGetModelAction.routes();
assertNotNull(routes);
Expand Down
52 changes: 52 additions & 0 deletions plugin/src/test/java/org/opensearch/ml/rest/SecureMLRestIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import org.apache.http.HttpHost;
import org.junit.After;
Expand All @@ -20,6 +21,7 @@
import org.opensearch.index.query.MatchAllQueryBuilder;
import org.opensearch.ml.common.parameter.FunctionName;
import org.opensearch.ml.common.parameter.KMeansParams;
import org.opensearch.ml.common.parameter.MLTaskState;
import org.opensearch.search.builder.SearchSourceBuilder;

public class SecureMLRestIT extends MLCommonsRestTestCase {
Expand Down Expand Up @@ -142,4 +144,54 @@ public void testTrainAndPredictWithFullAccess() throws IOException {
}
);
}

public void testTrainModelWithFullAccessThenPredict() throws IOException {
KMeansParams kMeansParams = KMeansParams.builder().build();
// train model
train(mlFullAccessClient, FunctionName.KMEANS, irisIndex, kMeansParams, searchSourceBuilder, trainResult -> {
String modelId = (String) trainResult.get("model_id");
assertNotNull(modelId);
String status = (String) trainResult.get("status");
assertEquals(MLTaskState.COMPLETED.name(), status);
try {
getModel(mlFullAccessClient, modelId, model -> {
String algorithm = (String) model.get("algorithm");
assertEquals(FunctionName.KMEANS.name(), algorithm);
});
} catch (IOException e) {
assertNull(e);
}
try {
// predict with trained model
predict(mlFullAccessClient, FunctionName.KMEANS, modelId, irisIndex, kMeansParams, searchSourceBuilder, predictResult -> {
String predictStatus = (String) predictResult.get("status");
assertEquals(MLTaskState.COMPLETED.name(), predictStatus);
Map<String, Object> predictionResult = (Map<String, Object>) predictResult.get("prediction_result");
ArrayList rows = (ArrayList) predictionResult.get("rows");
assertTrue(rows.size() > 1);
amitgalitz marked this conversation as resolved.
Show resolved Hide resolved
});
} catch (IOException e) {
assertNull(e);
}
}, false);
}

public void testTrainModelInAsyncWayWithFullAccess() throws IOException {
train(mlFullAccessClient, FunctionName.KMEANS, irisIndex, KMeansParams.builder().build(), searchSourceBuilder, trainResult -> {
assertFalse(trainResult.containsKey("model_id"));
String taskId = (String) trainResult.get("task_id");
assertNotNull(taskId);
String status = (String) trainResult.get("status");
assertEquals(MLTaskState.CREATED.name(), status);
try {
getTask(mlFullAccessClient, taskId, task -> {
String algorithm = (String) task.get("function_name");
assertEquals(FunctionName.KMEANS.name(), algorithm);
});
} catch (IOException e) {
ylwu-amzn marked this conversation as resolved.
Show resolved Hide resolved
assertNull(e);
}
}, true);
}

}