-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathKsqlRestClient.java
409 lines (354 loc) · 13.5 KB
/
KsqlRestClient.java
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.rest.client;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.confluent.ksql.properties.LocalProperties;
import io.confluent.ksql.rest.client.exception.KsqlRestClientException;
import io.confluent.ksql.rest.entity.ClusterStatusResponse;
import io.confluent.ksql.rest.entity.CommandStatus;
import io.confluent.ksql.rest.entity.CommandStatuses;
import io.confluent.ksql.rest.entity.HealthCheckResponse;
import io.confluent.ksql.rest.entity.HeartbeatResponse;
import io.confluent.ksql.rest.entity.KsqlEntityList;
import io.confluent.ksql.rest.entity.KsqlHostInfoEntity;
import io.confluent.ksql.rest.entity.LagReportingMessage;
import io.confluent.ksql.rest.entity.LagReportingResponse;
import io.confluent.ksql.rest.entity.ServerClusterId;
import io.confluent.ksql.rest.entity.ServerInfo;
import io.confluent.ksql.rest.entity.ServerMetadata;
import io.confluent.ksql.rest.entity.StreamedRow;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpVersion;
import java.io.Closeable;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
public final class KsqlRestClient implements Closeable {
static final String CCLOUD_CONNECT_USERNAME_HEADER = "X-Confluent-API-Key";
static final String CCLOUD_CONNECT_PASSWORD_HEADER = "X-Confluent-API-Secret";
static final int CHUNK_SIZE = 16 * 1024;
private final KsqlClient client;
private final LocalProperties localProperties;
private final AtomicReference<String> serializedConsistencyVector;
private final Optional<BasicCredentials> ccloudApiKey;
private List<URI> serverAddresses;
private boolean isCCloudServer;
/**
* @param serverAddress the address of the KSQL server to connect to.
* @param localProps initial set of local properties.
* @param clientProps properties used to build the client.
* @param creds optional credentials
*/
@Deprecated
public static KsqlRestClient create(
final String serverAddress,
final Map<String, ?> localProps,
final Map<String, String> clientProps,
final Optional<BasicCredentials> creds
) {
return create(
serverAddress,
localProps,
clientProps,
creds,
Optional.empty(),
(cprops, credz, lprops) -> new KsqlClient(cprops, credz, lprops,
new HttpClientOptions(),
Optional.of(new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2)))
);
}
/**
* @param serverAddress the address of the KSQL server to connect to.
* @param localProps initial set of local properties.
* @param clientProps properties used to build the client.
* @param creds optional credentials
* @param ccloudApiKey optional Confluent Cloud credentials for connector management
* from the ksqlDB CLI
*/
public static KsqlRestClient create(
final String serverAddress,
final Map<String, ?> localProps,
final Map<String, String> clientProps,
final Optional<BasicCredentials> creds,
final Optional<BasicCredentials> ccloudApiKey
) {
return create(
serverAddress,
localProps,
clientProps,
creds,
ccloudApiKey,
(cprops, credz, lprops) -> new KsqlClient(cprops, credz, lprops,
new HttpClientOptions().setMaxChunkSize(CHUNK_SIZE),
Optional.of(new HttpClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setMaxChunkSize(CHUNK_SIZE)))
);
}
@VisibleForTesting
static KsqlRestClient create(
final String serverAddress,
final Map<String, ?> localProps,
final Map<String, String> clientProps,
final Optional<BasicCredentials> creds,
final Optional<BasicCredentials> ccloudApiKey,
final KsqlClientSupplier clientSupplier
) {
final LocalProperties localProperties = new LocalProperties(localProps);
final KsqlClient client = clientSupplier.get(clientProps, creds, localProperties);
return new KsqlRestClient(client, serverAddress, localProperties, ccloudApiKey);
}
@FunctionalInterface
interface KsqlClientSupplier {
KsqlClient get(
Map<String, String> clientProps,
Optional<BasicCredentials> creds,
LocalProperties localProps
);
}
private KsqlRestClient(
final KsqlClient client,
final String serverAddress,
final LocalProperties localProps,
final Optional<BasicCredentials> ccloudApiKey
) {
this.client = requireNonNull(client, "client");
this.serverAddresses = parseServerAddresses(serverAddress);
this.localProperties = requireNonNull(localProps, "localProps");
this.ccloudApiKey = ccloudApiKey;
this.serializedConsistencyVector = new AtomicReference<>();
this.isCCloudServer = false;
}
public URI getServerAddress() {
return serverAddresses.get(0);
}
public boolean getIsCCloudServer() {
return isCCloudServer;
}
public boolean getHasCCloudApiKey() {
return ccloudApiKey.isPresent();
}
public void setServerAddress(final String serverAddress) {
this.serverAddresses = parseServerAddresses(serverAddress);
}
public void setIsCCloudServer(final boolean isCCloudServer) {
this.isCCloudServer = isCCloudServer;
}
public RestResponse<ServerInfo> getServerInfo() {
return target().getServerInfo();
}
public RestResponse<CommandStatus> getStatus(final String commandId) {
return target().getStatus(commandId);
}
public RestResponse<CommandStatuses> getAllStatuses() {
return target().getStatuses();
}
public RestResponse<ServerMetadata> getServerMetadata() {
return target().getServerMetadata();
}
public RestResponse<ServerClusterId> getServerMetadataId() {
return target().getServerMetadataId();
}
public RestResponse<HealthCheckResponse> getServerHealth() {
return target().getServerHealth();
}
public CompletableFuture<RestResponse<HeartbeatResponse>> makeAsyncHeartbeatRequest(
final KsqlHostInfoEntity host,
final long timestamp
) {
return target().postAsyncHeartbeatRequest(host, timestamp);
}
public RestResponse<ClusterStatusResponse> makeClusterStatusRequest() {
return target().getClusterStatus();
}
public CompletableFuture<RestResponse<LagReportingResponse>> makeAsyncLagReportingRequest(
final LagReportingMessage lagReportingMessage
) {
return target().postAsyncLagReportingRequest(lagReportingMessage);
}
public RestResponse<KsqlEntityList> makeKsqlRequest(final String ksql) {
return target().postKsqlRequest(ksql, Collections.emptyMap(), Optional.empty());
}
public RestResponse<KsqlEntityList> makeKsqlRequest(final String ksql, final Long commandSeqNum) {
return target()
.postKsqlRequest(ksql, Collections.emptyMap(), Optional.ofNullable(commandSeqNum));
}
public RestResponse<KsqlEntityList> makeConnectorRequest(
final String ksql,
final Long commandSeqNum
) {
return target(true)
.postKsqlRequest(ksql, Collections.emptyMap(), Optional.ofNullable(commandSeqNum));
}
public RestResponse<CommandStatuses> makeStatusRequest() {
return target().getStatuses();
}
public RestResponse<CommandStatus> makeStatusRequest(final String commandId) {
return target().getStatus(commandId);
}
public RestResponse<Boolean> makeIsValidRequest(final String propertyName) {
return target().getIsValidRequest(propertyName);
}
public RestResponse<StreamPublisher<StreamedRow>> makeQueryRequestStreamed(
final String ksql,
final Long commandSeqNum
) {
return makeQueryRequestStreamed(ksql, commandSeqNum, null);
}
public RestResponse<StreamPublisher<StreamedRow>> makeQueryRequestStreamed(
final String ksql,
final Long commandSeqNum,
final Map<String, ?> properties
) {
return makeQueryRequestStreamed(ksql, commandSeqNum, properties, Collections.emptyMap());
}
public RestResponse<StreamPublisher<StreamedRow>> makeQueryRequestStreamed(
final String ksql,
final Long commandSeqNum,
final Map<String, ?> properties,
final Map<String, ?> requestProperties
) {
KsqlTarget target = target();
final Map<String, Object> requestPropertiesToSend = setConsistencyVector(requestProperties);
if (properties != null) {
target = target.properties(properties);
}
final RestResponse<StreamPublisher<StreamedRow>> response = target.postQueryRequestStreamed(
ksql, requestPropertiesToSend, Optional.ofNullable(commandSeqNum));
return response;
}
@VisibleForTesting
public CompletableFuture<RestResponse<StreamPublisher<StreamedRow>>>
makeQueryRequestStreamedAsync(
final String ksql,
final Map<String, ?> properties
) {
KsqlTarget targetHttp2 = targetHttp2();
if (!properties.isEmpty()) {
targetHttp2 = targetHttp2.properties(properties);
}
return targetHttp2.postQueryRequestStreamedAsync(ksql, properties);
}
public RestResponse<List<StreamedRow>> makeQueryRequest(final String ksql,
final Long commandSeqNum) {
return makeQueryRequest(ksql, commandSeqNum, null, Collections.emptyMap());
}
public RestResponse<List<StreamedRow>> makeQueryRequest(
final String ksql,
final Long commandSeqNum,
final Map<String, ?> properties,
final Map<String, ?> requestProperties) {
KsqlTarget target = target();
if (properties != null) {
target = target.properties(properties);
}
final Map<String, Object> requestPropertiesToSend = setConsistencyVector(requestProperties);
return target.postQueryRequest(
ksql, requestPropertiesToSend, Optional.ofNullable(commandSeqNum));
}
public RestResponse<List<StreamedRow>> makeQueryStreamRequestProto(
final String ksql,
final Map<String, Object> requestProperties
) {
final KsqlTarget target = target();
return target.postQueryStreamRequestProto(ksql, requestProperties);
}
public RestResponse<StreamPublisher<String>> makePrintTopicRequest(
final String ksql,
final Long commandSeqNum
) {
return target().postPrintTopicRequest(ksql, Optional.ofNullable(commandSeqNum));
}
@Override
public void close() {
client.close();
}
public Object setProperty(final String property, final Object value) {
return localProperties.set(property, value);
}
public Object unsetProperty(final String property) {
return localProperties.unset(property);
}
public Object getProperty(final String property) {
return localProperties.get(property);
}
@VisibleForTesting
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "should be mutable")
public AtomicReference<String> getSerializedConsistencyVector() {
return serializedConsistencyVector;
}
private KsqlTarget target() {
return target(false);
}
private KsqlTarget target(final boolean includeConnectorHeaders) {
final Map<String, String> additionalHeaders = includeConnectorHeaders && isCCloudServer
? ccloudConnectorHeaders()
: Collections.emptyMap();
return client.target(getServerAddress(), additionalHeaders);
}
private KsqlTarget targetHttp2() {
return client.targetHttp2(getServerAddress());
}
private Map<String, String> ccloudConnectorHeaders() {
if (!ccloudApiKey.isPresent()) {
throw new IllegalStateException("Should not request headers if no credentials provided.");
}
return ImmutableMap.of(
CCLOUD_CONNECT_USERNAME_HEADER, ccloudApiKey.get().username(),
CCLOUD_CONNECT_PASSWORD_HEADER, ccloudApiKey.get().password()
);
}
private static List<URI> parseServerAddresses(final String serverAddresses) {
requireNonNull(serverAddresses, "serverAddress");
return ImmutableList.copyOf(
Arrays.stream(serverAddresses.split(","))
.map(String::trim)
.map(KsqlRestClient::parseUri)
.collect(Collectors.toList()));
}
private static URI parseUri(final String serverAddress) {
try {
final URL url = new URL(serverAddress);
if (url.getPort() == -1) {
return new URL(serverAddress.concat(":") + url.getDefaultPort()).toURI();
}
return url.toURI();
} catch (final Exception e) {
throw new KsqlRestClientException(
"The supplied serverAddress is invalid: " + serverAddress, e);
}
}
private Map<String, Object> setConsistencyVector(
final Map<String, ?> requestProperties
) {
final Map<String, Object> requestPropertiesToSend = new HashMap<>();
if (requestProperties != null) {
requestPropertiesToSend.putAll(requestProperties);
}
return requestPropertiesToSend;
}
}