-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathEtcdClusterConfig.java
More file actions
306 lines (273 loc) · 11.5 KB
/
EtcdClusterConfig.java
File metadata and controls
306 lines (273 loc) · 11.5 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
/*
* Copyright 2017, 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ibm.etcd.client.config;
import static com.ibm.etcd.client.KeyUtils.bs;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.protobuf.ByteString;
import com.ibm.etcd.client.EtcdClient;
/**
* See etcd-json-schema.md for the json schema for etcd cluster config
*
*/
public class EtcdClusterConfig {
private static final Logger logger = LoggerFactory.getLogger(EtcdClusterConfig.class);
public static final int DEFAULT_MAX_MSG_SIZE = 256 * 1024 * 1024; // 256 MiB
//TODO later make this more configurable/narrow; only really needed for getting large ranges
protected final int maxMessageSize = Integer.getInteger("etcd-java.maxMessageSize",
DEFAULT_MAX_MSG_SIZE);
public enum TlsMode { TLS, PLAINTEXT, AUTO }
Set<String> endpoints;
TlsMode tlsMode;
ByteString user, password;
ByteString rootPrefix; // a.k.a namespace
@Deprecated
String composeDeployment;
ByteSource certificate;
String overrideAuthority;
protected EtcdClusterConfig() {}
public ByteString getRootPrefix() {
return rootPrefix;
}
public Set<String> getEndpoints() {
return endpoints;
}
public EtcdClient getClient() throws IOException, CertificateException {
return getClient(this);
}
private EtcdClient newClient() throws IOException, CertificateException {
List<String> endpointList = new ArrayList<>(endpoints);
EtcdClient.Builder builder = EtcdClient.forEndpoints(endpointList)
.withCredentials(user, password).withImmediateAuth()
.withMaxInboundMessageSize(maxMessageSize);
if (overrideAuthority != null) {
builder.overrideAuthority(overrideAuthority);
}
TlsMode ssl = tlsMode;
if (ssl == TlsMode.AUTO || ssl == null) {
String ep = endpointList.get(0);
ssl = ep.startsWith("https://")
|| (!ep.startsWith("http://") && certificate != null)
? TlsMode.TLS : TlsMode.PLAINTEXT;
}
if (ssl == TlsMode.PLAINTEXT) {
builder.withPlainText();
} else if (composeDeployment != null) {
builder.withTrustManager(new ComposeTrustManagerFactory(composeDeployment,
composeDeployment, certificate));
} else if (certificate != null) {
builder.withCaCert(certificate);
}
if (isShutdown) {
throw new IllegalStateException("shutdown");
}
return builder.build();
}
// mainly for testing
public static EtcdClusterConfig newSimpleConfig(String endpoints, String rootPrefix) {
EtcdClusterConfig config = new EtcdClusterConfig();
config.endpoints = Sets.newHashSet(endpoints.split(","));
config.rootPrefix = bs(rootPrefix);
return config;
}
public static EtcdClusterConfig fromProperties(ByteSource source) throws IOException {
Properties props = new Properties();
try (InputStream in = source.openStream()) {
props.load(in);
}
String epString = props.getProperty("endpoints");
if (epString == null) {
throw new IOException("etcd config must contain endpoints property");
}
EtcdClusterConfig config = new EtcdClusterConfig();
config.endpoints = Sets.newHashSet(epString.split(","));
config.user = bs(props.getProperty("username"));
config.password = bs(props.getProperty("password"));
config.composeDeployment = props.getProperty("compose_deployment");
config.rootPrefix = bs(props.getProperty("root_prefix")); // a.k.a namespace
String tlsMode = props.getProperty("tls_mode");
if (tlsMode != null) {
config.tlsMode = TlsMode.valueOf(tlsMode);
}
String certPath = props.getProperty("certificate_file");
if (certPath != null) {
File certFile = new File(certPath);
if (!certFile.exists()) {
throw new IOException("cant find certificate file: " + certPath);
}
config.certificate = Files.asByteSource(certFile);
}
config.overrideAuthority = props.getProperty("override_authority");
return config;
}
public static EtcdClusterConfig fromJson(ByteSource source, File dir) throws IOException {
JsonConfig jsonConfig;
try (InputStream in = source.openStream()) {
jsonConfig = deserializeJson(in);
}
if (jsonConfig.endpoints == null || jsonConfig.endpoints.trim().isEmpty()) {
throw new IOException("etcd config must contain endpoints property");
}
EtcdClusterConfig config = new EtcdClusterConfig();
config.endpoints = Sets.newHashSet(jsonConfig.endpoints.split(","));
config.user = bs(jsonConfig.user);
config.password = bs(jsonConfig.password);
config.composeDeployment = jsonConfig.composeDeployment;
config.rootPrefix = bs(jsonConfig.rootPrefix);
if (jsonConfig.certificateFile != null) {
File certFile = new File(jsonConfig.certificateFile);
if (dir != null && !certFile.exists()) {
// try same dir as the config file
certFile = new File(dir, jsonConfig.certificateFile);
}
if (certFile.exists()) {
config.certificate = Files.asByteSource(certFile);
} else {
// will fall back to embedded if present
logger.warn("Can't find certificate file: " + jsonConfig.certificateFile);
}
}
if (jsonConfig.certificate != null) {
if (config.certificate != null) {
logger.warn("Ignoring json-embedded cert because file was also provided");
} else {
config.certificate = ByteSource.wrap(jsonConfig.certificate.getBytes(UTF_8));
}
}
config.overrideAuthority = jsonConfig.overrideAuthority;
return config;
}
public static EtcdClusterConfig fromJson(ByteSource source) throws IOException {
return fromJson(source, null);
}
public static EtcdClusterConfig fromJsonFile(String file) throws IOException {
File f = new File(file);
return fromJson(Files.asByteSource(f), f.getParentFile());
}
protected static final String ADDR_STR = "(?:https?://)?(?:[a-zA-Z0-9\\-.]+)(?::\\d+)?";
protected static final Pattern SIMPLE_PATT = Pattern.compile(String
.format("((?:%s)(?:,%s)*)(?:;rootPrefix=(.+))?", ADDR_STR, ADDR_STR));
/**
* @param fileOrSimpleString path to json config file <b>or</b> simple config of the form
* "endpoint1,endpoint2,...;rootPrefix=<prefix>", where ;rootPrefix=<prefix>
* is optional.
* @throws IOException
*/
public static EtcdClusterConfig fromJsonFileOrSimple(String fileOrSimpleString) throws IOException {
File f = new File(fileOrSimpleString);
if (f.exists()) {
return fromJson(Files.asByteSource(f), f.getParentFile());
}
Matcher m = SIMPLE_PATT.matcher(fileOrSimpleString);
if (m.matches()) {
return EtcdClusterConfig.newSimpleConfig(m.group(1), m.group(2));
}
throw new FileNotFoundException("etcd config json file not found: " + f);
}
private static final Cache<CacheKey,EtcdClient> clientCache = CacheBuilder.newBuilder().weakValues()
.<CacheKey,EtcdClient>removalListener(rn -> rn.getValue().close()).build();
public static EtcdClient getClient(EtcdClusterConfig config) throws IOException, CertificateException {
try {
return clientCache.get(new CacheKey(config), config::newClient);
} catch (ExecutionException ee) {
Throwables.throwIfInstanceOf(ee.getCause(), IOException.class);
Throwables.throwIfInstanceOf(ee.getCause(), CertificateException.class);
Throwables.throwIfUnchecked(ee.getCause());
throw new RuntimeException(ee.getCause());
}
}
private static volatile boolean isShutdown = false;
/**
* Should generally only be called during JVM shutdown
*/
public static void shutdownAll() {
isShutdown = true;
clientCache.invalidateAll();
}
static class CacheKey {
private final EtcdClusterConfig config;
CacheKey(EtcdClusterConfig config) {
this.config = Preconditions.checkNotNull(config);
}
// NOTE: rootPrefix is currently intentionally excluded
// since it's not used to build the client
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CacheKey)) {
return false;
}
EtcdClusterConfig other = ((CacheKey) obj).config;
return Objects.equals(config.endpoints, other.endpoints)
&& Objects.equals(config.composeDeployment, other.composeDeployment)
&& Objects.equals(config.user, other.user)
&& Objects.equals(config.tlsMode, other.tlsMode);
}
@Override
public int hashCode() {
return Objects.hash(config.endpoints, config.user,
config.composeDeployment, config.tlsMode);
}
}
// ---- json deserialization
private static final Gson gson = new Gson();
private static JsonConfig deserializeJson(InputStream in) {
return gson.fromJson(new InputStreamReader(in, StandardCharsets.UTF_8), JsonConfig.class);
}
static class JsonConfig {
@SerializedName("endpoints")
String endpoints;
@SerializedName("userid")
String user;
@SerializedName("password")
String password;
@SerializedName("root_prefix") // a.k.a namespace
String rootPrefix;
@Deprecated
@SerializedName("compose_deployment")
String composeDeployment;
@SerializedName("certificate")
String certificate;
@SerializedName("certificate_file")
String certificateFile;
@SerializedName("override_authority")
String overrideAuthority;
}
}