-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathConnectionBroker.java
More file actions
329 lines (298 loc) · 17 KB
/
ConnectionBroker.java
File metadata and controls
329 lines (298 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package io.mantisrx.api.push;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.netflix.spectator.api.Counter;
import com.netflix.zuul.netty.SpectatorUtils;
import io.mantisrx.api.Constants;
import io.mantisrx.api.Util;
import io.mantisrx.api.services.JobDiscoveryService;
import io.mantisrx.api.tunnel.MantisCrossRegionalClient;
import io.mantisrx.client.MantisClient;
import io.mantisrx.client.SinkConnectionFunc;
import io.mantisrx.client.SseSinkConnectionFunction;
import io.mantisrx.common.MantisServerSentEvent;
import io.mantisrx.runtime.parameter.SinkParameters;
import io.mantisrx.server.worker.client.MetricsClient;
import io.mantisrx.server.worker.client.SseWorkerConnectionFunction;
import io.mantisrx.server.worker.client.WorkerConnectionsStatus;
import io.mantisrx.server.worker.client.WorkerMetricsClient;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.mantisrx.api.Constants.TunnelPingMessage;
import static io.mantisrx.api.Util.getLocalRegion;
@Slf4j
@Singleton
public class ConnectionBroker {
private final MantisClient mantisClient;
private final MantisCrossRegionalClient mantisCrossRegionalClient;
private final WorkerMetricsClient workerMetricsClient;
private final JobDiscoveryService jobDiscoveryService;
private final Scheduler scheduler;
private final ObjectMapper objectMapper;
private final Map<PushConnectionDetails, Observable<String>> connectionCache = new WeakHashMap<>();
@Inject
public ConnectionBroker(MantisClient mantisClient,
MantisCrossRegionalClient mantisCrossRegionalClient,
WorkerMetricsClient workerMetricsClient,
@Named("io-scheduler") Scheduler scheduler,
ObjectMapper objectMapper) {
this.mantisClient = mantisClient;
this.mantisCrossRegionalClient = mantisCrossRegionalClient;
this.workerMetricsClient = workerMetricsClient;
this.jobDiscoveryService = JobDiscoveryService.getInstance(mantisClient, scheduler);
this.scheduler = scheduler;
this.objectMapper = objectMapper;
}
public Observable<String> connect(PushConnectionDetails details) {
if (!connectionCache.containsKey(details)) {
switch (details.type) {
case CONNECT_BY_NAME:
log.info("Getting connection by name for {} since it is not in cache.", details);
return getConnectByNameFor(details)
.subscribeOn(scheduler)
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnError(t -> log.error("Error in connect by name for " + details, t))
.share();
case CONNECT_BY_ID:
return getConnectByIdFor(details)
.subscribeOn(scheduler)
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.share();
case METRICS:
return getWorkerMetrics(details)
.subscribeOn(scheduler)
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
});
case JOB_STATUS:
connectionCache.put(details,
mantisClient
.getJobStatusObservable(details.target)
.subscribeOn(scheduler)
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.replay(25)
.autoConnect());
break;
case JOB_SCHEDULING_INFO:
connectionCache.put(details,
mantisClient.getSchedulingChanges(details.target)
.subscribeOn(scheduler)
.map(changes -> Try.of(() -> objectMapper.writeValueAsString(changes)).getOrElse("Error"))
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.replay(1)
.autoConnect());
break;
case JOB_CLUSTER_DISCOVERY:
connectionCache.put(details,
jobDiscoveryService.jobDiscoveryInfoStream(jobDiscoveryService.key(JobDiscoveryService.LookupType.JOB_CLUSTER, details.target))
.subscribeOn(scheduler)
.map(jdi ->Try.of(() -> objectMapper.writeValueAsString(jdi)).getOrElse("Error"))
.doOnCompleted(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.doOnUnsubscribe(() -> {
log.info("Purging {} from cache.", details);
connectionCache.remove(details);
})
.replay(1)
.autoConnect());
break;
}
log.info("Caching connection for: {}", details);
}
return connectionCache.get(details);
}
//
// Helpers
//
private Observable<String> getConnectByNameFor(PushConnectionDetails details) {
return details.regions.isEmpty()
? getResults(false, this.mantisClient, details.target, details.getSinkparameters())
.flatMap(m -> m)
.map(MantisServerSentEvent::getEventAsString)
: getRemoteDataObservable(details.getUri(), details.target, details.getRegions().asJava());
}
private Observable<String> getConnectByIdFor(PushConnectionDetails details) {
return details.getRegions().isEmpty()
? getResults(true, this.mantisClient, details.target, details.getSinkparameters())
.flatMap(m -> m)
.map(MantisServerSentEvent::getEventAsString)
: getRemoteDataObservable(details.getUri(), details.target, details.getRegions().asJava());
}
private static SinkConnectionFunc<MantisServerSentEvent> getSseConnFunc(final String target, SinkParameters sinkParameters) {
return new SseSinkConnectionFunction(true,
t -> log.warn("Reconnecting to sink of job " + target + " after error: " + t.getMessage()),
sinkParameters);
}
private static Observable<Observable<MantisServerSentEvent>> getResults(boolean isJobId, MantisClient mantisClient,
final String target, SinkParameters sinkParameters) {
log.info("Getting results for target: {}", target);
final AtomicBoolean hasError = new AtomicBoolean();
return isJobId ?
mantisClient.getSinkClientByJobId(target, getSseConnFunc(target, sinkParameters), null).getResults() :
mantisClient.getSinkClientByJobName(target, getSseConnFunc(target, sinkParameters), null)
.switchMap(serverSentEventSinkClient -> {
if (serverSentEventSinkClient.hasError()) {
hasError.set(true);
log.error("Error getting sink client for job " + target, serverSentEventSinkClient.getError());
return Observable.error(new Exception(serverSentEventSinkClient.getError()));
}
return serverSentEventSinkClient.getResults();
})
.takeWhile(o -> !hasError.get());
}
//
// Tunnel
//
private Observable<String> getRemoteDataObservable(String uri, String target, List<String> regions) {
return Observable.from(regions)
.flatMap(region -> {
final String originReplacement = "\\{\"" + Constants.metaOriginName + "\": \"" + region + "\", ";
if (region.equalsIgnoreCase(getLocalRegion())) {
return this.connect(PushConnectionDetails.from(uri))
.map(datum -> datum.replaceFirst("^\\{", originReplacement));
} else {
log.info("Connecting to remote region {} at {}.", region, uri);
return mantisCrossRegionalClient.getSecureSseClient(region)
.submit(HttpClientRequest.createGet(uri))
// .retryWhen(Util.getRetryFunc(log, uri + " in " + region))
.doOnError(throwable -> log.warn(
"Error getting response from remote SSE server for uri {} in region {}: {}",
uri, region, throwable.getMessage(), throwable)
).flatMap(remoteResponse -> {
if (!remoteResponse.getStatus().reasonPhrase().equals("OK")) {
log.warn("Unexpected response from remote sink for uri {} region {}: {}", uri, region, remoteResponse.getStatus().reasonPhrase());
String err = remoteResponse.getHeaders().get(Constants.metaErrorMsgHeader);
if (err == null || err.isEmpty())
err = remoteResponse.getStatus().reasonPhrase();
return Observable.<MantisServerSentEvent>error(new Exception(err))
.map(datum -> datum.getEventAsString());
}
return clientResponseToObservable(remoteResponse, target, region, uri)
.map(datum -> datum.replaceFirst("^\\{", originReplacement))
.doOnError(t -> log.error(t.getMessage()));
})
.subscribeOn(scheduler)
.observeOn(scheduler)
.doOnError(t -> log.error("Error streaming in remote data ({}). Will retry: {}", region, t.getMessage(), t))
.doOnCompleted(() -> log.info(String.format("remote sink connection complete for uri %s, region=%s", uri, region)));
}
})
.observeOn(scheduler)
.subscribeOn(scheduler)
.doOnError(t -> log.error("Error in flatMapped cross-regional observable for {}", uri, t));
}
private Observable<String> clientResponseToObservable(HttpClientResponse<ServerSentEvent> response, String target, String
region, String uri) {
Counter numRemoteBytes = SpectatorUtils.newCounter(Constants.numRemoteBytesCounterName, target, "region", region);
Counter numRemoteMessages = SpectatorUtils.newCounter(Constants.numRemoteMessagesCounterName, target, "region", region);
Counter numSseErrors = SpectatorUtils.newCounter(Constants.numSseErrorsCounterName, target, "region", region);
return response.getContent()
.doOnError(t -> log.warn(t.getMessage()))
.timeout(3 * Constants.TunnelPingIntervalSecs, TimeUnit.SECONDS)
.doOnError(t -> log.warn("Timeout getting data from remote {} connection for {}", region, uri))
.filter(sse -> !(!sse.hasEventType() || !sse.getEventTypeAsString().startsWith("error:")) ||
!TunnelPingMessage.equals(sse.contentAsString()))
.map(t1 -> {
String data = "";
if (t1.hasEventType() && t1.getEventTypeAsString().startsWith("error:")) {
log.error("SSE has error, type=" + t1.getEventTypeAsString() + ", content=" + t1.contentAsString());
numSseErrors.increment();
throw new RuntimeException("Got error SSE event: " + t1.contentAsString());
}
try {
data = t1.contentAsString();
if (data != null) {
numRemoteBytes.increment(data.length());
numRemoteMessages.increment();
}
} catch (Exception e) {
log.error("Could not extract data from SSE " + e.getMessage(), e);
}
return data;
});
}
private Observable<String> getWorkerMetrics(PushConnectionDetails details) {
final String jobId = details.target;
SinkParameters metricNamesFilter = details.getSinkparameters();
final MetricsClient<MantisServerSentEvent> metricsClient = workerMetricsClient.getMetricsClientByJobId(jobId,
new SseWorkerConnectionFunction(true, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
log.error("Metric connection error: " + throwable.getMessage());
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
log.error("Interrupted waiting for retrying connection");
}
}
}, metricNamesFilter),
new Observer<WorkerConnectionsStatus>() {
@Override
public void onCompleted() {
log.info("got onCompleted in WorkerConnStatus obs");
}
@Override
public void onError(Throwable e) {
log.info("got onError in WorkerConnStatus obs");
}
@Override
public void onNext(WorkerConnectionsStatus workerConnectionsStatus) {
log.info("got WorkerConnStatus {}", workerConnectionsStatus);
}
});
return metricsClient
.getResults()
.flatMap(metrics -> metrics
.map(MantisServerSentEvent::getEventAsString));
}
}