/
Emulator.java
317 lines (278 loc) · 9.77 KB
/
Emulator.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
/*
* Copyright 2018 Google LLC
*
* 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
*
* https://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.google.cloud.bigtable.emulator.v2;
import com.google.api.core.BetaApi;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Wraps the Bigtable emulator in a java api.
*
* <p>This class will use the golang binaries embedded in this jar to launch the emulator as an
* external process and redirect its output to a {@link Logger}.
*/
@BetaApi("Surface for Bigtable emulator is not yet stable")
public class Emulator {
private static final Logger LOGGER = Logger.getLogger(Emulator.class.getName());
private final Path executable;
private Process process;
private boolean isStopped = true;
private Thread shutdownHook;
private int port;
private ManagedChannel dataChannel;
private ManagedChannel adminChannel;
public static Emulator createFromPath(Path path) {
return new Emulator(path);
}
/**
* Create a new instance of emulator. The emulator will use the bundled binaries in this jar.
* Please note that the emulator is created in a stopped state, please use {@link #start()} after
* creating it.
*/
public static Emulator createBundled() throws IOException {
String resourcePath = getBundledResourcePath();
File tmpEmulator = File.createTempFile("cbtemulator", "");
tmpEmulator.deleteOnExit();
try (InputStream is = Emulator.class.getResourceAsStream(resourcePath);
FileOutputStream os = new FileOutputStream(tmpEmulator)) {
if (is == null) {
throw new FileNotFoundException(
"Failed to find the bundled emulator binary: " + resourcePath);
}
byte[] buff = new byte[2048];
int length;
while ((length = is.read(buff)) != -1) {
os.write(buff, 0, length);
}
}
tmpEmulator.setExecutable(true);
return new Emulator(tmpEmulator.toPath());
}
private Emulator(Path executable) {
this.executable = executable;
}
/** Starts the emulator process and waits for it to be ready. */
public synchronized void start() throws IOException, TimeoutException, InterruptedException {
if (!isStopped) {
throw new IllegalStateException("Emulator is already started");
}
this.port = getAvailablePort();
// Try to align the localhost address across java & golang emulator
// This should fix issues on systems that default to ipv4 but the jvm is started with
// -Djava.net.preferIPv6Addresses=true
Optional<String> localhostAddress = Optional.empty();
try {
localhostAddress = Optional.of(InetAddress.getByName(null).getHostAddress());
} catch (UnknownHostException e) {
}
// Workaround https://bugs.openjdk.java.net/browse/JDK-8068370
for (int attemptsLeft = 3; process == null; attemptsLeft--) {
try {
String cmd = executable.toString();
if (localhostAddress.isPresent()) {
cmd += String.format(" -host [%s]", localhostAddress.get());
}
cmd += String.format(" -port %d", port);
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
if (attemptsLeft > 0) {
Thread.sleep(1000);
continue;
}
throw e;
}
}
pipeStreamToLog(process.getInputStream(), Level.INFO);
pipeStreamToLog(process.getErrorStream(), Level.WARNING);
isStopped = false;
shutdownHook =
new Thread() {
@Override
public void run() {
if (!isStopped) {
isStopped = true;
process.destroy();
}
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
waitForPort(port);
}
/** Stops the emulator process. */
public synchronized void stop() {
if (isStopped) {
throw new IllegalStateException("Emulator already stopped");
}
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
shutdownHook = null;
// Shutdown channels in parallel
if (dataChannel != null) {
dataChannel.shutdownNow();
}
if (adminChannel != null) {
adminChannel.shutdownNow();
}
// Then wait for actual shutdown
if (dataChannel != null) {
dataChannel.awaitTermination(1, TimeUnit.MINUTES);
dataChannel = null;
}
if (adminChannel != null) {
adminChannel.awaitTermination(1, TimeUnit.MINUTES);
adminChannel = null;
}
} catch (InterruptedException e) {
LOGGER.warning("Interrupted while waiting for client channels to close");
Thread.currentThread().interrupt();
} finally {
isStopped = true;
process.destroy();
}
}
public synchronized int getPort() {
if (isStopped) {
throw new IllegalStateException("Emulator is not running");
}
return port;
}
public synchronized ManagedChannel getDataChannel() {
if (isStopped) {
throw new IllegalStateException("Emulator is not running");
}
if (dataChannel == null) {
dataChannel =
newChannelBuilder(port)
.maxInboundMessageSize(256 * 1024 * 1024)
.keepAliveTimeout(10, TimeUnit.SECONDS)
.keepAliveTime(10, TimeUnit.SECONDS)
.keepAliveWithoutCalls(true)
.build();
}
return dataChannel;
}
public synchronized ManagedChannel getAdminChannel() {
if (isStopped) {
throw new IllegalStateException("Emulator is not running");
}
if (adminChannel == null) {
adminChannel = newChannelBuilder(port).build();
}
return adminChannel;
}
// <editor-fold desc="Helpers">
/** Gets the current platform, which will be used to select the appropriate emulator binary. */
private static String getBundledResourcePath() {
String unformattedOs = System.getProperty("os.name", "unknown").toLowerCase(Locale.ENGLISH);
String os;
String suffix = "";
if (unformattedOs.contains("mac") || unformattedOs.contains("darwin")) {
os = "darwin";
} else if (unformattedOs.contains("win")) {
os = "windows";
suffix = ".exe";
} else if (unformattedOs.contains("linux")) {
os = "linux";
} else {
throw new UnsupportedOperationException(
"Emulator is not supported on your platform: " + unformattedOs);
}
String unformattedArch = System.getProperty("os.arch");
String arch;
switch (unformattedArch) {
case "x86":
arch = "x86";
break;
case "x86_64":
case "amd64":
arch = "x86_64";
break;
case "aarch64":
arch = "arm";
break;
default:
throw new UnsupportedOperationException("Unsupported architecture: " + unformattedArch);
}
return String.format(
"/gcloud/bigtable-%s-%s/platform/bigtable-emulator/cbtemulator%s", os, arch, suffix);
}
/** Gets a random open port number. */
private static int getAvailablePort() {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
} catch (IOException e) {
throw new RuntimeException("Failed to find open port");
}
}
/** Waits for a port to open. It's used to wait for the emulator's gRPC server to be ready. */
private static void waitForPort(int port) throws InterruptedException, TimeoutException {
for (int i = 0; i < 100; i++) {
try (Socket ignored = new Socket("localhost", port)) {
return;
} catch (IOException e) {
Thread.sleep(200);
}
}
throw new TimeoutException("Timed out waiting for server to start");
}
/** Creates a {@link io.grpc.ManagedChannelBuilder} preconfigured for the emulator's port. */
private static ManagedChannelBuilder<?> newChannelBuilder(int port) {
// NOTE: usePlaintext is currently @ExperimentalAPI.
// See https://github.com/grpc/grpc-java/issues/1772 for discussion
return ManagedChannelBuilder.forAddress("localhost", port).usePlaintext();
}
/** Creates a thread that will pipe an {@link java.io.InputStream} to this class' Logger. */
private static void pipeStreamToLog(final InputStream stream, final Level level) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
Thread thread =
new Thread(
new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine()) != null) {
LOGGER.log(level, line);
}
} catch (IOException e) {
if (!"Stream closed".equals(e.getMessage())) {
LOGGER.log(Level.WARNING, "Failed to read process stream", e);
}
}
}
});
thread.setDaemon(true);
thread.start();
}
// </editor-fold>
}