forked from tikv/pd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
300 lines (259 loc) · 7.61 KB
/
util.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
// Copyright 2016 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"encoding/binary"
"fmt"
"math/rand"
"net/http"
"regexp"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/golang/protobuf/proto"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/pd/pkg/etcdutil"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const (
requestTimeout = etcdutil.DefaultRequestTimeout
slowRequestTime = etcdutil.DefaultSlowRequestTime
)
// Version information.
var (
PDReleaseVersion = "None"
PDBuildTS = "None"
PDGitHash = "None"
PDGitBranch = "None"
)
// DialClient used to dail http request.
var DialClient = &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
},
}
// LogPDInfo prints the PD version information.
func LogPDInfo() {
log.Infof("Welcome to Placement Driver (PD).")
log.Infof("Release Version: %s", PDReleaseVersion)
log.Infof("Git Commit Hash: %s", PDGitHash)
log.Infof("Git Branch: %s", PDGitBranch)
log.Infof("UTC Build Time: %s", PDBuildTS)
}
// PrintPDInfo prints the PD version information without log info.
func PrintPDInfo() {
fmt.Println("Release Version:", PDReleaseVersion)
fmt.Println("Git Commit Hash:", PDGitHash)
fmt.Println("Git Branch:", PDGitBranch)
fmt.Println("UTC Build Time: ", PDBuildTS)
}
// CheckPDVersion checks if PD needs to be upgraded.
func CheckPDVersion(opt *scheduleOption) {
pdVersion := MinSupportedVersion(Base)
if PDReleaseVersion != "None" {
pdVersion = *MustParseVersion(PDReleaseVersion)
}
clusterVersion := opt.loadClusterVersion()
if pdVersion.LessThan(clusterVersion) {
log.Warnf("PD version %s less than cluster version: %s, please upgrade PD", pdVersion, clusterVersion)
}
}
// A helper function to get value with key from etcd.
func getValue(c *clientv3.Client, key string, opts ...clientv3.OpOption) ([]byte, error) {
resp, err := get(c, key, opts...)
if err != nil {
return nil, err
}
if resp == nil {
return nil, nil
}
return resp.Kvs[0].Value, nil
}
func get(c *clientv3.Client, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) {
resp, err := kvGet(c, key, opts...)
if err != nil {
return nil, err
}
if n := len(resp.Kvs); n == 0 {
return nil, nil
} else if n > 1 {
return nil, errors.Errorf("invalid get value resp %v, must only one", resp.Kvs)
}
return resp, nil
}
// Return boolean to indicate whether the key exists or not.
func getProtoMsgWithModRev(c *clientv3.Client, key string, msg proto.Message, opts ...clientv3.OpOption) (bool, int64, error) {
resp, err := get(c, key, opts...)
if err != nil {
return false, 0, err
}
if resp == nil {
return false, 0, nil
}
value := resp.Kvs[0].Value
if err = proto.Unmarshal(value, msg); err != nil {
return false, 0, errors.WithStack(err)
}
return true, resp.Kvs[0].ModRevision, nil
}
func initOrGetClusterID(c *clientv3.Client, key string) (uint64, error) {
ctx, cancel := context.WithTimeout(c.Ctx(), requestTimeout)
defer cancel()
// Generate a random cluster ID.
ts := uint64(time.Now().Unix())
clusterID := (ts << 32) + uint64(rand.Uint32())
value := uint64ToBytes(clusterID)
// Multiple PDs may try to init the cluster ID at the same time.
// Only one PD can commit this transaction, then other PDs can get
// the committed cluster ID.
resp, err := c.Txn(ctx).
If(clientv3.Compare(clientv3.CreateRevision(key), "=", 0)).
Then(clientv3.OpPut(key, string(value))).
Else(clientv3.OpGet(key)).
Commit()
if err != nil {
return 0, errors.WithStack(err)
}
// Txn commits ok, return the generated cluster ID.
if resp.Succeeded {
return clusterID, nil
}
// Otherwise, parse the committed cluster ID.
if len(resp.Responses) == 0 {
return 0, errors.Errorf("txn returns empty response: %v", resp)
}
response := resp.Responses[0].GetResponseRange()
if response == nil || len(response.Kvs) != 1 {
return 0, errors.Errorf("txn returns invalid range response: %v", resp)
}
return bytesToUint64(response.Kvs[0].Value)
}
func bytesToUint64(b []byte) (uint64, error) {
if len(b) != 8 {
return 0, errors.Errorf("invalid data, must 8 bytes, but %d", len(b))
}
return binary.BigEndian.Uint64(b), nil
}
func uint64ToBytes(v uint64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, v)
return b
}
// slowLogTxn wraps etcd transaction and log slow one.
type slowLogTxn struct {
clientv3.Txn
cancel context.CancelFunc
}
func newSlowLogTxn(client *clientv3.Client) clientv3.Txn {
ctx, cancel := context.WithTimeout(client.Ctx(), requestTimeout)
return &slowLogTxn{
Txn: client.Txn(ctx),
cancel: cancel,
}
}
func (t *slowLogTxn) If(cs ...clientv3.Cmp) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.If(cs...),
cancel: t.cancel,
}
}
func (t *slowLogTxn) Then(ops ...clientv3.Op) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.Then(ops...),
cancel: t.cancel,
}
}
// Commit implements Txn Commit interface.
func (t *slowLogTxn) Commit() (*clientv3.TxnResponse, error) {
start := time.Now()
resp, err := t.Txn.Commit()
t.cancel()
cost := time.Since(start)
if cost > slowRequestTime {
log.Warnf("txn runs too slow, resp: %v, err: %v, cost: %s", resp, err, cost)
}
label := "success"
if err != nil {
label = "failed"
}
txnCounter.WithLabelValues(label).Inc()
txnDuration.WithLabelValues(label).Observe(cost.Seconds())
return resp, errors.WithStack(err)
}
// GetMembers return a slice of Members.
func GetMembers(etcdClient *clientv3.Client) ([]*pdpb.Member, error) {
listResp, err := etcdutil.ListEtcdMembers(etcdClient)
if err != nil {
return nil, err
}
members := make([]*pdpb.Member, 0, len(listResp.Members))
for _, m := range listResp.Members {
info := &pdpb.Member{
Name: m.Name,
MemberId: m.ID,
ClientUrls: m.ClientURLs,
PeerUrls: m.PeerURLs,
}
members = append(members, info)
}
return members, nil
}
func parseTimestamp(data []byte) (time.Time, error) {
nano, err := bytesToUint64(data)
if err != nil {
return zeroTime, err
}
return time.Unix(0, int64(nano)), nil
}
func subTimeByWallClock(after time.Time, before time.Time) time.Duration {
return time.Duration(after.UnixNano() - before.UnixNano())
}
// InitHTTPClient initials a http client.
func InitHTTPClient(svr *Server) error {
tlsConfig, err := svr.GetSecurityConfig().ToTLSConfig()
if err != nil {
return err
}
DialClient = &http.Client{Transport: &http.Transport{
TLSClientConfig: tlsConfig,
DisableKeepAlives: true,
}}
return nil
}
const matchRule = "^[A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?$"
// ValidateLabelString checks the legality of the label string.
// The valid label consist of alphanumeric characters, '-', '_' or '.',
// and must start and end with an alphanumeric character.
func ValidateLabelString(s string) error {
isValid, _ := regexp.MatchString(matchRule, s)
if !isValid {
return errors.Errorf("invalid label: %s", s)
}
return nil
}
// ValidateLabels checks the legality of the labels.
func ValidateLabels(labels []*metapb.StoreLabel) error {
for _, label := range labels {
err := ValidateLabelString(label.Key)
if err != nil {
return err
}
err = ValidateLabelString(label.Value)
if err != nil {
return err
}
}
return nil
}