use of org.opensearch.action.ActionResponse in project anomaly-detection by opensearch-project.
the class IndexAnomalyDetectorActionHandlerTests method testUpdateTemplate.
@SuppressWarnings("unchecked")
private void testUpdateTemplate(String fieldTypeName) throws IOException {
String field = "a";
AnomalyDetector detector = TestHelpers.randomAnomalyDetectorUsingCategoryFields(detectorId, Arrays.asList(field));
SearchResponse detectorResponse = mock(SearchResponse.class);
int totalHits = 9;
when(detectorResponse.getHits()).thenReturn(TestHelpers.createSearchHits(totalHits));
GetResponse getDetectorResponse = TestHelpers.createGetResponse(detector, detector.getDetectorId(), AnomalyDetector.ANOMALY_DETECTORS_INDEX);
SearchResponse userIndexResponse = mock(SearchResponse.class);
int userIndexHits = 0;
when(userIndexResponse.getHits()).thenReturn(TestHelpers.createSearchHits(userIndexHits));
// extend NodeClient since its execute method is final and mockito does not allow to mock final methods
// we can also use spy to overstep the final methods
NodeClient client = new NodeClient(Settings.EMPTY, threadPool) {
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
try {
if (action.equals(SearchAction.INSTANCE)) {
assertTrue(request instanceof SearchRequest);
SearchRequest searchRequest = (SearchRequest) request;
if (searchRequest.indices()[0].equals(ANOMALY_DETECTORS_INDEX)) {
listener.onResponse((Response) detectorResponse);
} else {
listener.onResponse((Response) userIndexResponse);
}
} else if (action.equals(GetAction.INSTANCE)) {
assertTrue(request instanceof GetRequest);
listener.onResponse((Response) getDetectorResponse);
} else {
GetFieldMappingsResponse response = new GetFieldMappingsResponse(TestHelpers.createFieldMappings(detector.getIndices().get(0), field, fieldTypeName));
listener.onResponse((Response) response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
NodeClient clientSpy = spy(client);
ClusterName clusterName = new ClusterName("test");
ClusterState clusterState = ClusterState.builder(clusterName).metadata(Metadata.builder().build()).build();
when(clusterService.state()).thenReturn(clusterState);
handler = new IndexAnomalyDetectorActionHandler(clusterService, clientSpy, transportService, channel, anomalyDetectionIndices, detectorId, seqNo, primaryTerm, refreshPolicy, detector, requestTimeout, maxSingleEntityAnomalyDetectors, maxMultiEntityAnomalyDetectors, maxAnomalyFeatures, RestRequest.Method.PUT, xContentRegistry(), null, adTaskManager, searchFeatureDao);
ArgumentCaptor<Exception> response = ArgumentCaptor.forClass(Exception.class);
handler.start();
verify(clientSpy, times(1)).execute(eq(GetFieldMappingsAction.INSTANCE), any(), any());
verify(channel).onFailure(response.capture());
Exception value = response.getValue();
if (fieldTypeName.equals(CommonName.IP_TYPE) || fieldTypeName.equals(CommonName.KEYWORD_TYPE)) {
assertTrue(value.getMessage().contains(IndexAnomalyDetectorActionHandler.NO_DOCS_IN_USER_INDEX_MSG));
} else {
assertTrue(value.getMessage().contains(IndexAnomalyDetectorActionHandler.CATEGORICAL_FIELD_TYPE_ERR_MSG));
}
}
use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.
the class RestCancellableNodeClient method doExecute.
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
CloseListener closeListener = httpChannels.computeIfAbsent(httpChannel, channel -> new CloseListener());
TaskHolder taskHolder = new TaskHolder();
Task task = client.executeLocally(action, request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
try {
closeListener.unregisterTask(taskHolder);
} finally {
listener.onResponse(response);
}
}
@Override
public void onFailure(Exception e) {
try {
closeListener.unregisterTask(taskHolder);
} finally {
listener.onFailure(e);
}
}
});
final TaskId taskId = new TaskId(client.getLocalNodeId(), task.getId());
closeListener.registerTask(taskHolder, taskId);
closeListener.maybeRegisterChannel(httpChannel);
}
use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.
the class ParentTaskAssigningClientTests method testSetsParentId.
public void testSetsParentId() {
TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAlphaOfLength(3), randomLong()) };
// This mock will do nothing but verify that parentTaskId is set on all requests sent to it.
NoOpClient mock = new NoOpClient(getTestName()) {
@Override
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
assertEquals(parentTaskId[0], request.getParentTask());
super.doExecute(action, request, listener);
}
};
try (ParentTaskAssigningClient client = new ParentTaskAssigningClient(mock, parentTaskId[0])) {
// All of these should have the parentTaskId set
client.bulk(new BulkRequest());
client.search(new SearchRequest());
client.clearScroll(new ClearScrollRequest());
// Now lets verify that unwrapped calls don't have the parentTaskId set
parentTaskId[0] = TaskId.EMPTY_TASK_ID;
client.unwrap().bulk(new BulkRequest());
client.unwrap().search(new SearchRequest());
client.unwrap().clearScroll(new ClearScrollRequest());
}
}
use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.
the class OriginSettingClientTests method testSetsParentId.
public void testSetsParentId() {
String origin = randomAlphaOfLength(7);
/*
* This mock will do nothing but verify that origin is set in the
* thread context before executing the action.
*/
NoOpClient mock = new NoOpClient(getTestName()) {
@Override
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(ActionType<Response> action, Request request, ActionListener<Response> listener) {
assertEquals(origin, threadPool().getThreadContext().getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME));
super.doExecute(action, request, listener);
}
};
try (OriginSettingClient client = new OriginSettingClient(mock, origin)) {
// All of these should have the origin set
client.bulk(new BulkRequest());
client.search(new SearchRequest());
client.clearScroll(new ClearScrollRequest());
ThreadContext threadContext = client.threadPool().getThreadContext();
client.bulk(new BulkRequest(), listenerThatAssertsOriginNotSet(threadContext));
client.search(new SearchRequest(), listenerThatAssertsOriginNotSet(threadContext));
client.clearScroll(new ClearScrollRequest(), listenerThatAssertsOriginNotSet(threadContext));
}
}
use of org.opensearch.action.ActionResponse in project OpenSearch by opensearch-project.
the class TransportActionFilterChainTests method testTooManyContinueProcessingRequest.
public void testTooManyContinueProcessingRequest() throws InterruptedException {
final int additionalContinueCount = randomInt(10);
RequestTestFilter testFilter = new RequestTestFilter(randomInt(), new RequestCallback() {
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void execute(Task task, String action, Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> actionFilterChain) {
for (int i = 0; i <= additionalContinueCount; i++) {
actionFilterChain.proceed(task, action, request, listener);
}
}
});
Set<ActionFilter> filters = new HashSet<>();
filters.add(testFilter);
String actionName = randomAlphaOfLength(randomInt(30));
ActionFilters actionFilters = new ActionFilters(filters);
TransportAction<TestRequest, TestResponse> transportAction = new TransportAction<TestRequest, TestResponse>(actionName, actionFilters, new TaskManager(Settings.EMPTY, threadPool, Collections.emptySet())) {
@Override
protected void doExecute(Task task, TestRequest request, ActionListener<TestResponse> listener) {
listener.onResponse(new TestResponse());
}
};
final CountDownLatch latch = new CountDownLatch(additionalContinueCount + 1);
final AtomicInteger responses = new AtomicInteger();
final List<Throwable> failures = new CopyOnWriteArrayList<>();
transportAction.execute(new TestRequest(), new LatchedActionListener<>(new ActionListener<TestResponse>() {
@Override
public void onResponse(TestResponse testResponse) {
responses.incrementAndGet();
}
@Override
public void onFailure(Exception e) {
failures.add(e);
}
}, latch));
if (!latch.await(10, TimeUnit.SECONDS)) {
fail("timeout waiting for the filter to notify the listener as many times as expected");
}
assertThat(testFilter.runs.get(), equalTo(1));
assertThat(testFilter.lastActionName, equalTo(actionName));
assertThat(responses.get(), equalTo(1));
assertThat(failures.size(), equalTo(additionalContinueCount));
for (Throwable failure : failures) {
assertThat(failure, instanceOf(IllegalStateException.class));
}
}
Aggregations