|
| 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