forked from opensearch-project/OpenSearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestSendToExtensionAction.java
173 lines (156 loc) · 7.22 KB
/
RestSendToExtensionAction.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
* 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 org.opensearch.extensions.rest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.client.node.NodeClient;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.extensions.DiscoveryExtension;
import org.opensearch.extensions.ExtensionsOrchestrator;
import org.opensearch.rest.BaseRestHandler;
import org.opensearch.rest.BytesRestResponse;
import org.opensearch.rest.RestRequest;
import org.opensearch.rest.RestRequest.Method;
import org.opensearch.rest.RestStatus;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.TransportException;
import org.opensearch.transport.TransportResponseHandler;
import org.opensearch.transport.TransportService;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableList;
/**
* An action that forwards REST requests to an extension
*/
public class RestSendToExtensionAction extends BaseRestHandler {
private static final String SEND_TO_EXTENSION_ACTION = "send_to_extension_action";
private static final Logger logger = LogManager.getLogger(RestSendToExtensionAction.class);
private final List<Route> routes;
private final String uriPrefix;
private final DiscoveryExtension discoveryExtension;
private final TransportService transportService;
/**
* Instantiates this object using a {@link RegisterRestActionsRequest} to populate the routes.
*
* @param restActionsRequest A request encapsulating a list of Strings with the API methods and URIs.
* @param transportService The OpenSearch transport service
* @param discoveryExtension The extension node to which to send actions
*/
public RestSendToExtensionAction(
RegisterRestActionsRequest restActionsRequest,
DiscoveryExtension discoveryExtension,
TransportService transportService
) {
this.uriPrefix = "/_extensions/_" + restActionsRequest.getUniqueId();
List<Route> restActionsAsRoutes = new ArrayList<>();
for (String restAction : restActionsRequest.getRestActions()) {
RestRequest.Method method;
String uri;
try {
int delim = restAction.indexOf(' ');
method = RestRequest.Method.valueOf(restAction.substring(0, delim));
uri = uriPrefix + restAction.substring(delim).trim();
} catch (IndexOutOfBoundsException | IllegalArgumentException e) {
throw new IllegalArgumentException(restAction + " does not begin with a valid REST method");
}
logger.info("Registering: " + method + " " + uri);
restActionsAsRoutes.add(new Route(method, uri));
}
this.routes = unmodifiableList(restActionsAsRoutes);
this.discoveryExtension = discoveryExtension;
this.transportService = transportService;
}
@Override
public String getName() {
return SEND_TO_EXTENSION_ACTION;
}
@Override
public List<Route> routes() {
return this.routes;
}
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
Method method = request.getHttpRequest().method();
String uri = request.getHttpRequest().uri();
if (uri.startsWith(uriPrefix)) {
uri = uri.substring(uriPrefix.length());
}
String message = "Forwarding the request " + method + " " + uri + " to " + discoveryExtension;
logger.info(message);
// Initialize response. Values will be changed in the handler.
final RestExecuteOnExtensionResponse restExecuteOnExtensionResponse = new RestExecuteOnExtensionResponse(
RestStatus.INTERNAL_SERVER_ERROR,
BytesRestResponse.TEXT_CONTENT_TYPE,
message.getBytes(StandardCharsets.UTF_8),
emptyMap()
);
final CountDownLatch inProgressLatch = new CountDownLatch(1);
final TransportResponseHandler<RestExecuteOnExtensionResponse> restExecuteOnExtensionResponseHandler = new TransportResponseHandler<
RestExecuteOnExtensionResponse>() {
@Override
public RestExecuteOnExtensionResponse read(StreamInput in) throws IOException {
return new RestExecuteOnExtensionResponse(in);
}
@Override
public void handleResponse(RestExecuteOnExtensionResponse response) {
logger.info("Received response from extension: {}", response.getStatus());
restExecuteOnExtensionResponse.setStatus(response.getStatus());
restExecuteOnExtensionResponse.setContentType(response.getContentType());
restExecuteOnExtensionResponse.setContent(response.getContent());
restExecuteOnExtensionResponse.setHeaders(response.getHeaders());
inProgressLatch.countDown();
}
@Override
public void handleException(TransportException exp) {
logger.debug("REST request failed", exp);
// Status is already defaulted to 500 (INTERNAL_SERVER_ERROR)
byte[] responseBytes = ("Request failed: " + exp.getMessage()).getBytes(StandardCharsets.UTF_8);
restExecuteOnExtensionResponse.setContent(responseBytes);
inProgressLatch.countDown();
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
};
try {
transportService.sendRequest(
discoveryExtension,
ExtensionsOrchestrator.REQUEST_REST_EXECUTE_ON_EXTENSION_ACTION,
new RestExecuteOnExtensionRequest(method, uri),
restExecuteOnExtensionResponseHandler
);
try {
inProgressLatch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return channel -> channel.sendResponse(
new BytesRestResponse(RestStatus.REQUEST_TIMEOUT, "No response from extension to request.")
);
}
} catch (Exception e) {
logger.info("Failed to send REST Actions to extension " + discoveryExtension.getName(), e);
}
BytesRestResponse restResponse = new BytesRestResponse(
restExecuteOnExtensionResponse.getStatus(),
restExecuteOnExtensionResponse.getContentType(),
restExecuteOnExtensionResponse.getContent()
);
for (Entry<String, List<String>> headerEntry : restExecuteOnExtensionResponse.getHeaders().entrySet()) {
for (String value : headerEntry.getValue()) {
restResponse.addHeader(headerEntry.getKey(), value);
}
}
return channel -> channel.sendResponse(restResponse);
}
}