mirror of
https://github.com/NationalSecurityAgency/timely.git
synced 2026-11-09 17:36:01 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ecbba6daf | ||
|
|
dcf6e604a1 | ||
|
|
bfbbad3b2d |
No files matched your search
+2
-3
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-analytics</artifactId>
|
||||
<!--
|
||||
@@ -68,7 +68,6 @@
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<compilerId>jdt</compilerId>
|
||||
@@ -77,7 +76,7 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.tycho</groupId>
|
||||
<artifactId>tycho-compiler-jdt</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<version>0.21.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
|
||||
@@ -66,7 +66,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
||||
LOG.info("Opening summarization job.");
|
||||
super.open(parameters);
|
||||
client = new WebSocketSubscriptionClient(jp.getTimelyHostname(), jp.getTimelyHttpsPort(), jp.getTimelyWssPort(),
|
||||
jp.isClientAuth(), jp.isDoLogin(), jp.getTimelyUsername(), jp.getTimelyPassword(), jp.getKeyStoreFile(),
|
||||
jp.isDoLogin(), jp.getTimelyUsername(), jp.getTimelyPassword(), jp.getKeyStoreFile(),
|
||||
jp.getKeyStoreType(), jp.getKeyStorePass(), jp.getTrustStoreFile(), jp.getTrustStoreType(),
|
||||
jp.getTrustStorePass(), jp.isHostVerificationEnabled(), jp.getBufferSize());
|
||||
}
|
||||
@@ -96,7 +96,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
||||
|
||||
@Override
|
||||
public void onOpen(Session session, EndpointConfig config) {
|
||||
session.addMessageHandler(String.class, new MessageHandler.Whole<String>() {
|
||||
session.addMessageHandler(new MessageHandler.Whole<String>() {
|
||||
|
||||
private final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH");
|
||||
private long lastWatermarkTime = 0L;
|
||||
|
||||
@@ -67,7 +67,7 @@ public class SummarizationJob {
|
||||
})
|
||||
.name("Metric Windows")
|
||||
.addSink(
|
||||
new SocketClientSink<MetricHistogram>(jp.getTimelyHostname(), jp.getTimelyTcpPort(),
|
||||
new SocketClientSink<MetricHistogram>(jp.getTimelyHostname(), jp.getTimelyTcpPort(),
|
||||
new MetricHistogram(), 2, true) {
|
||||
|
||||
private final Logger LOG = LoggerFactory
|
||||
|
||||
@@ -18,7 +18,6 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
||||
private final int timelyTcpPort;
|
||||
private final int timelyHttpsPort;
|
||||
private final int timelyWssPort;
|
||||
private final boolean clientAuth;
|
||||
private final boolean doLogin;
|
||||
private final String timelyUsername;
|
||||
private final String timelyPassword;
|
||||
@@ -41,7 +40,6 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
||||
timelyTcpPort = params.getInt("timelyTcpPort", 4241);
|
||||
timelyHttpsPort = params.getInt("timelyHttpsPort", 4242);
|
||||
timelyWssPort = params.getInt("timelyWssPort", 4243);
|
||||
clientAuth = params.getBoolean("clientAuth", false);
|
||||
doLogin = params.getBoolean("doLogin", false);
|
||||
timelyUsername = params.get("timelyUsername", null);
|
||||
timelyPassword = params.get("timelyPassword", null);
|
||||
@@ -71,7 +69,6 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
||||
timelyTcpPort = conf.getInteger("timelyTcpPort", 4241);
|
||||
timelyHttpsPort = conf.getInteger("timelyHttpsPort", 4242);
|
||||
timelyWssPort = conf.getInteger("timelyWssPort", 4243);
|
||||
clientAuth = conf.getBoolean("clientAuth", false);
|
||||
doLogin = conf.getBoolean("doLogin", false);
|
||||
timelyUsername = conf.getString("timelyUsername", null);
|
||||
timelyPassword = conf.getString("timelyPassword", null);
|
||||
@@ -115,10 +112,6 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
||||
return timelyWssPort;
|
||||
}
|
||||
|
||||
public boolean isClientAuth() {
|
||||
return clientAuth;
|
||||
}
|
||||
|
||||
public boolean isDoLogin() {
|
||||
return doLogin;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/bin/bash
|
||||
#!/bin/bash -vx
|
||||
|
||||
if [[ `uname` == "Darwin" ]]; then
|
||||
THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0`
|
||||
@@ -27,14 +27,15 @@ fi
|
||||
mkdir -p ${NATIVE_DIR}
|
||||
|
||||
pushd ${BASE_DIR}/bin
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative-boringssl-static*.jar META-INF/native/libnetty_tcnative_linux_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-all*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative*.jar META-INF/native/libnetty_tcnative.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-transport-native-epoll*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
popd
|
||||
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*:${HADOOP_CONF_DIR}"
|
||||
JVM_ARGS="-Xmx1G -Xms1G -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS} -Dlog4j.configurationFile=${CONF_DIR}/log4j2-spring.xml"
|
||||
JVM_ARGS="-Xmx1G -Xms1G -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS}"
|
||||
JVM_ARGS="${JVM_ARGS} -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}/libnetty-${TCNATIVE_SUFFIX}"
|
||||
|
||||
#JVM_ARGS="${JVM_ARGS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
|
||||
|
||||
|
||||
+17
-39
@@ -11,33 +11,21 @@
|
||||
|
||||
<beans:bean id="x509PrincipalExtractor" class="org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor">
|
||||
<beans:property name="subjectDnRegex" value="CN=(.*?)(?:,|$)"/>
|
||||
</beans:bean>
|
||||
</beans:bean>
|
||||
|
||||
<beans:bean id="timelyUserDetailsService" class="timely.auth.UserDetailsService">
|
||||
<beans:property name="users">
|
||||
<util:list>
|
||||
<beans:bean class="timely.auth.TimelyUser">
|
||||
<beans:constructor-arg name="subjectDn">
|
||||
<beans:value>CN=example.com</beans:value>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="auths">
|
||||
<util:list>
|
||||
<beans:value>D</beans:value>
|
||||
<beans:value>E</beans:value>
|
||||
<beans:value>F</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="roles">
|
||||
<util:list>
|
||||
<beans:value>G</beans:value>
|
||||
<beans:value>H</beans:value>
|
||||
<beans:value>I</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
</beans:bean>
|
||||
</util:list>
|
||||
</beans:property>
|
||||
</beans:bean>
|
||||
<beans:bean id="timelyUserDetailsService" class="timely.auth.UserDetailsService">
|
||||
<beans:property name="users">
|
||||
<util:map key-type="java.lang.String">
|
||||
<beans:entry key="example.com">
|
||||
<util:list>
|
||||
<beans:value>D</beans:value>
|
||||
<beans:value>E</beans:value>
|
||||
<beans:value>F</beans:value>
|
||||
</util:list>
|
||||
</beans:entry>
|
||||
</util:map>
|
||||
</beans:property>
|
||||
</beans:bean>
|
||||
|
||||
<beans:bean id="x509AuthorizationProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
|
||||
<beans:property name="preAuthenticatedUserDetailsService" ref="timelyUserDetailsService" />
|
||||
@@ -46,12 +34,9 @@
|
||||
<user-service id="usernamePasswordService">
|
||||
<user name="test" password="test1" authorities="A,B,C" />
|
||||
</user-service>
|
||||
|
||||
<beans:bean id="noOpPasswordEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"/>
|
||||
|
||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
|
||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
<beans:property name="userDetailsService" ref="usernamePasswordService"/>
|
||||
<beans:property name="passwordEncoder" ref="noOpPasswordEncoder"/>
|
||||
</beans:bean>
|
||||
|
||||
<authentication-manager alias="authenticationManager">
|
||||
@@ -60,12 +45,5 @@
|
||||
<!-- Basic authorization provider, validates provided username and password -->
|
||||
<authentication-provider ref="UserNamePasswordAuthenticationProvider" />
|
||||
</authentication-manager>
|
||||
|
||||
<util:list id="requiredRoles" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
|
||||
<util:list id="requiredAuths" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
|
||||
</beans:beans>
|
||||
@@ -8,10 +8,7 @@ timely-balancer:
|
||||
assignmentFile: /timely/balancer/assignments.csv
|
||||
security:
|
||||
session-max-age: 86400
|
||||
cache-expiration-minutes: 60
|
||||
cache-refresh-minutes: 5
|
||||
allow-anonymous-http-access: true
|
||||
allow-anonymous-ws-access: true
|
||||
allow-anonymous-access: true
|
||||
serverSsl:
|
||||
certificate-file:
|
||||
key-file:
|
||||
@@ -34,7 +31,7 @@ timely-balancer:
|
||||
nonCachedMetrics:
|
||||
server:
|
||||
ip: 127.0.0.1
|
||||
tcpPort: 4242
|
||||
tcp-port: 4242
|
||||
numTcpPools: 1
|
||||
tcpBufferSize: 100
|
||||
tcpClientPool:
|
||||
@@ -54,7 +51,7 @@ timely-balancer:
|
||||
jmxEnabled: true
|
||||
testOnBorrow: false
|
||||
testOnReturn: false
|
||||
udpPort: 4245
|
||||
udp-port: 4245
|
||||
udpClientPool:
|
||||
minIdlePerKey: 0
|
||||
maxIdlePerKey: 40
|
||||
@@ -111,7 +108,6 @@ timely-balancer:
|
||||
flush-interval-seconds: 30
|
||||
scanner-read-ahead: 1
|
||||
subscription-batch-size: 5000
|
||||
incomingBufferSize: 50000000
|
||||
wsClientPool:
|
||||
minIdlePerKey: 0
|
||||
maxIdlePerKey: 40
|
||||
|
||||
+44
-3
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-balancer</artifactId>
|
||||
<dependencies>
|
||||
@@ -161,7 +161,9 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<artifactId>netty-tcnative</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
<classifier>${os.detected.classifier}</classifier>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -199,6 +201,11 @@
|
||||
<artifactId>spring-boot-test-autoconfigure</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-common</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
@@ -245,8 +252,9 @@
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<artifactId>netty-tcnative</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
<classifier>${os.detected.classifier}</classifier>
|
||||
<type>jar</type>
|
||||
<overWrite>false</overWrite>
|
||||
<outputDirectory>${project.build.directory}/native</outputDirectory>
|
||||
@@ -288,4 +296,37 @@
|
||||
</extension>
|
||||
</extensions>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>native-epoll-linux</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>!mac</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<version>${version.netty}</version>
|
||||
<classifier>linux-x86_64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>native-epoll</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>mac</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<version>${version.netty}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
Vendored
+1
-1
@@ -33,7 +33,7 @@
|
||||
<directory>${project.basedir}/bin</directory>
|
||||
<outputDirectory>bin</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
<include>*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
|
||||
@@ -25,7 +25,6 @@ import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.WriteBufferWaterMark;
|
||||
import io.netty.channel.epoll.EpollChannelOption;
|
||||
import io.netty.channel.epoll.EpollDatagramChannel;
|
||||
import io.netty.channel.epoll.EpollEventLoopGroup;
|
||||
@@ -57,7 +56,6 @@ import io.netty.handler.stream.ChunkedWriteHandler;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import io.netty.util.NettyRuntime;
|
||||
import io.netty.util.internal.SystemPropertyUtil;
|
||||
import org.apache.accumulo.core.conf.AccumuloConfiguration;
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
@@ -66,10 +64,8 @@ import org.apache.zookeeper.CreateMode;
|
||||
import org.apache.zookeeper.data.Stat;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import timely.auth.AuthCache;
|
||||
import timely.balancer.configuration.BalancerConfiguration;
|
||||
import timely.balancer.configuration.ClientSsl;
|
||||
import timely.balancer.configuration.SpringBootstrap;
|
||||
@@ -95,7 +91,7 @@ import timely.netty.tcp.TcpDecoder;
|
||||
import timely.netty.tcp.TcpVersionHandler;
|
||||
import timely.netty.udp.UdpDecoder;
|
||||
import timely.netty.udp.UdpPacketToByteBuf;
|
||||
import timely.netty.websocket.WebSocketFullRequestHandler;
|
||||
import timely.netty.websocket.WebSocketHttpCookieHandler;
|
||||
import timely.netty.websocket.WebSocketRequestDecoder;
|
||||
import timely.netty.websocket.subscription.WSTimelyExceptionHandler;
|
||||
|
||||
@@ -146,7 +142,7 @@ public class Balancer {
|
||||
}
|
||||
|
||||
protected static ConfigurableApplicationContext initializeConfiguration(String[] args) {
|
||||
return new SpringApplicationBuilder(SpringBootstrap.class).web(WebApplicationType.NONE).run(args);
|
||||
return new SpringApplicationBuilder(SpringBootstrap.class).web(false).run(args);
|
||||
}
|
||||
|
||||
private void shutdownHook() {
|
||||
@@ -361,14 +357,11 @@ public class Balancer {
|
||||
|
||||
// start curator framework
|
||||
RetryPolicy retryPolicy = new RetryForever(1000);
|
||||
int timeout = Long.valueOf(AccumuloConfiguration.getTimeInMillis(balancerConfig.getZooKeeper().getTimeout()))
|
||||
.intValue();
|
||||
curatorFramework = CuratorFrameworkFactory.newClient(balancerConfig.getZooKeeper().getServers(), timeout, 10000,
|
||||
curatorFramework = CuratorFrameworkFactory.newClient(balancerConfig.getZooKeeper().getServers(), 30000, 1000,
|
||||
retryPolicy);
|
||||
curatorFramework.start();
|
||||
ensureZkPaths(curatorFramework, zkPaths);
|
||||
|
||||
AuthCache.configure(balancerConfig.getSecurity());
|
||||
final boolean useEpoll = useEpoll();
|
||||
Class<? extends ServerSocketChannel> channelClass;
|
||||
Class<? extends Channel> datagramChannelClass;
|
||||
@@ -434,8 +427,7 @@ public class Balancer {
|
||||
httpServer.group(httpBossGroup, httpWorkerGroup);
|
||||
httpServer.channel(channelClass);
|
||||
httpServer.handler(new LoggingHandler());
|
||||
HttpClientPool httpClientPool = new HttpClientPool(balancerConfig.getSecurity(), balancerConfig.getHttp(),
|
||||
clientSSLContext);
|
||||
HttpClientPool httpClientPool = new HttpClientPool(balancerConfig, clientSSLContext);
|
||||
httpServer.childHandler(setupHttpChannel(balancerConfig, sslCtx, metricResolver, httpClientPool));
|
||||
httpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||
httpServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||
@@ -454,9 +446,10 @@ public class Balancer {
|
||||
wsServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||
wsServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||
wsServer.option(ChannelOption.SO_KEEPALIVE, true);
|
||||
/* Not sure if next two lines are necessary */
|
||||
/* Not sure if next three lines are necessary */
|
||||
wsServer.option(ChannelOption.SO_SNDBUF, 1048576);
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(620145, 838860));
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 838860);
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 620145);
|
||||
wsChannelHandle = wsServer.bind(wsIp, wsPort).sync().channel();
|
||||
final String wsAddress = ((InetSocketAddress) wsChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||
|
||||
@@ -514,14 +507,15 @@ public class Balancer {
|
||||
ch.pipeline().addLast("decoder", new HttpRequestDecoder());
|
||||
ch.pipeline().addLast("compressor", new HttpContentCompressor());
|
||||
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
||||
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
|
||||
ch.pipeline().addLast("queryDecoder", new timely.netty.http.HttpRequestDecoder(
|
||||
balancerConfig.getSecurity(), balancerConfig.getHttp()));
|
||||
ch.pipeline().addLast("fileServer", new HttpStaticFileServerHandler());
|
||||
ch.pipeline().addLast("login",
|
||||
new X509LoginRequestHandler(balancerConfig.getSecurity(), balancerConfig.getHttp()));
|
||||
ch.pipeline().addLast("httpRelay", new HttpRelayHandler(metricResolver, httpClientPool));
|
||||
ch.pipeline().addLast("httpRelay",
|
||||
new HttpRelayHandler(balancerConfig, metricResolver, httpClientPool));
|
||||
ch.pipeline().addLast("error", new TimelyExceptionHandler());
|
||||
}
|
||||
};
|
||||
@@ -535,7 +529,7 @@ public class Balancer {
|
||||
ch.pipeline().addLast("logger", new LoggingHandler());
|
||||
ch.pipeline().addLast("packetDecoder", new UdpPacketToByteBuf());
|
||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("putDecoder", new UdpDecoder());
|
||||
ch.pipeline().addLast("udpRelayHandler", new UdpRelayHandler(metricResolver, udpClientPool));
|
||||
}
|
||||
@@ -548,7 +542,7 @@ public class Balancer {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("putDecoder", new TcpDecoder());
|
||||
ch.pipeline().addLast("tcpRelayHandler", new TcpRelayHandler(metricResolver, tcpClientPools));
|
||||
ch.pipeline().addLast("versionHandler", new TcpVersionHandler());
|
||||
@@ -564,13 +558,13 @@ public class Balancer {
|
||||
protected void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
|
||||
ch.pipeline().addLast("httpServer", new HttpServerCodec());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast("sessionExtractor", new WebSocketFullRequestHandler());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
||||
ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(balancerConfig.getSecurity()));
|
||||
|
||||
ch.pipeline().addLast("idle-handler",
|
||||
new IdleStateHandler(balancerConfig.getWebsocket().getTimeout(), 0, 0));
|
||||
ch.pipeline().addLast("ws-protocol",
|
||||
new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, false, true));
|
||||
new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, true));
|
||||
ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(balancerConfig.getSecurity()));
|
||||
ch.pipeline().addLast("httpRelay", new WsRelayHandler(balancerConfig, metricResolver, wsClientPool));
|
||||
ch.pipeline().addLast("error", new WSTimelyExceptionHandler());
|
||||
|
||||
@@ -5,10 +5,8 @@ import javax.validation.Valid;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import timely.configuration.Cache;
|
||||
|
||||
@Validated
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "timely-balancer")
|
||||
public class BalancerConfiguration {
|
||||
|
||||
@@ -3,7 +3,6 @@ package timely.balancer.configuration;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import timely.configuration.Http;
|
||||
|
||||
@@ -11,9 +10,9 @@ public class BalancerHttp extends Http {
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private GenericKeyedObjectPoolConfig<CloseableHttpClient> httpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||
private GenericKeyedObjectPoolConfig httpClientPool = new GenericKeyedObjectPoolConfig();
|
||||
|
||||
public GenericKeyedObjectPoolConfig<CloseableHttpClient> getHttpClientPool() {
|
||||
public GenericKeyedObjectPoolConfig getHttpClientPool() {
|
||||
return httpClientPool;
|
||||
}
|
||||
}
|
||||
@@ -4,29 +4,27 @@ import javax.validation.Valid;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import timely.client.tcp.TcpClient;
|
||||
import timely.client.udp.UdpClient;
|
||||
import timely.configuration.Server;
|
||||
|
||||
public class BalancerServer extends Server {
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private GenericKeyedObjectPoolConfig<UdpClient> udpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||
private GenericKeyedObjectPoolConfig udpClientPool = new GenericKeyedObjectPoolConfig();
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private GenericKeyedObjectPoolConfig<TcpClient> tcpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||
private GenericKeyedObjectPoolConfig tcpClientPool = new GenericKeyedObjectPoolConfig();
|
||||
|
||||
private int numTcpPools = 1;
|
||||
|
||||
private int tcpBufferSize = -1;
|
||||
|
||||
public GenericKeyedObjectPoolConfig<UdpClient> getUdpClientPool() {
|
||||
public GenericKeyedObjectPoolConfig getUdpClientPool() {
|
||||
return udpClientPool;
|
||||
}
|
||||
|
||||
public GenericKeyedObjectPoolConfig<TcpClient> getTcpClientPool() {
|
||||
public GenericKeyedObjectPoolConfig getTcpClientPool() {
|
||||
return tcpClientPool;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,26 +4,15 @@ import javax.validation.Valid;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||
import timely.configuration.Websocket;
|
||||
|
||||
public class BalancerWebsocket extends Websocket {
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private GenericKeyedObjectPoolConfig<WebSocketSubscriptionClient> wsClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||
private GenericKeyedObjectPoolConfig wsClientPool = new GenericKeyedObjectPoolConfig();
|
||||
|
||||
public GenericKeyedObjectPoolConfig<WebSocketSubscriptionClient> getWsClientPool() {
|
||||
public GenericKeyedObjectPoolConfig getWsClientPool() {
|
||||
return wsClientPool;
|
||||
}
|
||||
|
||||
public int incomingBufferSize = 50000000;
|
||||
|
||||
public int getIncomingBufferSize() {
|
||||
return incomingBufferSize;
|
||||
}
|
||||
|
||||
public void setIncomingBufferSize(int incomingBufferSize) {
|
||||
this.incomingBufferSize = incomingBufferSize;
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,6 @@ public class ClientSsl {
|
||||
private String trustStoreFile;
|
||||
private String trustStoreType;
|
||||
private String trustStorePassword;
|
||||
private boolean useClientCert = true;
|
||||
private boolean hostVerificationEnabled = true;
|
||||
|
||||
public String getKeyFile() {
|
||||
return keyFile;
|
||||
@@ -57,21 +55,6 @@ public class ClientSsl {
|
||||
|
||||
public void setTrustStorePassword(String trustStorePassword) {
|
||||
this.trustStorePassword = trustStorePassword;
|
||||
}
|
||||
|
||||
public void setUseClientCert(boolean useClientCert) {
|
||||
this.useClientCert = useClientCert;
|
||||
}
|
||||
|
||||
public boolean isUseClientCert() {
|
||||
return useClientCert;
|
||||
}
|
||||
|
||||
public void setHostVerificationEnabled(boolean hostVerificationEnabled) {
|
||||
this.hostVerificationEnabled = hostVerificationEnabled;
|
||||
}
|
||||
|
||||
public boolean isHostVerificationEnabled() {
|
||||
return hostVerificationEnabled;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
package timely.balancer.configuration;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
public class ZooKeeper {
|
||||
|
||||
private String servers;
|
||||
|
||||
@NotBlank
|
||||
private String timeout = "120s";
|
||||
|
||||
public String getServers() {
|
||||
return servers;
|
||||
}
|
||||
@@ -16,12 +11,4 @@ public class ZooKeeper {
|
||||
public void setServers(String servers) {
|
||||
this.servers = servers;
|
||||
}
|
||||
|
||||
public String getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
public void setTimeout(String timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
}
|
||||
@@ -5,25 +5,22 @@ import javax.net.ssl.SSLContext;
|
||||
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
||||
import org.apache.commons.pool2.PooledObject;
|
||||
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import timely.balancer.configuration.BalancerSecurity;
|
||||
import timely.balancer.connection.TimelyBalancedHost;
|
||||
|
||||
public class HttpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, CloseableHttpClient> {
|
||||
|
||||
private final SSLContext sslContext;
|
||||
private final BalancerSecurity security;
|
||||
|
||||
public HttpClientFactory(BalancerSecurity security, SSLContext sslContext) {
|
||||
this.security = security;
|
||||
public HttpClientFactory(SSLContext sslContext) {
|
||||
this.sslContext = sslContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PooledObject<CloseableHttpClient> makeObject(TimelyBalancedHost k) throws Exception {
|
||||
// disable cookie management because we are sharing connections
|
||||
return new DefaultPooledObject<>(timely.client.http.HttpClient.get(this.sslContext, null,
|
||||
security.getClientSsl().isHostVerificationEnabled(), security.getClientSsl().isUseClientCert()));
|
||||
BasicCookieStore cookieJar = new BasicCookieStore();
|
||||
return new DefaultPooledObject<>(timely.client.http.HttpClient.get(this.sslContext, cookieJar, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -4,13 +4,16 @@ import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import timely.balancer.configuration.BalancerHttp;
|
||||
import timely.balancer.configuration.BalancerSecurity;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import timely.balancer.configuration.BalancerConfiguration;
|
||||
import timely.balancer.connection.TimelyBalancedHost;
|
||||
|
||||
public class HttpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost, CloseableHttpClient> {
|
||||
|
||||
public HttpClientPool(BalancerSecurity balancerSecurity, BalancerHttp http, SSLContext sslContext) {
|
||||
super(new HttpClientFactory(balancerSecurity, sslContext), http.getHttpClientPool());
|
||||
private static final Logger LOG = LoggerFactory.getLogger(HttpClientPool.class);
|
||||
|
||||
public HttpClientPool(BalancerConfiguration config, SSLContext sslContext) {
|
||||
super(new HttpClientFactory(sslContext), config.getHttp().getHttpClientPool());
|
||||
}
|
||||
}
|
||||
@@ -12,21 +12,21 @@ import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||
public class WsClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, WebSocketSubscriptionClient> {
|
||||
|
||||
private final SSLContext sslContext;
|
||||
private final boolean doLogin;
|
||||
private BalancerConfiguration balancerConfig;
|
||||
|
||||
public WsClientFactory(BalancerConfiguration balancerConfig, SSLContext sslContext) {
|
||||
this.balancerConfig = balancerConfig;
|
||||
this.sslContext = sslContext;
|
||||
this.doLogin = balancerConfig.isLoginRequired();
|
||||
this.balancerConfig = balancerConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PooledObject<WebSocketSubscriptionClient> makeObject(TimelyBalancedHost k) throws Exception {
|
||||
|
||||
int bufferSize = balancerConfig.getWebsocket().getIncomingBufferSize();
|
||||
int bufferSize = balancerConfig.getWebsocket().getSubscriptionBatchSize() * 500;
|
||||
WebSocketSubscriptionClient client = new WebSocketSubscriptionClient(sslContext, k.getHost(), k.getHttpPort(),
|
||||
k.getWsPort(), balancerConfig.getSecurity().getClientSsl().isUseClientCert(),
|
||||
balancerConfig.isLoginRequired(), "", "",
|
||||
balancerConfig.getSecurity().getClientSsl().isHostVerificationEnabled(), bufferSize);
|
||||
k.getWsPort(), doLogin, "", "", false, bufferSize);
|
||||
return new DefaultPooledObject<>(client);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package timely.balancer.netty.http;
|
||||
|
||||
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
|
||||
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
@@ -11,7 +12,6 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
@@ -33,26 +33,26 @@ import org.apache.http.message.BasicHeader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import timely.api.request.AuthenticatedRequest;
|
||||
import timely.api.request.MetricRequest;
|
||||
import timely.api.request.timeseries.HttpRequest;
|
||||
import timely.api.request.timeseries.QueryRequest;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.util.HttpHeaderUtils;
|
||||
import timely.auth.util.ProxiedEntityUtils;
|
||||
import timely.balancer.configuration.BalancerConfiguration;
|
||||
import timely.balancer.connection.TimelyBalancedHost;
|
||||
import timely.balancer.connection.http.HttpClientPool;
|
||||
import timely.balancer.resolver.MetricResolver;
|
||||
import timely.netty.http.TimelyHttpHandler;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> implements TimelyHttpHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(HttpRelayHandler.class);
|
||||
private final BalancerConfiguration balancerConf;
|
||||
private final HttpClientPool httpClientPool;
|
||||
private MetricResolver metricResolver;
|
||||
|
||||
public HttpRelayHandler(MetricResolver metricResolver, HttpClientPool httpClientPool) {
|
||||
public HttpRelayHandler(BalancerConfiguration balancerConf, MetricResolver metricResolver,
|
||||
HttpClientPool httpClientPool) {
|
||||
this.balancerConf = balancerConf;
|
||||
this.metricResolver = metricResolver;
|
||||
this.httpClientPool = httpClientPool;
|
||||
}
|
||||
@@ -67,7 +67,7 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
try {
|
||||
try {
|
||||
request = msg.getHttpRequest();
|
||||
String originalURI = request.uri();
|
||||
String originalURI = request.getUri();
|
||||
originalURI = encodeURI(originalURI);
|
||||
|
||||
String metric = null;
|
||||
@@ -86,22 +86,14 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
} else {
|
||||
k = metricResolver.getHostPortKey(null);
|
||||
}
|
||||
k = metricResolver.getHostPortKey(metric);
|
||||
client = httpClientPool.borrowObject(k);
|
||||
|
||||
Multimap<String, String> headers = HttpHeaderUtils.toMultimap(request.headers());
|
||||
if (msg instanceof AuthenticatedRequest) {
|
||||
AuthenticatedRequest authenticatedRequest = (AuthenticatedRequest) msg;
|
||||
TimelyAuthenticationToken token = authenticatedRequest.getToken();
|
||||
if (token != null) {
|
||||
if (token.getClientCert() != null) {
|
||||
ProxiedEntityUtils.addProxyHeaders(headers, token.getClientCert());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<Map.Entry<String, String>> headerList = request.headers().entries();
|
||||
List<Header> relayedHeaderList = new ArrayList<>();
|
||||
for (Map.Entry<String, String> h : headers.entries()) {
|
||||
if (!h.getKey().equals(CONTENT_LENGTH.toString())) {
|
||||
|
||||
for (Map.Entry<String, String> h : headerList) {
|
||||
if (!h.getKey().equals(CONTENT_LENGTH)) {
|
||||
relayedHeaderList.add(new BasicHeader(h.getKey(), h.getValue()));
|
||||
}
|
||||
}
|
||||
@@ -109,14 +101,14 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
relayedHeaderList.toArray(headerArray);
|
||||
|
||||
String relayURI = "https://" + k.getHost() + ":" + k.getHttpPort() + originalURI;
|
||||
if (request.method().equals(HttpMethod.GET)) {
|
||||
if (request.getMethod().equals(HttpMethod.GET)) {
|
||||
HttpUriRequest relayedRequest = new HttpGet(relayURI);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
|
||||
} else if (request.method().equals(HttpMethod.POST)) {
|
||||
} else if (request.getMethod().equals(HttpMethod.POST)) {
|
||||
HttpPost relayedRequest = new HttpPost(relayURI);
|
||||
|
||||
String content = request.content().toString(StandardCharsets.UTF_8);
|
||||
@@ -151,6 +143,7 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.METHOD_NOT_ALLOWED.code(),
|
||||
"Method not allowed", "Method not allowed"));
|
||||
} else {
|
||||
// buf = JsonUtil.getObjectMapper().writeValueAsBytes(msg);
|
||||
ByteArrayOutputStream baos = new MyByteArrayOutputStream();
|
||||
StreamUtils.copy(relayedResponse.getEntity().getContent(), baos);
|
||||
|
||||
@@ -160,6 +153,8 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
for (Header h : relayedResponse.getAllHeaders()) {
|
||||
response.headers().add(h.getName(), h.getValue());
|
||||
}
|
||||
// response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
|
||||
// Constants.JSON_TYPE);
|
||||
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
|
||||
sendResponse(ctx, response);
|
||||
}
|
||||
@@ -170,7 +165,7 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
if (client != null && k != null) {
|
||||
httpClientPool.returnObject(k, client);
|
||||
} else {
|
||||
LOG.error("NOT RETURNING CONNECTION! " + msg.getHttpRequest().uri());
|
||||
LOG.error("NOT RETURNING CONNECTION! " + msg.getHttpRequest().getUri());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,4 +197,13 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String s = "https://127.0.0.1:4243/api/query?start=1356998400000&end=1528398304000&m=sum:rate{false,100,0}:sys.thermal.gauge{class=aws}";
|
||||
URI uri = URI.create(encodeURI(s));
|
||||
|
||||
System.out.println(uri.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +1,12 @@
|
||||
package timely.balancer.netty.ws;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.EndpointConfig;
|
||||
import javax.websocket.MessageHandler;
|
||||
import javax.websocket.Session;
|
||||
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
|
||||
@@ -19,48 +15,25 @@ import io.netty.util.concurrent.ScheduledFuture;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.util.ProxiedEntityUtils;
|
||||
import timely.client.websocket.ClientHandler;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class WsClientHandler extends ClientHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WsClientHandler.class);
|
||||
private final ChannelHandlerContext ctx;
|
||||
private final TimelyAuthenticationToken token;
|
||||
private ScheduledFuture<?> ping;
|
||||
|
||||
public WsClientHandler(ChannelHandlerContext ctx, TimelyAuthenticationToken token, int pingRate) {
|
||||
public WsClientHandler(ChannelHandlerContext ctx, int pingRate) {
|
||||
this.ctx = ctx;
|
||||
this.token = token;
|
||||
this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
|
||||
LOG.trace("Sending ping on channel {}", ctx.channel());
|
||||
ctx.writeAndFlush(new PingWebSocketFrame());
|
||||
}, pingRate, pingRate, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeRequest(Map<String, List<String>> headers) {
|
||||
if (token.getClientCert() != null) {
|
||||
Multimap<String, String> proxyRequestHeaders = HashMultimap.create();
|
||||
ProxiedEntityUtils.addProxyHeaders(proxyRequestHeaders, token.getClientCert());
|
||||
for (String s : proxyRequestHeaders.keySet()) {
|
||||
headers.put(s, new ArrayList<>(proxyRequestHeaders.get(s)));
|
||||
}
|
||||
}
|
||||
|
||||
Multimap<String, String> originalRequestHeaders = token.getHttpHeaders();
|
||||
for (String s : originalRequestHeaders.keySet()) {
|
||||
if (!headers.containsKey(s)) {
|
||||
// add pre-existing values if key does not exist in proxyRequest
|
||||
headers.put(s, new ArrayList<>(originalRequestHeaders.get(s)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(Session session, EndpointConfig config) {
|
||||
session.addMessageHandler(String.class, message -> {
|
||||
session.addMessageHandler((MessageHandler.Whole<String>) message -> {
|
||||
ctx.writeAndFlush(new TextWebSocketFrame(message));
|
||||
LOG.debug("Message received on Websocket session {}: {}", session.getId(), message);
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
@@ -25,7 +24,6 @@ import timely.api.request.subscription.CreateSubscription;
|
||||
import timely.api.request.subscription.RemoveSubscription;
|
||||
import timely.api.request.subscription.SubscriptionRequest;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.util.ProxiedEntityUtils;
|
||||
import timely.balancer.configuration.BalancerConfiguration;
|
||||
import timely.balancer.connection.TimelyBalancedHost;
|
||||
import timely.balancer.connection.ws.WsClientPool;
|
||||
@@ -66,10 +64,6 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
||||
String subscriptionId;
|
||||
try {
|
||||
String metric = null;
|
||||
|
||||
Multimap<String, String> headers = msg.getRequestHeaders();
|
||||
ProxiedEntityUtils.addProxyHeaders(headers, msg.getToken().getClientCert());
|
||||
|
||||
if (msg instanceof CreateSubscription) {
|
||||
CreateSubscription create = (CreateSubscription) msg;
|
||||
final String currentSubscriptionId = create.getSubscriptionId();
|
||||
@@ -124,8 +118,7 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
||||
if (hostClientHolder == null) {
|
||||
k = metricResolver.getHostPortKey(metric);
|
||||
client = wsClientPool.borrowObject(k);
|
||||
client.open(new WsClientHandler(origContext, add.getToken(),
|
||||
(balancerConfig.getWebsocket().getTimeout() / 2)));
|
||||
client.open(new WsClientHandler(origContext, (balancerConfig.getWebsocket().getTimeout() / 2)));
|
||||
metricToClientMap.put(metric, new WsClientHolder(k, client));
|
||||
} else {
|
||||
client = hostClientHolder.getClient();
|
||||
|
||||
@@ -72,7 +72,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
private Random r = new Random();
|
||||
final private HealthChecker healthChecker;
|
||||
private Timer timer = new Timer("RebalanceTimer", true);
|
||||
private Timer arrivalRateTimer = new Timer("ArrivalRateTimerResolver", true);
|
||||
private Timer arrivalRateTimer = new Timer("AriivalRateTimerResolver", true);
|
||||
private int roundRobinCounter = 0;
|
||||
private Set<String> nonCachedMetrics = new HashSet<>();
|
||||
private DistributedAtomicValue nonCachedMetricsIP;
|
||||
@@ -105,15 +105,25 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
|
||||
@Override
|
||||
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
|
||||
LOG.debug("Handling assignments event {}. assignmentsLastUpdatedInHdfs:{}", event.getType().toString(),
|
||||
LOG.info("Handling assignments event {}. assignmentsLastUpdatedInHdfs:{}", event.getType().toString(),
|
||||
new Date(assignmentsLastUpdatedInHdfs.get().postValue()));
|
||||
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
|
||||
readAssignmentsFromHdfs(true);
|
||||
long lastLocalUpdate = assignmentsLastUpdatedLocal.get();
|
||||
long lastHdfsUpdate = assignmentsLastUpdatedInHdfs.get().postValue();
|
||||
if (lastHdfsUpdate > lastLocalUpdate) {
|
||||
LOG.info("Reading assignments from hdfs lastHdfsUpdate ({}) > lastLocalUpdate ({})",
|
||||
new Date(lastHdfsUpdate), new Date(lastLocalUpdate));
|
||||
readAssignmentsFromHdfs();
|
||||
} else {
|
||||
LOG.info("Not reading assignments from hdfs lastHdfsUpdate ({}) <= lastLocalUpdate ({})",
|
||||
new Date(lastHdfsUpdate), new Date(lastLocalUpdate));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try (TreeCache assignmentTreeCache = new TreeCache(curatorFramework, ASSIGNMENTS_LAST_UPDATED_PATH)) {
|
||||
try {
|
||||
TreeCache assignmentTreeCache = new TreeCache(curatorFramework, ASSIGNMENTS_LAST_UPDATED_PATH);
|
||||
assignmentTreeCache.getListenable().addListener(assignmentListener);
|
||||
assignmentTreeCache.start();
|
||||
} catch (Exception e) {
|
||||
@@ -128,13 +138,14 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
@Override
|
||||
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
|
||||
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
|
||||
LOG.debug("Handling nonCachedMetricsIP event {}", event.getType().toString());
|
||||
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
|
||||
readNonCachedMetricsIP();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try (TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS)) {
|
||||
try {
|
||||
TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS);
|
||||
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
|
||||
nonCachedMetricsTreeCache.start();
|
||||
} catch (Exception e) {
|
||||
@@ -149,7 +160,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
}
|
||||
readNonCachedMetricsIP();
|
||||
|
||||
readAssignmentsFromHdfs(false);
|
||||
readAssignmentsFromHdfs();
|
||||
|
||||
timer.schedule(new TimerTask() {
|
||||
|
||||
@@ -174,16 +185,10 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
long lastLocalUpdate = assignmentsLastUpdatedLocal.get();
|
||||
long lastHdfsUpdate = assignmentsLastUpdatedInHdfs.get().postValue();
|
||||
if (lastLocalUpdate > lastHdfsUpdate) {
|
||||
LOG.debug("Leader writing assignments to hdfs lastLocalUpdate ({}) > lastHdfsUpdate ({})",
|
||||
new Date(lastLocalUpdate), new Date(lastHdfsUpdate));
|
||||
writeAssignmentsToHdfs();
|
||||
} else {
|
||||
LOG.trace(
|
||||
"Leader not writing assignments to hdfs lastLocalUpdate ({}) <= lastHdfsUpdate ({})",
|
||||
LOG.info("Writing assignments to hdfs lastLocalUpdate ({}) > lastHdfsUpdate ({})",
|
||||
new Date(lastLocalUpdate), new Date(lastHdfsUpdate));
|
||||
writeAssigmentsToHdfs();
|
||||
}
|
||||
} else {
|
||||
readAssignmentsFromHdfs(true);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
@@ -193,46 +198,52 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
}
|
||||
|
||||
private void readNonCachedMetricsIP() {
|
||||
|
||||
Set<String> currentNonCachedMetricsDistributed = new TreeSet<>();
|
||||
try {
|
||||
boolean acquired = false;
|
||||
while (!acquired) {
|
||||
acquired = nonCachedMetricsIPRWLock.readLock().acquire(60, TimeUnit.SECONDS);
|
||||
}
|
||||
byte[] currentNonCachedMetricsDistributedBytes = nonCachedMetricsIP.get().postValue();
|
||||
if (currentNonCachedMetricsDistributedBytes != null) {
|
||||
try {
|
||||
currentNonCachedMetricsDistributed = SerializationUtils
|
||||
.deserialize(currentNonCachedMetricsDistributedBytes);
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
nonCachedMetricsLocalLock.readLock().lock();
|
||||
Set<String> currentNonCachedMetricsDistributed;
|
||||
try {
|
||||
nonCachedMetricsIPRWLock.readLock().acquire();
|
||||
byte[] currentNonCachedMetricsDistributedBytes = nonCachedMetricsIP.get().postValue();
|
||||
if (currentNonCachedMetricsDistributedBytes == null) {
|
||||
currentNonCachedMetricsDistributed = new TreeSet<>();
|
||||
} else {
|
||||
try {
|
||||
currentNonCachedMetricsDistributed = SerializationUtils
|
||||
.deserialize(currentNonCachedMetricsDistributedBytes);
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage());
|
||||
currentNonCachedMetricsDistributed = new TreeSet<>();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
nonCachedMetricsIPRWLock.readLock().release();
|
||||
}
|
||||
|
||||
if (nonCachedMetrics.containsAll(currentNonCachedMetricsDistributed)) {
|
||||
LOG.info("local nonCachedMetrics already contains {}", currentNonCachedMetricsDistributed);
|
||||
} else {
|
||||
nonCachedMetricsLocalLock.readLock().unlock();
|
||||
nonCachedMetricsLocalLock.writeLock().lock();
|
||||
currentNonCachedMetricsDistributed.removeAll(nonCachedMetrics);
|
||||
LOG.info("Adding {} to local nonCachedMetrics", currentNonCachedMetricsDistributed);
|
||||
nonCachedMetrics.addAll(currentNonCachedMetricsDistributed);
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
for (String m : currentNonCachedMetricsDistributed) {
|
||||
metricToHostMap.remove(m);
|
||||
}
|
||||
} finally {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
} finally {
|
||||
try {
|
||||
nonCachedMetricsIPRWLock.readLock().release();
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
nonCachedMetricsLocalLock.writeLock().lock();
|
||||
try {
|
||||
if (nonCachedMetrics.containsAll(currentNonCachedMetricsDistributed)) {
|
||||
LOG.debug("local nonCachedMetrics already contains {}", currentNonCachedMetricsDistributed);
|
||||
if (nonCachedMetricsLocalLock.isWriteLockedByCurrentThread()) {
|
||||
nonCachedMetricsLocalLock.writeLock().unlock();
|
||||
} else {
|
||||
currentNonCachedMetricsDistributed.removeAll(nonCachedMetrics);
|
||||
LOG.debug("Adding {} to local nonCachedMetrics", currentNonCachedMetricsDistributed);
|
||||
nonCachedMetrics.addAll(currentNonCachedMetricsDistributed);
|
||||
nonCachedMetricsLocalLock.readLock().unlock();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
} finally {
|
||||
nonCachedMetricsLocalLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +258,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
public void isLeader() {
|
||||
LOG.info("this balancer is the leader");
|
||||
isLeader.set(true);
|
||||
writeAssignmentsToHdfs();
|
||||
writeAssigmentsToHdfs();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -263,15 +274,15 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
|
||||
private void startServiceListener(CuratorFramework curatorFramework) {
|
||||
try {
|
||||
ServiceDiscovery<ServerDetails> discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class)
|
||||
.client(curatorFramework).basePath(SERVICE_DISCOVERY_PATH).build();
|
||||
ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class).client(curatorFramework)
|
||||
.basePath(SERVICE_DISCOVERY_PATH).build();
|
||||
discovery.start();
|
||||
Collection<ServiceInstance<ServerDetails>> instances = discovery.queryForInstances("timely-server");
|
||||
Collection<ServiceInstance> instances = discovery.queryForInstances("timely-server");
|
||||
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
for (ServiceInstance<ServerDetails> si : instances) {
|
||||
ServerDetails pl = si.getPayload();
|
||||
for (ServiceInstance si : instances) {
|
||||
ServerDetails pl = (ServerDetails) si.getPayload();
|
||||
TimelyBalancedHost tbh = TimelyBalancedHost.of(pl.getHost(), pl.getTcpPort(), pl.getHttpPort(),
|
||||
pl.getWsPort(), pl.getUdpPort());
|
||||
LOG.info("adding service {} host:{} tcpPort:{} httpPort:{} wsPort:{} udpPort:{}", si.getId(),
|
||||
@@ -284,8 +295,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
|
||||
final ServiceCache<ServerDetails> serviceCache = discovery.serviceCacheBuilder().name("timely-server")
|
||||
.build();
|
||||
final ServiceCache serviceCache = discovery.serviceCacheBuilder().name("timely-server").build();
|
||||
ServiceCacheListener listener = new ServiceCacheListener() {
|
||||
|
||||
@Override
|
||||
@@ -293,9 +303,9 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
boolean rebalanceNeeded = false;
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
List<ServiceInstance<ServerDetails>> instances = serviceCache.getInstances();
|
||||
List<ServiceInstance> instances = serviceCache.getInstances();
|
||||
Set<TimelyBalancedHost> availableHosts = new HashSet<>();
|
||||
for (ServiceInstance<ServerDetails> si : instances) {
|
||||
for (ServiceInstance si : instances) {
|
||||
ServerDetails pl = (ServerDetails) si.getPayload();
|
||||
TimelyBalancedHost tbh = TimelyBalancedHost.of(pl.getHost(), pl.getTcpPort(),
|
||||
pl.getHttpPort(), pl.getWsPort(), pl.getUdpPort());
|
||||
@@ -340,16 +350,14 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
assignMetric(s, h);
|
||||
LOG.debug("Assigned server removed. Assigning {} to server {}:{}", s, h.getTcpPort());
|
||||
}
|
||||
writeAssigmentsToHdfs();
|
||||
}
|
||||
|
||||
} finally {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
if (isLeader.get()) {
|
||||
if (rebalanceNeeded) {
|
||||
balance();
|
||||
}
|
||||
writeAssignmentsToHdfs();
|
||||
if (isLeader.get() && rebalanceNeeded) {
|
||||
balance();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,21 +514,21 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
}
|
||||
|
||||
if (highHosts.isEmpty() && lowHosts.isEmpty()) {
|
||||
LOG.debug("Host's arrival rates are within {} of the average", controlBandPercentage);
|
||||
LOG.info("Host's arrival rates are within {} of the average", controlBandPercentage);
|
||||
} else if (!highHosts.isEmpty() && !lowHosts.isEmpty()) {
|
||||
LOG.debug("begin rebalancing {}", BalanceType.HIGH_LOW);
|
||||
LOG.info("begin rebalancing {}", BalanceType.HIGH_LOW);
|
||||
numReassigned = rebalance(highHosts, lowHosts, calculatedRates, averageArrivalRate,
|
||||
BalanceType.HIGH_LOW);
|
||||
LOG.debug("end rebalancing {} - reassigned {}", BalanceType.HIGH_LOW, numReassigned);
|
||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.HIGH_LOW, numReassigned);
|
||||
} else if (lowHosts.isEmpty()) {
|
||||
LOG.debug("begin rebalancing {}", BalanceType.HIGH_AVG);
|
||||
LOG.info("begin rebalancing {}", BalanceType.HIGH_AVG);
|
||||
numReassigned = rebalance(highHosts, avgHosts, calculatedRates, averageArrivalRate,
|
||||
BalanceType.HIGH_AVG);
|
||||
LOG.debug("end rebalancing {} - reassigned {}", BalanceType.HIGH_AVG, numReassigned);
|
||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.HIGH_AVG, numReassigned);
|
||||
} else {
|
||||
LOG.debug("begin rebalancing {}", BalanceType.AVG_LOW);
|
||||
LOG.info("begin rebalancing {}", BalanceType.AVG_LOW);
|
||||
numReassigned = rebalance(avgHosts, lowHosts, calculatedRates, averageArrivalRate, BalanceType.AVG_LOW);
|
||||
LOG.debug("end rebalancing {} - reassigned {}", BalanceType.AVG_LOW, numReassigned);
|
||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.AVG_LOW, numReassigned);
|
||||
}
|
||||
}
|
||||
return numReassigned;
|
||||
@@ -634,19 +642,24 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
private void addNonCachedMetrics(Collection<String> nonCachedMetricsUpdate) {
|
||||
if (!nonCachedMetricsUpdate.isEmpty()) {
|
||||
try {
|
||||
LOG.debug("Adding {} to local nonCachedMetrics", nonCachedMetricsUpdate);
|
||||
LOG.info("Adding {} to local nonCachedMetrics", nonCachedMetricsUpdate);
|
||||
nonCachedMetricsLocalLock.writeLock().lock();
|
||||
try {
|
||||
nonCachedMetrics.addAll(nonCachedMetricsUpdate);
|
||||
} finally {
|
||||
nonCachedMetricsLocalLock.writeLock().unlock();
|
||||
}
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
for (String m : nonCachedMetricsUpdate) {
|
||||
metricToHostMap.remove(m);
|
||||
}
|
||||
} finally {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
|
||||
try {
|
||||
boolean acquired = false;
|
||||
while (!acquired) {
|
||||
acquired = nonCachedMetricsIPRWLock.writeLock().acquire(60, TimeUnit.SECONDS);
|
||||
}
|
||||
nonCachedMetricsIPRWLock.writeLock().acquire();
|
||||
byte[] currentNonCachedMetricsDistributedBytes = nonCachedMetricsIP.get().postValue();
|
||||
Set<String> currentNonCachedMetricsIP;
|
||||
if (currentNonCachedMetricsDistributedBytes == null) {
|
||||
@@ -656,10 +669,10 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
.deserialize(currentNonCachedMetricsDistributedBytes);
|
||||
}
|
||||
if (currentNonCachedMetricsIP.containsAll(nonCachedMetricsUpdate)) {
|
||||
LOG.debug("nonCachedMetricsIP already contains {}", nonCachedMetricsUpdate);
|
||||
LOG.info("nonCachedMetricsIP already contains {}", nonCachedMetricsUpdate);
|
||||
} else {
|
||||
nonCachedMetricsUpdate.removeAll(currentNonCachedMetricsIP);
|
||||
LOG.debug("Adding {} to nonCachedMetricsIP", nonCachedMetricsUpdate);
|
||||
LOG.info("Adding {} to nonCachedMetricsIP", nonCachedMetricsUpdate);
|
||||
TreeSet<String> updateSet = new TreeSet<>();
|
||||
updateSet.addAll(currentNonCachedMetricsIP);
|
||||
updateSet.addAll(nonCachedMetricsUpdate);
|
||||
@@ -693,7 +706,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
try {
|
||||
lock.writeLock().release();
|
||||
} catch (Exception e3) {
|
||||
LOG.error(e3.getMessage(), e3);
|
||||
LOG.error(e3.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -724,7 +737,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
try {
|
||||
for (String r : nonCachedMetrics) {
|
||||
if (metricName.matches(r)) {
|
||||
LOG.debug("Adding {} to list of non-cached metrics", metricName);
|
||||
LOG.info("Adding {} to list of non-cached metrics", metricName);
|
||||
addNonCachedMetrics(Collections.singleton(metricName));
|
||||
return false;
|
||||
}
|
||||
@@ -773,7 +786,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
} else if (!tbh.isUp()) {
|
||||
TimelyBalancedHost oldTbh = tbh;
|
||||
tbh = getLeastUsedHost();
|
||||
LOG.debug("rebalancing from host that is down: reassigning metric {} from server {}:{} to {}:{}",
|
||||
LOG.info("rebalancing from host that is down: reassigning metric {} from server {}:{} to {}:{}",
|
||||
metric, oldTbh.getHost(), oldTbh.getTcpPort(), tbh.getHost(), tbh.getTcpPort());
|
||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
||||
balancerLock.readLock().unlock();
|
||||
@@ -878,32 +891,11 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
return tbh;
|
||||
}
|
||||
|
||||
private void readAssignmentsFromHdfs(boolean checkIfNecessary) {
|
||||
|
||||
try {
|
||||
long lastLocalUpdate = assignmentsLastUpdatedLocal.get();
|
||||
long lastHdfsUpdate = assignmentsLastUpdatedInHdfs.get().postValue();
|
||||
if (checkIfNecessary) {
|
||||
if (lastHdfsUpdate <= lastLocalUpdate) {
|
||||
LOG.debug("Not reading assignments from hdfs lastHdfsUpdate ({}) <= lastLocalUpdate ({})",
|
||||
new Date(lastHdfsUpdate), new Date(lastLocalUpdate));
|
||||
return;
|
||||
}
|
||||
}
|
||||
LOG.debug("Reading assignments from hdfs lastHdfsUpdate ({}) > lastLocalUpdate ({})",
|
||||
new Date(lastHdfsUpdate), new Date(lastLocalUpdate));
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
}
|
||||
|
||||
// proceed with reading from HDFS
|
||||
private void readAssignmentsFromHdfs() {
|
||||
|
||||
Map<String, TimelyBalancedHost> assignedMetricToHostMap = new TreeMap<>();
|
||||
try {
|
||||
boolean acquired = false;
|
||||
while (!acquired) {
|
||||
acquired = assignmentsIPRWLock.readLock().acquire(60, TimeUnit.SECONDS);
|
||||
}
|
||||
assignmentsIPRWLock.readLock().acquire();
|
||||
balancerLock.writeLock().lock();
|
||||
Configuration configuration = new Configuration();
|
||||
FileSystem fs = FileSystem.get(configuration);
|
||||
@@ -936,14 +928,8 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
|
||||
metricToHostMap.clear();
|
||||
for (Map.Entry<String, TimelyBalancedHost> e : assignedMetricToHostMap.entrySet()) {
|
||||
if (StringUtils.isNotBlank(e.getKey()) && e.getValue() != null) {
|
||||
if (shouldCache(e.getKey())) {
|
||||
metricToHostMap.put(e.getKey(), e.getValue());
|
||||
}
|
||||
} else {
|
||||
Exception e1 = new IllegalStateException(
|
||||
"Bad assignment metric:" + e.getKey() + " host:" + e.getValue());
|
||||
LOG.warn(e1.getMessage(), e1);
|
||||
if (shouldCache(e.getKey())) {
|
||||
metricToHostMap.put(e.getKey(), e.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -974,14 +960,11 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAssignmentsToHdfs() {
|
||||
private void writeAssigmentsToHdfs() {
|
||||
|
||||
CsvWriter writer = null;
|
||||
try {
|
||||
boolean acquired = false;
|
||||
while (!acquired) {
|
||||
acquired = assignmentsIPRWLock.writeLock().acquire(60, TimeUnit.SECONDS);
|
||||
}
|
||||
assignmentsIPRWLock.writeLock().acquire();
|
||||
balancerLock.readLock().lock();
|
||||
nonCachedMetricsLocalLock.readLock().lock();
|
||||
try {
|
||||
@@ -1016,7 +999,7 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
if (!assignmentsLastUpdatedInHdfs.get().succeeded()) {
|
||||
assignmentsLastUpdatedInHdfs.forceSet(now);
|
||||
}
|
||||
LOG.debug("Wrote {} assignments to hdfs lastHdfsUpdate = lastLocalUpdate ({})",
|
||||
LOG.info("Wrote {} assignments to hdfs lastHdfsUpdate = lastLocalUpdate ({})",
|
||||
metricToHostMap.size(), new Date(assignmentsLastUpdatedLocal.get()));
|
||||
}
|
||||
} finally {
|
||||
@@ -1039,17 +1022,12 @@ public class BalancedMetricResolver implements MetricResolver {
|
||||
|
||||
private void assignMetric(String metric, TimelyBalancedHost tbh) {
|
||||
if (isLeader.get()) {
|
||||
if (StringUtils.isNotBlank(metric) && tbh != null) {
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
metricToHostMap.put(metric, tbh);
|
||||
assignmentsLastUpdatedLocal.set(System.currentTimeMillis());
|
||||
} finally {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
} else {
|
||||
Exception e = new IllegalStateException("Bad assignment metric:" + metric + " host:" + tbh);
|
||||
LOG.warn(e.getMessage(), e);
|
||||
balancerLock.writeLock().lock();
|
||||
try {
|
||||
metricToHostMap.put(metric, tbh);
|
||||
assignmentsLastUpdatedLocal.set(System.currentTimeMillis());
|
||||
} finally {
|
||||
balancerLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-42
@@ -4,13 +4,12 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-client</artifactId>
|
||||
<properties>
|
||||
<!-- PEP 440 compliant version gets substituted into src/main/python/template/setup.py -->
|
||||
<!-- use .dev0 instead of -SNAPSHOT -->
|
||||
<python.client.version>1.2.6</python.client.version>
|
||||
<python.client.version>0.0.7.dev0</python.client.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
@@ -108,43 +107,4 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>python</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>python-dist</id>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<phase>package</phase>
|
||||
<configuration>
|
||||
<executable>python</executable>
|
||||
<workingDirectory>${project.basedir}/src/main/python</workingDirectory>
|
||||
<commandlineArgs>setup.py sdist --dist-dir ${project.build.directory}</commandlineArgs>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>python-clean</id>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<phase>package</phase>
|
||||
<configuration>
|
||||
<executable>rm</executable>
|
||||
<workingDirectory>${project.basedir}/src/main/python</workingDirectory>
|
||||
<commandlineArgs>-rf timely.egg-info setup.py</commandlineArgs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -1,13 +1,12 @@
|
||||
package timely.client.http;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.config.CookieSpecs;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
@@ -41,31 +40,14 @@ public class HttpClient {
|
||||
}
|
||||
|
||||
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
|
||||
return get(ssl, cookieStore, hostVerificationEnabled, false);
|
||||
}
|
||||
|
||||
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled,
|
||||
boolean clientAuth) {
|
||||
HostnameVerifier hostnameVerifier;
|
||||
if (hostVerificationEnabled) {
|
||||
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
|
||||
} else {
|
||||
hostnameVerifier = new NoopHostnameVerifier();
|
||||
}
|
||||
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
|
||||
HttpClientBuilder builder;
|
||||
if (cookieStore == null) {
|
||||
builder = HttpClients.custom().setSSLContext(ssl).disableCookieManagement()
|
||||
.setDefaultRequestConfig(defaultRequestConfig).setSSLHostnameVerifier(hostnameVerifier);
|
||||
} else {
|
||||
builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
|
||||
.setDefaultRequestConfig(defaultRequestConfig).setSSLHostnameVerifier(hostnameVerifier);
|
||||
}
|
||||
|
||||
if (clientAuth) {
|
||||
SSLConnectionSocketFactory sslCSF = new SSLConnectionSocketFactory(ssl,
|
||||
new String[] { "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier);
|
||||
builder.setSSLSocketFactory(sslCSF);
|
||||
HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
|
||||
.setDefaultRequestConfig(defaultRequestConfig);
|
||||
if (hostVerificationEnabled) {
|
||||
builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
|
||||
} else {
|
||||
builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package timely.client.tcp;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.Socket;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
@@ -15,7 +14,7 @@ public class TcpClient implements AutoCloseable {
|
||||
private final String host;
|
||||
private final int port;
|
||||
private Socket sock = null;
|
||||
private BufferedWriter out = null;
|
||||
private PrintWriter out = null;
|
||||
private long connectTime = 0L;
|
||||
private long backoff = 2000;
|
||||
private int bufferSize = -1;
|
||||
@@ -48,6 +47,7 @@ public class TcpClient implements AutoCloseable {
|
||||
*
|
||||
* @param metric
|
||||
* newline terminated string representation of Timely metric
|
||||
* @throws IOException
|
||||
*/
|
||||
public synchronized void write(String metric) throws IOException {
|
||||
if (connect() != 0) {
|
||||
@@ -60,7 +60,7 @@ public class TcpClient implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void flush() throws IOException {
|
||||
public synchronized void flush() {
|
||||
if (null != out) {
|
||||
out.flush();
|
||||
writesSinceFlush = 0;
|
||||
@@ -94,12 +94,12 @@ public class TcpClient implements AutoCloseable {
|
||||
}
|
||||
|
||||
private synchronized int connect() {
|
||||
if (null == sock || !sock.isConnected()) {
|
||||
if (null == sock || !sock.isConnected() || out.checkError()) {
|
||||
if (System.currentTimeMillis() > (connectTime + backoff)) {
|
||||
try {
|
||||
connectTime = System.currentTimeMillis();
|
||||
sock = new Socket(host, port);
|
||||
out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
|
||||
out = new PrintWriter(sock.getOutputStream(), false);
|
||||
backoff = 2000;
|
||||
LOG.trace("Connected to Timely at {}:{}", host, port);
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package timely.client.websocket;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.Endpoint;
|
||||
import javax.websocket.EndpointConfig;
|
||||
@@ -38,6 +35,4 @@ public abstract class ClientHandler extends Endpoint {
|
||||
LOG.error("Error occurred on Websocket session" + session.getId(), error);
|
||||
}
|
||||
|
||||
public void beforeRequest(Map<String, List<String>> headers) {
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,13 @@ import org.apache.http.cookie.Cookie;
|
||||
public class TimelyEndpointConfig implements ClientEndpointConfig {
|
||||
|
||||
private String sessionCookie = null;
|
||||
private final ClientHandler clientEndpoint;
|
||||
|
||||
private static final String FORMAT = "%s=%s;";
|
||||
|
||||
public TimelyEndpointConfig(ClientHandler clientEndpoint, Cookie sessionCookie) {
|
||||
public TimelyEndpointConfig(Cookie sessionCookie) {
|
||||
if (null != sessionCookie) {
|
||||
this.sessionCookie = String.format(FORMAT, sessionCookie.getName(), sessionCookie.getValue());
|
||||
}
|
||||
this.clientEndpoint = clientEndpoint;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -60,7 +58,6 @@ public class TimelyEndpointConfig implements ClientEndpointConfig {
|
||||
if (null != sessionCookie) {
|
||||
headers.put("Cookie", Collections.singletonList(sessionCookie));
|
||||
}
|
||||
TimelyEndpointConfig.this.clientEndpoint.beforeRequest(headers);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@ public class WebSocketClient implements AutoCloseable {
|
||||
private final int timelyHttpsPort;
|
||||
private final int timelyWssPort;
|
||||
private final boolean doLogin;
|
||||
private final boolean clientAuth;
|
||||
private final String timelyUsername;
|
||||
private final String timelyPassword;
|
||||
private final boolean hostVerificationEnabled;
|
||||
@@ -52,14 +51,13 @@ public class WebSocketClient implements AutoCloseable {
|
||||
protected volatile boolean closed = true;
|
||||
|
||||
protected WebSocketClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort,
|
||||
boolean clientAuth, boolean doLogin, String timelyUsername, String timelyPassword,
|
||||
boolean hostVerificationEnabled, int bufferSize) {
|
||||
boolean doLogin, String timelyUsername, String timelyPassword, boolean hostVerificationEnabled,
|
||||
int bufferSize) {
|
||||
this.ssl = ssl;
|
||||
this.timelyHostname = timelyHostname;
|
||||
this.timelyHttpsPort = timelyHttpsPort;
|
||||
this.timelyWssPort = timelyWssPort;
|
||||
this.doLogin = doLogin;
|
||||
this.clientAuth = clientAuth;
|
||||
this.timelyUsername = timelyUsername;
|
||||
this.timelyPassword = timelyPassword;
|
||||
this.hostVerificationEnabled = hostVerificationEnabled;
|
||||
@@ -69,28 +67,28 @@ public class WebSocketClient implements AutoCloseable {
|
||||
Preconditions.checkNotNull(timelyHttpsPort, "%s must be supplied", "Timely HTTPS port");
|
||||
Preconditions.checkNotNull(timelyWssPort, "%s must be supplied", "Timely WSS port");
|
||||
|
||||
if (doLogin && !clientAuth) {
|
||||
if ((StringUtils.isEmpty(timelyUsername) && !StringUtils.isEmpty(timelyPassword)
|
||||
|| (!StringUtils.isEmpty(timelyUsername) && StringUtils.isEmpty(timelyPassword)))) {
|
||||
throw new IllegalArgumentException("Both Timely username and password must be empty or non-empty");
|
||||
}
|
||||
if (doLogin && ((StringUtils.isEmpty(timelyUsername) && !StringUtils.isEmpty(timelyPassword)
|
||||
|| (!StringUtils.isEmpty(timelyUsername) && StringUtils.isEmpty(timelyPassword))))) {
|
||||
throw new IllegalArgumentException("Both Timely username and password must be empty or non-empty");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected WebSocketClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean clientAuth,
|
||||
boolean doLogin, String timelyUsername, String timelyPassword, String keyStoreFile, String keyStoreType,
|
||||
String keyStorePass, String trustStoreFile, String trustStoreType, String trustStorePass,
|
||||
boolean hostVerificationEnabled, int bufferSize) {
|
||||
protected WebSocketClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean doLogin,
|
||||
String timelyUsername, String timelyPassword, String keyStoreFile, String keyStoreType, String keyStorePass,
|
||||
String trustStoreFile, String trustStoreType, String trustStorePass, boolean hostVerificationEnabled,
|
||||
int bufferSize) {
|
||||
this(HttpClient.getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType,
|
||||
keyStorePass), timelyHostname, timelyHttpsPort, timelyWssPort, clientAuth, doLogin, timelyUsername,
|
||||
timelyPassword, hostVerificationEnabled, bufferSize);
|
||||
keyStorePass), timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword,
|
||||
hostVerificationEnabled, bufferSize);
|
||||
}
|
||||
|
||||
public void open(ClientHandler clientEndpoint) throws IOException, DeploymentException, URISyntaxException {
|
||||
|
||||
Cookie sessionCookie = null;
|
||||
if (doLogin) {
|
||||
BasicCookieStore cookieJar = new BasicCookieStore();
|
||||
try (CloseableHttpClient client = HttpClient.get(ssl, cookieJar, hostVerificationEnabled, clientAuth)) {
|
||||
try (CloseableHttpClient client = HttpClient.get(ssl, cookieJar, hostVerificationEnabled)) {
|
||||
|
||||
String target = "https://" + timelyHostname + ":" + timelyHttpsPort + "/login";
|
||||
|
||||
@@ -142,8 +140,8 @@ public class WebSocketClient implements AutoCloseable {
|
||||
webSocketClient.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngine);
|
||||
webSocketClient.getProperties().put(ClientProperties.INCOMING_BUFFER_SIZE, bufferSize);
|
||||
String wssPath = "wss://" + timelyHostname + ":" + timelyWssPort + "/websocket";
|
||||
session = webSocketClient.connectToServer(clientEndpoint,
|
||||
new TimelyEndpointConfig(clientEndpoint, sessionCookie), new URI(wssPath));
|
||||
session = webSocketClient.connectToServer(clientEndpoint, new TimelyEndpointConfig(sessionCookie),
|
||||
new URI(wssPath));
|
||||
|
||||
final ByteBuffer pingData = ByteBuffer.allocate(0);
|
||||
webSocketClient.getScheduledExecutorService().scheduleAtFixedRate(() -> {
|
||||
|
||||
+10
-10
@@ -27,21 +27,21 @@ public class WebSocketSubscriptionClient extends WebSocketClient {
|
||||
private final String subscriptionId;
|
||||
|
||||
public WebSocketSubscriptionClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort,
|
||||
boolean clientAuth, boolean doLogin, String timelyUsername, String timelyPassword,
|
||||
boolean hostVerificationEnabled, int bufferSize) {
|
||||
super(ssl, timelyHostname, timelyHttpsPort, timelyWssPort, clientAuth, doLogin, timelyUsername, timelyPassword,
|
||||
boolean doLogin, String timelyUsername, String timelyPassword, boolean hostVerificationEnabled,
|
||||
int bufferSize) {
|
||||
super(ssl, timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword,
|
||||
hostVerificationEnabled, bufferSize);
|
||||
subscriptionId = UUID.randomUUID().toString();
|
||||
LOG.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
||||
}
|
||||
|
||||
public WebSocketSubscriptionClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort,
|
||||
boolean clientAuth, boolean doLogin, String timelyUsername, String timelyPassword, String keyStoreFile,
|
||||
String keyStoreType, String keyStorePass, String trustStoreFile, String trustStoreType,
|
||||
String trustStorePass, boolean hostVerificationEnabled, int bufferSize) {
|
||||
super(timelyHostname, timelyHttpsPort, timelyWssPort, clientAuth, doLogin, timelyUsername, timelyPassword,
|
||||
keyStoreFile, keyStoreType, keyStorePass, trustStoreFile, trustStoreType, trustStorePass,
|
||||
hostVerificationEnabled, bufferSize);
|
||||
public WebSocketSubscriptionClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean doLogin,
|
||||
String timelyUsername, String timelyPassword, String keyStoreFile, String keyStoreType, String keyStorePass,
|
||||
String trustStoreFile, String trustStoreType, String trustStorePass, boolean hostVerificationEnabled,
|
||||
int bufferSize) {
|
||||
super(timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword, keyStoreFile,
|
||||
keyStoreType, keyStorePass, trustStoreFile, trustStoreType, trustStorePass, hostVerificationEnabled,
|
||||
bufferSize);
|
||||
subscriptionId = UUID.randomUUID().toString();
|
||||
LOG.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ public interface ObjectSizeOf {
|
||||
* ObjectSizeOf interface and if implemented on the object will use that.
|
||||
* Otherwise it will do a simple navigation of the fields using reflection.
|
||||
*
|
||||
* @param o
|
||||
* @return an approximation of the object size
|
||||
*/
|
||||
public static long getObjectSize(Object o, boolean useSizeInBytesMethod, boolean debug) {
|
||||
|
||||
@@ -77,6 +77,8 @@ public class Tag implements Comparable<Tag>, Serializable {
|
||||
|
||||
/**
|
||||
* Joins key and value into key=value
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String join() {
|
||||
return tagParser.combine(this);
|
||||
|
||||
@@ -47,6 +47,7 @@ public class TagListParser implements Parser<List<Tag>>, Combiner<Collection<Tag
|
||||
* An alternative combiner for a map of string to string instead of a list of
|
||||
* tags
|
||||
*
|
||||
* @param tags
|
||||
* @return string representation
|
||||
*/
|
||||
public String combine(Map<String, String> tags) {
|
||||
|
||||
@@ -23,7 +23,7 @@ def pivot(df, metric, groupByColumn=None):
|
||||
return dataFrame
|
||||
|
||||
|
||||
def resample(df, sample, how='mean', interpolate=True, fill=None):
|
||||
def resample(df, sample, how='mean'):
|
||||
|
||||
dataFrame = pandas.DataFrame(df, copy=True)
|
||||
if dataFrame is not None:
|
||||
|
||||
@@ -2,6 +2,7 @@ import time
|
||||
from datetime import datetime
|
||||
from datetime import timedelta
|
||||
from datetime import tzinfo
|
||||
from pandas.tslib import Timedelta
|
||||
import pandas
|
||||
|
||||
class TimeDateError(ValueError):
|
||||
|
||||
@@ -16,15 +16,14 @@ utc = UTC()
|
||||
class TimelyWebSocketClient(WebSocketClient):
|
||||
|
||||
def __init__(self, hostport, metric, tags, startTime, endTime, connect_timeout=WebSocketClient.DEFAULT_CONNECT_TIMEOUT,
|
||||
request_timeout=WebSocketClient.DEFAULT_REQUEST_TIMEOUT, client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||
request_timeout=WebSocketClient.DEFAULT_REQUEST_TIMEOUT):
|
||||
|
||||
self.metric = metric
|
||||
self.tags = tags
|
||||
self.startTime = startTime
|
||||
self.endTime = endTime
|
||||
self.subscriptionId = random.randint(1000000000, 9999999999)
|
||||
WebSocketClient.__init__(self, hostport, '/websocket', {'metric' : metric}, connect_timeout, request_timeout,
|
||||
client_cert=client_cert, client_key=client_key, ca_certs=ca_certs, validate_cert=validate_cert)
|
||||
WebSocketClient.__init__(self, hostport, '/websocket', {'metric' : metric}, connect_timeout, request_timeout)
|
||||
|
||||
def _on_message(self, msg):
|
||||
# implement in subclass
|
||||
@@ -73,8 +72,7 @@ class TimelyMetric(TimelyWebSocketClient):
|
||||
client = None
|
||||
endtime = None
|
||||
|
||||
def __init__(self, hostport, metric, tags, beginStr, endStr, period, sample,
|
||||
client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||
def __init__(self, hostport, metric, tags, beginStr, endStr, period, sample):
|
||||
self.series = pandas.Series()
|
||||
self.metric = metric
|
||||
self.tags = tags
|
||||
@@ -84,8 +82,7 @@ class TimelyMetric(TimelyWebSocketClient):
|
||||
self.data = []
|
||||
self.timeDateRange = TimeDateRange(beginStr, endStr, period)
|
||||
|
||||
TimelyWebSocketClient.__init__(self, hostport, metric, tags, self.timeDateRange.getBeginMs(), self.timeDateRange.getEndMs(),
|
||||
client_cert=client_cert, client_key=client_key, ca_certs=ca_certs, validate_cert=validate_cert)
|
||||
TimelyWebSocketClient.__init__(self, hostport, metric, tags, self.timeDateRange.getBeginMs(), self.timeDateRange.getEndMs())
|
||||
|
||||
def debugOn(self):
|
||||
self.debug = True
|
||||
|
||||
@@ -15,14 +15,10 @@ class WebSocketClient():
|
||||
APPLICATION_JSON = 'application/json'
|
||||
|
||||
def __init__(self, hostport, path, params, connect_timeout=DEFAULT_CONNECT_TIMEOUT,
|
||||
request_timeout=DEFAULT_REQUEST_TIMEOUT, client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||
request_timeout=DEFAULT_REQUEST_TIMEOUT):
|
||||
|
||||
self.connect_timeout = connect_timeout
|
||||
self.request_timeout = request_timeout
|
||||
self.client_cert=client_cert
|
||||
self.client_key=client_key
|
||||
self.ca_certs=ca_certs
|
||||
self.validate_cert=validate_cert
|
||||
self.url = 'wss://' + hostport
|
||||
if (path is not None and len(path) > 0):
|
||||
if (path.startswith('/')):
|
||||
@@ -43,8 +39,7 @@ class WebSocketClient():
|
||||
"""Connect to the server.
|
||||
:param str url: server URL.
|
||||
"""
|
||||
request = websocket.httpclient.HTTPRequest(self.url, connect_timeout=self.connect_timeout, request_timeout=self.request_timeout, validate_cert=self.validate_cert,
|
||||
client_cert=self.client_cert, client_key=self.client_key, ca_certs=self.ca_certs)
|
||||
request = websocket.httpclient.HTTPRequest(self.url, connect_timeout=self.connect_timeout, request_timeout=self.request_timeout, validate_cert=False)
|
||||
websocket.websocket_connect(request, io_loop=ioloop, callback=self._connect_callback)
|
||||
|
||||
def send(self, data):
|
||||
|
||||
@@ -5,9 +5,7 @@ import os
|
||||
from timely.TimelyAnalyticConfiguration import TimelyAnalyticConfiguration
|
||||
|
||||
hostport = "127.0.0.1:5244"
|
||||
client_cert = None
|
||||
client_key = None
|
||||
timelyMetric = timely.TimelyMetric.TimelyMetric(hostport, 'timely.keys.metric.inserted', None, None, None, '24 hours', None, client_cert=client_cert, client_key=client_key).fetch()
|
||||
timelyMetric = timely.TimelyMetric.TimelyMetric(hostport, 'timely.keys.metric.inserted', None, None, None, '24 hours', None).fetch()
|
||||
|
||||
print(timelyMetric.getDataFrame())
|
||||
exit()
|
||||
|
||||
@@ -5,9 +5,4 @@
|
||||
<Method name="connect" />
|
||||
<Class name="timely.client.tcp.TcpClient"/>
|
||||
</Match>
|
||||
<Match>
|
||||
<!-- Must ignore these everywhere, because of a javac byte code generation bug -->
|
||||
<!-- https://github.com/spotbugs/spotbugs/issues/756 -->
|
||||
<Bug pattern="RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE" />
|
||||
</Match>
|
||||
</FindBugsFilter>
|
||||
@@ -47,9 +47,9 @@ public class SerializationTest {
|
||||
testSerialization(remove);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> void testSerialization(T o) throws Exception {
|
||||
String ser = mapper.writeValueAsString(o);
|
||||
@SuppressWarnings("unchecked")
|
||||
T des = mapper.readValue(ser, (Class<T>) o.getClass());
|
||||
Assert.assertEquals(o, des);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>collectd-nsq-plugin</artifactId>
|
||||
<dependencies>
|
||||
|
||||
+8
-8
@@ -10,7 +10,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.collectd.api.OConfigItem;
|
||||
|
||||
public class PooledCloseableHttpClientFactory implements PooledObjectFactory<CloseableHttpClient> {
|
||||
public class PooledCloseableHttpClientFactory implements PooledObjectFactory {
|
||||
|
||||
private int connectionRequestTimeout = 10000; // 10 seconds in milliseconds
|
||||
private int connectTimeout = 30000; // 30 seconds in milliseconds
|
||||
@@ -43,19 +43,19 @@ public class PooledCloseableHttpClientFactory implements PooledObjectFactory<Clo
|
||||
}
|
||||
|
||||
@Override
|
||||
public PooledObject<CloseableHttpClient> makeObject() throws Exception {
|
||||
public PooledObject makeObject() throws Exception {
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
|
||||
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
|
||||
HttpClientBuilder builder = HttpClientBuilder.create();
|
||||
builder.setDefaultRequestConfig(requestConfig);
|
||||
builder.setConnectionTimeToLive(connectionTimeToLive, TimeUnit.MILLISECONDS);
|
||||
return new DefaultPooledObject<>(builder.build());
|
||||
return new DefaultPooledObject(builder.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyObject(PooledObject<CloseableHttpClient> pooledObject) throws Exception {
|
||||
public void destroyObject(PooledObject pooledObject) throws Exception {
|
||||
try {
|
||||
pooledObject.getObject().close();
|
||||
((CloseableHttpClient) pooledObject.getObject()).close();
|
||||
} catch (Exception e) {
|
||||
// do nothing
|
||||
} finally {
|
||||
@@ -65,17 +65,17 @@ public class PooledCloseableHttpClientFactory implements PooledObjectFactory<Clo
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateObject(PooledObject<CloseableHttpClient> pooledObject) {
|
||||
public boolean validateObject(PooledObject pooledObject) {
|
||||
return pooledObject.getObject() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void activateObject(PooledObject<CloseableHttpClient> pooledObject) throws Exception {
|
||||
public void activateObject(PooledObject pooledObject) throws Exception {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void passivateObject(PooledObject<CloseableHttpClient> pooledObject) throws Exception {
|
||||
public void passivateObject(PooledObject pooledObject) throws Exception {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ public class WriteNSQPlugin extends CollectDPluginParent
|
||||
Collectd.registerWrite(WriteNSQPlugin.class.getName(), this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int write(ValueList vl) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
DataOutputStream out = new DataOutputStream(baos);
|
||||
@@ -111,17 +110,15 @@ public class WriteNSQPlugin extends CollectDPluginParent
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int shutdown() {
|
||||
Collectd.logInfo("Shutting down connection to NSQ at " + host + ":" + port);
|
||||
clientPool.close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int config(OConfigItem config) {
|
||||
super.config(config);
|
||||
GenericObjectPoolConfig<CloseableHttpClient> poolConfig = new GenericObjectPoolConfig<>();
|
||||
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
|
||||
// use max size for maxTotal and maxIdle
|
||||
// no need to activate or passivate
|
||||
poolConfig.setMaxTotal(POOL_MAX_SIZE);
|
||||
@@ -159,7 +156,7 @@ public class WriteNSQPlugin extends CollectDPluginParent
|
||||
Collectd.logError("NSQ host, port, and topic must be configured");
|
||||
return -1;
|
||||
}
|
||||
this.clientPool = new GenericObjectPool<>(pooledCloseableHttpClientFactory, poolConfig);
|
||||
this.clientPool = new GenericObjectPool(pooledCloseableHttpClientFactory, poolConfig);
|
||||
this.endpoint = "http://" + host + ":" + port + "/mpub?topic=" + topic;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>collectd-plugin-parent</artifactId>
|
||||
<dependencies>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>collectd-timely-plugin</artifactId>
|
||||
<dependencies>
|
||||
|
||||
+7
-7
@@ -8,7 +8,7 @@ import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||
import org.collectd.api.Collectd;
|
||||
import org.collectd.api.OConfigItem;
|
||||
|
||||
public class PooledSocketFactory implements PooledObjectFactory<Socket> {
|
||||
public class PooledSocketFactory implements PooledObjectFactory {
|
||||
|
||||
private String host = null;
|
||||
private int port = 0;
|
||||
@@ -81,12 +81,12 @@ public class PooledSocketFactory implements PooledObjectFactory<Socket> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public PooledObject<Socket> makeObject() throws Exception {
|
||||
return new DefaultPooledObject<>(connect());
|
||||
public PooledObject makeObject() throws Exception {
|
||||
return new DefaultPooledObject(connect());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyObject(PooledObject<Socket> pooledObject) throws Exception {
|
||||
public void destroyObject(PooledObject pooledObject) throws Exception {
|
||||
try {
|
||||
Collectd.logDebug("Shutting down connection to Timely at " + host + ":" + port);
|
||||
Socket socket = (Socket) pooledObject.getObject();
|
||||
@@ -103,7 +103,7 @@ public class PooledSocketFactory implements PooledObjectFactory<Socket> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateObject(PooledObject<Socket> pooledObject) {
|
||||
public boolean validateObject(PooledObject pooledObject) {
|
||||
if (connectionTimeToLive > -1) {
|
||||
if (System.currentTimeMillis() > pooledObject.getCreateTime() + connectionTimeToLive) {
|
||||
return false;
|
||||
@@ -114,12 +114,12 @@ public class PooledSocketFactory implements PooledObjectFactory<Socket> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void activateObject(PooledObject<Socket> pooledObject) throws Exception {
|
||||
public void activateObject(PooledObject pooledObject) throws Exception {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void passivateObject(PooledObject<Socket> pooledObject) throws Exception {
|
||||
public void passivateObject(PooledObject pooledObject) throws Exception {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
@@ -86,13 +86,13 @@ public class WriteTimelyPlugin extends CollectDPluginParent
|
||||
PooledSocketFactory socketFactory = new PooledSocketFactory();
|
||||
retval = socketFactory.config(config);
|
||||
if (retval == 0) {
|
||||
GenericObjectPoolConfig<Socket> poolConfig = new GenericObjectPoolConfig<>();
|
||||
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
|
||||
// use max size for maxTotal and maxIdle
|
||||
// no need to activate and passivate
|
||||
poolConfig.setMaxTotal(POOL_MAX_SIZE);
|
||||
poolConfig.setMaxIdle(POOL_MAX_SIZE);
|
||||
poolConfig.setTestOnReturn(true);
|
||||
socketPool = new GenericObjectPool<>(socketFactory, poolConfig);
|
||||
socketPool = new GenericObjectPool(socketFactory, poolConfig);
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-common</artifactId>
|
||||
<dependencies>
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [[ `uname` == "Darwin" ]]; then
|
||||
THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0`
|
||||
TCNATIVE_SUFFIX="jnilib"
|
||||
else
|
||||
THIS_SCRIPT=`readlink -f $0`
|
||||
TCNATIVE_SUFFIX="so"
|
||||
fi
|
||||
|
||||
THIS_DIR="${THIS_SCRIPT%/*}"
|
||||
NATIVE_DIR="${THIS_DIR}/META-INF/native"
|
||||
BASE_DIR=${THIS_DIR}/..
|
||||
TMP_DIR="${BASE_DIR}/tmp"
|
||||
CONF_DIR="${BASE_DIR}/conf"
|
||||
LIB_DIR="${BASE_DIR}/lib"
|
||||
NUM_SERVER_THREADS=4
|
||||
|
||||
if [[ -e ${TMP_DIR} ]]; then
|
||||
rm -rf ${TMP_DIR}
|
||||
fi
|
||||
mkdir ${TMP_DIR}
|
||||
|
||||
if [[ -e ${NATIVE_DIR} ]]; then
|
||||
rm -rf ${NATIVE_DIR}
|
||||
fi
|
||||
mkdir -p ${NATIVE_DIR}
|
||||
|
||||
pushd ${BASE_DIR}/bin
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative-boringssl-static*.jar META-INF/native/libnetty_tcnative_linux_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-all*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
popd
|
||||
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*:${HADOOP_CONF_DIR}"
|
||||
JVM_ARGS="-Xmx1G -Xms1G -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS} Dlog4j.configurationFile=${CONF_DIR}/log4j2-spring.xml"
|
||||
JVM_ARGS="${JVM_ARGS} -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}"
|
||||
|
||||
#JVM_ARGS="${JVM_ARGS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
|
||||
|
||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.grafana.auth.GrafanaAuth --spring.config.name=grafana-auth"
|
||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.grafana.auth.GrafanaAuth --spring.config.name=grafana-auth
|
||||
@@ -1,55 +0,0 @@
|
||||
grafana-auth:
|
||||
grafana:
|
||||
host: localhost
|
||||
port: 3001
|
||||
security:
|
||||
session-max-age: 86400
|
||||
cache-expiration-minutes: 60
|
||||
cache-refresh-minutes: 5
|
||||
allow-anonymous-http-access: true
|
||||
allow-anonymous-ws-access: true
|
||||
serverSsl:
|
||||
certificate-file:
|
||||
key-file:
|
||||
#key-password:
|
||||
use-generated-keypair: true
|
||||
trust-store-file:
|
||||
use-openssl: true
|
||||
#use-ciphers:
|
||||
clientSsl:
|
||||
keyFile:
|
||||
keyType: pkcs12
|
||||
#keyPassword:
|
||||
trustStoreFile:
|
||||
trustStoreType: jks
|
||||
#trustStorePassword:
|
||||
http:
|
||||
host: localhost
|
||||
ip: 127.0.0.1
|
||||
port: 3000
|
||||
redirect-path: /secure-me
|
||||
strict-transport-max-age: 608400
|
||||
cors:
|
||||
allow-any-origin: false
|
||||
allow-null-origin: false
|
||||
allow-credentials: true
|
||||
allowed-origins:
|
||||
allowed-methods: DELETE,GET,HEAD,OPTIONS,PUT,POST
|
||||
allowed-headers: content-type
|
||||
httpClientPool:
|
||||
minIdlePerKey: 0
|
||||
maxIdlePerKey: 40
|
||||
maxTotalPerKey: 40
|
||||
maxTotal: -1
|
||||
lifo: true
|
||||
fairness: false
|
||||
maxWaitMillis: -1
|
||||
minEvictableIdleTimeMillis: 1800000
|
||||
evictorShutdownTimeoutMillis: 10000
|
||||
softMinEvictableIdleTimeMillis: -1
|
||||
numTestsPerEvictionRun: 3
|
||||
timeBetweenEvictionRunsMillis: -1
|
||||
blockWhenExhausted: true
|
||||
jmxEnabled: true
|
||||
testOnBorrow: false
|
||||
testOnReturn: false
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="warn" monitorInterval="60">
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="error" includeLocation="false">
|
||||
<AppenderRef ref="Console" level="error" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
@@ -1,29 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="warn" monitorInterval="60">
|
||||
<Properties>
|
||||
<Property name="PID">????</Property>
|
||||
<Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%wEx</Property>
|
||||
</Properties>
|
||||
<Appenders>
|
||||
<RollingRandomAccessFile name="Rolling" fileName="/srv/logs/timely/grafana-auth.log"
|
||||
filePattern="/srv/logs/timely/$${date:yyyy-MM}/grafana-auth-%d{MM-dd-yyyy}-%i.log.gz">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
<Policies>
|
||||
<SizeBasedTriggeringPolicy size="1024 MB" />
|
||||
</Policies>
|
||||
<DefaultRolloverStrategy max="10" />
|
||||
</RollingRandomAccessFile>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Root level="trace" includeLocation="false">
|
||||
<AppenderRef ref="Console" level="warn" />
|
||||
<AppenderRef ref="Rolling" level="trace" />
|
||||
</Root>
|
||||
<Logger name="timely" additivity="false">
|
||||
<AppenderRef ref="Console" level="debug" />
|
||||
</Logger>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
@@ -1,71 +0,0 @@
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/util
|
||||
http://www.springframework.org/schema/util/spring-util.xsd">
|
||||
|
||||
<beans:bean id="x509PrincipalExtractor" class="org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor">
|
||||
<beans:property name="subjectDnRegex" value="CN=(.*?)(?:,|$)"/>
|
||||
</beans:bean>
|
||||
|
||||
<beans:bean id="timelyUserDetailsService" class="timely.auth.UserDetailsService">
|
||||
<beans:property name="users">
|
||||
<util:list>
|
||||
<beans:bean class="timely.auth.TimelyUser">
|
||||
<beans:constructor-arg name="subjectDn">
|
||||
<beans:value>CN=example.com</beans:value>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="auths">
|
||||
<util:list>
|
||||
<beans:value>D</beans:value>
|
||||
<beans:value>E</beans:value>
|
||||
<beans:value>F</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="roles">
|
||||
<util:list>
|
||||
<beans:value>G</beans:value>
|
||||
<beans:value>H</beans:value>
|
||||
<beans:value>I</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
</beans:bean>
|
||||
</util:list>
|
||||
</beans:property>
|
||||
</beans:bean>
|
||||
|
||||
<beans:bean id="x509AuthorizationProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
|
||||
<beans:property name="preAuthenticatedUserDetailsService" ref="timelyUserDetailsService" />
|
||||
</beans:bean>
|
||||
|
||||
<user-service id="usernamePasswordService">
|
||||
<user name="test" password="test1" authorities="A,B,C" />
|
||||
</user-service>
|
||||
|
||||
<beans:bean id="noOpPasswordEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"/>
|
||||
|
||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
<beans:property name="userDetailsService" ref="usernamePasswordService"/>
|
||||
<beans:property name="passwordEncoder" ref="noOpPasswordEncoder"/>
|
||||
</beans:bean>
|
||||
|
||||
<authentication-manager alias="authenticationManager">
|
||||
<!-- X509 PreAuthenticated authorization provider -->
|
||||
<authentication-provider ref="x509AuthorizationProvider"/>
|
||||
<!-- Basic authorization provider, validates provided username and password -->
|
||||
<authentication-provider ref="UserNamePasswordAuthenticationProvider" />
|
||||
</authentication-manager>
|
||||
|
||||
<util:list id="requiredRoles" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
|
||||
<util:list id="requiredAuths" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
</beans:beans>
|
||||
@@ -1,295 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
</parent>
|
||||
<artifactId>grafana-auth</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jdk8</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.flatbuffers</groupId>
|
||||
<artifactId>flatbuffers-java</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-beanutils</groupId>
|
||||
<artifactId>commons-beanutils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.lukehutch</groupId>
|
||||
<artifactId>fast-classpath-scanner</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.javacsv</groupId>
|
||||
<artifactId>javacsv</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.accumulo</groupId>
|
||||
<artifactId>accumulo-core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-log4j12</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.accumulo</groupId>
|
||||
<artifactId>accumulo-minicluster</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-framework</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-recipes</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-x-discovery</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.hadoop</groupId>
|
||||
<artifactId>hadoop-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.hadoop</groupId>
|
||||
<artifactId>hadoop-common</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>jdk.tools</groupId>
|
||||
<artifactId>jdk.tools</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.hadoop</groupId>
|
||||
<artifactId>hadoop-minicluster</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-websocket</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-balancer</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.lmax</groupId>
|
||||
<artifactId>disruptor</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-slf4j-impl</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
<artifactId>javassist</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-test-autoconfigure</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble</id>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<phase>package</phase>
|
||||
<configuration>
|
||||
<descriptors>
|
||||
<descriptor>src/main/dist/assembly.xml</descriptor>
|
||||
</descriptors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<phase>prepare-package</phase>
|
||||
<configuration>
|
||||
<excludeArtifactIds>junit</excludeArtifactIds>
|
||||
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>unpack-native</id>
|
||||
<goals>
|
||||
<goal>unpack</goal>
|
||||
</goals>
|
||||
<phase>process-test-classes</phase>
|
||||
<configuration>
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
<type>jar</type>
|
||||
<overWrite>false</overWrite>
|
||||
<outputDirectory>${project.build.directory}/native</outputDirectory>
|
||||
<includes>**/*.so</includes>
|
||||
</artifactItem>
|
||||
</artifactItems>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<phase>generate-sources</phase>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/generated-java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<extensions>
|
||||
<!-- Use os-maven-plugin to initialize the "os.detected" properties -->
|
||||
<extension>
|
||||
<groupId>kr.motd.maven</groupId>
|
||||
<artifactId>os-maven-plugin</artifactId>
|
||||
</extension>
|
||||
</extensions>
|
||||
</build>
|
||||
</project>
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
|
||||
<id>dist</id>
|
||||
<formats>
|
||||
<format>tar.gz</format>
|
||||
</formats>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${project.basedir}</directory>
|
||||
<outputDirectory></outputDirectory>
|
||||
<includes>
|
||||
<include>README*</include>
|
||||
<include>LICENSE*</include>
|
||||
<include>NOTICE*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${project.build.directory}</directory>
|
||||
<outputDirectory>lib</outputDirectory>
|
||||
<includes>
|
||||
<include>timely*.jar</include>
|
||||
<include>grafana*.jar</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${project.build.directory}/lib</directory>
|
||||
<outputDirectory>lib</outputDirectory>
|
||||
<includes>
|
||||
<include>*.jar</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${project.basedir}/bin</directory>
|
||||
<outputDirectory>bin</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${project.basedir}/conf</directory>
|
||||
<outputDirectory>conf</outputDirectory>
|
||||
<includes>
|
||||
<include>*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${project.basedir}/src/main/resources/webapp</directory>
|
||||
<outputDirectory>bin/webapp</outputDirectory>
|
||||
<includes>
|
||||
<include>*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
</assembly>
|
||||
@@ -1,321 +0,0 @@
|
||||
package timely.grafana.auth;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.PooledByteBufAllocator;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.epoll.EpollEventLoopGroup;
|
||||
import io.netty.channel.epoll.EpollServerSocketChannel;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.ServerSocketChannel;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.http.HttpContentCompressor;
|
||||
import io.netty.handler.codec.http.HttpContentDecompressor;
|
||||
import io.netty.handler.codec.http.HttpObjectAggregator;
|
||||
import io.netty.handler.codec.http.HttpRequestDecoder;
|
||||
import io.netty.handler.codec.http.HttpResponseEncoder;
|
||||
import io.netty.handler.logging.LoggingHandler;
|
||||
import io.netty.handler.ssl.ClientAuth;
|
||||
import io.netty.handler.ssl.OpenSslServerContext;
|
||||
import io.netty.handler.ssl.OpenSslServerSessionContext;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.SslProvider;
|
||||
import io.netty.handler.ssl.util.SelfSignedCertificate;
|
||||
import io.netty.handler.stream.ChunkedWriteHandler;
|
||||
import io.netty.util.internal.SystemPropertyUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import timely.auth.AuthCache;
|
||||
import timely.balancer.configuration.ClientSsl;
|
||||
import timely.balancer.connection.http.HttpClientPool;
|
||||
import timely.client.http.HttpClient;
|
||||
import timely.configuration.ServerSsl;
|
||||
import timely.grafana.auth.configuration.GrafanaAuthConfiguration;
|
||||
import timely.grafana.auth.configuration.SpringBootstrap;
|
||||
import timely.grafana.auth.netty.http.GrafanaRelayHandler;
|
||||
import timely.grafana.auth.netty.http.GrafanaRequestDecoder;
|
||||
import timely.netty.http.HttpStaticFileServerHandler;
|
||||
import timely.netty.http.NonSslRedirectHandler;
|
||||
import timely.netty.http.TimelyExceptionHandler;
|
||||
import timely.netty.http.auth.X509LoginRequestHandler;
|
||||
|
||||
public class GrafanaAuth {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GrafanaAuth.class);
|
||||
private static final int EPOLL_MIN_MAJOR_VERSION = 2;
|
||||
private static final int EPOLL_MIN_MINOR_VERSION = 6;
|
||||
private static final int EPOLL_MIN_PATCH_VERSION = 32;
|
||||
private static final String OS_NAME = "os.name";
|
||||
private static final String OS_VERSION = "os.version";
|
||||
protected static final CountDownLatch LATCH = new CountDownLatch(1);
|
||||
static ConfigurableApplicationContext applicationContext;
|
||||
|
||||
private final GrafanaAuthConfiguration grafanaAuthConfig;
|
||||
private EventLoopGroup httpWorkerGroup = null;
|
||||
private EventLoopGroup httpBossGroup = null;
|
||||
protected Channel httpChannelHandle = null;
|
||||
protected volatile boolean shutdown = false;
|
||||
|
||||
public GrafanaAuth(GrafanaAuthConfiguration grafanaAuthConfig) throws Exception {
|
||||
this.grafanaAuthConfig = grafanaAuthConfig;
|
||||
}
|
||||
|
||||
protected static ConfigurableApplicationContext initializeConfiguration(String[] args) {
|
||||
return new SpringApplicationBuilder(SpringBootstrap.class).web(WebApplicationType.NONE).run(args);
|
||||
}
|
||||
|
||||
private void shutdownHook() {
|
||||
|
||||
final Runnable shutdownRunner = () -> {
|
||||
if (!shutdown) {
|
||||
shutdown();
|
||||
}
|
||||
};
|
||||
final Thread hook = new Thread(shutdownRunner, "shutdown-hook-thread");
|
||||
Runtime.getRuntime().addShutdownHook(hook);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
List<ChannelFuture> channelFutures = new ArrayList<>();
|
||||
|
||||
if (httpChannelHandle != null) {
|
||||
LOG.info("Closing httpChannelHandle");
|
||||
channelFutures.add(httpChannelHandle.close());
|
||||
}
|
||||
|
||||
// wait for the channels to shutdown
|
||||
channelFutures.forEach(f -> {
|
||||
try {
|
||||
f.get();
|
||||
} catch (final Exception e) {
|
||||
LOG.error("Error while shutting down channel: {}", f.channel().config());
|
||||
LOG.error("{}", e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
|
||||
Integer quietPeriod = grafanaAuthConfig.getShutdownQuietPeriod();
|
||||
List<Future<?>> groupFutures = new ArrayList<>();
|
||||
|
||||
if (httpBossGroup != null) {
|
||||
LOG.info("Shutting down httpBossGroup");
|
||||
groupFutures.add(httpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
if (httpWorkerGroup != null) {
|
||||
LOG.info("Shutting down httpWorkerGroup");
|
||||
groupFutures.add(httpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
groupFutures.parallelStream().forEach(f -> {
|
||||
try {
|
||||
f.get();
|
||||
} catch (final Exception e) {
|
||||
LOG.error("Error while shutting down group: {}", f.toString());
|
||||
LOG.error("{}", e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
|
||||
if (applicationContext != null) {
|
||||
LOG.info("Closing applicationContext");
|
||||
applicationContext.close();
|
||||
}
|
||||
|
||||
this.shutdown = true;
|
||||
LOG.info("Server shut down.");
|
||||
}
|
||||
|
||||
private static boolean useEpoll() {
|
||||
|
||||
// Should we just return true if this is Linux and if we get an error
|
||||
// during Epoll
|
||||
// setup handle it there?
|
||||
final String os = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
|
||||
final String[] version = SystemPropertyUtil.get(OS_VERSION).toLowerCase().trim().split("\\.");
|
||||
if (os.startsWith("linux") && version.length >= 3) {
|
||||
final int major = Integer.parseInt(version[0]);
|
||||
if (major > EPOLL_MIN_MAJOR_VERSION) {
|
||||
return true;
|
||||
} else if (major == EPOLL_MIN_MAJOR_VERSION) {
|
||||
final int minor = Integer.parseInt(version[1]);
|
||||
if (minor > EPOLL_MIN_MINOR_VERSION) {
|
||||
return true;
|
||||
} else if (minor == EPOLL_MIN_MINOR_VERSION) {
|
||||
final int patch = Integer.parseInt(version[2].substring(0, 2));
|
||||
return patch >= EPOLL_MIN_PATCH_VERSION;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected SslContext createSSLContext(GrafanaAuthConfiguration config) throws Exception {
|
||||
|
||||
ServerSsl sslCfg = config.getSecurity().getServerSsl();
|
||||
Boolean generate = sslCfg.isUseGeneratedKeypair();
|
||||
SslContextBuilder ssl;
|
||||
if (generate) {
|
||||
LOG.warn("Using generated self signed server certificate");
|
||||
Date begin = new Date();
|
||||
Date end = new Date(begin.getTime() + 86400000);
|
||||
SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
|
||||
ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
|
||||
} else {
|
||||
String cert = sslCfg.getCertificateFile();
|
||||
String key = sslCfg.getKeyFile();
|
||||
String keyPass = sslCfg.getKeyPassword();
|
||||
if (null == cert || null == key) {
|
||||
throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
|
||||
}
|
||||
ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
|
||||
}
|
||||
|
||||
ssl.ciphers(sslCfg.getUseCiphers());
|
||||
|
||||
// Can't set to REQUIRE because the CORS pre-flight requests will fail.
|
||||
ssl.clientAuth(ClientAuth.OPTIONAL);
|
||||
|
||||
Boolean useOpenSSL = sslCfg.isUseOpenssl();
|
||||
if (useOpenSSL) {
|
||||
ssl.sslProvider(SslProvider.OPENSSL);
|
||||
} else {
|
||||
ssl.sslProvider(SslProvider.JDK);
|
||||
}
|
||||
String trustStore = sslCfg.getTrustStoreFile();
|
||||
if (null != trustStore) {
|
||||
if (!trustStore.isEmpty()) {
|
||||
ssl.trustManager(new File(trustStore));
|
||||
}
|
||||
}
|
||||
return ssl.build();
|
||||
}
|
||||
|
||||
protected SSLContext createSSLClientContext(GrafanaAuthConfiguration config) throws Exception {
|
||||
|
||||
ClientSsl ssl = config.getSecurity().getClientSsl();
|
||||
return HttpClient.getSSLContext(ssl.getTrustStoreFile(), ssl.getTrustStoreType(), ssl.getTrustStorePassword(),
|
||||
ssl.getKeyFile(), ssl.getKeyType(), ssl.getKeyPassword());
|
||||
}
|
||||
|
||||
public void run() throws Exception {
|
||||
|
||||
AuthCache.configure(grafanaAuthConfig.getSecurity());
|
||||
final boolean useEpoll = useEpoll();
|
||||
Class<? extends ServerSocketChannel> channelClass;
|
||||
if (useEpoll) {
|
||||
httpWorkerGroup = new EpollEventLoopGroup();
|
||||
httpBossGroup = new EpollEventLoopGroup();
|
||||
channelClass = EpollServerSocketChannel.class;
|
||||
} else {
|
||||
httpWorkerGroup = new NioEventLoopGroup();
|
||||
httpBossGroup = new NioEventLoopGroup();
|
||||
channelClass = NioServerSocketChannel.class;
|
||||
}
|
||||
LOG.info("Using channel class {}", channelClass.getSimpleName());
|
||||
|
||||
final int httpPort = grafanaAuthConfig.getHttp().getPort();
|
||||
final String httpIp = grafanaAuthConfig.getHttp().getIp();
|
||||
SslContext sslCtx = createSSLContext(grafanaAuthConfig);
|
||||
if (sslCtx instanceof OpenSslServerContext) {
|
||||
OpenSslServerContext openssl = (OpenSslServerContext) sslCtx;
|
||||
String application = "GrafanaAuth_" + httpPort;
|
||||
OpenSslServerSessionContext opensslCtx = openssl.sessionContext();
|
||||
opensslCtx.setSessionCacheEnabled(true);
|
||||
opensslCtx.setSessionCacheSize(128);
|
||||
opensslCtx.setSessionIdContext(application.getBytes(StandardCharsets.UTF_8));
|
||||
opensslCtx.setSessionTimeout(grafanaAuthConfig.getSecurity().getSessionMaxAge());
|
||||
}
|
||||
SSLContext clientSSLContext = createSSLClientContext(grafanaAuthConfig);
|
||||
final ServerBootstrap httpServer = new ServerBootstrap();
|
||||
httpServer.group(httpBossGroup, httpWorkerGroup);
|
||||
httpServer.channel(channelClass);
|
||||
httpServer.handler(new LoggingHandler());
|
||||
HttpClientPool httpClientPool = new HttpClientPool(grafanaAuthConfig.getSecurity(), grafanaAuthConfig.getHttp(),
|
||||
clientSSLContext);
|
||||
httpServer.childHandler(setupHttpChannel(grafanaAuthConfig, sslCtx, httpClientPool));
|
||||
httpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||
httpServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||
httpServer.option(ChannelOption.SO_KEEPALIVE, true);
|
||||
httpChannelHandle = httpServer.bind(httpIp, httpPort).sync().channel();
|
||||
final String httpAddress = ((InetSocketAddress) httpChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||
|
||||
shutdownHook();
|
||||
LOG.info("Server started. Listening on {}:{} for HTTP traffic", httpAddress, httpPort);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
GrafanaAuth.applicationContext = GrafanaAuth.initializeConfiguration(args);
|
||||
GrafanaAuthConfiguration balancerConf = applicationContext.getBean(GrafanaAuthConfiguration.class);
|
||||
|
||||
GrafanaAuth b = new GrafanaAuth(balancerConf);
|
||||
try {
|
||||
b.run();
|
||||
LATCH.await();
|
||||
} catch (final InterruptedException e) {
|
||||
LOG.info("Server shutting down.");
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error running server.", e);
|
||||
} finally {
|
||||
try {
|
||||
b.shutdown();
|
||||
} catch (Exception e) {
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected ChannelHandler setupHttpChannel(GrafanaAuthConfiguration config, SslContext sslCtx,
|
||||
HttpClientPool httpClientPool) {
|
||||
|
||||
return new ChannelInitializer<SocketChannel>() {
|
||||
|
||||
@Override
|
||||
protected void initChannel(SocketChannel ch) throws Exception {
|
||||
|
||||
ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config.getHttp(), sslCtx));
|
||||
ch.pipeline().addLast("encoder", new HttpResponseEncoder());
|
||||
ch.pipeline().addLast("decoder", new HttpRequestDecoder());
|
||||
ch.pipeline().addLast("compressor", new HttpContentCompressor());
|
||||
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
|
||||
// high maximum contentLength so that grafana snapshots can be delivered
|
||||
// might not be necessary if inbound chunking (while proxying) is handled
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(2097152));
|
||||
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
|
||||
ch.pipeline().addLast("grafanaDecoder",
|
||||
new GrafanaRequestDecoder(config.getSecurity(), config.getHttp()));
|
||||
ch.pipeline().addLast("fileServer", new HttpStaticFileServerHandler());
|
||||
ch.pipeline().addLast("login", new X509LoginRequestHandler(config.getSecurity(), config.getHttp()));
|
||||
ch.pipeline().addLast("httpRelay", new GrafanaRelayHandler(config, httpClientPool));
|
||||
ch.pipeline().addLast("error", new TimelyExceptionHandler());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package timely.grafana.auth.configuration;
|
||||
|
||||
public class Grafana {
|
||||
|
||||
private String host = "localhost";
|
||||
private Integer port = 3000;
|
||||
private String protocol = "http";
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void setPort(Integer port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setProtocol(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package timely.grafana.auth.configuration;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import timely.balancer.configuration.BalancerHttp;
|
||||
import timely.balancer.configuration.BalancerSecurity;
|
||||
|
||||
@Validated
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "grafana-auth")
|
||||
public class GrafanaAuthConfiguration {
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private BalancerHttp http = new BalancerHttp();
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private BalancerSecurity security = new BalancerSecurity();
|
||||
|
||||
@Valid
|
||||
@NestedConfigurationProperty
|
||||
private Grafana grafana = new Grafana();
|
||||
|
||||
private Integer shutdownQuietPeriod = 5;
|
||||
|
||||
public BalancerSecurity getSecurity() {
|
||||
return security;
|
||||
}
|
||||
|
||||
public BalancerHttp getHttp() {
|
||||
return http;
|
||||
}
|
||||
|
||||
public Grafana getGrafana() {
|
||||
return grafana;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time to wait (in seconds) for connections to finish and to make sure no new
|
||||
* connections happen before shutting down Netty event loop groups.
|
||||
*/
|
||||
public int getShutdownQuietPeriod() {
|
||||
return this.shutdownQuietPeriod;
|
||||
}
|
||||
|
||||
public void setShutdownQuietPeriod(Integer quietPeriod) {
|
||||
this.shutdownQuietPeriod = quietPeriod;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package timely.grafana.auth.configuration;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication(scanBasePackageClasses = { SpringBootstrap.class })
|
||||
public class SpringBootstrap {
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
package timely.grafana.auth.netty.http;
|
||||
|
||||
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import io.netty.handler.codec.http.FullHttpResponse;
|
||||
import io.netty.handler.codec.http.HttpMethod;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.handler.codec.http.HttpVersion;
|
||||
import io.netty.util.ReferenceCountUtil;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpHead;
|
||||
import org.apache.http.client.methods.HttpOptions;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.message.BasicHeader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import timely.api.request.timeseries.HttpRequest;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.TimelyPrincipal;
|
||||
import timely.auth.TimelyUser;
|
||||
import timely.auth.util.DnUtils;
|
||||
import timely.auth.util.HttpHeaderUtils;
|
||||
import timely.balancer.connection.TimelyBalancedHost;
|
||||
import timely.balancer.connection.http.HttpClientPool;
|
||||
import timely.grafana.auth.configuration.GrafanaAuthConfiguration;
|
||||
import timely.grafana.request.GrafanaRequest;
|
||||
import timely.netty.http.TimelyHttpHandler;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class GrafanaRelayHandler extends SimpleChannelInboundHandler<HttpRequest> implements TimelyHttpHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GrafanaRelayHandler.class);
|
||||
private final HttpClientPool httpClientPool;
|
||||
private GrafanaAuthConfiguration config;
|
||||
|
||||
public GrafanaRelayHandler(GrafanaAuthConfiguration config, HttpClientPool httpClientPool) {
|
||||
this.config = config;
|
||||
this.httpClientPool = httpClientPool;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
|
||||
|
||||
CloseableHttpClient client = null;
|
||||
CloseableHttpResponse relayedResponse = null;
|
||||
FullHttpRequest request = null;
|
||||
GrafanaRequest grafanaRequest;
|
||||
TimelyBalancedHost k = null;
|
||||
String relayURI = null;
|
||||
try {
|
||||
try {
|
||||
request = msg.getHttpRequest();
|
||||
String originalURI = request.uri();
|
||||
originalURI = encodeURI(originalURI);
|
||||
|
||||
if (msg instanceof GrafanaRequest) {
|
||||
grafanaRequest = (GrafanaRequest) msg;
|
||||
} else {
|
||||
throw new UnsupportedOperationException("Request not supported");
|
||||
}
|
||||
TimelyAuthenticationToken token = grafanaRequest.getToken();
|
||||
if (token == null) {
|
||||
throw new IllegalStateException("No token on grafana request");
|
||||
}
|
||||
|
||||
String protocol = config.getGrafana().getProtocol();
|
||||
String host = config.getGrafana().getHost();
|
||||
Integer port = config.getGrafana().getPort();
|
||||
k = TimelyBalancedHost.of(host, -1, port, -1, -1);
|
||||
client = httpClientPool.borrowObject(k);
|
||||
Multimap<String, String> headers = HttpHeaderUtils.toMultimap(request.headers());
|
||||
|
||||
// If incoming user sets these headers, do not relay them
|
||||
headers.removeAll("x-webauth-user");
|
||||
headers.removeAll("x-webauth-name");
|
||||
TimelyPrincipal principal = token.getTimelyPrincipal();
|
||||
TimelyUser user = principal.getPrimaryUser();
|
||||
String subjectDn = user.getDn().subjectDN();
|
||||
String userName = DnUtils.getCommonName(subjectDn);
|
||||
String loginName = DnUtils.getShortName(subjectDn);
|
||||
headers.put("x-webauth-user", loginName);
|
||||
headers.put("x-webauth-name", userName);
|
||||
List<Header> relayedHeaderList = new ArrayList<>();
|
||||
for (Map.Entry<String, String> h : headers.entries()) {
|
||||
if (!h.getKey().equals(CONTENT_LENGTH.toString())) {
|
||||
relayedHeaderList.add(new BasicHeader(h.getKey(), h.getValue()));
|
||||
}
|
||||
}
|
||||
Header[] headerArray = new Header[relayedHeaderList.size()];
|
||||
relayedHeaderList.toArray(headerArray);
|
||||
relayURI = protocol + "://" + host + ":" + port + originalURI;
|
||||
if (request.method().equals(HttpMethod.HEAD)) {
|
||||
HttpHead relayedRequest = new HttpHead(relayURI);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
} else if (request.method().equals(HttpMethod.GET)) {
|
||||
HttpGet relayedRequest = new HttpGet(relayURI);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
} else if (request.method().equals(HttpMethod.POST)) {
|
||||
HttpPost relayedRequest = new HttpPost(relayURI);
|
||||
String content = request.content().toString(StandardCharsets.UTF_8);
|
||||
StringEntity entity = new StringEntity(content);
|
||||
relayedRequest.setEntity(entity);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
} else if (request.method().equals(HttpMethod.PUT)) {
|
||||
HttpPut relayedRequest = new HttpPut(relayURI);
|
||||
String content = request.content().toString(StandardCharsets.UTF_8);
|
||||
StringEntity entity = new StringEntity(content);
|
||||
relayedRequest.setEntity(entity);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
} else if (request.method().equals(HttpMethod.DELETE)) {
|
||||
HttpDelete relayedRequest = new HttpDelete(relayURI);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
} else if (request.method().equals(HttpMethod.OPTIONS)) {
|
||||
HttpOptions relayedRequest = new HttpOptions(relayURI);
|
||||
if (headerArray.length > 0) {
|
||||
relayedRequest.setHeaders(headerArray);
|
||||
}
|
||||
relayedResponse = client.execute(relayedRequest);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String message = e.getMessage();
|
||||
if (message == null) {
|
||||
LOG.error("", e);
|
||||
} else {
|
||||
LOG.error(message, e);
|
||||
}
|
||||
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
|
||||
e.getMessage(), e.getLocalizedMessage(), e));
|
||||
return;
|
||||
} finally {
|
||||
if (request != null && request instanceof AutoCloseable) {
|
||||
ReferenceCountUtil.release(request);
|
||||
}
|
||||
}
|
||||
|
||||
FullHttpResponse response = null;
|
||||
if (relayedResponse == null) {
|
||||
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.METHOD_NOT_ALLOWED.code(),
|
||||
"Method not allowed", "Method not allowed"));
|
||||
} else {
|
||||
LOG.debug("RequestURL:{} ResponseCode:{}", relayURI, relayedResponse.getStatusLine().getStatusCode());
|
||||
HttpEntity httpEntity = relayedResponse.getEntity();
|
||||
if (httpEntity == null) {
|
||||
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
|
||||
HttpResponseStatus.valueOf(relayedResponse.getStatusLine().getStatusCode()));
|
||||
} else {
|
||||
ByteArrayOutputStream baos = new MyByteArrayOutputStream();
|
||||
StreamUtils.copy(httpEntity.getContent(), baos);
|
||||
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
|
||||
HttpResponseStatus.valueOf(relayedResponse.getStatusLine().getStatusCode()),
|
||||
Unpooled.copiedBuffer(baos.toByteArray()));
|
||||
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
|
||||
}
|
||||
for (Header h : relayedResponse.getAllHeaders()) {
|
||||
response.headers().add(h.getName(), h.getValue());
|
||||
}
|
||||
sendResponse(ctx, response);
|
||||
}
|
||||
} finally {
|
||||
if (relayedResponse != null) {
|
||||
relayedResponse.close();
|
||||
}
|
||||
if (client != null && k != null) {
|
||||
httpClientPool.returnObject(k, client);
|
||||
} else {
|
||||
LOG.error("NOT RETURNING CONNECTION! " + msg.getHttpRequest().uri());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static public class MyByteArrayOutputStream extends ByteArrayOutputStream {
|
||||
|
||||
public MyByteArrayOutputStream() {
|
||||
}
|
||||
|
||||
public MyByteArrayOutputStream(int size) {
|
||||
super(size);
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public byte[] getBuf() {
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
|
||||
static public String encodeURI(String s) {
|
||||
try {
|
||||
s = s.replaceAll("\\{", URLEncoder.encode("{", "UTF-8"));
|
||||
s = s.replaceAll("\\}", URLEncoder.encode("}", "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package timely.grafana.auth.netty.http;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.MessageToMessageDecoder;
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import timely.api.request.AuthenticatedRequest;
|
||||
import timely.api.request.timeseries.HttpRequest;
|
||||
import timely.api.response.StrictTransportResponse;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.AuthCache;
|
||||
import timely.auth.AuthenticationService;
|
||||
import timely.auth.SubjectIssuerDNPair;
|
||||
import timely.auth.TimelyPrincipal;
|
||||
import timely.auth.util.HttpHeaderUtils;
|
||||
import timely.configuration.Http;
|
||||
import timely.configuration.Security;
|
||||
import timely.grafana.request.GrafanaRequest;
|
||||
import timely.netty.Constants;
|
||||
import timely.netty.http.TimelyHttpHandler;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class GrafanaRequestDecoder extends MessageToMessageDecoder<FullHttpRequest> implements TimelyHttpHandler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(GrafanaRequestDecoder.class);
|
||||
private static final String LOG_RECEIVED_REQUEST = "Received HTTP request {}";
|
||||
private static final String LOG_PARSED_REQUEST = "Parsed request {}";
|
||||
|
||||
private final Security security;
|
||||
private final String nonSecureRedirectAddress;
|
||||
|
||||
public GrafanaRequestDecoder(Security security, Http http) {
|
||||
|
||||
this.security = security;
|
||||
this.nonSecureRedirectAddress = http.getRedirectPath();
|
||||
}
|
||||
|
||||
public static String getSessionId(FullHttpRequest msg) {
|
||||
Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
|
||||
Collection<String> cookies = headers.get(HttpHeaderNames.COOKIE.toString());
|
||||
final StringBuilder buf = new StringBuilder();
|
||||
cookies.forEach(h -> {
|
||||
ServerCookieDecoder.STRICT.decode(h).forEach(c -> {
|
||||
if (c.name().equals(Constants.COOKIE_NAME)) {
|
||||
if (buf.length() == 0) {
|
||||
buf.append(c.value());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if (buf.length() == 0) {
|
||||
return null;
|
||||
} else {
|
||||
return buf.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception {
|
||||
|
||||
LOG.trace(LOG_RECEIVED_REQUEST, msg);
|
||||
|
||||
final String uri = msg.uri();
|
||||
final QueryStringDecoder decoder = new QueryStringDecoder(uri);
|
||||
if (decoder.path().equals(nonSecureRedirectAddress)) {
|
||||
out.add(new StrictTransportResponse());
|
||||
return;
|
||||
}
|
||||
|
||||
final String sessionId = getSessionId(msg);
|
||||
LOG.trace("SessionID: " + sessionId);
|
||||
|
||||
HttpRequest request;
|
||||
try {
|
||||
request = new GrafanaRequest();
|
||||
Multimap<String, String> headers = HttpHeaderUtils.toMultimap(msg.headers());
|
||||
((AuthenticatedRequest) request).addHeaders(headers);
|
||||
X509Certificate clientCert = AuthenticationService.getClientCertificate(ctx);
|
||||
TimelyAuthenticationToken token;
|
||||
if (StringUtils.isNotBlank(sessionId)) {
|
||||
TimelyPrincipal principal;
|
||||
((AuthenticatedRequest) request).setSessionId(sessionId);
|
||||
if (AuthCache.containsKey(sessionId)) {
|
||||
principal = AuthCache.get(sessionId);
|
||||
} else {
|
||||
principal = TimelyPrincipal.anonymousPrincipal();
|
||||
}
|
||||
SubjectIssuerDNPair dn = principal.getPrimaryUser().getDn();
|
||||
token = AuthenticationService.getAuthenticationToken(null, dn.subjectDN(), dn.issuerDN());
|
||||
} else if (clientCert != null) {
|
||||
token = AuthenticationService.getAuthenticationToken(clientCert, headers);
|
||||
} else {
|
||||
SubjectIssuerDNPair dn = TimelyPrincipal.anonymousPrincipal().getPrimaryUser().getDn();
|
||||
token = AuthenticationService.getAuthenticationToken(null, dn.subjectDN(), dn.issuerDN());
|
||||
}
|
||||
((AuthenticatedRequest) request).setToken(token);
|
||||
request.setHttpRequest(msg.copy());
|
||||
LOG.trace(LOG_PARSED_REQUEST, request);
|
||||
request.validate();
|
||||
out.add(request);
|
||||
} catch (UnsupportedOperationException | NullPointerException e) {
|
||||
// Return the original http request to route to the static file
|
||||
// server
|
||||
msg.retain();
|
||||
out.add(msg);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
try {
|
||||
AuthenticationService.enforceAccess((AuthenticatedRequest) request);
|
||||
} catch (TimelyException e) {
|
||||
if (!security.isAllowAnonymousHttpAccess()) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
out.clear();
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package timely.grafana.request;
|
||||
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import timely.api.annotation.Http;
|
||||
import timely.api.request.AuthenticatedRequest;
|
||||
import timely.api.request.HttpGetRequest;
|
||||
import timely.api.request.HttpPostRequest;
|
||||
|
||||
@Http(path = "/")
|
||||
public class GrafanaRequest extends AuthenticatedRequest implements HttpGetRequest, HttpPostRequest {
|
||||
|
||||
private FullHttpRequest httpRequest = null;
|
||||
|
||||
@Override
|
||||
public HttpGetRequest parseQueryParameters(QueryStringDecoder decoder) throws Exception {
|
||||
return new GrafanaRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpPostRequest parseBody(String content) throws Exception {
|
||||
return new GrafanaRequest();
|
||||
}
|
||||
|
||||
public void setHttpRequest(FullHttpRequest httpRequest) {
|
||||
this.httpRequest = httpRequest;
|
||||
}
|
||||
|
||||
public FullHttpRequest getHttpRequest() {
|
||||
return httpRequest;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<FindBugsFilter>
|
||||
<Match>
|
||||
<Class name="timely.grafana.auth.netty.http.GrafanaRelayHandler$MyByteArrayOutputStream" />
|
||||
<Method name="getBuf" />
|
||||
<Bug pattern="EI_EXPOSE_REP" />
|
||||
</Match>
|
||||
</FindBugsFilter>
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-app</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
Vendored
+2
-2
@@ -23,8 +23,8 @@
|
||||
{"name": "Project site", "url": "https://github.com/NationalSecurityAgency/timely"},
|
||||
{"name": "License & Terms", "url": "https://raw.githubusercontent.com/NationalSecurityAgency/timely/master/LICENSE"}
|
||||
],
|
||||
"version": "1.2.6",
|
||||
"updated": "2019-10-30"
|
||||
"version": "0.0.6-SNAPSHOT",
|
||||
"updated": "2017-08-11"
|
||||
},
|
||||
|
||||
"includes": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "timely-app",
|
||||
"private": true,
|
||||
"version": "1.2.6",
|
||||
"version": "0.0.2",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
{"name": "Project site", "url": "https://github.com/NationalSecurityAgency/timely"},
|
||||
{"name": "License & Terms", "url": "https://raw.githubusercontent.com/NationalSecurityAgency/timely/master/LICENSE"}
|
||||
],
|
||||
"version": "1.2.6",
|
||||
"updated": "2019-10-30"
|
||||
"version": "0.0.6-SNAPSHOT",
|
||||
"updated": "2017-08-11"
|
||||
},
|
||||
|
||||
"includes": [
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Timely</name>
|
||||
<description>A secure and scalable time series database based on Apache Accumulo</description>
|
||||
@@ -20,7 +20,6 @@
|
||||
<module>grafana</module>
|
||||
<module>analytics</module>
|
||||
<module>balancer</module>
|
||||
<module>grafana-auth</module>
|
||||
</modules>
|
||||
<scm>
|
||||
<connection>scm:git:https://github.com/NationalSecurityAgency/timely.git</connection>
|
||||
@@ -41,50 +40,50 @@
|
||||
<os.detection.classifierWithLikes>fedora</os.detection.classifierWithLikes>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<version.accumulo>1.9.3</version.accumulo>
|
||||
<version.accumulo>1.7.4</version.accumulo>
|
||||
<version.buildnumber-maven>1.4</version.buildnumber-maven>
|
||||
<version.caffeine>2.6.2</version.caffeine>
|
||||
<version.collectd>5.7.1</version.collectd>
|
||||
<version.commons-collections4>4.3</version.commons-collections4>
|
||||
<version.commons-lang3>3.8.1</version.commons-lang3>
|
||||
<version.commons-pool2>2.6.1</version.commons-pool2>
|
||||
<version.curator>4.1.0</version.curator>
|
||||
<version.disruptor>3.4.2</version.disruptor>
|
||||
<version.easymock>4.0.2</version.easymock>
|
||||
<version.caffeine>2.3.3</version.caffeine>
|
||||
<version.collectd>5.5.1</version.collectd>
|
||||
<version.commons-collections4>4.1</version.commons-collections4>
|
||||
<version.commons-configuration>1.10</version.commons-configuration>
|
||||
<version.commons-io>2.6</version.commons-io>
|
||||
<version.commons-lang3>3.5</version.commons-lang3>
|
||||
<version.commons-pool2>2.6.0</version.commons-pool2>
|
||||
<version.curator>2.11.1</version.curator>
|
||||
<version.disruptor>3.3.6</version.disruptor>
|
||||
<version.eclipse-lifecycle>1.0.0</version.eclipse-lifecycle>
|
||||
<version.fast-classpath-scanner>3.1.13</version.fast-classpath-scanner>
|
||||
<version.fast-classpath-scanner>2.0.5</version.fast-classpath-scanner>
|
||||
<version.flink>1.1.4</version.flink>
|
||||
<version.google-flatbuffers>1.10.0</version.google-flatbuffers>
|
||||
<version.guava>27.1-jre</version.guava>
|
||||
<version.hadoop>2.7.7</version.hadoop>
|
||||
<version.httpcomponents>4.5.6</version.httpcomponents>
|
||||
<version.impsort>1.3.0</version.impsort>
|
||||
<version.jackson>2.9.10</version.jackson>
|
||||
<version.jackson.databind>2.9.10</version.jackson.databind>
|
||||
<version.jacoco>0.8.4</version.jacoco>
|
||||
<version.guava>19.0</version.guava>
|
||||
<version.hadoop>2.7.3</version.hadoop>
|
||||
<version.httpcomponents>4.5.2</version.httpcomponents>
|
||||
<version.impsort>1.2.0</version.impsort>
|
||||
<version.jackson>2.9.7</version.jackson>
|
||||
<version.jacoco>0.7.6.201602180812</version.jacoco>
|
||||
<version.javacsv>2.0</version.javacsv>
|
||||
<version.javassist>3.24.1-GA</version.javassist>
|
||||
<version.javassist>3.21.0-GA</version.javassist>
|
||||
<version.jcip-annotations>1.0</version.jcip-annotations>
|
||||
<version.jsoup>1.11.3</version.jsoup>
|
||||
<version.jsoup>1.9.2</version.jsoup>
|
||||
<version.junit>4.12</version.junit>
|
||||
<version.log4j>2.11.2</version.log4j>
|
||||
<version.maven-assembly>3.1.1</version.maven-assembly>
|
||||
<version.maven-build-helper>3.0.0</version.maven-build-helper>
|
||||
<version.maven-compiler>3.8.1</version.maven-compiler>
|
||||
<version.maven-dependency>3.1.1</version.maven-dependency>
|
||||
<version.maven-jar>3.1.2</version.maven-jar>
|
||||
<version.maven-pmd>3.12.0</version.maven-pmd>
|
||||
<version.maven-rpm>2.2.0</version.maven-rpm>
|
||||
<version.maven-shade>3.2.1</version.maven-shade>
|
||||
<version.maven-surefire>3.0.0-M3</version.maven-surefire>
|
||||
<version.netty>4.1.42.Final</version.netty>
|
||||
<version.netty-tcnative>2.0.25.Final</version.netty-tcnative>
|
||||
<version.log4j>2.6.2</version.log4j>
|
||||
<version.maven-assembly>2.6</version.maven-assembly>
|
||||
<version.maven-build-helper>1.12</version.maven-build-helper>
|
||||
<version.maven-compiler>3.3</version.maven-compiler>
|
||||
<version.maven-dependency>2.10</version.maven-dependency>
|
||||
<version.maven-jar>3.0.1</version.maven-jar>
|
||||
<version.maven-pmd>3.6</version.maven-pmd>
|
||||
<version.maven-rpm>2.1.4</version.maven-rpm>
|
||||
<version.maven-shade>2.4.2</version.maven-shade>
|
||||
<version.maven-surefire>2.19.1</version.maven-surefire>
|
||||
<version.netty>4.0.56.Final</version.netty>
|
||||
<version.netty-tcnative>2.0.7.Final</version.netty-tcnative>
|
||||
<version.os-maven>1.5.0.Final</version.os-maven>
|
||||
<version.powermock>1.6.4</version.powermock>
|
||||
<version.slf4j>1.7.26</version.slf4j>
|
||||
<version.spotbugs-maven>3.1.12.1</version.spotbugs-maven>
|
||||
<version.spring-boot>2.1.3.RELEASE</version.spring-boot>
|
||||
<version.tyrus>1.15</version.tyrus>
|
||||
<version.slf4j>1.7.21</version.slf4j>
|
||||
<version.spotbugs-maven>3.1.7</version.spotbugs-maven>
|
||||
<version.spring-boot>1.4.1.RELEASE</version.spring-boot>
|
||||
<version.tyrus>1.13</version.tyrus>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
@@ -101,11 +100,6 @@
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${version.jackson.databind}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-guava</artifactId>
|
||||
<version>${version.jackson}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -141,18 +135,13 @@
|
||||
<dependency>
|
||||
<groupId>io.github.lukehutch</groupId>
|
||||
<artifactId>fast-classpath-scanner</artifactId>
|
||||
<version>${version.fast-classpath-scanner}</version>
|
||||
<version>2.0.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>${version.netty}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.javacsv</groupId>
|
||||
<artifactId>javacsv</artifactId>
|
||||
@@ -162,12 +151,6 @@
|
||||
<groupId>org.apache.accumulo</groupId>
|
||||
<artifactId>accumulo-core</artifactId>
|
||||
<version>${version.accumulo}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.accumulo</groupId>
|
||||
@@ -321,11 +304,6 @@
|
||||
<artifactId>collectd-plugin-parent</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-balancer</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely-client</artifactId>
|
||||
@@ -398,12 +376,6 @@
|
||||
<version>${version.jcip-annotations}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.easymock</groupId>
|
||||
<artifactId>easymock</artifactId>
|
||||
<version>${version.easymock}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-easymock-release-full</artifactId>
|
||||
@@ -419,7 +391,7 @@
|
||||
<plugin>
|
||||
<groupId>net.revelc.code.formatter</groupId>
|
||||
<artifactId>formatter-maven-plugin</artifactId>
|
||||
<version>2.10.0</version>
|
||||
<version>2.8.0</version>
|
||||
<configuration>
|
||||
<compilerCompliance>${maven.compiler.source}</compilerCompliance>
|
||||
<compilerSource>${maven.compiler.source}</compilerSource>
|
||||
@@ -437,7 +409,7 @@
|
||||
<plugin>
|
||||
<groupId>com.github.ekryd.sortpom</groupId>
|
||||
<artifactId>sortpom-maven-plugin</artifactId>
|
||||
<version>2.10.0</version>
|
||||
<version>2.8.0</version>
|
||||
<configuration>
|
||||
<predefinedSortOrder>recommended_2008_06</predefinedSortOrder>
|
||||
<createBackupFile>false</createBackupFile>
|
||||
@@ -469,7 +441,7 @@
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${version.maven-surefire}</version>
|
||||
<configuration>
|
||||
<argLine>${failsafeArgLine} -Djava.library.path=${project.build.directory}/native/META-INF/native/libnetty_tcnative_linux_x86_64.so -Dzookeeper.sasl.client=false</argLine>
|
||||
<argLine>${failsafeArgLine} -Djava.library.path=${project.build.directory}/native/META-INF/native/libnetty-tcnative.so -Dzookeeper.sasl.client=false</argLine>
|
||||
<includes>
|
||||
<include>**/*.java</include>
|
||||
</includes>
|
||||
@@ -512,7 +484,7 @@
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${version.maven-surefire}</version>
|
||||
<configuration>
|
||||
<argLine>${sureFireArgLine} -Djava.library.path=${project.build.directory}/native/META-INF/native/libnetty-tcnative_linux_x86_64.so -Dzookeeper.sasl.client=false</argLine>
|
||||
<argLine>${sureFireArgLine} -Djava.library.path=${project.build.directory}/native/META-INF/native/libnetty-tcnative.so -Dzookeeper.sasl.client=false</argLine>
|
||||
<excludedGroups>timely.test.IntegrationTest</excludedGroups>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
</configuration>
|
||||
@@ -581,7 +553,7 @@
|
||||
<configuration>
|
||||
<rules>
|
||||
<requireMavenVersion>
|
||||
<version>3.5.0</version>
|
||||
<version>3.0.5</version>
|
||||
</requireMavenVersion>
|
||||
<requireJavaVersion>
|
||||
<version>[${maven.compiler.target},)</version>
|
||||
@@ -752,9 +724,6 @@
|
||||
<name>m2e.version</name>
|
||||
</property>
|
||||
</activation>
|
||||
<properties>
|
||||
<maven.compiler.release>8</maven.compiler.release>
|
||||
</properties>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
@@ -815,14 +784,5 @@
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>jdk-release-flag</id>
|
||||
<activation>
|
||||
<jdk>[9,)</jdk>
|
||||
</activation>
|
||||
<properties>
|
||||
<maven.compiler.release>8</maven.compiler.release>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [[ `uname` == "Darwin" ]]; then
|
||||
THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0`
|
||||
else
|
||||
THIS_SCRIPT=`readlink -f $0`
|
||||
fi
|
||||
|
||||
THIS_DIR="${THIS_SCRIPT%/*}"
|
||||
BASE_DIR=${THIS_DIR}/..
|
||||
CONF_DIR="${BASE_DIR}/conf"
|
||||
LIB_DIR="${BASE_DIR}/lib"
|
||||
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*"
|
||||
JVM_ARGS="-Xmx1024m -Xms128m"
|
||||
JVM_ARGS="${JVM_ARGS} -Dlogging.config=${CONF_DIR}/log4j2-error-console.xml"
|
||||
JVM_ARGS="${JVM_ARGS} -Dlog4j.configurationFile=${CONF_DIR}/log4j2-error-console.xml"
|
||||
JVM_ARGS="${JVM_ARGS} -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||
|
||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.store.compaction.util.TabletMetadataConsole --spring.config.name=timely"
|
||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.store.compaction.util.TabletMetadataConsole --spring.config.name=timely
|
||||
@@ -27,14 +27,15 @@ fi
|
||||
mkdir -p ${NATIVE_DIR}
|
||||
|
||||
pushd ${BASE_DIR}/bin
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative-boringssl-static*.jar META-INF/native/libnetty_tcnative_linux_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-all*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative*.jar META-INF/native/libnetty_tcnative.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-transport-native-epoll*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
popd
|
||||
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*:${HADOOP_CONF_DIR}"
|
||||
JVM_ARGS="-Xmx256m -Xms256m -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS} -Dlog4j.configurationFile=${CONF_DIR}/log4j2-spring.xml"
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*"
|
||||
JVM_ARGS="-Xmx256m -Xms256m -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS}"
|
||||
JVM_ARGS="${JVM_ARGS} -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}/libnetty-${TCNATIVE_SUFFIX}"
|
||||
|
||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.Server --spring.config.name=timely"
|
||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.Server --spring.config.name=timely
|
||||
|
||||
@@ -2,12 +2,17 @@
|
||||
|
||||
if [[ `uname` == "Darwin" ]]; then
|
||||
THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0`
|
||||
TCNATIVE_SUFFIX="jnilib"
|
||||
TCNATIVE_SUFFIX="tcnative.jnilib"
|
||||
else
|
||||
THIS_SCRIPT=`readlink -f $0`
|
||||
TCNATIVE_SUFFIX="so"
|
||||
TCNATIVE_SUFFIX="tcnative.so"
|
||||
fi
|
||||
|
||||
# netty tcnative file reference
|
||||
#netty-tcnative-1.1.33.Fork18-linux-x86_64-fedora.jar -> libnetty-tcnative.so
|
||||
#netty-tcnative-1.1.33.Fork18-linux-x86_64.jar -> libnetty-tcnative.so
|
||||
#netty-tcnative-1.1.33.Fork18-osx-x86_64.jar -> libnetty-tcnative.jnilib
|
||||
|
||||
THIS_DIR="${THIS_SCRIPT%/*}"
|
||||
NATIVE_DIR="${THIS_DIR}/META-INF/native"
|
||||
BASE_DIR=${THIS_DIR}/..
|
||||
@@ -27,12 +32,11 @@ fi
|
||||
mkdir -p ${NATIVE_DIR}
|
||||
|
||||
pushd ${BASE_DIR}/bin
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative-boringssl-static*.jar META-INF/native/libnetty_tcnative_linux_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-all*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${TCNATIVE_SUFFIX}
|
||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative*.jar META-INF/native/libnetty-${TCNATIVE_SUFFIX}
|
||||
popd
|
||||
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*:${HADOOP_CONF_DIR}"
|
||||
JVM_ARGS="-Xmx256m -Xms256m -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS} -Dlog4j.configurationFile=${CONF_DIR}/log4j2-spring.xml"
|
||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*"
|
||||
JVM_ARGS="-Xmx256m -Xms256m -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS}"
|
||||
JVM_ARGS="${JVM_ARGS} -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}"
|
||||
# for debugging
|
||||
|
||||
+12
-34
@@ -15,27 +15,15 @@
|
||||
|
||||
<beans:bean id="timelyUserDetailsService" class="timely.auth.UserDetailsService">
|
||||
<beans:property name="users">
|
||||
<util:list>
|
||||
<beans:bean class="timely.auth.TimelyUser">
|
||||
<beans:constructor-arg name="subjectDn">
|
||||
<beans:value>CN=example.com</beans:value>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="auths">
|
||||
<util:list>
|
||||
<beans:value>D</beans:value>
|
||||
<beans:value>E</beans:value>
|
||||
<beans:value>F</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
<beans:constructor-arg name="roles">
|
||||
<util:list>
|
||||
<beans:value>G</beans:value>
|
||||
<beans:value>H</beans:value>
|
||||
<beans:value>I</beans:value>
|
||||
</util:list>
|
||||
</beans:constructor-arg>
|
||||
</beans:bean>
|
||||
</util:list>
|
||||
<util:map key-type="java.lang.String">
|
||||
<beans:entry key="example.com">
|
||||
<util:list>
|
||||
<beans:value>D</beans:value>
|
||||
<beans:value>E</beans:value>
|
||||
<beans:value>F</beans:value>
|
||||
</util:list>
|
||||
</beans:entry>
|
||||
</util:map>
|
||||
</beans:property>
|
||||
</beans:bean>
|
||||
|
||||
@@ -46,12 +34,9 @@
|
||||
<user-service id="usernamePasswordService">
|
||||
<user name="test" password="test1" authorities="A,B,C" />
|
||||
</user-service>
|
||||
|
||||
<beans:bean id="noOpPasswordEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"/>
|
||||
|
||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
|
||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
<beans:property name="userDetailsService" ref="usernamePasswordService"/>
|
||||
<beans:property name="passwordEncoder" ref="noOpPasswordEncoder"/>
|
||||
</beans:bean>
|
||||
|
||||
<authentication-manager alias="authenticationManager">
|
||||
@@ -60,12 +45,5 @@
|
||||
<!-- Basic authorization provider, validates provided username and password -->
|
||||
<authentication-provider ref="UserNamePasswordAuthenticationProvider" />
|
||||
</authentication-manager>
|
||||
|
||||
<util:list id="requiredRoles" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
|
||||
<util:list id="requiredAuths" value-type="java.lang.String">
|
||||
<beans:value></beans:value>
|
||||
</util:list>
|
||||
|
||||
</beans:beans>
|
||||
@@ -18,11 +18,8 @@ timely:
|
||||
max-downsample-memory: 10000000
|
||||
security:
|
||||
session-max-age: 86400
|
||||
cache-expiration-minutes: 60
|
||||
cache-refresh-minutes: 5
|
||||
allow-anonymous-http-access: true
|
||||
allow-anonymous-ws-access: true
|
||||
server-ssl:
|
||||
allow-anonymous-access: true
|
||||
ssl:
|
||||
certificate-file: /timely-server-src/server/pki/timely.csr
|
||||
key-file: /timely-server-src/server/pki/timely-pkcs8.key
|
||||
key-password: password
|
||||
@@ -52,9 +49,9 @@ timely:
|
||||
timeout: 60
|
||||
subscription-lag: 120
|
||||
meta-cache:
|
||||
expiration-minutes: 1440
|
||||
cache-refresh-minutes: 60
|
||||
max-tag-values: 100
|
||||
expiration-minutes: 60
|
||||
initial-capacity: 2000
|
||||
max-capacity: 10000
|
||||
visibility-cache:
|
||||
expiration-minutes: 60
|
||||
initial-capacity: 2000
|
||||
|
||||
@@ -3,8 +3,6 @@ timely:
|
||||
meta-table: timely.meta
|
||||
metric-age-off-days:
|
||||
default: 7
|
||||
cache:
|
||||
enabled: false
|
||||
metrics-report-ignored-tags:
|
||||
accumulo:
|
||||
instance-name: TimelyStandalone
|
||||
@@ -20,11 +18,8 @@ timely:
|
||||
max-downsample-memory: 10000000
|
||||
security:
|
||||
session-max-age: 86400
|
||||
cache-expiration-minutes: 60
|
||||
cache-refresh-minutes: 5
|
||||
allow-anonymous-http-access: true
|
||||
allow-anonymous-ws-access: true
|
||||
server-ssl:
|
||||
allow-anonymous-access: true
|
||||
ssl:
|
||||
certificate-file:
|
||||
key-file:
|
||||
key-password: timely
|
||||
@@ -58,9 +53,9 @@ timely:
|
||||
scanner-read-ahead: 1
|
||||
subscription-batch-size: 5000
|
||||
meta-cache:
|
||||
expiration-minutes: 1440
|
||||
cache-refresh-minutes: 60
|
||||
max-tag-values: 100
|
||||
expiration-minutes: 60
|
||||
initial-capacity: 2000
|
||||
max-capacity: 10000
|
||||
visibility-cache:
|
||||
expiration-minutes: 60
|
||||
initial-capacity: 2000
|
||||
|
||||
+7
-10
@@ -8,7 +8,6 @@ timely:
|
||||
age-off-hours:
|
||||
default: 26
|
||||
metrics-report-ignored-tags:
|
||||
defaultVisibility:
|
||||
accumulo:
|
||||
instance-name: accumulo
|
||||
zookeepers: localhost:2181
|
||||
@@ -23,11 +22,8 @@ timely:
|
||||
max-downsample-memory: 10000000
|
||||
security:
|
||||
session-max-age: 86400
|
||||
cache-expiration-minutes: 60
|
||||
cache-refresh-minutes: 5
|
||||
allow-anonymous-http-access: true
|
||||
allow-anonymous-ws-access: true
|
||||
server-ssl:
|
||||
allow-anonymous-access: true
|
||||
serverSsl:
|
||||
certificate-file:
|
||||
key-file:
|
||||
key-password:
|
||||
@@ -62,9 +58,10 @@ timely:
|
||||
scanner-read-ahead: 1
|
||||
subscription-batch-size: 5000
|
||||
meta-cache:
|
||||
expiration-minutes: 1440
|
||||
cache-refresh-minutes: 60
|
||||
max-tag-values: 100
|
||||
expiration-minutes: 60
|
||||
initial-capacity: 2000
|
||||
max-capacity: 10000
|
||||
visibility-cache:
|
||||
expiration-minutes: 60
|
||||
|
||||
initial-capacity: 2000
|
||||
max-capacity: 10000
|
||||
+39
-18
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>timely</groupId>
|
||||
<artifactId>timely</artifactId>
|
||||
<version>1.2.6</version>
|
||||
<version>1.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>timely-server</artifactId>
|
||||
<dependencies>
|
||||
@@ -20,10 +20,6 @@
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-guava</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jdk8</artifactId>
|
||||
@@ -149,7 +145,9 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<artifactId>netty-tcnative</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
<classifier>${os.detected.classifier}</classifier>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -177,22 +175,11 @@
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.easymock</groupId>
|
||||
<artifactId>easymock</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-easymock-release-full</artifactId>
|
||||
<classifier>full</classifier>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-test-autoconfigure</artifactId>
|
||||
@@ -249,8 +236,9 @@
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||
<artifactId>netty-tcnative</artifactId>
|
||||
<version>${version.netty-tcnative}</version>
|
||||
<classifier>${os.detected.classifier}</classifier>
|
||||
<type>jar</type>
|
||||
<overWrite>false</overWrite>
|
||||
<outputDirectory>${project.build.directory}/native</outputDirectory>
|
||||
@@ -292,4 +280,37 @@
|
||||
</extension>
|
||||
</extensions>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>native-epoll-linux</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>!mac</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<version>${version.netty}</version>
|
||||
<classifier>linux-x86_64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>native-epoll</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>mac</family>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-transport-native-epoll</artifactId>
|
||||
<version>${version.netty}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
Vendored
+1
-1
@@ -33,7 +33,7 @@
|
||||
<directory>${project.basedir}/bin</directory>
|
||||
<outputDirectory>bin</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
<include>*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
|
||||
@@ -24,7 +24,6 @@ import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.WriteBufferWaterMark;
|
||||
import io.netty.channel.epoll.EpollChannelOption;
|
||||
import io.netty.channel.epoll.EpollDatagramChannel;
|
||||
import io.netty.channel.epoll.EpollEventLoopGroup;
|
||||
@@ -45,7 +44,6 @@ import io.netty.handler.codec.http.HttpRequestDecoder;
|
||||
import io.netty.handler.codec.http.HttpResponseEncoder;
|
||||
import io.netty.handler.codec.http.HttpServerCodec;
|
||||
import io.netty.handler.codec.http.cors.CorsConfig;
|
||||
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
|
||||
import io.netty.handler.codec.http.cors.CorsHandler;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import io.netty.handler.logging.LoggingHandler;
|
||||
@@ -60,7 +58,6 @@ import io.netty.handler.stream.ChunkedWriteHandler;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import io.netty.util.NettyRuntime;
|
||||
import io.netty.util.internal.SystemPropertyUtil;
|
||||
import org.apache.accumulo.core.conf.AccumuloConfiguration;
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
@@ -73,7 +70,6 @@ import org.apache.zookeeper.CreateMode;
|
||||
import org.apache.zookeeper.data.Stat;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import timely.api.response.TimelyException;
|
||||
@@ -105,7 +101,7 @@ import timely.netty.udp.UdpDecoder;
|
||||
import timely.netty.udp.UdpPacketToByteBuf;
|
||||
import timely.netty.websocket.WSMetricPutHandler;
|
||||
import timely.netty.websocket.WSVersionRequestHandler;
|
||||
import timely.netty.websocket.WebSocketFullRequestHandler;
|
||||
import timely.netty.websocket.WebSocketHttpCookieHandler;
|
||||
import timely.netty.websocket.WebSocketRequestDecoder;
|
||||
import timely.netty.websocket.subscription.WSAddSubscriptionRequestHandler;
|
||||
import timely.netty.websocket.subscription.WSCloseSubscriptionRequestHandler;
|
||||
@@ -212,13 +208,13 @@ public class Server {
|
||||
payload.setWsPort(config.getWebsocket().getPort());
|
||||
payload.setUdpPort(config.getServer().getUdpPort());
|
||||
|
||||
ServiceInstanceBuilder<ServerDetails> builder = ServiceInstance.builder();
|
||||
ServiceInstanceBuilder builder = ServiceInstance.builder();
|
||||
String serviceName = host + ":" + config.getServer().getTcpPort();
|
||||
ServiceInstance<ServerDetails> serviceInstance = builder.id(serviceName).name("timely-server")
|
||||
ServiceInstance serviceInstance = builder.id(serviceName).name("timely-server")
|
||||
.address(config.getServer().getIp()).port(config.getServer().getTcpPort()).payload(payload).build();
|
||||
|
||||
ServiceDiscovery<ServerDetails> discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class)
|
||||
.client(curatorFramework).basePath(SERVICE_DISCOVERY_PATH).build();
|
||||
ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class).client(curatorFramework)
|
||||
.basePath(SERVICE_DISCOVERY_PATH).build();
|
||||
discovery.start();
|
||||
discovery.registerService(serviceInstance);
|
||||
|
||||
@@ -254,7 +250,7 @@ public class Server {
|
||||
}
|
||||
|
||||
protected static Configuration initializeConfiguration(String[] args) {
|
||||
applicationContext = new SpringApplicationBuilder(SpringBootstrap.class).web(WebApplicationType.NONE).run(args);
|
||||
applicationContext = new SpringApplicationBuilder(SpringBootstrap.class).web(false).run(args);
|
||||
return applicationContext.getBean(Configuration.class);
|
||||
}
|
||||
|
||||
@@ -418,9 +414,7 @@ public class Server {
|
||||
public void run() throws Exception {
|
||||
|
||||
RetryPolicy retryPolicy = new RetryForever(1000);
|
||||
int timeout = Long.valueOf(AccumuloConfiguration.getTimeInMillis(config.getAccumulo().getZookeeperTimeout()))
|
||||
.intValue();
|
||||
curatorFramework = CuratorFrameworkFactory.newClient(config.getAccumulo().getZookeepers(), timeout, 10000,
|
||||
curatorFramework = CuratorFrameworkFactory.newClient(config.getAccumulo().getZookeepers(), 30000, 10000,
|
||||
retryPolicy);
|
||||
curatorFramework.start();
|
||||
ensureZkPaths(curatorFramework, zkPaths);
|
||||
@@ -436,7 +430,7 @@ public class Server {
|
||||
// Initialize the MetaCache
|
||||
MetaCacheFactory.getCache(config);
|
||||
// initialize the auth cache
|
||||
AuthCache.configure(config.getSecurity());
|
||||
AuthCache.setSessionMaxAge(config);
|
||||
// Initialize the VisibilityCache
|
||||
VisibilityCache.init(config);
|
||||
final boolean useEpoll = useEpoll();
|
||||
@@ -513,9 +507,10 @@ public class Server {
|
||||
wsServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||
wsServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||
wsServer.option(ChannelOption.SO_KEEPALIVE, true);
|
||||
/* Not sure if next two lines are necessary */
|
||||
/* Not sure if next three lines are necessary */
|
||||
wsServer.option(ChannelOption.SO_SNDBUF, 1048576);
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(620145, 838860));
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 838860);
|
||||
wsServer.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 620145);
|
||||
wsChannelHandle = wsServer.bind(wsIp, wsPort).sync().channel();
|
||||
final String wsAddress = ((InetSocketAddress) wsChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||
|
||||
@@ -592,14 +587,14 @@ public class Server {
|
||||
ch.pipeline().addLast("decoder", new HttpRequestDecoder());
|
||||
ch.pipeline().addLast("compressor", new HttpContentCompressor());
|
||||
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
||||
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
|
||||
final Cors corsCfg = config.getHttp().getCors();
|
||||
final CorsConfigBuilder ccb;
|
||||
final CorsConfig.Builder ccb;
|
||||
if (corsCfg.isAllowAnyOrigin()) {
|
||||
ccb = CorsConfigBuilder.forAnyOrigin();
|
||||
ccb = new CorsConfig.Builder();
|
||||
} else {
|
||||
ccb = CorsConfigBuilder.forOrigins(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
|
||||
ccb = new CorsConfig.Builder(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
|
||||
}
|
||||
if (corsCfg.isAllowNullOrigin()) {
|
||||
ccb.allowNullOrigin();
|
||||
@@ -640,7 +635,7 @@ public class Server {
|
||||
ch.pipeline().addLast("logger", new LoggingHandler());
|
||||
ch.pipeline().addLast("packetDecoder", new UdpPacketToByteBuf());
|
||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("putDecoder", new UdpDecoder());
|
||||
ch.pipeline().addLast("putHandler", new TcpPutHandler(dataStore));
|
||||
}
|
||||
@@ -653,7 +648,7 @@ public class Server {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
||||
ch.pipeline().addLast("putDecoder", new TcpDecoder());
|
||||
ch.pipeline().addLast("putHandler", new TcpPutHandler(dataStore));
|
||||
ch.pipeline().addLast("versionHandler", new TcpVersionHandler());
|
||||
@@ -668,11 +663,11 @@ public class Server {
|
||||
protected void initChannel(SocketChannel ch) throws Exception {
|
||||
ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
|
||||
ch.pipeline().addLast("httpServer", new HttpServerCodec());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast("sessionExtractor", new WebSocketFullRequestHandler());
|
||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
||||
ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(config.getSecurity()));
|
||||
ch.pipeline().addLast("idle-handler", new IdleStateHandler(conf.getWebsocket().getTimeout(), 0, 0));
|
||||
ch.pipeline().addLast("ws-protocol",
|
||||
new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, false, true));
|
||||
new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, true));
|
||||
ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(config.getSecurity()));
|
||||
ch.pipeline().addLast("aggregators", new WSAggregatorsRequestHandler());
|
||||
ch.pipeline().addLast("metrics", new WSMetricsRequestHandler(config));
|
||||
@@ -681,8 +676,7 @@ public class Server {
|
||||
ch.pipeline().addLast("suggest", new WSSuggestRequestHandler(dataStore));
|
||||
ch.pipeline().addLast("version", new WSVersionRequestHandler());
|
||||
ch.pipeline().addLast("put", new WSMetricPutHandler(dataStore));
|
||||
ch.pipeline().addLast("create",
|
||||
new WSCreateSubscriptionRequestHandler(dataStore, dataStoreCache, config));
|
||||
ch.pipeline().addLast("create", new WSCreateSubscriptionRequestHandler(dataStore, config));
|
||||
ch.pipeline().addLast("add", new WSAddSubscriptionRequestHandler());
|
||||
ch.pipeline().addLast("remove", new WSRemoveSubscriptionRequestHandler());
|
||||
ch.pipeline().addLast("close", new WSCloseSubscriptionRequestHandler());
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package timely.adapter.accumulo;
|
||||
|
||||
import org.apache.accumulo.core.data.Key;
|
||||
import timely.api.model.Meta;
|
||||
import timely.model.Metric;
|
||||
|
||||
/**
|
||||
* Creates Accumulo data structures from {@link Metric}
|
||||
*/
|
||||
public class MetaAdapter {
|
||||
|
||||
public static Key createMetricKey(String metricName, Long timestamp) {
|
||||
return new Key(Meta.METRIC_PREFIX + metricName, "", "", timestamp);
|
||||
}
|
||||
|
||||
public static Key createTagKey(String metricName, String tagName, Long timestamp) {
|
||||
return new Key(Meta.TAG_PREFIX + metricName, tagName, "", timestamp);
|
||||
}
|
||||
|
||||
public static Key createValueKey(String metricName, String tagName, String tagValue, Long timestamp) {
|
||||
return new Key(Meta.VALUE_PREFIX + metricName, tagName, tagValue, timestamp);
|
||||
}
|
||||
|
||||
public static Meta parse(Key key) {
|
||||
String row = key.getRow().toString();
|
||||
if (row.startsWith(Meta.METRIC_PREFIX)) {
|
||||
return Meta.parse(key, null, Meta.METRIC_PREFIX);
|
||||
} else if (row.startsWith(Meta.TAG_PREFIX)) {
|
||||
return Meta.parse(key, null, Meta.TAG_PREFIX);
|
||||
} else if (row.startsWith(Meta.VALUE_PREFIX)) {
|
||||
return Meta.parse(key, null, Meta.VALUE_PREFIX);
|
||||
}
|
||||
throw new IllegalStateException("Invalid key in meta " + key.toString());
|
||||
}
|
||||
|
||||
public static String decodeRowKey(Key key) {
|
||||
return parse(key).getMetric();
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,6 @@ import java.util.List;
|
||||
|
||||
import org.apache.accumulo.core.data.Key;
|
||||
import org.apache.accumulo.core.data.Value;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.builder.CompareToBuilder;
|
||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||
|
||||
public class Meta implements Comparable<Meta> {
|
||||
|
||||
@@ -53,79 +49,60 @@ public class Meta implements Comparable<Meta> {
|
||||
|
||||
public List<Key> toKeys() {
|
||||
List<Key> keys = new ArrayList<>();
|
||||
if (StringUtils.isNotBlank(metric)) {
|
||||
keys.add(new Key(METRIC_PREFIX + metric));
|
||||
}
|
||||
if (StringUtils.isNotBlank(tagKey)) {
|
||||
keys.add(new Key(TAG_PREFIX + metric, tagKey));
|
||||
}
|
||||
if (StringUtils.isNotBlank(tagKey) && StringUtils.isNotBlank(tagValue)) {
|
||||
keys.add(new Key(VALUE_PREFIX + metric, tagKey, tagValue));
|
||||
}
|
||||
keys.add(new Key(METRIC_PREFIX + metric));
|
||||
keys.add(new Key(TAG_PREFIX + metric, tagKey));
|
||||
keys.add(new Key(VALUE_PREFIX + metric, tagKey, tagValue));
|
||||
return keys;
|
||||
}
|
||||
|
||||
public static String prefix(Key key) {
|
||||
String row = key.getRow().toString();
|
||||
if (row.startsWith(Meta.METRIC_PREFIX)) {
|
||||
return Meta.METRIC_PREFIX;
|
||||
} else if (row.startsWith(Meta.TAG_PREFIX)) {
|
||||
return Meta.TAG_PREFIX;
|
||||
} else if (row.startsWith(Meta.VALUE_PREFIX)) {
|
||||
return Meta.VALUE_PREFIX;
|
||||
}
|
||||
throw new IllegalStateException("Invalid key in meta " + key.toString());
|
||||
}
|
||||
|
||||
public static Meta parse(Key key) {
|
||||
return parse(key, null);
|
||||
}
|
||||
|
||||
public static Meta parse(Key key, Value value) {
|
||||
String row = key.getRow().toString();
|
||||
if (row.startsWith(Meta.METRIC_PREFIX)) {
|
||||
return Meta.parse(key, value, Meta.METRIC_PREFIX);
|
||||
} else if (row.startsWith(Meta.TAG_PREFIX)) {
|
||||
return Meta.parse(key, value, Meta.TAG_PREFIX);
|
||||
} else if (row.startsWith(Meta.VALUE_PREFIX)) {
|
||||
return Meta.parse(key, value, Meta.VALUE_PREFIX);
|
||||
}
|
||||
throw new IllegalStateException("Invalid key in meta " + key.toString());
|
||||
}
|
||||
|
||||
public static Meta parse(Key k, Value v, String prefix) {
|
||||
public static Meta parse(Key k, Value v) {
|
||||
if (k.getColumnQualifier().getLength() > 0) {
|
||||
return new Meta(k.getRow().toString().substring(prefix.length()), k.getColumnFamily().toString(),
|
||||
return new Meta(k.getRow().toString().substring(METRIC_PREFIX.length()), k.getColumnFamily().toString(),
|
||||
k.getColumnQualifier().toString());
|
||||
} else if (k.getColumnFamily().getLength() > 0) {
|
||||
return new Meta(k.getRow().toString().substring(prefix.length()), k.getColumnFamily().toString(), null);
|
||||
return new Meta(k.getRow().toString().substring(METRIC_PREFIX.length()), k.getColumnFamily().toString(),
|
||||
null);
|
||||
|
||||
} else {
|
||||
return new Meta(k.getRow().toString().substring(prefix.length()), null, null);
|
||||
return new Meta(k.getRow().toString().substring(METRIC_PREFIX.length()), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
HashCodeBuilder builder = new HashCodeBuilder();
|
||||
builder.append(metric);
|
||||
builder.append(tagKey);
|
||||
builder.append(tagValue);
|
||||
return builder.toHashCode();
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((metric == null) ? 0 : metric.hashCode());
|
||||
result = prime * result + ((tagKey == null) ? 0 : tagKey.hashCode());
|
||||
result = prime * result + ((tagValue == null) ? 0 : tagValue.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof Meta) {
|
||||
Meta obj = (Meta) o;
|
||||
EqualsBuilder builder = new EqualsBuilder();
|
||||
builder.append(this.metric, obj.metric);
|
||||
builder.append(this.tagKey, obj.tagKey);
|
||||
builder.append(this.tagValue, obj.tagValue);
|
||||
return builder.isEquals();
|
||||
} else {
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Meta other = (Meta) obj;
|
||||
if (metric == null) {
|
||||
if (other.metric != null)
|
||||
return false;
|
||||
} else if (!metric.equals(other.metric))
|
||||
return false;
|
||||
if (tagKey == null) {
|
||||
if (other.tagKey != null)
|
||||
return false;
|
||||
} else if (!tagKey.equals(other.tagKey))
|
||||
return false;
|
||||
if (tagValue == null) {
|
||||
if (other.tagValue != null)
|
||||
return false;
|
||||
} else if (!tagValue.equals(other.tagValue))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -135,10 +112,15 @@ public class Meta implements Comparable<Meta> {
|
||||
|
||||
@Override
|
||||
public int compareTo(Meta o) {
|
||||
CompareToBuilder builder = new CompareToBuilder();
|
||||
builder.append(this.metric, o.metric);
|
||||
builder.append(this.tagKey, o.tagKey);
|
||||
builder.append(this.tagValue, o.tagValue);
|
||||
return builder.toComparison();
|
||||
int result = metric.compareTo(o.metric);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = tagKey.compareTo(o.tagKey);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
return tagValue.compareTo(o.tagValue);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +1,18 @@
|
||||
package timely.api.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import timely.auth.TimelyUser;
|
||||
import timely.auth.util.HttpHeaderUtils;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* Base class for requests that require auth
|
||||
* Base class for requests that require authentication
|
||||
*/
|
||||
@JsonIgnoreProperties({ "userName", "requestHeader" })
|
||||
public class AuthenticatedRequest implements Request {
|
||||
|
||||
private String sessionId = null;
|
||||
private TimelyAuthenticationToken token = null;
|
||||
private Multimap<String, String> requestHeaders = HashMultimap.create();
|
||||
private Map<String, String> requestHeaders = new HashMap<>();
|
||||
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
@@ -26,17 +22,12 @@ public class AuthenticatedRequest implements Request {
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
|
||||
public void addHeaders(Multimap<String, String> headers) {
|
||||
requestHeaders.putAll(headers);
|
||||
public void addHeaders(List<Entry<String, String>> headers) {
|
||||
headers.forEach(l -> requestHeaders.put(l.getKey(), l.getValue()));
|
||||
}
|
||||
|
||||
public Multimap<String, String> getRequestHeaders() {
|
||||
return requestHeaders;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getRequestHeader(String name) {
|
||||
return HttpHeaderUtils.getSingleHeader(requestHeaders, name, false);
|
||||
public Map<String, String> getRequestHeaders() {
|
||||
return Collections.unmodifiableMap(requestHeaders);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -44,32 +35,17 @@ public class AuthenticatedRequest implements Request {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("{");
|
||||
buf.append("Session ID: ").append(sessionId);
|
||||
buf.append("Token: ").append(token == null ? null : token.getTimelyPrincipal().getName());
|
||||
buf.append(", Request Headers: ").append(requestHeaders.toString());
|
||||
buf.append("}");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public void setToken(TimelyAuthenticationToken token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public TimelyAuthenticationToken getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getUserName() {
|
||||
String name;
|
||||
try {
|
||||
TimelyUser user = token.getTimelyPrincipal().getPrimaryUser();
|
||||
name = user.getCommonName();
|
||||
if (name == null) {
|
||||
name = user.getName();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
name = "UNKNOWN";
|
||||
@Override
|
||||
public void validate() {
|
||||
Request.super.validate();
|
||||
if (null == sessionId) {
|
||||
throw new IllegalArgumentException("SessionID is null, must log in first");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,6 +4,8 @@ public interface TcpRequest extends Request {
|
||||
|
||||
/**
|
||||
* Parse a line of text received and populate this object
|
||||
*
|
||||
* @param line
|
||||
*/
|
||||
public void parse(String line);
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ public interface UdpRequest {
|
||||
|
||||
/**
|
||||
* Parse a line of text received and populate this object
|
||||
*
|
||||
* @param line
|
||||
*/
|
||||
public void parse(String line);
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
||||
import io.netty.handler.codec.http.FullHttpResponse;
|
||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||
import io.netty.handler.codec.http.HttpHeaders.Names;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.handler.codec.http.HttpVersion;
|
||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
@@ -129,8 +129,8 @@ public class MetricsResponse {
|
||||
}
|
||||
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
|
||||
Unpooled.copiedBuffer(buf));
|
||||
response.headers().set(HttpHeaderNames.CONTENT_TYPE, responseType);
|
||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
|
||||
response.headers().set(Names.CONTENT_TYPE, responseType);
|
||||
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -156,10 +156,8 @@ public class MetricsResponse {
|
||||
b.append(TR_END);
|
||||
String prevMetric = null;
|
||||
StringBuilder tags = new StringBuilder();
|
||||
Map<String, Long> tagMap = new HashMap<>();
|
||||
for (Meta m : tree) {
|
||||
if (prevMetric != null && !m.getMetric().equals(prevMetric)) {
|
||||
tagMap.clear();
|
||||
b.append(TR_START);
|
||||
b.append(TD_START).append(prevMetric).append(TD_END);
|
||||
b.append(TD_START).append(tags.toString()).append(TD_END);
|
||||
@@ -170,12 +168,8 @@ public class MetricsResponse {
|
||||
if (prevMetric == null) {
|
||||
prevMetric = m.getMetric();
|
||||
}
|
||||
long numValues = tagMap.getOrDefault(m.getTagKey(), 0l);
|
||||
if (!(this.ignoredTags.contains(m.getTagKey()))) {
|
||||
if (numValues <= conf.getMetaCache().getMaxTagValues()) {
|
||||
tags.append(m.getTagKey()).append("=").append(m.getTagValue()).append(" ");
|
||||
tagMap.put(m.getTagKey(), ++numValues);
|
||||
}
|
||||
tags.append(m.getTagKey()).append("=").append(m.getTagValue()).append(" ");
|
||||
}
|
||||
}
|
||||
b.append(TR_START);
|
||||
|
||||
@@ -1,150 +1,81 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import timely.api.request.AuthenticatedRequest;
|
||||
import timely.api.request.AuthenticatedWebSocketRequest;
|
||||
import timely.auth.util.AuthorizationsUtil;
|
||||
import timely.api.request.Request;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.configuration.Configuration;
|
||||
import timely.configuration.Security;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class AuthCache {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AuthCache.class);
|
||||
private static Cache<String, TimelyPrincipal> CACHE = null;
|
||||
private static Cache<String, Authentication> CACHE = null;
|
||||
|
||||
private static int cacheExpirationMinutes = -1;
|
||||
private static int cacheRefreshMinutes = -1;
|
||||
private static int sessionMaxAge = -1;
|
||||
|
||||
/**
|
||||
* For tests only
|
||||
*/
|
||||
public static void resetConfiguration() {
|
||||
cacheExpirationMinutes = -1;
|
||||
cacheRefreshMinutes = -1;
|
||||
public static void resetSessionMaxAge() {
|
||||
sessionMaxAge = -1;
|
||||
}
|
||||
|
||||
public static void configure(Security security) {
|
||||
if (-1 != cacheExpirationMinutes || -1 != cacheRefreshMinutes) {
|
||||
throw new IllegalStateException("Cache already configured.");
|
||||
public static void setSessionMaxAge(Configuration config) {
|
||||
if (-1 != sessionMaxAge) {
|
||||
throw new IllegalStateException("Cache session max age already configured.");
|
||||
}
|
||||
cacheExpirationMinutes = security.getCacheExpirationMinutes();
|
||||
cacheRefreshMinutes = security.getCacheRefreshMinutes();
|
||||
sessionMaxAge = config.getSecurity().getSessionMaxAge();
|
||||
}
|
||||
|
||||
private static Cache<String, TimelyPrincipal> getCache() {
|
||||
if (-1 == cacheExpirationMinutes) {
|
||||
public static Cache<String, Authentication> getCache() {
|
||||
if (-1 == sessionMaxAge) {
|
||||
throw new IllegalStateException("Cache session max age not configured.");
|
||||
}
|
||||
if (null == CACHE) {
|
||||
Caffeine<Object, Object> caffeine = Caffeine.newBuilder();
|
||||
caffeine.expireAfterWrite(cacheExpirationMinutes, TimeUnit.MINUTES);
|
||||
if (cacheRefreshMinutes > 0) {
|
||||
caffeine.refreshAfterWrite(cacheRefreshMinutes, TimeUnit.MINUTES);
|
||||
CACHE = caffeine.build(key -> getTimelyPrincipal(key));
|
||||
} else {
|
||||
CACHE = caffeine.build();
|
||||
}
|
||||
CACHE = Caffeine.newBuilder().expireAfterAccess(sessionMaxAge, TimeUnit.SECONDS).build();
|
||||
}
|
||||
return CACHE;
|
||||
}
|
||||
|
||||
private static TimelyPrincipal getTimelyPrincipal(String key) {
|
||||
LOG.debug("Refreshing TimelyPrincipal {}", key);
|
||||
TimelyPrincipal timelyPrincipal = null;
|
||||
String[] dnArray = key.split(" -> ");
|
||||
if (dnArray.length == 1) {
|
||||
SubjectIssuerDNPair pair = SubjectIssuerDNPair.parse(dnArray[0]);
|
||||
TimelyAuthenticationToken token = AuthenticationService.getAuthenticationToken(new Object(),
|
||||
pair.subjectDN(), pair.issuerDN());
|
||||
timelyPrincipal = AuthenticationService.authenticate(token, pair, token.getTimelyPrincipal().getName(),
|
||||
false);
|
||||
} else if (dnArray.length > 1) {
|
||||
Collection<TimelyUser> timelyUsers = new ArrayList<>();
|
||||
for (String s : dnArray) {
|
||||
SubjectIssuerDNPair pair = SubjectIssuerDNPair.parse(s);
|
||||
TimelyAuthenticationToken token = AuthenticationService.getAuthenticationToken(new Object(),
|
||||
pair.subjectDN(), pair.issuerDN());
|
||||
TimelyPrincipal p = AuthenticationService.authenticate(token, pair,
|
||||
token.getTimelyPrincipal().getName(), false);
|
||||
timelyUsers.addAll(p.getProxiedUsers());
|
||||
}
|
||||
timelyPrincipal = new TimelyPrincipal(timelyUsers);
|
||||
}
|
||||
return timelyPrincipal;
|
||||
}
|
||||
|
||||
public static boolean containsKey(String key) {
|
||||
return getCache().getIfPresent(key) != null;
|
||||
}
|
||||
|
||||
public static TimelyPrincipal get(String key) {
|
||||
return getCache().getIfPresent(key);
|
||||
}
|
||||
|
||||
public static void put(String key, TimelyPrincipal principal) {
|
||||
getCache().put(key, principal);
|
||||
}
|
||||
|
||||
public static void remove(String key) {
|
||||
getCache().invalidate(key);
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
if (CACHE != null) {
|
||||
CACHE.invalidateAll();
|
||||
}
|
||||
}
|
||||
|
||||
protected static Collection<Authorizations> getAuthorizations(String entityName) {
|
||||
if (!StringUtils.isEmpty(entityName)) {
|
||||
List<Authorizations> authorizationsList = new ArrayList<>();
|
||||
TimelyPrincipal principal = AuthCache.get(entityName);
|
||||
if (principal != null) {
|
||||
for (Collection<String> authCollection : principal.getAuthorizations()) {
|
||||
authorizationsList.add(AuthorizationsUtil.toAuthorizations(authCollection));
|
||||
}
|
||||
LOG.debug("Authorizations for user {} {}", entityName, principal.getAuthorizationsString());
|
||||
return authorizationsList;
|
||||
public static Authorizations getAuthorizations(String sessionId) {
|
||||
if (!StringUtils.isEmpty(sessionId)) {
|
||||
Authentication auth = CACHE.asMap().get(sessionId);
|
||||
if (null != auth) {
|
||||
Collection<? extends GrantedAuthority> authorities = CACHE.asMap().get(sessionId).getAuthorities();
|
||||
String[] auths = new String[authorities.size()];
|
||||
final AtomicInteger i = new AtomicInteger(0);
|
||||
authorities.forEach(a -> auths[i.getAndIncrement()] = a.getAuthority());
|
||||
return new Authorizations(auths);
|
||||
} else {
|
||||
return Collections.singletonList(Authorizations.EMPTY);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
throw new IllegalArgumentException("entityName can not be null");
|
||||
throw new IllegalArgumentException("session id cannot be null");
|
||||
}
|
||||
}
|
||||
|
||||
public static Collection<Authorizations> getAuthorizations(AuthenticatedRequest request, Security security) {
|
||||
Collection<Authorizations> auths;
|
||||
boolean anonAccessAllowed;
|
||||
if (request instanceof AuthenticatedWebSocketRequest) {
|
||||
anonAccessAllowed = security.isAllowAnonymousWsAccess();
|
||||
} else {
|
||||
anonAccessAllowed = security.isAllowAnonymousHttpAccess();
|
||||
}
|
||||
TimelyAuthenticationToken token = request.getToken();
|
||||
String sessionId = request.getSessionId();
|
||||
if (StringUtils.isBlank(sessionId) && token.getClientCert() == null) {
|
||||
if (anonAccessAllowed) {
|
||||
auths = Collections.singletonList(Authorizations.EMPTY);
|
||||
} else {
|
||||
throw new IllegalArgumentException("User must provide either a sessionId or a client certificate");
|
||||
public static void enforceAccess(Security security, Request r) throws Exception {
|
||||
if (!security.isAllowAnonymousAccess() && (r instanceof AuthenticatedRequest)) {
|
||||
AuthenticatedRequest ar = (AuthenticatedRequest) r;
|
||||
if (StringUtils.isEmpty(ar.getSessionId())) {
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "User must log in",
|
||||
"Anonymous access is disabled, log in first");
|
||||
}
|
||||
if (!AuthCache.getCache().asMap().containsKey(ar.getSessionId())) {
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "User must log in",
|
||||
"Unknown session id was submitted, log in again");
|
||||
}
|
||||
} else if (StringUtils.isNotBlank(sessionId)) {
|
||||
auths = getAuthorizations(sessionId);
|
||||
} else {
|
||||
auths = getAuthorizations(token.getTimelyPrincipal().getName());
|
||||
}
|
||||
return auths;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,275 +1,37 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.ServiceConfigurationError;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||
import io.netty.handler.ssl.SslHandler;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import timely.api.request.AuthenticatedRequest;
|
||||
import timely.api.response.TimelyException;
|
||||
import timely.auth.util.DnUtils;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
import timely.netty.http.auth.TimelyUserDetails;
|
||||
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
|
||||
|
||||
public class AuthenticationService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AuthenticationService.class);
|
||||
private static ApplicationContext springContext = null;
|
||||
private static AuthenticationManager authManager = null;
|
||||
private static ConcurrentHashMap<String, Object> fetchingEntity = new ConcurrentHashMap<>();
|
||||
private static ConcurrentHashMap<String, Object> fetchingPrincipal = new ConcurrentHashMap<>();
|
||||
private static Collection<String> requiredRoles;
|
||||
private static Collection<String> requiredAuths;
|
||||
private static SubjectDnX509PrincipalExtractor x509 = null;
|
||||
|
||||
static {
|
||||
try {
|
||||
springContext = new ClassPathXmlApplicationContext("security.xml");
|
||||
authManager = springContext.getBean("authenticationManager", AuthenticationManager.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> uncheckedRoles = springContext.getBean("requiredRoles", List.class);
|
||||
requiredRoles = uncheckedRoles;
|
||||
requiredRoles.removeIf(String::isEmpty);
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> uncheckedAuths = springContext.getBean("requiredAuths", List.class);
|
||||
requiredAuths = uncheckedAuths;
|
||||
requiredAuths.removeIf(String::isEmpty);
|
||||
authManager = (AuthenticationManager) springContext.getBean("authenticationManager");
|
||||
x509 = (SubjectDnX509PrincipalExtractor) springContext.getBean("x509PrincipalExtractor");
|
||||
} catch (BeansException e) {
|
||||
throw new ServiceConfigurationError("Error setting up Authentication objects: " + e.getMessage(),
|
||||
e.getRootCause());
|
||||
}
|
||||
}
|
||||
|
||||
private static AuthenticationManager getAuthenticationManager() {
|
||||
public static AuthenticationManager getAuthenticationManager() {
|
||||
return authManager;
|
||||
}
|
||||
|
||||
public static TimelyPrincipal authenticate(Authentication authentication, String cacheName) {
|
||||
return authenticate(authentication, SubjectIssuerDNPair.of(cacheName), cacheName);
|
||||
public static String extractDN(X509Certificate clientCert) throws Exception {
|
||||
return (String) x509.extractPrincipal(clientCert);
|
||||
}
|
||||
|
||||
public static TimelyPrincipal authenticate(Authentication authentication, SubjectIssuerDNPair pair, String entity) {
|
||||
return authenticate(authentication, pair, entity, true);
|
||||
}
|
||||
|
||||
public static TimelyPrincipal authenticate(Authentication authentication, SubjectIssuerDNPair pair, String entity,
|
||||
boolean useCache) {
|
||||
|
||||
// only one thread should call the authenticationManager for a given entity
|
||||
TimelyPrincipal principal = null;
|
||||
if (useCache) {
|
||||
principal = AuthCache.get(entity);
|
||||
}
|
||||
// once an entity is in the AuthCache, we can bypass all of this
|
||||
if (principal == null) {
|
||||
Object newObj = new Object();
|
||||
Object o = fetchingEntity.getOrDefault(entity, newObj);
|
||||
if (o == null) {
|
||||
o = newObj;
|
||||
}
|
||||
try {
|
||||
synchronized (o) {
|
||||
// if multiple threads are waiting on this synchronized, then the 2nd and all
|
||||
// others will get the principal here
|
||||
if (useCache) {
|
||||
principal = AuthCache.get(entity);
|
||||
}
|
||||
if (principal == null) {
|
||||
Authentication token = getAuthenticationManager().authenticate(authentication);
|
||||
principal = getTimelyPrincipal(token, pair);
|
||||
LOG.trace("Got entity principal for {} from AuthenticationManager", entity);
|
||||
if (useCache) {
|
||||
AuthCache.put(entity, principal);
|
||||
}
|
||||
} else {
|
||||
LOG.trace("Got entity principal for {} from AuthCache on 2nd attempt", entity);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fetchingEntity.remove(entity);
|
||||
}
|
||||
} else {
|
||||
LOG.trace("Got entity principal for {} from AuthCache on 1st attempt", entity);
|
||||
}
|
||||
return principal;
|
||||
}
|
||||
|
||||
public static void enforceAccess(AuthenticatedRequest request) throws Exception {
|
||||
String sessionId = request.getSessionId();
|
||||
X509Certificate clientCert = request.getToken().getClientCert();
|
||||
TimelyPrincipal verifiedPrincipal = null;
|
||||
if (StringUtils.isBlank(sessionId) && clientCert == null) {
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "User must log in",
|
||||
"Anonymous access is disabled. User must either send a client certificate or log in");
|
||||
} else if (StringUtils.isNotBlank(sessionId)) {
|
||||
verifiedPrincipal = AuthCache.get(sessionId);
|
||||
if (verifiedPrincipal == null) {
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "User must log in",
|
||||
"Unknown session id was submitted, log in again");
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
TimelyAuthenticationToken token = request.getToken();
|
||||
TimelyPrincipal requestPrincipal = token.getTimelyPrincipal();
|
||||
String entity = requestPrincipal.getName();
|
||||
verifiedPrincipal = AuthCache.get(entity);
|
||||
if (verifiedPrincipal == null) {
|
||||
Object newObj = new Object();
|
||||
Object o = fetchingPrincipal.getOrDefault(entity, newObj);
|
||||
if (o == null) {
|
||||
o = newObj;
|
||||
}
|
||||
try {
|
||||
synchronized (o) {
|
||||
// check again if in the AuthCache
|
||||
verifiedPrincipal = AuthCache.get(entity);
|
||||
if (verifiedPrincipal == null) {
|
||||
// first thread here, so authenticate all entities in requestPrincipal
|
||||
List<TimelyUser> authenticatedTimelyUsers = new ArrayList<>();
|
||||
for (TimelyUser user : requestPrincipal.getProxiedUsers()) {
|
||||
SubjectIssuerDNPair p = user.getDn();
|
||||
TimelyAuthenticationToken entityToken = getAuthenticationToken(clientCert,
|
||||
p.subjectDN(), p.issuerDN());
|
||||
TimelyPrincipal entityPrincipal = authenticate(entityToken, p,
|
||||
entityToken.getTimelyPrincipal().getName());
|
||||
authenticatedTimelyUsers.addAll(entityPrincipal.getProxiedUsers());
|
||||
}
|
||||
verifiedPrincipal = new TimelyPrincipal(authenticatedTimelyUsers);
|
||||
AuthCache.put(verifiedPrincipal.getName(), verifiedPrincipal);
|
||||
LOG.debug("Authenticated user {} for request {} with authorizations {}",
|
||||
verifiedPrincipal.getName(), request.toString(),
|
||||
verifiedPrincipal.getAuthorizationsString());
|
||||
} else {
|
||||
LOG.trace("Verified principal {} in AuthCache on 2nd attempt", entity);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fetchingPrincipal.remove(entity);
|
||||
}
|
||||
} else {
|
||||
LOG.trace("Verified principal {} in AuthCache on 1st attempt", entity);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "Access denied", e.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
checkAllowedAccess(verifiedPrincipal.getPrimaryUser());
|
||||
} catch (TimelyException e) {
|
||||
// validation based on roles and/or auths failed
|
||||
// remove combined principal and primary user from cache
|
||||
// i.e. don't cache a failure
|
||||
AuthCache.remove(verifiedPrincipal.getName());
|
||||
AuthCache.remove(verifiedPrincipal.getPrimaryUser().getName());
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void checkAllowedAccess(TimelyUser primaryUser) throws TimelyException {
|
||||
Set<String> missingRoles = new TreeSet<>();
|
||||
Set<String> missingAuths = new TreeSet<>();
|
||||
if (requiredRoles != null) {
|
||||
if (!primaryUser.getRoles().containsAll(requiredRoles)) {
|
||||
missingRoles.addAll(requiredRoles);
|
||||
missingRoles.removeAll(primaryUser.getRoles());
|
||||
}
|
||||
}
|
||||
if (requiredAuths != null) {
|
||||
if (!primaryUser.getAuths().containsAll(requiredAuths)) {
|
||||
missingAuths.addAll(requiredRoles);
|
||||
missingAuths.removeAll(primaryUser.getAuths());
|
||||
}
|
||||
}
|
||||
|
||||
if (!missingRoles.isEmpty() || !missingAuths.isEmpty()) {
|
||||
String message = "";
|
||||
if (!missingRoles.isEmpty() && !missingAuths.isEmpty()) {
|
||||
message = "User:" + primaryUser.getName() + " is missing role(s):" + missingRoles + " and auth(s):"
|
||||
+ missingAuths;
|
||||
|
||||
} else if (!missingRoles.isEmpty()) {
|
||||
message = "User:" + primaryUser.getName() + " is missing role(s):" + missingRoles;
|
||||
} else if (missingAuths.isEmpty()) {
|
||||
message = "User:" + primaryUser.getName() + " is missing auths(s):" + missingAuths;
|
||||
}
|
||||
LOG.debug(message);
|
||||
throw new TimelyException(HttpResponseStatus.UNAUTHORIZED.code(), "Access denied", message);
|
||||
}
|
||||
}
|
||||
|
||||
public static X509Certificate getClientCertificate(ChannelHandlerContext ctx) {
|
||||
X509Certificate clientCert = null;
|
||||
if (ctx != null) {
|
||||
SslHandler sslHandler = (SslHandler) ctx.channel().pipeline().get("ssl");
|
||||
if (null != sslHandler) {
|
||||
try {
|
||||
clientCert = (X509Certificate) sslHandler.engine().getSession().getPeerCertificates()[0];
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
} else {
|
||||
throw new IllegalStateException("The expected SSL handler is not in the pipeline.");
|
||||
}
|
||||
}
|
||||
return clientCert;
|
||||
}
|
||||
|
||||
public static TimelyAuthenticationToken getAuthenticationToken(X509Certificate clientCert,
|
||||
Multimap<String, String> headers) {
|
||||
TimelyAuthenticationToken authenticationToken = null;
|
||||
try {
|
||||
authenticationToken = new TimelyAuthenticationToken(clientCert.getSubjectDN().getName(), clientCert,
|
||||
headers);
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
}
|
||||
return authenticationToken;
|
||||
}
|
||||
|
||||
public static TimelyAuthenticationToken getAuthenticationToken(Object clientCert, String subjectDn,
|
||||
String issuerDn) {
|
||||
TimelyAuthenticationToken authenticationToken = null;
|
||||
try {
|
||||
authenticationToken = new TimelyAuthenticationToken(subjectDn, issuerDn, clientCert);
|
||||
} catch (Exception e) {
|
||||
LOG.error(e.getMessage(), e);
|
||||
}
|
||||
return authenticationToken;
|
||||
}
|
||||
|
||||
private static TimelyPrincipal getTimelyPrincipal(Authentication authentication,
|
||||
SubjectIssuerDNPair subjectIssuerDNPair) {
|
||||
String subjectDn = subjectIssuerDNPair.subjectDN();
|
||||
TimelyUser.UserType userType = DnUtils.isServerDN(subjectDn) ? TimelyUser.UserType.SERVER
|
||||
: TimelyUser.UserType.USER;
|
||||
Collection<String> auths = authentication.getAuthorities().stream().map(a -> a.getAuthority())
|
||||
.collect(Collectors.toList());
|
||||
Object o = authentication.getPrincipal();
|
||||
Collection<String> roles = null;
|
||||
if (o instanceof TimelyUserDetails) {
|
||||
roles = ((TimelyUserDetails) o).getRoles();
|
||||
}
|
||||
TimelyUser timelyUser = new TimelyUser(subjectIssuerDNPair, userType, auths, roles, null,
|
||||
System.currentTimeMillis());
|
||||
return new TimelyPrincipal(Arrays.asList(timelyUser));
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
|
||||
/**
|
||||
* @see AuthorizationsMinimizer#minimize(Collection)
|
||||
*/
|
||||
public class AuthorizationsMinimizer {
|
||||
|
||||
/**
|
||||
* Given a collection of Accumulo {@link Authorizations} objects, this method
|
||||
* attempts to compute a "minimum" set that can be used for a multi-entity scan
|
||||
* of data from Accumulo. The idea is that there is a call chain with multiple
|
||||
* entities (e.g., a middleware broker acting on behalf of a GUI that is in turn
|
||||
* acting on behalf of a user). In order to ensure that only data visible to all
|
||||
* of the entities is returned, we must add a visibility filter for each entity
|
||||
* in the chain to ensure that each key/value pair returned by Accumulo can be
|
||||
* seen by all of the entities in the chain. Since we may be scanning a very
|
||||
* large number of keys, it would be ideal if we could reduce the number of
|
||||
* visibility filters to a small set if that can be done safely.
|
||||
* <p>
|
||||
* The crux of the problem, and the reason we need multiple filters in the first
|
||||
* place (as opposed to just intersecting the authorizations for all all
|
||||
* entities and using that set), is the fact that Accumulo visibility
|
||||
* expressions may include disjunctions. Consider the following visibility
|
||||
* expression.
|
||||
* <p>
|
||||
* {@code (A & B & ORG1) | (A & C & ORG2)}
|
||||
* <p>
|
||||
* If the incoming user has the Accumulo authorizations A, B, and ORG1 and the
|
||||
* user is coming through a server with the Accumulo authorizations A, C, and
|
||||
* ORG2, then the server is allowed to see data protected with this expression
|
||||
* and the user is also allowed, so the data should be returned with those two
|
||||
* calling entities. If we simply computed an intersection of the authorizations
|
||||
* that set would be A. That set of authorizations does not match the visibility
|
||||
* expression and data that should be returned would not be.
|
||||
* <p>
|
||||
* Given that we must apply multiple visibility filters in order to properly
|
||||
* return data for a calling entity chain, it is desirable to minimize the
|
||||
* number of visibility filters used, if possible. If a set of authorizations is
|
||||
* a superset of any other set of authorizations, then it does not need to be
|
||||
* tested. As long as we are not changing any of the authorizations sets, we
|
||||
* know we will never allow any data to be returned that would otherwise not be.
|
||||
* By removing authorizations sets, we might only prevent the return of data
|
||||
* that should otherwise be returned. Consider a given set of authorizations
|
||||
* that is a subset of another. If the subset passes a visibility expression,
|
||||
* then the superset will too since it contains at least the same
|
||||
* authorizations, so there is no need to test against it. If the subset does
|
||||
* not pass, then the data is not visible to the chain anyway, so there is no
|
||||
* point in testing the superset.
|
||||
*
|
||||
* @param authorizations
|
||||
* the list of Authorizations for each entity in the call chain
|
||||
* @return a minimized set of Authorizations that allows visibility of exactly
|
||||
* the same data as {@code authorizations}
|
||||
*/
|
||||
public static Collection<Authorizations> minimize(Collection<Authorizations> authorizations) {
|
||||
if (authorizations.size() > 1) {
|
||||
// Convert collection of Authorizations into a collection of String sets (the
|
||||
// individual authorizations).
|
||||
// Since we are adding to a LinkedHashSet, this will de-dupe any duplicate
|
||||
// authorization sets.
|
||||
final LinkedHashSet<Set<String>> allAuths = authorizations.stream().map(
|
||||
a -> a.getAuthorizations().stream().map(String::new).collect(Collectors.toCollection(HashSet::new)))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
|
||||
// Go through the authorizations sets and remove any that are supersets of any
|
||||
// other.
|
||||
for (Iterator<Set<String>> it = allAuths.iterator(); it.hasNext(); /* empty */) {
|
||||
Set<String> currentSet = it.next();
|
||||
if (allAuths.stream().filter(a -> a != currentSet && a.size() <= currentSet.size())
|
||||
.anyMatch(currentSet::containsAll))
|
||||
it.remove();
|
||||
}
|
||||
|
||||
// If we removed any sets of authorizations, then we need to convert the reduced
|
||||
// set from
|
||||
// TreeSet<String> objects back into Authorizations objects.
|
||||
if (allAuths.size() < authorizations.size()) {
|
||||
authorizations = allAuths.stream().map(a -> new Authorizations(a.toArray(new String[0])))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
}
|
||||
}
|
||||
return authorizations;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.accumulo.core.data.Key;
|
||||
import org.apache.accumulo.core.data.Value;
|
||||
import org.apache.accumulo.core.iterators.IteratorEnvironment;
|
||||
import org.apache.accumulo.core.iterators.OptionDescriber;
|
||||
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
|
||||
import org.apache.accumulo.core.iterators.WrappingIterator;
|
||||
import org.apache.accumulo.core.iterators.system.VisibilityFilter;
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class ConfigurableVisibilityFilter extends WrappingIterator implements OptionDescriber {
|
||||
|
||||
public static final String AUTHORIZATIONS_OPT = "authorizations";
|
||||
private SortedKeyValueIterator<Key, Value> delegate;
|
||||
|
||||
private static final Logger log = Logger.getLogger(ConfigurableVisibilityFilter.class);
|
||||
|
||||
public ConfigurableVisibilityFilter() {
|
||||
}
|
||||
|
||||
public ConfigurableVisibilityFilter(SortedKeyValueIterator<Key, Value> iterator, Authorizations authorizations,
|
||||
byte[] defaultVisibility) {
|
||||
setSource(iterator);
|
||||
}
|
||||
|
||||
public ConfigurableVisibilityFilter(ConfigurableVisibilityFilter other, IteratorEnvironment env) {
|
||||
this.delegate = other.delegate.deepCopy(env);
|
||||
this.setSource(delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(SortedKeyValueIterator<Key, Value> source, Map<String, String> options, IteratorEnvironment env)
|
||||
throws IOException {
|
||||
Authorizations auths = Authorizations.EMPTY;
|
||||
if (options.containsKey(AUTHORIZATIONS_OPT))
|
||||
auths = new Authorizations(options.get(AUTHORIZATIONS_OPT).split(","));
|
||||
log.debug("Using authorizations: " + auths);
|
||||
|
||||
delegate = VisibilityFilter.wrap(source, auths, new byte[0]);
|
||||
super.init(delegate, options, env);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedKeyValueIterator<Key, Value> deepCopy(IteratorEnvironment env) {
|
||||
return new ConfigurableVisibilityFilter(this, env);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IteratorOptions describeOptions() {
|
||||
IteratorOptions opts = new IteratorOptions(getClass().getSimpleName(),
|
||||
"Filters keys based to return only those whose visibility tests positive against the supplied authorizations",
|
||||
null, null);
|
||||
opts.addNamedOption(AUTHORIZATIONS_OPT, "Comma delimited list of scan authorizations");
|
||||
return opts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateOptions(Map<String, String> options) {
|
||||
boolean valid = false;
|
||||
String auths = options.get(AUTHORIZATIONS_OPT);
|
||||
if (auths != null) {
|
||||
try {
|
||||
new Authorizations(auths.split(","));
|
||||
valid = true;
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.apache.accumulo.core.client.IteratorSetting;
|
||||
import org.apache.accumulo.core.client.IteratorSetting.Column;
|
||||
import org.apache.accumulo.core.client.ScannerBase;
|
||||
import org.apache.accumulo.core.client.impl.ScannerOptions;
|
||||
import org.apache.accumulo.core.client.sample.SamplerConfiguration;
|
||||
import org.apache.accumulo.core.data.Key;
|
||||
import org.apache.accumulo.core.data.Value;
|
||||
import org.apache.accumulo.core.data.thrift.IterInfo;
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
import org.apache.hadoop.io.Text;
|
||||
|
||||
/**
|
||||
* A simple wrapper around a {@link ScannerBase} that overrides the methods that
|
||||
* configure iterators.
|
||||
*
|
||||
* @see ScannerOptionsHelper
|
||||
*/
|
||||
public class ScannerBaseDelegate implements ScannerBase {
|
||||
|
||||
private static final String SYSTEM_ITERATOR_NAME_PREFIX = "sys_";
|
||||
|
||||
protected final ScannerBase delegate;
|
||||
|
||||
public ScannerBaseDelegate(ScannerBase delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addScanIterator(IteratorSetting cfg) {
|
||||
if (cfg.getName().startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Non-system iterators' names cannot start with " + SYSTEM_ITERATOR_NAME_PREFIX);
|
||||
} else {
|
||||
delegate.addScanIterator(cfg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a "system" scan iterator. The iterator name is automatically prefixed
|
||||
* with {@link #SYSTEM_ITERATOR_NAME_PREFIX}. A "system" scan iterator can only
|
||||
* be modified or removed by calling
|
||||
* {@link #updateSystemScanIteratorOption(String, String, String)},
|
||||
* {@link #removeSystemScanIterator(String)}, or
|
||||
* {@link #clearSystemScanIterators()}. Updates the iterator configuration for
|
||||
* {@code iteratorName}. The iterator name is automatically prefixed with
|
||||
* {@link #SYSTEM_ITERATOR_NAME_PREFIX}.
|
||||
*
|
||||
* @param cfg
|
||||
* the configuration of the iterator to add
|
||||
*/
|
||||
public void addSystemScanIterator(IteratorSetting cfg) {
|
||||
if (!cfg.getName().startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
cfg.setName(SYSTEM_ITERATOR_NAME_PREFIX + cfg.getName());
|
||||
}
|
||||
delegate.addScanIterator(cfg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeScanIterator(String iteratorName) {
|
||||
if (iteratorName.startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
throw new IllegalArgumentException("DATAWAVE system iterator " + iteratorName + " cannot be removed");
|
||||
} else {
|
||||
delegate.removeScanIterator(iteratorName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a "system" scan iterator. The iterator name is automatically prefixed
|
||||
* with {@link #SYSTEM_ITERATOR_NAME_PREFIX}.
|
||||
*
|
||||
* @param iteratorName
|
||||
* the name of the system iterator to remove
|
||||
*/
|
||||
public void removeSystemScanIterator(String iteratorName) {
|
||||
if (!iteratorName.startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
iteratorName = SYSTEM_ITERATOR_NAME_PREFIX + iteratorName;
|
||||
}
|
||||
delegate.removeScanIterator(iteratorName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateScanIteratorOption(String iteratorName, String key, String value) {
|
||||
if (iteratorName.startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
throw new IllegalArgumentException("DATAWAVE system iterator " + iteratorName + " cannot be updated");
|
||||
} else {
|
||||
delegate.updateScanIteratorOption(iteratorName, key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the iterator configuration for {@code iteratorName}. The iterator
|
||||
* name is automatically prefixed with {@link #SYSTEM_ITERATOR_NAME_PREFIX}.
|
||||
*
|
||||
* @param iteratorName
|
||||
* the name of the system iterator to modify
|
||||
* @param key
|
||||
* the name of the iterator option to modify
|
||||
* @param value
|
||||
* the new value for the iterator option named in {@code key}
|
||||
*/
|
||||
public void updateSystemScanIteratorOption(String iteratorName, String key, String value) {
|
||||
if (!iteratorName.startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
iteratorName = SYSTEM_ITERATOR_NAME_PREFIX + iteratorName;
|
||||
}
|
||||
delegate.updateScanIteratorOption(iteratorName, key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fetchColumnFamily(Text col) {
|
||||
delegate.fetchColumnFamily(col);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fetchColumn(Text colFam, Text colQual) {
|
||||
delegate.fetchColumn(colFam, colQual);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fetchColumn(Column column) {
|
||||
delegate.fetchColumn(column);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearColumns() {
|
||||
delegate.clearColumns();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearScanIterators() {
|
||||
if (delegate instanceof ScannerOptions) {
|
||||
try (ScannerOptionsHelper opts = new ScannerOptionsHelper((ScannerOptions) delegate)) {
|
||||
for (IteratorSetting iteratorSetting : opts.getIterators()) {
|
||||
if (!iteratorSetting.getName().startsWith(SYSTEM_ITERATOR_NAME_PREFIX)) {
|
||||
delegate.removeScanIterator(iteratorSetting.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new UnsupportedOperationException(
|
||||
"Cannot clear scan iterators on a non-ScannerOptions class! (" + delegate.getClass() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all iterators (including system iterators).
|
||||
*/
|
||||
public void clearSystemScanIterators() {
|
||||
delegate.clearScanIterators();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Map.Entry<Key, Value>> iterator() {
|
||||
return delegate.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTimeout(long timeOut, TimeUnit timeUnit) {
|
||||
delegate.setTimeout(timeOut, timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTimeout(TimeUnit timeUnit) {
|
||||
return delegate.getTimeout(timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authorizations getAuthorizations() {
|
||||
return delegate.getAuthorizations();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSamplerConfiguration(SamplerConfiguration samplerConfiguration) {
|
||||
delegate.setSamplerConfiguration(samplerConfiguration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SamplerConfiguration getSamplerConfiguration() {
|
||||
return delegate.getSamplerConfiguration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearSamplerConfiguration() {
|
||||
delegate.clearSamplerConfiguration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBatchTimeout(long l, TimeUnit timeUnit) {
|
||||
delegate.setBatchTimeout(l, timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getBatchTimeout(TimeUnit timeUnit) {
|
||||
return delegate.getBatchTimeout(timeUnit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setClassLoaderContext(String s) {
|
||||
delegate.setClassLoaderContext(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearClassLoaderContext() {
|
||||
delegate.clearClassLoaderContext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClassLoaderContext() {
|
||||
return delegate.getClassLoaderContext();
|
||||
}
|
||||
|
||||
public void setContext(String context) {
|
||||
delegate.setClassLoaderContext(context);
|
||||
}
|
||||
|
||||
public void clearContext() {
|
||||
delegate.clearClassLoaderContext();
|
||||
}
|
||||
|
||||
public String getContext() {
|
||||
return delegate.getClassLoaderContext();
|
||||
}
|
||||
|
||||
private static class ScannerOptionsHelper extends ScannerOptions {
|
||||
|
||||
public ScannerOptionsHelper(ScannerOptions other) {
|
||||
super(other);
|
||||
}
|
||||
|
||||
public Collection<IteratorSetting> getIterators() {
|
||||
Collection<IteratorSetting> settings = Lists.newArrayList();
|
||||
for (IterInfo iter : serverSideIteratorList) {
|
||||
IteratorSetting setting = new IteratorSetting(iter.getPriority(), iter.getIterName(),
|
||||
iter.getClassName());
|
||||
setting.addOptions(serverSideIteratorOptions.get(iter.getIterName()));
|
||||
settings.add(setting);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonGetter;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import timely.auth.util.ProxiedEntityUtils;
|
||||
|
||||
/**
|
||||
* A simple pair containing a subject and (optional) issuer DN. The supplied DN
|
||||
* values are normalized into a lower-case form with the CN portion first.
|
||||
*/
|
||||
public class SubjectIssuerDNPair implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String subjectDN;
|
||||
private final String issuerDN;
|
||||
|
||||
public static SubjectIssuerDNPair of(String subjectDN) {
|
||||
return new SubjectIssuerDNPair(subjectDN, null);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static SubjectIssuerDNPair of(@JsonProperty("subjectDN") String subjectDN,
|
||||
@JsonProperty("issuerDN") String issuerDN) {
|
||||
return new SubjectIssuerDNPair(subjectDN, issuerDN);
|
||||
}
|
||||
|
||||
public static SubjectIssuerDNPair parse(String dn) {
|
||||
String[] dns = ProxiedEntityUtils.splitProxiedSubjectIssuerDNs(dn);
|
||||
if (dns.length != 2)
|
||||
throw new IllegalArgumentException(dn + " must contain a single subject and issuer DN");
|
||||
return new SubjectIssuerDNPair(dns[0], dns[1]);
|
||||
}
|
||||
|
||||
protected SubjectIssuerDNPair(String subjectDN, String issuerDN) {
|
||||
this.subjectDN = ProxiedEntityUtils.normalizeDN(subjectDN);
|
||||
if (issuerDN != null) {
|
||||
this.issuerDN = ProxiedEntityUtils.normalizeDN(issuerDN);
|
||||
} else {
|
||||
this.issuerDN = null;
|
||||
}
|
||||
}
|
||||
|
||||
@JsonGetter
|
||||
public String subjectDN() {
|
||||
return subjectDN;
|
||||
}
|
||||
|
||||
@JsonGetter
|
||||
public String issuerDN() {
|
||||
return issuerDN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return issuerDN == null ? subjectDN + "<>" : ProxiedEntityUtils.buildProxiedDN(subjectDN, issuerDN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
SubjectIssuerDNPair that = (SubjectIssuerDNPair) o;
|
||||
|
||||
if (!subjectDN.equals(that.subjectDN))
|
||||
return false;
|
||||
return issuerDN != null ? issuerDN.equals(that.issuerDN) : that.issuerDN == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = subjectDN.hashCode();
|
||||
result = 31 * result + (issuerDN != null ? issuerDN.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import static timely.auth.TimelyUser.ANONYMOUS_USER;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.security.Principal;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
import timely.auth.util.DnUtils;
|
||||
|
||||
/**
|
||||
* A {@link Principal} that represents a set of proxied {@link TimelyUser}s. For
|
||||
* example, this proxied user could represent a GUI server acting on behalf of a
|
||||
* user. The GUI server user represents the entity that made the call to us and
|
||||
* the other proxied user would be the actual end user.
|
||||
*/
|
||||
@XmlRootElement
|
||||
@XmlType(factoryMethod = "anonymousPrincipal", propOrder = { "name", "proxiedUsers", "creationTime" })
|
||||
@XmlAccessorType(XmlAccessType.NONE)
|
||||
public class TimelyPrincipal implements Principal, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final String username;
|
||||
private final TimelyUser primaryUser;
|
||||
@XmlElement
|
||||
private final Set<TimelyUser> proxiedUsers = new LinkedHashSet<>();
|
||||
@XmlElement
|
||||
private final long creationTime;
|
||||
|
||||
/**
|
||||
* This constructor should not be used. It is here to allow JAX-B mapping and
|
||||
* CDI proxying of this class.
|
||||
*/
|
||||
public TimelyPrincipal() {
|
||||
this(ANONYMOUS_USER);
|
||||
}
|
||||
|
||||
public TimelyPrincipal(TimelyUser timelyUser) {
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
this.primaryUser = timelyUser;
|
||||
this.proxiedUsers.add(timelyUser);
|
||||
this.username = timelyUser.getName();
|
||||
}
|
||||
|
||||
public TimelyPrincipal(Collection<TimelyUser> proxiedUsers) {
|
||||
this(proxiedUsers, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public TimelyPrincipal(Collection<TimelyUser> proxiedUsers, long creationTime) {
|
||||
this.creationTime = creationTime;
|
||||
TimelyUser first = proxiedUsers.stream().findFirst().orElse(null);
|
||||
this.primaryUser = proxiedUsers.stream().filter(u -> u.getUserType() == TimelyUser.UserType.USER).findFirst()
|
||||
.orElse(first);
|
||||
this.proxiedUsers.add(primaryUser);
|
||||
this.proxiedUsers
|
||||
.addAll(proxiedUsers.stream().filter(u -> !u.equals(primaryUser)).collect(Collectors.toList()));
|
||||
this.username = this.proxiedUsers.stream().map(TimelyUser::getName).collect(Collectors.joining(" -> "));
|
||||
}
|
||||
|
||||
public Set<TimelyUser> getProxiedUsers() {
|
||||
return Collections.unmodifiableSet(proxiedUsers);
|
||||
}
|
||||
|
||||
public TimelyUser getPrimaryUser() {
|
||||
return primaryUser;
|
||||
}
|
||||
|
||||
public Collection<? extends Collection<String>> getAuthorizations() {
|
||||
return Collections
|
||||
.unmodifiableCollection(proxiedUsers.stream().map(TimelyUser::getAuths).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public String[] getDNs() {
|
||||
return proxiedUsers.stream().map(TimelyUser::getDn).map(SubjectIssuerDNPair::subjectDN).toArray(String[]::new);
|
||||
}
|
||||
|
||||
public long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
@XmlElement
|
||||
public String getName() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String getShortName() {
|
||||
return DnUtils.getShortName(getPrimaryUser().getName());
|
||||
}
|
||||
|
||||
public SubjectIssuerDNPair getUserDN() {
|
||||
return getPrimaryUser().getDn();
|
||||
}
|
||||
|
||||
public Set<String> getProxyServers() {
|
||||
|
||||
// @formatter:off
|
||||
Set<String> proxyServers = getProxiedUsers().stream()
|
||||
.filter(u -> u.getUserType() == TimelyUser.UserType.SERVER)
|
||||
.map(TimelyUser::getDn)
|
||||
.map(SubjectIssuerDNPair::subjectDN)
|
||||
.collect(Collectors.toSet());
|
||||
// @formatter:on
|
||||
return proxyServers.isEmpty() ? null : proxyServers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
TimelyPrincipal that = (TimelyPrincipal) o;
|
||||
|
||||
if (!username.equals(that.username))
|
||||
return false;
|
||||
return proxiedUsers.equals(that.proxiedUsers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = username.hashCode();
|
||||
result = 31 * result + proxiedUsers.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TimelyPrincipal{" + "name='" + username + "'" + ", proxiedUsers=" + proxiedUsers + "}";
|
||||
}
|
||||
|
||||
public static TimelyPrincipal anonymousPrincipal() {
|
||||
return new TimelyPrincipal(ANONYMOUS_USER);
|
||||
}
|
||||
|
||||
public String getAuthorizationsString() {
|
||||
return proxiedUsers.stream().map(TimelyUser::getAuths).map(a -> a.toString())
|
||||
.collect(Collectors.joining(" -> ", "[", "]"));
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package timely.auth;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.google.common.collect.LinkedHashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import timely.auth.util.DnUtils;
|
||||
|
||||
/**
|
||||
* A user of a TIMELY service. Typically, one or more of these users (a chain
|
||||
* where a user called an intermediate service which in turn called us) is
|
||||
* represented with a TimelyPrincipal.
|
||||
*/
|
||||
public class TimelyUser implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public enum UserType {
|
||||
USER, SERVER
|
||||
}
|
||||
|
||||
public static final TimelyUser ANONYMOUS_USER = new TimelyUser(SubjectIssuerDNPair.of("ANONYMOUS"), UserType.USER,
|
||||
null, null, null, -1L);
|
||||
private final String name;
|
||||
private final String commonName;
|
||||
private final SubjectIssuerDNPair dn;
|
||||
private final UserType userType;
|
||||
private final Collection<String> auths;
|
||||
private final Collection<String> unmodifiableAuths;
|
||||
private final Collection<String> roles;
|
||||
private final Collection<String> unmodifiableRoles;
|
||||
private final Multimap<String, String> roleToAuthMapping;
|
||||
private final long creationTime;
|
||||
private final long expirationTime;
|
||||
|
||||
/*
|
||||
* For Spring configuration
|
||||
*/
|
||||
public TimelyUser(String subjectDn, Collection<String> auths, Collection<String> roles) {
|
||||
this.name = subjectDn;
|
||||
this.commonName = DnUtils.getCommonName(subjectDn);
|
||||
this.dn = SubjectIssuerDNPair.of(subjectDn);
|
||||
this.userType = DnUtils.isServerDN(subjectDn) ? UserType.SERVER : UserType.USER;
|
||||
this.auths = auths == null ? Collections.emptyList() : new LinkedHashSet<>(auths);
|
||||
this.unmodifiableAuths = Collections.unmodifiableCollection(this.auths);
|
||||
this.roles = roles == null ? Collections.emptyList() : new LinkedHashSet<>(roles);
|
||||
this.unmodifiableRoles = Collections.unmodifiableCollection(this.roles);
|
||||
this.roleToAuthMapping = null;
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
this.expirationTime = -1L;
|
||||
}
|
||||
|
||||
/*
|
||||
* For testing
|
||||
*/
|
||||
public TimelyUser(String subjectDn, Collection<String> auths) {
|
||||
this(SubjectIssuerDNPair.of(subjectDn), UserType.USER, auths, null, null, System.currentTimeMillis(), -1L);
|
||||
}
|
||||
|
||||
public TimelyUser(SubjectIssuerDNPair dn, UserType userType, Collection<String> auths, Collection<String> roles,
|
||||
Multimap<String, String> roleToAuthMapping, long creationTime) {
|
||||
this(dn, userType, auths, roles, roleToAuthMapping, creationTime, -1L);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public TimelyUser(@JsonProperty(value = "dn", required = true) SubjectIssuerDNPair dn,
|
||||
@JsonProperty(value = "userType", required = true) UserType userType,
|
||||
@JsonProperty("auths") Collection<String> auths, @JsonProperty("roles") Collection<String> roles,
|
||||
@JsonProperty("roleToAuthMapping") Multimap<String, String> roleToAuthMapping,
|
||||
@JsonProperty(value = "creationTime", defaultValue = "-1L") long creationTime,
|
||||
@JsonProperty(value = "expirationTime", defaultValue = "-1L") long expirationTime) {
|
||||
this.name = dn.toString();
|
||||
this.commonName = DnUtils.getCommonName(dn.subjectDN());
|
||||
this.dn = dn;
|
||||
this.userType = userType;
|
||||
this.auths = auths == null ? Collections.emptyList() : new LinkedHashSet<>(auths);
|
||||
this.unmodifiableAuths = Collections.unmodifiableCollection(this.auths);
|
||||
this.roles = roles == null ? Collections.emptyList() : new LinkedHashSet<>(roles);
|
||||
this.unmodifiableRoles = Collections.unmodifiableCollection(this.roles);
|
||||
this.roleToAuthMapping = roleToAuthMapping == null ? LinkedHashMultimap.create()
|
||||
: Multimaps.unmodifiableMultimap(LinkedHashMultimap.create(roleToAuthMapping));
|
||||
this.creationTime = creationTime;
|
||||
this.expirationTime = expirationTime;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getCommonName() {
|
||||
return commonName;
|
||||
}
|
||||
|
||||
public SubjectIssuerDNPair getDn() {
|
||||
return dn;
|
||||
}
|
||||
|
||||
public UserType getUserType() {
|
||||
return userType;
|
||||
}
|
||||
|
||||
public Collection<String> getAuths() {
|
||||
return unmodifiableAuths;
|
||||
}
|
||||
|
||||
public Collection<String> getRoles() {
|
||||
return unmodifiableRoles;
|
||||
}
|
||||
|
||||
public Multimap<String, String> getRoleToAuthMapping() {
|
||||
return roleToAuthMapping;
|
||||
}
|
||||
|
||||
public long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
public long getExpirationTime() {
|
||||
return expirationTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
|
||||
TimelyUser that = (TimelyUser) o;
|
||||
|
||||
return creationTime == that.creationTime && dn.equals(that.dn) && userType == that.userType
|
||||
&& auths.equals(that.auths) && roles.equals(that.roles);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = dn.hashCode();
|
||||
result = 31 * result + userType.hashCode();
|
||||
result = 31 * result + auths.hashCode();
|
||||
result = 31 * result + roles.hashCode();
|
||||
result = 31 * result + (int) (creationTime ^ (creationTime >>> 32));
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TimelyUser{" + "name='" + getName() + "'" + ", userType=" + getUserType() + ", auths=" + getAuths()
|
||||
+ ", roles=" + getRoles() + ", creationTime=" + getCreationTime() + "}";
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package timely.auth;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -10,20 +11,18 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
import timely.netty.http.auth.TimelyUserDetails;
|
||||
|
||||
public class UserDetailsService implements
|
||||
org.springframework.security.core.userdetails.AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
|
||||
|
||||
private HashMap<String, TimelyUser> users;
|
||||
private HashMap<String, List<String>> users;
|
||||
|
||||
public Map<String, TimelyUser> getUsers() {
|
||||
public Map<String, List<String>> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public void setUsers(List<TimelyUser> users) {
|
||||
this.users = new HashMap<>();
|
||||
users.forEach(u -> this.users.put(u.getName(), u));
|
||||
public void setUsers(LinkedHashMap<String, List<String>> users) {
|
||||
this.users = new HashMap<>(users);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -31,32 +30,25 @@ public class UserDetailsService implements
|
||||
throws UsernameNotFoundException {
|
||||
// Determine if the user is allowed to access the system, if not throw
|
||||
// UsernameNotFoundException
|
||||
String username = token.getName();
|
||||
String username = token.getName().toString();
|
||||
if (!users.containsKey(username)) {
|
||||
throw new UsernameNotFoundException(username + " not configured.");
|
||||
}
|
||||
// If allowed, populate the user details object with the authorities for
|
||||
// the user.
|
||||
return new TimelyUserDetails() {
|
||||
return new UserDetails() {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public Collection<SimpleGrantedAuthority> getAuthorities() {
|
||||
final Collection<SimpleGrantedAuthority> auths = new ArrayList<>();
|
||||
users.get(username).getAuths().forEach(a -> {
|
||||
users.get(username).forEach(a -> {
|
||||
auths.add(new SimpleGrantedAuthority(a));
|
||||
});
|
||||
return auths;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getRoles() {
|
||||
final Collection<String> roles = new ArrayList<>();
|
||||
roles.addAll(users.get(username).getRoles());
|
||||
return roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return "";
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package timely.auth.util;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
import timely.auth.AuthorizationsMinimizer;
|
||||
|
||||
public class AuthorizationsUtil {
|
||||
|
||||
public static Authorizations union(Iterable<byte[]> authorizations1, Iterable<byte[]> authorizations2) {
|
||||
LinkedList<byte[]> aggregatedAuthorizations = Lists.newLinkedList();
|
||||
addTo(aggregatedAuthorizations, authorizations1);
|
||||
addTo(aggregatedAuthorizations, authorizations2);
|
||||
return new Authorizations(aggregatedAuthorizations);
|
||||
}
|
||||
|
||||
private static void addTo(LinkedList<byte[]> aggregatedAuthorizations, Iterable<byte[]> authsToAdd) {
|
||||
for (byte[] auth : authsToAdd) {
|
||||
aggregatedAuthorizations.add(auth);
|
||||
}
|
||||
}
|
||||
|
||||
public static Authorizations toAuthorizations(Collection<String> auths) {
|
||||
return new Authorizations(auths.stream().map(String::trim).map(s -> s.getBytes(Charset.forName("UTF-8")))
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public static List<String> splitAuths(String requestedAuths) {
|
||||
return Arrays.asList(Iterables.toArray(Splitter.on(',').omitEmptyStrings().trimResults().split(requestedAuths),
|
||||
String.class));
|
||||
}
|
||||
|
||||
public static Set<Authorizations> buildAuthorizations(Collection<? extends Collection<String>> userAuths) {
|
||||
if (null == userAuths) {
|
||||
return Collections.singleton(new Authorizations());
|
||||
}
|
||||
|
||||
HashSet<Authorizations> auths = Sets.newHashSet();
|
||||
for (Collection<String> userAuth : userAuths) {
|
||||
auths.add(new Authorizations(userAuth.toArray(new String[userAuth.size()])));
|
||||
}
|
||||
|
||||
return auths;
|
||||
}
|
||||
|
||||
public static Collection<Authorizations> minimize(Collection<Authorizations> authorizations) {
|
||||
return AuthorizationsMinimizer.minimize(authorizations);
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
package timely.auth.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DnUtils {
|
||||
|
||||
/** Config for injecting NPE OU identifiers */
|
||||
public static final String PROPS_RESOURCE = "dnutils.properties";
|
||||
|
||||
private static final Properties PROPS = new Properties();
|
||||
|
||||
public static final String SUBJECT_DN_PATTERN_PROPERTY = "subject.dn.pattern";
|
||||
|
||||
private static final Pattern SUBJECT_DN_PATTERN;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DnUtils.class);
|
||||
|
||||
static {
|
||||
InputStream in = null;
|
||||
try {
|
||||
in = DnUtils.class.getClassLoader().getResourceAsStream(PROPS_RESOURCE);
|
||||
PROPS.load(in);
|
||||
} catch (Throwable t) {
|
||||
log.error(PROPS_RESOURCE + " could not be loaded!", t);
|
||||
throw new RuntimeException(t);
|
||||
} finally {
|
||||
if (null != in) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to close input stream", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
String subjectDnPattern = System.getProperty(SUBJECT_DN_PATTERN_PROPERTY,
|
||||
PROPS.getProperty(SUBJECT_DN_PATTERN_PROPERTY));
|
||||
try {
|
||||
if (null == subjectDnPattern || subjectDnPattern.isEmpty()) {
|
||||
throw new IllegalStateException(SUBJECT_DN_PATTERN_PROPERTY + " property value cannot be null");
|
||||
}
|
||||
SUBJECT_DN_PATTERN = Pattern.compile(subjectDnPattern, Pattern.CASE_INSENSITIVE);
|
||||
} catch (Throwable t) {
|
||||
log.error(SUBJECT_DN_PATTERN_PROPERTY + " = '" + subjectDnPattern + "' could not be compiled", t);
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] splitProxiedDNs(String proxiedDNs, boolean allowDups) {
|
||||
return ProxiedEntityUtils.splitProxiedDNs(proxiedDNs, allowDups);
|
||||
}
|
||||
|
||||
public static String[] splitProxiedSubjectIssuerDNs(String proxiedDNs) {
|
||||
return ProxiedEntityUtils.splitProxiedSubjectIssuerDNs(proxiedDNs);
|
||||
}
|
||||
|
||||
public static String buildProxiedDN(String... dns) {
|
||||
return ProxiedEntityUtils.buildProxiedDN(dns);
|
||||
}
|
||||
|
||||
public static Collection<String> buildNormalizedDNList(String subjectDN, String issuerDN, String proxiedSubjectDNs,
|
||||
String proxiedIssuerDNs) {
|
||||
subjectDN = normalizeDN(subjectDN);
|
||||
issuerDN = normalizeDN(issuerDN);
|
||||
List<String> dnList = new ArrayList<>();
|
||||
HashSet<String> subjects = new HashSet<>();
|
||||
String subject = subjectDN.replaceAll("(?<!\\\\)([<>])", "\\\\$1");
|
||||
dnList.add(subject);
|
||||
subjects.add(subject);
|
||||
dnList.add(issuerDN.replaceAll("(?<!\\\\)([<>])", "\\\\$1"));
|
||||
if (proxiedSubjectDNs != null) {
|
||||
if (proxiedIssuerDNs == null)
|
||||
throw new IllegalArgumentException(
|
||||
"If proxied subject DNs are supplied, then issuer DNs must be supplied as well.");
|
||||
String[] subjectDNarray = splitProxiedDNs(proxiedSubjectDNs, true);
|
||||
String[] issuerDNarray = splitProxiedDNs(proxiedIssuerDNs, true);
|
||||
if (subjectDNarray.length != issuerDNarray.length)
|
||||
throw new IllegalArgumentException(
|
||||
"Subject and issuer DN lists do not have the same number of entries: "
|
||||
+ Arrays.toString(subjectDNarray) + " vs " + Arrays.toString(issuerDNarray));
|
||||
for (int i = 0; i < subjectDNarray.length; ++i) {
|
||||
subjectDNarray[i] = normalizeDN(subjectDNarray[i]);
|
||||
if (!subjects.contains(subjectDNarray[i])) {
|
||||
issuerDNarray[i] = normalizeDN(issuerDNarray[i]);
|
||||
subjects.add(subjectDNarray[i]);
|
||||
dnList.add(subjectDNarray[i]);
|
||||
dnList.add(issuerDNarray[i]);
|
||||
if (issuerDNarray[i].equalsIgnoreCase(subjectDNarray[i]))
|
||||
throw new IllegalArgumentException(
|
||||
"Subject DN " + issuerDNarray[i] + " was passed as an issuer DN.");
|
||||
if (SUBJECT_DN_PATTERN.matcher(issuerDNarray[i]).find())
|
||||
throw new IllegalArgumentException(
|
||||
"It appears that a subject DN (" + issuerDNarray[i] + ") was passed as an issuer DN.");
|
||||
}
|
||||
}
|
||||
}
|
||||
return dnList;
|
||||
}
|
||||
|
||||
public static String buildNormalizedProxyDN(String subjectDN, String issuerDN, String proxiedSubjectDNs,
|
||||
String proxiedIssuerDNs) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String escapedDN : buildNormalizedDNList(subjectDN, issuerDN, proxiedSubjectDNs, proxiedIssuerDNs)) {
|
||||
if (sb.length() == 0)
|
||||
sb.append(escapedDN);
|
||||
else
|
||||
sb.append('<').append(escapedDN).append('>');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getCommonName(String dn) {
|
||||
return ProxiedEntityUtils.getCommonName(dn);
|
||||
}
|
||||
|
||||
public static String[] getOrganizationalUnits(String dn) {
|
||||
return ProxiedEntityUtils.getOrganizationalUnits(dn);
|
||||
}
|
||||
|
||||
public static String getShortName(String dn) {
|
||||
return ProxiedEntityUtils.getShortName(dn);
|
||||
}
|
||||
|
||||
public static boolean isServerDN(String dn) {
|
||||
return NpeUtils.isNPE(dn);
|
||||
}
|
||||
|
||||
public static String getUserDN(String[] dns) {
|
||||
return getUserDN(dns, false);
|
||||
}
|
||||
|
||||
public static String getUserDN(String[] dns, boolean issuerDNs) {
|
||||
if (issuerDNs && (dns.length % 2) != 0)
|
||||
throw new IllegalArgumentException("DNs array is not a subject/issuer DN list: " + Arrays.toString(dns));
|
||||
|
||||
for (int i = 0; i < dns.length; i += (issuerDNs) ? 2 : 1) {
|
||||
String dn = dns[i];
|
||||
if (!isServerDN(dn))
|
||||
return dn;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String[] getComponents(String dn, String componentName) {
|
||||
return ProxiedEntityUtils.getComponents(dn, componentName);
|
||||
}
|
||||
|
||||
public static String normalizeDN(String userName) {
|
||||
return ProxiedEntityUtils.normalizeDN(userName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encapsulates the known/valid NPE OU list, and whatever else is needed for NPE
|
||||
* handling. Static inner-class, so that injection of the configured OUs is only
|
||||
* performed on-demand/if needed
|
||||
*/
|
||||
public static class NpeUtils {
|
||||
|
||||
/** Property containing a comma-delimited list of OUs */
|
||||
public static final String NPE_OU_PROPERTY = "npe.ou.entries";
|
||||
|
||||
/** Parsed NPE OU identifiers */
|
||||
static final List<String> NPE_OU_LIST;
|
||||
|
||||
private NpeUtils() {
|
||||
}
|
||||
|
||||
static {
|
||||
List<String> npeOUs = new ArrayList<>();
|
||||
String ouString = System.getProperty(NPE_OU_PROPERTY, PROPS.getProperty(NPE_OU_PROPERTY));
|
||||
if (null == ouString || ouString.isEmpty()) {
|
||||
throw new IllegalStateException("No '" + NPE_OU_PROPERTY + "' value has been configured");
|
||||
}
|
||||
// Normalize and load...
|
||||
String[] ouArray = ouString.split(",");
|
||||
for (String ou : ouArray) {
|
||||
npeOUs.add(ou.trim().toUpperCase());
|
||||
}
|
||||
NPE_OU_LIST = Collections.unmodifiableList(npeOUs);
|
||||
}
|
||||
|
||||
static boolean isNPE(String dn) {
|
||||
String[] ouList = ProxiedEntityUtils.getOrganizationalUnits(dn);
|
||||
for (String ou : ouList) {
|
||||
if (NPE_OU_LIST.contains(ou.toUpperCase())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
QueryStringDecoder decoder = new QueryStringDecoder("https://my.server:3000");
|
||||
|
||||
System.out.println(decoder.path());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package timely.auth.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.handler.codec.http.HttpHeaders;
|
||||
|
||||
public class HttpHeaderUtils {
|
||||
|
||||
public static Multimap<String, String> toMultimap(HttpHeaders headers) {
|
||||
Multimap<String, String> headerMultimap = HashMultimap.create();
|
||||
if (headers != null) {
|
||||
for (Map.Entry<String, String> e : headers.entries()) {
|
||||
// lower case for HTTP/2 compatibility; even for HTTP/1, these were always
|
||||
// case-insensitive
|
||||
headerMultimap.put(e.getKey().toLowerCase(), e.getValue());
|
||||
}
|
||||
}
|
||||
return headerMultimap;
|
||||
}
|
||||
|
||||
public static String getSingleHeader(Multimap<String, String> headers, String headerName, boolean enforceOneValue)
|
||||
throws IllegalArgumentException {
|
||||
String value = null;
|
||||
// lower case for HTTP/2 compatibility; even for HTTP/1, these were always
|
||||
// case-insensitive
|
||||
headerName = headerName.toLowerCase();
|
||||
Collection<String> values = (headers == null) ? null : headers.get(headerName);
|
||||
if (values != null && !values.isEmpty()) {
|
||||
if (values.size() > 1 && enforceOneValue) {
|
||||
throw new IllegalArgumentException(headerName + " was specified multiple times, which is not allowed");
|
||||
}
|
||||
value = values.stream().findFirst().orElse(null);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package timely.auth.util;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.naming.InvalidNameException;
|
||||
import javax.naming.ldap.LdapName;
|
||||
import javax.naming.ldap.Rdn;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import timely.netty.http.auth.TimelyAuthenticationToken;
|
||||
|
||||
public class ProxiedEntityUtils {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProxiedEntityUtils.class);
|
||||
|
||||
public static String[] splitProxiedDNs(String proxiedDNs, boolean allowDups) {
|
||||
String[] dns;
|
||||
if (proxiedDNs.indexOf('<') < 0) {
|
||||
dns = new String[] { proxiedDNs };
|
||||
} else {
|
||||
Collection<String> dnCollection = allowDups ? new ArrayList<>() : new LinkedHashSet<>();
|
||||
String[] pieces = proxiedDNs.split("(?<!\\\\)<|(?<!\\\\)>");
|
||||
for (String piece : pieces) {
|
||||
if (piece.trim().length() > 0)
|
||||
dnCollection.add(piece);
|
||||
}
|
||||
|
||||
dns = dnCollection.toArray(new String[0]);
|
||||
}
|
||||
return dns;
|
||||
}
|
||||
|
||||
public static String[] splitProxiedSubjectIssuerDNs(String proxiedDNs) {
|
||||
String[] dns;
|
||||
if (proxiedDNs.indexOf('<') < 0) {
|
||||
dns = new String[] { proxiedDNs };
|
||||
} else {
|
||||
HashSet<String> subjects = new HashSet<>();
|
||||
List<String> dnList = new ArrayList<>();
|
||||
String[] pieces = proxiedDNs.split("(?<!\\\\)<|(?<!\\\\)>");
|
||||
ArrayList<String> trimmedPieces = new ArrayList<>(pieces.length);
|
||||
for (String piece : pieces) {
|
||||
piece = piece.trim();
|
||||
if (piece.length() > 0)
|
||||
trimmedPieces.add(piece);
|
||||
}
|
||||
if ((trimmedPieces.size() % 2) != 0)
|
||||
throw new IllegalArgumentException("Invalid proxied DNs list does not have entries in pairs.");
|
||||
for (int i = 0; i < trimmedPieces.size(); i += 2) {
|
||||
String subject = trimmedPieces.get(i);
|
||||
String issuer = trimmedPieces.get(i + 1);
|
||||
if (subject.length() > 0 && !subjects.contains(subject)) {
|
||||
subjects.add(subject);
|
||||
dnList.add(subject);
|
||||
dnList.add(issuer);
|
||||
}
|
||||
}
|
||||
|
||||
dns = dnList.toArray(new String[0]);
|
||||
}
|
||||
return dns;
|
||||
}
|
||||
|
||||
public static String buildProxiedDN(String... dns) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String dn : dns) {
|
||||
String escapedDN = dn.replaceAll("(?<!\\\\)(<|>)", "\\\\$1");
|
||||
if (sb.length() == 0)
|
||||
sb.append(escapedDN);
|
||||
else
|
||||
sb.append('<').append(escapedDN).append('>');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getCommonName(String dn) {
|
||||
String[] comps = getComponents(dn, "CN");
|
||||
return comps.length >= 1 ? comps[0] : null;
|
||||
}
|
||||
|
||||
public static String[] getOrganizationalUnits(String dn) {
|
||||
return getComponents(dn, "OU");
|
||||
}
|
||||
|
||||
public static String getShortName(String dn) {
|
||||
String cn = getCommonName(dn);
|
||||
if (cn == null)
|
||||
cn = dn;
|
||||
String sid = cn;
|
||||
int idx = cn.lastIndexOf(' ');
|
||||
if (idx >= 0)
|
||||
sid = cn.substring(idx + 1);
|
||||
return sid;
|
||||
}
|
||||
|
||||
public static String[] getComponents(String dn, String componentName) {
|
||||
componentName = componentName.toUpperCase();
|
||||
ArrayList<String> components = new ArrayList<>();
|
||||
try {
|
||||
LdapName name = new LdapName(dn);
|
||||
for (Rdn rdn : name.getRdns()) {
|
||||
if (componentName.equals(rdn.getType().toUpperCase())) {
|
||||
components.add(String.valueOf(rdn.getValue()));
|
||||
}
|
||||
}
|
||||
} catch (InvalidNameException e) {
|
||||
// ignore -- invalid name, so can't find components
|
||||
}
|
||||
return components.toArray(new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to normalize a DN by taking it and reversing the components if it
|
||||
* doesn't start with CN. Some systems requires the DN components be in a
|
||||
* specific order, or that order reversed. We cannot arbitrarily reorder the
|
||||
* components however, e.g., sorting them.
|
||||
*/
|
||||
public static String normalizeDN(String userName) {
|
||||
String normalizedUserName = userName.trim().toLowerCase();
|
||||
try {
|
||||
if (!normalizedUserName.startsWith("cn") || Pattern.compile(",[^ ]").matcher(normalizedUserName).find()) {
|
||||
LdapName name = new LdapName(userName);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
ArrayList<Rdn> rdns = new ArrayList<>(name.getRdns());
|
||||
if (rdns.size() > 0 && !rdns.get(0).toString().toLowerCase().startsWith("cn"))
|
||||
Collections.reverse(rdns);
|
||||
for (Rdn rdn : rdns) {
|
||||
if (sb.length() > 0)
|
||||
sb.append(", ");
|
||||
sb.append(rdn.toString());
|
||||
}
|
||||
normalizedUserName = sb.toString().toLowerCase();
|
||||
}
|
||||
} catch (InvalidNameException e) {
|
||||
// ignore -- might be a sid rather than a DN
|
||||
}
|
||||
log.trace("Normalized [" + userName + "] into [" + normalizedUserName + "]");
|
||||
return normalizedUserName;
|
||||
}
|
||||
|
||||
public static void addProxyHeaders(Multimap<String, String> headers, X509Certificate clientCert) {
|
||||
if (clientCert != null) {
|
||||
List<String> proxiedEntitiesList = new ArrayList<>();
|
||||
if (headers.containsKey(TimelyAuthenticationToken.PROXIED_ENTITIES_HEADER)) {
|
||||
String proxiedEntities = HttpHeaderUtils.getSingleHeader(headers,
|
||||
TimelyAuthenticationToken.PROXIED_ENTITIES_HEADER, false);
|
||||
headers.removeAll(TimelyAuthenticationToken.PROXIED_ENTITIES_HEADER);
|
||||
String[] preExistingProxiedEntities = ProxiedEntityUtils.splitProxiedDNs(proxiedEntities, false);
|
||||
if (preExistingProxiedEntities.length > 0) {
|
||||
proxiedEntitiesList.addAll(Arrays.asList(preExistingProxiedEntities));
|
||||
}
|
||||
}
|
||||
String subjectDN = DnUtils.normalizeDN(clientCert.getSubjectDN().getName());
|
||||
proxiedEntitiesList.add(subjectDN);
|
||||
String[] newProxiedEntities = new String[proxiedEntitiesList.size()];
|
||||
proxiedEntitiesList.toArray(newProxiedEntities);
|
||||
headers.put(TimelyAuthenticationToken.PROXIED_ENTITIES_HEADER,
|
||||
ProxiedEntityUtils.buildProxiedDN(newProxiedEntities));
|
||||
|
||||
List<String> proxiedIssuersList = new ArrayList<>();
|
||||
if (headers.containsKey(TimelyAuthenticationToken.PROXIED_ISSUERS_HEADER)) {
|
||||
String proxiedIssuers = HttpHeaderUtils.getSingleHeader(headers,
|
||||
TimelyAuthenticationToken.PROXIED_ISSUERS_HEADER, false);
|
||||
headers.removeAll(TimelyAuthenticationToken.PROXIED_ISSUERS_HEADER);
|
||||
String[] preExistingProxiedIssuers = ProxiedEntityUtils.splitProxiedDNs(proxiedIssuers, false);
|
||||
if (preExistingProxiedIssuers.length > 0) {
|
||||
proxiedEntitiesList.addAll(Arrays.asList(preExistingProxiedIssuers));
|
||||
}
|
||||
}
|
||||
String issuerDN = DnUtils.normalizeDN(clientCert.getIssuerDN().getName());
|
||||
proxiedIssuersList.add(issuerDN);
|
||||
String[] newProxiedIssuers = new String[proxiedIssuersList.size()];
|
||||
proxiedIssuersList.toArray(newProxiedIssuers);
|
||||
headers.put(TimelyAuthenticationToken.PROXIED_ISSUERS_HEADER,
|
||||
ProxiedEntityUtils.buildProxiedDN(newProxiedIssuers));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package timely.auth.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.accumulo.core.client.BatchDeleter;
|
||||
import org.apache.accumulo.core.client.BatchScanner;
|
||||
import org.apache.accumulo.core.client.BatchWriterConfig;
|
||||
import org.apache.accumulo.core.client.Connector;
|
||||
import org.apache.accumulo.core.client.IteratorSetting;
|
||||
import org.apache.accumulo.core.client.Scanner;
|
||||
import org.apache.accumulo.core.client.ScannerBase;
|
||||
import org.apache.accumulo.core.client.TableNotFoundException;
|
||||
import org.apache.accumulo.core.security.Authorizations;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import timely.auth.AuthorizationsMinimizer;
|
||||
import timely.auth.ConfigurableVisibilityFilter;
|
||||
import timely.auth.ScannerBaseDelegate;
|
||||
|
||||
public class ScannerHelper {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ScannerHelper.class);
|
||||
|
||||
public static Scanner createScanner(Connector connector, String tableName,
|
||||
Collection<Authorizations> authorizations) throws TableNotFoundException {
|
||||
if (authorizations == null || authorizations.isEmpty())
|
||||
throw new IllegalArgumentException("Authorizations must not be empty.");
|
||||
|
||||
Iterator<Authorizations> iter = AuthorizationsMinimizer.minimize(authorizations).iterator();
|
||||
Scanner scanner = connector.createScanner(tableName, iter.next());
|
||||
addVisibilityFilters(iter, scanner);
|
||||
return scanner;
|
||||
}
|
||||
|
||||
public static BatchScanner createBatchScanner(Connector connector, String tableName,
|
||||
Collection<Authorizations> authorizations, int numQueryThreads) throws TableNotFoundException {
|
||||
if (authorizations == null || authorizations.isEmpty())
|
||||
throw new IllegalArgumentException("Authorizations must not be empty.");
|
||||
|
||||
Iterator<Authorizations> iter = AuthorizationsMinimizer.minimize(authorizations).iterator();
|
||||
BatchScanner batchScanner = connector.createBatchScanner(tableName, iter.next(), numQueryThreads);
|
||||
addVisibilityFilters(iter, batchScanner);
|
||||
return batchScanner;
|
||||
}
|
||||
|
||||
public static BatchDeleter createBatchDeleter(Connector connector, String tableName,
|
||||
Collection<Authorizations> authorizations, int numQueryThreads, long maxMemory, long maxLatency,
|
||||
int maxWriteThreads) throws TableNotFoundException {
|
||||
if (authorizations == null || authorizations.isEmpty())
|
||||
throw new IllegalArgumentException("Authorizations must not be empty.");
|
||||
|
||||
Iterator<Authorizations> iter = AuthorizationsMinimizer.minimize(authorizations).iterator();
|
||||
BatchWriterConfig bwCfg = new BatchWriterConfig().setMaxLatency(maxLatency, TimeUnit.MILLISECONDS)
|
||||
.setMaxMemory(maxMemory).setMaxWriteThreads(maxWriteThreads);
|
||||
BatchDeleter batchDeleter = connector.createBatchDeleter(tableName, iter.next(), numQueryThreads, bwCfg);
|
||||
addVisibilityFilters(iter, batchDeleter);
|
||||
return batchDeleter;
|
||||
}
|
||||
|
||||
protected static void addVisibilityFilters(Iterator<Authorizations> iter, ScannerBase scanner) {
|
||||
for (int priority = 10; iter.hasNext(); priority++) {
|
||||
IteratorSetting cfg = new IteratorSetting(priority, ConfigurableVisibilityFilter.class);
|
||||
cfg.setName("visibilityFilter" + priority);
|
||||
cfg.addOption(ConfigurableVisibilityFilter.AUTHORIZATIONS_OPT, iter.next().toString());
|
||||
// Set the visibility filter as a "system" iterator, which means that normal
|
||||
// modify, remove, clear operations performed
|
||||
// on the scanner will not modify/remove/clear this iterator. This way, if a
|
||||
// query logic attempts to reconfigure the
|
||||
// scanner's iterators, then this iterator will remain intact.
|
||||
if (scanner instanceof ScannerBaseDelegate) {
|
||||
((ScannerBaseDelegate) scanner).addSystemScanIterator(cfg);
|
||||
} else {
|
||||
logger.warn("Adding system visibility filter to non-wrapped scanner {}.", scanner.getClass(),
|
||||
new Exception());
|
||||
scanner.addScanIterator(cfg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package timely.configuration;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
import org.hibernate.validator.constraints.NotBlank;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
public class Accumulo {
|
||||
@@ -12,8 +12,6 @@ public class Accumulo {
|
||||
@NotBlank
|
||||
private String instanceName;
|
||||
@NotBlank
|
||||
private String zookeeperTimeout = "120s";
|
||||
@NotBlank
|
||||
private String username;
|
||||
@NotBlank
|
||||
private String password;
|
||||
@@ -48,14 +46,6 @@ public class Accumulo {
|
||||
this.instanceName = instanceName;
|
||||
}
|
||||
|
||||
public String getZookeeperTimeout() {
|
||||
return zookeeperTimeout;
|
||||
}
|
||||
|
||||
public void setZookeeperTimeout(String zookeeperTimeout) {
|
||||
this.zookeeperTimeout = zookeeperTimeout;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ public class Cache {
|
||||
private List<String> nonCachedMetrics = new ArrayList<>();
|
||||
private long maxUniqueTagSets = 50000;
|
||||
private long flushInterval = 5000;
|
||||
private long staleCacheExpiration = 1800000;
|
||||
|
||||
public HashMap<String, Integer> getMetricAgeOffHours() {
|
||||
return metricAgeOffHours;
|
||||
@@ -58,12 +57,4 @@ public class Cache {
|
||||
public void setFlushInterval(long flushInterval) {
|
||||
this.flushInterval = flushInterval;
|
||||
}
|
||||
|
||||
public long getStaleCacheExpiration() {
|
||||
return staleCacheExpiration;
|
||||
}
|
||||
|
||||
public void setStaleCacheExpiration(long staleCacheExpiration) {
|
||||
this.staleCacheExpiration = staleCacheExpiration;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user