mirror of
https://github.com/NationalSecurityAgency/timely.git
synced 2026-11-10 11:51:29 -10:00
Compare commits
175
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1597ec61ae | ||
|
|
89a374f9a2 | ||
|
|
f145d0d1a4 | ||
|
|
387140722c | ||
|
|
b3617820f7 | ||
|
|
ac2d9463dc | ||
|
|
c32867685f | ||
|
|
08057e7d67 | ||
|
|
a058e5a816 | ||
|
|
99b81986a4 | ||
|
|
d7ecbd345f | ||
|
|
0f9059b6b6 | ||
|
|
fcbdd9296b | ||
|
|
df3ade7929 | ||
|
|
823a6fa08f | ||
|
|
89ab2635fd | ||
|
|
13d8db5ab7 | ||
|
|
8db5358b50 | ||
|
|
3e376e106b | ||
|
|
18eecfd7b0 | ||
|
|
065d8a9a9f | ||
|
|
09c2ef7e11 | ||
|
|
cb875819ff | ||
|
|
fcc5f0f716 | ||
|
|
c87543f7d7 | ||
|
|
d7f5a3b20b | ||
|
|
9601cdc927 | ||
|
|
60c2588c79 | ||
|
|
f3275c6a34 | ||
|
|
7486b6b761 | ||
|
|
b1a968590c | ||
|
|
8f86b20c02 | ||
|
|
a3620a3f24 | ||
|
|
9c99e74958 | ||
|
|
91ec36e819 | ||
|
|
9ad1b18b74 | ||
|
|
82c45d4dd4 | ||
|
|
a0e47d0b48 | ||
|
|
d3dc324d84 | ||
|
|
4871b3a4a9 | ||
|
|
8d5d5eeca8 | ||
|
|
a006a44372 | ||
|
|
6cfcdc1030 | ||
|
|
4eb7ceff8c | ||
|
|
6ad8da2b99 | ||
|
|
7f56a36906 | ||
|
|
1443fdceb9 | ||
|
|
3cff14eb03 | ||
|
|
8fa5b56e62 | ||
|
|
b2f2cef834 | ||
|
|
c6a2988083 | ||
|
|
d54817cc9a | ||
|
|
c4ee035584 | ||
|
|
d4bfc1a3aa | ||
|
|
fb315148a1 | ||
|
|
e8ae575086 | ||
|
|
da0146c741 | ||
|
|
882b4e2587 | ||
|
|
8048862f2c | ||
|
|
c2f00c3d19 | ||
|
|
61b1a245e2 | ||
|
|
a3c33115c4 | ||
|
|
bed1ceb9ee | ||
|
|
06e2699a44 | ||
|
|
d09faaa087 | ||
|
|
088f1a5cab | ||
|
|
cf6d4ada3e | ||
|
|
e464a8c9e0 | ||
|
|
8e4e61c373 | ||
|
|
729dca23ba | ||
|
|
104d20ad1b | ||
|
|
f0f005f8fa | ||
|
|
8593218b89 | ||
|
|
cbfe6a439f | ||
|
|
455616d568 | ||
|
|
9d3172cc75 | ||
|
|
7aa7b0da2a | ||
|
|
6c61861d83 | ||
|
|
91882ba363 | ||
|
|
ed61b5f305 | ||
|
|
a083c2d632 | ||
|
|
2891794174 | ||
|
|
c99b2471cf | ||
|
|
bb479a58d7 | ||
|
|
ff37d40801 | ||
|
|
a7d980975e | ||
|
|
30f5a0c1b2 | ||
|
|
2f9e6ca2d7 | ||
|
|
954528a460 | ||
|
|
0f7b514b30 | ||
|
|
a6ca46e1c1 | ||
|
|
487d1d4a5c | ||
|
|
e3c26f815c | ||
|
|
bbc1946204 | ||
|
|
991412f99b | ||
|
|
5428e93cb5 | ||
|
|
c18aae5a89 | ||
|
|
6972c46a1a | ||
|
|
4d7bee7566 | ||
|
|
4b11b3d50f | ||
|
|
84b9856ec7 | ||
|
|
c9548a9b9a | ||
|
|
aec7bd4c38 | ||
|
|
e2b8b643f2 | ||
|
|
c19e1d8b2f | ||
|
|
cb73e8e75c | ||
|
|
4c508c1a7d | ||
|
|
c6c2c0d41e | ||
|
|
a24cef78b3 | ||
|
|
08f99f6540 | ||
|
|
be11da7d15 | ||
|
|
4bc5753328 | ||
|
|
2ccb89a06d | ||
|
|
dfc3840ad4 | ||
|
|
6235034d8b | ||
|
|
d8de6ac06f | ||
|
|
f381946abe | ||
|
|
48bbe6a561 | ||
|
|
0f6110ea59 | ||
|
|
461b5e7e78 | ||
|
|
4ec7d94c28 | ||
|
|
77e910ae06 | ||
|
|
a4998af887 | ||
|
|
2858549ede | ||
|
|
57f0e1408f | ||
|
|
151adc025a | ||
|
|
5abd9d7200 | ||
|
|
fa2e211c72 | ||
|
|
a21438976e | ||
|
|
ba37047f3a | ||
|
|
9305470c69 | ||
|
|
200233542e | ||
|
|
3cd78dc624 | ||
|
|
9027cac6e3 | ||
|
|
3663b4e6d5 | ||
|
|
64973d0674 | ||
|
|
5512306f1e | ||
|
|
d35ae08188 | ||
|
|
e448657afb | ||
|
|
1dcd893711 | ||
|
|
409f5375d1 | ||
|
|
c5df8139ca | ||
|
|
dcd23d4fc8 | ||
|
|
cc7326fc19 | ||
|
|
0d2b6e61c8 | ||
|
|
b7cd8765c5 | ||
|
|
a9d27d5b1b | ||
|
|
7d67eb218d | ||
|
|
5fb7e3dd2b | ||
|
|
5a89861cec | ||
|
|
a3bc9a01ee | ||
|
|
dba494b06d | ||
|
|
5826884c3c | ||
|
|
f94c731bbc | ||
|
|
4e042bcb94 | ||
|
|
ab7f499134 | ||
|
|
c098f9f3e4 | ||
|
|
94cfcbc0c4 | ||
|
|
674e1b0ab5 | ||
|
|
4eedb84547 | ||
|
|
bef86eac37 | ||
|
|
27bb16e403 | ||
|
|
e2bbe4e212 | ||
|
|
a95d2d7ea1 | ||
|
|
f751175190 | ||
|
|
648199f330 | ||
|
|
fcfc3f7bc0 | ||
|
|
200bc39902 | ||
|
|
f854c9e394 | ||
|
|
73ddae1f8d | ||
|
|
cb7184503e | ||
|
|
3a357b50ef | ||
|
|
689aee0678 | ||
|
|
32f6b9d4c9 | ||
|
|
512f318387 |
No files matched your search
@@ -7,4 +7,5 @@ target/
|
|||||||
logs/
|
logs/
|
||||||
server/pki/
|
server/pki/
|
||||||
client/src/main/python/setup.py
|
client/src/main/python/setup.py
|
||||||
|
grafana/timely-app/yarn-error.log
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
|
|
||||||
Apache License
|
Apache License
|
||||||
Version 2.0, January 2004
|
Version 2.0, January 2004
|
||||||
http://www.apache.org/licenses/
|
httpProperties://www.apache.org/licenses/
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
httpProperties://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[![Apache License][li]][ll]
|
[![Apache License][li]][ll]
|
||||||
|
|
||||||
Timely is a time series database application that provides secure access to time series data. Timely is written in Java and designed to work with [Apache Accumulo](https://accumulo.apache.org/) and [Grafana](https://www.grafana.com). Documentation is located [here](https://nationalsecurityagency.github.io/timely/).
|
Timely is a time series database application that provides secure access to time series data. Timely is written in Java and designed to work with [Apache Accumulo](https://accumuloProperties.apache.org/) and [Grafana](https://www.grafana.com). Documentation is located [here](https://nationalsecurityagency.github.io/timely/).
|
||||||
|
|
||||||
[li]: https://img.shields.io/badge/license-ASL-blue.svg
|
[li]: https://img.shields.io/badge/license-ASL-blue.svg
|
||||||
[ll]: https://www.apache.org/licenses/LICENSE-2.0
|
[ll]: https://www.apache.org/licenses/LICENSE-2.0
|
||||||
+21
-7
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely</artifactId>
|
<artifactId>timely</artifactId>
|
||||||
<version>1.0.1-SNAPSHOT</version>
|
<version>2.1.4-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>timely-analytics</artifactId>
|
<artifactId>timely-analytics</artifactId>
|
||||||
<!--
|
<!--
|
||||||
@@ -53,14 +53,13 @@
|
|||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely-common</artifactId>
|
<artifactId>timely-common</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@@ -68,6 +67,7 @@
|
|||||||
<pluginManagement>
|
<pluginManagement>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<configuration>
|
<configuration>
|
||||||
<compilerId>jdt</compilerId>
|
<compilerId>jdt</compilerId>
|
||||||
@@ -76,7 +76,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.tycho</groupId>
|
<groupId>org.eclipse.tycho</groupId>
|
||||||
<artifactId>tycho-compiler-jdt</artifactId>
|
<artifactId>tycho-compiler-jdt</artifactId>
|
||||||
<version>0.21.0</version>
|
<version>1.4.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</plugin>
|
</plugin>
|
||||||
@@ -168,6 +168,12 @@
|
|||||||
</excludes>
|
</excludes>
|
||||||
</artifactSet>
|
</artifactSet>
|
||||||
<filters>
|
<filters>
|
||||||
|
<filter>
|
||||||
|
<artifact>*:*</artifact>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/module-info.class</exclude>
|
||||||
|
</excludes>
|
||||||
|
</filter>
|
||||||
<filter>
|
<filter>
|
||||||
<artifact>org.apache.flink:*</artifact>
|
<artifact>org.apache.flink:*</artifact>
|
||||||
<excludes>
|
<excludes>
|
||||||
@@ -245,6 +251,14 @@
|
|||||||
<artifactSet>
|
<artifactSet>
|
||||||
<excludes combine.self="override" />
|
<excludes combine.self="override" />
|
||||||
</artifactSet>
|
</artifactSet>
|
||||||
|
<filters>
|
||||||
|
<filter>
|
||||||
|
<artifact>*:*</artifact>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/module-info.class</exclude>
|
||||||
|
</excludes>
|
||||||
|
</filter>
|
||||||
|
</filters>
|
||||||
</configuration>
|
</configuration>
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import java.util.List;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.apache.flink.streaming.util.serialization.SerializationSchema;
|
import org.apache.flink.streaming.util.serialization.SerializationSchema;
|
||||||
|
|
||||||
import timely.model.Tag;
|
import timely.model.Tag;
|
||||||
|
|
||||||
public class MetricHistogram implements Serializable, SerializationSchema<MetricHistogram> {
|
public class MetricHistogram implements Serializable, SerializationSchema<MetricHistogram> {
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package timely.analytics.flink;
|
package timely.analytics.flink;
|
||||||
|
|
||||||
import org.apache.flink.api.java.functions.KeySelector;
|
import org.apache.flink.api.java.functions.KeySelector;
|
||||||
|
|
||||||
import timely.api.response.MetricResponse;
|
import timely.api.response.MetricResponse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Uniquely defines a time series in a Flink stream. A unique time series is the
|
* Uniquely defines a time series in a Flink stream. A unique time series is the metric name and all of its tags, to include visibility if it exists.
|
||||||
* metric name and all of its tags, to include visibility if it exists.
|
|
||||||
*/
|
*/
|
||||||
public class MetricKeySelector implements KeySelector<MetricResponse, String> {
|
public class MetricKeySelector implements KeySelector<MetricResponse,String> {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ import org.apache.flink.api.common.accumulators.Accumulator;
|
|||||||
* Custom accumulator that retains a sorted map of strings and their counts
|
* Custom accumulator that retains a sorted map of strings and their counts
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class SortedStringAccumulator implements Accumulator<String, ConcurrentSkipListMap<String, MutableLong>> {
|
public class SortedStringAccumulator implements Accumulator<String,ConcurrentSkipListMap<String,MutableLong>> {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private ConcurrentSkipListMap<String, MutableLong> values = new ConcurrentSkipListMap<>();
|
private ConcurrentSkipListMap<String,MutableLong> values = new ConcurrentSkipListMap<>();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void add(String value) {
|
public void add(String value) {
|
||||||
@@ -25,7 +25,7 @@ public class SortedStringAccumulator implements Accumulator<String, ConcurrentSk
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ConcurrentSkipListMap<String, MutableLong> getLocalValue() {
|
public ConcurrentSkipListMap<String,MutableLong> getLocalValue() {
|
||||||
return values;
|
return values;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ public class SortedStringAccumulator implements Accumulator<String, ConcurrentSk
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void merge(Accumulator<String, ConcurrentSkipListMap<String, MutableLong>> other) {
|
public void merge(Accumulator<String,ConcurrentSkipListMap<String,MutableLong>> other) {
|
||||||
other.getLocalValue().forEach((k, v) -> {
|
other.getLocalValue().forEach((k, v) -> {
|
||||||
if (values.containsKey(k)) {
|
if (values.containsKey(k)) {
|
||||||
values.get(k).add(v.longValue());
|
values.get(k).add(v.longValue());
|
||||||
@@ -46,7 +46,7 @@ public class SortedStringAccumulator implements Accumulator<String, ConcurrentSk
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Accumulator<String, ConcurrentSkipListMap<String, MutableLong>> clone() {
|
public Accumulator<String,ConcurrentSkipListMap<String,MutableLong>> clone() {
|
||||||
SortedStringAccumulator a = new SortedStringAccumulator();
|
SortedStringAccumulator a = new SortedStringAccumulator();
|
||||||
a.getLocalValue().putAll(this.values);
|
a.getLocalValue().putAll(this.values);
|
||||||
return a;
|
return a;
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
|
|||||||
import org.apache.flink.streaming.api.watermark.Watermark;
|
import org.apache.flink.streaming.api.watermark.Watermark;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import timely.api.response.MetricResponse;
|
import timely.api.response.MetricResponse;
|
||||||
import timely.api.response.MetricResponses;
|
import timely.api.response.MetricResponses;
|
||||||
import timely.client.websocket.ClientHandler;
|
import timely.client.websocket.ClientHandler;
|
||||||
@@ -41,7 +42,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SubscriptionSource.class);
|
private static final Logger log = LoggerFactory.getLogger(SubscriptionSource.class);
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private transient WebSocketSubscriptionClient client = null;
|
private transient WebSocketSubscriptionClient client = null;
|
||||||
@@ -63,12 +64,11 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void open(Configuration parameters) throws Exception {
|
public void open(Configuration parameters) throws Exception {
|
||||||
LOG.info("Opening summarization job.");
|
log.info("Opening summarization job.");
|
||||||
super.open(parameters);
|
super.open(parameters);
|
||||||
client = new WebSocketSubscriptionClient(jp.getTimelyHostname(), jp.getTimelyHttpsPort(), jp.getTimelyWssPort(),
|
client = new WebSocketSubscriptionClient(jp.getTimelyHostname(), jp.getTimelyHttpsPort(), jp.getTimelyWssPort(), jp.isClientAuth(), jp.isDoLogin(),
|
||||||
jp.isDoLogin(), jp.getTimelyUsername(), jp.getTimelyPassword(), jp.getKeyStoreFile(),
|
jp.getKeyStoreFile(), jp.getKeyStoreType(), jp.getKeyStorePass(), jp.getTrustStoreFile(), jp.getTrustStoreType(),
|
||||||
jp.getKeyStoreType(), jp.getKeyStorePass(), jp.getTrustStoreFile(), jp.getTrustStoreType(),
|
jp.getTrustStorePass(), jp.isHostVerificationEnabled(), jp.getBufferSize());
|
||||||
jp.getTrustStorePass(), jp.isHostVerificationEnabled(), jp.getBufferSize());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -81,7 +81,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run(SourceContext<MetricResponse> ctx) throws Exception {
|
public void run(SourceContext<MetricResponse> ctx) throws Exception {
|
||||||
LOG.info("Running summarization job");
|
log.info("Running summarization job");
|
||||||
final SortedStringAccumulator dateTimeAccumulator = new SortedStringAccumulator();
|
final SortedStringAccumulator dateTimeAccumulator = new SortedStringAccumulator();
|
||||||
this.getRuntimeContext().addAccumulator("source hourly count", dateTimeAccumulator);
|
this.getRuntimeContext().addAccumulator("source hourly count", dateTimeAccumulator);
|
||||||
final LongCounter sourceInputs = new LongCounter();
|
final LongCounter sourceInputs = new LongCounter();
|
||||||
@@ -96,29 +96,27 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Session session, EndpointConfig config) {
|
public void onOpen(Session session, EndpointConfig config) {
|
||||||
session.addMessageHandler(new MessageHandler.Whole<String>() {
|
session.addMessageHandler(String.class, new MessageHandler.Whole<String>() {
|
||||||
|
|
||||||
private final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH");
|
private final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH");
|
||||||
private long lastWatermarkTime = 0L;
|
private long lastWatermarkTime = 0L;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onMessage(final String message) {
|
public void onMessage(final String message) {
|
||||||
LOG.info("Message received on Websocket session {}, length: {}", session.getId(),
|
log.info("Message received on Websocket session {}, length: {}", session.getId(), message.length());
|
||||||
message.length());
|
|
||||||
try {
|
try {
|
||||||
// Deserialize in this thread
|
// Deserialize in this thread
|
||||||
final MetricResponses responses = JsonSerializer.getObjectMapper().readValue(message,
|
final MetricResponses responses = JsonSerializer.getObjectMapper().readValue(message, MetricResponses.class);
|
||||||
MetricResponses.class);
|
|
||||||
// Process in the other
|
// Process in the other
|
||||||
final Runnable r = () -> {
|
final Runnable r = () -> {
|
||||||
responses.getResponses().forEach(response -> {
|
responses.getResponses().forEach(response -> {
|
||||||
if (response.isComplete()) {
|
if (response.isComplete()) {
|
||||||
LOG.info("Received last message.");
|
log.info("Received last message.");
|
||||||
ctx.emitWatermark(new Watermark(Long.MAX_VALUE));
|
ctx.emitWatermark(new Watermark(Long.MAX_VALUE));
|
||||||
subscriptionsRemaining.getAndDecrement();
|
subscriptionsRemaining.getAndDecrement();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
LOG.trace("Received metric: {}", response);
|
log.trace("Received metric: {}", response);
|
||||||
long time = response.getTimestamp();
|
long time = response.getTimestamp();
|
||||||
ctx.collectWithTimestamp(response, time);
|
ctx.collectWithTimestamp(response, time);
|
||||||
dateTimeAccumulator.add(formatter.format(new Date(response.getTimestamp())));
|
dateTimeAccumulator.add(formatter.format(new Date(response.getTimestamp())));
|
||||||
@@ -141,11 +139,11 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
inputProcessedInMainThread.add(1);
|
inputProcessedInMainThread.add(1);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOG.error("Error deserializing metric response, closing", e);
|
log.error("Error deserializing metric response, closing", e);
|
||||||
try {
|
try {
|
||||||
close();
|
close();
|
||||||
} catch (Exception e1) {
|
} catch (Exception e1) {
|
||||||
LOG.error("Error closing client", e1);
|
log.error("Error closing client", e1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -158,7 +156,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
try {
|
try {
|
||||||
close();
|
close();
|
||||||
} catch (Exception e1) {
|
} catch (Exception e1) {
|
||||||
LOG.error("Error closing client", e1);
|
log.error("Error closing client", e1);
|
||||||
}
|
}
|
||||||
// Signal done sending data
|
// Signal done sending data
|
||||||
ctx.emitWatermark(new Watermark(Long.MAX_VALUE));
|
ctx.emitWatermark(new Watermark(Long.MAX_VALUE));
|
||||||
@@ -170,7 +168,7 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
try {
|
try {
|
||||||
close();
|
close();
|
||||||
} catch (Exception e1) {
|
} catch (Exception e1) {
|
||||||
LOG.error("Error closing client", e1);
|
log.error("Error closing client", e1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,14 +176,14 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
try {
|
try {
|
||||||
client.open(handler);
|
client.open(handler);
|
||||||
for (String m : metrics) {
|
for (String m : metrics) {
|
||||||
LOG.info("Adding subscription for {}", m);
|
log.info("Adding subscription for {}", m);
|
||||||
client.addSubscription(m, null, start, end, 5000);
|
client.addSubscription(m, null, start, end, 5000);
|
||||||
}
|
}
|
||||||
while (!client.isClosed() && subscriptionsRemaining.get() > 0) {
|
while (!client.isClosed() && subscriptionsRemaining.get() > 0) {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(5000);
|
Thread.sleep(5000);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
LOG.error("Sleep interrupted.");
|
log.error("Sleep interrupted.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -195,21 +193,21 @@ public class SubscriptionSource extends RichSourceFunction<MetricResponse> imple
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void cancel() {
|
public void cancel() {
|
||||||
LOG.info("Cancelling subscription source.");
|
log.info("Cancelling subscription source.");
|
||||||
try {
|
try {
|
||||||
close();
|
close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Error closing web socket client");
|
log.error("Error closing web socket client");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
LOG.info("Stopping subscription source.");
|
log.info("Stopping subscription source.");
|
||||||
try {
|
try {
|
||||||
close();
|
close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Error closing web socket client");
|
log.error("Error closing web socket client");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,11 +13,12 @@ import org.apache.flink.streaming.api.functions.sink.SocketClientSink;
|
|||||||
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
|
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import timely.api.response.MetricResponse;
|
import timely.api.response.MetricResponse;
|
||||||
|
|
||||||
public class SummarizationJob {
|
public class SummarizationJob {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(SummarizationJob.class);
|
private static final Logger log = LoggerFactory.getLogger(SummarizationJob.class);
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
@@ -26,11 +27,11 @@ public class SummarizationJob {
|
|||||||
System.exit(1);
|
System.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG.info("Loading properties from: {}", args[0]);
|
log.info("Loading properties from: {}", args[0]);
|
||||||
ParameterTool params = ParameterTool.fromPropertiesFile(args[0]);
|
ParameterTool params = ParameterTool.fromPropertiesFile(args[0]);
|
||||||
|
|
||||||
final SummarizationJobParameters jp = new SummarizationJobParameters(params);
|
final SummarizationJobParameters jp = new SummarizationJobParameters(params);
|
||||||
LOG.info("Properties: {}", jp);
|
log.info("Properties: {}", jp);
|
||||||
|
|
||||||
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
|
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
@@ -42,7 +43,7 @@ public class SummarizationJob {
|
|||||||
.window(TumblingEventTimeWindows.of(jp.getSummarizationInterval()))
|
.window(TumblingEventTimeWindows.of(jp.getSummarizationInterval()))
|
||||||
.fold(new MetricHistogram(), new FoldFunction<MetricResponse, MetricHistogram>() {
|
.fold(new MetricHistogram(), new FoldFunction<MetricResponse, MetricHistogram>() {
|
||||||
|
|
||||||
private final Logger LOG = LoggerFactory
|
private final Logger log = LoggerFactory
|
||||||
.getLogger("timely.analytics.SummarizationJob.FoldFunction@");
|
.getLogger("timely.analytics.SummarizationJob.FoldFunction@");
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ public class SummarizationJob {
|
|||||||
throw new RuntimeException("Tags don't not match - partitioning problem");
|
throw new RuntimeException("Tags don't not match - partitioning problem");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LOG.trace("Updating histogram for {} with value {} at {} for metric {}", histo.getMetric()
|
log.trace("Updating histogram for {} with value {} at {} for metric {}", histo.getMetric()
|
||||||
+ histo.getTags(), metric.getValue(), metric.getTimestamp(), metric.getMetric()
|
+ histo.getTags(), metric.getValue(), metric.getTimestamp(), metric.getMetric()
|
||||||
+ metric.getTags());
|
+ metric.getTags());
|
||||||
histo.update(metric.getValue(), metric.getTimestamp());
|
histo.update(metric.getValue(), metric.getTimestamp());
|
||||||
@@ -67,10 +68,10 @@ public class SummarizationJob {
|
|||||||
})
|
})
|
||||||
.name("Metric Windows")
|
.name("Metric Windows")
|
||||||
.addSink(
|
.addSink(
|
||||||
new SocketClientSink<MetricHistogram>(jp.getTimelyHostname(), jp.getTimelyTcpPort(),
|
new SocketClientSink<MetricHistogram>(jp.getTimelyHostname(), jp.getTimelyTcpPort(),
|
||||||
new MetricHistogram(), 2, true) {
|
new MetricHistogram(), 2, true) {
|
||||||
|
|
||||||
private final Logger LOG = LoggerFactory
|
private final Logger log = LoggerFactory
|
||||||
.getLogger("timely.analytics.SummarizationJob.SocketClientSink");
|
.getLogger("timely.analytics.SummarizationJob.SocketClientSink");
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private final LongCounter sinkCounter = new LongCounter();
|
private final LongCounter sinkCounter = new LongCounter();
|
||||||
@@ -82,7 +83,7 @@ public class SummarizationJob {
|
|||||||
super.open(parameters);
|
super.open(parameters);
|
||||||
this.getRuntimeContext().addAccumulator("sink counter", this.sinkCounter);
|
this.getRuntimeContext().addAccumulator("sink counter", this.sinkCounter);
|
||||||
this.getRuntimeContext().addAccumulator("sink hourly count", dateTimeAccumulator);
|
this.getRuntimeContext().addAccumulator("sink hourly count", dateTimeAccumulator);
|
||||||
LOG.info("Sink opened");
|
log.info("Sink opened");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -96,7 +97,7 @@ public class SummarizationJob {
|
|||||||
@Override
|
@Override
|
||||||
public void close() throws Exception {
|
public void close() throws Exception {
|
||||||
super.close();
|
super.close();
|
||||||
LOG.info("Sink closed");
|
log.info("Sink closed");
|
||||||
}
|
}
|
||||||
|
|
||||||
}).name("Timely Metric Sink");
|
}).name("Timely Metric Sink");
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
|||||||
private final int timelyTcpPort;
|
private final int timelyTcpPort;
|
||||||
private final int timelyHttpsPort;
|
private final int timelyHttpsPort;
|
||||||
private final int timelyWssPort;
|
private final int timelyWssPort;
|
||||||
|
private final boolean clientAuth;
|
||||||
private final boolean doLogin;
|
private final boolean doLogin;
|
||||||
private final String timelyUsername;
|
private final String timelyUsername;
|
||||||
private final String timelyPassword;
|
private final String timelyPassword;
|
||||||
@@ -40,6 +41,7 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
|||||||
timelyTcpPort = params.getInt("timelyTcpPort", 4241);
|
timelyTcpPort = params.getInt("timelyTcpPort", 4241);
|
||||||
timelyHttpsPort = params.getInt("timelyHttpsPort", 4242);
|
timelyHttpsPort = params.getInt("timelyHttpsPort", 4242);
|
||||||
timelyWssPort = params.getInt("timelyWssPort", 4243);
|
timelyWssPort = params.getInt("timelyWssPort", 4243);
|
||||||
|
clientAuth = params.getBoolean("clientAuth", false);
|
||||||
doLogin = params.getBoolean("doLogin", false);
|
doLogin = params.getBoolean("doLogin", false);
|
||||||
timelyUsername = params.get("timelyUsername", null);
|
timelyUsername = params.get("timelyUsername", null);
|
||||||
timelyPassword = params.get("timelyPassword", null);
|
timelyPassword = params.get("timelyPassword", null);
|
||||||
@@ -69,6 +71,7 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
|||||||
timelyTcpPort = conf.getInteger("timelyTcpPort", 4241);
|
timelyTcpPort = conf.getInteger("timelyTcpPort", 4241);
|
||||||
timelyHttpsPort = conf.getInteger("timelyHttpsPort", 4242);
|
timelyHttpsPort = conf.getInteger("timelyHttpsPort", 4242);
|
||||||
timelyWssPort = conf.getInteger("timelyWssPort", 4243);
|
timelyWssPort = conf.getInteger("timelyWssPort", 4243);
|
||||||
|
clientAuth = conf.getBoolean("clientAuth", false);
|
||||||
doLogin = conf.getBoolean("doLogin", false);
|
doLogin = conf.getBoolean("doLogin", false);
|
||||||
timelyUsername = conf.getString("timelyUsername", null);
|
timelyUsername = conf.getString("timelyUsername", null);
|
||||||
timelyPassword = conf.getString("timelyPassword", null);
|
timelyPassword = conf.getString("timelyPassword", null);
|
||||||
@@ -112,6 +115,10 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
|||||||
return timelyWssPort;
|
return timelyWssPort;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isClientAuth() {
|
||||||
|
return clientAuth;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isDoLogin() {
|
public boolean isDoLogin() {
|
||||||
return doLogin;
|
return doLogin;
|
||||||
}
|
}
|
||||||
@@ -177,8 +184,8 @@ public class SummarizationJobParameters extends GlobalJobParameters implements S
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, String> toMap() {
|
public Map<String,String> toMap() {
|
||||||
Map<String, String> m = new HashMap<>();
|
Map<String,String> m = new HashMap<>();
|
||||||
m.put("timelyHostname", this.timelyHostname);
|
m.put("timelyHostname", this.timelyHostname);
|
||||||
m.put("timelyHttpsPort", Integer.toString(this.timelyHttpsPort));
|
m.put("timelyHttpsPort", Integer.toString(this.timelyHttpsPort));
|
||||||
m.put("timelyWssPort", Integer.toString(this.timelyWssPort));
|
m.put("timelyWssPort", Integer.toString(this.timelyWssPort));
|
||||||
|
|||||||
@@ -15,4 +15,12 @@
|
|||||||
<Method name="getMetrics" />
|
<Method name="getMetrics" />
|
||||||
<Bug pattern="EI_EXPOSE_REP" />
|
<Bug pattern="EI_EXPOSE_REP" />
|
||||||
</Match>
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<!-- these are probably avoidable, but needs further triage to fix -->
|
||||||
|
<Bug pattern="EI_EXPOSE_REP" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<!-- these are probably avoidable, but needs further triage to fix -->
|
||||||
|
<Bug pattern="EI_EXPOSE_REP2" />
|
||||||
|
</Match>
|
||||||
</FindBugsFilter>
|
</FindBugsFilter>
|
||||||
@@ -6,6 +6,7 @@ import java.util.List;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import timely.model.Metric;
|
import timely.model.Metric;
|
||||||
import timely.model.Tag;
|
import timely.model.Tag;
|
||||||
import timely.model.parse.MetricParser;
|
import timely.model.parse.MetricParser;
|
||||||
@@ -96,9 +97,8 @@ public class MetricHistogramTest {
|
|||||||
Metric metric = metricParser.parse(put);
|
Metric metric = metricParser.parse(put);
|
||||||
Assert.assertEquals("sys.cpu.user_summarized", metric.getName());
|
Assert.assertEquals("sys.cpu.user_summarized", metric.getName());
|
||||||
metric.getTags().forEach(t -> {
|
metric.getTags().forEach(t -> {
|
||||||
Assert.assertTrue(
|
Assert.assertTrue(t.equals(t1) || t.equals(t2) || t.equals(avg) || t.equals(min) || t.equals(max) || t.equals(sum) || t.equals(count)
|
||||||
t.equals(t1) || t.equals(t2) || t.equals(avg) || t.equals(min) || t.equals(max) || t.equals(sum)
|
|| t.equals(p50) || t.equals(p75) || t.equals(p90) || t.equals(p99));
|
||||||
|| t.equals(count) || t.equals(p50) || t.equals(p75) || t.equals(p90) || t.equals(p99));
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/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=$(cd $THIS_DIR/.. && pwd)
|
||||||
|
BIN_DIR=${BASE_DIR}/bin
|
||||||
|
|
||||||
|
. ${BIN_DIR}/timely-balancer-env.sh
|
||||||
|
|
||||||
|
for i in $(seq 1 $NUM_INSTANCES); do
|
||||||
|
echo ${BIN_DIR}/timely-balancer.sh $i
|
||||||
|
${BIN_DIR}/timely-balancer.sh $i
|
||||||
|
done
|
||||||
Executable
+21
@@ -0,0 +1,21 @@
|
|||||||
|
#!/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=$(cd $THIS_DIR/.. && pwd)
|
||||||
|
BIN_DIR=${BASE_DIR}/bin
|
||||||
|
|
||||||
|
. ${BIN_DIR}/timely-balancer-env.sh
|
||||||
|
|
||||||
|
for i in $(seq 1 $NUM_INSTANCES); do
|
||||||
|
PID=`jps -m | grep -E 'timely-balancer-.*-exec.jar' | grep "instance=${i}" | awk '{print $1}'`
|
||||||
|
if [ "$PID" != "" ]; then
|
||||||
|
echo "stopping timely-balancer instance ${i} [${PID}]"
|
||||||
|
kill -9 $PID
|
||||||
|
fi
|
||||||
|
done
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
export TRUSTSTORE_FILE=
|
|
||||||
export TRUSTSTORE_TYPE="jks";
|
|
||||||
export TRUSTSTORE_PASS=
|
|
||||||
export KEYSTORE_FILE=
|
|
||||||
export KEYSTORE_TYPE="pkcs12";
|
|
||||||
export KEYSTORE_PASS=
|
|
||||||
|
|
||||||
export NUM_QUERY_THREADS=4
|
|
||||||
export NUM_INGEST_THREADS=4
|
|
||||||
@@ -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}/../..
|
|
||||||
TMP_DIR="${BASE_DIR}/tmp"
|
|
||||||
CONF_DIR="${BASE_DIR}/conf"
|
|
||||||
LIB_DIR="${BASE_DIR}/lib"
|
|
||||||
|
|
||||||
. ${THIS_DIR}/load-test-env.sh
|
|
||||||
|
|
||||||
export CLASSPATH="${CONF_DIR}:${THIS_DIR}:${LIB_DIR}/*"
|
|
||||||
JVM_ARGS="-Xmx1G -Xms1G"
|
|
||||||
|
|
||||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.testing.MetricPutLoadTest $*"
|
|
||||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.testing.MetricPutLoadTest $*
|
|
||||||
@@ -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}/../..
|
|
||||||
TMP_DIR="${BASE_DIR}/tmp"
|
|
||||||
CONF_DIR="${BASE_DIR}/conf"
|
|
||||||
LIB_DIR="${BASE_DIR}/lib"
|
|
||||||
|
|
||||||
. ${THIS_DIR}/load-test-env.sh
|
|
||||||
|
|
||||||
export CLASSPATH="${CONF_DIR}:${THIS_DIR}:${LIB_DIR}/*"
|
|
||||||
JVM_ARGS="-Xmx1G -Xms1G"
|
|
||||||
|
|
||||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.testing.MetricQueryLoadTest $*"
|
|
||||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.testing.MetricQueryLoadTest $*
|
|
||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
NUM_INSTANCES=1
|
||||||
|
ACCUMULO_ZOOKEEPERS=localhost:2181
|
||||||
|
HADOOP_CONF_DIR=${HADOOP_CONF_DIR}
|
||||||
|
HADOOP_DEFAULT_FS=hdfs://localhost:8020
|
||||||
|
TCP_BASE_PORT=4242
|
||||||
|
HTTP_BASE_PORT=4243
|
||||||
|
WEBSOCKET_BASE_PORT=4244
|
||||||
|
UDP_BASE_PORT=4245
|
||||||
|
|
||||||
|
HOST_IP=0.0.0.0
|
||||||
|
HOST=$(hostname -s)
|
||||||
|
HOST_VERIFICATION_ENABLED=true
|
||||||
|
|
||||||
|
GENERATE_KEYS=true
|
||||||
|
TRUST_STORE_TYPE=
|
||||||
|
TRUST_STORE_FILE=
|
||||||
|
TRUST_STORE_PASSWORD=
|
||||||
|
KEY_STORE_TYPE=
|
||||||
|
KEY_STORE_FILE=
|
||||||
|
KEY_STORE_PASSWORD=
|
||||||
|
AUTHORIZATION_URL=
|
||||||
|
AUTHORIZATION_CERTIFICATE_TYPE=
|
||||||
|
AUTHORIZATION_CERTIFICATE_FILE=
|
||||||
|
ANONYMOUS_HTTP=true
|
||||||
|
ANONYMOUS_WEBSOCKET=true
|
||||||
@@ -1,46 +1,68 @@
|
|||||||
#!/bin/bash -vx
|
#!/bin/bash
|
||||||
|
|
||||||
if [[ `uname` == "Darwin" ]]; then
|
if [[ $(uname) == "Darwin" ]]; then
|
||||||
THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0`
|
THIS_SCRIPT=$(python -c 'import os,sys; print os.path.realpath(sys.argv[1])' "$0")
|
||||||
TCNATIVE_SUFFIX="jnilib"
|
|
||||||
else
|
else
|
||||||
THIS_SCRIPT=`readlink -f $0`
|
THIS_SCRIPT=$(readlink -f "$0")
|
||||||
TCNATIVE_SUFFIX="so"
|
HW=`uname -m`
|
||||||
|
OS_PATH=linux-${HW}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# netty tcnative file reference
|
if [ -z "$1" ]; then
|
||||||
#netty-tcnative-1.1.33.Fork18-linux-x86_64-fedora.jar -> libnetty-tcnative.so
|
export INSTANCE="1"
|
||||||
#netty-tcnative-1.1.33.Fork18-linux-x86_64.jar -> libnetty-tcnative.so
|
else
|
||||||
#netty-tcnative-1.1.33.Fork18-osx-x86_64.jar -> libnetty-tcnative.jnilib
|
export INSTANCE="$1"
|
||||||
|
|
||||||
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
|
fi
|
||||||
mkdir ${TMP_DIR}
|
|
||||||
|
|
||||||
if [[ -e ${NATIVE_DIR} ]]; then
|
PID=$(jps -m | grep -E 'timely-balancer-.*-exec.jar' | grep "instance=${INSTANCE}" | awk '{print $1}')
|
||||||
rm -rf ${NATIVE_DIR}
|
|
||||||
|
if [ "$PID" == "" ]; then
|
||||||
|
THIS_DIR="${THIS_SCRIPT%/*}"
|
||||||
|
BASE_DIR=$(cd "$THIS_DIR"/.. && pwd)
|
||||||
|
TMP_DIR="${BASE_DIR}/tmp"
|
||||||
|
LIB_DIR="${BASE_DIR}/lib"
|
||||||
|
BIN_DIR="${BASE_DIR}/bin"
|
||||||
|
export CONF_DIR="${BASE_DIR}/conf"
|
||||||
|
NATIVE_DIR="${BIN_DIR}/META-INF/native"
|
||||||
|
|
||||||
|
set -a
|
||||||
|
. "${BIN_DIR}/timely-balancer-env.sh"
|
||||||
|
set +a
|
||||||
|
|
||||||
|
# use either a value from timely-balancer-env.sh or the default
|
||||||
|
export LOG_DIR="${TIMELY_LOG_DIR:-${BASE_DIR}/logs}"
|
||||||
|
|
||||||
|
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}"
|
||||||
|
|
||||||
|
if [[ ! -e ${LOG_DIR} ]]; then
|
||||||
|
mkdir "${LOG_DIR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
JVM_ARGS="-Xmx2G -Xms2G -XX:NewSize=1G -XX:MaxNewSize=1G"
|
||||||
|
JVM_ARGS="${JVM_ARGS} -Dlogging.config=${CONF_DIR}/log4j2.yml"
|
||||||
|
JVM_ARGS="${JVM_ARGS} -Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"
|
||||||
|
JVM_ARGS="${JVM_ARGS} -XX:+UseG1GC -XX:+UseStringDeduplication"
|
||||||
|
JVM_ARGS="${JVM_ARGS} -Djava.net.preferIPv4Stack=true"
|
||||||
|
JVM_ARGS="${JVM_ARGS} -XX:+UseNUMA"
|
||||||
|
|
||||||
|
if [[ -n "$OS_PATH" ]]; then
|
||||||
|
pushd "${BASE_DIR}/bin" || exit
|
||||||
|
"${JAVA_HOME}"/bin/jar xf "${LIB_DIR}"/netty-tcnative-boringssl-static-*.Final-"${OS_PATH}".jar ${NATIVE_DIR}/libnetty_tcnative_linux_"${HW}".so
|
||||||
|
"${JAVA_HOME}"/bin/jar xf "${LIB_DIR}"/netty-transport-native-epoll-*-"${OS_PATH}".jar ${NATIVE_DIR}/libnetty_transport_native_epoll_"${HW}".so
|
||||||
|
popd || exit
|
||||||
|
JVM_ARGS="${JVM_ARGS} -Djava.library.path=${NATIVE_DIR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "${JAVA_HOME}/bin/java ${JVM_ARGS} -jar ${BIN_DIR}/timely-balancer-*-exec.jar --instance=${INSTANCE}"
|
||||||
|
nohup "${JAVA_HOME}"/bin/java ${JVM_ARGS} -jar "${BIN_DIR}"/timely-balancer-*-exec.jar --instance="${INSTANCE}" >> "${LOG_DIR}/timely-balancer${INSTANCE}.out" 2>&1 &
|
||||||
|
else
|
||||||
|
echo "timely-balancer --instance=${INSTANCE} already running with pid ${PID}"
|
||||||
fi
|
fi
|
||||||
mkdir -p ${NATIVE_DIR}
|
|
||||||
|
|
||||||
pushd ${BASE_DIR}/bin
|
|
||||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-tcnative*.jar META-INF/native/libnetty_tcnative.${NATIVE_SUFFIX}
|
|
||||||
$JAVA_HOME/bin/jar xf ${LIB_DIR}/netty-transport-native-epoll*.jar META-INF/native/libnetty_transport_native_epoll_x86_64.${NATIVE_SUFFIX}
|
|
||||||
popd
|
|
||||||
|
|
||||||
export CLASSPATH="${CONF_DIR}:${LIB_DIR}/*"
|
|
||||||
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} -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
|
|
||||||
|
|
||||||
echo "$JAVA_HOME/bin/java ${JVM_ARGS} timely.balancer.Balancer --spring.config.name=timely --spring.profiles.active=balancer"
|
|
||||||
$JAVA_HOME/bin/java ${JVM_ARGS} timely.balancer.Balancer --spring.config.name=timely --spring.profiles.active=balancer
|
|
||||||
@@ -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,26 +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/timely-balancer.log"
|
|
||||||
filePattern="/srv/logs/timely/$${date:yyyy-MM}/timely-balancer-%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>
|
|
||||||
</Loggers>
|
|
||||||
</Configuration>
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
Configuration:
|
||||||
|
status: warn
|
||||||
|
monitorInterval: 60
|
||||||
|
|
||||||
|
Properties:
|
||||||
|
Property:
|
||||||
|
- name: logDir
|
||||||
|
value: ${env:LOG_DIR}
|
||||||
|
- name: PID
|
||||||
|
value: "????"
|
||||||
|
- name: LOG_PATTERN
|
||||||
|
value: "%d{ISO8601} %-5p [%-40.40t] [%-40.40c{1.}] %m%n%wEx"
|
||||||
|
|
||||||
|
Appenders:
|
||||||
|
RollingFile:
|
||||||
|
- name: File
|
||||||
|
fileName: "${sys:logDir}/timely-balancer${env:INSTANCE}.log"
|
||||||
|
filePattern: "${sys:logDir}/timely-balancer${env:INSTANCE}.log.%d{yyyy-MM-dd}-%i.gz"
|
||||||
|
append: true
|
||||||
|
bufferedIO: true
|
||||||
|
bufferSize: 8192
|
||||||
|
Policies:
|
||||||
|
TimeBasedTriggeringPolicy:
|
||||||
|
interval: 1
|
||||||
|
SizeBasedTriggeringPolicy:
|
||||||
|
size: 250MB
|
||||||
|
DefaultRolloverStrategy:
|
||||||
|
max: 10
|
||||||
|
PatternLayout:
|
||||||
|
pattern: "${LOG_PATTERN}"
|
||||||
|
|
||||||
|
Loggers:
|
||||||
|
Root:
|
||||||
|
level: info
|
||||||
|
AppenderRef:
|
||||||
|
- ref: File
|
||||||
@@ -1,49 +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: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" />
|
|
||||||
</beans:bean>
|
|
||||||
|
|
||||||
<user-service id="usernamePasswordService">
|
|
||||||
<user name="test" password="test1" authorities="A,B,C" />
|
|
||||||
</user-service>
|
|
||||||
|
|
||||||
<beans:bean id="UserNamePasswordAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
|
||||||
<beans:property name="userDetailsService" ref="usernamePasswordService"/>
|
|
||||||
</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>
|
|
||||||
|
|
||||||
</beans:beans>
|
|
||||||
+142
-120
@@ -1,127 +1,149 @@
|
|||||||
timely-balancer:
|
timely:
|
||||||
zooKeeper:
|
instance: ${INSTANCE}
|
||||||
servers: localhost:2181
|
zookeeper:
|
||||||
|
servers: ${ACCUMULO_ZOOKEEPERS}
|
||||||
timeout: 30s
|
timeout: 30s
|
||||||
checkServerHealthInterval: 10000
|
|
||||||
serverFailuresBeforeDown: 6
|
|
||||||
serverSuccessesBeforeUp: 1
|
|
||||||
assignmentFile: /timely/balancer/assignments.csv
|
|
||||||
security:
|
security:
|
||||||
session-max-age: 86400
|
session-max-age: 86400
|
||||||
allow-anonymous-access: true
|
cache-expiration-minutes: 60
|
||||||
serverSsl:
|
cache-refresh-minutes: 5
|
||||||
certificate-file:
|
authorization-url: ${AUTHORIZATION_URL}
|
||||||
key-file:
|
allow-anonymous-http-access: ${ANONYMOUS_HTTP:true}
|
||||||
#key-password:
|
allow-anonymous-ws-access: ${ANONYMOUS_WEBSOCKET:true}
|
||||||
use-generated-keypair: false
|
server-ssl:
|
||||||
trust-store-file:
|
key-store-type: ${KEY_STORE_TYPE}
|
||||||
use-openssl: true
|
key-store-file: ${KEY_STORE_FILE}
|
||||||
#use-ciphers:
|
key-store-password: ${KEY_STORE_PASSWORD}
|
||||||
clientSsl:
|
use-generated-keypair: ${GENERATE_KEYS}
|
||||||
keyFile:
|
ignore-ssl-handshake-errors: true
|
||||||
keyType: pkcs12
|
trust-store-type: ${TRUST_STORE_TYPE}
|
||||||
#keyPassword:
|
trust-store-file: ${TRUST_STORE_FILE}
|
||||||
trustStoreFile:
|
trust-store-password: ${TRUST_STORE_PASSWORD}
|
||||||
trustStoreType: jks
|
client-ssl:
|
||||||
#trustStorePassword:
|
key-store-type: ${KEY_STORE_TYPE}
|
||||||
|
key-store-file: ${KEY_STORE_FILE}
|
||||||
|
key-store-password: ${KEY_STORE_PASSWORD}
|
||||||
|
trust-store-type: ${TRUST_STORE_TYPE}
|
||||||
|
trust-store-file: ${TRUST_STORE_FILE}
|
||||||
|
trust-store-password: ${TRUST_STORE_PASSWORD}
|
||||||
|
hostVerificationEnabled: ${HOST_VERIFICATION_ENABLED:true}
|
||||||
|
jwt-ssl:
|
||||||
|
key-store-type: ${AUTHORIZATION_CERTIFICATE_TYPE}
|
||||||
|
key-store-file: ${AUTHORIZATION_CERTIFICATE_FILE}
|
||||||
|
key-store-password: ${AUTHORIZATION_CERTIFICATE_PASSWORD}
|
||||||
cache:
|
cache:
|
||||||
enabled: false
|
enabled: false
|
||||||
metric-age-off-hours:
|
metric-age-off-hours:
|
||||||
default: 26
|
default: 26
|
||||||
nonCachedMetrics:
|
non-cached-metrics:
|
||||||
server:
|
balancer:
|
||||||
ip: 127.0.0.1
|
check-server-health-interval: 10000
|
||||||
tcp-port: 4242
|
server-failures-before-down: 6
|
||||||
numTcpPools: 1
|
server-successes-before-up: 1
|
||||||
tcpBufferSize: 100
|
default-fs: ${HADOOP_DEFAULT_FS}
|
||||||
tcpClientPool:
|
fs-config-resources:
|
||||||
minIdlePerKey: 0
|
- ${HADOOP_CONF_DIR}/core-site.xml
|
||||||
maxIdlePerKey: 40
|
- ${HADOOP_CONF_DIR}/hdfs-site.xml
|
||||||
maxTotalPerKey: 40
|
assignment-file: hdfs:///timely/balancer/assignments.csv
|
||||||
maxTotal: -1
|
server:
|
||||||
lifo: true
|
ip: ${HOST_IP}
|
||||||
fairness: false
|
tcp-base-port: ${TCP_BASE_PORT}
|
||||||
maxWaitMillis: -1
|
num-tcp-pools: 1
|
||||||
minEvictableIdleTimeMillis: 1800000
|
tcp-buffer-size: 100
|
||||||
evictorShutdownTimeoutMillis: 10000
|
tcp-client-pool:
|
||||||
softMinEvictableIdleTimeMillis: -1
|
min-idle-per-key: 0
|
||||||
numTestsPerEvictionRun: 3
|
max-idle-per-key: 40
|
||||||
timeBetweenEvictionRunsMillis: -1
|
max-total-per-key: 40
|
||||||
blockWhenExhausted: true
|
max-total: -1
|
||||||
jmxEnabled: true
|
lifo: true
|
||||||
testOnBorrow: false
|
fairness: false
|
||||||
testOnReturn: false
|
max-wait-millis: -1
|
||||||
udp-port: 4245
|
min-evictable-idle-time-millis: 1800000
|
||||||
udpClientPool:
|
evictor-shutdown-timeout-millis: 10000
|
||||||
minIdlePerKey: 0
|
soft-min-evictable-idle-time-millis: -1
|
||||||
maxIdlePerKey: 40
|
num-tests-per-eviction-run: 3
|
||||||
maxTotalPerKey: 40
|
time-between-eviction-runs-millis: -1
|
||||||
maxTotal: -1
|
block-when-exhausted: true
|
||||||
lifo: true
|
jmx-enabled: true
|
||||||
fairness: false
|
test-on-borrow: false
|
||||||
maxWaitMillis: -1
|
test-on-return: false
|
||||||
minEvictableIdleTimeMillis: 1800000
|
udp-base-port: ${UDP_BASE_PORT}
|
||||||
evictorShutdownTimeoutMillis: 10000
|
udp-client-pool:
|
||||||
softMinEvictableIdleTimeMillis: -1
|
min-idle-per-key: 0
|
||||||
numTestsPerEvictionRun: 3
|
max-idle-per-key: 40
|
||||||
timeBetweenEvictionRunsMillis: -1
|
max-total-per-key: 40
|
||||||
blockWhenExhausted: true
|
max-total: -1
|
||||||
jmxEnabled: true
|
lifo: true
|
||||||
testOnBorrow: false
|
fairness: false
|
||||||
testOnReturn: false
|
max-wait-millis: -1
|
||||||
http:
|
min-evictable-idle-time-millis: 1800000
|
||||||
host: localhost
|
evictor-shutdown-timeout-millis: 10000
|
||||||
ip: 127.0.0.1
|
soft-min-evictable-idle-time-millis: -1
|
||||||
port: 4243
|
num-tests-per-eviction-run: 3
|
||||||
redirect-path: /secure-me
|
time-between-eviction-runs-millis: -1
|
||||||
strict-transport-max-age: 608400
|
block-when-exhausted: true
|
||||||
cors:
|
jmx-enabled: true
|
||||||
allow-any-origin: false
|
test-on-borrow: false
|
||||||
allow-null-origin: false
|
test-on-return: false
|
||||||
allow-credentials: true
|
http:
|
||||||
allowed-origins:
|
host: ${HOST}
|
||||||
allowed-methods: DELETE,GET,HEAD,OPTIONS,PUT,POST
|
ip: ${HOST_IP}
|
||||||
allowed-headers: content-type
|
base-port: ${HTTP_BASE_PORT}
|
||||||
httpClientPool:
|
redirect-path: /secure-me
|
||||||
minIdlePerKey: 0
|
strict-transport-max-age: 604800
|
||||||
maxIdlePerKey: 40
|
cors:
|
||||||
maxTotalPerKey: 40
|
allow-any-origin: false
|
||||||
maxTotal: -1
|
allow-null-origin: false
|
||||||
lifo: true
|
allow-credentials: true
|
||||||
fairness: false
|
allowed-origins:
|
||||||
maxWaitMillis: -1
|
allowed-methods: DELETE,GET,HEAD,OPTIONS,PUT,POST
|
||||||
minEvictableIdleTimeMillis: 1800000
|
allowed-headers: content-type
|
||||||
evictorShutdownTimeoutMillis: 10000
|
httpClientPool:
|
||||||
softMinEvictableIdleTimeMillis: -1
|
min-idle-per-key: 0
|
||||||
numTestsPerEvictionRun: 3
|
max-idle-per-key: 40
|
||||||
timeBetweenEvictionRunsMillis: -1
|
max-total-per-key: 40
|
||||||
blockWhenExhausted: true
|
max-total: -1
|
||||||
jmxEnabled: true
|
lifo: true
|
||||||
testOnBorrow: false
|
fairness: false
|
||||||
testOnReturn: false
|
max-wait-millis: -1
|
||||||
websocket:
|
min-evictable-idle-time-millis: 1800000
|
||||||
ip: 127.0.0.1
|
evictor-shutdown-timeout-millis: 10000
|
||||||
port: 5244
|
soft-min-evictable-idle-time-millis: -1
|
||||||
timeout: 60
|
num-tests-per-eviction-run: 3
|
||||||
subscription-lag: 120
|
time-between-eviction-runs-millis: -1
|
||||||
scanner-batch-size: 10000
|
block-when-exhausted: true
|
||||||
flush-interval-seconds: 30
|
jmx-enabled: true
|
||||||
scanner-read-ahead: 1
|
test-on-borrow: false
|
||||||
subscription-batch-size: 5000
|
test-on-return: false
|
||||||
wsClientPool:
|
websocket:
|
||||||
minIdlePerKey: 0
|
ip: ${HOST_IP}
|
||||||
maxIdlePerKey: 40
|
base-port: ${WEBSOCKET_BASE_PORT}
|
||||||
maxTotalPerKey: 40
|
timeout: 60
|
||||||
maxTotal: -1
|
subscription-lag: 120
|
||||||
lifo: true
|
scanner-batch-size: 10000
|
||||||
fairness: false
|
flush-interval-seconds: 30
|
||||||
maxWaitMillis: -1
|
scanner-read-ahead: 1
|
||||||
minEvictableIdleTimeMillis: 1800000
|
subscription-batch-size: 5000
|
||||||
evictorShutdownTimeoutMillis: 10000
|
incoming-buffer-size: 50000000
|
||||||
softMinEvictableIdleTimeMillis: -1
|
ws-client-pool:
|
||||||
numTestsPerEvictionRun: 3
|
min-idle-per-key: 0
|
||||||
timeBetweenEvictionRunsMillis: -1
|
max-idle-per-key: 40
|
||||||
blockWhenExhausted: true
|
max-total-per-key: 40
|
||||||
jmxEnabled: true
|
max-total: -1
|
||||||
testOnBorrow: false
|
lifo: true
|
||||||
testOnReturn: false
|
fairness: false
|
||||||
|
max-wait-millis: -1
|
||||||
|
min-evictable-idle-time-millis: 1800000
|
||||||
|
evictor-shutdown-timeout-millis: 10000
|
||||||
|
soft-min-evictable-idle-time-millis: -1
|
||||||
|
num-tests-per-eviction-run: 3
|
||||||
|
time-between-eviction-runs-millis: -1
|
||||||
|
block-when-exhausted: true
|
||||||
|
jmx-enabled: true
|
||||||
|
test-on-borrow: false
|
||||||
|
test-on-return: false
|
||||||
|
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
ROOT: info
|
||||||
|
timely: debug
|
||||||
+89
-69
@@ -4,9 +4,13 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely</artifactId>
|
<artifactId>timely</artifactId>
|
||||||
<version>1.0.1-SNAPSHOT</version>
|
<version>2.1.4-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>timely-balancer</artifactId>
|
<artifactId>timely-balancer</artifactId>
|
||||||
|
<description>Timely Balancer</description>
|
||||||
|
<properties>
|
||||||
|
<start-class>timely.balancer.TimelyBalancer</start-class>
|
||||||
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
@@ -37,12 +41,8 @@
|
|||||||
<artifactId>commons-beanutils</artifactId>
|
<artifactId>commons-beanutils</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.github.lukehutch</groupId>
|
<groupId>io.github.classgraph</groupId>
|
||||||
<artifactId>fast-classpath-scanner</artifactId>
|
<artifactId>classgraph</artifactId>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>io.netty</groupId>
|
|
||||||
<artifactId>netty-all</artifactId>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sourceforge.javacsv</groupId>
|
<groupId>net.sourceforge.javacsv</groupId>
|
||||||
@@ -51,16 +51,6 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.accumulo</groupId>
|
<groupId>org.apache.accumulo</groupId>
|
||||||
<artifactId>accumulo-core</artifactId>
|
<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>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
@@ -97,21 +87,19 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.hadoop</groupId>
|
<groupId>org.apache.hadoop</groupId>
|
||||||
<artifactId>hadoop-common</artifactId>
|
<artifactId>hadoop-common</artifactId>
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>jdk.tools</groupId>
|
|
||||||
<artifactId>jdk.tools</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.hadoop</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>hadoop-minicluster</artifactId>
|
<artifactId>log4j-1.2-api</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-websocket</artifactId>
|
<artifactId>spring-websocket</artifactId>
|
||||||
@@ -134,6 +122,18 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-validation</artifactId>
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-context</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-config</artifactId>
|
<artifactId>spring-security-config</artifactId>
|
||||||
@@ -150,10 +150,6 @@
|
|||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely-common</artifactId>
|
<artifactId>timely-common</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>timely</groupId>
|
|
||||||
<artifactId>timely-server</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.lmax</groupId>
|
<groupId>com.lmax</groupId>
|
||||||
<artifactId>disruptor</artifactId>
|
<artifactId>disruptor</artifactId>
|
||||||
@@ -161,9 +157,31 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.netty</groupId>
|
<groupId>io.netty</groupId>
|
||||||
<artifactId>netty-tcnative</artifactId>
|
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||||
<version>${version.netty-tcnative}</version>
|
<classifier>linux-aarch_64</classifier>
|
||||||
<classifier>${os.detected.classifier}</classifier>
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.netty</groupId>
|
||||||
|
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||||
|
<classifier>linux-x86_64</classifier>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.netty</groupId>
|
||||||
|
<artifactId>netty-transport-native-epoll</artifactId>
|
||||||
|
<classifier>linux-aarch_64</classifier>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.netty</groupId>
|
||||||
|
<artifactId>netty-transport-native-epoll</artifactId>
|
||||||
|
<classifier>linux-x86_64</classifier>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.activation</groupId>
|
||||||
|
<artifactId>activation</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -176,11 +194,6 @@
|
|||||||
<artifactId>log4j-core</artifactId>
|
<artifactId>log4j-core</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-slf4j-impl</artifactId>
|
|
||||||
<scope>runtime</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.javassist</groupId>
|
<groupId>org.javassist</groupId>
|
||||||
<artifactId>javassist</artifactId>
|
<artifactId>javassist</artifactId>
|
||||||
@@ -191,11 +204,21 @@
|
|||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.hadoop</groupId>
|
||||||
|
<artifactId>hadoop-minicluster</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jsoup</groupId>
|
<groupId>org.jsoup</groupId>
|
||||||
<artifactId>jsoup</artifactId>
|
<artifactId>jsoup</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-test-autoconfigure</artifactId>
|
<artifactId>spring-boot-test-autoconfigure</artifactId>
|
||||||
@@ -203,12 +226,16 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely-common</artifactId>
|
<artifactId>timely-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
@@ -252,9 +279,8 @@
|
|||||||
<artifactItems>
|
<artifactItems>
|
||||||
<artifactItem>
|
<artifactItem>
|
||||||
<groupId>io.netty</groupId>
|
<groupId>io.netty</groupId>
|
||||||
<artifactId>netty-tcnative</artifactId>
|
<artifactId>netty-tcnative-boringssl-static</artifactId>
|
||||||
<version>${version.netty-tcnative}</version>
|
<version>${version.netty-tcnative}</version>
|
||||||
<classifier>${os.detected.classifier}</classifier>
|
|
||||||
<type>jar</type>
|
<type>jar</type>
|
||||||
<overWrite>false</overWrite>
|
<overWrite>false</overWrite>
|
||||||
<outputDirectory>${project.build.directory}/native</outputDirectory>
|
<outputDirectory>${project.build.directory}/native</outputDirectory>
|
||||||
@@ -269,6 +295,20 @@
|
|||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-failsafe-plugin</artifactId>
|
<artifactId>maven-failsafe-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<version>3.1.2</version>
|
||||||
|
<configuration>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<!--suppress UnresolvedMavenProperty, MavenModelInspection -->
|
||||||
|
<mainClass>${start-class}</mainClass>
|
||||||
|
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>build-helper-maven-plugin</artifactId>
|
<artifactId>build-helper-maven-plugin</artifactId>
|
||||||
@@ -298,35 +338,15 @@
|
|||||||
</build>
|
</build>
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>native-epoll-linux</id>
|
<id>docker</id>
|
||||||
<activation>
|
<build>
|
||||||
<os>
|
<plugins>
|
||||||
<family>!mac</family>
|
<plugin>
|
||||||
</os>
|
<groupId>com.spotify</groupId>
|
||||||
</activation>
|
<artifactId>docker-maven-plugin</artifactId>
|
||||||
<dependencies>
|
</plugin>
|
||||||
<dependency>
|
</plugins>
|
||||||
<groupId>io.netty</groupId>
|
</build>
|
||||||
<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>
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
</project>
|
</project>
|
||||||
Vendored
+13
-10
@@ -15,25 +15,28 @@
|
|||||||
<include>NOTICE*</include>
|
<include>NOTICE*</include>
|
||||||
</includes>
|
</includes>
|
||||||
</fileSet>
|
</fileSet>
|
||||||
<fileSet>
|
|
||||||
<directory>${project.build.directory}</directory>
|
|
||||||
<outputDirectory>lib</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>timely*.jar</include>
|
|
||||||
</includes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
<fileSet>
|
||||||
<directory>${project.build.directory}/lib</directory>
|
<directory>${project.build.directory}/lib</directory>
|
||||||
<outputDirectory>lib</outputDirectory>
|
<outputDirectory>lib</outputDirectory>
|
||||||
<includes>
|
<includes>
|
||||||
<include>*.jar</include>
|
<include>netty-tcnative-boringssl-static*linux-x86_64.jar</include>
|
||||||
|
<include>netty-tcnative-boringssl-static*linux-aarch_64.jar</include>
|
||||||
|
<include>netty-transport-native-epoll*linux-x86_64.jar</include>
|
||||||
|
<include>netty-transport-native-epoll*linux-aarch_64.jar</include>
|
||||||
</includes>
|
</includes>
|
||||||
</fileSet>
|
</fileSet>
|
||||||
|
<fileSet>
|
||||||
|
<directory>${project.build.directory}</directory>
|
||||||
|
<outputDirectory>bin</outputDirectory>
|
||||||
|
<includes>
|
||||||
|
<include>timely-balancer-*-exec.jar</include>
|
||||||
|
</includes>
|
||||||
|
</fileSet>
|
||||||
<fileSet>
|
<fileSet>
|
||||||
<directory>${project.basedir}/bin</directory>
|
<directory>${project.basedir}/bin</directory>
|
||||||
<outputDirectory>bin</outputDirectory>
|
<outputDirectory>bin</outputDirectory>
|
||||||
<includes>
|
<includes>
|
||||||
<include>*</include>
|
<include>**/*</include>
|
||||||
</includes>
|
</includes>
|
||||||
</fileSet>
|
</fileSet>
|
||||||
<fileSet>
|
<fileSet>
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
FROM azul/zulu-openjdk-alpine:11
|
||||||
|
|
||||||
|
LABEL version=${project.version} \
|
||||||
|
run="docker run ${docker.image.prefix}${project.artifactId}:latest" \
|
||||||
|
description="${project.description}"
|
||||||
|
|
||||||
|
ADD ${project.build.finalName}-exec.jar /app.jar
|
||||||
|
RUN apk add libc6-compat curl
|
||||||
|
|
||||||
|
EXPOSE 54322 54323 54324 54325
|
||||||
|
ENTRYPOINT ["java","-jar","app.jar"]
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package timely.balancer;
|
package timely.balancer;
|
||||||
|
|
||||||
import java.util.Timer;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
import java.util.TimerTask;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
import com.google.common.util.concurrent.AtomicDouble;
|
import com.google.common.util.concurrent.AtomicDouble;
|
||||||
@@ -20,38 +20,26 @@ public class ArrivalRate {
|
|||||||
private AtomicDouble longTermRate = new AtomicDouble(0);
|
private AtomicDouble longTermRate = new AtomicDouble(0);
|
||||||
private AtomicLong longTermLastReset = new AtomicLong(0);
|
private AtomicLong longTermLastReset = new AtomicLong(0);
|
||||||
|
|
||||||
public ArrivalRate(Timer timer) {
|
public ArrivalRate(ScheduledExecutorService arrivalRateExecutor) {
|
||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
shortTermLastReset.set(now);
|
shortTermLastReset.set(now);
|
||||||
mediumTermLastReset.set(now);
|
mediumTermLastReset.set(now);
|
||||||
longTermLastReset.set(now);
|
longTermLastReset.set(now);
|
||||||
|
|
||||||
// 2 minute
|
// 2 minute
|
||||||
timer.schedule(new TimerTask() {
|
arrivalRateExecutor.scheduleAtFixedRate(() -> {
|
||||||
|
resetShort();
|
||||||
@Override
|
}, 2, 2, TimeUnit.MINUTES);
|
||||||
public void run() {
|
|
||||||
resetShort();
|
|
||||||
}
|
|
||||||
}, 120000, 120000);
|
|
||||||
|
|
||||||
// 5 minute
|
// 5 minute
|
||||||
timer.schedule(new TimerTask() {
|
arrivalRateExecutor.scheduleAtFixedRate(() -> {
|
||||||
|
resetMedium();
|
||||||
@Override
|
}, 5, 5, TimeUnit.MINUTES);
|
||||||
public void run() {
|
|
||||||
resetMedium();
|
|
||||||
}
|
|
||||||
}, 300000, 300000);
|
|
||||||
|
|
||||||
// 15 minute
|
// 15 minute
|
||||||
timer.schedule(new TimerTask() {
|
arrivalRateExecutor.scheduleAtFixedRate(() -> {
|
||||||
|
resetLong();
|
||||||
@Override
|
}, 15, 15, TimeUnit.MINUTES);
|
||||||
public void run() {
|
|
||||||
resetLong();
|
|
||||||
}
|
|
||||||
}, 900000, 900000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void resetShort() {
|
private void resetShort() {
|
||||||
|
|||||||
@@ -1,17 +1,34 @@
|
|||||||
package timely.balancer;
|
package timely.balancer;
|
||||||
|
|
||||||
import java.io.File;
|
import static org.apache.accumulo.core.conf.ConfigurationTypeHelper.getTimeInMillis;
|
||||||
|
import static timely.Constants.NON_CACHED_METRICS;
|
||||||
|
import static timely.Constants.NON_CACHED_METRICS_LOCK_PATH;
|
||||||
|
import static timely.Constants.SERVICE_DISCOVERY_PATH;
|
||||||
|
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Date;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CountDownLatch;
|
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.curator.RetryPolicy;
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||||
|
import org.apache.curator.retry.RetryForever;
|
||||||
|
import org.apache.zookeeper.CreateMode;
|
||||||
|
import org.apache.zookeeper.data.Stat;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
|
||||||
|
import io.netty.bootstrap.AbstractBootstrap;
|
||||||
import io.netty.bootstrap.Bootstrap;
|
import io.netty.bootstrap.Bootstrap;
|
||||||
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
import io.netty.buffer.PooledByteBufAllocator;
|
import io.netty.buffer.PooledByteBufAllocator;
|
||||||
@@ -41,37 +58,31 @@ import io.netty.handler.codec.http.HttpResponseEncoder;
|
|||||||
import io.netty.handler.codec.http.HttpServerCodec;
|
import io.netty.handler.codec.http.HttpServerCodec;
|
||||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||||
import io.netty.handler.logging.LoggingHandler;
|
import io.netty.handler.logging.LoggingHandler;
|
||||||
import io.netty.handler.ssl.ClientAuth;
|
|
||||||
import io.netty.handler.ssl.OpenSslServerContext;
|
import io.netty.handler.ssl.OpenSslServerContext;
|
||||||
import io.netty.handler.ssl.OpenSslServerSessionContext;
|
import io.netty.handler.ssl.OpenSslServerSessionContext;
|
||||||
import io.netty.handler.ssl.SslContext;
|
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.handler.stream.ChunkedWriteHandler;
|
||||||
import io.netty.handler.timeout.IdleStateHandler;
|
import io.netty.handler.timeout.IdleStateHandler;
|
||||||
import io.netty.util.NettyRuntime;
|
import io.netty.util.NettyRuntime;
|
||||||
import io.netty.util.internal.SystemPropertyUtil;
|
import io.netty.util.internal.SystemPropertyUtil;
|
||||||
import org.slf4j.Logger;
|
import timely.auth.JWTTokenHandler;
|
||||||
import org.slf4j.LoggerFactory;
|
import timely.balancer.configuration.BalancerHttpProperties;
|
||||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
import org.springframework.context.ConfigurableApplicationContext;
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
import timely.balancer.configuration.BalancerWebsocketProperties;
|
||||||
import timely.balancer.configuration.ClientSsl;
|
|
||||||
import timely.balancer.configuration.SpringBootstrap;
|
|
||||||
import timely.balancer.connection.http.HttpClientPool;
|
import timely.balancer.connection.http.HttpClientPool;
|
||||||
import timely.balancer.connection.tcp.TcpClientPool;
|
import timely.balancer.connection.tcp.TcpClientPool;
|
||||||
import timely.balancer.connection.udp.UdpClientPool;
|
import timely.balancer.connection.udp.UdpClientPool;
|
||||||
import timely.balancer.connection.ws.WsClientPool;
|
import timely.balancer.connection.ws.WsClientPool;
|
||||||
import timely.balancer.healthcheck.HealthChecker;
|
|
||||||
import timely.balancer.netty.http.HttpRelayHandler;
|
import timely.balancer.netty.http.HttpRelayHandler;
|
||||||
import timely.balancer.netty.tcp.TcpRelayHandler;
|
import timely.balancer.netty.tcp.TcpRelayHandler;
|
||||||
import timely.balancer.netty.udp.UdpRelayHandler;
|
import timely.balancer.netty.udp.UdpRelayHandler;
|
||||||
import timely.balancer.netty.ws.WsRelayHandler;
|
import timely.balancer.netty.ws.WsRelayHandler;
|
||||||
import timely.balancer.resolver.BalancedMetricResolver;
|
import timely.common.component.AuthenticationService;
|
||||||
import timely.balancer.resolver.MetricResolver;
|
import timely.common.configuration.SecurityProperties;
|
||||||
import timely.client.http.HttpClient;
|
import timely.common.configuration.SslClientProperties;
|
||||||
import timely.configuration.ServerSsl;
|
import timely.common.configuration.SslServerProperties;
|
||||||
|
import timely.common.configuration.ZookeeperProperties;
|
||||||
import timely.netty.http.HttpStaticFileServerHandler;
|
import timely.netty.http.HttpStaticFileServerHandler;
|
||||||
import timely.netty.http.NonSslRedirectHandler;
|
import timely.netty.http.NonSslRedirectHandler;
|
||||||
import timely.netty.http.TimelyExceptionHandler;
|
import timely.netty.http.TimelyExceptionHandler;
|
||||||
@@ -81,7 +92,7 @@ import timely.netty.tcp.TcpDecoder;
|
|||||||
import timely.netty.tcp.TcpVersionHandler;
|
import timely.netty.tcp.TcpVersionHandler;
|
||||||
import timely.netty.udp.UdpDecoder;
|
import timely.netty.udp.UdpDecoder;
|
||||||
import timely.netty.udp.UdpPacketToByteBuf;
|
import timely.netty.udp.UdpPacketToByteBuf;
|
||||||
import timely.netty.websocket.WebSocketHttpCookieHandler;
|
import timely.netty.websocket.WebSocketFullRequestHandler;
|
||||||
import timely.netty.websocket.WebSocketRequestDecoder;
|
import timely.netty.websocket.WebSocketRequestDecoder;
|
||||||
import timely.netty.websocket.subscription.WSTimelyExceptionHandler;
|
import timely.netty.websocket.subscription.WSTimelyExceptionHandler;
|
||||||
|
|
||||||
@@ -91,17 +102,25 @@ public class Balancer {
|
|||||||
final public static String ASSIGNMENTS_LOCK_PATH = "/timely/balancer/assignments/lock";
|
final public static String ASSIGNMENTS_LOCK_PATH = "/timely/balancer/assignments/lock";
|
||||||
final public static String ASSIGNMENTS_LAST_UPDATED_PATH = "/timely/balancer/assignments/lastUpdated";
|
final public static String ASSIGNMENTS_LAST_UPDATED_PATH = "/timely/balancer/assignments/lastUpdated";
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(Balancer.class);
|
private static final Logger log = LoggerFactory.getLogger(Balancer.class);
|
||||||
private static final int EPOLL_MIN_MAJOR_VERSION = 2;
|
private static final String EPOLL_MIN_VERSION = "2.7";
|
||||||
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_NAME = "os.name";
|
||||||
private static final String OS_VERSION = "os.version";
|
private static final String OS_VERSION = "os.version";
|
||||||
private static final String WS_PATH = "/websocket";
|
private static final String WS_PATH = "/websocket";
|
||||||
protected static final CountDownLatch LATCH = new CountDownLatch(1);
|
private BalancerProperties balancerProperties;
|
||||||
static ConfigurableApplicationContext applicationContext;
|
private SecurityProperties securityProperties;
|
||||||
|
private SslServerProperties sslServerProperties;
|
||||||
private final BalancerConfiguration balancerConfig;
|
private SslClientProperties sslClientProperties;
|
||||||
|
private ZookeeperProperties zookeeperProperties;
|
||||||
|
private BalancerServerProperties balancerServerProperties;
|
||||||
|
private BalancerHttpProperties balancerHttpProperties;
|
||||||
|
private BalancerWebsocketProperties balancerWebsocketProperties;
|
||||||
|
private ApplicationContext applicationContext;
|
||||||
|
private AuthenticationService authenticationService;
|
||||||
|
private CuratorFramework curatorFramework;
|
||||||
|
private int quietPeriod;
|
||||||
|
private SslContext serverSslContext;
|
||||||
|
private SSLContext clientSSLContext;
|
||||||
private EventLoopGroup tcpWorkerGroup = null;
|
private EventLoopGroup tcpWorkerGroup = null;
|
||||||
private EventLoopGroup tcpBossGroup = null;
|
private EventLoopGroup tcpBossGroup = null;
|
||||||
private EventLoopGroup httpWorkerGroup = null;
|
private EventLoopGroup httpWorkerGroup = null;
|
||||||
@@ -115,53 +134,200 @@ public class Balancer {
|
|||||||
protected Channel httpChannelHandle = null;
|
protected Channel httpChannelHandle = null;
|
||||||
protected Channel wsChannelHandle = null;
|
protected Channel wsChannelHandle = null;
|
||||||
protected List<Channel> udpChannelHandleList = new ArrayList<>();
|
protected List<Channel> udpChannelHandleList = new ArrayList<>();
|
||||||
protected volatile boolean shutdown = false;
|
protected int DEFAULT_EVENT_LOOP_THREADS;
|
||||||
private static final int DEFAULT_EVENT_LOOP_THREADS;
|
|
||||||
|
|
||||||
static {
|
private String[] zkPaths = new String[] {LEADER_LATCH_PATH, ASSIGNMENTS_LAST_UPDATED_PATH, ASSIGNMENTS_LOCK_PATH, SERVICE_DISCOVERY_PATH,
|
||||||
DEFAULT_EVENT_LOOP_THREADS = Math.max(1,
|
NON_CACHED_METRICS, NON_CACHED_METRICS_LOCK_PATH};
|
||||||
SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
public Balancer(BalancerConfiguration balancerConf) throws Exception {
|
private static boolean useEpoll() {
|
||||||
this.balancerConfig = balancerConf;
|
final String osName = SystemPropertyUtil.get(OS_NAME).toLowerCase().trim();
|
||||||
}
|
final String osVersion = SystemPropertyUtil.get(OS_VERSION).toLowerCase();
|
||||||
|
// split at periods, keep the first two, join with a period
|
||||||
protected static ConfigurableApplicationContext initializeConfiguration(String[] args) {
|
final String majMinVers = StringUtils.join(Arrays.stream(osVersion.split("\\.")).limit(2).collect(Collectors.toList()), ".");
|
||||||
return new SpringApplicationBuilder(SpringBootstrap.class).web(false).run(args);
|
if (osName.startsWith("linux")) {
|
||||||
}
|
try {
|
||||||
|
Runtime.Version currentVersion = Runtime.Version.parse(majMinVers);
|
||||||
private void shutdownHook() {
|
Runtime.Version epollMinVersion = Runtime.Version.parse(EPOLL_MIN_VERSION);
|
||||||
|
return currentVersion.compareTo(epollMinVersion) > 0;
|
||||||
final Runnable shutdownRunner = () -> {
|
} catch (Exception e) {
|
||||||
if (!shutdown) {
|
log.error(e.getMessage(), e);
|
||||||
shutdown();
|
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
final Thread hook = new Thread(shutdownRunner, "shutdown-hook-thread");
|
return false;
|
||||||
Runtime.getRuntime().addShutdownHook(hook);
|
}
|
||||||
|
|
||||||
|
public Balancer(ApplicationContext applicationContext, SslContext serverSslContext, SSLContext clientSSLContext,
|
||||||
|
AuthenticationService authenticationService, MetricResolver metricResolver, BalancerProperties balancerProperties,
|
||||||
|
ZookeeperProperties zookeeperProperties, SecurityProperties securityProperties, SslServerProperties sslServerProperties,
|
||||||
|
SslClientProperties sslClientProperties, BalancerServerProperties balancerServerProperties, BalancerHttpProperties balancerHttpProperties,
|
||||||
|
BalancerWebsocketProperties balancerWebsocketProperties) {
|
||||||
|
this.serverSslContext = serverSslContext;
|
||||||
|
this.clientSSLContext = clientSSLContext;
|
||||||
|
this.quietPeriod = balancerServerProperties.getShutdownQuietPeriod();
|
||||||
|
this.applicationContext = applicationContext;
|
||||||
|
this.authenticationService = authenticationService;
|
||||||
|
this.metricResolver = metricResolver;
|
||||||
|
this.balancerProperties = balancerProperties;
|
||||||
|
this.zookeeperProperties = zookeeperProperties;
|
||||||
|
this.securityProperties = securityProperties;
|
||||||
|
this.sslServerProperties = sslServerProperties;
|
||||||
|
this.sslClientProperties = sslClientProperties;
|
||||||
|
this.balancerServerProperties = balancerServerProperties;
|
||||||
|
this.balancerHttpProperties = balancerHttpProperties;
|
||||||
|
this.balancerWebsocketProperties = balancerWebsocketProperties;
|
||||||
|
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
log.info("Starting {}", this.getClass().getSimpleName());
|
||||||
|
try {
|
||||||
|
// start curator framework
|
||||||
|
RetryPolicy retryPolicy = new RetryForever(1000);
|
||||||
|
int timeout = Long.valueOf(getTimeInMillis(zookeeperProperties.getTimeout())).intValue();
|
||||||
|
curatorFramework = CuratorFrameworkFactory.newClient(zookeeperProperties.getServers(), timeout, 10000, retryPolicy);
|
||||||
|
curatorFramework.start();
|
||||||
|
ensureZkPaths(curatorFramework, zkPaths);
|
||||||
|
|
||||||
|
JWTTokenHandler.init(securityProperties, null);
|
||||||
|
final boolean useEpoll = useEpoll();
|
||||||
|
Class<? extends ServerSocketChannel> channelClass;
|
||||||
|
Class<? extends Channel> datagramChannelClass;
|
||||||
|
if (useEpoll) {
|
||||||
|
tcpWorkerGroup = new EpollEventLoopGroup();
|
||||||
|
tcpBossGroup = new EpollEventLoopGroup();
|
||||||
|
httpWorkerGroup = new EpollEventLoopGroup();
|
||||||
|
httpBossGroup = new EpollEventLoopGroup();
|
||||||
|
wsWorkerGroup = new EpollEventLoopGroup();
|
||||||
|
wsBossGroup = new EpollEventLoopGroup();
|
||||||
|
udpWorkerGroup = new EpollEventLoopGroup();
|
||||||
|
udpBossGroup = new EpollEventLoopGroup();
|
||||||
|
channelClass = EpollServerSocketChannel.class;
|
||||||
|
datagramChannelClass = EpollDatagramChannel.class;
|
||||||
|
} else {
|
||||||
|
tcpWorkerGroup = new NioEventLoopGroup();
|
||||||
|
tcpBossGroup = new NioEventLoopGroup();
|
||||||
|
httpWorkerGroup = new NioEventLoopGroup();
|
||||||
|
httpBossGroup = new NioEventLoopGroup();
|
||||||
|
wsWorkerGroup = new NioEventLoopGroup();
|
||||||
|
wsBossGroup = new NioEventLoopGroup();
|
||||||
|
udpWorkerGroup = new NioEventLoopGroup();
|
||||||
|
udpBossGroup = new NioEventLoopGroup();
|
||||||
|
channelClass = NioServerSocketChannel.class;
|
||||||
|
datagramChannelClass = NioDatagramChannel.class;
|
||||||
|
}
|
||||||
|
log.info("Using channel class {}", channelClass.getSimpleName());
|
||||||
|
|
||||||
|
List<TcpClientPool> tcpClientPools = new ArrayList<>();
|
||||||
|
for (int x = 0; x < balancerServerProperties.getNumTcpPools(); x++) {
|
||||||
|
tcpClientPools.add(new TcpClientPool(balancerServerProperties));
|
||||||
|
}
|
||||||
|
|
||||||
|
final ServerBootstrap tcpServer = new ServerBootstrap();
|
||||||
|
tcpServer.group(tcpBossGroup, tcpWorkerGroup);
|
||||||
|
tcpServer.channel(channelClass);
|
||||||
|
tcpServer.handler(new LoggingHandler());
|
||||||
|
tcpServer.childHandler(setupTcpChannel(metricResolver, tcpClientPools));
|
||||||
|
tcpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||||
|
tcpServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||||
|
tcpServer.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||||
|
final int tcpPort = balancerServerProperties.getTcpPort();
|
||||||
|
final String tcpIp = balancerServerProperties.getIp();
|
||||||
|
tcpChannelHandle = bind(tcpServer, tcpIp, tcpPort);
|
||||||
|
final String tcpAddress = ((InetSocketAddress) tcpChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||||
|
|
||||||
|
final int httpPort = balancerHttpProperties.getPort();
|
||||||
|
final String httpIp = balancerHttpProperties.getIp();
|
||||||
|
|
||||||
|
if (serverSslContext instanceof OpenSslServerContext) {
|
||||||
|
OpenSslServerContext openssl = (OpenSslServerContext) serverSslContext;
|
||||||
|
String application = "Timely_" + httpPort;
|
||||||
|
OpenSslServerSessionContext opensslCtx = openssl.sessionContext();
|
||||||
|
opensslCtx.setSessionCacheEnabled(true);
|
||||||
|
opensslCtx.setSessionCacheSize(128);
|
||||||
|
opensslCtx.setSessionIdContext(application.getBytes(StandardCharsets.UTF_8));
|
||||||
|
opensslCtx.setSessionTimeout(securityProperties.getSessionMaxAge());
|
||||||
|
}
|
||||||
|
final ServerBootstrap httpServer = new ServerBootstrap();
|
||||||
|
httpServer.group(httpBossGroup, httpWorkerGroup);
|
||||||
|
httpServer.channel(channelClass);
|
||||||
|
httpServer.handler(new LoggingHandler());
|
||||||
|
HttpClientPool httpClientPool = new HttpClientPool(balancerHttpProperties, clientSSLContext, sslClientProperties);
|
||||||
|
httpServer.childHandler(setupHttpChannel(balancerHttpProperties, sslServerProperties, serverSslContext, metricResolver, httpClientPool));
|
||||||
|
httpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||||
|
httpServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||||
|
httpServer.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||||
|
httpChannelHandle = bind(httpServer, httpIp, httpPort);
|
||||||
|
final String httpAddress = ((InetSocketAddress) httpChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||||
|
|
||||||
|
final int wsPort = balancerWebsocketProperties.getPort();
|
||||||
|
final String wsIp = balancerWebsocketProperties.getIp();
|
||||||
|
final ServerBootstrap wsServer = new ServerBootstrap();
|
||||||
|
wsServer.group(wsBossGroup, wsWorkerGroup);
|
||||||
|
wsServer.channel(channelClass);
|
||||||
|
wsServer.handler(new LoggingHandler());
|
||||||
|
WsClientPool wsClientPool = new WsClientPool(balancerProperties, balancerWebsocketProperties, sslClientProperties, clientSSLContext);
|
||||||
|
wsServer.childHandler(setupWSChannel(balancerWebsocketProperties, securityProperties, serverSslContext, metricResolver, wsClientPool));
|
||||||
|
wsServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||||
|
wsServer.option(ChannelOption.SO_BACKLOG, 128);
|
||||||
|
wsServer.childOption(ChannelOption.SO_KEEPALIVE, true);
|
||||||
|
wsChannelHandle = bind(wsServer, wsIp, wsPort);
|
||||||
|
final String wsAddress = ((InetSocketAddress) wsChannelHandle.localAddress()).getAddress().getHostAddress();
|
||||||
|
|
||||||
|
final int udpPort = balancerServerProperties.getUdpPort();
|
||||||
|
final String udpIp = balancerServerProperties.getIp();
|
||||||
|
UdpClientPool udpClientPool = new UdpClientPool(balancerServerProperties);
|
||||||
|
for (int n = 0; n < DEFAULT_EVENT_LOOP_THREADS; n++) {
|
||||||
|
final Bootstrap udpServer = new Bootstrap();
|
||||||
|
udpServer.group(udpBossGroup);
|
||||||
|
udpServer.channel(datagramChannelClass);
|
||||||
|
udpServer.handler(setupUdpChannel(metricResolver, udpClientPool));
|
||||||
|
udpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
||||||
|
udpServer.option(EpollChannelOption.SO_REUSEADDR, true);
|
||||||
|
udpServer.option(EpollChannelOption.SO_REUSEPORT, true);
|
||||||
|
udpChannelHandleList.add(bind(udpServer, udpIp, udpPort));
|
||||||
|
}
|
||||||
|
log.info("Balancer started. Listening on {}:{} for TCP traffic, {}:{} for HTTP traffic, {}:{} for WebSocket traffic, and {}:{} for UDP traffic",
|
||||||
|
tcpAddress, tcpPort, httpAddress, httpPort, wsAddress, wsPort, wsAddress, udpPort);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
SpringApplication.exit(applicationContext, () -> 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Channel bind(AbstractBootstrap server, String ip, int port) {
|
||||||
|
Channel channel = null;
|
||||||
|
try {
|
||||||
|
channel = server.bind(ip, port).sync().channel();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.error("Failed to bind to {}:{} -- {}", ip, port, e.getMessage());
|
||||||
|
}
|
||||||
|
if (channel == null) {
|
||||||
|
throw new IllegalStateException("Failed to bind to port:" + ip + ":" + port);
|
||||||
|
}
|
||||||
|
return channel;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
List<ChannelFuture> channelFutures = new ArrayList<>();
|
List<ChannelFuture> channelFutures = new ArrayList<>();
|
||||||
|
|
||||||
if (tcpChannelHandle != null) {
|
if (tcpChannelHandle != null) {
|
||||||
LOG.info("Closing tcpChannelHandle");
|
log.info("Closing tcpChannelHandle");
|
||||||
channelFutures.add(tcpChannelHandle.close());
|
channelFutures.add(tcpChannelHandle.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (httpChannelHandle != null) {
|
if (httpChannelHandle != null) {
|
||||||
LOG.info("Closing httpChannelHandle");
|
log.info("Closing httpChannelHandle");
|
||||||
channelFutures.add(httpChannelHandle.close());
|
channelFutures.add(httpChannelHandle.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wsChannelHandle != null) {
|
if (wsChannelHandle != null) {
|
||||||
LOG.info("Closing wsChannelHandle");
|
log.info("Closing wsChannelHandle");
|
||||||
channelFutures.add(wsChannelHandle.close());
|
channelFutures.add(wsChannelHandle.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int udpChannel = 1;
|
||||||
for (Channel c : udpChannelHandleList) {
|
for (Channel c : udpChannelHandleList) {
|
||||||
LOG.info("Closing udpChannelHandle");
|
log.info("Closing udpChannelHandle #" + udpChannel++);
|
||||||
channelFutures.add(c.close());
|
channelFutures.add(c.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,51 +336,49 @@ public class Balancer {
|
|||||||
try {
|
try {
|
||||||
f.get();
|
f.get();
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
LOG.error("Error while shutting down channel: {}", f.channel().config());
|
log.error("Channel:" + f.channel().config() + " -> " + e.getMessage(), e);
|
||||||
LOG.error("{}", e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Integer quietPeriod = balancerConfig.getServer().getShutdownQuietPeriod();
|
|
||||||
List<Future<?>> groupFutures = new ArrayList<>();
|
List<Future<?>> groupFutures = new ArrayList<>();
|
||||||
|
|
||||||
if (tcpBossGroup != null) {
|
if (tcpBossGroup != null) {
|
||||||
LOG.info("Shutting down tcpBossGroup");
|
log.info("Shutting down tcpBossGroup");
|
||||||
groupFutures.add(tcpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(tcpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tcpWorkerGroup != null) {
|
if (tcpWorkerGroup != null) {
|
||||||
LOG.info("Shutting down tcpWorkerGroup");
|
log.info("Shutting down tcpWorkerGroup");
|
||||||
groupFutures.add(tcpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(tcpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (httpBossGroup != null) {
|
if (httpBossGroup != null) {
|
||||||
LOG.info("Shutting down httpBossGroup");
|
log.info("Shutting down httpBossGroup");
|
||||||
groupFutures.add(httpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(httpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (httpWorkerGroup != null) {
|
if (httpWorkerGroup != null) {
|
||||||
LOG.info("Shutting down httpWorkerGroup");
|
log.info("Shutting down httpWorkerGroup");
|
||||||
groupFutures.add(httpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(httpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wsBossGroup != null) {
|
if (wsBossGroup != null) {
|
||||||
LOG.info("Shutting down wsBossGroup");
|
log.info("Shutting down wsBossGroup");
|
||||||
groupFutures.add(wsBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(wsBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wsWorkerGroup != null) {
|
if (wsWorkerGroup != null) {
|
||||||
LOG.info("Shutting down wsWorkerGroup");
|
log.info("Shutting down wsWorkerGroup");
|
||||||
groupFutures.add(wsWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(wsWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (udpBossGroup != null) {
|
if (udpBossGroup != null) {
|
||||||
LOG.info("Shutting down udpBossGroup");
|
log.info("Shutting down udpBossGroup");
|
||||||
groupFutures.add(udpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(udpBossGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (udpWorkerGroup != null) {
|
if (udpWorkerGroup != null) {
|
||||||
LOG.info("Shutting down udpWorkerGroup");
|
log.info("Shutting down udpWorkerGroup");
|
||||||
groupFutures.add(udpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
groupFutures.add(udpWorkerGroup.shutdownGracefully(quietPeriod, 10, TimeUnit.SECONDS));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,261 +386,55 @@ public class Balancer {
|
|||||||
try {
|
try {
|
||||||
f.get();
|
f.get();
|
||||||
} catch (final Exception e) {
|
} catch (final Exception e) {
|
||||||
LOG.error("Error while shutting down group: {}", f.toString());
|
log.error("Group:" + f.toString() + " -> " + e.getMessage(), e);
|
||||||
LOG.error("{}", e.getMessage());
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
LOG.info("Closing WebSocketRequestDecoder");
|
log.info("Closing WebSocketRequestDecoder");
|
||||||
WebSocketRequestDecoder.close();
|
WebSocketRequestDecoder.close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Error closing WebSocketRequestDecoder during shutdown", e);
|
log.error("Error closing WebSocketRequestDecoder during shutdown", e);
|
||||||
}
|
}
|
||||||
|
log.info("{} shut down.", this.getClass().getSimpleName());
|
||||||
if (applicationContext != null) {
|
|
||||||
LOG.info("Closing applicationContext");
|
|
||||||
applicationContext.close();
|
|
||||||
}
|
|
||||||
this.shutdown = true;
|
|
||||||
LOG.info("Server shut down.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean useEpoll() {
|
private void ensureZkPaths(CuratorFramework curatorFramework, String[] paths) {
|
||||||
|
for (String s : paths) {
|
||||||
// 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(BalancerConfiguration 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(BalancerConfiguration 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 {
|
|
||||||
|
|
||||||
final boolean useEpoll = useEpoll();
|
|
||||||
Class<? extends ServerSocketChannel> channelClass;
|
|
||||||
Class<? extends Channel> datagramChannelClass;
|
|
||||||
if (useEpoll) {
|
|
||||||
tcpWorkerGroup = new EpollEventLoopGroup();
|
|
||||||
tcpBossGroup = new EpollEventLoopGroup();
|
|
||||||
httpWorkerGroup = new EpollEventLoopGroup();
|
|
||||||
httpBossGroup = new EpollEventLoopGroup();
|
|
||||||
wsWorkerGroup = new EpollEventLoopGroup();
|
|
||||||
wsBossGroup = new EpollEventLoopGroup();
|
|
||||||
udpWorkerGroup = new EpollEventLoopGroup();
|
|
||||||
udpBossGroup = new EpollEventLoopGroup();
|
|
||||||
channelClass = EpollServerSocketChannel.class;
|
|
||||||
datagramChannelClass = EpollDatagramChannel.class;
|
|
||||||
} else {
|
|
||||||
tcpWorkerGroup = new NioEventLoopGroup();
|
|
||||||
tcpBossGroup = new NioEventLoopGroup();
|
|
||||||
httpWorkerGroup = new NioEventLoopGroup();
|
|
||||||
httpBossGroup = new NioEventLoopGroup();
|
|
||||||
wsWorkerGroup = new NioEventLoopGroup();
|
|
||||||
wsBossGroup = new NioEventLoopGroup();
|
|
||||||
udpWorkerGroup = new NioEventLoopGroup();
|
|
||||||
udpBossGroup = new NioEventLoopGroup();
|
|
||||||
channelClass = NioServerSocketChannel.class;
|
|
||||||
datagramChannelClass = NioDatagramChannel.class;
|
|
||||||
}
|
|
||||||
LOG.info("Using channel class {}", channelClass.getSimpleName());
|
|
||||||
|
|
||||||
List<TcpClientPool> tcpClientPools = new ArrayList<>();
|
|
||||||
for (int x = 0; x < balancerConfig.getServer().getNumTcpPools(); x++) {
|
|
||||||
tcpClientPools.add(new TcpClientPool(this.balancerConfig));
|
|
||||||
}
|
|
||||||
HealthChecker healthChecker = new HealthChecker(this.balancerConfig, tcpClientPools.get(0));
|
|
||||||
this.metricResolver = new BalancedMetricResolver(this.balancerConfig, healthChecker);
|
|
||||||
|
|
||||||
final ServerBootstrap tcpServer = new ServerBootstrap();
|
|
||||||
tcpServer.group(tcpBossGroup, tcpWorkerGroup);
|
|
||||||
tcpServer.channel(channelClass);
|
|
||||||
tcpServer.handler(new LoggingHandler());
|
|
||||||
tcpServer.childHandler(setupTcpChannel(metricResolver, tcpClientPools));
|
|
||||||
tcpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
|
||||||
tcpServer.option(ChannelOption.SO_BACKLOG, 128);
|
|
||||||
tcpServer.option(ChannelOption.SO_KEEPALIVE, true);
|
|
||||||
final int tcpPort = balancerConfig.getServer().getTcpPort();
|
|
||||||
final String tcpIp = balancerConfig.getServer().getIp();
|
|
||||||
tcpChannelHandle = tcpServer.bind(tcpIp, tcpPort).sync().channel();
|
|
||||||
final String tcpAddress = ((InetSocketAddress) tcpChannelHandle.localAddress()).getAddress().getHostAddress();
|
|
||||||
|
|
||||||
final int httpPort = balancerConfig.getHttp().getPort();
|
|
||||||
final String httpIp = balancerConfig.getHttp().getIp();
|
|
||||||
SslContext sslCtx = createSSLContext(balancerConfig);
|
|
||||||
if (sslCtx instanceof OpenSslServerContext) {
|
|
||||||
OpenSslServerContext openssl = (OpenSslServerContext) sslCtx;
|
|
||||||
String application = "Timely_" + httpPort;
|
|
||||||
OpenSslServerSessionContext opensslCtx = openssl.sessionContext();
|
|
||||||
opensslCtx.setSessionCacheEnabled(true);
|
|
||||||
opensslCtx.setSessionCacheSize(128);
|
|
||||||
opensslCtx.setSessionIdContext(application.getBytes(StandardCharsets.UTF_8));
|
|
||||||
opensslCtx.setSessionTimeout(balancerConfig.getSecurity().getSessionMaxAge());
|
|
||||||
}
|
|
||||||
SSLContext clientSSLContext = createSSLClientContext(balancerConfig);
|
|
||||||
final ServerBootstrap httpServer = new ServerBootstrap();
|
|
||||||
httpServer.group(httpBossGroup, httpWorkerGroup);
|
|
||||||
httpServer.channel(channelClass);
|
|
||||||
httpServer.handler(new LoggingHandler());
|
|
||||||
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);
|
|
||||||
httpServer.option(ChannelOption.SO_KEEPALIVE, true);
|
|
||||||
httpChannelHandle = httpServer.bind(httpIp, httpPort).sync().channel();
|
|
||||||
final String httpAddress = ((InetSocketAddress) httpChannelHandle.localAddress()).getAddress().getHostAddress();
|
|
||||||
|
|
||||||
final int wsPort = balancerConfig.getWebsocket().getPort();
|
|
||||||
final String wsIp = balancerConfig.getWebsocket().getIp();
|
|
||||||
final ServerBootstrap wsServer = new ServerBootstrap();
|
|
||||||
wsServer.group(wsBossGroup, wsWorkerGroup);
|
|
||||||
wsServer.channel(channelClass);
|
|
||||||
wsServer.handler(new LoggingHandler());
|
|
||||||
WsClientPool wsClientPool = new WsClientPool(balancerConfig, clientSSLContext);
|
|
||||||
wsServer.childHandler(setupWSChannel(balancerConfig, sslCtx, metricResolver, wsClientPool));
|
|
||||||
wsServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
|
||||||
wsServer.option(ChannelOption.SO_BACKLOG, 128);
|
|
||||||
wsServer.option(ChannelOption.SO_KEEPALIVE, true);
|
|
||||||
/* Not sure if next three lines are necessary */
|
|
||||||
wsServer.option(ChannelOption.SO_SNDBUF, 1048576);
|
|
||||||
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();
|
|
||||||
|
|
||||||
final int udpPort = balancerConfig.getServer().getUdpPort();
|
|
||||||
final String udpIp = balancerConfig.getServer().getIp();
|
|
||||||
UdpClientPool udpClientPool = new UdpClientPool(balancerConfig);
|
|
||||||
for (int n = 1; n < DEFAULT_EVENT_LOOP_THREADS; n++) {
|
|
||||||
final Bootstrap udpServer = new Bootstrap();
|
|
||||||
udpServer.group(udpBossGroup);
|
|
||||||
udpServer.channel(datagramChannelClass);
|
|
||||||
udpServer.handler(setupUdpChannel(metricResolver, udpClientPool));
|
|
||||||
udpServer.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
|
|
||||||
udpServer.option(EpollChannelOption.SO_REUSEADDR, true);
|
|
||||||
udpServer.option(EpollChannelOption.SO_REUSEPORT, true);
|
|
||||||
udpChannelHandleList.add(udpServer.bind(udpIp, udpPort).sync().channel());
|
|
||||||
}
|
|
||||||
shutdownHook();
|
|
||||||
LOG.info(
|
|
||||||
"Server started. Listening on {}:{} for TCP traffic, {}:{} for HTTP traffic, {}:{} for WebSocket traffic, and {}:{} for UDP traffic",
|
|
||||||
tcpAddress, tcpPort, httpAddress, httpPort, wsAddress, wsPort, wsAddress, udpPort);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
|
||||||
|
|
||||||
Balancer.applicationContext = Balancer.initializeConfiguration(args);
|
|
||||||
BalancerConfiguration balancerConf = applicationContext.getBean(BalancerConfiguration.class);
|
|
||||||
|
|
||||||
Balancer b = new Balancer(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 {
|
try {
|
||||||
b.shutdown();
|
Stat stat = curatorFramework.checkExists().forPath(s);
|
||||||
|
if (stat == null) {
|
||||||
|
curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(s);
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.exit(1);
|
log.info(e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ChannelHandler setupHttpChannel(BalancerConfiguration balancerConfig, SslContext sslCtx,
|
protected ChannelHandler setupHttpChannel(BalancerHttpProperties balancerHttpProperties, SslServerProperties sslServerProperties, SslContext sslCtx,
|
||||||
MetricResolver metricResolver, HttpClientPool httpClientPool) {
|
MetricResolver metricResolver, HttpClientPool httpClientPool) {
|
||||||
|
|
||||||
return new ChannelInitializer<SocketChannel>() {
|
return new ChannelInitializer<SocketChannel>() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void initChannel(SocketChannel ch) throws Exception {
|
protected void initChannel(SocketChannel ch) {
|
||||||
|
|
||||||
ch.pipeline().addLast("ssl", new NonSslRedirectHandler(balancerConfig.getHttp(), sslCtx));
|
ch.pipeline().addLast("ssl", new NonSslRedirectHandler(balancerHttpProperties, sslCtx));
|
||||||
ch.pipeline().addLast("encoder", new HttpResponseEncoder());
|
ch.pipeline().addLast("encoder", new HttpResponseEncoder());
|
||||||
ch.pipeline().addLast("decoder", new HttpRequestDecoder());
|
ch.pipeline().addLast("decoder", new HttpRequestDecoder(4096, 32768, 8192, true, 128));
|
||||||
ch.pipeline().addLast("compressor", new HttpContentCompressor());
|
ch.pipeline().addLast("compressor", new HttpContentCompressor());
|
||||||
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
|
ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
|
||||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||||
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
|
ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
|
||||||
ch.pipeline().addLast("queryDecoder", new timely.netty.http.HttpRequestDecoder(
|
ch.pipeline().addLast("queryDecoder",
|
||||||
balancerConfig.getSecurity(), balancerConfig.getHttp()));
|
new timely.netty.http.HttpRequestDecoder(authenticationService, securityProperties, balancerHttpProperties));
|
||||||
ch.pipeline().addLast("fileServer", new HttpStaticFileServerHandler());
|
ch.pipeline().addLast("fileServer",
|
||||||
ch.pipeline().addLast("login",
|
new HttpStaticFileServerHandler().setIgnoreSslHandshakeErrors(sslServerProperties.isIgnoreSslHandshakeErrors()));
|
||||||
new X509LoginRequestHandler(balancerConfig.getSecurity(), balancerConfig.getHttp()));
|
ch.pipeline().addLast("login", new X509LoginRequestHandler(authenticationService, securityProperties, balancerHttpProperties));
|
||||||
ch.pipeline().addLast("httpRelay",
|
ch.pipeline().addLast("httpRelay", new HttpRelayHandler(metricResolver, httpClientPool));
|
||||||
new HttpRelayHandler(balancerConfig, metricResolver, httpClientPool));
|
ch.pipeline().addLast("error", new TimelyExceptionHandler().setIgnoreSslHandshakeErrors(sslServerProperties.isIgnoreSslHandshakeErrors()));
|
||||||
ch.pipeline().addLast("error", new TimelyExceptionHandler());
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -489,7 +447,7 @@ public class Balancer {
|
|||||||
ch.pipeline().addLast("logger", new LoggingHandler());
|
ch.pipeline().addLast("logger", new LoggingHandler());
|
||||||
ch.pipeline().addLast("packetDecoder", new UdpPacketToByteBuf());
|
ch.pipeline().addLast("packetDecoder", new UdpPacketToByteBuf());
|
||||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||||
ch.pipeline().addLast("putDecoder", new UdpDecoder());
|
ch.pipeline().addLast("putDecoder", new UdpDecoder());
|
||||||
ch.pipeline().addLast("udpRelayHandler", new UdpRelayHandler(metricResolver, udpClientPool));
|
ch.pipeline().addLast("udpRelayHandler", new UdpRelayHandler(metricResolver, udpClientPool));
|
||||||
}
|
}
|
||||||
@@ -502,7 +460,7 @@ public class Balancer {
|
|||||||
@Override
|
@Override
|
||||||
protected void initChannel(SocketChannel ch) throws Exception {
|
protected void initChannel(SocketChannel ch) throws Exception {
|
||||||
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
ch.pipeline().addLast("buffer", new MetricsBufferDecoder());
|
||||||
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(8192, true, Delimiters.lineDelimiter()));
|
ch.pipeline().addLast("frame", new DelimiterBasedFrameDecoder(65536, true, Delimiters.lineDelimiter()));
|
||||||
ch.pipeline().addLast("putDecoder", new TcpDecoder());
|
ch.pipeline().addLast("putDecoder", new TcpDecoder());
|
||||||
ch.pipeline().addLast("tcpRelayHandler", new TcpRelayHandler(metricResolver, tcpClientPools));
|
ch.pipeline().addLast("tcpRelayHandler", new TcpRelayHandler(metricResolver, tcpClientPools));
|
||||||
ch.pipeline().addLast("versionHandler", new TcpVersionHandler());
|
ch.pipeline().addLast("versionHandler", new TcpVersionHandler());
|
||||||
@@ -510,23 +468,21 @@ public class Balancer {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ChannelHandler setupWSChannel(BalancerConfiguration balancerConfig, SslContext sslCtx,
|
protected ChannelHandler setupWSChannel(BalancerWebsocketProperties balancerWebsocketProperties, SecurityProperties securityProperties, SslContext sslCtx,
|
||||||
MetricResolver metricResolver, WsClientPool wsClientPool) {
|
MetricResolver metricResolver, WsClientPool wsClientPool) {
|
||||||
return new ChannelInitializer<SocketChannel>() {
|
return new ChannelInitializer<SocketChannel>() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void initChannel(SocketChannel ch) throws Exception {
|
protected void initChannel(SocketChannel ch) throws Exception {
|
||||||
ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
|
ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
|
||||||
ch.pipeline().addLast("httpServer", new HttpServerCodec());
|
ch.pipeline().addLast("httpServer", new HttpServerCodec());
|
||||||
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
|
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
|
||||||
ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(balancerConfig.getSecurity()));
|
ch.pipeline().addLast("sessionExtractor", new WebSocketFullRequestHandler(authenticationService));
|
||||||
|
|
||||||
ch.pipeline().addLast("idle-handler",
|
ch.pipeline().addLast("idle-handler", new IdleStateHandler(balancerWebsocketProperties.getTimeout(), 0, 0));
|
||||||
new IdleStateHandler(balancerConfig.getWebsocket().getTimeout(), 0, 0));
|
ch.pipeline().addLast("ws-protocol", new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, false, true));
|
||||||
ch.pipeline().addLast("ws-protocol",
|
ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(authenticationService, securityProperties));
|
||||||
new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, true));
|
ch.pipeline().addLast("httpRelay", new WsRelayHandler(balancerWebsocketProperties, metricResolver, wsClientPool));
|
||||||
ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(balancerConfig.getSecurity()));
|
|
||||||
ch.pipeline().addLast("httpRelay", new WsRelayHandler(balancerConfig, metricResolver, wsClientPool));
|
|
||||||
ch.pipeline().addLast("error", new WSTimelyExceptionHandler());
|
ch.pipeline().addLast("error", new WSTimelyExceptionHandler());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package timely.balancer;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
import timely.balancer.connection.tcp.TcpClientPool;
|
||||||
|
import timely.balancer.healthcheck.TCPServerHealthCheck;
|
||||||
|
|
||||||
|
public class HealthChecker {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(HealthChecker.class);
|
||||||
|
private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
|
||||||
|
private TCPServerHealthCheck tcpServerHealthCheck;
|
||||||
|
private BalancerProperties balancerProperties;
|
||||||
|
private BalancerServerProperties balancerServerProperties;
|
||||||
|
protected List<TimelyBalancedHost> timelyHosts = new ArrayList<>();
|
||||||
|
|
||||||
|
public HealthChecker(BalancerProperties balancerProperties, BalancerServerProperties balancerServerProperties) {
|
||||||
|
this.balancerProperties = balancerProperties;
|
||||||
|
this.balancerServerProperties = balancerServerProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
TcpClientPool tcpClientPool = new TcpClientPool(balancerServerProperties);
|
||||||
|
this.tcpServerHealthCheck = new TCPServerHealthCheck(tcpClientPool);
|
||||||
|
this.executorService.scheduleAtFixedRate(() -> {
|
||||||
|
synchronized (timelyHosts) {
|
||||||
|
for (TimelyBalancedHost h : timelyHosts) {
|
||||||
|
try {
|
||||||
|
if (tcpServerHealthCheck.isServerHealthy(h)) {
|
||||||
|
h.reportSuccess();
|
||||||
|
} else {
|
||||||
|
h.reportFailure();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
h.reportFailure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 0, balancerProperties.getCheckServerHealthInterval(), TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
this.executorService.shutdown();
|
||||||
|
try {
|
||||||
|
this.executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (!this.executorService.isTerminated()) {
|
||||||
|
this.executorService.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimelyHosts(List<TimelyBalancedHost> timelyHosts) {
|
||||||
|
synchronized (timelyHosts) {
|
||||||
|
this.timelyHosts.clear();
|
||||||
|
this.timelyHosts.addAll(timelyHosts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
|||||||
|
package timely.balancer;
|
||||||
|
|
||||||
|
import org.springframework.boot.WebApplicationType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
|
||||||
|
@SpringBootApplication(scanBasePackages = {"timely.balancer", "timely.common"}, exclude = {ErrorMvcAutoConfiguration.class})
|
||||||
|
public class TimelyBalancer {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new SpringApplicationBuilder(TimelyBalancer.class).web(WebApplicationType.NONE).run(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,121 +1,58 @@
|
|||||||
package timely.balancer.configuration;
|
package timely.balancer.configuration;
|
||||||
|
|
||||||
import javax.validation.Valid;
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import timely.configuration.Cache;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
@Component
|
import io.netty.handler.ssl.SslContext;
|
||||||
@ConfigurationProperties(prefix = "timely-balancer")
|
import timely.balancer.Balancer;
|
||||||
|
import timely.balancer.HealthChecker;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
|
import timely.common.component.AuthenticationService;
|
||||||
|
import timely.common.configuration.CacheProperties;
|
||||||
|
import timely.common.configuration.SecurityProperties;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
import timely.common.configuration.SslServerProperties;
|
||||||
|
import timely.common.configuration.ZookeeperProperties;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties({BalancerProperties.class, BalancerServerProperties.class, BalancerWebsocketProperties.class, BalancerHttpProperties.class})
|
||||||
public class BalancerConfiguration {
|
public class BalancerConfiguration {
|
||||||
|
|
||||||
@Valid
|
@Bean
|
||||||
@NestedConfigurationProperty
|
@ConditionalOnMissingBean
|
||||||
private BalancerServer server = new BalancerServer();
|
public Balancer balancer(ApplicationContext applicationContext, @Qualifier("nettySslContext") SslContext serverSslContext,
|
||||||
|
@Qualifier("outboundJDKSslContext") SSLContext clientSSLContext, AuthenticationService authenticationService, MetricResolver metricResolver,
|
||||||
@Valid
|
BalancerProperties balancerProperties, ZookeeperProperties zookeeperProperties, SecurityProperties securityProperties,
|
||||||
@NestedConfigurationProperty
|
SslServerProperties sslServerProperties, SslClientProperties sslClientProperties, BalancerServerProperties balancerServerProperties,
|
||||||
private BalancerHttp http = new BalancerHttp();
|
BalancerHttpProperties balancerHttpProperties, BalancerWebsocketProperties balancerWebsocketProperties) {
|
||||||
|
Balancer balancer = new Balancer(applicationContext, serverSslContext, clientSSLContext, authenticationService, metricResolver, balancerProperties,
|
||||||
@Valid
|
zookeeperProperties, securityProperties, sslServerProperties, sslClientProperties, balancerServerProperties, balancerHttpProperties,
|
||||||
@NestedConfigurationProperty
|
balancerWebsocketProperties);
|
||||||
private BalancerWebsocket websocket = new BalancerWebsocket();
|
balancer.start();
|
||||||
|
return balancer;
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private ZooKeeper zooKeeper = new ZooKeeper();
|
|
||||||
|
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private BalancerSecurity security = new BalancerSecurity();
|
|
||||||
|
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private Cache cache = new Cache();
|
|
||||||
|
|
||||||
private boolean loginRequired = false;
|
|
||||||
|
|
||||||
private String assignmentFile;
|
|
||||||
|
|
||||||
private Double controlBandPercentage = 0.05;
|
|
||||||
|
|
||||||
private long checkServerHealthInterval = 10000;
|
|
||||||
|
|
||||||
private int serverFailuresBeforeDown = 3;
|
|
||||||
|
|
||||||
private int serverSuccessesBeforeUp = 3;
|
|
||||||
|
|
||||||
public ZooKeeper getZooKeeper() {
|
|
||||||
return zooKeeper;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLoginRequired(boolean loginRequired) {
|
@Bean
|
||||||
this.loginRequired = loginRequired;
|
@ConditionalOnMissingBean
|
||||||
|
public HealthChecker healthChecker(BalancerProperties balancerProperties, BalancerServerProperties balancerServerProperties) {
|
||||||
|
HealthChecker healthChecker = new HealthChecker(balancerProperties, balancerServerProperties);
|
||||||
|
healthChecker.start();
|
||||||
|
return healthChecker;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isLoginRequired() {
|
@Bean
|
||||||
return loginRequired;
|
@ConditionalOnMissingBean
|
||||||
}
|
public MetricResolver metricResolver(CuratorFramework curatorFramework, BalancerProperties balancerProperties, CacheProperties cacheProperties,
|
||||||
|
HealthChecker healthChecker) {
|
||||||
public String getAssignmentFile() {
|
MetricResolver metricResolver = new MetricResolver(curatorFramework, balancerProperties, cacheProperties, healthChecker);
|
||||||
return assignmentFile;
|
metricResolver.start();
|
||||||
}
|
return metricResolver;
|
||||||
|
|
||||||
public void setAssignmentFile(String assignmentFile) {
|
|
||||||
this.assignmentFile = assignmentFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setControlBandPercentage(Double controlBandPercentage) {
|
|
||||||
this.controlBandPercentage = controlBandPercentage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Double getControlBandPercentage() {
|
|
||||||
return controlBandPercentage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BalancerSecurity getSecurity() {
|
|
||||||
return security;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BalancerServer getServer() {
|
|
||||||
return server;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BalancerHttp getHttp() {
|
|
||||||
return http;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BalancerWebsocket getWebsocket() {
|
|
||||||
return websocket;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Cache getCache() {
|
|
||||||
return cache;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCheckServerHealthInterval(long checkServerHealthInterval) {
|
|
||||||
this.checkServerHealthInterval = checkServerHealthInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getCheckServerHealthInterval() {
|
|
||||||
return checkServerHealthInterval;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getServerFailuresBeforeDown() {
|
|
||||||
return serverFailuresBeforeDown;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setServerFailuresBeforeDown(int serverFailuresBeforeDown) {
|
|
||||||
this.serverFailuresBeforeDown = serverFailuresBeforeDown;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getServerSuccessesBeforeUp() {
|
|
||||||
return serverSuccessesBeforeUp;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setServerSuccessesBeforeUp(int serverSuccessesBeforeUp) {
|
|
||||||
this.serverSuccessesBeforeUp = serverSuccessesBeforeUp;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
import javax.validation.Valid;
|
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
|
||||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
|
||||||
import timely.configuration.Http;
|
|
||||||
|
|
||||||
public class BalancerHttp extends Http {
|
|
||||||
|
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private GenericKeyedObjectPoolConfig httpClientPool = new GenericKeyedObjectPoolConfig();
|
|
||||||
|
|
||||||
public GenericKeyedObjectPoolConfig getHttpClientPool() {
|
|
||||||
return httpClientPool;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
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.ConfigurationProperties;
|
||||||
|
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||||
|
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||||
|
|
||||||
|
import timely.common.configuration.HttpProperties;
|
||||||
|
|
||||||
|
@RefreshScope
|
||||||
|
@ConfigurationProperties(prefix = "timely.balancer.http")
|
||||||
|
public class BalancerHttpProperties extends HttpProperties {
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
@NestedConfigurationProperty
|
||||||
|
private GenericKeyedObjectPoolConfig<CloseableHttpClient> httpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||||
|
|
||||||
|
public GenericKeyedObjectPoolConfig<CloseableHttpClient> getHttpClientPool() {
|
||||||
|
return httpClientPool;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package timely.balancer.configuration;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
|
||||||
|
@Validated
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "timely.balancer")
|
||||||
|
public class BalancerProperties {
|
||||||
|
|
||||||
|
private boolean loginRequired = false;
|
||||||
|
|
||||||
|
private String assignmentFile;
|
||||||
|
|
||||||
|
private String defaultFs;
|
||||||
|
|
||||||
|
private List<String> fsConfigResources;
|
||||||
|
|
||||||
|
private Double controlBandPercentage = 0.05;
|
||||||
|
|
||||||
|
private long checkServerHealthInterval = 10000;
|
||||||
|
|
||||||
|
private int serverFailuresBeforeDown = 3;
|
||||||
|
|
||||||
|
private int serverSuccessesBeforeUp = 3;
|
||||||
|
|
||||||
|
public void setLoginRequired(boolean loginRequired) {
|
||||||
|
this.loginRequired = loginRequired;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isLoginRequired() {
|
||||||
|
return loginRequired;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAssignmentFile() {
|
||||||
|
return assignmentFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAssignmentFile(String assignmentFile) {
|
||||||
|
this.assignmentFile = assignmentFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDefaultFs() {
|
||||||
|
return defaultFs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDefaultFs(String defaultFs) {
|
||||||
|
this.defaultFs = defaultFs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getFsConfigResources() {
|
||||||
|
return fsConfigResources;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFsConfigResources(List<String> fsConfigResources) {
|
||||||
|
this.fsConfigResources = fsConfigResources;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setControlBandPercentage(Double controlBandPercentage) {
|
||||||
|
this.controlBandPercentage = controlBandPercentage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getControlBandPercentage() {
|
||||||
|
return controlBandPercentage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCheckServerHealthInterval(long checkServerHealthInterval) {
|
||||||
|
this.checkServerHealthInterval = checkServerHealthInterval;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getCheckServerHealthInterval() {
|
||||||
|
return checkServerHealthInterval;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getServerFailuresBeforeDown() {
|
||||||
|
return serverFailuresBeforeDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setServerFailuresBeforeDown(int serverFailuresBeforeDown) {
|
||||||
|
this.serverFailuresBeforeDown = serverFailuresBeforeDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getServerSuccessesBeforeUp() {
|
||||||
|
return serverSuccessesBeforeUp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setServerSuccessesBeforeUp(int serverSuccessesBeforeUp) {
|
||||||
|
this.serverSuccessesBeforeUp = serverSuccessesBeforeUp;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
import javax.validation.Valid;
|
|
||||||
|
|
||||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
|
||||||
import timely.configuration.Security;
|
|
||||||
|
|
||||||
public class BalancerSecurity extends Security {
|
|
||||||
|
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private ClientSsl clientSsl = new ClientSsl();
|
|
||||||
|
|
||||||
public ClientSsl getClientSsl() {
|
|
||||||
return clientSsl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+13
-6
@@ -3,28 +3,35 @@ package timely.balancer.configuration;
|
|||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||||
import timely.configuration.Server;
|
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||||
|
|
||||||
public class BalancerServer extends Server {
|
import timely.client.tcp.TcpClient;
|
||||||
|
import timely.client.udp.UdpClient;
|
||||||
|
import timely.common.configuration.ServerProperties;
|
||||||
|
|
||||||
|
@RefreshScope
|
||||||
|
@ConfigurationProperties(prefix = "timely.balancer.server")
|
||||||
|
public class BalancerServerProperties extends ServerProperties {
|
||||||
|
|
||||||
@Valid
|
@Valid
|
||||||
@NestedConfigurationProperty
|
@NestedConfigurationProperty
|
||||||
private GenericKeyedObjectPoolConfig udpClientPool = new GenericKeyedObjectPoolConfig();
|
private GenericKeyedObjectPoolConfig<UdpClient> udpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||||
|
|
||||||
@Valid
|
@Valid
|
||||||
@NestedConfigurationProperty
|
@NestedConfigurationProperty
|
||||||
private GenericKeyedObjectPoolConfig tcpClientPool = new GenericKeyedObjectPoolConfig();
|
private GenericKeyedObjectPoolConfig<TcpClient> tcpClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||||
|
|
||||||
private int numTcpPools = 1;
|
private int numTcpPools = 1;
|
||||||
|
|
||||||
private int tcpBufferSize = -1;
|
private int tcpBufferSize = -1;
|
||||||
|
|
||||||
public GenericKeyedObjectPoolConfig getUdpClientPool() {
|
public GenericKeyedObjectPoolConfig<UdpClient> getUdpClientPool() {
|
||||||
return udpClientPool;
|
return udpClientPool;
|
||||||
}
|
}
|
||||||
|
|
||||||
public GenericKeyedObjectPoolConfig getTcpClientPool() {
|
public GenericKeyedObjectPoolConfig<TcpClient> getTcpClientPool() {
|
||||||
return tcpClientPool;
|
return tcpClientPool;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
import javax.validation.Valid;
|
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
|
||||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
|
||||||
import timely.configuration.Websocket;
|
|
||||||
|
|
||||||
public class BalancerWebsocket extends Websocket {
|
|
||||||
|
|
||||||
@Valid
|
|
||||||
@NestedConfigurationProperty
|
|
||||||
private GenericKeyedObjectPoolConfig wsClientPool = new GenericKeyedObjectPoolConfig();
|
|
||||||
|
|
||||||
public GenericKeyedObjectPoolConfig getWsClientPool() {
|
|
||||||
return wsClientPool;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package timely.balancer.configuration;
|
||||||
|
|
||||||
|
import javax.validation.Valid;
|
||||||
|
|
||||||
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||||
|
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||||
|
|
||||||
|
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||||
|
import timely.common.configuration.WebsocketProperties;
|
||||||
|
|
||||||
|
@RefreshScope
|
||||||
|
@ConfigurationProperties(prefix = "timely.balancer.websocket")
|
||||||
|
public class BalancerWebsocketProperties extends WebsocketProperties {
|
||||||
|
|
||||||
|
@Valid
|
||||||
|
@NestedConfigurationProperty
|
||||||
|
private GenericKeyedObjectPoolConfig<WebSocketSubscriptionClient> wsClientPool = new GenericKeyedObjectPoolConfig<>();
|
||||||
|
|
||||||
|
public GenericKeyedObjectPoolConfig<WebSocketSubscriptionClient> getWsClientPool() {
|
||||||
|
return wsClientPool;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int incomingBufferSize = 50000000;
|
||||||
|
|
||||||
|
public int getIncomingBufferSize() {
|
||||||
|
return incomingBufferSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIncomingBufferSize(int incomingBufferSize) {
|
||||||
|
this.incomingBufferSize = incomingBufferSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
public class ClientSsl {
|
|
||||||
|
|
||||||
private String keyFile;
|
|
||||||
private String keyType;
|
|
||||||
private String keyPassword;
|
|
||||||
private String trustStoreFile;
|
|
||||||
private String trustStoreType;
|
|
||||||
private String trustStorePassword;
|
|
||||||
|
|
||||||
public String getKeyFile() {
|
|
||||||
return keyFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKeyFile(String keyFile) {
|
|
||||||
this.keyFile = keyFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getKeyType() {
|
|
||||||
return keyType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKeyType(String keyType) {
|
|
||||||
this.keyType = keyType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getKeyPassword() {
|
|
||||||
return keyPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKeyPassword(String keyPassword) {
|
|
||||||
this.keyPassword = keyPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTrustStoreFile() {
|
|
||||||
return trustStoreFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTrustStoreFile(String trustStoreFile) {
|
|
||||||
this.trustStoreFile = trustStoreFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTrustStoreType() {
|
|
||||||
return trustStoreType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTrustStoreType(String trustStoreType) {
|
|
||||||
this.trustStoreType = trustStoreType;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTrustStorePassword() {
|
|
||||||
return trustStorePassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTrustStorePassword(String trustStorePassword) {
|
|
||||||
this.trustStorePassword = trustStorePassword;
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
||||||
|
|
||||||
@SpringBootApplication(scanBasePackageClasses = { SpringBootstrap.class })
|
|
||||||
public class SpringBootstrap {
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package timely.balancer.configuration;
|
|
||||||
|
|
||||||
public class ZooKeeper {
|
|
||||||
|
|
||||||
private String servers;
|
|
||||||
|
|
||||||
public String getServers() {
|
|
||||||
return servers;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setServers(String servers) {
|
|
||||||
this.servers = servers;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,15 +5,13 @@ import org.apache.commons.lang3.builder.HashCodeBuilder;
|
|||||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import timely.balancer.ArrivalRate;
|
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
|
|
||||||
import java.util.Timer;
|
import timely.balancer.ArrivalRate;
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
|
||||||
public class TimelyBalancedHost {
|
public class TimelyBalancedHost {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(TimelyBalancedHost.class);
|
private static final Logger log = LoggerFactory.getLogger(TimelyBalancedHost.class);
|
||||||
static private Timer arrivalRateTimer = new Timer("ArrivalRateTimerTBH", true);
|
|
||||||
|
|
||||||
private String host;
|
private String host;
|
||||||
private int tcpPort;
|
private int tcpPort;
|
||||||
@@ -21,41 +19,30 @@ public class TimelyBalancedHost {
|
|||||||
private int wsPort;
|
private int wsPort;
|
||||||
private int udpPort;
|
private int udpPort;
|
||||||
private boolean isUp = true;
|
private boolean isUp = true;
|
||||||
private BalancerConfiguration balancerConfig;
|
private BalancerProperties balancerProperties;
|
||||||
private int failures = 0;
|
private int failures = 0;
|
||||||
private int successes = 0;
|
private int successes = 0;
|
||||||
private ArrivalRate arrivalRate = new ArrivalRate(arrivalRateTimer);
|
private ArrivalRate arrivalRate = null;
|
||||||
|
|
||||||
public TimelyBalancedHost() {
|
private TimelyBalancedHost() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public TimelyBalancedHost(String host, int tcpPort, int httpPort, int wsPort, int udpPort) {
|
private TimelyBalancedHost(String host, int tcpPort, int httpPort, int wsPort, int udpPort, ArrivalRate arrivalRate) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.tcpPort = tcpPort;
|
this.tcpPort = tcpPort;
|
||||||
this.httpPort = httpPort;
|
this.httpPort = httpPort;
|
||||||
this.wsPort = wsPort;
|
this.wsPort = wsPort;
|
||||||
this.udpPort = udpPort;
|
this.udpPort = udpPort;
|
||||||
|
this.arrivalRate = arrivalRate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public TimelyBalancedHost(String host, int basePort) {
|
static public TimelyBalancedHost of(String host, int tcpPort, int httpPort, int wsPort, int udpPort, ArrivalRate arrivalRate) {
|
||||||
this.host = host;
|
return new TimelyBalancedHost(host, tcpPort, httpPort, wsPort, udpPort, arrivalRate);
|
||||||
this.tcpPort = basePort;
|
|
||||||
this.httpPort = basePort + 1;
|
|
||||||
this.wsPort = basePort + 2;
|
|
||||||
this.udpPort = basePort + 3;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static public TimelyBalancedHost of(String host, int tcpPort, int httpPort, int wsPort, int udpPort) {
|
public void setBalancerProperties(BalancerProperties balancerProperties) {
|
||||||
return new TimelyBalancedHost(host, tcpPort, httpPort, wsPort, udpPort);
|
this.balancerProperties = balancerProperties;
|
||||||
}
|
|
||||||
|
|
||||||
static public TimelyBalancedHost of(String host, int basePort) {
|
|
||||||
return new TimelyBalancedHost(host, basePort);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBalancerConfig(BalancerConfiguration balancerConfig) {
|
|
||||||
this.balancerConfig = balancerConfig;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
synchronized public boolean isUp() {
|
synchronized public boolean isUp() {
|
||||||
@@ -63,38 +50,38 @@ public class TimelyBalancedHost {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void reportSuccess() {
|
public void reportSuccess() {
|
||||||
int serverSuccessesBeforeUp = balancerConfig.getServerSuccessesBeforeUp();
|
int serverSuccessesBeforeUp = balancerProperties.getServerSuccessesBeforeUp();
|
||||||
String h = host;
|
String h = host;
|
||||||
int p = tcpPort;
|
int p = tcpPort;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
if (LOG.isTraceEnabled()) {
|
if (log.isTraceEnabled()) {
|
||||||
LOG.trace("success reported host:{} port:{} isUp:{} successes:{} serverSuccessesBeforeUp:{}", h, p,
|
log.trace("success reported host:{} port:{} isUp:{} successes:{} serverSuccessesBeforeUp:{}", h, p, isUp, (successes + 1),
|
||||||
isUp, (successes + 1), serverSuccessesBeforeUp);
|
serverSuccessesBeforeUp);
|
||||||
}
|
}
|
||||||
if (!isUp) {
|
if (!isUp) {
|
||||||
if (++successes >= serverSuccessesBeforeUp) {
|
if (++successes >= serverSuccessesBeforeUp) {
|
||||||
isUp = true;
|
isUp = true;
|
||||||
successes = 0;
|
successes = 0;
|
||||||
LOG.info("host up host:{} port:{}", h, p);
|
log.info("host up host:{} port:{}", h, p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reportFailure() {
|
public void reportFailure() {
|
||||||
int serverFailuresBeforeDown = balancerConfig.getServerFailuresBeforeDown();
|
int serverFailuresBeforeDown = balancerProperties.getServerFailuresBeforeDown();
|
||||||
String h = host;
|
String h = host;
|
||||||
int p = tcpPort;
|
int p = tcpPort;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
if (LOG.isTraceEnabled()) {
|
if (log.isTraceEnabled()) {
|
||||||
LOG.trace("failure reported host:{} port:{} isUp:{} failures:{} serverFailuresBeforeUp:{}", h, p, isUp,
|
log.trace("failure reported host:{} port:{} isUp:{} failures:{} serverFailuresBeforeUp:{}", h, p, isUp, (failures + 1),
|
||||||
(failures + 1), serverFailuresBeforeDown);
|
serverFailuresBeforeDown);
|
||||||
}
|
}
|
||||||
if (isUp) {
|
if (isUp) {
|
||||||
if (++failures >= serverFailuresBeforeDown) {
|
if (++failures >= serverFailuresBeforeDown) {
|
||||||
isUp = false;
|
isUp = false;
|
||||||
failures = 0;
|
failures = 0;
|
||||||
LOG.info("host down host:{} port:{}", h, p);
|
log.info("host down host:{} port:{}", h, p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,11 +128,17 @@ public class TimelyBalancedHost {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void arrived() {
|
public void arrived() {
|
||||||
arrivalRate.arrived();
|
if (this.arrivalRate != null) {
|
||||||
|
this.arrivalRate.arrived();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public double getArrivalRate() {
|
public double getArrivalRate() {
|
||||||
return arrivalRate.getRate();
|
if (this.arrivalRate == null) {
|
||||||
|
return 0;
|
||||||
|
} else {
|
||||||
|
return this.arrivalRate.getRate();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -5,22 +5,27 @@ import javax.net.ssl.SSLContext;
|
|||||||
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
||||||
import org.apache.commons.pool2.PooledObject;
|
import org.apache.commons.pool2.PooledObject;
|
||||||
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||||
import org.apache.http.impl.client.BasicCookieStore;
|
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
|
||||||
|
|
||||||
public class HttpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, CloseableHttpClient> {
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
import timely.client.http.HttpClient;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
|
||||||
|
public class HttpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost,CloseableHttpClient> {
|
||||||
|
|
||||||
private final SSLContext sslContext;
|
private final SSLContext sslContext;
|
||||||
|
private SslClientProperties sslClientProperties;
|
||||||
|
|
||||||
public HttpClientFactory(SSLContext sslContext) {
|
public HttpClientFactory(SSLContext sslContext, SslClientProperties sslClientProperties) {
|
||||||
this.sslContext = sslContext;
|
this.sslContext = sslContext;
|
||||||
|
this.sslClientProperties = sslClientProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PooledObject<CloseableHttpClient> makeObject(TimelyBalancedHost k) throws Exception {
|
public PooledObject<CloseableHttpClient> makeObject(TimelyBalancedHost k) throws Exception {
|
||||||
BasicCookieStore cookieJar = new BasicCookieStore();
|
// disable cookie management because we are sharing connections
|
||||||
return new DefaultPooledObject<>(timely.client.http.HttpClient.get(this.sslContext, cookieJar, false));
|
return new DefaultPooledObject<>(
|
||||||
|
HttpClient.get(this.sslContext, null, sslClientProperties.isHostVerificationEnabled(), sslClientProperties.isUseClientCert()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -4,16 +4,14 @@ import javax.net.ssl.SSLContext;
|
|||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
import timely.balancer.configuration.BalancerHttpProperties;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
|
||||||
public class HttpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost, CloseableHttpClient> {
|
public class HttpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost,CloseableHttpClient> {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(HttpClientPool.class);
|
public HttpClientPool(BalancerHttpProperties http, SSLContext sslContext, SslClientProperties sslClientProperties) {
|
||||||
|
super(new HttpClientFactory(sslContext, sslClientProperties), http.getHttpClientPool());
|
||||||
public HttpClientPool(BalancerConfiguration config, SSLContext sslContext) {
|
|
||||||
super(new HttpClientFactory(sslContext), config.getHttp().getHttpClientPool());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,11 @@ import java.io.IOException;
|
|||||||
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
||||||
import org.apache.commons.pool2.PooledObject;
|
import org.apache.commons.pool2.PooledObject;
|
||||||
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||||
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.tcp.TcpClient;
|
import timely.client.tcp.TcpClient;
|
||||||
|
|
||||||
public class TcpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, TcpClient> {
|
public class TcpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost,TcpClient> {
|
||||||
|
|
||||||
private int bufferSize;
|
private int bufferSize;
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
package timely.balancer.connection.tcp;
|
package timely.balancer.connection.tcp;
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.tcp.TcpClient;
|
import timely.client.tcp.TcpClient;
|
||||||
|
|
||||||
public class TcpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost, TcpClient> {
|
public class TcpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost,TcpClient> {
|
||||||
|
|
||||||
public TcpClientPool(BalancerConfiguration config) {
|
public TcpClientPool(BalancerServerProperties balancerServerProperties) {
|
||||||
super(new TcpClientFactory(config.getServer().getTcpBufferSize()), config.getServer().getTcpClientPool());
|
super(new TcpClientFactory(balancerServerProperties.getTcpBufferSize()), balancerServerProperties.getTcpClientPool());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,13 +5,13 @@ import java.io.IOException;
|
|||||||
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
||||||
import org.apache.commons.pool2.PooledObject;
|
import org.apache.commons.pool2.PooledObject;
|
||||||
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||||
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.udp.UdpClient;
|
import timely.client.udp.UdpClient;
|
||||||
|
|
||||||
public class UdpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, UdpClient> {
|
public class UdpClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost,UdpClient> {
|
||||||
|
|
||||||
public UdpClientFactory() {
|
public UdpClientFactory() {}
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PooledObject<UdpClient> makeObject(TimelyBalancedHost k) throws Exception {
|
public PooledObject<UdpClient> makeObject(TimelyBalancedHost k) throws Exception {
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
package timely.balancer.connection.udp;
|
package timely.balancer.connection.udp;
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.udp.UdpClient;
|
import timely.client.udp.UdpClient;
|
||||||
|
|
||||||
public class UdpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost, UdpClient> {
|
public class UdpClientPool extends GenericKeyedObjectPool<TimelyBalancedHost,UdpClient> {
|
||||||
|
|
||||||
public UdpClientPool(BalancerConfiguration config) {
|
public UdpClientPool(BalancerServerProperties serverProperties) {
|
||||||
super(new UdpClientFactory(), config.getServer().getUdpClientPool());
|
super(new UdpClientFactory(), serverProperties.getUdpClientPool());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,28 +5,35 @@ import javax.net.ssl.SSLContext;
|
|||||||
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
import org.apache.commons.pool2.KeyedPooledObjectFactory;
|
||||||
import org.apache.commons.pool2.PooledObject;
|
import org.apache.commons.pool2.PooledObject;
|
||||||
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
import org.apache.commons.pool2.impl.DefaultPooledObject;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerWebsocketProperties;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
|
||||||
public class WsClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost, WebSocketSubscriptionClient> {
|
public class WsClientFactory implements KeyedPooledObjectFactory<TimelyBalancedHost,WebSocketSubscriptionClient> {
|
||||||
|
|
||||||
private final SSLContext sslContext;
|
private final SSLContext sslContext;
|
||||||
private final boolean doLogin;
|
private BalancerProperties balancerProperties;
|
||||||
private BalancerConfiguration balancerConfig;
|
private BalancerWebsocketProperties balancerWebsocketProperties;
|
||||||
|
private SslClientProperties sslClientProperties;
|
||||||
|
|
||||||
public WsClientFactory(BalancerConfiguration balancerConfig, SSLContext sslContext) {
|
public WsClientFactory(BalancerProperties balancerProperties, BalancerWebsocketProperties balancerWebsocketProperties,
|
||||||
|
SslClientProperties sslClientProperties, SSLContext sslContext) {
|
||||||
|
this.balancerProperties = balancerProperties;
|
||||||
|
this.balancerWebsocketProperties = balancerWebsocketProperties;
|
||||||
|
this.sslClientProperties = sslClientProperties;
|
||||||
this.sslContext = sslContext;
|
this.sslContext = sslContext;
|
||||||
this.doLogin = balancerConfig.isLoginRequired();
|
|
||||||
this.balancerConfig = balancerConfig;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PooledObject<WebSocketSubscriptionClient> makeObject(TimelyBalancedHost k) throws Exception {
|
public PooledObject<WebSocketSubscriptionClient> makeObject(TimelyBalancedHost k) throws Exception {
|
||||||
|
|
||||||
int bufferSize = balancerConfig.getWebsocket().getSubscriptionBatchSize() * 500;
|
int bufferSize = balancerWebsocketProperties.getIncomingBufferSize();
|
||||||
WebSocketSubscriptionClient client = new WebSocketSubscriptionClient(sslContext, k.getHost(), k.getHttpPort(),
|
WebSocketSubscriptionClient client = new WebSocketSubscriptionClient(sslContext, k.getHost(), k.getHttpPort(), k.getWsPort(),
|
||||||
k.getWsPort(), doLogin, "", "", false, bufferSize);
|
sslClientProperties.isUseClientCert(), balancerProperties.isLoginRequired(), sslClientProperties.isHostVerificationEnabled(),
|
||||||
|
bufferSize);
|
||||||
return new DefaultPooledObject<>(client);
|
return new DefaultPooledObject<>(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,18 @@ package timely.balancer.connection.ws;
|
|||||||
import javax.net.ssl.SSLContext;
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerWebsocketProperties;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
|
||||||
public class WsClientPool extends GenericKeyedObjectPool<TimelyBalancedHost, WebSocketSubscriptionClient> {
|
public class WsClientPool extends GenericKeyedObjectPool<TimelyBalancedHost,WebSocketSubscriptionClient> {
|
||||||
|
|
||||||
public WsClientPool(BalancerConfiguration balancerConfig, SSLContext sslContext) {
|
public WsClientPool(BalancerProperties balancerProperties, BalancerWebsocketProperties balancerWebsocketProperties, SslClientProperties sslClientProperties,
|
||||||
super(new WsClientFactory(balancerConfig, sslContext), balancerConfig.getWebsocket().getWsClientPool());
|
SSLContext sslContext) {
|
||||||
|
super(new WsClientFactory(balancerProperties, balancerWebsocketProperties, sslClientProperties, sslContext),
|
||||||
|
balancerWebsocketProperties.getWsClientPool());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
package timely.balancer.healthcheck;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Timer;
|
|
||||||
import java.util.TimerTask;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
|
||||||
import timely.balancer.connection.tcp.TcpClientPool;
|
|
||||||
|
|
||||||
public class HealthChecker {
|
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(HealthChecker.class);
|
|
||||||
private List<TimelyBalancedHost> timelyHosts = new ArrayList<>();
|
|
||||||
private Timer timer;
|
|
||||||
final private TCPServerHealthCheck tcpServerHealthCheck;
|
|
||||||
private TimerTask check = new TimerTask() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
synchronized (timelyHosts) {
|
|
||||||
for (TimelyBalancedHost h : timelyHosts) {
|
|
||||||
try {
|
|
||||||
if (tcpServerHealthCheck.isServerHealthy(h)) {
|
|
||||||
h.reportSuccess();
|
|
||||||
} else {
|
|
||||||
h.reportFailure();
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
h.reportFailure();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
public HealthChecker(BalancerConfiguration config, TcpClientPool tcpClientPool) {
|
|
||||||
this.tcpServerHealthCheck = new TCPServerHealthCheck(tcpClientPool);
|
|
||||||
this.timer = new Timer("HealthCheckerThread", true);
|
|
||||||
this.timer.scheduleAtFixedRate(check, 0, config.getCheckServerHealthInterval());
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTimelyHosts(List<TimelyBalancedHost> timelyHosts) {
|
|
||||||
synchronized (timelyHosts) {
|
|
||||||
this.timelyHosts.clear();
|
|
||||||
this.timelyHosts.addAll(timelyHosts);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
package timely.balancer.netty.http;
|
package timely.balancer.netty.http;
|
||||||
|
|
||||||
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
|
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -12,16 +11,6 @@ import java.util.Iterator;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
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.Header;
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
@@ -33,26 +22,39 @@ import org.apache.http.message.BasicHeader;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.util.StreamUtils;
|
import org.springframework.util.StreamUtils;
|
||||||
|
|
||||||
|
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 timely.api.request.AuthenticatedRequest;
|
||||||
|
import timely.api.request.HttpRequest;
|
||||||
import timely.api.request.MetricRequest;
|
import timely.api.request.MetricRequest;
|
||||||
import timely.api.request.timeseries.HttpRequest;
|
|
||||||
import timely.api.request.timeseries.QueryRequest;
|
import timely.api.request.timeseries.QueryRequest;
|
||||||
import timely.api.response.TimelyException;
|
import timely.api.response.TimelyException;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
import timely.auth.TimelyAuthenticationToken;
|
||||||
|
import timely.auth.util.HttpHeaderUtils;
|
||||||
|
import timely.auth.util.ProxiedEntityUtils;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.balancer.connection.http.HttpClientPool;
|
import timely.balancer.connection.http.HttpClientPool;
|
||||||
import timely.balancer.resolver.MetricResolver;
|
|
||||||
import timely.netty.http.TimelyHttpHandler;
|
import timely.netty.http.TimelyHttpHandler;
|
||||||
|
|
||||||
public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> implements TimelyHttpHandler {
|
public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> implements TimelyHttpHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(HttpRelayHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(HttpRelayHandler.class);
|
||||||
private final BalancerConfiguration balancerConf;
|
|
||||||
private final HttpClientPool httpClientPool;
|
private final HttpClientPool httpClientPool;
|
||||||
private MetricResolver metricResolver;
|
private MetricResolver metricResolver;
|
||||||
|
|
||||||
public HttpRelayHandler(BalancerConfiguration balancerConf, MetricResolver metricResolver,
|
public HttpRelayHandler(MetricResolver metricResolver, HttpClientPool httpClientPool) {
|
||||||
HttpClientPool httpClientPool) {
|
|
||||||
this.balancerConf = balancerConf;
|
|
||||||
this.metricResolver = metricResolver;
|
this.metricResolver = metricResolver;
|
||||||
this.httpClientPool = httpClientPool;
|
this.httpClientPool = httpClientPool;
|
||||||
}
|
}
|
||||||
@@ -67,7 +69,7 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
try {
|
try {
|
||||||
try {
|
try {
|
||||||
request = msg.getHttpRequest();
|
request = msg.getHttpRequest();
|
||||||
String originalURI = request.getUri();
|
String originalURI = request.uri();
|
||||||
originalURI = encodeURI(originalURI);
|
originalURI = encodeURI(originalURI);
|
||||||
|
|
||||||
String metric = null;
|
String metric = null;
|
||||||
@@ -86,14 +88,22 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
} else {
|
} else {
|
||||||
k = metricResolver.getHostPortKey(null);
|
k = metricResolver.getHostPortKey(null);
|
||||||
}
|
}
|
||||||
k = metricResolver.getHostPortKey(metric);
|
|
||||||
client = httpClientPool.borrowObject(k);
|
client = httpClientPool.borrowObject(k);
|
||||||
|
|
||||||
List<Map.Entry<String, String>> headerList = request.headers().entries();
|
Multimap<String,String> headers = HttpHeaderUtils.toMultimap(request.headers());
|
||||||
List<Header> relayedHeaderList = new ArrayList<>();
|
if (msg instanceof AuthenticatedRequest) {
|
||||||
|
AuthenticatedRequest authenticatedRequest = (AuthenticatedRequest) msg;
|
||||||
|
TimelyAuthenticationToken token = authenticatedRequest.getToken();
|
||||||
|
if (token != null) {
|
||||||
|
if (token.getClientCert() != null) {
|
||||||
|
ProxiedEntityUtils.addProxyHeaders(headers, token.getClientCert());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (Map.Entry<String, String> h : headerList) {
|
List<Header> relayedHeaderList = new ArrayList<>();
|
||||||
if (!h.getKey().equals(CONTENT_LENGTH)) {
|
for (Map.Entry<String,String> h : headers.entries()) {
|
||||||
|
if (!h.getKey().equals(CONTENT_LENGTH.toString())) {
|
||||||
relayedHeaderList.add(new BasicHeader(h.getKey(), h.getValue()));
|
relayedHeaderList.add(new BasicHeader(h.getKey(), h.getValue()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -101,14 +111,14 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
relayedHeaderList.toArray(headerArray);
|
relayedHeaderList.toArray(headerArray);
|
||||||
|
|
||||||
String relayURI = "https://" + k.getHost() + ":" + k.getHttpPort() + originalURI;
|
String relayURI = "https://" + k.getHost() + ":" + k.getHttpPort() + originalURI;
|
||||||
if (request.getMethod().equals(HttpMethod.GET)) {
|
if (request.method().equals(HttpMethod.GET)) {
|
||||||
HttpUriRequest relayedRequest = new HttpGet(relayURI);
|
HttpUriRequest relayedRequest = new HttpGet(relayURI);
|
||||||
if (headerArray.length > 0) {
|
if (headerArray.length > 0) {
|
||||||
relayedRequest.setHeaders(headerArray);
|
relayedRequest.setHeaders(headerArray);
|
||||||
}
|
}
|
||||||
relayedResponse = client.execute(relayedRequest);
|
relayedResponse = client.execute(relayedRequest);
|
||||||
|
|
||||||
} else if (request.getMethod().equals(HttpMethod.POST)) {
|
} else if (request.method().equals(HttpMethod.POST)) {
|
||||||
HttpPost relayedRequest = new HttpPost(relayURI);
|
HttpPost relayedRequest = new HttpPost(relayURI);
|
||||||
|
|
||||||
String content = request.content().toString(StandardCharsets.UTF_8);
|
String content = request.content().toString(StandardCharsets.UTF_8);
|
||||||
@@ -122,39 +132,33 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
String message = e.getMessage();
|
String message = e.getMessage();
|
||||||
if (message == null) {
|
if (message == null) {
|
||||||
LOG.error("", e);
|
log.error("", e);
|
||||||
} else {
|
} else {
|
||||||
if (message.contains("No matching tags")) {
|
if (message.contains("No matching tags")) {
|
||||||
LOG.trace(message);
|
log.trace(message);
|
||||||
} else {
|
} else {
|
||||||
LOG.error(message, e);
|
log.error(message, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
|
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), e.getMessage(), e.getLocalizedMessage(), e));
|
||||||
e.getMessage(), e.getLocalizedMessage(), e));
|
|
||||||
return;
|
return;
|
||||||
} finally {
|
} finally {
|
||||||
if (request != null && request instanceof AutoCloseable) {
|
if (request != null) {
|
||||||
ReferenceCountUtil.release(request);
|
ReferenceCountUtil.release(request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FullHttpResponse response = null;
|
FullHttpResponse response = null;
|
||||||
if (relayedResponse == null) {
|
if (relayedResponse == null) {
|
||||||
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.METHOD_NOT_ALLOWED.code(),
|
this.sendHttpError(ctx, new TimelyException(HttpResponseStatus.METHOD_NOT_ALLOWED.code(), "Method not allowed", "Method not allowed"));
|
||||||
"Method not allowed", "Method not allowed"));
|
|
||||||
} else {
|
} else {
|
||||||
// buf = JsonUtil.getObjectMapper().writeValueAsBytes(msg);
|
|
||||||
ByteArrayOutputStream baos = new MyByteArrayOutputStream();
|
ByteArrayOutputStream baos = new MyByteArrayOutputStream();
|
||||||
StreamUtils.copy(relayedResponse.getEntity().getContent(), baos);
|
StreamUtils.copy(relayedResponse.getEntity().getContent(), baos);
|
||||||
|
|
||||||
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
|
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(relayedResponse.getStatusLine().getStatusCode()),
|
||||||
HttpResponseStatus.valueOf(relayedResponse.getStatusLine().getStatusCode()),
|
Unpooled.copiedBuffer(baos.toByteArray()));
|
||||||
Unpooled.copiedBuffer(baos.toByteArray()));
|
|
||||||
for (Header h : relayedResponse.getAllHeaders()) {
|
for (Header h : relayedResponse.getAllHeaders()) {
|
||||||
response.headers().add(h.getName(), h.getValue());
|
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());
|
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
|
||||||
sendResponse(ctx, response);
|
sendResponse(ctx, response);
|
||||||
}
|
}
|
||||||
@@ -165,15 +169,14 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
if (client != null && k != null) {
|
if (client != null && k != null) {
|
||||||
httpClientPool.returnObject(k, client);
|
httpClientPool.returnObject(k, client);
|
||||||
} else {
|
} else {
|
||||||
LOG.error("NOT RETURNING CONNECTION! " + msg.getHttpRequest().getUri());
|
log.error("NOT RETURNING CONNECTION! " + msg.getHttpRequest().uri());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static public class MyByteArrayOutputStream extends ByteArrayOutputStream {
|
static public class MyByteArrayOutputStream extends ByteArrayOutputStream {
|
||||||
|
|
||||||
public MyByteArrayOutputStream() {
|
public MyByteArrayOutputStream() {}
|
||||||
}
|
|
||||||
|
|
||||||
public MyByteArrayOutputStream(int size) {
|
public MyByteArrayOutputStream(int size) {
|
||||||
super(size);
|
super(size);
|
||||||
@@ -197,13 +200,4 @@ public class HttpRelayHandler extends SimpleChannelInboundHandler<HttpRequest> i
|
|||||||
}
|
}
|
||||||
return s;
|
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());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -4,33 +4,33 @@ import java.io.IOException;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import io.netty.buffer.Unpooled;
|
import io.netty.buffer.Unpooled;
|
||||||
import io.netty.channel.ChannelFuture;
|
import io.netty.channel.ChannelFuture;
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import io.netty.channel.SimpleChannelInboundHandler;
|
import io.netty.channel.SimpleChannelInboundHandler;
|
||||||
import org.apache.commons.lang3.tuple.Pair;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import timely.api.request.MetricRequest;
|
import timely.api.request.MetricRequest;
|
||||||
import timely.api.request.TcpRequest;
|
import timely.api.request.TcpRequest;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.balancer.connection.tcp.TcpClientPool;
|
import timely.balancer.connection.tcp.TcpClientPool;
|
||||||
import timely.balancer.resolver.BalancedMetricResolver;
|
|
||||||
import timely.balancer.resolver.MetricResolver;
|
|
||||||
import timely.client.tcp.TcpClient;
|
import timely.client.tcp.TcpClient;
|
||||||
import timely.netty.Constants;
|
import timely.netty.Constants;
|
||||||
|
|
||||||
public class TcpRelayHandler extends SimpleChannelInboundHandler<TcpRequest> {
|
public class TcpRelayHandler extends SimpleChannelInboundHandler<TcpRequest> {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(TcpRelayHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(TcpRelayHandler.class);
|
||||||
private static final String LOG_ERR_MSG = "Error storing put metric: {}";
|
private static final String LOG_ERR_MSG = "Error storing put metric: {}";
|
||||||
private static final String ERR_MSG = "Error storing put metric: ";
|
private static final String ERR_MSG = "Error storing put metric: ";
|
||||||
|
|
||||||
private BalancedMetricResolver metricResolver;
|
private MetricResolver metricResolver;
|
||||||
private List<TcpClientPool> tcpClientPools;
|
private List<TcpClientPool> tcpClientPools;
|
||||||
|
|
||||||
public TcpRelayHandler(MetricResolver metricResolver, List<TcpClientPool> tcpClientPools) {
|
public TcpRelayHandler(MetricResolver metricResolver, List<TcpClientPool> tcpClientPools) {
|
||||||
this.metricResolver = (BalancedMetricResolver) metricResolver;
|
this.metricResolver = metricResolver;
|
||||||
this.tcpClientPools = tcpClientPools;
|
this.tcpClientPools = tcpClientPools;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,10 +41,10 @@ public class TcpRelayHandler extends SimpleChannelInboundHandler<TcpRequest> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void channelRead0(ChannelHandlerContext ctx, TcpRequest msg) throws Exception {
|
protected void channelRead0(ChannelHandlerContext ctx, TcpRequest msg) throws Exception {
|
||||||
LOG.trace("Received {}", msg);
|
log.trace("Received {}", msg);
|
||||||
try {
|
try {
|
||||||
String line;
|
String line;
|
||||||
Pair<TimelyBalancedHost, TcpClient> keyClientPair = null;
|
Pair<TimelyBalancedHost,TcpClient> keyClientPair = null;
|
||||||
try {
|
try {
|
||||||
if (msg instanceof MetricRequest) {
|
if (msg instanceof MetricRequest) {
|
||||||
String metricName = ((MetricRequest) msg).getMetric().getName();
|
String metricName = ((MetricRequest) msg).getMetric().getName();
|
||||||
@@ -63,29 +63,27 @@ public class TcpRelayHandler extends SimpleChannelInboundHandler<TcpRequest> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOG.error(LOG_ERR_MSG, msg, e);
|
log.error(LOG_ERR_MSG, msg, e);
|
||||||
ChannelFuture cf = ctx.writeAndFlush(
|
ChannelFuture cf = ctx.writeAndFlush(Unpooled.copiedBuffer((ERR_MSG + e.getMessage() + "\n").getBytes(StandardCharsets.UTF_8)));
|
||||||
Unpooled.copiedBuffer((ERR_MSG + e.getMessage() + "\n").getBytes(StandardCharsets.UTF_8)));
|
|
||||||
if (!cf.isSuccess()) {
|
if (!cf.isSuccess()) {
|
||||||
LOG.error(Constants.ERR_WRITING_RESPONSE, cf.cause());
|
log.error(Constants.ERR_WRITING_RESPONSE, cf.cause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Pair<TimelyBalancedHost, TcpClient> getClient(String metric, boolean metricRequest) {
|
private Pair<TimelyBalancedHost,TcpClient> getClient(String metric, boolean metricRequest) {
|
||||||
TcpClient client = null;
|
TcpClient client = null;
|
||||||
TimelyBalancedHost k = null;
|
TimelyBalancedHost k = null;
|
||||||
int failures = 0;
|
int failures = 0;
|
||||||
while (client == null) {
|
while (client == null) {
|
||||||
try {
|
try {
|
||||||
k = (metricRequest == true) ? metricResolver.getHostPortKeyIngest(metric)
|
k = (metricRequest == true) ? metricResolver.getHostPortKeyIngest(metric) : metricResolver.getHostPortKey(metric);
|
||||||
: metricResolver.getHostPortKey(metric);
|
|
||||||
client = tcpClientPool().borrowObject(k);
|
client = tcpClientPool().borrowObject(k);
|
||||||
} catch (Exception e1) {
|
} catch (Exception e1) {
|
||||||
failures++;
|
failures++;
|
||||||
client = null;
|
client = null;
|
||||||
if (failures % 10 == 0) {
|
if (failures % 10 == 0) {
|
||||||
LOG.error(e1.getMessage(), e1);
|
log.error(e1.getMessage(), e1);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Thread.sleep(failures < 10 ? 500 : 60000);
|
Thread.sleep(failures < 10 ? 500 : 60000);
|
||||||
|
|||||||
@@ -2,24 +2,25 @@ package timely.balancer.netty.udp;
|
|||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import io.netty.buffer.Unpooled;
|
import io.netty.buffer.Unpooled;
|
||||||
import io.netty.channel.ChannelFuture;
|
import io.netty.channel.ChannelFuture;
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import io.netty.channel.SimpleChannelInboundHandler;
|
import io.netty.channel.SimpleChannelInboundHandler;
|
||||||
import org.apache.commons.lang3.tuple.Pair;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import timely.api.request.MetricRequest;
|
import timely.api.request.MetricRequest;
|
||||||
import timely.api.request.UdpRequest;
|
import timely.api.request.UdpRequest;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.balancer.connection.udp.UdpClientPool;
|
import timely.balancer.connection.udp.UdpClientPool;
|
||||||
import timely.balancer.resolver.MetricResolver;
|
|
||||||
import timely.client.udp.UdpClient;
|
import timely.client.udp.UdpClient;
|
||||||
import timely.netty.Constants;
|
import timely.netty.Constants;
|
||||||
|
|
||||||
public class UdpRelayHandler extends SimpleChannelInboundHandler<UdpRequest> {
|
public class UdpRelayHandler extends SimpleChannelInboundHandler<UdpRequest> {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(UdpRelayHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(UdpRelayHandler.class);
|
||||||
private static final String LOG_ERR_MSG = "Error storing put metric: {}";
|
private static final String LOG_ERR_MSG = "Error storing put metric: {}";
|
||||||
private static final String ERR_MSG = "Error storing put metric: ";
|
private static final String ERR_MSG = "Error storing put metric: ";
|
||||||
|
|
||||||
@@ -33,11 +34,11 @@ public class UdpRelayHandler extends SimpleChannelInboundHandler<UdpRequest> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void channelRead0(ChannelHandlerContext ctx, UdpRequest msg) throws Exception {
|
protected void channelRead0(ChannelHandlerContext ctx, UdpRequest msg) throws Exception {
|
||||||
LOG.trace("Received {}", msg);
|
log.trace("Received {}", msg);
|
||||||
try {
|
try {
|
||||||
MetricRequest metricRequest = (MetricRequest) msg;
|
MetricRequest metricRequest = (MetricRequest) msg;
|
||||||
String metricName = metricRequest.getMetric().getName();
|
String metricName = metricRequest.getMetric().getName();
|
||||||
Pair<TimelyBalancedHost, UdpClient> keyClientPair = null;
|
Pair<TimelyBalancedHost,UdpClient> keyClientPair = null;
|
||||||
try {
|
try {
|
||||||
keyClientPair = getClient(metricName, true);
|
keyClientPair = getClient(metricName, true);
|
||||||
keyClientPair.getRight().write(metricRequest.getLine() + "\n");
|
keyClientPair.getRight().write(metricRequest.getLine() + "\n");
|
||||||
@@ -49,28 +50,26 @@ public class UdpRelayHandler extends SimpleChannelInboundHandler<UdpRequest> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error(LOG_ERR_MSG, msg, e);
|
log.error(LOG_ERR_MSG, msg, e);
|
||||||
ChannelFuture cf = ctx.writeAndFlush(
|
ChannelFuture cf = ctx.writeAndFlush(Unpooled.copiedBuffer((ERR_MSG + e.getMessage() + "\n").getBytes(StandardCharsets.UTF_8)));
|
||||||
Unpooled.copiedBuffer((ERR_MSG + e.getMessage() + "\n").getBytes(StandardCharsets.UTF_8)));
|
|
||||||
if (!cf.isSuccess()) {
|
if (!cf.isSuccess()) {
|
||||||
LOG.error(Constants.ERR_WRITING_RESPONSE, cf.cause());
|
log.error(Constants.ERR_WRITING_RESPONSE, cf.cause());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Pair<TimelyBalancedHost, UdpClient> getClient(String metric, boolean metricRequest) {
|
private Pair<TimelyBalancedHost,UdpClient> getClient(String metric, boolean metricRequest) {
|
||||||
UdpClient client = null;
|
UdpClient client = null;
|
||||||
TimelyBalancedHost k = null;
|
TimelyBalancedHost k = null;
|
||||||
int failures = 0;
|
int failures = 0;
|
||||||
while (client == null) {
|
while (client == null) {
|
||||||
try {
|
try {
|
||||||
k = (metricRequest == true) ? metricResolver.getHostPortKeyIngest(metric)
|
k = (metricRequest == true) ? metricResolver.getHostPortKeyIngest(metric) : metricResolver.getHostPortKey(metric);
|
||||||
: metricResolver.getHostPortKey(metric);
|
|
||||||
client = udpClientPool.borrowObject(k);
|
client = udpClientPool.borrowObject(k);
|
||||||
} catch (Exception e1) {
|
} catch (Exception e1) {
|
||||||
failures++;
|
failures++;
|
||||||
client = null;
|
client = null;
|
||||||
LOG.error(e1.getMessage(), e1);
|
log.error(e1.getMessage(), e1);
|
||||||
try {
|
try {
|
||||||
Thread.sleep(failures < 10 ? 500 : 60000);
|
Thread.sleep(failures < 10 ? 500 : 60000);
|
||||||
} catch (InterruptedException e2) {
|
} catch (InterruptedException e2) {
|
||||||
|
|||||||
@@ -1,41 +1,70 @@
|
|||||||
package timely.balancer.netty.ws;
|
package timely.balancer.netty.ws;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import javax.websocket.CloseReason;
|
import javax.websocket.CloseReason;
|
||||||
import javax.websocket.EndpointConfig;
|
import javax.websocket.EndpointConfig;
|
||||||
import javax.websocket.MessageHandler;
|
|
||||||
import javax.websocket.Session;
|
import javax.websocket.Session;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.google.common.collect.HashMultimap;
|
||||||
|
import com.google.common.collect.Multimap;
|
||||||
|
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||||
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
|
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
|
||||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||||
import io.netty.util.concurrent.ScheduledFuture;
|
import io.netty.util.concurrent.ScheduledFuture;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import timely.api.response.TimelyException;
|
import timely.api.response.TimelyException;
|
||||||
|
import timely.auth.TimelyAuthenticationToken;
|
||||||
|
import timely.auth.util.ProxiedEntityUtils;
|
||||||
import timely.client.websocket.ClientHandler;
|
import timely.client.websocket.ClientHandler;
|
||||||
|
|
||||||
public class WsClientHandler extends ClientHandler {
|
public class WsClientHandler extends ClientHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WsClientHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(WsClientHandler.class);
|
||||||
private final ChannelHandlerContext ctx;
|
private final ChannelHandlerContext ctx;
|
||||||
|
private final TimelyAuthenticationToken token;
|
||||||
private ScheduledFuture<?> ping;
|
private ScheduledFuture<?> ping;
|
||||||
|
|
||||||
public WsClientHandler(ChannelHandlerContext ctx, int pingRate) {
|
public WsClientHandler(ChannelHandlerContext ctx, TimelyAuthenticationToken token, int pingRate) {
|
||||||
this.ctx = ctx;
|
this.ctx = ctx;
|
||||||
|
this.token = token;
|
||||||
this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
|
this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
|
||||||
LOG.trace("Sending ping on channel {}", ctx.channel());
|
log.trace("Sending ping on channel {}", ctx.channel());
|
||||||
ctx.writeAndFlush(new PingWebSocketFrame());
|
ctx.writeAndFlush(new PingWebSocketFrame());
|
||||||
}, pingRate, pingRate, TimeUnit.SECONDS);
|
}, 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
|
@Override
|
||||||
public void onOpen(Session session, EndpointConfig config) {
|
public void onOpen(Session session, EndpointConfig config) {
|
||||||
session.addMessageHandler((MessageHandler.Whole<String>) message -> {
|
session.addMessageHandler(String.class, message -> {
|
||||||
ctx.writeAndFlush(new TextWebSocketFrame(message));
|
ctx.writeAndFlush(new TextWebSocketFrame(message));
|
||||||
LOG.debug("Message received on Websocket session {}: {}", session.getId(), message);
|
log.debug("Message received on Websocket session {}: {}", session.getId(), message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,9 +72,8 @@ public class WsClientHandler extends ClientHandler {
|
|||||||
public void onClose(Session session, CloseReason reason) {
|
public void onClose(Session session, CloseReason reason) {
|
||||||
super.onClose(session, reason);
|
super.onClose(session, reason);
|
||||||
if (!reason.getCloseCode().equals(CloseReason.CloseCodes.NORMAL_CLOSURE)) {
|
if (!reason.getCloseCode().equals(CloseReason.CloseCodes.NORMAL_CLOSURE)) {
|
||||||
LOG.error("Abnormal close: " + reason.getReasonPhrase());
|
log.error("Abnormal close: " + reason.getReasonPhrase());
|
||||||
Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), reason.getReasonPhrase(),
|
Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), reason.getReasonPhrase(), "");
|
||||||
"");
|
|
||||||
WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
|
WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
|
||||||
}
|
}
|
||||||
if (!ping.isCancelled()) {
|
if (!ping.isCancelled()) {
|
||||||
@@ -56,7 +84,7 @@ public class WsClientHandler extends ClientHandler {
|
|||||||
@Override
|
@Override
|
||||||
public void onError(Session session, Throwable t) {
|
public void onError(Session session, Throwable t) {
|
||||||
super.onError(session, t);
|
super.onError(session, t);
|
||||||
LOG.error(t.getMessage(), t);
|
log.error(t.getMessage(), t);
|
||||||
Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), t.getMessage(), "");
|
Exception e = new TimelyException(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), t.getMessage(), "");
|
||||||
WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
|
WsRelayHandler.sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
|
||||||
if (!ping.isCancelled()) {
|
if (!ping.isCancelled()) {
|
||||||
|
|||||||
@@ -4,15 +4,16 @@ import java.io.IOException;
|
|||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.balancer.connection.ws.WsClientPool;
|
import timely.balancer.connection.ws.WsClientPool;
|
||||||
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||||
|
|
||||||
public class WsClientHolder {
|
public class WsClientHolder {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WsClientHolder.class);
|
private static final Logger log = LoggerFactory.getLogger(WsClientHolder.class);
|
||||||
private WebSocketSubscriptionClient client = null;
|
private WebSocketSubscriptionClient client;
|
||||||
private TimelyBalancedHost host = null;
|
private TimelyBalancedHost host;
|
||||||
|
|
||||||
public WsClientHolder(TimelyBalancedHost host, WebSocketSubscriptionClient client) {
|
public WsClientHolder(TimelyBalancedHost host, WebSocketSubscriptionClient client) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
@@ -32,7 +33,7 @@ public class WsClientHolder {
|
|||||||
try {
|
try {
|
||||||
client.close();
|
client.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOG.error("Error closing web socket client", e);
|
log.error("Error closing web socket client", e);
|
||||||
}
|
}
|
||||||
wsClientPool.returnObject(host, client);
|
wsClientPool.returnObject(host, client);
|
||||||
client = null;
|
client = null;
|
||||||
|
|||||||
@@ -5,10 +5,15 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
|
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
|
||||||
|
import com.google.common.collect.Multimap;
|
||||||
|
|
||||||
import io.netty.channel.ChannelFuture;
|
import io.netty.channel.ChannelFuture;
|
||||||
import io.netty.channel.ChannelFutureListener;
|
import io.netty.channel.ChannelFutureListener;
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
@@ -16,31 +21,30 @@ import io.netty.channel.SimpleChannelInboundHandler;
|
|||||||
import io.netty.handler.codec.http.HttpResponseStatus;
|
import io.netty.handler.codec.http.HttpResponseStatus;
|
||||||
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
|
||||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||||
import org.slf4j.Logger;
|
import timely.api.request.websocket.AddSubscription;
|
||||||
import org.slf4j.LoggerFactory;
|
import timely.api.request.websocket.CloseSubscription;
|
||||||
import timely.api.request.subscription.AddSubscription;
|
import timely.api.request.websocket.CreateSubscription;
|
||||||
import timely.api.request.subscription.CloseSubscription;
|
import timely.api.request.websocket.RemoveSubscription;
|
||||||
import timely.api.request.subscription.CreateSubscription;
|
import timely.api.request.websocket.SubscriptionRequest;
|
||||||
import timely.api.request.subscription.RemoveSubscription;
|
|
||||||
import timely.api.request.subscription.SubscriptionRequest;
|
|
||||||
import timely.api.response.TimelyException;
|
import timely.api.response.TimelyException;
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
import timely.auth.util.ProxiedEntityUtils;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
|
import timely.balancer.configuration.BalancerWebsocketProperties;
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
import timely.balancer.connection.ws.WsClientPool;
|
import timely.balancer.connection.ws.WsClientPool;
|
||||||
import timely.balancer.resolver.MetricResolver;
|
|
||||||
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
import timely.client.websocket.subscription.WebSocketSubscriptionClient;
|
||||||
import timely.netty.http.TimelyHttpHandler;
|
import timely.netty.http.TimelyHttpHandler;
|
||||||
|
|
||||||
public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequest> implements TimelyHttpHandler {
|
public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequest> implements TimelyHttpHandler {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WsRelayHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(WsRelayHandler.class);
|
||||||
|
|
||||||
private final BalancerConfiguration balancerConfig;
|
private BalancerWebsocketProperties balancerWebsocketProperties;
|
||||||
private final WsClientPool wsClientPool;
|
private WsClientPool wsClientPool;
|
||||||
private MetricResolver metricResolver;
|
private MetricResolver metricResolver;
|
||||||
static private ObjectMapper mapper;
|
static private ObjectMapper mapper;
|
||||||
Map<String, Map<String, WsClientHolder>> wsClients = new ConcurrentHashMap<>();
|
Map<String,Map<String,WsClientHolder>> wsClients = new ConcurrentHashMap<>();
|
||||||
Map<String, ChannelHandlerContext> wsSubscriptions = new ConcurrentHashMap<>();
|
Map<String,ChannelHandlerContext> wsSubscriptions = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
mapper = new ObjectMapper();
|
mapper = new ObjectMapper();
|
||||||
@@ -50,9 +54,8 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
|
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public WsRelayHandler(BalancerConfiguration balancerConfig, MetricResolver metricResolver,
|
public WsRelayHandler(BalancerWebsocketProperties balancerWebsocketProperties, MetricResolver metricResolver, WsClientPool wsClientPool) {
|
||||||
WsClientPool wsClientPool) {
|
this.balancerWebsocketProperties = balancerWebsocketProperties;
|
||||||
this.balancerConfig = balancerConfig;
|
|
||||||
this.metricResolver = metricResolver;
|
this.metricResolver = metricResolver;
|
||||||
this.wsClientPool = wsClientPool;
|
this.wsClientPool = wsClientPool;
|
||||||
}
|
}
|
||||||
@@ -64,6 +67,10 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
String subscriptionId;
|
String subscriptionId;
|
||||||
try {
|
try {
|
||||||
String metric = null;
|
String metric = null;
|
||||||
|
|
||||||
|
Multimap<String,String> headers = msg.getRequestHeaders();
|
||||||
|
ProxiedEntityUtils.addProxyHeaders(headers, msg.getToken().getClientCert());
|
||||||
|
|
||||||
if (msg instanceof CreateSubscription) {
|
if (msg instanceof CreateSubscription) {
|
||||||
CreateSubscription create = (CreateSubscription) msg;
|
CreateSubscription create = (CreateSubscription) msg;
|
||||||
final String currentSubscriptionId = create.getSubscriptionId();
|
final String currentSubscriptionId = create.getSubscriptionId();
|
||||||
@@ -77,14 +84,13 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void operationComplete(ChannelFuture future) throws Exception {
|
public void operationComplete(ChannelFuture future) throws Exception {
|
||||||
Map<String, WsClientHolder> metricToClientMap = wsClients.get(currentSubscriptionId);
|
Map<String,WsClientHolder> metricToClientMap = wsClients.get(currentSubscriptionId);
|
||||||
|
|
||||||
if (metricToClientMap != null) {
|
if (metricToClientMap != null) {
|
||||||
synchronized (metricToClientMap) {
|
synchronized (metricToClientMap) {
|
||||||
// close all clients for this subscriptionId
|
// close all clients for this subscriptionId
|
||||||
LOG.info("Channel closed, closing subscriptions for subscriptionId:%s",
|
log.debug("Channel closed, closing subscriptions for subscriptionId:{}", currentSubscriptionId);
|
||||||
currentSubscriptionId);
|
for (Map.Entry<String,WsClientHolder> entry : metricToClientMap.entrySet()) {
|
||||||
for (Map.Entry<String, WsClientHolder> entry : metricToClientMap.entrySet()) {
|
|
||||||
entry.getValue().close(wsClientPool);
|
entry.getValue().close(wsClientPool);
|
||||||
}
|
}
|
||||||
wsClients.remove(currentSubscriptionId);
|
wsClients.remove(currentSubscriptionId);
|
||||||
@@ -102,12 +108,10 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
if (origContext == null) {
|
if (origContext == null) {
|
||||||
// send error because user never sent a CreateSubscription
|
// send error because user never sent a CreateSubscription
|
||||||
// and we have nowhere to send the results
|
// and we have nowhere to send the results
|
||||||
LOG.info("ChannelHandlerContext not found for subscriptionId:%s - createSubscription not called?",
|
log.info("ChannelHandlerContext not found for subscriptionId:{} - createSubscription not called?", subscriptionId);
|
||||||
subscriptionId);
|
sendErrorResponse(ctx, HttpResponseStatus.BAD_REQUEST, new IllegalArgumentException("Must call create first"));
|
||||||
sendErrorResponse(ctx, HttpResponseStatus.BAD_REQUEST,
|
|
||||||
new IllegalArgumentException("Must call create first"));
|
|
||||||
}
|
}
|
||||||
Map<String, WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
Map<String,WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
||||||
if (metricToClientMap == null) {
|
if (metricToClientMap == null) {
|
||||||
metricToClientMap = new HashMap<>();
|
metricToClientMap = new HashMap<>();
|
||||||
wsClients.put(subscriptionId, metricToClientMap);
|
wsClients.put(subscriptionId, metricToClientMap);
|
||||||
@@ -118,13 +122,13 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
if (hostClientHolder == null) {
|
if (hostClientHolder == null) {
|
||||||
k = metricResolver.getHostPortKey(metric);
|
k = metricResolver.getHostPortKey(metric);
|
||||||
client = wsClientPool.borrowObject(k);
|
client = wsClientPool.borrowObject(k);
|
||||||
client.open(new WsClientHandler(origContext, (balancerConfig.getWebsocket().getTimeout() / 2)));
|
client.open(new WsClientHandler(origContext, add.getToken(), (balancerWebsocketProperties.getTimeout() / 2)));
|
||||||
metricToClientMap.put(metric, new WsClientHolder(k, client));
|
metricToClientMap.put(metric, new WsClientHolder(k, client));
|
||||||
} else {
|
} else {
|
||||||
client = hostClientHolder.getClient();
|
client = hostClientHolder.getClient();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Map<String, String> tags = null;
|
Map<String,String> tags = null;
|
||||||
|
|
||||||
Long startTime = 0L;
|
Long startTime = 0L;
|
||||||
Long endTime = 0L;
|
Long endTime = 0L;
|
||||||
@@ -148,25 +152,25 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
RemoveSubscription remove = (RemoveSubscription) msg;
|
RemoveSubscription remove = (RemoveSubscription) msg;
|
||||||
metric = remove.getMetric();
|
metric = remove.getMetric();
|
||||||
subscriptionId = remove.getSubscriptionId();
|
subscriptionId = remove.getSubscriptionId();
|
||||||
Map<String, WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
Map<String,WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
||||||
if (metricToClientMap != null) {
|
if (metricToClientMap != null) {
|
||||||
synchronized (metricToClientMap) {
|
synchronized (metricToClientMap) {
|
||||||
WsClientHolder hostClientHolder = metricToClientMap.get(metric);
|
WsClientHolder hostClientHolder = metricToClientMap.get(metric);
|
||||||
if (hostClientHolder != null) {
|
if (hostClientHolder != null) {
|
||||||
hostClientHolder.getClient().removeSubscription(metric);
|
hostClientHolder.getClient().removeSubscription(metric);
|
||||||
} else {
|
} else {
|
||||||
LOG.info("client not found for subscriptionId:%s metric:%s", subscriptionId, metric);
|
log.info("client not found for subscriptionId:{} metric:{}", subscriptionId, metric);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (msg instanceof CloseSubscription) {
|
} else if (msg instanceof CloseSubscription) {
|
||||||
CloseSubscription close = (CloseSubscription) msg;
|
CloseSubscription close = (CloseSubscription) msg;
|
||||||
subscriptionId = close.getSubscriptionId();
|
subscriptionId = close.getSubscriptionId();
|
||||||
Map<String, WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
Map<String,WsClientHolder> metricToClientMap = wsClients.get(subscriptionId);
|
||||||
if (metricToClientMap != null) {
|
if (metricToClientMap != null) {
|
||||||
synchronized (metricToClientMap) {
|
synchronized (metricToClientMap) {
|
||||||
// close all clients for this subscriptionId
|
// close all clients for this subscriptionId
|
||||||
for (Map.Entry<String, WsClientHolder> entry : metricToClientMap.entrySet()) {
|
for (Map.Entry<String,WsClientHolder> entry : metricToClientMap.entrySet()) {
|
||||||
entry.getValue().close(wsClientPool);
|
entry.getValue().close(wsClientPool);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -176,11 +180,11 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
ctx.writeAndFlush(new CloseWebSocketFrame(1000, "Client requested close."));
|
ctx.writeAndFlush(new CloseWebSocketFrame(1000, "Client requested close."));
|
||||||
}
|
}
|
||||||
} catch (ConnectException e1) {
|
} catch (ConnectException e1) {
|
||||||
LOG.error(e1.getMessage(), e1);
|
log.error(e1.getMessage(), e1);
|
||||||
ChannelHandlerContext errorCtx = origContext == null ? ctx : origContext;
|
ChannelHandlerContext errorCtx = origContext == null ? ctx : origContext;
|
||||||
sendErrorResponse(errorCtx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e1);
|
sendErrorResponse(errorCtx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e1);
|
||||||
} catch (Exception e2) {
|
} catch (Exception e2) {
|
||||||
LOG.error(e2.getMessage(), e2);
|
log.error(e2.getMessage(), e2);
|
||||||
ChannelHandlerContext errorCtx = origContext == null ? ctx : origContext;
|
ChannelHandlerContext errorCtx = origContext == null ? ctx : origContext;
|
||||||
sendErrorResponse(errorCtx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e2);
|
sendErrorResponse(errorCtx, HttpResponseStatus.INTERNAL_SERVER_ERROR, e2);
|
||||||
}
|
}
|
||||||
@@ -194,7 +198,7 @@ public class WsRelayHandler extends SimpleChannelInboundHandler<SubscriptionRequ
|
|||||||
String json = mapper.writeValueAsString(te);
|
String json = mapper.writeValueAsString(te);
|
||||||
ctx.writeAndFlush(new TextWebSocketFrame(json));
|
ctx.writeAndFlush(new TextWebSocketFrame(json));
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JsonProcessingException e) {
|
||||||
LOG.error("Error serializing exception");
|
log.error("Error serializing exception");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,893 +0,0 @@
|
|||||||
package timely.balancer.resolver;
|
|
||||||
|
|
||||||
import static timely.Server.SERVICE_DISCOVERY_PATH;
|
|
||||||
import static timely.balancer.Balancer.ASSIGNMENTS_LAST_UPDATED_PATH;
|
|
||||||
import static timely.balancer.Balancer.ASSIGNMENTS_LOCK_PATH;
|
|
||||||
import static timely.balancer.Balancer.LEADER_LATCH_PATH;
|
|
||||||
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Random;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.Timer;
|
|
||||||
import java.util.TimerTask;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
|
||||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|
||||||
|
|
||||||
import com.csvreader.CsvReader;
|
|
||||||
import com.csvreader.CsvWriter;
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
import org.apache.curator.RetryPolicy;
|
|
||||||
import org.apache.curator.framework.CuratorFramework;
|
|
||||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
|
||||||
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
|
|
||||||
import org.apache.curator.framework.recipes.cache.TreeCache;
|
|
||||||
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
|
|
||||||
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
|
|
||||||
import org.apache.curator.framework.recipes.leader.LeaderLatch;
|
|
||||||
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
|
|
||||||
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
|
|
||||||
import org.apache.curator.framework.state.ConnectionState;
|
|
||||||
import org.apache.curator.retry.RetryUntilElapsed;
|
|
||||||
import org.apache.curator.x.discovery.ServiceCache;
|
|
||||||
import org.apache.curator.x.discovery.ServiceDiscovery;
|
|
||||||
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
|
|
||||||
import org.apache.curator.x.discovery.ServiceInstance;
|
|
||||||
import org.apache.curator.x.discovery.details.ServiceCacheListener;
|
|
||||||
import org.apache.hadoop.conf.Configuration;
|
|
||||||
import org.apache.hadoop.fs.FSDataInputStream;
|
|
||||||
import org.apache.hadoop.fs.FSDataOutputStream;
|
|
||||||
import org.apache.hadoop.fs.FileSystem;
|
|
||||||
import org.apache.hadoop.fs.Path;
|
|
||||||
import org.apache.zookeeper.data.Stat;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import timely.ServerDetails;
|
|
||||||
import timely.balancer.ArrivalRate;
|
|
||||||
import timely.balancer.configuration.BalancerConfiguration;
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
|
||||||
import timely.balancer.healthcheck.HealthChecker;
|
|
||||||
|
|
||||||
public class BalancedMetricResolver implements MetricResolver {
|
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(BalancedMetricResolver.class);
|
|
||||||
private Map<String, TimelyBalancedHost> metricToHostMap = new TreeMap<>();
|
|
||||||
private Map<String, ArrivalRate> metricMap = new HashMap<>();
|
|
||||||
private ReentrantReadWriteLock balancerLock = new ReentrantReadWriteLock();
|
|
||||||
private List<TimelyBalancedHost> serverList = new ArrayList<>();
|
|
||||||
private Random r = new Random();
|
|
||||||
final private HealthChecker healthChecker;
|
|
||||||
private Timer timer = new Timer("RebalanceTimer", true);
|
|
||||||
private Timer arrivalRateTimer = new Timer("AriivalRateTimerResolver", true);
|
|
||||||
private int roundRobinCounter = 0;
|
|
||||||
private Set<String> nonCachedMetrics = new HashSet<>();
|
|
||||||
private ReentrantReadWriteLock nonCachedMetricsLock = new ReentrantReadWriteLock();
|
|
||||||
private BalancerConfiguration balancerConfig;
|
|
||||||
private CuratorFramework curatorFramework;
|
|
||||||
private RetryPolicy retryPolicy = new RetryUntilElapsed(60000, 1000);
|
|
||||||
private LeaderLatch leaderLatch;
|
|
||||||
private AtomicBoolean isLeader = new AtomicBoolean(false);
|
|
||||||
private InterProcessReadWriteLock assignmentsLock;
|
|
||||||
private DistributedAtomicLong assignmentsLastUpdatedInHdfs;
|
|
||||||
private AtomicLong assignmentsLastUpdatedLocal = new AtomicLong(0);
|
|
||||||
|
|
||||||
private String[] zkPaths = new String[] { LEADER_LATCH_PATH, ASSIGNMENTS_LAST_UPDATED_PATH, ASSIGNMENTS_LOCK_PATH,
|
|
||||||
SERVICE_DISCOVERY_PATH };
|
|
||||||
|
|
||||||
private enum BalanceType {
|
|
||||||
HIGH_LOW, HIGH_AVG, AVG_LOW;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BalancedMetricResolver(BalancerConfiguration balancerConfig, HealthChecker healthChecker) {
|
|
||||||
this.balancerConfig = balancerConfig;
|
|
||||||
this.healthChecker = healthChecker;
|
|
||||||
|
|
||||||
// start curator framework
|
|
||||||
curatorFramework = CuratorFrameworkFactory.newClient(balancerConfig.getZooKeeper().getServers(), 30000, 1000,
|
|
||||||
retryPolicy);
|
|
||||||
curatorFramework.start();
|
|
||||||
ensureZkPaths(curatorFramework, zkPaths);
|
|
||||||
assignmentsLock = new InterProcessReadWriteLock(curatorFramework, ASSIGNMENTS_LOCK_PATH);
|
|
||||||
startLeaderLatch(curatorFramework);
|
|
||||||
startServiceListener(curatorFramework);
|
|
||||||
assignmentsLastUpdatedInHdfs = new DistributedAtomicLong(curatorFramework, ASSIGNMENTS_LAST_UPDATED_PATH,
|
|
||||||
retryPolicy);
|
|
||||||
|
|
||||||
TreeCacheListener listener = new TreeCacheListener() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
|
|
||||||
LOG.info("Handling event {}. assignmentsLastUpdatedInHdfs:{}", event.getType().toString(),
|
|
||||||
new Date(assignmentsLastUpdatedInHdfs.get().postValue()));
|
|
||||||
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
|
|
||||||
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 treeCache = new TreeCache(curatorFramework, ASSIGNMENTS_LAST_UPDATED_PATH);
|
|
||||||
treeCache.getListenable().addListener(listener);
|
|
||||||
treeCache.start();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
|
|
||||||
nonCachedMetricsLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
nonCachedMetrics.addAll(balancerConfig.getCache().getNonCachedMetrics());
|
|
||||||
} finally {
|
|
||||||
nonCachedMetricsLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
readAssignmentsFromHdfs();
|
|
||||||
|
|
||||||
timer.schedule(new TimerTask() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
if (isLeader.get()) {
|
|
||||||
try {
|
|
||||||
balance();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 900000, 900000);
|
|
||||||
|
|
||||||
timer.schedule(new TimerTask() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
try {
|
|
||||||
if (isLeader.get()) {
|
|
||||||
long lastLocalUpdate = assignmentsLastUpdatedLocal.get();
|
|
||||||
long lastHdfsUpdate = assignmentsLastUpdatedInHdfs.get().postValue();
|
|
||||||
if (lastLocalUpdate > lastHdfsUpdate) {
|
|
||||||
LOG.info("Writing assignments to hdfs lastLocalUpdate ({}) > lastHdfsUpdate ({})",
|
|
||||||
new Date(lastLocalUpdate), new Date(lastHdfsUpdate));
|
|
||||||
writeAssigmentsToHdfs();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 10000, 60000);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ensureZkPaths(CuratorFramework curatorFramework, String[] paths) {
|
|
||||||
for (String s : paths) {
|
|
||||||
try {
|
|
||||||
Stat stat = curatorFramework.checkExists().forPath(s);
|
|
||||||
if (stat == null) {
|
|
||||||
curatorFramework.create().creatingParentContainersIfNeeded().forPath(s);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.info(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startLeaderLatch(CuratorFramework curatorFramework) {
|
|
||||||
try {
|
|
||||||
|
|
||||||
this.leaderLatch = new LeaderLatch(curatorFramework, LEADER_LATCH_PATH);
|
|
||||||
this.leaderLatch.start();
|
|
||||||
this.leaderLatch.addListener(new LeaderLatchListener() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void isLeader() {
|
|
||||||
LOG.info("this balancer is the leader");
|
|
||||||
isLeader.set(true);
|
|
||||||
writeAssigmentsToHdfs();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void notLeader() {
|
|
||||||
LOG.info("this balancer is not the leader");
|
|
||||||
isLeader.set(false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void startServiceListener(CuratorFramework curatorFramework) {
|
|
||||||
try {
|
|
||||||
ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class).client(curatorFramework)
|
|
||||||
.basePath(SERVICE_DISCOVERY_PATH).build();
|
|
||||||
discovery.start();
|
|
||||||
Collection<ServiceInstance> instances = discovery.queryForInstances("timely-server");
|
|
||||||
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
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(),
|
|
||||||
pl.getHost(), pl.getTcpPort(), pl.getHttpPort(), pl.getWsPort(), pl.getUdpPort());
|
|
||||||
tbh.setBalancerConfig(balancerConfig);
|
|
||||||
serverList.add(tbh);
|
|
||||||
}
|
|
||||||
healthChecker.setTimelyHosts(serverList);
|
|
||||||
} finally {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
final ServiceCache serviceCache = discovery.serviceCacheBuilder().name("timely-server").build();
|
|
||||||
ServiceCacheListener listener = new ServiceCacheListener() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void cacheChanged() {
|
|
||||||
boolean rebalanceNeeded = false;
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
List<ServiceInstance> instances = serviceCache.getInstances();
|
|
||||||
Set<TimelyBalancedHost> availableHosts = new HashSet<>();
|
|
||||||
for (ServiceInstance si : instances) {
|
|
||||||
ServerDetails pl = (ServerDetails) si.getPayload();
|
|
||||||
TimelyBalancedHost tbh = TimelyBalancedHost.of(pl.getHost(), pl.getTcpPort(),
|
|
||||||
pl.getHttpPort(), pl.getWsPort(), pl.getUdpPort());
|
|
||||||
tbh.setBalancerConfig(balancerConfig);
|
|
||||||
availableHosts.add(tbh);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<String> reassignMetrics = new ArrayList<>();
|
|
||||||
// remove hosts that are no longer available
|
|
||||||
Iterator<TimelyBalancedHost> itr = serverList.iterator();
|
|
||||||
while (itr.hasNext()) {
|
|
||||||
TimelyBalancedHost h = itr.next();
|
|
||||||
if (availableHosts.contains(h)) {
|
|
||||||
availableHosts.remove(h);
|
|
||||||
} else {
|
|
||||||
itr.remove();
|
|
||||||
LOG.info("removing service {}:{} host:{} tcpPort:{} httpPort:{} wsPort:{} udpPort:{}",
|
|
||||||
h.getHost(), h.getTcpPort(), h.getHost(), h.getTcpPort(), h.getHttpPort(),
|
|
||||||
h.getWsPort(), h.getUdpPort());
|
|
||||||
for (Map.Entry<String, TimelyBalancedHost> e : metricToHostMap.entrySet()) {
|
|
||||||
if (e.getValue().equals(h)) {
|
|
||||||
reassignMetrics.add(e.getKey());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rebalanceNeeded = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// add new hosts that were not previously known
|
|
||||||
for (TimelyBalancedHost h : availableHosts) {
|
|
||||||
LOG.info("adding service {}:{} host:{} tcpPort:{} httpPort:{} wsPort:{} udpPort:{}",
|
|
||||||
h.getHost(), h.getTcpPort(), h.getHost(), h.getTcpPort(), h.getHttpPort(),
|
|
||||||
h.getWsPort(), h.getUdpPort());
|
|
||||||
serverList.add(h);
|
|
||||||
rebalanceNeeded = true;
|
|
||||||
}
|
|
||||||
healthChecker.setTimelyHosts(serverList);
|
|
||||||
|
|
||||||
if (isLeader.get()) {
|
|
||||||
for (String s : reassignMetrics) {
|
|
||||||
TimelyBalancedHost h = getRoundRobinHost(null);
|
|
||||||
assignMetric(s, h);
|
|
||||||
LOG.debug("Assigned server removed. Assigning {} to server {}:{}", s, h.getTcpPort());
|
|
||||||
}
|
|
||||||
writeAssigmentsToHdfs();
|
|
||||||
}
|
|
||||||
|
|
||||||
} finally {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
if (isLeader.get() && rebalanceNeeded) {
|
|
||||||
balance();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
|
|
||||||
LOG.info("serviceCache state changed. Connected:{}", connectionState.isConnected());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
serviceCache.addListener(listener);
|
|
||||||
serviceCache.start();
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private TimelyBalancedHost getLeastUsedHost() {
|
|
||||||
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
Map<Double, TimelyBalancedHost> rateSortedHosts = new TreeMap<>();
|
|
||||||
for (TimelyBalancedHost s : serverList) {
|
|
||||||
rateSortedHosts.put(s.getArrivalRate(), s);
|
|
||||||
}
|
|
||||||
|
|
||||||
Iterator<Map.Entry<Double, TimelyBalancedHost>> itr = rateSortedHosts.entrySet().iterator();
|
|
||||||
|
|
||||||
while (itr.hasNext() && tbh == null) {
|
|
||||||
TimelyBalancedHost currentTBH = itr.next().getValue();
|
|
||||||
if (currentTBH.isUp()) {
|
|
||||||
tbh = currentTBH;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TimelyBalancedHost getRandomHost(TimelyBalancedHost notThisOne) {
|
|
||||||
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
for (int x = 0; tbh == null && x < serverList.size(); x++) {
|
|
||||||
tbh = serverList.get(Math.abs(r.nextInt() & Integer.MAX_VALUE) % serverList.size());
|
|
||||||
if (!tbh.isUp()) {
|
|
||||||
tbh = null;
|
|
||||||
} else if (notThisOne != null && tbh.equals(notThisOne)) {
|
|
||||||
tbh = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TimelyBalancedHost getRoundRobinHost(TimelyBalancedHost notThisOne) {
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
int maxAttempts = serverList.size();
|
|
||||||
int currentAttempt = 0;
|
|
||||||
while (tbh == null && currentAttempt < maxAttempts) {
|
|
||||||
try {
|
|
||||||
currentAttempt++;
|
|
||||||
tbh = serverList.get(roundRobinCounter % serverList.size());
|
|
||||||
if (!tbh.isUp()) {
|
|
||||||
tbh = null;
|
|
||||||
}
|
|
||||||
if (notThisOne != null && notThisOne.equals(tbh)) {
|
|
||||||
tbh = null;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
roundRobinCounter++;
|
|
||||||
if (roundRobinCounter == Integer.MAX_VALUE) {
|
|
||||||
roundRobinCounter = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tbh == null) {
|
|
||||||
tbh = getRandomHost(notThisOne);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TimelyBalancedHost chooseHost(Set<TimelyBalancedHost> potentialHosts,
|
|
||||||
Map<TimelyBalancedHost, Double> calculatedRates, double referenceRate, BalanceType balanceType) {
|
|
||||||
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
Map<Long, TimelyBalancedHost> weightedList = new TreeMap<>();
|
|
||||||
long cumulativeWeight = 0;
|
|
||||||
for (TimelyBalancedHost h : potentialHosts) {
|
|
||||||
double currentDiff;
|
|
||||||
if (balanceType.equals(BalanceType.HIGH_LOW) || balanceType.equals(BalanceType.HIGH_AVG)) {
|
|
||||||
currentDiff = referenceRate - calculatedRates.get(h);
|
|
||||||
} else {
|
|
||||||
currentDiff = calculatedRates.get(h) - referenceRate;
|
|
||||||
}
|
|
||||||
cumulativeWeight += Math.round(currentDiff);
|
|
||||||
weightedList.put(cumulativeWeight, h);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cumulativeWeight > 0) {
|
|
||||||
long randomWeight = r.nextLong() % cumulativeWeight;
|
|
||||||
for (Map.Entry<Long, TimelyBalancedHost> e : weightedList.entrySet()) {
|
|
||||||
if (randomWeight <= e.getKey()) {
|
|
||||||
tbh = e.getValue();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int balance() {
|
|
||||||
|
|
||||||
int numReassigned = 0;
|
|
||||||
if (isLeader.get()) {
|
|
||||||
double controlBandPercentage = balancerConfig.getControlBandPercentage();
|
|
||||||
// save current rates so that we can modify
|
|
||||||
double totalArrivalRate = 0;
|
|
||||||
Map<TimelyBalancedHost, Double> calculatedRates = new HashMap<>();
|
|
||||||
for (TimelyBalancedHost h : serverList) {
|
|
||||||
double tbhArrivalRate = h.getArrivalRate();
|
|
||||||
calculatedRates.put(h, tbhArrivalRate);
|
|
||||||
totalArrivalRate += tbhArrivalRate;
|
|
||||||
}
|
|
||||||
double averageArrivalRate = totalArrivalRate / serverList.size();
|
|
||||||
|
|
||||||
Set<TimelyBalancedHost> highHosts = new HashSet<>();
|
|
||||||
Set<TimelyBalancedHost> lowHosts = new HashSet<>();
|
|
||||||
Set<TimelyBalancedHost> avgHosts = new HashSet<>();
|
|
||||||
|
|
||||||
double controlHighLimit = averageArrivalRate * (1.0 + controlBandPercentage);
|
|
||||||
double controlLowLimit = averageArrivalRate * (1.0 - controlBandPercentage);
|
|
||||||
|
|
||||||
for (TimelyBalancedHost h : serverList) {
|
|
||||||
if (h.isUp()) {
|
|
||||||
double currRate = calculatedRates.get(h);
|
|
||||||
if (currRate < controlLowLimit) {
|
|
||||||
lowHosts.add(h);
|
|
||||||
} else if (currRate > controlHighLimit) {
|
|
||||||
highHosts.add(h);
|
|
||||||
} else {
|
|
||||||
avgHosts.add(h);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (highHosts.isEmpty() && lowHosts.isEmpty()) {
|
|
||||||
LOG.info("Host's arrival rates are within {} of the average", controlBandPercentage);
|
|
||||||
} else if (!highHosts.isEmpty() && !lowHosts.isEmpty()) {
|
|
||||||
LOG.info("begin rebalancing {}", BalanceType.HIGH_LOW);
|
|
||||||
numReassigned = rebalance(highHosts, lowHosts, calculatedRates, averageArrivalRate,
|
|
||||||
BalanceType.HIGH_LOW);
|
|
||||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.HIGH_LOW, numReassigned);
|
|
||||||
} else if (lowHosts.isEmpty()) {
|
|
||||||
LOG.info("begin rebalancing {}", BalanceType.HIGH_AVG);
|
|
||||||
numReassigned = rebalance(highHosts, avgHosts, calculatedRates, averageArrivalRate,
|
|
||||||
BalanceType.HIGH_AVG);
|
|
||||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.HIGH_AVG, numReassigned);
|
|
||||||
} else {
|
|
||||||
LOG.info("begin rebalancing {}", BalanceType.AVG_LOW);
|
|
||||||
numReassigned = rebalance(avgHosts, lowHosts, calculatedRates, averageArrivalRate, BalanceType.AVG_LOW);
|
|
||||||
LOG.info("end rebalancing {} - reassigned {}", BalanceType.AVG_LOW, numReassigned);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return numReassigned;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int rebalance(Set<TimelyBalancedHost> losingHosts, Set<TimelyBalancedHost> gainingHosts,
|
|
||||||
Map<TimelyBalancedHost, Double> calculatedRates, double targetArrivalRate, BalanceType balanceType) {
|
|
||||||
|
|
||||||
int numReassigned = 0;
|
|
||||||
if (isLeader.get()) {
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
Map<String, ArrivalRate> tempMetricMap = new HashMap<>();
|
|
||||||
tempMetricMap.putAll(metricMap);
|
|
||||||
|
|
||||||
Set<TimelyBalancedHost> focusedHosts;
|
|
||||||
Set<TimelyBalancedHost> selectFromHosts;
|
|
||||||
if (balanceType.equals(BalanceType.HIGH_LOW) || balanceType.equals(BalanceType.HIGH_AVG)) {
|
|
||||||
focusedHosts = losingHosts;
|
|
||||||
selectFromHosts = gainingHosts;
|
|
||||||
} else {
|
|
||||||
focusedHosts = gainingHosts;
|
|
||||||
selectFromHosts = losingHosts;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (TimelyBalancedHost h : focusedHosts) {
|
|
||||||
double desiredChange;
|
|
||||||
if (balanceType.equals(BalanceType.HIGH_LOW) || balanceType.equals(BalanceType.HIGH_AVG)) {
|
|
||||||
desiredChange = h.getArrivalRate() - targetArrivalRate;
|
|
||||||
} else {
|
|
||||||
desiredChange = targetArrivalRate - h.getArrivalRate();
|
|
||||||
}
|
|
||||||
|
|
||||||
// sort metrics by rate
|
|
||||||
Map<Double, String> rateSortedMetrics = new TreeMap<>(Collections.reverseOrder());
|
|
||||||
for (Map.Entry<String, ArrivalRate> e : tempMetricMap.entrySet()) {
|
|
||||||
if (metricToHostMap.get(e.getKey()).equals(h)) {
|
|
||||||
rateSortedMetrics.put(e.getValue().getRate(), e.getKey());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
LOG.trace("focusHost {}:{} desiredChange:{} rateSortedMetrics.size():{}", h.getHost(),
|
|
||||||
h.getTcpPort(), desiredChange, rateSortedMetrics.size());
|
|
||||||
|
|
||||||
boolean doneWithHost = false;
|
|
||||||
while (!doneWithHost) {
|
|
||||||
Iterator<Map.Entry<Double, String>> itr = rateSortedMetrics.entrySet().iterator();
|
|
||||||
while (!doneWithHost && itr.hasNext()) {
|
|
||||||
Map.Entry<Double, String> e = null;
|
|
||||||
// find largest metric that does not exceed desired change
|
|
||||||
while (e == null && itr.hasNext()) {
|
|
||||||
e = itr.next();
|
|
||||||
if (e.getKey() > desiredChange) {
|
|
||||||
LOG.trace("Skipping:{} rate:{}", e.getValue(), e.getKey());
|
|
||||||
e = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e == null) {
|
|
||||||
LOG.trace("no metric small enough");
|
|
||||||
doneWithHost = true;
|
|
||||||
} else {
|
|
||||||
LOG.trace("Selected:{} rate:{}", e.getValue(), e.getKey());
|
|
||||||
TimelyBalancedHost candidateHost = chooseHost(selectFromHosts, calculatedRates,
|
|
||||||
calculatedRates.get(h), balanceType);
|
|
||||||
if (candidateHost == null) {
|
|
||||||
LOG.trace("candidate host is null");
|
|
||||||
doneWithHost = true;
|
|
||||||
} else {
|
|
||||||
String metric = e.getValue();
|
|
||||||
Double metricRate = e.getKey();
|
|
||||||
assignMetric(metric, candidateHost);
|
|
||||||
numReassigned++;
|
|
||||||
calculatedRates.put(candidateHost, calculatedRates.get(candidateHost) + metricRate);
|
|
||||||
calculatedRates.put(h, calculatedRates.get(h) - metricRate);
|
|
||||||
desiredChange -= metricRate;
|
|
||||||
// don't move this metric again this host or balance
|
|
||||||
itr.remove();
|
|
||||||
tempMetricMap.remove(metric);
|
|
||||||
LOG.info(
|
|
||||||
"rebalancing: reassigning metric:{} rate:{} from server {}:{} to {}:{} remaining delta {}",
|
|
||||||
metric, metricRate, h.getHost(), h.getTcpPort(), candidateHost.getHost(),
|
|
||||||
candidateHost.getTcpPort(), desiredChange);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!itr.hasNext()) {
|
|
||||||
LOG.trace("Reached end or rateSortedMetrics");
|
|
||||||
doneWithHost = true;
|
|
||||||
}
|
|
||||||
if (balanceType.equals(BalanceType.HIGH_LOW) || balanceType.equals(BalanceType.HIGH_AVG)) {
|
|
||||||
if (calculatedRates.get(h) <= targetArrivalRate) {
|
|
||||||
doneWithHost = true;
|
|
||||||
LOG.trace("calculatedRates.get(h) <= targetArivalRate");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (calculatedRates.get(h) >= targetArrivalRate) {
|
|
||||||
doneWithHost = true;
|
|
||||||
LOG.trace("calculatedRates.get(h) >= targetArivalRate");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return numReassigned;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean shouldCache(String metricName) {
|
|
||||||
|
|
||||||
if (StringUtils.isBlank(metricName)) {
|
|
||||||
return false;
|
|
||||||
} else {
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
if (metricToHostMap.containsKey(metricName)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
nonCachedMetricsLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
if (nonCachedMetrics.contains(metricName)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (String r : nonCachedMetrics) {
|
|
||||||
if (metricName.matches(r)) {
|
|
||||||
LOG.info("Adding {} to list of non-cached metrics", metricName);
|
|
||||||
nonCachedMetricsLock.readLock().unlock();
|
|
||||||
nonCachedMetricsLock.writeLock().lock();
|
|
||||||
nonCachedMetrics.add(metricName);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (nonCachedMetricsLock.isWriteLockedByCurrentThread()) {
|
|
||||||
nonCachedMetricsLock.writeLock().unlock();
|
|
||||||
} else {
|
|
||||||
nonCachedMetricsLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public TimelyBalancedHost getHostPortKeyIngest(String metric) {
|
|
||||||
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
boolean chooseMetricSpecificHost;
|
|
||||||
try {
|
|
||||||
chooseMetricSpecificHost = shouldCache(metric) ? true : false;
|
|
||||||
if (chooseMetricSpecificHost) {
|
|
||||||
ArrivalRate rate = metricMap.get(metric);
|
|
||||||
if (rate == null) {
|
|
||||||
rate = new ArrivalRate(arrivalRateTimer);
|
|
||||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
metricMap.put(metric, rate);
|
|
||||||
}
|
|
||||||
rate.arrived();
|
|
||||||
} else {
|
|
||||||
metric = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isBlank(metric)) {
|
|
||||||
tbh = getRandomHost(null);
|
|
||||||
} else {
|
|
||||||
tbh = metricToHostMap.get(metric);
|
|
||||||
if (tbh == null) {
|
|
||||||
tbh = getRoundRobinHost(null);
|
|
||||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
assignMetric(metric, tbh);
|
|
||||||
} else if (!tbh.isUp()) {
|
|
||||||
TimelyBalancedHost oldTbh = tbh;
|
|
||||||
tbh = getLeastUsedHost();
|
|
||||||
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();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
assignMetric(metric, tbh);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if all else fails
|
|
||||||
if (tbh == null || !tbh.isUp()) {
|
|
||||||
for (TimelyBalancedHost h : serverList) {
|
|
||||||
if (h.isUp()) {
|
|
||||||
tbh = h;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tbh != null && StringUtils.isNotBlank(metric)) {
|
|
||||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
assignMetric(metric, tbh);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
} else {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tbh != null && chooseMetricSpecificHost) {
|
|
||||||
tbh.arrived();
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public TimelyBalancedHost getHostPortKey(String metric) {
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
boolean chooseMetricSpecificHost = shouldCache(metric) ? true : false;
|
|
||||||
if (chooseMetricSpecificHost) {
|
|
||||||
tbh = metricToHostMap.get(metric);
|
|
||||||
} else {
|
|
||||||
metric = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tbh == null || !tbh.isUp()) {
|
|
||||||
for (int x = 0; tbh == null && x < serverList.size(); x++) {
|
|
||||||
tbh = serverList.get(Math.abs(r.nextInt() & Integer.MAX_VALUE) % serverList.size());
|
|
||||||
if (!tbh.isUp()) {
|
|
||||||
tbh = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tbh != null && StringUtils.isNotBlank(metric)) {
|
|
||||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
assignMetric(metric, tbh);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if all else fails
|
|
||||||
if (tbh == null || !tbh.isUp()) {
|
|
||||||
for (TimelyBalancedHost h : serverList) {
|
|
||||||
if (h.isUp()) {
|
|
||||||
tbh = h;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tbh != null && StringUtils.isNotBlank(metric)) {
|
|
||||||
if (!balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
}
|
|
||||||
assignMetric(metric, tbh);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (balancerLock.isWriteLockedByCurrentThread()) {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
} else {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TimelyBalancedHost findHost(String host, int tcpPort) {
|
|
||||||
TimelyBalancedHost tbh = null;
|
|
||||||
for (TimelyBalancedHost h : serverList) {
|
|
||||||
if (h.getHost().equals(host) && h.getTcpPort() == tcpPort) {
|
|
||||||
tbh = h;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tbh;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void readAssignmentsFromHdfs() {
|
|
||||||
|
|
||||||
Map<String, TimelyBalancedHost> assignedMetricToHostMap = new TreeMap<>();
|
|
||||||
try {
|
|
||||||
assignmentsLock.readLock().acquire();
|
|
||||||
Configuration configuration = new Configuration();
|
|
||||||
FileSystem fs = FileSystem.get(configuration);
|
|
||||||
Path assignmentFile = new Path(balancerConfig.getAssignmentFile());
|
|
||||||
FSDataInputStream iStream = fs.open(assignmentFile);
|
|
||||||
|
|
||||||
CsvReader reader = new CsvReader(iStream, ',', Charset.forName("UTF-8"));
|
|
||||||
reader.setUseTextQualifier(false);
|
|
||||||
|
|
||||||
// skip the headers
|
|
||||||
boolean success = true;
|
|
||||||
success = reader.readHeaders();
|
|
||||||
|
|
||||||
while (success) {
|
|
||||||
success = reader.readRecord();
|
|
||||||
String[] nextLine = reader.getValues();
|
|
||||||
if (nextLine.length >= 3) {
|
|
||||||
String metric = nextLine[0];
|
|
||||||
String host = nextLine[1];
|
|
||||||
int tcpPort = Integer.parseInt(nextLine[2]);
|
|
||||||
TimelyBalancedHost tbh = findHost(host, tcpPort);
|
|
||||||
if (tbh == null) {
|
|
||||||
tbh = getRoundRobinHost(null);
|
|
||||||
} else {
|
|
||||||
LOG.trace("Found assigment: {} to {}:{}", metric, host, tcpPort);
|
|
||||||
}
|
|
||||||
assignedMetricToHostMap.put(metric, tbh);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
metricToHostMap.clear();
|
|
||||||
for (Map.Entry<String, TimelyBalancedHost> e : assignedMetricToHostMap.entrySet()) {
|
|
||||||
if (shouldCache(e.getKey())) {
|
|
||||||
metricToHostMap.put(e.getKey(), e.getValue());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
assignmentsLastUpdatedLocal.set(assignmentsLastUpdatedInHdfs.get().postValue());
|
|
||||||
LOG.info("Read {} assignments from hdfs lastHdfsUpdate = lastLocalUpdate ({})", metricToHostMap.size(),
|
|
||||||
new Date(assignmentsLastUpdatedLocal.get()));
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
} finally {
|
|
||||||
try {
|
|
||||||
assignmentsLock.readLock().release();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void writeAssigmentsToHdfs() {
|
|
||||||
|
|
||||||
CsvWriter writer = null;
|
|
||||||
try {
|
|
||||||
assignmentsLock.writeLock().acquire();
|
|
||||||
balancerLock.readLock().lock();
|
|
||||||
try {
|
|
||||||
if (!metricToHostMap.isEmpty()) {
|
|
||||||
Configuration configuration = new Configuration();
|
|
||||||
FileSystem fs = FileSystem.get(configuration);
|
|
||||||
Path assignmentFile = new Path(balancerConfig.getAssignmentFile());
|
|
||||||
if (!fs.exists(assignmentFile.getParent())) {
|
|
||||||
fs.mkdirs(assignmentFile.getParent());
|
|
||||||
}
|
|
||||||
FSDataOutputStream oStream = fs.create(assignmentFile, true);
|
|
||||||
writer = new CsvWriter(oStream, ',', Charset.forName("UTF-8"));
|
|
||||||
writer.setUseTextQualifier(false);
|
|
||||||
writer.write("metric");
|
|
||||||
writer.write("host");
|
|
||||||
writer.write("tcpPort");
|
|
||||||
writer.endRecord();
|
|
||||||
for (Map.Entry<String, TimelyBalancedHost> e : metricToHostMap.entrySet()) {
|
|
||||||
writer.write(e.getKey());
|
|
||||||
writer.write(e.getValue().getHost());
|
|
||||||
writer.write(Integer.toString(e.getValue().getTcpPort()));
|
|
||||||
writer.endRecord();
|
|
||||||
LOG.trace("Saving assigment: {} to {}:{}", e.getKey(), e.getValue().getHost(),
|
|
||||||
e.getValue().getTcpPort());
|
|
||||||
}
|
|
||||||
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
assignmentsLastUpdatedLocal.set(now);
|
|
||||||
assignmentsLastUpdatedInHdfs.trySet(now);
|
|
||||||
if (!assignmentsLastUpdatedInHdfs.get().succeeded()) {
|
|
||||||
assignmentsLastUpdatedInHdfs.forceSet(now);
|
|
||||||
}
|
|
||||||
LOG.info("Wrote {} assignments to hdfs lastHdfsUpdate = lastLocalUpdate ({})",
|
|
||||||
metricToHostMap.size(), new Date(assignmentsLastUpdatedLocal.get()));
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
balancerLock.readLock().unlock();
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
} finally {
|
|
||||||
if (writer != null) {
|
|
||||||
writer.close();
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
assignmentsLock.writeLock().release();
|
|
||||||
} catch (Exception e) {
|
|
||||||
LOG.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void assignMetric(String metric, TimelyBalancedHost tbh) {
|
|
||||||
if (isLeader.get()) {
|
|
||||||
balancerLock.writeLock().lock();
|
|
||||||
try {
|
|
||||||
metricToHostMap.put(metric, tbh);
|
|
||||||
assignmentsLastUpdatedLocal.set(System.currentTimeMillis());
|
|
||||||
} finally {
|
|
||||||
balancerLock.writeLock().unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package timely.balancer.resolver;
|
|
||||||
|
|
||||||
import timely.balancer.connection.TimelyBalancedHost;
|
|
||||||
|
|
||||||
public interface MetricResolver {
|
|
||||||
|
|
||||||
public TimelyBalancedHost getHostPortKeyIngest(String metric);
|
|
||||||
|
|
||||||
public TimelyBalancedHost getHostPortKey(String metric);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
===============================================================================
|
||||||
|
_______ _ _ ____ _
|
||||||
|
|__ __(_) | | | _ \ | |
|
||||||
|
| | _ _ __ ___ ___| |_ _ | |_) | __ _| | __ _ _ __ ___ ___ _ __
|
||||||
|
| | | | '_ ` _ \ / _ \ | | | | | _ < / _` | |/ _` | '_ \ / __/ _ \ '__|
|
||||||
|
| | | | | | | | | __/ | |_| | | |_) | (_| | | (_| | | | | (_| __/ |
|
||||||
|
|_| |_|_| |_| |_|\___|_|\__, | |____/ \__,_|_|\__,_|_| |_|\___\___|_|
|
||||||
|
__/ |
|
||||||
|
|___/
|
||||||
|
===============================================================================
|
||||||
|
TimelyBalancer ${application.formatted-version}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: timely-balancer
|
||||||
|
config:
|
||||||
|
name: timely-balancer
|
||||||
|
location: ${CONF_DIR}/
|
||||||
@@ -10,4 +10,12 @@
|
|||||||
<Method name="getBuf" />
|
<Method name="getBuf" />
|
||||||
<Bug pattern="EI_EXPOSE_REP" />
|
<Bug pattern="EI_EXPOSE_REP" />
|
||||||
</Match>
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<!-- these are probably avoidable, but needs further triage to fix -->
|
||||||
|
<Bug pattern="EI_EXPOSE_REP" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<!-- these are probably avoidable, but needs further triage to fix -->
|
||||||
|
<Bug pattern="EI_EXPOSE_REP2" />
|
||||||
|
</Match>
|
||||||
</FindBugsFilter>
|
</FindBugsFilter>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package timely.balancer.configuration;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import io.netty.handler.ssl.SslContext;
|
||||||
|
import timely.balancer.HealthChecker;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
|
import timely.balancer.test.TestBalancer;
|
||||||
|
import timely.balancer.test.TestHealthChecker;
|
||||||
|
import timely.balancer.test.TestMetricResolver;
|
||||||
|
import timely.common.component.AuthenticationService;
|
||||||
|
import timely.common.configuration.CacheProperties;
|
||||||
|
import timely.common.configuration.SecurityProperties;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
import timely.common.configuration.SslServerProperties;
|
||||||
|
import timely.common.configuration.ZookeeperProperties;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ComponentScan(basePackages = {"timely.balancer", "timely.common", "timely.test"})
|
||||||
|
public class TestBalancerConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TestBalancer balancer(ApplicationContext applicationContext, @Qualifier("nettySslContext") SslContext serverSslContext,
|
||||||
|
@Qualifier("outboundJDKSslContext") SSLContext clientSSLContext, AuthenticationService authenticationService, MetricResolver metricResolver,
|
||||||
|
BalancerProperties balancerProperties, ZookeeperProperties zookeeperProperties, SecurityProperties securityProperties,
|
||||||
|
SslServerProperties sslServerProperties, SslClientProperties sslClientProperties, BalancerServerProperties balancerServerProperties,
|
||||||
|
BalancerHttpProperties balancerHttpProperties, BalancerWebsocketProperties balancerWebsocketProperties) {
|
||||||
|
TestBalancer balancer = new TestBalancer(applicationContext, serverSslContext, clientSSLContext, authenticationService, metricResolver,
|
||||||
|
balancerProperties, zookeeperProperties, securityProperties, sslServerProperties, sslClientProperties, balancerServerProperties,
|
||||||
|
balancerHttpProperties, balancerWebsocketProperties);
|
||||||
|
balancer.start();
|
||||||
|
return balancer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TestHealthChecker healthChecker(BalancerProperties balancerProperties, BalancerServerProperties balancerServerProperties) {
|
||||||
|
TestHealthChecker healthChecker = new TestHealthChecker(balancerProperties, balancerServerProperties);
|
||||||
|
healthChecker.start();
|
||||||
|
return healthChecker;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public TestMetricResolver metricResolver(CuratorFramework curatorFramework, BalancerProperties balancerProperties, CacheProperties cacheProperties,
|
||||||
|
HealthChecker healthChecker) {
|
||||||
|
TestMetricResolver metricResolver = new TestMetricResolver(curatorFramework, balancerProperties, cacheProperties, healthChecker);
|
||||||
|
metricResolver.start();
|
||||||
|
return metricResolver;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package timely.balancer.configuration;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import org.apache.zookeeper.server.ServerConfig;
|
||||||
|
import org.apache.zookeeper.server.ZooKeeperServerMain;
|
||||||
|
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import timely.common.configuration.ZookeeperProperties;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConditionalOnProperty(name = "timely.in-memory-accumulo.enabled", havingValue = "true")
|
||||||
|
public class TestZookeeperConfiguration {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(TestZookeeperConfiguration.class);
|
||||||
|
private static final int MAX_PORT = 100;
|
||||||
|
private int port;
|
||||||
|
|
||||||
|
private ZookeeperProperties zookeeperProperties;
|
||||||
|
|
||||||
|
@Bean(name = "ZooKeeperServerMain", destroyMethod = "close")
|
||||||
|
public ZooKeeperServerMain zooKeeperServerMain(ZookeeperProperties zookeeperProperties) throws Exception {
|
||||||
|
this.zookeeperProperties = zookeeperProperties;
|
||||||
|
this.port = getNextPort(2181);
|
||||||
|
this.zookeeperProperties.setServers(String.format("localhost:%d", port));
|
||||||
|
|
||||||
|
File tempDir;
|
||||||
|
try {
|
||||||
|
tempDir = Files.createTempDirectory("zookeeper_temp").toFile();
|
||||||
|
tempDir.deleteOnExit();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("Unable to create temp directory for mini accumulo cluster");
|
||||||
|
}
|
||||||
|
|
||||||
|
Properties properties = new Properties();
|
||||||
|
properties.put("dataDir", tempDir.getAbsolutePath() + "/data");
|
||||||
|
properties.put("clientPort", port);
|
||||||
|
properties.put("skipACL", "true");
|
||||||
|
properties.put("leaderServes", "yes");
|
||||||
|
properties.put("4lw.commands.whitelist", "*");
|
||||||
|
properties.put("admin.enableServer", "false");
|
||||||
|
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
|
||||||
|
quorumPeerConfig.parseProperties(properties);
|
||||||
|
|
||||||
|
ZooKeeperServerMain zookeeper = new ZooKeeperServerMain();
|
||||||
|
final ServerConfig config = new ServerConfig();
|
||||||
|
config.readFrom(quorumPeerConfig);
|
||||||
|
Executors.newSingleThreadExecutor().submit(() -> {
|
||||||
|
try {
|
||||||
|
zookeeper.runFromConfig(config);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
log.info("Started TestZookeeper on port {}", port);
|
||||||
|
return zookeeper;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getNextPort(int start) {
|
||||||
|
for (int port = start; port < start + MAX_PORT; ++port) {
|
||||||
|
try {
|
||||||
|
new ServerSocket(port).close();
|
||||||
|
return port;
|
||||||
|
} catch (IOException e) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package timely.balancer.integration;
|
||||||
|
|
||||||
|
import static timely.Constants.SERVICE_DISCOVERY_PATH;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.curator.framework.state.ConnectionState;
|
||||||
|
import org.apache.curator.x.discovery.ServiceCache;
|
||||||
|
import org.apache.curator.x.discovery.ServiceDiscovery;
|
||||||
|
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
|
||||||
|
import org.apache.curator.x.discovery.ServiceInstance;
|
||||||
|
import org.apache.curator.x.discovery.ServiceInstanceBuilder;
|
||||||
|
import org.apache.curator.x.discovery.details.ServiceCacheListener;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.experimental.categories.Category;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
|
||||||
|
import timely.ServerDetails;
|
||||||
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
import timely.balancer.test.TestHealthChecker;
|
||||||
|
import timely.balancer.test.TestMetricResolver;
|
||||||
|
import timely.test.IntegrationTest;
|
||||||
|
import timely.test.TimelyTestRule;
|
||||||
|
|
||||||
|
@Category(IntegrationTest.class)
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
|
||||||
|
public class MetricResolverIT {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(MetricResolverIT.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
@Rule
|
||||||
|
public TimelyTestRule testRule;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TestMetricResolver metricResolver;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TestHealthChecker healthChecker;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CuratorFramework curatorFramework;
|
||||||
|
|
||||||
|
private ServiceDiscovery<ServerDetails> discovery;
|
||||||
|
private ServiceCache<ServerDetails> serviceCache;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws Exception {
|
||||||
|
discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class).client(curatorFramework).basePath(SERVICE_DISCOVERY_PATH).build();
|
||||||
|
discovery.start();
|
||||||
|
serviceCache = discovery.serviceCacheBuilder().name("timely-server").build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ServiceRegistrationTest() {
|
||||||
|
LinkedBlockingQueue<List<ServiceInstance<ServerDetails>>> updateQueue = getServiceUpdateQueue(serviceCache);
|
||||||
|
registerService(curatorFramework, TimelyBalancedHost.of("host1", 5242, 5243, 5244, 5245, null));
|
||||||
|
registerService(curatorFramework, TimelyBalancedHost.of("host1", 5342, 5343, 5344, 5345, null));
|
||||||
|
registerService(curatorFramework, TimelyBalancedHost.of("host1", 5442, 5443, 5444, 5445, null));
|
||||||
|
registerService(curatorFramework, TimelyBalancedHost.of("host1", 5542, 5543, 5544, 5545, null));
|
||||||
|
try {
|
||||||
|
List<ServiceInstance<ServerDetails>> currentUpdate;
|
||||||
|
List<ServiceInstance<ServerDetails>> lastUpdate = null;
|
||||||
|
do {
|
||||||
|
currentUpdate = updateQueue.poll(200, TimeUnit.MILLISECONDS);
|
||||||
|
if (currentUpdate != null) {
|
||||||
|
lastUpdate = currentUpdate;
|
||||||
|
}
|
||||||
|
} while (currentUpdate != null);
|
||||||
|
Assert.assertNotNull(lastUpdate);
|
||||||
|
Assert.assertEquals(4, lastUpdate.size());
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Assert.fail("" + e.getMessage());
|
||||||
|
}
|
||||||
|
Assert.assertEquals(4, metricResolver.getServerList().size());
|
||||||
|
Assert.assertEquals(4, healthChecker.getTimelyHosts().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void registerService(CuratorFramework curatorFramework, TimelyBalancedHost server) {
|
||||||
|
try {
|
||||||
|
ServerDetails payload = new ServerDetails();
|
||||||
|
payload.setHost(server.getHost());
|
||||||
|
payload.setTcpPort(server.getTcpPort());
|
||||||
|
payload.setHttpPort(server.getHttpPort());
|
||||||
|
payload.setWsPort(server.getWsPort());
|
||||||
|
payload.setUdpPort(server.getUdpPort());
|
||||||
|
|
||||||
|
ServiceInstanceBuilder<ServerDetails> builder = ServiceInstance.builder();
|
||||||
|
String serviceName = server.getHost() + ":" + server.getTcpPort();
|
||||||
|
ServiceInstance<ServerDetails> serviceInstance = builder.id(serviceName).name("timely-server").address(server.getHost()).port(server.getTcpPort())
|
||||||
|
.payload(payload).build();
|
||||||
|
|
||||||
|
ServiceDiscovery<ServerDetails> discovery = ServiceDiscoveryBuilder.builder(ServerDetails.class).client(curatorFramework)
|
||||||
|
.basePath(SERVICE_DISCOVERY_PATH).build();
|
||||||
|
discovery.start();
|
||||||
|
discovery.registerService(serviceInstance);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LinkedBlockingQueue<List<ServiceInstance<ServerDetails>>> getServiceUpdateQueue(ServiceCache<ServerDetails> serviceCache) {
|
||||||
|
|
||||||
|
LinkedBlockingQueue<List<ServiceInstance<ServerDetails>>> updates = new LinkedBlockingQueue<>();
|
||||||
|
try {
|
||||||
|
|
||||||
|
ServiceCacheListener listener = new ServiceCacheListener() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void cacheChanged() {
|
||||||
|
updates.add(serviceCache.getInstances());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
serviceCache.addListener(listener);
|
||||||
|
serviceCache.start();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
return updates;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package timely.balancer.test;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
|
||||||
|
import io.netty.handler.ssl.SslContext;
|
||||||
|
import timely.balancer.Balancer;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
|
import timely.balancer.configuration.BalancerHttpProperties;
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerWebsocketProperties;
|
||||||
|
import timely.common.component.AuthenticationService;
|
||||||
|
import timely.common.configuration.SecurityProperties;
|
||||||
|
import timely.common.configuration.SslClientProperties;
|
||||||
|
import timely.common.configuration.SslServerProperties;
|
||||||
|
import timely.common.configuration.ZookeeperProperties;
|
||||||
|
|
||||||
|
public class TestBalancer extends Balancer {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(TestBalancer.class);
|
||||||
|
|
||||||
|
public TestBalancer(ApplicationContext applicationContext, SslContext serverSslContext, SSLContext clientSSLContext,
|
||||||
|
AuthenticationService authenticationService, MetricResolver metricResolver, BalancerProperties balancerProperties,
|
||||||
|
ZookeeperProperties zookeeperProperties, SecurityProperties securityProperties, SslServerProperties sslServerProperties,
|
||||||
|
SslClientProperties sslClientProperties, BalancerServerProperties balancerServerProperties, BalancerHttpProperties balancerHttpProperties,
|
||||||
|
BalancerWebsocketProperties balancerWebsocketProperties) {
|
||||||
|
super(applicationContext, serverSslContext, clientSSLContext, authenticationService, metricResolver, balancerProperties, zookeeperProperties,
|
||||||
|
securityProperties, sslServerProperties, sslClientProperties, balancerServerProperties, balancerHttpProperties,
|
||||||
|
balancerWebsocketProperties);
|
||||||
|
DEFAULT_EVENT_LOOP_THREADS = 1;
|
||||||
|
log.info("Starting TestBalancer");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package timely.balancer.test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import timely.balancer.HealthChecker;
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.configuration.BalancerServerProperties;
|
||||||
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
|
||||||
|
public class TestHealthChecker extends HealthChecker {
|
||||||
|
|
||||||
|
public TestHealthChecker(BalancerProperties balancerProperties, BalancerServerProperties balancerServerProperties) {
|
||||||
|
super(balancerProperties, balancerServerProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TimelyBalancedHost> getTimelyHosts() {
|
||||||
|
return this.timelyHosts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package timely.balancer.test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.hadoop.conf.Configuration;
|
||||||
|
import org.apache.hadoop.fs.FileSystem;
|
||||||
|
import org.apache.hadoop.fs.Path;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import timely.balancer.HealthChecker;
|
||||||
|
import timely.balancer.MetricResolver;
|
||||||
|
import timely.balancer.configuration.BalancerProperties;
|
||||||
|
import timely.balancer.connection.TimelyBalancedHost;
|
||||||
|
import timely.common.configuration.CacheProperties;
|
||||||
|
|
||||||
|
public class TestMetricResolver extends MetricResolver {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(TestMetricResolver.class);
|
||||||
|
|
||||||
|
public TestMetricResolver(CuratorFramework curatorFramework, BalancerProperties balancerProperties, CacheProperties cacheProperties,
|
||||||
|
HealthChecker healthChecker) {
|
||||||
|
super(curatorFramework, balancerProperties, cacheProperties, healthChecker);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void createAssignmentFile() {
|
||||||
|
try {
|
||||||
|
log.info("Creating assignment file: " + balancerProperties.getAssignmentFile());
|
||||||
|
Configuration configuration = new Configuration();
|
||||||
|
FileSystem fs = FileSystem.get(configuration);
|
||||||
|
Path assignmentFile = new Path(balancerProperties.getAssignmentFile());
|
||||||
|
fs.setWriteChecksum(false);
|
||||||
|
fs.create(assignmentFile);
|
||||||
|
fs.deleteOnExit(assignmentFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TimelyBalancedHost> getServerList() {
|
||||||
|
return this.serverList;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package timely.balancer.test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.security.authentication.ProviderManager;
|
||||||
|
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Primary
|
||||||
|
@Component
|
||||||
|
public class TestTimelyAuthenticationManager extends ProviderManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public TestTimelyAuthenticationManager(@Qualifier("file") PreAuthenticatedAuthenticationProvider file) {
|
||||||
|
super(Collections.singletonList(file));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
logging:
|
||||||
|
level:
|
||||||
|
ROOT: info
|
||||||
|
timely: debug
|
||||||
|
org.apache.zookeeper: error
|
||||||
|
|
||||||
|
timely:
|
||||||
|
test: true
|
||||||
|
instance: 1
|
||||||
|
accumulo:
|
||||||
|
instance-name: default
|
||||||
|
username: root
|
||||||
|
password: secret
|
||||||
|
mini-accumulo:
|
||||||
|
enabled: true
|
||||||
|
rootAuths: A,B,C,D,E,F,G,H,I
|
||||||
|
zookeeper:
|
||||||
|
servers: localhost:0
|
||||||
|
timeout: 30s
|
||||||
|
security:
|
||||||
|
session-max-age: 86400
|
||||||
|
cache-expiration-minutes: 60
|
||||||
|
cache-refresh-minutes: 5
|
||||||
|
allow-anonymous-http-access: true
|
||||||
|
allow-anonymous-ws-access: true
|
||||||
|
authorized-users:
|
||||||
|
- subject-dn: cn=example.com
|
||||||
|
roles: G,H,I
|
||||||
|
auths: D,E,F
|
||||||
|
user-type: USER
|
||||||
|
- subject-dn: cn=test a. user, ou=example developers, o=example corp, c=us
|
||||||
|
issuer-dn: cn=example corp ca, o=example corp, c=us
|
||||||
|
roles: G,H,I
|
||||||
|
auths: A,B,C
|
||||||
|
user-type: USER
|
||||||
|
server-ssl:
|
||||||
|
key-store-type: PKCS12
|
||||||
|
key-store-file: classpath:ssl/testServer.p12
|
||||||
|
key-store-password: ChangeIt
|
||||||
|
trust-store-type: JKS
|
||||||
|
trust-store-file: classpath:ssl/ca.jks
|
||||||
|
trust-store-password: ChangeIt
|
||||||
|
use-generated-keypair: false
|
||||||
|
ignore-ssl-handshake-errors: true
|
||||||
|
use-openssl: true
|
||||||
|
client-ssl:
|
||||||
|
key-store-type: PKCS12
|
||||||
|
key-store-file: classpath:ssl/testUser.p12
|
||||||
|
key-store-password: ChangeIt
|
||||||
|
trust-store-type: JKS
|
||||||
|
trust-store-file: classpath:ssl/ca.jks
|
||||||
|
trust-store-password: ChangeIt
|
||||||
|
cache:
|
||||||
|
enabled: false
|
||||||
|
metric-age-off-hours:
|
||||||
|
default: 26
|
||||||
|
non-cached-metrics:
|
||||||
|
balancer:
|
||||||
|
check-server-health-interval: 10000
|
||||||
|
server-failures-before-down: 6
|
||||||
|
server-successes-before-up: 1
|
||||||
|
assignment-file: file://${java.io.tmpdir}/timely/balancer/assignments.csv
|
||||||
|
server:
|
||||||
|
ip: 127.0.0.1
|
||||||
|
tcp-base-port: 4242
|
||||||
|
num-tcp-pools: 1
|
||||||
|
tcp-buffer-size: 100
|
||||||
|
tcp-client-pool:
|
||||||
|
min-idle-per-key: 0
|
||||||
|
max-idle-per-key: 40
|
||||||
|
max-total-per-key: 40
|
||||||
|
max-total: -1
|
||||||
|
lifo: true
|
||||||
|
fairness: false
|
||||||
|
max-wait-millis: -1
|
||||||
|
min-evictable-idle-time-millis: 1800000
|
||||||
|
evictor-shutdown-timeout-millis: 10000
|
||||||
|
soft-min-evictable-idle-time-millis: -1
|
||||||
|
num-tests-per-eviction-run: 3
|
||||||
|
time-between-eviction-runs-millis: -1
|
||||||
|
block-when-exhausted: true
|
||||||
|
jmx-enabled: true
|
||||||
|
test-on-borrow: false
|
||||||
|
test-on-return: false
|
||||||
|
udp-base-port: 4245
|
||||||
|
udp-client-pool:
|
||||||
|
min-idle-per-key: 0
|
||||||
|
max-idle-per-key: 40
|
||||||
|
max-total-per-key: 40
|
||||||
|
max-total: -1
|
||||||
|
lifo: true
|
||||||
|
fairness: false
|
||||||
|
max-wait-millis: -1
|
||||||
|
min-evictable-idle-time-millis: 1800000
|
||||||
|
evictor-shutdown-timeout-millis: 10000
|
||||||
|
soft-min-evictable-idle-time-millis: -1
|
||||||
|
num-tests-per-eviction-run: 3
|
||||||
|
time-between-eviction-runs-millis: -1
|
||||||
|
block-when-exhausted: true
|
||||||
|
jmx-enabled: true
|
||||||
|
test-on-borrow: false
|
||||||
|
test-on-return: false
|
||||||
|
http:
|
||||||
|
host: localhost
|
||||||
|
ip: 127.0.0.1
|
||||||
|
base-port: 4243
|
||||||
|
redirect-path: /secure-me
|
||||||
|
strict-transport-max-age: 604800
|
||||||
|
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
|
||||||
|
http-client-pool:
|
||||||
|
min-idle-per-key: 0
|
||||||
|
max-idle-per-key: 40
|
||||||
|
max-total-per-key: 40
|
||||||
|
max-total: -1
|
||||||
|
lifo: true
|
||||||
|
fairness: false
|
||||||
|
max-wait-millis: -1
|
||||||
|
min-evictable-idle-time-millis: 1800000
|
||||||
|
evictor-shutdown-timeout-millis: 10000
|
||||||
|
soft-min-evictable-idle-time-millis: -1
|
||||||
|
num-tests-per-eviction-run: 3
|
||||||
|
time-between-eviction-runs-millis: -1
|
||||||
|
block-when-exhausted: true
|
||||||
|
jmx-enabled: true
|
||||||
|
test-on-borrow: false
|
||||||
|
test-on-return: false
|
||||||
|
websocket:
|
||||||
|
ip: 127.0.0.1
|
||||||
|
base-port: 5244
|
||||||
|
timeout: 60
|
||||||
|
subscription-lag: 120
|
||||||
|
scanner-batch-size: 10000
|
||||||
|
flush-interval-seconds: 30
|
||||||
|
scanner-read-ahead: 1
|
||||||
|
subscription-batch-size: 5000
|
||||||
|
incoming-buffer-size: 50000000
|
||||||
|
ws-client-pool:
|
||||||
|
min-idle-per-key: 0
|
||||||
|
max-idle-per-key: 40
|
||||||
|
max-total-per-key: 40
|
||||||
|
max-total: -1
|
||||||
|
lifo: true
|
||||||
|
fairness: false
|
||||||
|
max-wait-millis: -1
|
||||||
|
min-evictable-idle-time-millis: 1800000
|
||||||
|
evictor-shutdown-timeout-millis: 10000
|
||||||
|
soft-min-evictable-idle-time-millis: -1
|
||||||
|
num-tests-per-eviction-run: 3
|
||||||
|
time-between-eviction-runs-millis: -1
|
||||||
|
block-when-exhausted: true
|
||||||
|
jmx-enabled: true
|
||||||
|
test-on-borrow: false
|
||||||
|
test-on-return: false
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: timely-balancer
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
Configuration:
|
||||||
|
status: warn
|
||||||
|
monitorInterval: 60
|
||||||
|
|
||||||
|
Properties:
|
||||||
|
Property:
|
||||||
|
- name: PID
|
||||||
|
value: "????"
|
||||||
|
- name: LOG_PATTERN
|
||||||
|
value: "%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"
|
||||||
|
|
||||||
|
Appenders:
|
||||||
|
Console:
|
||||||
|
name: Console
|
||||||
|
target: SYSTEM_OUT
|
||||||
|
follow: true
|
||||||
|
PatternLayout:
|
||||||
|
pattern: "${LOG_PATTERN}"
|
||||||
|
|
||||||
|
Loggers:
|
||||||
|
Root:
|
||||||
|
level: warn
|
||||||
|
AppenderRef:
|
||||||
|
- ref: Console
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
Bag Attributes: <No Attributes>
|
||||||
|
subject=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
issuer=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDTjCCAjagAwIBAgIURUj8l+ms/i9jeabIBBi19KxEhAgwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwPjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDEV4YW1wbGUgQ29ycDEYMBYGA1UE
|
||||||
|
AxMPRVhBTVBMRSBDT1JQIENBMCAXDTIzMDIwMTIzMTUwMFoYDzIxMjMwMTA4MjMx
|
||||||
|
NTAwWjA+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRXhhbXBsZSBDb3JwMRgwFgYD
|
||||||
|
VQQDEw9FWEFNUExFIENPUlAgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
|
||||||
|
AoIBAQDVBr2XF20SKmGXfvp2BUY44BF1fm3Qw83GkC66qIHgpgQxzJ8u44P34vV1
|
||||||
|
DYTj4XzrBpx23J0nCMEiAW8YW9MxZJPEokZafRNKFQAngVdgmAW9fHemHRQfaYwe
|
||||||
|
ySVz2UZ+z28DJ3C0QshvqXskrYstwLVs4Ss2uoX+XpeFbW9IVVg4aW+GX3LHPNTk
|
||||||
|
7Hji13Capp6BCiS61AGQAiMWNBW2aRgHVLOb7RDQug2Bka/dcJ44XxJDh26C6kV1
|
||||||
|
pNEZm0ToqWAiVfvyzionPec5im6NKX9kStZc+C/iikfx5vdmrvGIF5zxy6phdhJ7
|
||||||
|
AGd6cF6UBkkYm/SsIP3WTXpBek5LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP
|
||||||
|
BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSPLNlCmmp9PH+crzCx9TNp5BoCajAN
|
||||||
|
BgkqhkiG9w0BAQsFAAOCAQEAkjLnZKqLMjbu5Hy8YOVoKaEKahP+t/tNYZW/NtrC
|
||||||
|
xSxKmGLz5kVCkjpLgCykkcpu4h2wZW4MGZJ4nc87+tN22mJOg1WnqEpBzRsEPajk
|
||||||
|
7duVjdU2FDCarERj53hxF41l/u8BxvMGbFnrAijv5SzspeLi+VCGF3wu53Bi6UHi
|
||||||
|
7WO1dIhZLMHepqgtwbDDudxwlKbG/JWjJ7OspCNqOpktpY8BFUAQ42ctYZcOHy2w
|
||||||
|
kdZDcK5IhRztkBH2aSWOhudYh/CF7BOu2nSUdtR5NwhXnsStmSbud7ahw3W5Jc9/
|
||||||
|
IVAFXf2brkrfIzwrY5kmjnEPJ8mjUyLepwSlOlMTBrehzQ==
|
||||||
|
-----END CERTIFICATE-----
|
||||||
Binary file not shown.
@@ -0,0 +1,51 @@
|
|||||||
|
Bag Attributes
|
||||||
|
localKeyID: 22 89 1C EA 4E FF 9A F6 11 1B E7 9B 5E 4F 59 B7 B1 0F AA FA
|
||||||
|
friendlyName: example-server
|
||||||
|
subject=/C=US/O=Example Corp/OU=Servers/CN=testserver.example.com
|
||||||
|
issuer=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDwjCCAqqgAwIBAgIUe6yBgkY1m/oXuPXA9j/c/7+w16UwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwPjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDEV4YW1wbGUgQ29ycDEYMBYGA1UE
|
||||||
|
AxMPRVhBTVBMRSBDT1JQIENBMCAXDTIzMDIwMTIzMTUwMFoYDzIxMjMwMTA4MjMx
|
||||||
|
NTAwWjBXMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRXhhbXBsZSBDb3JwMRAwDgYD
|
||||||
|
VQQLEwdTZXJ2ZXJzMR8wHQYDVQQDExZ0ZXN0c2VydmVyLmV4YW1wbGUuY29tMIIB
|
||||||
|
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmb1pEWg9a6ZChQULazK75ppc
|
||||||
|
XScU5Ap29L70/5zcaOcbaBwqKhpKhdZCoZ1TD+Sdkk9kp7IlabCQjM2vVjknb6NY
|
||||||
|
msl3PbQFNva0EkH6s5cvpX4WhQDsWK77/4eztHT+0fpaG1YoKQn+Gy3VuW0CDyR6
|
||||||
|
GzGKifnI/aNLevgUBebbiiTPLEdGlo0jp3SXlZfoDZdbvnhBWI8Xc+aDekNlrXxW
|
||||||
|
X2TVnc02Fi914PECYJzkMpmxnBRPAcljU24WSqaUVgRoSbafkm4OXDw0xtvxnIrJ
|
||||||
|
s3iO0uZfRf7+OxAlqlvh4ZJ9/PufPMEKvmr6zea05KkFjBotKMip5Md43H3lQQID
|
||||||
|
AQABo4GcMIGZMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYI
|
||||||
|
KwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUDWwMrl9/uc1wplERWxas
|
||||||
|
bDROB4MwHwYDVR0jBBgwFoAUjyzZQppqfTx/nK8wsfUzaeQaAmowGgYDVR0RBBMw
|
||||||
|
EYIJbG9jYWxob3N0hwR/AAABMA0GCSqGSIb3DQEBCwUAA4IBAQBfG7StgQf3WNk/
|
||||||
|
EnaYuurwvaOOpcOV5NDcZ6tmgaXUrISPVDpyIWfsDGetNEXc+4gpefLQtGF2wuiW
|
||||||
|
odiLc4H9JwQ/yEkVYwzrFViPdZKVvxNU2EjiwO/e/3sl+SxxkTDy6o838uTXX+X5
|
||||||
|
Q8DabmL5L8ukcnqUHVOqW38oA1vRNBKiJX58JzOr8ezX8crZmqU9h8cNwG/V+ZXE
|
||||||
|
5U7+hSRzLm7gRwtixj8ZsTDUiGJxOdbyUKImPClt1Se9TizB2Q/xOPTdmYB1qiiB
|
||||||
|
+XVKkGwQPgIbHckLsZWhBor2u5cgdrBGW09Q+H88maagwq5sBHNMs33vkkgbUDpB
|
||||||
|
6WSEBJMi
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
Bag Attributes: <No Attributes>
|
||||||
|
subject=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
issuer=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDTjCCAjagAwIBAgIURUj8l+ms/i9jeabIBBi19KxEhAgwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwPjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDEV4YW1wbGUgQ29ycDEYMBYGA1UE
|
||||||
|
AxMPRVhBTVBMRSBDT1JQIENBMCAXDTIzMDIwMTIzMTUwMFoYDzIxMjMwMTA4MjMx
|
||||||
|
NTAwWjA+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRXhhbXBsZSBDb3JwMRgwFgYD
|
||||||
|
VQQDEw9FWEFNUExFIENPUlAgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
|
||||||
|
AoIBAQDVBr2XF20SKmGXfvp2BUY44BF1fm3Qw83GkC66qIHgpgQxzJ8u44P34vV1
|
||||||
|
DYTj4XzrBpx23J0nCMEiAW8YW9MxZJPEokZafRNKFQAngVdgmAW9fHemHRQfaYwe
|
||||||
|
ySVz2UZ+z28DJ3C0QshvqXskrYstwLVs4Ss2uoX+XpeFbW9IVVg4aW+GX3LHPNTk
|
||||||
|
7Hji13Capp6BCiS61AGQAiMWNBW2aRgHVLOb7RDQug2Bka/dcJ44XxJDh26C6kV1
|
||||||
|
pNEZm0ToqWAiVfvyzionPec5im6NKX9kStZc+C/iikfx5vdmrvGIF5zxy6phdhJ7
|
||||||
|
AGd6cF6UBkkYm/SsIP3WTXpBek5LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP
|
||||||
|
BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSPLNlCmmp9PH+crzCx9TNp5BoCajAN
|
||||||
|
BgkqhkiG9w0BAQsFAAOCAQEAkjLnZKqLMjbu5Hy8YOVoKaEKahP+t/tNYZW/NtrC
|
||||||
|
xSxKmGLz5kVCkjpLgCykkcpu4h2wZW4MGZJ4nc87+tN22mJOg1WnqEpBzRsEPajk
|
||||||
|
7duVjdU2FDCarERj53hxF41l/u8BxvMGbFnrAijv5SzspeLi+VCGF3wu53Bi6UHi
|
||||||
|
7WO1dIhZLMHepqgtwbDDudxwlKbG/JWjJ7OspCNqOpktpY8BFUAQ42ctYZcOHy2w
|
||||||
|
kdZDcK5IhRztkBH2aSWOhudYh/CF7BOu2nSUdtR5NwhXnsStmSbud7ahw3W5Jc9/
|
||||||
|
IVAFXf2brkrfIzwrY5kmjnEPJ8mjUyLepwSlOlMTBrehzQ==
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
Bag Attributes
|
||||||
|
localKeyID: 22 89 1C EA 4E FF 9A F6 11 1B E7 9B 5E 4F 59 B7 B1 0F AA FA
|
||||||
|
friendlyName: example-server
|
||||||
|
Key Attributes: <No Attributes>
|
||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZvWkRaD1rpkKF
|
||||||
|
BQtrMrvmmlxdJxTkCnb0vvT/nNxo5xtoHCoqGkqF1kKhnVMP5J2ST2SnsiVpsJCM
|
||||||
|
za9WOSdvo1iayXc9tAU29rQSQfqzly+lfhaFAOxYrvv/h7O0dP7R+lobVigpCf4b
|
||||||
|
LdW5bQIPJHobMYqJ+cj9o0t6+BQF5tuKJM8sR0aWjSOndJeVl+gNl1u+eEFYjxdz
|
||||||
|
5oN6Q2WtfFZfZNWdzTYWL3Xg8QJgnOQymbGcFE8ByWNTbhZKppRWBGhJtp+Sbg5c
|
||||||
|
PDTG2/GcismzeI7S5l9F/v47ECWqW+Hhkn38+588wQq+avrN5rTkqQWMGi0oyKnk
|
||||||
|
x3jcfeVBAgMBAAECggEAZEHC7NkfhL4NjxV1Ftkk9AMhzJWZ6ARzArQsrSysB7T+
|
||||||
|
iGwliwNOKe1J0n74FdsubqVbrIheIYhFG61edEodT44kT/ylyBVHeUp0r5tbVBZ5
|
||||||
|
ueB56w5pEoQ6Ta8/H6VUL7alYEJVOj4L+clwINXXi+xrvKQYBlZgHheJN43j8NxS
|
||||||
|
9lCrVcm58rzX3i29S7ErBf7RqDabgD6j2m7rehnSq5Ps2wxwV/LXMl4Lxlwa0jz/
|
||||||
|
LV8szNMZViPOWAqOCy7NZbwCCaCfKVUAwmNGBkE3p4JVPeLNLzCBY9G0rHVmFJLK
|
||||||
|
yPnCB7PtCZeFTsU+8OHHWoxMFsaOO9Pp8FtB/r8PYQKBgQDI0OzEo3t/QKvbwAdz
|
||||||
|
9Eze0LQvstzZIidTWbYMTxH0g7DIt+3p11d61GKtfeuYUTPlLodufdv/BaP8G9sI
|
||||||
|
NzxisB3uH/787M9fwi1OzO7zMMZZCVa7Q1vZk6ta1qY3PekcYMPqjBJhxP1X3S7x
|
||||||
|
8+mrW5vTq/l8ZRVFeLvEkh6bpQKBgQDD/MCRJoq6nzd2DoTyT9m5qO+Jlztmu9+T
|
||||||
|
vqVOg7q0NO7U7dzyMbWgMvMFoEBidnyllU1rEj2YOo4OrI2v/JmSPUVS8VXsBkkG
|
||||||
|
UqInV4F/g0Wp3hzrkZFMqHLa6AydugmRNkOpgurRKOiwAL0Pgvk8+bOIbKMM7JBE
|
||||||
|
tZ6Zvi0gbQKBgD4S5r0505jYQsdgqm0bXQ+a77e20DGGLyXCm1Ves6wjcOf6gt4/
|
||||||
|
pFjhgccjH0or/6CeK1rqKLDB65ioe6IkgNP4oKfU2BsSkF+HRD4RduNRdl5bVqX4
|
||||||
|
AlJVJSilJSf6SS5ucuDzf1MdczpPso0z2k0PujFJ/YqILHUXBuOST0fJAoGAZAdX
|
||||||
|
nX3HZpKmsumcLzRUEq9HerkmRzvyU60FH/qZyyoND75Le42lfpsicCenVNnWqoh2
|
||||||
|
WASaTVztbk3hjwXkt7/v5vJoASwAD2sTefLulE9Cuf00U4MbXr3GyTWQYtw1z9ib
|
||||||
|
ViQMhy5S/KmT1Rvq65UibanM2mbPB1KPHTb0P00CgYEAgieJ1YXYYHPjABWJ7/S9
|
||||||
|
3Z/8eJY0kuUe1DRFaKOlfej8SOCFFIa90IW2mAnujh55H4N2lww4s/N+FIRQoQpA
|
||||||
|
1Hrch9tYRiXyouQc67dFlLxmCOVJIf31ZUt7I4HcPhsfr4fuCJXUPBs1jaDmwQsk
|
||||||
|
90VWrXaTwSjmP+yHMiPfaA0=
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
Binary file not shown.
@@ -0,0 +1,50 @@
|
|||||||
|
Bag Attributes
|
||||||
|
localKeyID: 57 F6 9F DF B2 94 61 47 B0 B0 2E 3A F7 79 98 C8 15 5C 64 FA
|
||||||
|
friendlyName: example-client
|
||||||
|
subject=/C=US/O=Example Corp/OU=Example Developers/CN=Test A. User
|
||||||
|
issuer=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDmzCCAoOgAwIBAgIUFp4IuIaZ2XId7UNvzP6ZB9hChyUwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwPjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDEV4YW1wbGUgQ29ycDEYMBYGA1UE
|
||||||
|
AxMPRVhBTVBMRSBDT1JQIENBMCAXDTIzMDIwMTIzMTUwMFoYDzIxMjMwMTA4MjMx
|
||||||
|
NTAwWjBYMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRXhhbXBsZSBDb3JwMRswGQYD
|
||||||
|
VQQLExJFeGFtcGxlIERldmVsb3BlcnMxFTATBgNVBAMTDFRlc3QgQS4gVXNlcjCC
|
||||||
|
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMOMeN0ElMDxYKST2VD1wP6Z
|
||||||
|
jmy543Zv/QgRLTYizg3U9t3uZU0C3HqUJnK+c4+OJnRIyHuMXuJWEYVdairyAdYW
|
||||||
|
ZDF5sfiL9ikG9rZ2WxR2z7nsYLJcDGwKAt/Duzuoed6KSccEpiQc+BkoOTs9p87I
|
||||||
|
l4s7saX/anESMUY7YOomLSqS2zvQZh/zTjIdP1/9kG9PLzXPClJELuiC3pJCmr7Y
|
||||||
|
xdJIXecu6YKFpApy0y+rKcfYUVPML15gyRu9pIqH3U39y7mCkn+YP9Qc9GcZAoqR
|
||||||
|
iYdUEl1rFAgV/a3o0pmf1tFFRDOsoPSMUGNNQlaCjv1uZIbRm25nvvQlPfstFDEC
|
||||||
|
AwEAAaN1MHMwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMCMAwG
|
||||||
|
A1UdEwEB/wQCMAAwHQYDVR0OBBYEFPAe3n59DcNwRcnpIwQY2kPawbCVMB8GA1Ud
|
||||||
|
IwQYMBaAFI8s2UKaan08f5yvMLH1M2nkGgJqMA0GCSqGSIb3DQEBCwUAA4IBAQBo
|
||||||
|
+zadU9DwR1rnHTBZF6CJXmiIdrQmArojH4a3NOHbNjFjRXm7dkd/tAy5LtgDJkww
|
||||||
|
yg+ZrOyOKHbFgk6IXRZ8nw2b1Ck9I9MDW1vxfjid9YLW2nhDaMcIeTXz3aIBO5i6
|
||||||
|
gMCV+xMcFaU/O57Ohia+ADUqrqu14nG9Moi171UWPbMr5N3gYn3Fs4VrTGYs4i0Z
|
||||||
|
5x2itm88WB3bWj+cd06zKQopU9b0Y76mQv9h+w4EHxq4uWA7GmIDDkvtI61MQo8+
|
||||||
|
twdX159Ms6o4lW43SRqVBHeMgSJbiLDkdkypYJvd9PvAjWgmQK/sD1SYKxfgYhtx
|
||||||
|
hqIvAjlGeDwdf+55EGjf
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
Bag Attributes: <No Attributes>
|
||||||
|
subject=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
issuer=/C=US/O=Example Corp/CN=EXAMPLE CORP CA
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDTjCCAjagAwIBAgIURUj8l+ms/i9jeabIBBi19KxEhAgwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwPjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDEV4YW1wbGUgQ29ycDEYMBYGA1UE
|
||||||
|
AxMPRVhBTVBMRSBDT1JQIENBMCAXDTIzMDIwMTIzMTUwMFoYDzIxMjMwMTA4MjMx
|
||||||
|
NTAwWjA+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRXhhbXBsZSBDb3JwMRgwFgYD
|
||||||
|
VQQDEw9FWEFNUExFIENPUlAgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
|
||||||
|
AoIBAQDVBr2XF20SKmGXfvp2BUY44BF1fm3Qw83GkC66qIHgpgQxzJ8u44P34vV1
|
||||||
|
DYTj4XzrBpx23J0nCMEiAW8YW9MxZJPEokZafRNKFQAngVdgmAW9fHemHRQfaYwe
|
||||||
|
ySVz2UZ+z28DJ3C0QshvqXskrYstwLVs4Ss2uoX+XpeFbW9IVVg4aW+GX3LHPNTk
|
||||||
|
7Hji13Capp6BCiS61AGQAiMWNBW2aRgHVLOb7RDQug2Bka/dcJ44XxJDh26C6kV1
|
||||||
|
pNEZm0ToqWAiVfvyzionPec5im6NKX9kStZc+C/iikfx5vdmrvGIF5zxy6phdhJ7
|
||||||
|
AGd6cF6UBkkYm/SsIP3WTXpBek5LAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP
|
||||||
|
BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSPLNlCmmp9PH+crzCx9TNp5BoCajAN
|
||||||
|
BgkqhkiG9w0BAQsFAAOCAQEAkjLnZKqLMjbu5Hy8YOVoKaEKahP+t/tNYZW/NtrC
|
||||||
|
xSxKmGLz5kVCkjpLgCykkcpu4h2wZW4MGZJ4nc87+tN22mJOg1WnqEpBzRsEPajk
|
||||||
|
7duVjdU2FDCarERj53hxF41l/u8BxvMGbFnrAijv5SzspeLi+VCGF3wu53Bi6UHi
|
||||||
|
7WO1dIhZLMHepqgtwbDDudxwlKbG/JWjJ7OspCNqOpktpY8BFUAQ42ctYZcOHy2w
|
||||||
|
kdZDcK5IhRztkBH2aSWOhudYh/CF7BOu2nSUdtR5NwhXnsStmSbud7ahw3W5Jc9/
|
||||||
|
IVAFXf2brkrfIzwrY5kmjnEPJ8mjUyLepwSlOlMTBrehzQ==
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
Bag Attributes
|
||||||
|
localKeyID: 57 F6 9F DF B2 94 61 47 B0 B0 2E 3A F7 79 98 C8 15 5C 64 FA
|
||||||
|
friendlyName: example-client
|
||||||
|
Key Attributes: <No Attributes>
|
||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDjHjdBJTA8WCk
|
||||||
|
k9lQ9cD+mY5sueN2b/0IES02Is4N1Pbd7mVNAtx6lCZyvnOPjiZ0SMh7jF7iVhGF
|
||||||
|
XWoq8gHWFmQxebH4i/YpBva2dlsUds+57GCyXAxsCgLfw7s7qHneiknHBKYkHPgZ
|
||||||
|
KDk7PafOyJeLO7Gl/2pxEjFGO2DqJi0qkts70GYf804yHT9f/ZBvTy81zwpSRC7o
|
||||||
|
gt6SQpq+2MXSSF3nLumChaQKctMvqynH2FFTzC9eYMkbvaSKh91N/cu5gpJ/mD/U
|
||||||
|
HPRnGQKKkYmHVBJdaxQIFf2t6NKZn9bRRUQzrKD0jFBjTUJWgo79bmSG0ZtuZ770
|
||||||
|
JT37LRQxAgMBAAECggEBALFWsT1vLCAWRxi55Hkhhhbe12UO55O/V+969E+GHOw6
|
||||||
|
WG9IBaJjl+Oqe3vP8CkeNw15/CbfVCVa/KS/5Mpxkuy+fbrIrHfFJkZqxE8Q4uSa
|
||||||
|
IyRvk/nstG8+XQDlFuWxkmQZcXMFak6R3wWhjtWEwqwrChQA3Mi366YDY6BXtTpi
|
||||||
|
MuLJVWXqYVF2RirWX3a7eosR4MYBCJ1S8NnpI1w4oZwuew6iYiCJNkURctxnGKOe
|
||||||
|
hoop/711PEyIb/qHETBIlReY9scvZgJQZMgGe5mTGgFmAA8Bzo4e1/F2QrVIi7wy
|
||||||
|
REOSj4U+tP/QrYMSPk0cMpH5ft5+2mfh/o+D1ugm/AkCgYEA2qt3P4vlm1TMmJru
|
||||||
|
vMYc8iZjfe7UQTnD+J1EgrASBI0JP565zSZKBRIXnheumWhWS+2KR1MP8N6KAu4Q
|
||||||
|
xE/E7TKfLuE1CPzn7Rh/WZAxDqGNeQthk0qTbeBZ4/mHPKvt8V7c+N4vLjZ00uul
|
||||||
|
bKitlLpb49T+8FpSgRmk+nrBsesCgYEA5O6LmxH1+ip5NoMHoZVBhLbgJkxoXEzn
|
||||||
|
xHT7On8CjQ9B0T85NW9O38/a2gyIb5dIavcrh4dMvOKX8hdrVlal3chrXFRemyvy
|
||||||
|
VzpW7HZpMwthJb/QSim+GQ4u2Jsm+eXQAswq/yfowls9mp7K81McBgdfcdWgWuqc
|
||||||
|
Ttf3dBRS71MCgYBCPpu7ppgCfKgWuykEC0iNm0+cwROQRv21fX9Z0BlFQ6y/l0hW
|
||||||
|
e/kEnDyHakk8tD0gd2/it6kmoWRSCukNb9UKvsE2pIc6l9NzIm7CJUqXUh3Xw7jl
|
||||||
|
tDwBl2vkAp4TpUpKSyDKTBUi/OBbXYQZ7OfZHLPly4sIKXTBI5G1SCcRzQKBgE3Y
|
||||||
|
Y7ZmRBs+CBumMJkcVLwZJ10+jBoeuIzQLoF0oNxwfLP3aK+n2s02M7gDnP09Fw3w
|
||||||
|
YGfkdQ6hioNyvTgNnLcuqHsr4UOojO5mUxpzJVCLJQyeDei6Cv8gGIPlNjqxj6rz
|
||||||
|
3AcJfhdgyTDjoCVfdF8EcMsXlkB0GJSi0W0yYAUrAoGAVK5v0cbEEV+gxdQgh848
|
||||||
|
FwSQXx7i9jVOB2BUTLX2Q+gLUJibtFzLnh03sGCXtTa8sK+hLW4FCMWZa9Ev5ZjG
|
||||||
|
ylFyA96U97CNpS+2/ZW5+hvRZ/GuY/0yB8w26BeS38lI8RnmxSPi5cnexdl32NIX
|
||||||
|
5FkU9WJ4HKmi1n0304CkF+4=
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
Binary file not shown.
+48
-7
@@ -4,12 +4,13 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>timely</groupId>
|
<groupId>timely</groupId>
|
||||||
<artifactId>timely</artifactId>
|
<artifactId>timely</artifactId>
|
||||||
<version>1.0.1-SNAPSHOT</version>
|
<version>2.1.4-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>timely-client</artifactId>
|
<artifactId>timely-client</artifactId>
|
||||||
<properties>
|
<properties>
|
||||||
<!-- PEP 440 compliant version gets substituted into src/main/python/template/setup.py -->
|
<!-- PEP 440 compliant version gets substituted into src/main/python/template/setup.py -->
|
||||||
<python.client.version>0.0.7.dev0</python.client.version>
|
<!-- use .dev0 instead of -SNAPSHOT -->
|
||||||
|
<python.client.version>2.1.4.dev0</python.client.version>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -52,6 +53,10 @@
|
|||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>timely</groupId>
|
||||||
|
<artifactId>timely-common</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>log4j-api</artifactId>
|
<artifactId>log4j-api</artifactId>
|
||||||
@@ -62,21 +67,18 @@
|
|||||||
<artifactId>log4j-core</artifactId>
|
<artifactId>log4j-core</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!--
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
<artifactId>log4j-slf4j-impl</artifactId>
|
<artifactId>log4j-slf4j-impl</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
-->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>timely</groupId>
|
|
||||||
<artifactId>timely-common</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
@@ -107,4 +109,43 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</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>
|
</project>
|
||||||
@@ -7,7 +7,7 @@ public class AddSubscription extends SubscriptionRequest {
|
|||||||
|
|
||||||
private String operation = "add";
|
private String operation = "add";
|
||||||
private String metric = null;
|
private String metric = null;
|
||||||
private Optional<Map<String, String>> tags = Optional.empty();
|
private Optional<Map<String,String>> tags = Optional.empty();
|
||||||
private Optional<Long> startTime = Optional.empty();
|
private Optional<Long> startTime = Optional.empty();
|
||||||
private Optional<Long> endTime = Optional.empty();
|
private Optional<Long> endTime = Optional.empty();
|
||||||
private Optional<Long> delayTime = Optional.empty();
|
private Optional<Long> delayTime = Optional.empty();
|
||||||
@@ -20,7 +20,7 @@ public class AddSubscription extends SubscriptionRequest {
|
|||||||
return metric;
|
return metric;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<Map<String, String>> getTags() {
|
public Optional<Map<String,String>> getTags() {
|
||||||
return tags;
|
return tags;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public class AddSubscription extends SubscriptionRequest {
|
|||||||
this.metric = metric;
|
this.metric = metric;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTags(Optional<Map<String, String>> tags) {
|
public void setTags(Optional<Map<String,String>> tags) {
|
||||||
this.tags = tags;
|
this.tags = tags;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,9 +71,8 @@ public class AddSubscription extends SubscriptionRequest {
|
|||||||
}
|
}
|
||||||
if (obj instanceof AddSubscription) {
|
if (obj instanceof AddSubscription) {
|
||||||
AddSubscription other = (AddSubscription) obj;
|
AddSubscription other = (AddSubscription) obj;
|
||||||
return (this.subscriptionId.equals(other.subscriptionId) && this.metric.equals(other.metric)
|
return (this.subscriptionId.equals(other.subscriptionId) && this.metric.equals(other.metric) && this.tags.equals(other.tags)
|
||||||
&& this.tags.equals(other.tags) && this.startTime.equals(other.startTime)
|
&& this.startTime.equals(other.startTime) && this.endTime.equals(other.endTime) && this.delayTime.equals(other.delayTime));
|
||||||
&& this.endTime.equals(other.endTime) && this.delayTime.equals(other.delayTime));
|
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
package timely.api;
|
|
||||||
|
|
||||||
public class BasicAuthLogin {
|
|
||||||
|
|
||||||
protected String username;
|
|
||||||
protected String password;
|
|
||||||
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsername(String user) {
|
|
||||||
this.username = user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPassword(String password) {
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return (username + password).hashCode();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (null == obj) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (obj == this) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (obj instanceof BasicAuthLogin) {
|
|
||||||
BasicAuthLogin other = (BasicAuthLogin) obj;
|
|
||||||
return (this.username.equals(other.username) && this.password.equals(other.password));
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package timely.api;
|
||||||
|
|
||||||
|
public class VersionRequest {
|
||||||
|
|
||||||
|
private String operation = "version";
|
||||||
|
|
||||||
|
public String getOperation() {
|
||||||
|
return operation;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,13 @@ import java.util.List;
|
|||||||
import org.apache.commons.lang3.builder.EqualsBuilder;
|
import org.apache.commons.lang3.builder.EqualsBuilder;
|
||||||
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
import org.apache.commons.lang3.builder.HashCodeBuilder;
|
||||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||||
|
|
||||||
import timely.model.Metric;
|
import timely.model.Metric;
|
||||||
import timely.model.Tag;
|
import timely.model.Tag;
|
||||||
|
|
||||||
|
@JsonPropertyOrder({"metric", "timestamp", "value", "tags", "subscriptionId", "complete"})
|
||||||
public class MetricResponse {
|
public class MetricResponse {
|
||||||
|
|
||||||
private String metric;
|
private String metric;
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
package timely.client.http;
|
package timely.client.http;
|
||||||
|
|
||||||
|
import javax.net.ssl.HostnameVerifier;
|
||||||
import javax.net.ssl.SSLContext;
|
import javax.net.ssl.SSLContext;
|
||||||
|
|
||||||
import org.apache.http.client.CookieStore;
|
import org.apache.http.client.CookieStore;
|
||||||
import org.apache.http.client.config.CookieSpecs;
|
import org.apache.http.client.config.CookieSpecs;
|
||||||
import org.apache.http.client.config.RequestConfig;
|
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.NoopHostnameVerifier;
|
||||||
|
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
@@ -14,8 +15,8 @@ import org.glassfish.tyrus.client.SslContextConfigurator;
|
|||||||
|
|
||||||
public class HttpClient {
|
public class HttpClient {
|
||||||
|
|
||||||
public static SSLContext getSSLContext(String trustStoreFile, String trustStoreType, String trustStorePass,
|
public static SSLContext getSSLContext(String trustStoreFile, String trustStoreType, String trustStorePass, String keyStoreFile, String keyStoreType,
|
||||||
String keyStoreFile, String keyStoreType, String keyStorePass) {
|
String keyStorePass) {
|
||||||
SslContextConfigurator scc = new SslContextConfigurator();
|
SslContextConfigurator scc = new SslContextConfigurator();
|
||||||
scc.setTrustStoreFile(trustStoreFile);
|
scc.setTrustStoreFile(trustStoreFile);
|
||||||
scc.setTrustStoreType(trustStoreType);
|
scc.setTrustStoreType(trustStoreType);
|
||||||
@@ -30,24 +31,37 @@ public class HttpClient {
|
|||||||
return scc.createSSLContext();
|
return scc.createSSLContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static CloseableHttpClient get(String trustStoreFile, String trustStoreType, String trustStorePass,
|
public static CloseableHttpClient get(String trustStoreFile, String trustStoreType, String trustStorePass, String keyStoreFile, String keyStoreType,
|
||||||
String keyStoreFile, String keyStoreType, String keyStorePass, CookieStore cookieStore,
|
String keyStorePass, CookieStore cookieStore, boolean hostVerificationEnabled) {
|
||||||
boolean hostVerificationEnabled) {
|
|
||||||
|
|
||||||
SSLContext ssl = getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType,
|
SSLContext ssl = getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType, keyStorePass);
|
||||||
keyStorePass);
|
|
||||||
return get(ssl, cookieStore, hostVerificationEnabled);
|
return get(ssl, cookieStore, hostVerificationEnabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
|
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
|
||||||
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
|
return get(ssl, cookieStore, hostVerificationEnabled, false);
|
||||||
|
}
|
||||||
|
|
||||||
HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
|
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled, boolean clientAuth) {
|
||||||
.setDefaultRequestConfig(defaultRequestConfig);
|
HostnameVerifier hostnameVerifier;
|
||||||
if (hostVerificationEnabled) {
|
if (hostVerificationEnabled) {
|
||||||
builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
|
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
|
||||||
} else {
|
} else {
|
||||||
builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
|
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);
|
||||||
}
|
}
|
||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
package timely.client.tcp;
|
package timely.client.tcp;
|
||||||
|
|
||||||
|
import java.io.BufferedWriter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.PrintWriter;
|
import java.io.OutputStreamWriter;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
public class TcpClient implements AutoCloseable {
|
public class TcpClient implements AutoCloseable {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(TcpClient.class);
|
private static final Logger log = LoggerFactory.getLogger(TcpClient.class);
|
||||||
|
|
||||||
private final String host;
|
private final String host;
|
||||||
private final int port;
|
private final int port;
|
||||||
private Socket sock = null;
|
private Socket sock = null;
|
||||||
private PrintWriter out = null;
|
private BufferedWriter out = null;
|
||||||
private long connectTime = 0L;
|
private long connectTime = 0L;
|
||||||
private long backoff = 2000;
|
private long backoff = 2000;
|
||||||
private int bufferSize = -1;
|
private int bufferSize = -1;
|
||||||
@@ -47,7 +49,6 @@ public class TcpClient implements AutoCloseable {
|
|||||||
*
|
*
|
||||||
* @param metric
|
* @param metric
|
||||||
* newline terminated string representation of Timely metric
|
* newline terminated string representation of Timely metric
|
||||||
* @throws IOException
|
|
||||||
*/
|
*/
|
||||||
public synchronized void write(String metric) throws IOException {
|
public synchronized void write(String metric) throws IOException {
|
||||||
if (connect() != 0) {
|
if (connect() != 0) {
|
||||||
@@ -60,7 +61,7 @@ public class TcpClient implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void flush() {
|
public synchronized void flush() throws IOException {
|
||||||
if (null != out) {
|
if (null != out) {
|
||||||
out.flush();
|
out.flush();
|
||||||
writesSinceFlush = 0;
|
writesSinceFlush = 0;
|
||||||
@@ -75,7 +76,7 @@ public class TcpClient implements AutoCloseable {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
LOG.trace("Shutting down connection to Timely at {}:{}", host, port);
|
log.trace("Shutting down connection to Timely at {}:{}", host, port);
|
||||||
if (null != sock) {
|
if (null != sock) {
|
||||||
try {
|
try {
|
||||||
if (null != out) {
|
if (null != out) {
|
||||||
@@ -86,7 +87,7 @@ public class TcpClient implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
sock.close();
|
sock.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOG.error("Error closing connection to Timely at " + host + ":" + port + ". Error: " + e.getMessage());
|
log.error("Error closing connection to Timely at " + host + ":" + port + ". Error: " + e.getMessage());
|
||||||
} finally {
|
} finally {
|
||||||
sock = null;
|
sock = null;
|
||||||
}
|
}
|
||||||
@@ -94,24 +95,49 @@ public class TcpClient implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private synchronized int connect() {
|
private synchronized int connect() {
|
||||||
if (null == sock || !sock.isConnected() || out.checkError()) {
|
if (null == sock || !sock.isConnected()) {
|
||||||
if (System.currentTimeMillis() > (connectTime + backoff)) {
|
if (System.currentTimeMillis() > (connectTime + backoff)) {
|
||||||
|
OutputStreamWriter osw = null;
|
||||||
try {
|
try {
|
||||||
connectTime = System.currentTimeMillis();
|
connectTime = System.currentTimeMillis();
|
||||||
sock = new Socket(host, port);
|
sock = new Socket(host, port);
|
||||||
out = new PrintWriter(sock.getOutputStream(), false);
|
osw = new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8);
|
||||||
|
out = new BufferedWriter(osw);
|
||||||
backoff = 2000;
|
backoff = 2000;
|
||||||
LOG.trace("Connected to Timely at {}:{}", host, port);
|
log.trace("Connected to Timely at {}:{}", host, port);
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Error connecting to Timely at {}:" + host + ":" + port + ". Error: " + e.getMessage());
|
log.error("Error connecting to Timely at {}:{} - {}", host, port, e.getMessage());
|
||||||
|
if (sock != null) {
|
||||||
|
try {
|
||||||
|
sock.close();
|
||||||
|
} catch (IOException e1) {
|
||||||
|
log.error(e1.getMessage());
|
||||||
|
} finally {
|
||||||
|
sock = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (osw != null) {
|
||||||
|
try {
|
||||||
|
osw.close();
|
||||||
|
} catch (IOException e1) {
|
||||||
|
log.error(e1.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (out != null) {
|
||||||
|
try {
|
||||||
|
out.close();
|
||||||
|
} catch (IOException e1) {
|
||||||
|
log.error(e1.getMessage());
|
||||||
|
} finally {
|
||||||
|
out = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
backoff = backoff * 2;
|
backoff = backoff * 2;
|
||||||
sock = null;
|
log.info("Will retry connection in {} ms.", backoff);
|
||||||
out = null;
|
|
||||||
LOG.info("Will retry connection in {} ms.", backoff);
|
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
LOG.warn("Not writing to Timely, waiting to reconnect");
|
log.warn("Not writing to Timely, waiting to reconnect");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
public class UdpClient implements AutoCloseable {
|
public class UdpClient implements AutoCloseable {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(UdpClient.class);
|
private static final Logger log = LoggerFactory.getLogger(UdpClient.class);
|
||||||
|
|
||||||
private final String host;
|
private final String host;
|
||||||
private final int port;
|
private final int port;
|
||||||
@@ -38,12 +38,11 @@ public class UdpClient implements AutoCloseable {
|
|||||||
throw new IllegalStateException("Must call open first");
|
throw new IllegalStateException("Must call open first");
|
||||||
}
|
}
|
||||||
this.packet.setData(metric.getBytes(UTF_8));
|
this.packet.setData(metric.getBytes(UTF_8));
|
||||||
LOG.info("writing '" + metric + "' to " + this.host + ":" + this.port);
|
log.info("writing '" + metric + "' to " + this.host + ":" + this.port);
|
||||||
this.sock.send(packet);
|
this.sock.send(packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void flush() throws IOException {
|
public void flush() throws IOException {}
|
||||||
}
|
|
||||||
|
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
if (null != sock) {
|
if (null != sock) {
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package timely.client.websocket;
|
package timely.client.websocket;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import javax.websocket.CloseReason;
|
import javax.websocket.CloseReason;
|
||||||
import javax.websocket.Endpoint;
|
import javax.websocket.Endpoint;
|
||||||
import javax.websocket.EndpointConfig;
|
import javax.websocket.EndpointConfig;
|
||||||
import javax.websocket.MessageHandler;
|
|
||||||
import javax.websocket.Session;
|
import javax.websocket.Session;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -11,28 +13,25 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
public abstract class ClientHandler extends Endpoint {
|
public abstract class ClientHandler extends Endpoint {
|
||||||
|
|
||||||
private final static Logger LOG = LoggerFactory.getLogger(ClientHandler.class);
|
private final static Logger log = LoggerFactory.getLogger(ClientHandler.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Session session, EndpointConfig config) {
|
public void onOpen(Session session, EndpointConfig config) {
|
||||||
LOG.info("Websocket session {} opened.", session.getId());
|
log.info("Websocket session {} opened.", session.getId());
|
||||||
session.addMessageHandler(new MessageHandler.Whole<String>() {
|
session.addMessageHandler(String.class, message -> {
|
||||||
|
log.info("Message received on Websocket session {}: {}", session.getId(), message);
|
||||||
@Override
|
|
||||||
public void onMessage(String message) {
|
|
||||||
LOG.info("Message received on Websocket session {}: {}", session.getId(), message);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClose(Session session, CloseReason reason) {
|
public void onClose(Session session, CloseReason reason) {
|
||||||
LOG.info("Websocket session {} closed.", session.getId());
|
log.info("Websocket session {} closed.", session.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onError(Session session, Throwable error) {
|
public void onError(Session session, Throwable error) {
|
||||||
LOG.error("Error occurred on Websocket session" + session.getId(), error);
|
log.error("Error occurred on Websocket session" + session.getId(), error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void beforeRequest(Map<String,List<String>> headers) {}
|
||||||
}
|
}
|
||||||
@@ -14,13 +14,15 @@ import org.apache.http.cookie.Cookie;
|
|||||||
public class TimelyEndpointConfig implements ClientEndpointConfig {
|
public class TimelyEndpointConfig implements ClientEndpointConfig {
|
||||||
|
|
||||||
private String sessionCookie = null;
|
private String sessionCookie = null;
|
||||||
|
private final ClientHandler clientEndpoint;
|
||||||
|
|
||||||
private static final String FORMAT = "%s=%s;";
|
private static final String FORMAT = "%s=%s;";
|
||||||
|
|
||||||
public TimelyEndpointConfig(Cookie sessionCookie) {
|
public TimelyEndpointConfig(ClientHandler clientEndpoint, Cookie sessionCookie) {
|
||||||
if (null != sessionCookie) {
|
if (null != sessionCookie) {
|
||||||
this.sessionCookie = String.format(FORMAT, sessionCookie.getName(), sessionCookie.getValue());
|
this.sessionCookie = String.format(FORMAT, sessionCookie.getName(), sessionCookie.getValue());
|
||||||
}
|
}
|
||||||
|
this.clientEndpoint = clientEndpoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -34,7 +36,7 @@ public class TimelyEndpointConfig implements ClientEndpointConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getUserProperties() {
|
public Map<String,Object> getUserProperties() {
|
||||||
return Collections.emptyMap();
|
return Collections.emptyMap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,11 +55,12 @@ public class TimelyEndpointConfig implements ClientEndpointConfig {
|
|||||||
return new Configurator() {
|
return new Configurator() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void beforeRequest(Map<String, List<String>> headers) {
|
public void beforeRequest(Map<String,List<String>> headers) {
|
||||||
super.beforeRequest(headers);
|
super.beforeRequest(headers);
|
||||||
if (null != sessionCookie) {
|
if (null != sessionCookie) {
|
||||||
headers.put("Cookie", Collections.singletonList(sessionCookie));
|
headers.put("Cookie", Collections.singletonList(sessionCookie));
|
||||||
}
|
}
|
||||||
|
TimelyEndpointConfig.this.clientEndpoint.beforeRequest(headers);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,17 +10,13 @@ import javax.net.ssl.SSLContext;
|
|||||||
import javax.websocket.DeploymentException;
|
import javax.websocket.DeploymentException;
|
||||||
import javax.websocket.Session;
|
import javax.websocket.Session;
|
||||||
|
|
||||||
import com.google.common.base.Preconditions;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.HttpStatus;
|
import org.apache.http.HttpStatus;
|
||||||
import org.apache.http.client.HttpResponseException;
|
import org.apache.http.client.HttpResponseException;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.client.methods.HttpPost;
|
|
||||||
import org.apache.http.client.methods.HttpRequestBase;
|
import org.apache.http.client.methods.HttpRequestBase;
|
||||||
import org.apache.http.client.utils.HttpClientUtils;
|
import org.apache.http.client.utils.HttpClientUtils;
|
||||||
import org.apache.http.cookie.Cookie;
|
import org.apache.http.cookie.Cookie;
|
||||||
import org.apache.http.entity.StringEntity;
|
|
||||||
import org.apache.http.impl.client.BasicCookieStore;
|
import org.apache.http.impl.client.BasicCookieStore;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.glassfish.tyrus.client.ClientManager;
|
import org.glassfish.tyrus.client.ClientManager;
|
||||||
@@ -28,20 +24,20 @@ import org.glassfish.tyrus.client.ClientProperties;
|
|||||||
import org.glassfish.tyrus.client.SslEngineConfigurator;
|
import org.glassfish.tyrus.client.SslEngineConfigurator;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import timely.api.BasicAuthLogin;
|
|
||||||
|
import com.google.common.base.Preconditions;
|
||||||
|
|
||||||
import timely.client.http.HttpClient;
|
import timely.client.http.HttpClient;
|
||||||
import timely.serialize.JsonSerializer;
|
|
||||||
|
|
||||||
public class WebSocketClient implements AutoCloseable {
|
public class WebSocketClient implements AutoCloseable {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WebSocketClient.class);
|
private static final Logger log = LoggerFactory.getLogger(WebSocketClient.class);
|
||||||
|
|
||||||
private final String timelyHostname;
|
private final String timelyHostname;
|
||||||
private final int timelyHttpsPort;
|
private final int timelyHttpsPort;
|
||||||
private final int timelyWssPort;
|
private final int timelyWssPort;
|
||||||
private final boolean doLogin;
|
private final boolean doLogin;
|
||||||
private final String timelyUsername;
|
private final boolean clientAuth;
|
||||||
private final String timelyPassword;
|
|
||||||
private final boolean hostVerificationEnabled;
|
private final boolean hostVerificationEnabled;
|
||||||
private final int bufferSize;
|
private final int bufferSize;
|
||||||
private final SSLContext ssl;
|
private final SSLContext ssl;
|
||||||
@@ -50,71 +46,46 @@ public class WebSocketClient implements AutoCloseable {
|
|||||||
protected Session session = null;
|
protected Session session = null;
|
||||||
protected volatile boolean closed = true;
|
protected volatile boolean closed = true;
|
||||||
|
|
||||||
protected WebSocketClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort,
|
protected WebSocketClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean clientAuth, boolean doLogin,
|
||||||
boolean doLogin, String timelyUsername, String timelyPassword, boolean hostVerificationEnabled,
|
boolean hostVerificationEnabled, int bufferSize) {
|
||||||
int bufferSize) {
|
|
||||||
this.ssl = ssl;
|
this.ssl = ssl;
|
||||||
this.timelyHostname = timelyHostname;
|
this.timelyHostname = timelyHostname;
|
||||||
this.timelyHttpsPort = timelyHttpsPort;
|
this.timelyHttpsPort = timelyHttpsPort;
|
||||||
this.timelyWssPort = timelyWssPort;
|
this.timelyWssPort = timelyWssPort;
|
||||||
this.doLogin = doLogin;
|
this.doLogin = doLogin;
|
||||||
this.timelyUsername = timelyUsername;
|
this.clientAuth = clientAuth;
|
||||||
this.timelyPassword = timelyPassword;
|
|
||||||
this.hostVerificationEnabled = hostVerificationEnabled;
|
this.hostVerificationEnabled = hostVerificationEnabled;
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
|
|
||||||
Preconditions.checkNotNull(timelyHostname, "%s must be supplied", "Timely host name");
|
Preconditions.checkNotNull(timelyHostname, "%s must be supplied", "Timely host name");
|
||||||
Preconditions.checkNotNull(timelyHttpsPort, "%s must be supplied", "Timely HTTPS port");
|
Preconditions.checkNotNull(timelyHttpsPort, "%s must be supplied", "Timely HTTPS port");
|
||||||
Preconditions.checkNotNull(timelyWssPort, "%s must be supplied", "Timely WSS port");
|
Preconditions.checkNotNull(timelyWssPort, "%s must be supplied", "Timely WSS port");
|
||||||
|
|
||||||
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 doLogin,
|
protected WebSocketClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean clientAuth, boolean doLogin, String keyStoreFile,
|
||||||
String timelyUsername, String timelyPassword, String keyStoreFile, String keyStoreType, String keyStorePass,
|
String keyStoreType, String keyStorePass, String trustStoreFile, String trustStoreType, String trustStorePass,
|
||||||
String trustStoreFile, String trustStoreType, String trustStorePass, boolean hostVerificationEnabled,
|
boolean hostVerificationEnabled, int bufferSize) {
|
||||||
int bufferSize) {
|
this(HttpClient.getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType, keyStorePass), timelyHostname,
|
||||||
this(HttpClient.getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType,
|
timelyHttpsPort, timelyWssPort, clientAuth, doLogin, hostVerificationEnabled, bufferSize);
|
||||||
keyStorePass), timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword,
|
|
||||||
hostVerificationEnabled, bufferSize);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void open(ClientHandler clientEndpoint) throws IOException, DeploymentException, URISyntaxException {
|
public void open(ClientHandler clientEndpoint) throws IOException, DeploymentException, URISyntaxException {
|
||||||
|
|
||||||
Cookie sessionCookie = null;
|
Cookie sessionCookie = null;
|
||||||
if (doLogin) {
|
if (doLogin) {
|
||||||
BasicCookieStore cookieJar = new BasicCookieStore();
|
BasicCookieStore cookieJar = new BasicCookieStore();
|
||||||
try (CloseableHttpClient client = HttpClient.get(ssl, cookieJar, hostVerificationEnabled)) {
|
try (CloseableHttpClient client = HttpClient.get(ssl, cookieJar, hostVerificationEnabled, clientAuth)) {
|
||||||
|
|
||||||
String target = "https://" + timelyHostname + ":" + timelyHttpsPort + "/login";
|
String target = "https://" + timelyHostname + ":" + timelyHttpsPort + "/login";
|
||||||
|
|
||||||
HttpRequestBase request = null;
|
HttpRequestBase request = null;
|
||||||
if (StringUtils.isEmpty(timelyUsername)) {
|
// HTTP GET to /login to use certificate based login
|
||||||
// HTTP GET to /login to use certificate based login
|
request = new HttpGet(target);
|
||||||
request = new HttpGet(target);
|
log.trace("Performing client certificate login");
|
||||||
LOG.trace("Performing client certificate login");
|
|
||||||
} else {
|
|
||||||
// HTTP POST to /login to use username/password
|
|
||||||
BasicAuthLogin login = new BasicAuthLogin();
|
|
||||||
login.setUsername(timelyUsername);
|
|
||||||
login.setPassword(timelyPassword);
|
|
||||||
String payload = JsonSerializer.getObjectMapper().writeValueAsString(login);
|
|
||||||
HttpPost post = new HttpPost(target);
|
|
||||||
post.setEntity(new StringEntity(payload));
|
|
||||||
request = post;
|
|
||||||
LOG.trace("Performing BasicAuth login");
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpResponse response = null;
|
HttpResponse response = null;
|
||||||
try {
|
try {
|
||||||
response = client.execute(request);
|
response = client.execute(request);
|
||||||
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
||||||
throw new HttpResponseException(response.getStatusLine().getStatusCode(),
|
throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
|
||||||
response.getStatusLine().getReasonPhrase());
|
|
||||||
}
|
}
|
||||||
for (Cookie c : cookieJar.getCookies()) {
|
for (Cookie c : cookieJar.getCookies()) {
|
||||||
if (c.getName().equals("TSESSIONID")) {
|
if (c.getName().equals("TSESSIONID")) {
|
||||||
@@ -123,8 +94,7 @@ public class WebSocketClient implements AutoCloseable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (null == sessionCookie) {
|
if (null == sessionCookie) {
|
||||||
throw new IllegalStateException(
|
throw new IllegalStateException("Unable to find TSESSIONID cookie header in Timely login response");
|
||||||
"Unable to find TSESSIONID cookie header in Timely login response");
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
HttpClientUtils.closeQuietly(response);
|
HttpClientUtils.closeQuietly(response);
|
||||||
@@ -140,15 +110,14 @@ public class WebSocketClient implements AutoCloseable {
|
|||||||
webSocketClient.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngine);
|
webSocketClient.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngine);
|
||||||
webSocketClient.getProperties().put(ClientProperties.INCOMING_BUFFER_SIZE, bufferSize);
|
webSocketClient.getProperties().put(ClientProperties.INCOMING_BUFFER_SIZE, bufferSize);
|
||||||
String wssPath = "wss://" + timelyHostname + ":" + timelyWssPort + "/websocket";
|
String wssPath = "wss://" + timelyHostname + ":" + timelyWssPort + "/websocket";
|
||||||
session = webSocketClient.connectToServer(clientEndpoint, new TimelyEndpointConfig(sessionCookie),
|
session = webSocketClient.connectToServer(clientEndpoint, new TimelyEndpointConfig(clientEndpoint, sessionCookie), new URI(wssPath));
|
||||||
new URI(wssPath));
|
|
||||||
|
|
||||||
final ByteBuffer pingData = ByteBuffer.allocate(0);
|
final ByteBuffer pingData = ByteBuffer.allocate(0);
|
||||||
webSocketClient.getScheduledExecutorService().scheduleAtFixedRate(() -> {
|
webSocketClient.getScheduledExecutorService().scheduleAtFixedRate(() -> {
|
||||||
try {
|
try {
|
||||||
session.getBasicRemote().sendPing(pingData);
|
session.getBasicRemote().sendPing(pingData);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.error("Error sending ping", e);
|
log.error("Error sending ping", e);
|
||||||
}
|
}
|
||||||
}, 30, 60, TimeUnit.SECONDS);
|
}, 30, 60, TimeUnit.SECONDS);
|
||||||
closed = false;
|
closed = false;
|
||||||
|
|||||||
+19
-18
@@ -13,37 +13,35 @@ import javax.websocket.DeploymentException;
|
|||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import timely.api.AddSubscription;
|
import timely.api.AddSubscription;
|
||||||
import timely.api.CloseSubscription;
|
import timely.api.CloseSubscription;
|
||||||
import timely.api.CreateSubscription;
|
import timely.api.CreateSubscription;
|
||||||
import timely.api.RemoveSubscription;
|
import timely.api.RemoveSubscription;
|
||||||
|
import timely.api.VersionRequest;
|
||||||
import timely.client.websocket.ClientHandler;
|
import timely.client.websocket.ClientHandler;
|
||||||
import timely.client.websocket.WebSocketClient;
|
import timely.client.websocket.WebSocketClient;
|
||||||
import timely.serialize.JsonSerializer;
|
import timely.serialize.JsonSerializer;
|
||||||
|
|
||||||
public class WebSocketSubscriptionClient extends WebSocketClient {
|
public class WebSocketSubscriptionClient extends WebSocketClient {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WebSocketSubscriptionClient.class);
|
private static final Logger log = LoggerFactory.getLogger(WebSocketSubscriptionClient.class);
|
||||||
private final String subscriptionId;
|
private final String subscriptionId;
|
||||||
|
|
||||||
public WebSocketSubscriptionClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort,
|
public WebSocketSubscriptionClient(SSLContext ssl, String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean clientAuth, boolean doLogin,
|
||||||
boolean doLogin, String timelyUsername, String timelyPassword, boolean hostVerificationEnabled,
|
boolean hostVerificationEnabled, int bufferSize) {
|
||||||
int bufferSize) {
|
super(ssl, timelyHostname, timelyHttpsPort, timelyWssPort, clientAuth, doLogin, hostVerificationEnabled, bufferSize);
|
||||||
super(ssl, timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword,
|
|
||||||
hostVerificationEnabled, bufferSize);
|
|
||||||
subscriptionId = UUID.randomUUID().toString();
|
subscriptionId = UUID.randomUUID().toString();
|
||||||
LOG.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
log.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public WebSocketSubscriptionClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean doLogin,
|
public WebSocketSubscriptionClient(String timelyHostname, int timelyHttpsPort, int timelyWssPort, boolean clientAuth, boolean doLogin, String keyStoreFile,
|
||||||
String timelyUsername, String timelyPassword, String keyStoreFile, String keyStoreType, String keyStorePass,
|
String keyStoreType, String keyStorePass, String trustStoreFile, String trustStoreType, String trustStorePass,
|
||||||
String trustStoreFile, String trustStoreType, String trustStorePass, boolean hostVerificationEnabled,
|
boolean hostVerificationEnabled, int bufferSize) {
|
||||||
int bufferSize) {
|
super(timelyHostname, timelyHttpsPort, timelyWssPort, clientAuth, doLogin, keyStoreFile, keyStoreType, keyStorePass, trustStoreFile, trustStoreType,
|
||||||
super(timelyHostname, timelyHttpsPort, timelyWssPort, doLogin, timelyUsername, timelyPassword, keyStoreFile,
|
trustStorePass, hostVerificationEnabled, bufferSize);
|
||||||
keyStoreType, keyStorePass, trustStoreFile, trustStoreType, trustStorePass, hostVerificationEnabled,
|
|
||||||
bufferSize);
|
|
||||||
subscriptionId = UUID.randomUUID().toString();
|
subscriptionId = UUID.randomUUID().toString();
|
||||||
LOG.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
log.trace("Created WebSocketClient with subscriptionId {}", this.subscriptionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -63,14 +61,13 @@ public class WebSocketSubscriptionClient extends WebSocketClient {
|
|||||||
session.getBasicRemote().sendText(JsonSerializer.getObjectMapper().writeValueAsString(close));
|
session.getBasicRemote().sendText(JsonSerializer.getObjectMapper().writeValueAsString(close));
|
||||||
session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Client called close."));
|
session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Client called close."));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.info("Unable to send close message to server: {}", e.getMessage());
|
log.info("Unable to send close message to server: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
super.close();
|
super.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<Void> addSubscription(String metric, Map<String, String> tags, long startTime, long endTime,
|
public Future<Void> addSubscription(String metric, Map<String,String> tags, long startTime, long endTime, long delayTime) throws IOException {
|
||||||
long delayTime) throws IOException {
|
|
||||||
AddSubscription add = new AddSubscription();
|
AddSubscription add = new AddSubscription();
|
||||||
add.setSubscriptionId(subscriptionId);
|
add.setSubscriptionId(subscriptionId);
|
||||||
add.setMetric(metric);
|
add.setMetric(metric);
|
||||||
@@ -88,4 +85,8 @@ public class WebSocketSubscriptionClient extends WebSocketClient {
|
|||||||
return session.getAsyncRemote().sendText(JsonSerializer.getObjectMapper().writeValueAsString(remove));
|
return session.getAsyncRemote().sendText(JsonSerializer.getObjectMapper().writeValueAsString(remove));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Future<Void> requestVersion() throws Exception {
|
||||||
|
VersionRequest version = new VersionRequest();
|
||||||
|
return session.getAsyncRemote().sendText(JsonSerializer.getObjectMapper().writeValueAsString(version));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ def pivot(df, metric, groupByColumn=None):
|
|||||||
return dataFrame
|
return dataFrame
|
||||||
|
|
||||||
|
|
||||||
def resample(df, sample, how='mean'):
|
def resample(df, sample, how='mean', interpolate=True, fill=None):
|
||||||
|
|
||||||
dataFrame = pandas.DataFrame(df, copy=True)
|
dataFrame = pandas.DataFrame(df, copy=True)
|
||||||
if dataFrame is not None:
|
if dataFrame is not None:
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from datetime import tzinfo
|
from datetime import tzinfo
|
||||||
from pandas.tslib import Timedelta
|
|
||||||
import pandas
|
import pandas
|
||||||
|
|
||||||
class TimeDateError(ValueError):
|
class TimeDateError(ValueError):
|
||||||
|
|||||||
@@ -16,14 +16,15 @@ utc = UTC()
|
|||||||
class TimelyWebSocketClient(WebSocketClient):
|
class TimelyWebSocketClient(WebSocketClient):
|
||||||
|
|
||||||
def __init__(self, hostport, metric, tags, startTime, endTime, connect_timeout=WebSocketClient.DEFAULT_CONNECT_TIMEOUT,
|
def __init__(self, hostport, metric, tags, startTime, endTime, connect_timeout=WebSocketClient.DEFAULT_CONNECT_TIMEOUT,
|
||||||
request_timeout=WebSocketClient.DEFAULT_REQUEST_TIMEOUT):
|
request_timeout=WebSocketClient.DEFAULT_REQUEST_TIMEOUT, client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||||
|
|
||||||
self.metric = metric
|
self.metric = metric
|
||||||
self.tags = tags
|
self.tags = tags
|
||||||
self.startTime = startTime
|
self.startTime = startTime
|
||||||
self.endTime = endTime
|
self.endTime = endTime
|
||||||
self.subscriptionId = random.randint(1000000000, 9999999999)
|
self.subscriptionId = random.randint(1000000000, 9999999999)
|
||||||
WebSocketClient.__init__(self, hostport, '/websocket', {'metric' : metric}, connect_timeout, request_timeout)
|
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)
|
||||||
|
|
||||||
def _on_message(self, msg):
|
def _on_message(self, msg):
|
||||||
# implement in subclass
|
# implement in subclass
|
||||||
@@ -72,7 +73,8 @@ class TimelyMetric(TimelyWebSocketClient):
|
|||||||
client = None
|
client = None
|
||||||
endtime = None
|
endtime = None
|
||||||
|
|
||||||
def __init__(self, hostport, metric, tags, beginStr, endStr, period, sample):
|
def __init__(self, hostport, metric, tags, beginStr, endStr, period, sample,
|
||||||
|
client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||||
self.series = pandas.Series()
|
self.series = pandas.Series()
|
||||||
self.metric = metric
|
self.metric = metric
|
||||||
self.tags = tags
|
self.tags = tags
|
||||||
@@ -82,7 +84,8 @@ class TimelyMetric(TimelyWebSocketClient):
|
|||||||
self.data = []
|
self.data = []
|
||||||
self.timeDateRange = TimeDateRange(beginStr, endStr, period)
|
self.timeDateRange = TimeDateRange(beginStr, endStr, period)
|
||||||
|
|
||||||
TimelyWebSocketClient.__init__(self, hostport, metric, tags, self.timeDateRange.getBeginMs(), self.timeDateRange.getEndMs())
|
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)
|
||||||
|
|
||||||
def debugOn(self):
|
def debugOn(self):
|
||||||
self.debug = True
|
self.debug = True
|
||||||
|
|||||||
@@ -15,10 +15,14 @@ class WebSocketClient():
|
|||||||
APPLICATION_JSON = 'application/json'
|
APPLICATION_JSON = 'application/json'
|
||||||
|
|
||||||
def __init__(self, hostport, path, params, connect_timeout=DEFAULT_CONNECT_TIMEOUT,
|
def __init__(self, hostport, path, params, connect_timeout=DEFAULT_CONNECT_TIMEOUT,
|
||||||
request_timeout=DEFAULT_REQUEST_TIMEOUT):
|
request_timeout=DEFAULT_REQUEST_TIMEOUT, client_cert=None, client_key=None, ca_certs=None, validate_cert=False):
|
||||||
|
|
||||||
self.connect_timeout = connect_timeout
|
self.connect_timeout = connect_timeout
|
||||||
self.request_timeout = request_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
|
self.url = 'wss://' + hostport
|
||||||
if (path is not None and len(path) > 0):
|
if (path is not None and len(path) > 0):
|
||||||
if (path.startswith('/')):
|
if (path.startswith('/')):
|
||||||
@@ -39,7 +43,8 @@ class WebSocketClient():
|
|||||||
"""Connect to the server.
|
"""Connect to the server.
|
||||||
:param str url: server URL.
|
:param str url: server URL.
|
||||||
"""
|
"""
|
||||||
request = websocket.httpclient.HTTPRequest(self.url, connect_timeout=self.connect_timeout, request_timeout=self.request_timeout, validate_cert=False)
|
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)
|
||||||
websocket.websocket_connect(request, io_loop=ioloop, callback=self._connect_callback)
|
websocket.websocket_connect(request, io_loop=ioloop, callback=self._connect_callback)
|
||||||
|
|
||||||
def send(self, data):
|
def send(self, data):
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import os
|
|||||||
from timely.TimelyAnalyticConfiguration import TimelyAnalyticConfiguration
|
from timely.TimelyAnalyticConfiguration import TimelyAnalyticConfiguration
|
||||||
|
|
||||||
hostport = "127.0.0.1:5244"
|
hostport = "127.0.0.1:5244"
|
||||||
timelyMetric = timely.TimelyMetric.TimelyMetric(hostport, 'timely.keys.metric.inserted', None, None, None, '24 hours', None).fetch()
|
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()
|
||||||
|
|
||||||
print(timelyMetric.getDataFrame())
|
print(timelyMetric.getDataFrame())
|
||||||
exit()
|
exit()
|
||||||
|
|||||||
Loaded 100 of 675 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user