/
CloudClientExecutor.java
3522 lines (3365 loc) · 153 KB
/
CloudClientExecutor.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2022 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.executor.spanner;
import static com.google.cloud.spanner.TransactionRunner.TransactionCallable;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.Page;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.DeadlineExceededException;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnavailableException;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.NoCredentials;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Backup;
import com.google.cloud.spanner.BatchClient;
import com.google.cloud.spanner.BatchReadOnlyTransaction;
import com.google.cloud.spanner.BatchTransactionId;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.InstanceAdminClient;
import com.google.cloud.spanner.InstanceConfig;
import com.google.cloud.spanner.InstanceConfigId;
import com.google.cloud.spanner.InstanceConfigInfo;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.InstanceInfo;
import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeyRange;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Mutation.WriteBuilder;
import com.google.cloud.spanner.Options;
import com.google.cloud.spanner.Options.RpcPriority;
import com.google.cloud.spanner.Partition;
import com.google.cloud.spanner.PartitionOptions;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ReplicaInfo;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.StructReader;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.TransactionRunner;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.encryption.CustomerManagedEncryption;
import com.google.cloud.spanner.v1.stub.SpannerStubSettings;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.longrunning.Operation;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.Timestamps;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata;
import com.google.spanner.admin.instance.v1.Instance.State;
import com.google.spanner.executor.v1.AdminAction;
import com.google.spanner.executor.v1.AdminResult;
import com.google.spanner.executor.v1.BatchDmlAction;
import com.google.spanner.executor.v1.BatchPartition;
import com.google.spanner.executor.v1.CancelOperationAction;
import com.google.spanner.executor.v1.ChangeStreamRecord;
import com.google.spanner.executor.v1.ChildPartitionsRecord;
import com.google.spanner.executor.v1.CloseBatchTransactionAction;
import com.google.spanner.executor.v1.CloudBackupResponse;
import com.google.spanner.executor.v1.CloudDatabaseResponse;
import com.google.spanner.executor.v1.CloudInstanceConfigResponse;
import com.google.spanner.executor.v1.CloudInstanceResponse;
import com.google.spanner.executor.v1.Concurrency;
import com.google.spanner.executor.v1.CopyCloudBackupAction;
import com.google.spanner.executor.v1.CreateCloudBackupAction;
import com.google.spanner.executor.v1.CreateCloudDatabaseAction;
import com.google.spanner.executor.v1.CreateCloudInstanceAction;
import com.google.spanner.executor.v1.CreateUserInstanceConfigAction;
import com.google.spanner.executor.v1.DataChangeRecord;
import com.google.spanner.executor.v1.DeleteCloudBackupAction;
import com.google.spanner.executor.v1.DeleteCloudInstanceAction;
import com.google.spanner.executor.v1.DeleteUserInstanceConfigAction;
import com.google.spanner.executor.v1.DmlAction;
import com.google.spanner.executor.v1.DropCloudDatabaseAction;
import com.google.spanner.executor.v1.ExecuteChangeStreamQuery;
import com.google.spanner.executor.v1.ExecutePartitionAction;
import com.google.spanner.executor.v1.FinishTransactionAction;
import com.google.spanner.executor.v1.FinishTransactionAction.Mode;
import com.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction;
import com.google.spanner.executor.v1.GenerateDbPartitionsForReadAction;
import com.google.spanner.executor.v1.GetCloudBackupAction;
import com.google.spanner.executor.v1.GetCloudDatabaseAction;
import com.google.spanner.executor.v1.GetCloudInstanceAction;
import com.google.spanner.executor.v1.GetCloudInstanceConfigAction;
import com.google.spanner.executor.v1.GetOperationAction;
import com.google.spanner.executor.v1.HeartbeatRecord;
import com.google.spanner.executor.v1.ListCloudBackupOperationsAction;
import com.google.spanner.executor.v1.ListCloudBackupsAction;
import com.google.spanner.executor.v1.ListCloudDatabaseOperationsAction;
import com.google.spanner.executor.v1.ListCloudDatabasesAction;
import com.google.spanner.executor.v1.ListCloudInstanceConfigsAction;
import com.google.spanner.executor.v1.ListCloudInstancesAction;
import com.google.spanner.executor.v1.MutationAction;
import com.google.spanner.executor.v1.MutationAction.InsertArgs;
import com.google.spanner.executor.v1.MutationAction.Mod;
import com.google.spanner.executor.v1.MutationAction.UpdateArgs;
import com.google.spanner.executor.v1.OperationResponse;
import com.google.spanner.executor.v1.PartitionedUpdateAction;
import com.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions;
import com.google.spanner.executor.v1.QueryAction;
import com.google.spanner.executor.v1.ReadAction;
import com.google.spanner.executor.v1.RestoreCloudDatabaseAction;
import com.google.spanner.executor.v1.SpannerAction;
import com.google.spanner.executor.v1.SpannerActionOutcome;
import com.google.spanner.executor.v1.SpannerAsyncActionRequest;
import com.google.spanner.executor.v1.SpannerAsyncActionResponse;
import com.google.spanner.executor.v1.StartBatchTransactionAction;
import com.google.spanner.executor.v1.StartTransactionAction;
import com.google.spanner.executor.v1.TransactionExecutionOptions;
import com.google.spanner.executor.v1.UpdateCloudBackupAction;
import com.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction;
import com.google.spanner.executor.v1.UpdateCloudInstanceAction;
import com.google.spanner.v1.StructType;
import com.google.spanner.v1.TypeAnnotationCode;
import com.google.spanner.v1.TypeCode;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.threeten.bp.Duration;
import org.threeten.bp.LocalDate;
/**
* Implementation of the SpannerExecutorProxy gRPC service that proxies action request through the
* Java Cloud Client.
*/
public class CloudClientExecutor extends CloudExecutor {
private static final Logger LOGGER = Logger.getLogger(CloudClientExecutor.class.getName());
// Prefix for host address.
private static final String HOST_PREFIX = "https://localhost:";
public CloudClientExecutor(boolean enableGrpcFaultInjector) {
this.enableGrpcFaultInjector = enableGrpcFaultInjector;
}
/**
* Implementation of a ReadWriteTransaction, which is a wrapper of the cloud TransactionRunner. It
* stores all the status and related variables from the start to finish, and control the running
* flow of this transaction.
*
* <p>The following functions should be called on this struct externally:
*
* <p>startRWTransaction() initializes a transaction. It creates a callable and runs it with a
* ReadWriteTransaction() runner in a separate thread. That callable will accept a
* transactionContext when created, and we will pass it out to execute actions on it. Then the
* callable will be blocked until we need to exit (e.g. commit) the transaction.
*
* <p>getContext() returns the current ReadWriteTransaction context. Reads and writes can be
* performed on that object.
*
* <p>finish() is used to either commit or abandon the transaction. It gets a finishMode from
* finishAction and essentially unblocks the separate callable thread that's waiting inside
* ReadWriteTransaction(). As a result of this call, Spanner will commit the current transaction,
* abandon it without committing, or restart it, in which case the client should get a new
* transaction instance using getContext() and replay all the reads and writes through it.
*
* <p>Here's a typical workflow for how a read-write transaction works.
*
* <p>When we call startRWTransaction, a transaction runner will be started in another thread with
* a callable that stores the passed TransactionContext into the ReadWriteTransaction and blocks.
* This TransactionContext is used to run the read/write actions. To execute the finish action, we
* store the FinishMode in the ReadWriteTransaction object, which unblocks the thread in the
* callable and causes the callable to either return (to commit) or throw an exception (to abort).
* If the underlying Spanner transaction aborted, the transaction runner will invoke the callable
* again.
*/
private static class ReadWriteTransaction {
private final DatabaseClient dbClient;
private TransactionRunner runner;
private TransactionContext txnContext;
private com.google.protobuf.Timestamp timestamp;
private Mode finishMode;
private SpannerException error;
private final String transactionSeed;
private final boolean optimistic;
// Set to true when the transaction runner completed, one of these three could happen: runner
// committed, abandoned or threw an error.
private boolean runnerCompleted;
public ReadWriteTransaction(
DatabaseClient dbClient, String transactionSeed, boolean optimistic) {
this.dbClient = dbClient;
this.transactionSeed = transactionSeed;
this.optimistic = optimistic;
this.runnerCompleted = false;
}
/** Set context to be used for executing actions. */
private synchronized void setContext(TransactionContext transaction) {
finishMode = null;
txnContext = transaction;
Preconditions.checkNotNull(txnContext);
LOGGER.log(Level.INFO, "Transaction callable created, setting context %s\n", transactionSeed);
notifyAll();
}
/** Wait for finishAction to be executed and return the requested finish mode. */
private synchronized Mode waitForFinishAction() throws Exception {
while (finishMode == null) {
wait();
}
return finishMode;
}
/** Wait for transactionContext to be set. */
private synchronized void waitForTransactionContext() throws Exception {
while (txnContext == null && error == null) {
wait();
}
if (error != null) {
throw error;
}
}
/** Transaction successfully committed with a timestamp. */
private synchronized void transactionSucceeded(com.google.protobuf.Timestamp timestamp) {
this.timestamp = timestamp;
this.runnerCompleted = true;
notifyAll();
}
/** Transaction failed to commit, maybe abandoned or other errors occurred. */
private synchronized void transactionFailed(SpannerException e) {
// Handle abandon case
if (e.getErrorCode() == ErrorCode.UNKNOWN && e.getMessage().contains(TRANSACTION_ABANDONED)) {
LOGGER.log(Level.INFO, "Transaction abandoned");
} else {
// Store the error for sending back
error = e;
}
this.runnerCompleted = true;
notifyAll();
}
/** Return the commit timestamp. */
public synchronized com.google.protobuf.Timestamp getTimestamp() {
return timestamp;
}
/** Return the transactionContext to run actions. Must be called after start action. */
public synchronized TransactionContext getContext() {
Preconditions.checkState(txnContext != null);
return txnContext;
}
/**
* Create a new transaction runner and corresponding transaction callable to start a read-write
* transaction.
*/
public void startRWTransaction() throws Exception {
final TransactionCallable<Void> callable =
transaction -> {
setContext(transaction);
LOGGER.log(
Level.INFO,
String.format(
"Transaction context set, executing and waiting for finish %s\n",
transactionSeed));
Mode mode = waitForFinishAction();
if (mode == Mode.ABANDON) {
throw new Exception(TRANSACTION_ABANDONED);
}
// Try to commit
return null;
};
Runnable runnable =
() -> {
try {
runner =
optimistic
? dbClient.readWriteTransaction(Options.optimisticLock())
: dbClient.readWriteTransaction();
LOGGER.log(Level.INFO, String.format("Ready to run callable %s\n", transactionSeed));
runner.run(callable);
transactionSucceeded(runner.getCommitTimestamp().toProto());
} catch (SpannerException e) {
LOGGER.log(
Level.WARNING,
String.format("Transaction runnable failed with exception %s\n", e.getMessage()),
e);
transactionFailed(e);
}
};
LOGGER.log(
Level.INFO,
String.format("Callable and Runnable created, ready to execute %s\n", transactionSeed));
txnThreadPool.execute(runnable);
waitForTransactionContext();
LOGGER.log(
Level.INFO,
String.format("Transaction successfully created and running %s\n", transactionSeed));
}
/**
* Finish current transaction in given finishMode, if failed, throw the exception back to
* caller. Returns true if the transaction completed (i.e., committed), false if it was
* restarted by the transaction runner.
*/
public synchronized boolean finish(Mode finishMode) throws Exception {
switch (finishMode) {
case COMMIT:
case ABANDON:
// Signal that finish action has been called and finishMode has been set.
this.finishMode = finishMode;
Preconditions.checkNotNull(finishMode);
txnContext = null;
LOGGER.log(
Level.INFO,
String.format(
"TxnContext cleared, sending finishMode to finish transaction %s\n",
transactionSeed));
notifyAll();
// Wait for the transaction to finish or restart
while (txnContext == null && !runnerCompleted) {
wait();
}
LOGGER.log(
Level.INFO,
String.format("Transaction finished, getting back to caller %s\n", transactionSeed));
if (txnContext != null) {
// Transaction restarted
return false;
} else if (error != null) {
// Transaction runner threw an exception: re-throw it to the client.
// Filter expected errors
if (error.getErrorCode() == ErrorCode.UNKNOWN
&& error.getMessage().contains("Transaction outcome unknown")) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.DEADLINE_EXCEEDED, "Transaction outcome unknown.");
} else {
throw error;
}
}
// Transaction successfully completed
return true;
default:
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unsupported finish mode: " + finishMode);
}
}
}
/**
* All the context in which SpannerActions are executed. It stores the current running transaction
* and table metadata, shared by all the action executor and protected by a lock. There will only
* be exactly one instance of this class per stubby call, created when the executor is
* initialized.
*/
class ExecutionFlowContext {
// Database path from previous action
private String prevDbPath;
// Current read-write transaction
private ReadWriteTransaction rwTxn;
// Current read-only transaction
private ReadOnlyTransaction roTxn;
// Current batch read-only transaction
private BatchReadOnlyTransaction batchTxn;
// Current database client
private DatabaseClient dbClient;
// Metadata info about table columns
private Metadata metadata;
// Number of pending read/query actions.
private int numPendingReads;
// Indicate whether there's a read/query action got aborted and the transaction need to be
// reset.
private boolean readAborted;
// Log the workid and op pair for tracing the thread.
private String transactionSeed;
// Outgoing stream.
StreamObserver<SpannerAsyncActionResponse> responseObserver;
public ExecutionFlowContext(StreamObserver<SpannerAsyncActionResponse> responseObserver) {
this.responseObserver = responseObserver;
}
/** Call the underlying stream to send response. */
public synchronized void onNext(SpannerAsyncActionResponse response) {
responseObserver.onNext(response);
}
/** Call the underlying stream to send error. */
public synchronized void onError(Throwable t) {
responseObserver.onError(t);
}
/** Return current transaction that can used for performing read/query actions. */
public synchronized ReadContext getTransactionForRead() throws SpannerException {
if (roTxn != null) {
return roTxn;
}
if (rwTxn != null) {
return rwTxn.getContext();
}
if (batchTxn != null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Can't execute regular read in a batch transaction");
}
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "No active transaction");
}
/** Return current transaction that can used for performing mutation/update actions. */
public synchronized TransactionContext getTransactionForWrite() throws SpannerException {
if (rwTxn == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Not in a read-write transaction");
}
return rwTxn.getContext();
}
/** Return current batch transaction if it exists. */
public synchronized BatchReadOnlyTransaction getBatchTxn() throws SpannerException {
if (batchTxn == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Not in a batch transaction");
}
return batchTxn;
}
/** Set the transactionSeed string retrieved from startTransactionAction. */
public synchronized void updateTransactionSeed(String transactionSeed) {
if (!transactionSeed.isEmpty()) {
this.transactionSeed = transactionSeed;
}
}
/** Return current workid and op pair for logging. */
public synchronized String getTransactionSeed() {
return transactionSeed;
}
/** Return current database client. */
public DatabaseClient getDbClient() {
return dbClient;
}
/** Clear the transaction related variables. */
public synchronized void clear() {
rwTxn = null;
roTxn = null;
metadata = null;
}
/** Cleanup all the active transactions if the stubby call is closing. */
public synchronized void cleanup() {
if (roTxn != null) {
LOGGER.log(Level.INFO, "A read only transaction was active when stubby call closed");
roTxn.close();
}
if (rwTxn != null) {
LOGGER.log(Level.INFO, "A read write transaction was active when stubby call closed");
try {
rwTxn.finish(Mode.ABANDON);
} catch (Exception e) {
LOGGER.log(
Level.WARNING, "Failed to abandon a read-write transaction: " + e.getMessage());
}
}
}
/** Return previous databasePath if given dbPath is empty, then update. */
public synchronized String getDatabasePath(String dbPath) {
if (dbPath == null || dbPath.isEmpty()) {
return prevDbPath;
}
prevDbPath = dbPath;
return dbPath;
}
/** Set the metadata for future use. */
public synchronized void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
/** Start a read-only transaction. */
public synchronized void startReadOnlyTxn(
DatabaseClient dbClient, TimestampBound timestampBound, Metadata metadata) {
if ((rwTxn != null) || (roTxn != null) || (batchTxn != null)) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Already in a transaction");
}
this.metadata = metadata;
if (timestampBound.getMode() == TimestampBound.Mode.MIN_READ_TIMESTAMP
|| timestampBound.getMode() == TimestampBound.Mode.MAX_STALENESS) {
roTxn = dbClient.singleUseReadOnlyTransaction(timestampBound);
} else {
roTxn = dbClient.readOnlyTransaction(timestampBound);
}
}
/** Start a read-write transaction. */
public synchronized void startReadWriteTxn(
DatabaseClient dbClient, Metadata metadata, TransactionExecutionOptions options)
throws Exception {
if ((rwTxn != null) || (roTxn != null) || (batchTxn != null)) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Already in a transaction");
}
LOGGER.log(
Level.INFO,
String.format(
"There's no active transaction, safe to create rwTxn: %s\n", getTransactionSeed()));
this.metadata = metadata;
rwTxn = new ReadWriteTransaction(dbClient, transactionSeed, options.getOptimistic());
LOGGER.log(
Level.INFO,
String.format(
"Read-write transaction object created, try to start: %s\n", getTransactionSeed()));
rwTxn.startRWTransaction();
}
/** Start a batch transaction. */
public synchronized Status startBatchTxn(
StartBatchTransactionAction action, BatchClient batchClient, OutcomeSender sender) {
try {
if ((rwTxn != null) || (roTxn != null) || (batchTxn != null)) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Already in a transaction");
}
if (action.hasBatchTxnTime()) {
TimestampBound timestampBound =
TimestampBound.ofReadTimestamp(Timestamp.fromProto(action.getBatchTxnTime()));
batchTxn = batchClient.batchReadOnlyTransaction(timestampBound);
} else if (action.hasTid()) {
BatchTransactionId tId = unmarshall(action.getTid());
batchTxn = batchClient.batchReadOnlyTransaction(tId);
} else {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Either timestamp or tid must be set");
}
SpannerActionOutcome outcome =
SpannerActionOutcome.newBuilder()
.setStatus(toProto(Status.OK))
.setBatchTxnId(marshall(batchTxn.getBatchTransactionId()))
.build();
initReadState();
return sender.sendOutcome(outcome);
} catch (SpannerException e) {
return sender.finishWithError(toStatus(e));
} catch (Exception e) {
return sender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unexpected error: " + e.getMessage())));
}
}
/** Increase the read count when a read/query is issued. */
public synchronized void startRead() {
++numPendingReads;
}
/**
* Decrease the read count when a read/query is finished, if status is aborted and there's no
* pending read/query, reset the transaction for retry.
*/
public synchronized void finishRead(Status status) {
if (status.getCode() == Status.ABORTED.getCode()) {
readAborted = true;
}
--numPendingReads;
if (readAborted && numPendingReads <= 0) {
LOGGER.log(Level.FINE, "Transaction reset due to read/query abort");
readAborted = false;
}
}
/** Initialize the read count and aborted status when transaction started. */
public synchronized void initReadState() {
readAborted = false;
numPendingReads = 0;
}
/** Store the reference to the database client for future action use. */
public void setDatabaseClient(DatabaseClient client) {
dbClient = client;
}
/** Return a list of serviceKeyFile column types of the given table. */
public List<com.google.spanner.v1.Type> getKeyColumnTypes(String tableName)
throws SpannerException {
Preconditions.checkNotNull(metadata);
return metadata.getKeyColumnTypes(tableName);
}
/** Return column type of the given table and column. */
public com.google.spanner.v1.Type getColumnType(String tableName, String columnName)
throws SpannerException {
Preconditions.checkNotNull(metadata);
return metadata.getColumnType(tableName, columnName);
}
/** Buffer a list of mutations in a read-write transaction. */
public synchronized void bufferMutations(List<Mutation> mutations) throws SpannerException {
getTransactionForWrite().buffer(mutations);
}
/** Execute a batch of updates in a read-write transaction. */
public synchronized long[] executeBatchDml(@NotNull List<Statement> stmts)
throws SpannerException {
for (int i = 0; i < stmts.size(); i++) {
LOGGER.log(
Level.INFO, String.format("executeBatchDml [%d]: %s", i + 1, stmts.get(i).toString()));
}
return getTransactionForWrite()
.batchUpdate(stmts, Options.tag("batch-update-transaction-tag"));
}
/** Finish active transaction in given finishMode, then send outcome back to client. */
public synchronized Status finish(Mode finishMode, OutcomeSender sender) {
if (numPendingReads > 0) {
return sender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Reads pending when trying to finish")));
}
SpannerActionOutcome.Builder outcomeBuilder = SpannerActionOutcome.newBuilder();
outcomeBuilder.setStatus(toProto(Status.OK));
if (roTxn != null || rwTxn != null) {
try {
if (roTxn != null) {
// read-only transaction
Timestamp ts = roTxn.getReadTimestamp();
outcomeBuilder.setCommitTime(ts.toProto());
roTxn.close();
clear();
} else {
// read-write transaction
if (!rwTxn.finish(finishMode)) {
LOGGER.log(Level.FINE, "Transaction restarted");
outcomeBuilder.setTransactionRestarted(true);
} else {
LOGGER.log(Level.FINE, "Transaction finish successfully");
if (rwTxn.getTimestamp() != null) {
outcomeBuilder.setCommitTime(rwTxn.getTimestamp());
}
clear();
}
}
} catch (SpannerException e) {
outcomeBuilder.setStatus(toProto(toStatus(e)));
clear();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unexpected error: " + e.getMessage());
return sender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unexpected error: " + e.getMessage())));
}
return sender.sendOutcome(outcomeBuilder.build());
} else if (batchTxn != null) {
return toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Can't commit/abort a batch transaction"));
} else {
return toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "No currently active transaction"));
}
}
/** Close active batch transaction. */
public synchronized void closeBatchTxn() throws SpannerException {
if (batchTxn == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Not in a batch transaction");
}
batchTxn.close();
}
}
private Spanner client;
private Spanner clientWithTimeout;
private static final String TRANSACTION_ABANDONED = "Fake error to abandon transaction";
// Read-write transaction thread pool
private static final Executor txnThreadPool =
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("txn-pool-%d").build());
// Action thread pool
private static final Executor actionThreadPool =
Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("action-pool-%d").build());
private synchronized Spanner getClientWithTimeout(long timeoutSeconds) throws IOException {
if (clientWithTimeout != null) {
return clientWithTimeout;
}
clientWithTimeout = getClient(timeoutSeconds);
return clientWithTimeout;
}
private synchronized Spanner getClient() throws IOException {
if (client != null) {
return client;
}
client = getClient(/*timeoutSeconds=*/ 0);
return client;
}
// Return the spanner client, create one if not exists.
private synchronized Spanner getClient(long timeoutSeconds) throws IOException {
// Create a cloud spanner client
Credentials credentials;
if (WorkerProxy.serviceKeyFile.isEmpty()) {
credentials = NoCredentials.getInstance();
} else {
credentials =
GoogleCredentials.fromStream(
new ByteArrayInputStream(
FileUtils.readFileToByteArray(new File(WorkerProxy.serviceKeyFile))),
HTTP_TRANSPORT_FACTORY);
}
TransportChannelProvider channelProvider =
CloudUtil.newChannelProviderHelper(WorkerProxy.spannerPort);
Duration rpcTimeout = Duration.ofHours(1L);
if (timeoutSeconds > 0) {
rpcTimeout = Duration.ofSeconds(timeoutSeconds);
}
RetrySettings retrySettings =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofSeconds(1))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelay(Duration.ofSeconds(32))
.setInitialRpcTimeout(rpcTimeout)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(rpcTimeout)
.setTotalTimeout(rpcTimeout)
.build();
// Cloud Spanner Client does not support global retry settings,
// Thus, we need to add retry settings to each individual stub.
SpannerOptions.Builder optionsBuilder =
SpannerOptions.newBuilder()
.setProjectId(PROJECT_ID)
.setHost(HOST_PREFIX + WorkerProxy.spannerPort)
.setCredentials(credentials)
.setChannelProvider(channelProvider);
SpannerStubSettings.Builder stubSettingsBuilder =
optionsBuilder.getSpannerStubSettingsBuilder();
stubSettingsBuilder.executeSqlSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.executeStreamingSqlSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.readSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.streamingReadSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.commitSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.executeBatchDmlSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.partitionQuerySettings().setRetrySettings(retrySettings);
stubSettingsBuilder.partitionReadSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.rollbackSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.batchCreateSessionsSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.beginTransactionSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.createSessionSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.getSessionSettings().setRetrySettings(retrySettings);
stubSettingsBuilder.deleteSessionSettings().setRetrySettings(retrySettings);
return optionsBuilder.build().getService();
}
/** Handle actions. */
public Status startHandlingRequest(
SpannerAsyncActionRequest req, ExecutionFlowContext executionContext) {
OutcomeSender outcomeSender = new OutcomeSender(req.getActionId(), executionContext);
if (!req.hasAction()) {
return outcomeSender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Invalid request")));
}
SpannerAction action = req.getAction();
// Update dbPath
String dbPath = executionContext.getDatabasePath(action.getDatabasePath());
actionThreadPool.execute(
() -> {
Status status = executeAction(outcomeSender, action, dbPath, executionContext);
if (!status.isOk()) {
LOGGER.log(
Level.WARNING,
String.format("Failed to execute action with error: %s\n%s", status, action));
executionContext.onError(status.getCause());
}
});
return Status.OK;
}
/** Execute actions by action case, using OutcomeSender to send status and results back. */
private Status executeAction(
OutcomeSender outcomeSender,
SpannerAction action,
String dbPath,
ExecutionFlowContext executionContext) {
try {
if (action.hasAdmin()) {
return executeAdminAction(action.getAdmin(), outcomeSender);
} else if (action.hasStart()) {
if (dbPath == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Database path must be set for this action");
}
DatabaseClient dbClient = getClient().getDatabaseClient(DatabaseId.of(dbPath));
return executeStartTxn(action.getStart(), dbClient, outcomeSender, executionContext);
} else if (action.hasFinish()) {
return executeFinishTxn(action.getFinish(), outcomeSender, executionContext);
} else if (action.hasMutation()) {
return executeMutation(
action.getMutation(), outcomeSender, executionContext, /*isWrite=*/ false);
} else if (action.hasRead()) {
return executeRead(action.getRead(), outcomeSender, executionContext);
} else if (action.hasQuery()) {
return executeQuery(action.getQuery(), outcomeSender, executionContext);
} else if (action.hasDml()) {
return executeCloudDmlUpdate(action.getDml(), outcomeSender, executionContext);
} else if (action.hasBatchDml()) {
return executeCloudBatchDmlUpdates(action.getBatchDml(), outcomeSender, executionContext);
} else if (action.hasWrite()) {
return executeMutation(
action.getWrite().getMutation(), outcomeSender, executionContext, /*isWrite=*/ true);
} else if (action.hasStartBatchTxn()) {
if (dbPath == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "database path must be set for this action");
}
BatchClient batchClient = getClient().getBatchClient(DatabaseId.of(dbPath));
return executeStartBatchTxn(
action.getStartBatchTxn(), batchClient, outcomeSender, executionContext);
} else if (action.hasGenerateDbPartitionsRead()) {
return executeGenerateDbPartitionsRead(
action.getGenerateDbPartitionsRead(), outcomeSender, executionContext);
} else if (action.hasGenerateDbPartitionsQuery()) {
return executeGenerateDbPartitionsQuery(
action.getGenerateDbPartitionsQuery(), outcomeSender, executionContext);
} else if (action.hasExecutePartition()) {
return executeExecutePartition(
action.getExecutePartition(), outcomeSender, executionContext);
} else if (action.hasPartitionedUpdate()) {
if (dbPath == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Database path must be set for this action");
}
DatabaseClient dbClient = getClient().getDatabaseClient(DatabaseId.of(dbPath));
return executePartitionedUpdate(action.getPartitionedUpdate(), dbClient, outcomeSender);
} else if (action.hasCloseBatchTxn()) {
return executeCloseBatchTxn(action.getCloseBatchTxn(), outcomeSender, executionContext);
} else if (action.hasExecuteChangeStreamQuery()) {
if (dbPath == null) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Database path must be set for this action");
}
return executeExecuteChangeStreamQuery(
dbPath, action.getExecuteChangeStreamQuery(), outcomeSender);
} else {
return outcomeSender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.UNIMPLEMENTED, "Not implemented yet: \n" + action)));
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unexpected error: " + e.getMessage());
return outcomeSender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unexpected error: " + e.getMessage())));
}
}
/** Execute admin actions by action case, using OutcomeSender to send status and results back. */
private Status executeAdminAction(AdminAction action, OutcomeSender outcomeSender) {
try {
if (action.hasCreateCloudInstance()) {
return executeCreateCloudInstance(action.getCreateCloudInstance(), outcomeSender);
} else if (action.hasUpdateCloudInstance()) {
return executeUpdateCloudInstance(action.getUpdateCloudInstance(), outcomeSender);
} else if (action.hasDeleteCloudInstance()) {
return executeDeleteCloudInstance(action.getDeleteCloudInstance(), outcomeSender);
} else if (action.hasListCloudInstances()) {
return executeListCloudInstances(action.getListCloudInstances(), outcomeSender);
} else if (action.hasListInstanceConfigs()) {
return executeListCloudInstanceConfigs(action.getListInstanceConfigs(), outcomeSender);
} else if (action.hasGetCloudInstanceConfig()) {
return executeGetCloudInstanceConfig(action.getGetCloudInstanceConfig(), outcomeSender);
} else if (action.hasGetCloudInstance()) {
return executeGetCloudInstance(action.getGetCloudInstance(), outcomeSender);
} else if (action.hasCreateUserInstanceConfig()) {
return executeCreateUserInstanceConfig(action.getCreateUserInstanceConfig(), outcomeSender);
} else if (action.hasDeleteUserInstanceConfig()) {
return executeDeleteUserInstanceConfig(action.getDeleteUserInstanceConfig(), outcomeSender);
} else if (action.hasCreateCloudDatabase()) {
return executeCreateCloudDatabase(action.getCreateCloudDatabase(), outcomeSender);
} else if (action.hasUpdateCloudDatabaseDdl()) {
return executeUpdateCloudDatabaseDdl(action.getUpdateCloudDatabaseDdl(), outcomeSender);
} else if (action.hasDropCloudDatabase()) {
return executeDropCloudDatabase(action.getDropCloudDatabase(), outcomeSender);
} else if (action.hasCreateCloudBackup()) {
return executeCreateCloudBackup(action.getCreateCloudBackup(), outcomeSender);
} else if (action.hasCopyCloudBackup()) {
return executeCopyCloudBackup(action.getCopyCloudBackup(), outcomeSender);
} else if (action.hasGetCloudBackup()) {
return executeGetCloudBackup(action.getGetCloudBackup(), outcomeSender);
} else if (action.hasUpdateCloudBackup()) {
return executeUpdateCloudBackup(action.getUpdateCloudBackup(), outcomeSender);
} else if (action.hasDeleteCloudBackup()) {
return executeDeleteCloudBackup(action.getDeleteCloudBackup(), outcomeSender);
} else if (action.hasListCloudBackups()) {
return executeListCloudBackups(action.getListCloudBackups(), outcomeSender);
} else if (action.hasListCloudBackupOperations()) {
return executeListCloudBackupOperations(
action.getListCloudBackupOperations(), outcomeSender);
} else if (action.hasListCloudDatabases()) {
return executeListCloudDatabases(action.getListCloudDatabases(), outcomeSender);
} else if (action.hasListCloudDatabaseOperations()) {
return executeListCloudDatabaseOperations(
action.getListCloudDatabaseOperations(), outcomeSender);
} else if (action.hasRestoreCloudDatabase()) {
return executeRestoreCloudDatabase(action.getRestoreCloudDatabase(), outcomeSender);
} else if (action.hasGetCloudDatabase()) {
return executeGetCloudDatabase(action.getGetCloudDatabase(), outcomeSender);
} else if (action.hasGetOperation()) {
return executeGetOperation(action.getGetOperation(), outcomeSender);
} else if (action.hasCancelOperation()) {
return executeCancelOperation(action.getCancelOperation(), outcomeSender);
} else {
return outcomeSender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.UNIMPLEMENTED, "Not implemented yet: \n" + action)));
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unexpected error: " + e.getMessage());
return outcomeSender.finishWithError(
toStatus(
SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unexpected error: " + e.getMessage())));
}
}