/
meta_client.go
3586 lines (3125 loc) · 95.5 KB
/
meta_client.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
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
//nolint
/*
Copyright (c) 2013-2016 Errplane Inc.
This code is originally from: https://github.com/influxdata/influxdb/blob/1.7/services/meta/client.go
2022.01.23 change http to rpc
Add TagKeys,FieldKeys etc.
Copyright 2022 Huawei Cloud Computing Technologies Co., Ltd.
*/
package metaclient
import (
"bytes"
crand "crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
"path"
"sort"
"strconv"
"strings"
"sync"
"time"
set "github.com/deckarep/golang-set"
"github.com/influxdata/influxdb/models"
originql "github.com/influxdata/influxql"
"github.com/openGemini/openGemini/app/ts-meta/meta/message"
"github.com/openGemini/openGemini/engine/executor/spdy"
"github.com/openGemini/openGemini/engine/executor/spdy/transport"
"github.com/openGemini/openGemini/engine/op"
"github.com/openGemini/openGemini/lib/config"
"github.com/openGemini/openGemini/lib/errno"
"github.com/openGemini/openGemini/lib/logger"
"github.com/openGemini/openGemini/lib/obs"
"github.com/openGemini/openGemini/lib/rand"
"github.com/openGemini/openGemini/lib/statisticsPusher/statistics"
"github.com/openGemini/openGemini/lib/sysinfo"
"github.com/openGemini/openGemini/lib/util"
"github.com/openGemini/openGemini/lib/util/lifted/hashicorp/serf/serf"
"github.com/openGemini/openGemini/lib/util/lifted/influx/influxql"
meta2 "github.com/openGemini/openGemini/lib/util/lifted/influx/meta"
proto2 "github.com/openGemini/openGemini/lib/util/lifted/influx/meta/proto"
"github.com/openGemini/openGemini/lib/util/lifted/influx/query"
"github.com/openGemini/openGemini/lib/util/lifted/protobuf/proto"
"github.com/openGemini/openGemini/lib/util/lifted/vm/protoparser/influx"
"go.uber.org/zap"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
const (
// errSleep is the time to sleep after we've failed on every metaserver
// before making another pass
errSleep = time.Second
// SaltBytes is the number of bytes used for salts.
SaltBytes = 32
// pbkdf2 iter times
pbkdf2Iter4096 = 4096
pbkdf2Iter1000 = 1000
// the length of key generated by pbkdf2
pbkdf2KeyLen = 32
// hash algorithm version flag of password save
hashAlgoVerOne = "#Ver:001#"
// PBKDF2 iterator 4096 times
hashAlgoVerTwo = "#Ver:002#"
// PBKDF2 iterator 1000 times
hashAlgoVerThree = "#Ver:003#"
maxDbOrRpName = 256
// ShardGroupDeletedExpiration is the amount of time before a shard group info will be removed from cached
// data after it has been marked deleted (2 weeks).
ShardGroupDeletedExpiration = -2 * 7 * 24 * time.Hour
IndexGroupDeletedExpiration = -2 * 7 * 24 * time.Hour
RPCReqTimeout = 10 * time.Second
HttpSnapshotTimeout = 4 * time.Second
//for lock user
maxLoginLimit = 5 //Maximum number of login attempts
authFailCacheLimit = 200 //Size of the channel for processing authentication failures.
lockUserTime = 30 //User Lock Duration, in seconds.
maxLoginValidTime = 3600 //Validity duration of login records, in seconds.
minUsernameLen = 4 // Minimum username length
maxUsernameLen = 100 // Maximum username length
minPasswordLen = 8 // Minimum password length
maxPasswordLen = 256 // Maximum password length
)
type Role int
const (
SQL Role = iota
STORE
META
algoVer01 = 1
algoVer02 = 2
algoVer03 = 3
)
var (
ErrNameTooLong = fmt.Errorf("database name must have fewer than %d characters", maxDbOrRpName)
RetryGetUserInfoTimeout = 5 * time.Second
RetryExecTimeout = 60 * time.Second
RetryReportTimeout = 60 * time.Second
HttpReqTimeout = 10 * time.Second
)
var DefaultTypeMapper = influxql.MultiTypeMapper(
op.TypeMapper{},
query.MathTypeMapper{},
query.FunctionTypeMapper{},
query.StringFunctionTypeMapper{},
)
var DefaultMetaClient *Client
var cliOnce sync.Once
type StorageNodeInfo struct {
InsertAddr string
SelectAddr string
}
type FieldKey struct {
Field string
FieldType int32
}
type FieldKeys []FieldKey
func (a FieldKeys) Len() int { return len(a) }
func (a FieldKeys) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a FieldKeys) Less(i, j int) bool { return a[i].Field < a[j].Field }
// MetaClient is an interface for accessing meta data.
type MetaClient interface {
CreateMeasurement(database, retentionPolicy, mst string, shardKey *meta2.ShardKeyInfo, indexR *influxql.IndexRelation, engineType config.EngineType,
colStoreInfo *meta2.ColStoreInfo, schemaInfo []*proto2.FieldSchema, options *meta2.Options) (*meta2.MeasurementInfo, error)
AlterShardKey(database, retentionPolicy, mst string, shardKey *meta2.ShardKeyInfo) error
CreateDatabase(name string, enableTagArray bool, replicaN uint32, options *obs.ObsOptions) (*meta2.DatabaseInfo, error)
CreateDatabaseWithRetentionPolicy(name string, spec *meta2.RetentionPolicySpec, shardKey *meta2.ShardKeyInfo, enableTagArray bool, replicaN uint32) (*meta2.DatabaseInfo, error)
CreateRetentionPolicy(database string, spec *meta2.RetentionPolicySpec, makeDefault bool) (*meta2.RetentionPolicyInfo, error)
CreateSubscription(database, rp, name, mode string, destinations []string) error
CreateUser(name, password string, admin, rwuser bool) (meta2.User, error)
Databases() map[string]*meta2.DatabaseInfo
Database(name string) (*meta2.DatabaseInfo, error)
DataNode(id uint64) (*meta2.DataNode, error)
DataNodes() ([]meta2.DataNode, error)
AliveReadNodes() ([]meta2.DataNode, error)
DeleteDataNode(id uint64) error
DeleteMetaNode(id uint64) error
DropShard(id uint64) error
DropSubscription(database, rp, name string) error
DropUser(name string) error
MetaNodes() ([]meta2.NodeInfo, error)
RetentionPolicy(database, name string) (rpi *meta2.RetentionPolicyInfo, err error)
SetAdminPrivilege(username string, admin bool) error
SetPrivilege(username, database string, p originql.Privilege) error
ShardsByTimeRange(sources influxql.Sources, tmin, tmax time.Time) (a []meta2.ShardInfo, err error)
ShardGroupsByTimeRange(database, policy string, min, max time.Time) (a []meta2.ShardGroupInfo, err error)
UpdateRetentionPolicy(database, name string, rpu *meta2.RetentionPolicyUpdate, makeDefault bool) error
UpdateUser(name, password string) error
UserPrivilege(username, database string) (*originql.Privilege, error)
UserPrivileges(username string) (map[string]originql.Privilege, error)
Users() []meta2.UserInfo
MarkDatabaseDelete(name string) error
MarkRetentionPolicyDelete(database, name string) error
MarkMeasurementDelete(database, mst string) error
DBPtView(database string) (meta2.DBPtInfos, error)
ShardOwner(shardID uint64) (database, policy string, sgi *meta2.ShardGroupInfo)
Measurement(database string, rpName string, mstName string) (*meta2.MeasurementInfo, error)
Schema(database string, retentionPolicy string, mst string) (fields map[string]int32, dimensions map[string]struct{}, err error)
GetMeasurements(m *influxql.Measurement) ([]*meta2.MeasurementInfo, error)
TagKeys(database string) map[string]set.Set
FieldKeys(database string, ms influxql.Measurements) (map[string]map[string]int32, error)
QueryTagKeys(database string, ms influxql.Measurements, cond influxql.Expr) (map[string]map[string]struct{}, error)
MatchMeasurements(database string, ms influxql.Measurements) (map[string]*meta2.MeasurementInfo, error)
Measurements(database string, ms influxql.Measurements) ([]string, error)
ShowShards() models.Rows
ShowShardGroups() models.Rows
ShowSubscriptions() models.Rows
ShowRetentionPolicies(database string) (models.Rows, error)
ShowCluster() models.Rows
ShowClusterWithCondition(nodeType string, ID uint64) (models.Rows, error)
GetAliveShards(database string, sgi *meta2.ShardGroupInfo) []int
NewDownSamplePolicy(database, name string, info *meta2.DownSamplePolicyInfo) error
DropDownSamplePolicy(database, name string, dropAll bool) error
ShowDownSamplePolicies(database string) (models.Rows, error)
GetMstInfoWithInRp(dbName, rpName string, dataTypes []int64) (*meta2.RpMeasurementsFieldsInfo, error)
AdminUserExists() bool
Authenticate(username, password string) (u meta2.User, e error)
UpdateShardDownSampleInfo(Ident *meta2.ShardIdentifier) error
OpenAtStore()
UpdateStreamMstSchema(database string, retentionPolicy string, mst string, stmt *influxql.SelectStatement) error
CreateStreamPolicy(info *meta2.StreamInfo) error
GetStreamInfos() map[string]*meta2.StreamInfo
GetStreamInfosStore() map[string]*meta2.StreamInfo
ShowStreams(database string, showAll bool) (models.Rows, error)
DropStream(name string) error
GetMeasurementInfoStore(database string, rpName string, mstName string) (*meta2.MeasurementInfo, error)
GetMeasurementsInfoStore(dbName string, rpName string) (*meta2.MeasurementsInfo, error)
GetAllMst(dbName string) []string
RetryRegisterQueryIDOffset(host string) (uint64, error)
ThermalShards(db string, start, end time.Duration) map[uint64]struct{}
GetNodePtsMap(database string) (map[uint64][]uint32, error)
DBRepGroups(database string) []meta2.ReplicaGroup
GetReplicaN(database string) (int, error)
// for continuous query
SendSql2MetaHeartbeat(host string) error
CreateContinuousQuery(database, name, query string) error
ShowContinuousQueries() (models.Rows, error)
DropContinuousQuery(name string, database string) error
UpdateShardInfoTier(shardID uint64, tier uint64, dbName, rpName string) error
// sysctrl for admin
SendSysCtrlToMeta(mod string, param map[string]string) (map[string]string, error)
}
type LoadCtx struct {
LoadCh chan *DBPTCtx
ReportCtx sync.Pool
}
func (ctx *LoadCtx) GetReportCtx() *DBPTCtx {
v := ctx.ReportCtx.Get()
if v == nil {
return &DBPTCtx{}
}
return v.(*DBPTCtx)
}
func (ctx *LoadCtx) PutReportCtx(dbPTCtx *DBPTCtx) {
dbPTCtx.DBPTStat.DB = proto.String("")
dbPTCtx.DBPTStat.PtID = proto.Uint32(0)
dbPTCtx.putRpStat(&dbPTCtx.DBPTStat.RpStats)
ctx.ReportCtx.Put(dbPTCtx)
}
type DBPTCtx struct {
DBPTStat *proto2.DBPtStatus
RpStatusPool sync.Pool
}
func (r *DBPTCtx) GetDBPTStat() *proto2.DBPtStatus {
if r.DBPTStat == nil {
r.DBPTStat = &proto2.DBPtStatus{}
}
return r.DBPTStat
}
func (r *DBPTCtx) GetRpStat() []*proto2.RpShardStatus {
v := r.RpStatusPool.Get()
if v == nil {
return []*proto2.RpShardStatus{}
}
return *(v.(*[]*proto2.RpShardStatus))
}
func (r *DBPTCtx) putRpStat(rss *[]*proto2.RpShardStatus) {
for i := range *rss {
(*rss)[i].RpName = proto.String("")
(*rss)[i].ShardStats.ShardID = proto.Uint64(0)
(*rss)[i].ShardStats.ShardSize = proto.Uint64(0)
(*rss)[i].ShardStats.SeriesCount = proto.Int32(0)
(*rss)[i].ShardStats.MaxTime = proto.Int64(0)
}
*rss = (*rss)[:0]
r.RpStatusPool.Put(rss)
}
func (r *DBPTCtx) String() string {
if r.DBPTStat == nil {
return ""
}
return r.DBPTStat.String()
}
type SendRPCMessage interface {
SendRPCMsg(currentServer int, msg *message.MetaMessage, callback transport.Callback) error
}
type RPCMessageSender struct{}
func (s *RPCMessageSender) SendRPCMsg(currentServer int, msg *message.MetaMessage, callback transport.Callback) error {
trans, err := transport.NewMetaTransport(uint64(currentServer), spdy.MetaRequest, callback)
if err != nil {
return err
}
trans.SetTimeout(RPCReqTimeout)
if err = trans.Send(msg); err != nil {
return err
}
if err = trans.Wait(); err != nil {
return err
}
refreshConnectedServer(currentServer)
return nil
}
// Client is used to execute commands on and read data from
// a meta service cluster.
type Client struct {
tls bool
logger *logger.Logger
nodeID uint64
ShardDurations map[uint64]*meta2.ShardDurationInfo
DBBriefInfos map[string]*meta2.DatabaseBriefInfo
mu sync.RWMutex
metaServers []string
closing chan struct{}
changed chan chan struct{}
cacheData *meta2.Data
// Authentication cache.
authCache map[string]authUser
weakPwdPath string
retentionAutoCreate bool
ShardTier uint64
// auth fail lock user
arChan chan *authRcd
muAuthData sync.RWMutex
authFailRcds map[string]authFailCache
authSuccRcds map[string]time.Time
// select hash ver
optAlgoVer int
replicaInfoManager *ReplicaInfoManager
// send RPC message interface.
SendRPCMessage
}
type authRcd struct {
user string
result bool // auth result(succ or fail)
occurTime time.Time
}
type authFailCache struct {
user string
occurTimeLst []time.Time // auth time list
}
type authUser struct {
bhash string
salt []byte
hash []byte
}
// NewClient returns a new *Client.
func NewClient(weakPwdPath string, retentionAutoCreate bool, maxConcurrentWriteLimit int) *Client {
cli := &Client{
cacheData: &meta2.Data{},
closing: make(chan struct{}),
changed: make(chan chan struct{}, maxConcurrentWriteLimit),
authCache: make(map[string]authUser),
weakPwdPath: weakPwdPath,
retentionAutoCreate: retentionAutoCreate,
logger: logger.NewLogger(errno.ModuleMetaClient).With(zap.String("service", "metaclient")),
arChan: make(chan *authRcd, authFailCacheLimit),
authFailRcds: make(map[string]authFailCache),
authSuccRcds: make(map[string]time.Time),
replicaInfoManager: NewReplicaInfoManager(),
SendRPCMessage: &RPCMessageSender{},
}
cliOnce.Do(func() {
DefaultMetaClient = cli
})
return cli
}
func cvtDataForAlgoVer(ver string) int {
var rst int
switch ver {
case "ver01":
rst = algoVer01
case "ver02":
rst = algoVer02
case "ver03":
rst = algoVer03
default:
rst = algoVer02
}
return rst
}
func (c *Client) SetHashAlgo(optHashAlgo string) {
c.optAlgoVer = cvtDataForAlgoVer(optHashAlgo)
}
// Open a connection to a meta service cluster.
func (c *Client) Open() error {
c.cacheData = c.retryUntilSnapshot(SQL, 0)
go c.pollForUpdates(SQL)
go c.updateAuthCacheData()
return nil
}
func (c *Client) OpenAtStore() {
c.cacheData = c.retryUntilSnapshot(STORE, 0)
go c.pollForUpdates(STORE)
go c.verifyDataNodeStatus()
}
// Close the meta service cluster connection.
func (c *Client) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if t, ok := http.DefaultTransport.(*http.Transport); ok {
t.CloseIdleConnections()
}
select {
case <-c.closing:
return nil
default:
close(c.closing)
}
return nil
}
// NodeID GetNodeID returns the client's node ID.
func (c *Client) NodeID() uint64 { return c.nodeID }
func (c *Client) SetTier(tier string) error {
c.ShardTier = meta2.StringToTier(strings.ToUpper(tier))
if c.ShardTier == util.TierBegin {
return fmt.Errorf("invalid tier %s", tier)
}
return nil
}
// SetMetaServers updates the meta servers on the client.
func (c *Client) SetMetaServers(a []string) {
c.mu.Lock()
defer c.mu.Unlock()
c.metaServers = a
for i, server := range a {
transport.NewMetaNodeManager().Add(uint64(i), server)
}
}
// SetTLS sets whether the client should use TLS when connecting.
// This function is not safe for concurrent use.
func (c *Client) SetTLS(v bool) { c.tls = v }
// Ping will hit the ping endpoint for the metaservice and return nil if
// it returns 200. If checkAllMetaServers is set to true, it will hit the
// ping endpoint and tell it to verify the health of all metaservers in the
// cluster
func (c *Client) Ping(checkAllMetaServers bool) error {
all := 0
if checkAllMetaServers {
all = 1
}
callback := &PingCallback{}
msg := message.NewMetaMessage(message.PingRequestMessage, &message.PingRequest{All: all})
err := c.SendRPCMsg(0, msg, callback)
if err != nil {
return err
}
return fmt.Errorf(string(callback.Leader))
}
// ClusterID returns the ID of the cluster it's connected to.
func (c *Client) ClusterID() uint64 {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ClusterID
}
// DataNode returns a node by id.
func (c *Client) DataNode(id uint64) (*meta2.DataNode, error) {
c.mu.RLock()
defer c.mu.RUnlock()
for i := range c.cacheData.DataNodes {
if c.cacheData.DataNodes[i].ID == id {
return &c.cacheData.DataNodes[i], nil
}
}
return nil, meta2.ErrNodeNotFound
}
func (c *Client) AliveReadNodes() ([]meta2.DataNode, error) {
c.mu.RLock()
defer c.mu.RUnlock()
var aliveReaders []meta2.DataNode
var aliveDefault []meta2.DataNode
for _, n := range c.cacheData.DataNodes {
if n.Status != serf.StatusAlive {
continue
}
if n.Role == meta2.NodeReader {
aliveReaders = append(aliveReaders, n)
} else if n.Role == meta2.NodeDefault {
aliveDefault = append(aliveDefault, n)
}
}
if len(aliveReaders) == 0 {
if len(aliveDefault) == 0 {
return nil, fmt.Errorf("there is no data nodes for querying")
}
sort.Sort(meta2.DataNodeInfos(aliveDefault))
return aliveDefault, nil
}
sort.Sort(meta2.DataNodeInfos(aliveReaders))
return aliveReaders, nil
}
// DataNodes returns the data nodes' info.
func (c *Client) DataNodes() ([]meta2.DataNode, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.DataNodes, nil
}
func (c *Client) GetAllMst(dbName string) []string {
var mstName []string
c.mu.RLock()
defer c.mu.RUnlock()
if _, ok := c.cacheData.Databases[dbName]; !ok {
return nil
}
for _, rp := range c.cacheData.Databases[dbName].RetentionPolicies {
for mst := range rp.Measurements {
mstName = append(mstName, mst)
}
}
return mstName
}
// CreateDataNode will create a new data node in the metastore
func (c *Client) CreateDataNode(writeHost, queryHost, role string) (uint64, uint64, uint64, error) {
currentServer := connectedServer
for {
// exit if we're closed
select {
case <-c.closing:
return 0, 0, 0, meta2.ErrClientClosed
default:
// we're still open, continue on
}
c.mu.RLock()
if currentServer >= len(c.metaServers) {
currentServer = 0
}
c.mu.RUnlock()
node, err := c.getNode(currentServer, writeHost, queryHost, role)
if err == nil && node.NodeId > 0 {
c.nodeID = node.NodeId
return c.nodeID, node.LTime, node.ConnId, nil
}
c.logger.Warn("get node failed", zap.Error(err), zap.String("writeHost", writeHost), zap.String("queryHost", queryHost))
time.Sleep(errSleep)
currentServer++
}
}
// DataNodeByHTTPHost returns the data node with the give http bind address
func (c *Client) DataNodeByHTTPHost(httpAddr string) (*meta2.DataNode, error) {
nodes, err := c.DataNodes()
if err != nil {
return nil, err
}
for _, n := range nodes {
if n.Host == httpAddr {
return &n, nil
}
}
return nil, meta2.ErrNodeNotFound
}
// DataNodeByTCPHost returns the data node with the give http bind address
func (c *Client) DataNodeByTCPHost(tcpAddr string) (*meta2.DataNode, error) {
nodes, err := c.DataNodes()
if err != nil {
return nil, err
}
for _, n := range nodes {
if n.TCPHost == tcpAddr {
return &n, nil
}
}
return nil, meta2.ErrNodeNotFound
}
// DeleteDataNode deletes a data node from the cluster.
func (c *Client) DeleteDataNode(id uint64) error {
cmd := &proto2.DeleteDataNodeCommand{
ID: proto.Uint64(id),
}
return c.retryUntilExec(proto2.Command_DeleteDataNodeCommand, proto2.E_DeleteDataNodeCommand_Command, cmd)
}
// MetaNodes returns the meta nodes' info.
func (c *Client) MetaNodes() ([]meta2.NodeInfo, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.MetaNodes, nil
}
// MetaNodeByAddr returns the meta node's info.
func (c *Client) MetaNodeByAddr(addr string) *meta2.NodeInfo {
c.mu.RLock()
defer c.mu.RUnlock()
for _, n := range c.cacheData.MetaNodes {
if n.Host == addr {
return &n
}
}
return nil
}
func (c *Client) FieldKeys(database string, ms influxql.Measurements) (map[string]map[string]int32, error) {
c.mu.RLock()
defer c.mu.RUnlock()
mis, err := c.matchMeasurements(database, ms)
if err != nil {
return nil, err
}
if len(mis) == 0 {
return nil, nil
}
ret := make(map[string]map[string]int32, len(mis))
for _, m := range mis {
ret[m.OriginName()] = make(map[string]int32)
m.FieldKeys(ret)
}
return ret, nil
}
func (c *Client) TagKeys(database string) map[string]set.Set {
c.mu.RLock()
defer c.mu.RUnlock()
dbi := c.cacheData.Database(database)
uniqueMap := make(map[string]set.Set)
dbi.WalkRetentionPolicy(func(rp *meta2.RetentionPolicyInfo) {
rp.EachMeasurements(func(mst *meta2.MeasurementInfo) {
s := set.NewSet()
for key := range mst.Schema {
if mst.Schema[key] == influx.Field_Type_Tag {
s.Add(key)
}
}
_, ok := uniqueMap[mst.Name]
if ok {
uniqueMap[mst.Name] = uniqueMap[mst.Name].Union(s)
return
}
uniqueMap[mst.Name] = s
})
})
return uniqueMap
}
func (c *Client) GetMeasurements(m *influxql.Measurement) ([]*meta2.MeasurementInfo, error) {
var measurements []*meta2.MeasurementInfo
c.mu.RLock()
defer c.mu.RUnlock()
dbi, err := c.cacheData.GetDatabase(m.Database)
if err != nil {
return nil, err
}
rpi, err := dbi.GetRetentionPolicy(m.RetentionPolicy)
if err != nil {
return nil, err
}
if m.Regex != nil {
rpi.EachMeasurements(func(msti *meta2.MeasurementInfo) {
if m.Regex.Val.Match([]byte(influx.GetOriginMstName(msti.Name))) {
measurements = append(measurements, msti)
}
})
sort.Slice(measurements, func(i, j int) bool {
return influx.GetOriginMstName(measurements[i].Name) < influx.GetOriginMstName(measurements[j].Name)
})
} else {
msti, err := rpi.GetMeasurement(m.Name)
if err != nil {
return nil, err
}
measurements = append(measurements, msti)
}
return measurements, nil
}
func (c *Client) Measurement(database string, rpName string, mstName string) (*meta2.MeasurementInfo, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.Measurement(database, rpName, mstName)
}
func (c *Client) RetryGetMeasurementInfoStore(database string, rpName string, mstName string) ([]byte, error) {
startTime := time.Now()
currentServer := connectedServer
var err error
var info []byte
for {
c.mu.RLock()
select {
case <-c.closing:
c.mu.RUnlock()
return nil, errors.New("GetMeasurementInfoStore fail")
default:
}
if currentServer >= len(c.metaServers) {
currentServer = 0
}
c.mu.RUnlock()
info, err = c.getMeasurementInfo(currentServer, database, rpName, mstName)
if err == nil {
break
}
if time.Since(startTime).Seconds() > float64(len(c.metaServers))*HttpReqTimeout.Seconds() {
break
}
time.Sleep(errSleep)
currentServer++
}
return info, nil
}
func (c *Client) getMeasurementInfo(currentServer int, database string, rpName string, mstName string) ([]byte, error) {
callback := &GetMeasurementInfoCallback{}
msg := message.NewMetaMessage(message.GetMeasurementInfoRequestMessage, &message.GetMeasurementInfoRequest{
DbName: database, RpName: rpName, MstName: mstName})
err := c.SendRPCMsg(currentServer, msg, callback)
if err != nil {
if !strings.Contains(err.Error(), "node is not the leader") {
c.logger.Error("GetMeasurementInfoR SendRPCMsg fail", zap.Error(err))
}
}
return callback.Data, nil
}
func (c *Client) GetMeasurementInfoStore(dbName string, rpName string, mstName string) (*meta2.MeasurementInfo, error) {
b, err := c.RetryGetMeasurementInfoStore(dbName, rpName, mstName)
if err != nil {
return nil, err
}
mst := &meta2.MeasurementInfo{}
if err = mst.UnmarshalBinary(b); err != nil {
return nil, err
}
return mst, nil
}
func (c *Client) GetMeasurementsInfoStore(dbName string, rpName string) (*meta2.MeasurementsInfo, error) {
b, err := c.RetryGetMeasurementsInfoStore(dbName, rpName)
if err != nil {
return nil, err
}
mst := &meta2.MeasurementsInfo{}
if err = mst.UnmarshalBinary(b); err != nil {
return nil, err
}
return mst, nil
}
func (c *Client) RetryGetMeasurementsInfoStore(database string, rpName string) ([]byte, error) {
startTime := time.Now()
currentServer := connectedServer
var err error
var info []byte
for {
c.mu.RLock()
select {
case <-c.closing:
c.mu.RUnlock()
return nil, errors.New("GetMeasurementsInfoStore fail")
default:
}
if currentServer >= len(c.metaServers) {
currentServer = 0
}
c.mu.RUnlock()
info, err = c.getMeasurementsInfo(currentServer, database, rpName)
if err == nil {
break
}
if time.Since(startTime).Seconds() > float64(len(c.metaServers))*HttpReqTimeout.Seconds() {
break
}
time.Sleep(errSleep)
currentServer++
}
return info, nil
}
func (c *Client) getMeasurementsInfo(currentServer int, database string, rpName string) ([]byte, error) {
callback := &GetMeasurementsInfoCallback{}
msg := message.NewMetaMessage(message.GetMeasurementsInfoRequestMessage, &message.GetMeasurementsInfoRequest{
DbName: database, RpName: rpName})
err := c.SendRPCMsg(currentServer, msg, callback)
if err != nil {
c.logger.Error("GetMeasurementInfoR SendRPCMsg fail", zap.Error(err))
return nil, err
}
return callback.Data, nil
}
// Database returns info for the requested database.
func (c *Client) Database(name string) (*meta2.DatabaseInfo, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.GetDatabase(name)
}
// Databases returns a list of all database infos.
func (c *Client) Databases() map[string]*meta2.DatabaseInfo {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.Databases
}
func (c *Client) ShowShards() models.Rows {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowShards()
}
func (c *Client) ShowShardGroups() models.Rows {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowShardGroups()
}
func (c *Client) ShowSubscriptions() models.Rows {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowSubscriptions()
}
func (c *Client) ShowRetentionPolicies(database string) (models.Rows, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowRetentionPolicies(database)
}
func (c *Client) ShowCluster() models.Rows {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowCluster()
}
func (c *Client) ShowClusterWithCondition(nodeType string, ID uint64) (models.Rows, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cacheData.ShowClusterWithCondition(nodeType, ID)
}
func (c *Client) Schema(database string, retentionPolicy string, mst string) (fields map[string]int32,
dimensions map[string]struct{}, err error) {
fields = make(map[string]int32)
dimensions = make(map[string]struct{})
msti, err := c.Measurement(database, retentionPolicy, mst)
if err != nil {
return nil, nil, err
}
for key := range msti.Schema {
if msti.Schema[key] == influx.Field_Type_Tag {
dimensions[key] = struct{}{}
} else {
fields[key] = msti.Schema[key]
}
}
return fields, dimensions, nil
}
func (c *Client) UpdateSchema(database string, retentionPolicy string, mst string, fieldToCreate []*proto2.FieldSchema) error {
cmd := &proto2.UpdateSchemaCommand{
Database: proto.String(database),
RpName: proto.String(retentionPolicy),
Measurement: proto.String(mst),
FieldToCreate: fieldToCreate,
}
err := c.retryUntilExec(proto2.Command_UpdateSchemaCommand, proto2.E_UpdateSchemaCommand_Command, cmd)
if err != nil {
return err
}
return nil
}
func (c *Client) CreateMeasurement(database, retentionPolicy, mst string, shardKey *meta2.ShardKeyInfo, indexR *influxql.IndexRelation,
engineType config.EngineType, colStoreInfo *meta2.ColStoreInfo, schemaInfo []*proto2.FieldSchema, options *meta2.Options) (*meta2.MeasurementInfo, error) {
msti, err := c.Measurement(database, retentionPolicy, mst)
if msti != nil {
// check shardkey equal or not
n := len(msti.ShardKeys)
if n == 0 || !shardKey.EqualsToAnother(&msti.ShardKeys[n-1]) {
return nil, meta2.ErrMeasurementExists
}
return msti, nil
}
if err != meta2.ErrMeasurementNotFound {
return nil, err
}
if !meta2.ValidMeasurementName(mst) {
return nil, errno.NewError(errno.InvalidMeasurement, mst)
}
cmd := &proto2.CreateMeasurementCommand{
DBName: proto.String(database),
RpName: proto.String(retentionPolicy),
Name: proto.String(mst),
EngineType: proto.Uint32(uint32(engineType)),
}
if shardKey != nil {
cmd.Ski = shardKey.Marshal()
}
if indexR != nil {
if msti == nil {
indexR.Rid = 0
} else {
indexR.Rid = 1
}
cmd.IR = meta2.EncodeIndexRelation(indexR)
}
if colStoreInfo != nil {
cmd.ColStoreInfo = colStoreInfo.Marshal()
}
if len(schemaInfo) > 0 {
cmd.SchemaInfo = schemaInfo
}
if options != nil {
cmd.Options = options.Marshal()
}
err = c.retryUntilExec(proto2.Command_CreateMeasurementCommand, proto2.E_CreateMeasurementCommand_Command, cmd)
if err != nil {
return nil, err
}
return c.Measurement(database, retentionPolicy, mst)
}
func (c *Client) AlterShardKey(database, retentionPolicy, mst string, shardKey *meta2.ShardKeyInfo) error {
_, err := c.Measurement(database, retentionPolicy, mst)
if err != nil {