forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 2
/
local_sender.go
203 lines (184 loc) · 6.24 KB
/
local_sender.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
// Copyright 2014 The Cockroach Authors.
//
// 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. See the AUTHORS file
// for names of contributors.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
package kv
import (
"fmt"
"sync"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/client"
"github.com/cockroachdb/cockroach/proto"
"github.com/cockroachdb/cockroach/storage"
"github.com/cockroachdb/cockroach/util"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/tracer"
gogoproto "github.com/gogo/protobuf/proto"
)
// A LocalSender provides methods to access a collection of local stores.
type LocalSender struct {
mu sync.RWMutex // Protects storeMap and addrs
storeMap map[proto.StoreID]*storage.Store // Map from StoreID to Store
}
var _ client.Sender = &LocalSender{}
// NewLocalSender returns a local-only sender which directly accesses
// a collection of stores.
func NewLocalSender() *LocalSender {
return &LocalSender{
storeMap: map[proto.StoreID]*storage.Store{},
}
}
// GetStoreCount returns the number of stores this node is exporting.
func (ls *LocalSender) GetStoreCount() int {
ls.mu.RLock()
defer ls.mu.RUnlock()
return len(ls.storeMap)
}
// HasStore returns true if the specified store is owned by this LocalSender.
func (ls *LocalSender) HasStore(storeID proto.StoreID) bool {
ls.mu.RLock()
defer ls.mu.RUnlock()
_, ok := ls.storeMap[storeID]
return ok
}
// GetStore looks up the store by store ID. Returns an error
// if not found.
func (ls *LocalSender) GetStore(storeID proto.StoreID) (*storage.Store, error) {
ls.mu.RLock()
store, ok := ls.storeMap[storeID]
ls.mu.RUnlock()
if !ok {
return nil, util.Errorf("store %d not found", storeID)
}
return store, nil
}
// AddStore adds the specified store to the store map.
func (ls *LocalSender) AddStore(s *storage.Store) {
ls.mu.Lock()
defer ls.mu.Unlock()
if _, ok := ls.storeMap[s.Ident.StoreID]; ok {
panic(fmt.Sprintf("cannot add store twice to local db: %+v", s.Ident))
}
ls.storeMap[s.Ident.StoreID] = s
}
// RemoveStore removes the specified store from the store map.
func (ls *LocalSender) RemoveStore(s *storage.Store) {
ls.mu.Lock()
defer ls.mu.Unlock()
delete(ls.storeMap, s.Ident.StoreID)
}
// VisitStores implements a visitor pattern over stores in the storeMap.
// The specified function is invoked with each store in turn. Stores are
// visited in a random order.
func (ls *LocalSender) VisitStores(visitor func(s *storage.Store) error) error {
ls.mu.RLock()
defer ls.mu.RUnlock()
for _, s := range ls.storeMap {
if err := visitor(s); err != nil {
return err
}
}
return nil
}
// GetStoreIDs returns all the current store ids in a random order.
func (ls *LocalSender) GetStoreIDs() []proto.StoreID {
ls.mu.RLock()
defer ls.mu.RUnlock()
storeIDs := make([]proto.StoreID, 0, len(ls.storeMap))
for storeID := range ls.storeMap {
storeIDs = append(storeIDs, storeID)
}
return storeIDs
}
// Send implements the client.Sender interface. The store is looked
// up from the store map if specified by header.Replica; otherwise,
// the command is being executed locally, and the replica is
// determined via lookup through each store's LookupRange method.
func (ls *LocalSender) Send(ctx context.Context, call proto.Call) {
var err error
var store *storage.Store
trace := tracer.FromCtx(ctx)
// If we aren't given a Replica, then a little bending over
// backwards here. This case applies exclusively to unittests.
header := call.Args.Header()
if header.RangeID == 0 || header.Replica.StoreID == 0 {
var repl *proto.Replica
var rangeID proto.RangeID
rangeID, repl, err = ls.lookupReplica(header.Key, header.EndKey)
if err == nil {
header.RangeID = rangeID
header.Replica = *repl
}
}
ctx = log.Add(ctx,
log.Method, call.Method(),
log.Key, header.Key,
log.RangeID, header.RangeID)
if err == nil {
store, err = ls.GetStore(header.Replica.StoreID)
}
var reply proto.Response
if err == nil {
// For calls that read data within a txn, we can avoid uncertainty
// related retries in certain situations. If the node is in
// "CertainNodes", we need not worry about uncertain reads any
// more. Setting MaxTimestamp=Timestamp for the operation
// accomplishes that. See proto.Transaction.CertainNodes for details.
if header.Txn != nil && header.Txn.CertainNodes.Contains(header.Replica.NodeID) {
// MaxTimestamp = Timestamp corresponds to no clock uncertainty.
trace.Event("read has no clock uncertainty")
header.Txn.MaxTimestamp = header.Txn.Timestamp
}
reply, err = store.ExecuteCmd(ctx, call.Args)
}
if reply != nil {
gogoproto.Merge(call.Reply, reply)
}
if call.Reply.Header().Error != nil {
panic(proto.ErrorUnexpectedlySet)
}
if err != nil {
call.Reply.Header().SetGoError(err)
}
}
// lookupReplica looks up replica by key [range]. Lookups are done
// by consulting each store in turn via Store.LookupRange(key).
// Returns RangeID and replica on success; RangeKeyMismatch error
// if not found.
// TODO(tschottdorf) with a very large number of stores, the LocalSender
// may want to avoid scanning the whole map of stores on each invocation.
func (ls *LocalSender) lookupReplica(start, end proto.Key) (rangeID proto.RangeID, replica *proto.Replica, err error) {
ls.mu.RLock()
defer ls.mu.RUnlock()
var rng *storage.Replica
for _, store := range ls.storeMap {
rng = store.LookupReplica(start, end)
if rng == nil {
continue
}
if replica == nil {
rangeID = rng.Desc().RangeID
replica = rng.GetReplica()
continue
}
// Should never happen outside of tests.
return 0, nil, util.Errorf(
"range %+v exists on additional store: %+v", rng, store)
}
if replica == nil {
err = proto.NewRangeKeyMismatchError(start, end, nil)
}
return rangeID, replica, err
}