Skip to content

Commit 439b2e5

Browse files
dsmileyclaudenick-boss-tech
authored
SOLR-18537: Proxy requests to a node via X-Solr-targetNode (#5112)
Any request can now be routed to a specific SolrCloud node by setting the `X-Solr-targetNode` header (or, for GET requests, a query parameter of the same name). The receiving node proxies the request there. This is useful for reaching a particular node behind a load balancer, including for node-level admin APIs. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Nick Shanin <nick.boss.us@gmail.com>
1 parent d5d7df9 commit 439b2e5

9 files changed

Lines changed: 665 additions & 8 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
title: >
2+
Any request can now be routed to a specific SolrCloud node by setting the `X-Solr-targetNode` header
3+
(or, for GET requests, a query parameter of the same name). The receiving node proxies the request there.
4+
This is useful for reaching a particular node behind a load balancer, including for node-level admin APIs.
5+
type: added
6+
authors:
7+
- name: David Smiley
8+
links:
9+
- name: SOLR-18537
10+
url: https://issues.apache.org/jira/browse/SOLR-18537

‎solr/core/src/java/org/apache/solr/servlet/HttpSolrCall.java‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.io.EOFException;
3636
import java.io.IOException;
3737
import java.lang.invoke.MethodHandles;
38+
import java.net.URI;
3839
import java.nio.charset.StandardCharsets;
3940
import java.util.ArrayList;
4041
import java.util.Collection;
@@ -643,13 +644,14 @@ protected void sendRemoteProxy() throws IOException {
643644
updatedQueryParams.set(INTERNAL_REQUEST_COUNT, forwardCount);
644645
String queryStr = updatedQueryParams.toQueryString();
645646

646-
String coreUrlAndPath = coreUrl + path;
647-
log.info("Proxying request to: {}", coreUrlAndPath);
647+
log.info("Proxying request to: {}{}", coreUrl, path);
648648
try {
649+
// path is decoded, so encode it
650+
URI uri = URI.create(coreUrl + new URI(null, null, path, null).getRawPath() + queryStr);
649651
response.reset(); // clear all headers and status
650652
HttpClient httpClient =
651653
((HttpJettySolrClient) cores.getDefaultHttpSolrClient()).getHttpClient();
652-
HttpSolrProxy.doHttpProxy(httpClient, req, response, coreUrlAndPath + queryStr);
654+
HttpSolrProxy.doHttpProxy(httpClient, req, response, uri);
653655
} catch (Exception e) {
654656
// note: don't handle interruption differently; we are stopping
655657
sendError(

‎solr/core/src/java/org/apache/solr/servlet/HttpSolrProxy.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import jakarta.servlet.http.HttpServletResponse;
2222
import java.io.IOException;
2323
import java.io.OutputStream;
24+
import java.net.URI;
2425
import java.nio.ByteBuffer;
2526
import java.util.EnumSet;
2627
import java.util.Set;
@@ -60,10 +61,7 @@ class HttpSolrProxy {
6061
private static final Set<String> NO_BODY_METHODS = Set.of("GET", "HEAD", "DELETE");
6162

6263
static void doHttpProxy(
63-
HttpClient httpClient,
64-
HttpServletRequest servletReq,
65-
HttpServletResponse servletRsp,
66-
String url)
64+
HttpClient httpClient, HttpServletRequest servletReq, HttpServletResponse servletRsp, URI url)
6765
throws Throwable {
6866
Request proxyReq = httpClient.newRequest(url).method(servletReq.getMethod());
6967

Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.solr.servlet;
19+
20+
import static org.apache.solr.common.SolrException.ErrorCode.BAD_REQUEST;
21+
import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
22+
import static org.apache.solr.common.SolrException.ErrorCode.SERVICE_UNAVAILABLE;
23+
24+
import jakarta.servlet.FilterChain;
25+
import jakarta.servlet.ServletException;
26+
import jakarta.servlet.UnavailableException;
27+
import jakarta.servlet.http.HttpServletRequest;
28+
import jakarta.servlet.http.HttpServletRequestWrapper;
29+
import jakarta.servlet.http.HttpServletResponse;
30+
import java.io.IOException;
31+
import java.lang.invoke.MethodHandles;
32+
import java.net.URI;
33+
import java.util.ArrayList;
34+
import java.util.Collections;
35+
import java.util.Enumeration;
36+
import java.util.List;
37+
import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
38+
import org.apache.solr.common.SolrException;
39+
import org.apache.solr.common.cloud.ZkStateReader;
40+
import org.apache.solr.common.params.ModifiableSolrParams;
41+
import org.apache.solr.common.params.SolrParams;
42+
import org.apache.solr.core.CoreContainer;
43+
import org.eclipse.jetty.client.HttpClient;
44+
import org.slf4j.Logger;
45+
import org.slf4j.LoggerFactory;
46+
47+
/**
48+
* If the request carries the {@link #TARGET_NODE_HEADER} header naming a different live node,
49+
* proxies the request there verbatim and returns; otherwise passes the request through. Unlike
50+
* {@link HttpSolrCall}'s collection/core-driven proxying, this works for any endpoint, including
51+
* node-level ones (e.g. {@code /solr/admin/**}, {@code /api/node/**}), so a request can be pinned
52+
* to a specific node even when reached through a load balancer that hides which node answers.
53+
*/
54+
public class NodeTargetProxyFilter extends CoreContainerAwareHttpFilter {
55+
56+
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
57+
58+
/**
59+
* Header naming a live node (as it appears in ZK live_nodes) to proxy this request to. Two
60+
* shorthand forms are also accepted, both resolved relative to the current node: a value of all
61+
* digits replaces the trailing {@code -<digits>} ordinal in the current node's hostname (e.g.
62+
* {@code 8} turns {@code myhost-3.mydomain.com:3000} into {@code myhost-8.mydomain.com:3000});
63+
* otherwise, a value with no '.' or ':' is treated as a bare peer hostname, with the current
64+
* node's domain suffix and port appended.
65+
*/
66+
public static final String TARGET_NODE_HEADER = "X-Solr-targetNode";
67+
68+
@Override
69+
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
70+
throws IOException, ServletException {
71+
72+
String targetNode = req.getHeader(TARGET_NODE_HEADER);
73+
74+
// also accept it as a query param on GET requests, for convenience when a header can't
75+
// easily be set (e.g. a browser address bar)
76+
String queryString = req.getQueryString();
77+
if ("GET".equals(req.getMethod())
78+
&& queryString != null
79+
&& queryString.contains(TARGET_NODE_HEADER)) { // cheap; avoid double-parse
80+
SolrParams params = SolrRequestParsers.parseQueryString(queryString);
81+
String paramTargetNode = params.get(TARGET_NODE_HEADER);
82+
if (paramTargetNode != null) {
83+
if (targetNode != null) {
84+
res.sendError(400, TARGET_NODE_HEADER + " must EITHER be a header or url param");
85+
return;
86+
}
87+
targetNode = paramTargetNode;
88+
queryString = filterQueryString(params);
89+
}
90+
}
91+
92+
// wrap the request to filter out the header & param.
93+
// NOTE: we assume downstream processing only accesses such data via what we override !!
94+
if (targetNode != null) {
95+
final List<String> headerNames = filterHeaderNamesToList(req); // cheap
96+
final String finalQueryString = queryString; // filtered already if needed
97+
req =
98+
new HttpServletRequestWrapper(req) {
99+
@Override
100+
public Enumeration<String> getHeaderNames() {
101+
return Collections.enumeration(headerNames);
102+
}
103+
104+
@Override
105+
public String getQueryString() {
106+
return finalQueryString;
107+
}
108+
};
109+
}
110+
111+
if (targetNode != null && !targetNode.isBlank() && proxyToNode(targetNode, req, res)) {
112+
return;
113+
}
114+
chain.doFilter(req, res);
115+
}
116+
117+
private static List<String> filterHeaderNamesToList(HttpServletRequest req) {
118+
List<String> headerNames = new ArrayList<>();
119+
var headerNamesEnum = req.getHeaderNames();
120+
while (headerNamesEnum.hasMoreElements()) {
121+
String headerName = headerNamesEnum.nextElement();
122+
if (!headerName.equalsIgnoreCase(TARGET_NODE_HEADER)) {
123+
headerNames.add(headerName);
124+
}
125+
}
126+
return headerNames;
127+
}
128+
129+
private static String filterQueryString(SolrParams params) {
130+
ModifiableSolrParams modifiableSolrParams = ModifiableSolrParams.of(params);
131+
modifiableSolrParams.remove(TARGET_NODE_HEADER);
132+
String queryString = modifiableSolrParams.toQueryString();
133+
if (queryString.startsWith("?")) {
134+
queryString = queryString.substring(1);
135+
}
136+
return queryString; // could be empty string
137+
}
138+
139+
/**
140+
* Returns true if the request was handled here: proxied to {@code targetNode}, or answered with
141+
* an error. Reports errors itself, since an exception would be treated by {@link
142+
* AuthenticationFilter}, our caller, as an authentication failure.
143+
*/
144+
private boolean proxyToNode(String targetNode, HttpServletRequest req, HttpServletResponse res)
145+
throws IOException {
146+
CoreContainer cores;
147+
try {
148+
cores = getCores();
149+
} catch (UnavailableException e) {
150+
res.sendError(SERVICE_UNAVAILABLE.code, "Core Container Unavailable");
151+
return true;
152+
}
153+
if (!cores.isZooKeeperAware()) {
154+
// note: we could adapt this filter to support standalone mode with AllowListUrlChecker
155+
res.sendError(BAD_REQUEST.code, TARGET_NODE_HEADER + " header/param requires SolrCloud");
156+
return true;
157+
}
158+
String ownNodeName = cores.getZkController().getNodeName();
159+
String resolvedNode = resolvePeerShorthand(targetNode, ownNodeName);
160+
ZkStateReader zkStateReader = cores.getZkController().getZkStateReader();
161+
if (!zkStateReader.getClusterState().getLiveNodes().contains(resolvedNode)) {
162+
res.sendError(BAD_REQUEST.code, "Unknown or non-live node: " + resolvedNode);
163+
return true;
164+
}
165+
if (resolvedNode.equals(ownNodeName)) {
166+
return false; // already on the target node; let it process normally
167+
}
168+
169+
URI uri;
170+
try {
171+
uri = targetUri(zkStateReader.getBaseUrlForNodeName(resolvedNode), req);
172+
} catch (SolrException e) {
173+
res.sendError(e.code(), e.getMessage());
174+
return true;
175+
} catch (IllegalArgumentException e) {
176+
res.sendError(BAD_REQUEST.code, "Invalid request URI");
177+
return true;
178+
}
179+
try {
180+
HttpClient httpClient =
181+
((HttpJettySolrClient) cores.getDefaultHttpSolrClient()).getHttpClient();
182+
HttpSolrProxy.doHttpProxy(httpClient, req, res, uri);
183+
} catch (Exception e) {
184+
log.warn("Error proxying request to node {}", resolvedNode, e);
185+
res.sendError(SERVER_ERROR.code, "Error proxying request to node: " + resolvedNode);
186+
} catch (Error e) {
187+
throw e;
188+
} catch (Throwable e) {
189+
throw new RuntimeException(e);
190+
}
191+
return true;
192+
}
193+
194+
/**
195+
* The request's URI on another node. The path is reused as received (still encoded). The query is
196+
* re-encoded because Jetty accepts characters in it, like '{' or '|', that a URI rejects.
197+
*/
198+
private static URI targetUri(String baseUrl, HttpServletRequest req) {
199+
String query = req.getQueryString();
200+
query = query == null ? "" : SolrRequestParsers.parseQueryString(query).toQueryString();
201+
return URI.create(baseUrl + pathAfterContext(req) + query);
202+
}
203+
204+
/** The still-encoded request path with the context path removed. Starts with "/". */
205+
private static String pathAfterContext(HttpServletRequest req) {
206+
return req.getRequestURI().substring(req.getContextPath().length());
207+
}
208+
209+
/**
210+
* If {@code targetNode} is all digits, it's an ordinal shorthand: {@code ownNodeName}'s first
211+
* hostname label is expected to end in {@code -<digits>}, which gets replaced. Otherwise, if it
212+
* has no '.' or ':', it's a bare peer hostname; expand it using {@code ownNodeName}'s domain
213+
* suffix and {@code :port_context}. Otherwise, returned unchanged.
214+
*/
215+
static String resolvePeerShorthand(String targetNode, String ownNodeName) {
216+
if (targetNode.contains(".") || targetNode.contains(":")) {
217+
return targetNode; // already a full node name
218+
}
219+
int colonIdx = ownNodeName.indexOf(':');
220+
String ownHost = ownNodeName.substring(0, colonIdx);
221+
String portAndContext = ownNodeName.substring(colonIdx);
222+
int dotIdx = ownHost.indexOf('.');
223+
String domainSuffix = dotIdx >= 0 ? ownHost.substring(dotIdx) : "";
224+
225+
if (targetNode.matches("\\d+")) {
226+
String firstLabel = dotIdx >= 0 ? ownHost.substring(0, dotIdx) : ownHost;
227+
targetNode = firstLabel.replaceFirst("-\\d+$", "-" + targetNode);
228+
}
229+
230+
return targetNode + domainSuffix + portAndContext;
231+
}
232+
}

0 commit comments

Comments
 (0)