Skip to content
Closed
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 @@ -30,7 +30,7 @@ public interface HaDispatchMessages {
@Message(level = MessageLevel.INFO, text = "Could not connect to server: {0} {1}")
void errorConnectingToServer(String uri, @StackTrace(level = MessageLevel.DEBUG) Exception e);

@Message(level = MessageLevel.INFO, text = "Failing over request to a different server: {0}")
@Message(level = MessageLevel.INFO, text = "Failing over request to a different server from: {0}")
void failingOverRequest(String uri);

@Message(level = MessageLevel.INFO, text = "Failed to connect to: {0}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,10 @@
limitations under the License.
Comment thread
risdenk marked this conversation as resolved.
-->
<rules>
<!-- These should be removed at some point since Livy
doesn't have /v1 in the REST API specification -->
<rule dir="IN" name="LIVYSERVER/livy/root/v1/inbound/" pattern="*://*:*/**/livy/v1">
<rule dir="IN" name="LIVYSERVER/livy/root/inbound" pattern="*://*:*/**/livy/v1">
<rewrite template="{$serviceUrl[LIVYSERVER]}"/>
</rule>
<rule dir="IN" name="LIVYSERVER/livy/path/v1/inbound" pattern="*://*:*/**/livy/v1/{path=**}?{**}">
<rule dir="IN" name="LIVYSERVER/livy/path/inbound" pattern="*://*:*/**/livy/v1/{path=**}?{**}">
<rewrite template="{$serviceUrl[LIVYSERVER]}/{path=**}?{**}"/>
</rule>

<!-- Prefer these rules without v1 in the url -->
<rule dir="IN" name="LIVYSERVER/livy/root/inbound" pattern="*://*:*/**/livy">
<rewrite template="{$serviceUrl[LIVYSERVER]}"/>
</rule>
<rule dir="IN" name="LIVYSERVER/livy/path/inbound" pattern="*://*:*/**/livy/{path=**}?{**}">
<rewrite template="{$serviceUrl[LIVYSERVER]}/{path=**}?{**}"/>
</rule>

<rule dir="OUT" name="LIVYSERVER/livy/outbound/sparkurl" pattern="*://*:*/proxy/{**}">
<rewrite template="{$frontend[url]}/yarn/proxy/{**}"/>
</rule>

<rule dir="OUT" name="LIVYSERVER/livy/outbound/logs" pattern="{scheme}://{host}:{port}/node/containerlogs/{**}?{**}">
<rewrite template="{$frontend[url]}/yarn/nodemanager/node/containerlogs/{**}?{**}?{scheme}?host={$hostmap(host)}?{port}"/>
</rule>

<rule dir="OUT" name="LIVYSERVER/livy/outbound/logs2" pattern="{scheme}://{host}:{port}/node/containerlogs/{**}">
<rewrite template="{$frontend[url]}/yarn/nodemanager/node/containerlogs/{**}?{scheme}?host={$hostmap(host)}?{port}"/>
</rule>

</rules>
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
-->
<service role="LIVYSERVER" name="livy" version="0.4.0">

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most likely going to want a new version of the service definitions instead of just modifying what is there. I don't think 0.4.0 of Livy had HA redirects.

<routes>
<route path="/livy/**?**"/>
<route path="/livy"/>
<route path="/livy/"/>
<route path="/livy/v1/**?**"/>
<route path="/livy/v1"/>
<route path="/livy/v1/"/>
Comment thread
risdenk marked this conversation as resolved.
Outdated
</routes>
<dispatch classname="org.apache.knox.gateway.livy.LivyDispatch"/>
<dispatch classname="org.apache.knox.gateway.livy.LivyDispatch" ha-classname="org.apache.knox.gateway.rm.dispatch.LivyHaDispatch"/>
</service>
14 changes: 13 additions & 1 deletion gateway-service-livy/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
<description>The extension to the gateway for supporting Livy.</description>

<dependencies>
<dependency>
<groupId>org.apache.knox</groupId>
<artifactId>gateway-i18n</artifactId>
</dependency>
<dependency>
<groupId>org.apache.knox</groupId>
<artifactId>gateway-spi</artifactId>
Expand All @@ -38,7 +42,10 @@
<groupId>org.apache.knox</groupId>
<artifactId>gateway-provider-rewrite</artifactId>
</dependency>

<dependency>
<groupId>org.apache.knox</groupId>
<artifactId>gateway-provider-ha</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
Expand All @@ -58,5 +65,10 @@
<artifactId>gateway-test-utils</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Comment thread
risdenk marked this conversation as resolved.
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.knox.gateway.livy;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.knox.gateway.dispatch.DefaultDispatch;
import org.apache.knox.gateway.filter.AbstractGatewayFilter;
import org.apache.knox.gateway.ha.provider.HaProvider;
import org.apache.knox.gateway.ha.provider.impl.HaServiceConfigConstants;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.livy.i18n.RMMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

class LivyHaBaseDispatcher extends DefaultDispatch {
Comment thread
risdenk marked this conversation as resolved.
Outdated
private static final String FAILOVER_COUNTER_ATTRIBUTE = "dispatch.ha.failover.counter";
private static final String LOCATION = "Location";
private static final RMMessages LOG = MessagesFactory.get(RMMessages.class);
Comment thread
risdenk marked this conversation as resolved.
Outdated
private int maxFailoverAttempts = HaServiceConfigConstants.DEFAULT_MAX_FAILOVER_ATTEMPTS;
private int failoverSleep = HaServiceConfigConstants.DEFAULT_FAILOVER_SLEEP;
private String resourceRole = null;
private HttpResponse inboundResponse = null;

/**
*
* @return HttpReponse used for unit testing so we
* can inject inboundResponse before calling executeRequest method
*/
private HttpResponse getInboundResponse() {
HttpResponse response = this.inboundResponse;
this.setInboundResponse(null);
return response;
}

void setInboundResponse(HttpResponse inboundResponse) {
this.inboundResponse = inboundResponse;
}

void setHaProvider(HaProvider haProvider) {
this.haProvider = haProvider;
}

private HaProvider haProvider;

void setMaxFailoverAttempts(int maxFailoverAttempts) {
this.maxFailoverAttempts = maxFailoverAttempts;
}

void setFailoverSleep(int failoverSleep) {
this.failoverSleep = failoverSleep;
}

void setResourceRole(String resourceRole) {
this.resourceRole = resourceRole;
}

@Override
protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
HttpResponse inboundResponse = this.getInboundResponse();
try {
if( this.getInboundResponse() == null ) {
inboundResponse = executeOutboundRequest(outboundRequest);
}
writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
} catch (StandbyException e) {
LOG.errorReceivedFromStandbyNode(e);
failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
} catch (IOException e) {
LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
}
}

/**
* Checks for specific outbound response codes/content to trigger a retry or failover
*/
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
int status = inboundResponse.getStatusLine().getStatusCode();
if ( status == 403 || status == 307) {
BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
inboundResponse.setEntity(entity);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inboundResponse.getEntity().writeTo(outputStream);
String body = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
if (body.contains("This is a standby Livy Instance")) {
throw new StandbyException();
}
}
super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}

private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception) throws IOException {
LOG.failingOverRequest(outboundRequest.getURI().toString());
URI uri;
String outboundURIs;
AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
if (counter == null) {
counter = new AtomicInteger(0);
}
inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
outboundURIs = outboundRequest.getURI().toString();

if (counter.incrementAndGet() <= maxFailoverAttempts) {
//null out target url so that rewriters run again
inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);

uri = getUriFromInbound(inboundRequest, inboundResponse, outboundURIs);
((HttpRequestBase) outboundRequest).setURI(uri);
if (failoverSleep > 0) {
try {
Thread.sleep(failoverSleep);
} catch (InterruptedException e) {
LOG.failoverSleepFailed(this.resourceRole, e);
}
}
executeRequest(outboundRequest, inboundRequest, outboundResponse);
} else {
LOG.maxFailoverAttemptsReached(maxFailoverAttempts, this.resourceRole);
if (inboundResponse != null) {
writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
} else {
throw new IOException(exception);
}
}
}

URI getUriFromInbound(HttpServletRequest inboundRequest, HttpResponse inboundResponse, String outboundURIs) {
URI uri;
if( outboundURIs != null ) {
markFailedURL(outboundURIs);
}
try {
if( inboundResponse != null ) {
// We get redirection URI, failover condition we don't
// need to consult list of host.
String host = inboundResponse.getFirstHeader(LOCATION).getValue();
LOG.failoverRedirect(host);
uri = URI.create(host);
} else { // inboundRequest was null previous active node is down
// get next URI in list to try.
uri = getDispatchUrl(inboundRequest);
}
} catch(Exception ex ) {
uri = getDispatchUrl(inboundRequest);
}
haProvider.setActiveURL(this.resourceRole, uri.toString());
return uri;
}

private void markFailedURL(String outboundURIs) {
haProvider.markFailedURL(this.resourceRole, outboundURIs);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.knox.gateway.livy;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRequestStream;
import org.apache.knox.gateway.security.SubjectUtils;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.livy.i18n.RMMessages;
import org.apache.knox.gateway.config.Configure;
import org.apache.knox.gateway.ha.provider.HaProvider;
import org.apache.knox.gateway.ha.provider.HaServiceConfig;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* This specialized dispatch provides Livy specific features to the
* default dispatch.
*/
public class LivyHaDispatch extends LivyHaBaseDispatcher {
private static final String RESOURCE_ROLE = "RESOURCEMANAGER";
private HaProvider haProvider;

private static final RMMessages LOG = MessagesFactory.get(RMMessages.class);

Comment thread
risdenk marked this conversation as resolved.
Outdated
public LivyHaDispatch() {
super();
}
@Configure
public void setHaProvider(HaProvider haProvider) {
this.haProvider = haProvider;
}

@Override
public void doPost(URI url, HttpServletRequest request, HttpServletResponse response)
throws IOException, URISyntaxException {
super.doPost(url, new LivyHttpServletRequest(request), response);
}

@Override
public void init() {
super.init();
if (haProvider != null) {
super.setResourceRole(RESOURCE_ROLE);
HaServiceConfig serviceConfig = haProvider.getHaDescriptor().getServiceConfig(RESOURCE_ROLE);
super.setMaxFailoverAttempts( serviceConfig.getMaxFailoverAttempts());
super.setFailoverSleep( serviceConfig.getFailoverSleep());
super.setHaProvider(haProvider);
}
}

/**
* HttpServletRequest that adds or sets the proxyUser parameter on the json body
*/
private class LivyHttpServletRequest extends HttpServletRequestWrapper {
private final List<String> proxyUserEndpoints = Arrays.asList("/batches", "/sessions");

LivyHttpServletRequest(HttpServletRequest request) {
super(request);
}

@Override
public ServletInputStream getInputStream() throws IOException {
ServletInputStream inputStream = super.getInputStream();

HttpServletRequest request = (HttpServletRequest)getRequest();
String requestURI = request.getRequestURI();
if(matchProxyUserEndpoints(requestURI)) {
// Parse the json object from the request
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = objectMapper.readValue(inputStream, new TypeReference<Map<String,Object>>(){});

// Force the proxyUser to be set to the remote user
jsonMap.put("proxyUser", SubjectUtils.getCurrentEffectivePrincipalName());

// Create the new ServletInputStream with modified json map.
String s = objectMapper.writeValueAsString(jsonMap);
return new UrlRewriteRequestStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
}

return inputStream;
}
Comment thread
RogPodge marked this conversation as resolved.

private boolean matchProxyUserEndpoints(String requestURI) {
for(String endpoint : proxyUserEndpoints) {
if(requestURI.endsWith(endpoint) || requestURI.endsWith(endpoint + '/')) {
return true;
}
}
return false;
}

@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
}
}
}

Loading