/
LocalDatastoreHelper.java
339 lines (301 loc) · 11.9 KB
/
LocalDatastoreHelper.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
/*
* Copyright 2015 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
*
* 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.google.cloud.datastore.testing;
import com.google.api.core.InternalApi;
import com.google.cloud.NoCredentials;
import com.google.cloud.ServiceOptions;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.testing.BaseEmulatorHelper;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import org.threeten.bp.Duration;
/**
* Utility to start and stop local Google Cloud Datastore emulators.
*
* <p>This class is unstable.
*/
@InternalApi
public class LocalDatastoreHelper extends BaseEmulatorHelper<DatastoreOptions> {
private final List<EmulatorRunner> emulatorRunners;
private final double consistency;
private final Path gcdPath;
private boolean storeOnDisk;
// Gcloud emulator settings
private static final String GCLOUD_CMD_TEXT = "gcloud beta emulators datastore start";
private static final String GCLOUD_CMD_PORT_FLAG = "--host-port=";
private static final String VERSION_PREFIX = "cloud-datastore-emulator ";
private static final String MIN_VERSION = "1.2.0";
// Downloadable emulator settings
private static final String BIN_NAME = "cloud-datastore-emulator/cloud_datastore_emulator";
private static final String FILENAME = "cloud-datastore-emulator-" + MIN_VERSION + ".zip";
private static final String MD5_CHECKSUM = "ec2237a0f0ac54964c6bd95e12c73720";
private static final String BIN_CMD_PORT_FLAG = "--port=";
private static final URL EMULATOR_URL;
// Common settings
private static final String CONSISTENCY_FLAG = "--consistency=";
private static final double DEFAULT_CONSISTENCY = 0.9;
private static final Logger LOGGER = Logger.getLogger(LocalDatastoreHelper.class.getName());
static {
try {
EMULATOR_URL = new URL("http://storage.googleapis.com/gcd/tools/" + FILENAME);
} catch (MalformedURLException ex) {
throw new IllegalStateException(ex);
}
}
/** A builder for {@code LocalDatastoreHelper} objects. */
public static class Builder {
private double consistency;
private int port;
private Path dataDir;
private boolean storeOnDisk = true;
private Builder() {}
private Builder(LocalDatastoreHelper helper) {
this.consistency = helper.consistency;
this.dataDir = helper.gcdPath;
this.storeOnDisk = helper.storeOnDisk;
}
public Builder setConsistency(double consistency) {
this.consistency = consistency;
return this;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public Builder setDataDir(Path dataDir) {
this.dataDir = dataDir;
return this;
}
public Builder setStoreOnDisk(boolean storeOnDisk) {
this.storeOnDisk = storeOnDisk;
return this;
}
/** Creates a {@code LocalDatastoreHelper} object. */
public LocalDatastoreHelper build() {
return new LocalDatastoreHelper(this);
}
}
private LocalDatastoreHelper(Builder builder) {
super(
"datastore",
builder.port > 0 ? builder.port : BaseEmulatorHelper.findAvailablePort(DEFAULT_PORT),
PROJECT_ID_PREFIX + UUID.randomUUID().toString());
this.consistency = builder.consistency > 0 ? builder.consistency : DEFAULT_CONSISTENCY;
this.gcdPath = builder.dataDir;
this.storeOnDisk = builder.storeOnDisk;
String binName = BIN_NAME;
if (isWindows()) {
binName = BIN_NAME.replace("/", "\\");
}
List<String> gcloudCommand = new ArrayList<>(Arrays.asList(GCLOUD_CMD_TEXT.split(" ")));
gcloudCommand.add(GCLOUD_CMD_PORT_FLAG + "localhost:" + getPort());
gcloudCommand.add(CONSISTENCY_FLAG + builder.consistency);
if (!builder.storeOnDisk) {
gcloudCommand.add("--no-store-on-disk");
}
GcloudEmulatorRunner gcloudRunner =
new GcloudEmulatorRunner(gcloudCommand, VERSION_PREFIX, MIN_VERSION);
List<String> binCommand = new ArrayList<>(Arrays.asList(binName, "start"));
binCommand.add("--testing");
binCommand.add(BIN_CMD_PORT_FLAG + getPort());
binCommand.add(CONSISTENCY_FLAG + getConsistency());
if (builder.dataDir != null) {
gcloudCommand.add("--data-dir=" + getGcdPath());
}
DownloadableEmulatorRunner downloadRunner =
new DownloadableEmulatorRunner(binCommand, EMULATOR_URL, MD5_CHECKSUM);
this.emulatorRunners = ImmutableList.of(gcloudRunner, downloadRunner);
}
/** Returns a builder for {@code LocalDatastoreHelper} object. */
public LocalDatastoreHelper.Builder toBuilder() {
return new Builder(this);
}
/** Returns a builder for {@code LocalDatastoreHelper} object. */
public static LocalDatastoreHelper.Builder newBuilder() {
return new LocalDatastoreHelper.Builder();
}
@Override
protected List<EmulatorRunner> getEmulatorRunners() {
return emulatorRunners;
}
@Override
protected Logger getLogger() {
return LOGGER;
}
private DatastoreOptions.Builder optionsBuilder() {
return DatastoreOptions.newBuilder()
.setProjectId(getProjectId())
.setHost(DEFAULT_HOST + ":" + Integer.toString(getPort()))
.setCredentials(NoCredentials.getInstance())
.setRetrySettings(ServiceOptions.getNoRetrySettings());
}
/**
* Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
* localhost.
*/
@Override
public DatastoreOptions getOptions() {
return optionsBuilder().build();
}
/**
* Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
* localhost. The default namespace is set to {@code namespace}.
*/
public DatastoreOptions getOptions(String namespace) {
return optionsBuilder().setNamespace(namespace).build();
}
/** Returns the consistency setting for the local Datastore emulator. */
public double getConsistency() {
return consistency;
}
/** Returns the data directory path of the local Datastore emulator. */
public Path getGcdPath() {
return gcdPath;
}
/** Returns {@code true} data persist on disk, otherwise {@code false} data not store on disk. */
public boolean isStoreOnDisk() {
return storeOnDisk;
}
/**
* Creates a local Datastore helper with the specified settings for project ID and consistency.
*
* @param consistency the fraction of Datastore writes that are immediately visible to global
* queries, with 0.0 meaning no writes are immediately visible and 1.0 meaning all writes are
* immediately visible. Note that setting this to 1.0 may mask incorrect assumptions about the
* consistency of non-ancestor queries; non-ancestor queries are eventually consistent.
*/
public static LocalDatastoreHelper create(double consistency) {
return LocalDatastoreHelper.newBuilder().setConsistency(consistency).setPort(0).build();
}
/**
* Creates a local Datastore helper with the specified settings for project ID and consistency.
*
* @param consistency the fraction of Datastore writes that are immediately visible to global
* queries, with 0.0 meaning no writes are immediately visible and 1.0 meaning all writes are
* immediately visible. Note that setting this to 1.0 may mask incorrect assumptions about the
* consistency of non-ancestor queries; non-ancestor queries are eventually consistent.
* @param port the port to be used to start the emulator service. Note that setting this to 0 the
* emulator will search for a free random port.
*/
public static LocalDatastoreHelper create(double consistency, int port) {
return LocalDatastoreHelper.newBuilder().setConsistency(consistency).setPort(port).build();
}
/**
* Creates a local Datastore helper with a placeholder project ID and the default consistency
* setting of 0.9.
*
* @param port the port to be used to start the emulator service. Note that setting this to 0 the
* emulator will search for a free random port.
*/
public static LocalDatastoreHelper create(int port) {
return LocalDatastoreHelper.newBuilder()
.setConsistency(DEFAULT_CONSISTENCY)
.setPort(port)
.build();
}
/**
* Creates a local Datastore helper with a placeholder project ID and the default consistency
* setting of 0.9. Consistency refers to the fraction of Datastore writes that are immediately
* visible to global queries, with 0.0 meaning no writes are immediately visible and 1.0 meaning
* all writes are immediately visible.
*/
public static LocalDatastoreHelper create() {
return LocalDatastoreHelper.newBuilder().setConsistency(DEFAULT_CONSISTENCY).build();
}
/**
* Starts the local Datastore emulator through {@code gcloud}, downloads and caches the zip file
* if user does not have {@code gcloud} or a compatible emulator version installed.
*
* <p>Currently the emulator does not persist any state across runs.
*/
@Override
public void start() throws IOException, InterruptedException {
String blockUntilOutput = "Dev App Server is now running";
startProcess(blockUntilOutput);
}
/**
* Resets the internal state of the Datastore emulator.
*
* <p>When running tests, one might {@code reset()} before each test, so earlier tests would not
* affect later ones.
*/
@Override
public void reset() throws IOException {
sendPostRequest("/reset");
}
/**
* Stops the Datastore emulator.
*
* <p>It is important to stop the emulator. Since the emulator runs in its own process, not
* stopping it might cause it to become orphan.
*
* <p>It is not required to call {@link #reset()} before {@code stop}.
*
* @param timeout The duration to wait for the emulator process to stop. It is recommended to set
* this value high to ensure proper shutdown, like 5 seconds or more.
*/
@Override
public void stop(Duration timeout) throws IOException, InterruptedException, TimeoutException {
sendPostRequest("/shutdown");
waitForProcess(timeout);
deleteRecursively(gcdPath);
}
/**
* Stops the Datastore emulator. The same as {@link #stop(Duration)} but with timeout duration of
* 20 seconds.
*
* <p>It is important to stop the emulator. Since the emulator runs in its own process, not
* stopping it might cause it to become orphan.
*
* <p>It is not required to call {@link #reset()} before {@code stop()}.
*/
public void stop() throws IOException, InterruptedException, TimeoutException {
stop(Duration.ofSeconds(20));
}
static void deleteRecursively(Path path) throws IOException {
if (path == null || !Files.exists(path)) {
return;
}
Files.walkFileTree(
path,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
}
}