-
Notifications
You must be signed in to change notification settings - Fork 31
/
session.go
433 lines (376 loc) · 14.3 KB
/
session.go
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
//
// Copyright 2020 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 main
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"cloud.google.com/go/spanner"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
adminapi "cloud.google.com/go/spanner/admin/database/apiv1"
pb "cloud.google.com/go/spanner/apiv1/spannerpb"
)
var defaultClientConfig = spanner.ClientConfig{
SessionPoolConfig: spanner.SessionPoolConfig{
MinOpened: 1,
MaxOpened: 10, // FIXME: integration_test requires more than a single session
},
}
var defaultClientOpts = []option.ClientOption{
option.WithGRPCConnectionPool(1),
}
// Use MEDIUM priority not to disturb regular workloads on the database.
const defaultPriority = pb.RequestOptions_PRIORITY_MEDIUM
type Session struct {
projectId string
instanceId string
databaseId string
client *spanner.Client
adminClient *adminapi.DatabaseAdminClient
clientConfig spanner.ClientConfig
clientOpts []option.ClientOption
defaultPriority pb.RequestOptions_Priority
directedRead *pb.DirectedReadOptions
tc *transactionContext
tcMutex sync.Mutex // Guard a critical section for transaction.
protoDescriptor []byte
}
type transactionContext struct {
tag string
priority pb.RequestOptions_Priority
sendHeartbeat bool // Becomes true only after a user-driven query is executed on the transaction.
rwTxn *spanner.ReadWriteStmtBasedTransaction
roTxn *spanner.ReadOnlyTransaction
}
func NewSession(projectId string, instanceId string, databaseId string, priority pb.RequestOptions_Priority, role string, directedRead *pb.DirectedReadOptions,
protoDescriptor []byte, opts ...option.ClientOption) (*Session, error) {
ctx := context.Background()
dbPath := fmt.Sprintf("projects/%s/instances/%s/databases/%s", projectId, instanceId, databaseId)
clientConfig := defaultClientConfig
clientConfig.DatabaseRole = role
clientConfig.DirectedReadOptions = directedRead
opts = append(opts, defaultClientOpts...)
client, err := spanner.NewClientWithConfig(ctx, dbPath, clientConfig, opts...)
if err != nil {
return nil, err
}
adminClient, err := adminapi.NewDatabaseAdminClient(ctx, opts...)
if err != nil {
return nil, err
}
if priority == pb.RequestOptions_PRIORITY_UNSPECIFIED {
priority = defaultPriority
}
session := &Session{
projectId: projectId,
instanceId: instanceId,
databaseId: databaseId,
client: client,
clientConfig: clientConfig,
clientOpts: opts,
adminClient: adminClient,
defaultPriority: priority,
directedRead: directedRead,
protoDescriptor: protoDescriptor,
}
go session.startHeartbeat()
return session, nil
}
// InReadWriteTransaction returns true if the session is running read-write transaction.
func (s *Session) InReadWriteTransaction() bool {
return s.tc != nil && s.tc.rwTxn != nil
}
// InReadOnlyTransaction returns true if the session is running read-only transaction.
func (s *Session) InReadOnlyTransaction() bool {
return s.tc != nil && s.tc.roTxn != nil
}
// BeginReadWriteTransaction starts read-write transaction.
func (s *Session) BeginReadWriteTransaction(ctx context.Context, priority pb.RequestOptions_Priority, tag string) error {
if s.InReadWriteTransaction() {
return errors.New("read-write transaction is already running")
}
// Use session's priority if transaction priority is not set.
if priority == pb.RequestOptions_PRIORITY_UNSPECIFIED {
priority = s.defaultPriority
}
opts := spanner.TransactionOptions{
CommitOptions: spanner.CommitOptions{ReturnCommitStats: true},
CommitPriority: priority,
TransactionTag: tag,
}
txn, err := spanner.NewReadWriteStmtBasedTransactionWithOptions(ctx, s.client, opts)
if err != nil {
return err
}
s.tc = &transactionContext{
tag: tag,
priority: priority,
rwTxn: txn,
}
return nil
}
// CommitReadWriteTransaction commits read-write transaction and returns commit timestamp if successful.
func (s *Session) CommitReadWriteTransaction(ctx context.Context) (spanner.CommitResponse, error) {
if !s.InReadWriteTransaction() {
return spanner.CommitResponse{}, errors.New("read-write transaction is not running")
}
s.tcMutex.Lock()
defer s.tcMutex.Unlock()
resp, err := s.tc.rwTxn.CommitWithReturnResp(ctx)
s.tc = nil
return resp, err
}
// RollbackReadWriteTransaction rollbacks read-write transaction.
func (s *Session) RollbackReadWriteTransaction(ctx context.Context) error {
if !s.InReadWriteTransaction() {
return errors.New("read-write transaction is not running")
}
s.tcMutex.Lock()
defer s.tcMutex.Unlock()
s.tc.rwTxn.Rollback(ctx)
s.tc = nil
return nil
}
// BeginReadOnlyTransaction starts read-only transaction and returns the snapshot timestamp for the transaction if successful.
func (s *Session) BeginReadOnlyTransaction(ctx context.Context, typ timestampBoundType, staleness time.Duration, timestamp time.Time, priority pb.RequestOptions_Priority, tag string) (time.Time, error) {
if s.InReadOnlyTransaction() {
return time.Time{}, errors.New("read-only transaction is already running")
}
txn := s.client.ReadOnlyTransaction()
switch typ {
case strong:
txn = txn.WithTimestampBound(spanner.StrongRead())
case exactStaleness:
txn = txn.WithTimestampBound(spanner.ExactStaleness(staleness))
case readTimestamp:
txn = txn.WithTimestampBound(spanner.ReadTimestamp(timestamp))
}
// Use session's priority if transaction priority is not set.
if priority == pb.RequestOptions_PRIORITY_UNSPECIFIED {
priority = s.defaultPriority
}
// Because google-cloud-go/spanner defers calling BeginTransaction RPC until an actual query is run,
// we explicitly run a "SELECT 1" query so that we can determine the timestamp of read-only transaction.
opts := spanner.QueryOptions{Priority: priority}
if err := txn.QueryWithOptions(ctx, spanner.NewStatement("SELECT 1"), opts).Do(func(r *spanner.Row) error {
return nil
}); err != nil {
return time.Time{}, err
}
s.tc = &transactionContext{
tag: tag,
priority: priority,
roTxn: txn,
}
return txn.Timestamp()
}
// CloseReadOnlyTransaction closes a running read-only transaction.
func (s *Session) CloseReadOnlyTransaction() error {
if !s.InReadOnlyTransaction() {
return errors.New("read-only transaction is not running")
}
s.tc.roTxn.Close()
s.tc = nil
return nil
}
// RunQueryWithStats executes a statement with stats either on the running transaction or on the temporal read-only transaction.
// It returns row iterator and read-only transaction if the statement was executed on the read-only transaction.
func (s *Session) RunQueryWithStats(ctx context.Context, stmt spanner.Statement) (*spanner.RowIterator, *spanner.ReadOnlyTransaction) {
mode := pb.ExecuteSqlRequest_PROFILE
opts := spanner.QueryOptions{
Mode: &mode,
Priority: s.currentPriority(),
}
return s.runQueryWithOptions(ctx, stmt, opts)
}
// RunQuery executes a statement either on the running transaction or on the temporal read-only transaction.
// It returns row iterator and read-only transaction if the statement was executed on the read-only transaction.
func (s *Session) RunQuery(ctx context.Context, stmt spanner.Statement) (*spanner.RowIterator, *spanner.ReadOnlyTransaction) {
opts := spanner.QueryOptions{
Priority: s.currentPriority(),
}
return s.runQueryWithOptions(ctx, stmt, opts)
}
// RunAnalyzeQuery analyzes a statement either on the running transaction or on the temporal read-only transaction.
func (s *Session) RunAnalyzeQuery(ctx context.Context, stmt spanner.Statement) (*pb.QueryPlan, *pb.ResultSetMetadata, error) {
mode := pb.ExecuteSqlRequest_PLAN
opts := spanner.QueryOptions{
Mode: &mode,
Priority: s.currentPriority(),
}
iter, _ := s.runQueryWithOptions(ctx, stmt, opts)
// Need to read rows from iterator to get the query plan.
err := iter.Do(func(r *spanner.Row) error {
return nil
})
if err != nil {
return nil, nil, err
}
return iter.QueryPlan, iter.Metadata, nil
}
func (s *Session) runQueryWithOptions(ctx context.Context, stmt spanner.Statement, opts spanner.QueryOptions) (*spanner.RowIterator, *spanner.ReadOnlyTransaction) {
if s.InReadWriteTransaction() {
// The current Go Spanner client library does not apply client-level directed read options to read-write transactions.
// Therefore, we explicitly set query-level options here to fail the query during a read-write transaction.
opts.DirectedReadOptions = s.clientConfig.DirectedReadOptions
opts.RequestTag = s.tc.tag
iter := s.tc.rwTxn.QueryWithOptions(ctx, stmt, opts)
s.tc.sendHeartbeat = true
return iter, nil
}
if s.InReadOnlyTransaction() {
opts.RequestTag = s.tc.tag
return s.tc.roTxn.QueryWithOptions(ctx, stmt, opts), s.tc.roTxn
}
txn := s.client.Single()
return txn.QueryWithOptions(ctx, stmt, opts), txn
}
// RunUpdate executes a DML statement on the running read-write transaction.
// It returns error if there is no running read-write transaction.
// useUpdate flag enforce to use Update function internally and disable `THEN RETURN` result printing.
func (s *Session) RunUpdate(ctx context.Context, stmt spanner.Statement, useUpdate bool) ([]Row, []string, int64, *pb.ResultSetMetadata, error) {
if !s.InReadWriteTransaction() {
return nil, nil, 0, nil, errors.New("read-write transaction is not running")
}
opts := spanner.QueryOptions{
Priority: s.currentPriority(),
RequestTag: s.tc.tag,
}
// Workaround: Usually, we can execute DMLs using Query(ExecuteStreamingSql RPC),
// but spannertest doesn't support DMLs execution using ExecuteStreamingSql RPC.
// It enforces to use ExecuteSql RPC.
if useUpdate {
rowCount, err := s.tc.rwTxn.UpdateWithOptions(ctx, stmt, opts)
s.tc.sendHeartbeat = true
return nil, nil, rowCount, nil, err
}
rowIter := s.tc.rwTxn.QueryWithOptions(ctx, stmt, opts)
defer rowIter.Stop()
result, columnNames, err := parseQueryResult(rowIter)
s.tc.sendHeartbeat = true
return result, columnNames, rowIter.RowCount, rowIter.Metadata, err
}
func (s *Session) Close() {
s.client.Close()
s.adminClient.Close()
}
func (s *Session) DatabasePath() string {
return fmt.Sprintf("projects/%s/instances/%s/databases/%s", s.projectId, s.instanceId, s.databaseId)
}
func (s *Session) InstancePath() string {
return fmt.Sprintf("projects/%s/instances/%s", s.projectId, s.instanceId)
}
func (s *Session) DatabaseExists() (bool, error) {
// For users who don't have `spanner.databases.get` IAM permission,
// check database existence by running an actual query.
// cf. https://github.com/cloudspannerecosystem/spanner-cli/issues/10
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
stmt := spanner.NewStatement("SELECT 1")
iter := s.client.Single().QueryWithOptions(ctx, stmt, spanner.QueryOptions{Priority: s.currentPriority()})
defer iter.Stop()
_, err := iter.Next()
if err == nil {
return true, nil
}
switch spanner.ErrCode(err) {
case codes.NotFound:
return false, nil
case codes.InvalidArgument:
return false, nil
default:
return false, fmt.Errorf("checking database existence failed: %v", err)
}
}
// RecreateClient closes the current client and creates a new client for the session.
func (s *Session) RecreateClient() error {
ctx := context.Background()
c, err := spanner.NewClientWithConfig(ctx, s.DatabasePath(), s.clientConfig, s.clientOpts...)
if err != nil {
return err
}
s.client.Close()
s.client = c
return nil
}
func (s *Session) currentPriority() pb.RequestOptions_Priority {
if s.tc != nil {
return s.tc.priority
}
return s.defaultPriority
}
// startHeartbeat starts heartbeat for read-write transaction.
//
// If no reads or DMLs happen within 10 seconds, the rw-transaction is considered idle at Cloud Spanner server.
// This "SELECT 1" query prevents the transaction from being considered idle.
// cf. https://godoc.org/cloud.google.com/go/spanner#hdr-Idle_transactions
//
// We send an actual heartbeat only if the read-write transaction is active and
// at least one user-initialized SQL query has been executed on the transaction.
// Background: https://github.com/cloudspannerecosystem/spanner-cli/issues/100
func (s *Session) startHeartbeat() {
interval := time.NewTicker(5 * time.Second)
defer interval.Stop()
for {
select {
case <-interval.C:
s.tcMutex.Lock()
if s.tc != nil && s.tc.rwTxn != nil && s.tc.sendHeartbeat {
heartbeat(s.tc.rwTxn, s.currentPriority())
}
s.tcMutex.Unlock()
}
}
}
func heartbeat(txn *spanner.ReadWriteStmtBasedTransaction, priority pb.RequestOptions_Priority) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
iter := txn.QueryWithOptions(ctx, spanner.NewStatement("SELECT 1"), spanner.QueryOptions{Priority: priority})
defer iter.Stop()
_, err := iter.Next()
return err
}
func parseDirectedReadOption(directedReadOptionText string) (*pb.DirectedReadOptions, error) {
directedReadOption := strings.Split(directedReadOptionText, ":")
if len(directedReadOption) > 2 {
return nil, fmt.Errorf("directed read option must be in the form of <replica_location>:<replica_type>, but got %q", directedReadOptionText)
}
replicaSelection := pb.DirectedReadOptions_ReplicaSelection{
Location: directedReadOption[0],
}
if len(directedReadOption) == 2 {
switch strings.ToUpper(directedReadOption[1]) {
case "READ_ONLY":
replicaSelection.Type = pb.DirectedReadOptions_ReplicaSelection_READ_ONLY
case "READ_WRITE":
replicaSelection.Type = pb.DirectedReadOptions_ReplicaSelection_READ_WRITE
default:
return nil, fmt.Errorf("<replica_type> must be either READ_WRITE or READ_ONLY, but got %q", directedReadOption[1])
}
}
return &pb.DirectedReadOptions{
Replicas: &pb.DirectedReadOptions_IncludeReplicas_{
IncludeReplicas: &pb.DirectedReadOptions_IncludeReplicas{
ReplicaSelections: []*pb.DirectedReadOptions_ReplicaSelection{&replicaSelection},
AutoFailoverDisabled: true,
},
},
}, nil
}