Debian Codegraph @

_examples/custom_engine_tarantool/tntengine/multi_conn.go

raw
1 package tntengine
2
3 import (
4 "context"
5 "errors"
6 "sync"
7 "time"
8
9 "github.com/FZambia/tarantool"
10 )
11
12 type ConnectionMode int
13
14 const (
15 ConnectionModeSingleInstance ConnectionMode = 0
16 ConnectionModeLeaderFollower ConnectionMode = 1
17 ConnectionModeLeaderFollowerRaft ConnectionMode = 2
18 )
19
20 type MultiConnection struct {
21 opts MultiOpts
22 leaderMu sync.RWMutex
23 leaderAddr string
24 conns map[string]*tarantool.Connection
25 closeCh chan struct{}
26 closeOnce sync.Once
27 }
28
29 type MultiOpts struct {
30 ConnectionMode ConnectionMode
31 LeaderCheckInterval time.Duration
32 }
33
34 func Connect(addrs []string, opts tarantool.Opts, multiOpts MultiOpts) (*MultiConnection, error) {
35 conns, err := getConns(addrs, opts)
36 if err != nil {
37 return nil, err
38 }
39 mc := &MultiConnection{
40 opts: multiOpts,
41 conns: conns,
42 closeCh: make(chan struct{}),
43 }
44 leaderFound := mc.checkLeaderOnce()
45 if !leaderFound {
46 return nil, ErrNoLeader
47 }
48 go mc.checkLeader()
49 return mc, nil
50 }
51
52 var ErrNoLeader = errors.New("no leader")
53
54 func (c *MultiConnection) NewLeaderConn(opts tarantool.Opts) (*tarantool.Connection, error) {
55 c.leaderMu.RLock()
56 if c.leaderAddr == "" {
57 c.leaderMu.RUnlock()
58 return nil, ErrNoLeader
59 }
60 c.leaderMu.RUnlock()
61 return tarantool.Connect(c.leaderAddr, opts)
62 }
63
64 func (c *MultiConnection) LeaderChanged() {
65 if c.opts.ConnectionMode == ConnectionModeSingleInstance {
66 return
67 }
68 c.leaderMu.Lock()
69 defer c.leaderMu.Unlock()
70 c.leaderAddr = ""
71 }
72
73 func (c *MultiConnection) LeaderConn() (*tarantool.Connection, error) {
74 c.leaderMu.RLock()
75 defer c.leaderMu.RUnlock()
76 if c.leaderAddr != "" {
77 return c.conns[c.leaderAddr], nil
78 }
79 return nil, ErrNoLeader
80 }
81
82 func getConns(addrs []string, opts tarantool.Opts) (map[string]*tarantool.Connection, error) {
83 conns := map[string]*tarantool.Connection{}
84 var wg sync.WaitGroup
85 var connsMu sync.Mutex
86 var firstErr error
87 var numErrors int
88 wg.Add(len(addrs))
89 for _, addr := range addrs {
90 go func(addr string) {
91 defer wg.Done()
92 conn, err := tarantool.Connect(addr, opts)
93 if err != nil {
94 connsMu.Lock()
95 if firstErr == nil {
96 firstErr = err
97 }
98 numErrors++
99 connsMu.Unlock()
100 return
101 }
102 connsMu.Lock()
103 conns[addr] = conn
104 connsMu.Unlock()
105 }(addr)
106
107 }
108 wg.Wait()
109 if numErrors == len(addrs) {
110 return nil, firstErr
111 }
112 return conns, nil
113 }
114
115 func (c *MultiConnection) checkLeader() {
116 if c.opts.ConnectionMode == ConnectionModeSingleInstance {
117 return
118 }
119 checkInterval := c.opts.LeaderCheckInterval
120 if checkInterval == 0 {
121 checkInterval = time.Second
122 }
123 for {
124 select {
125 case <-c.closeCh:
126 return
127 case <-time.After(checkInterval):
128 c.checkLeaderOnce()
129 }
130 }
131 }
132
133 func (c *MultiConnection) IsLeader(conn *tarantool.Connection) (bool, error) {
134 if c.opts.ConnectionMode == ConnectionModeSingleInstance {
135 return true, nil
136 }
137 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
138 defer cancel()
139 leaderCheck := "return box.info.ro == false"
140 if c.opts.ConnectionMode == ConnectionModeLeaderFollowerRaft {
141 leaderCheck = "return box.info.election.state == 'leader'"
142 }
143 resp, err := conn.ExecContext(ctx, tarantool.Eval(leaderCheck, []interface{}{}))
144 if err != nil {
145 return false, err
146 }
147 if len(resp.Data) < 1 {
148 return false, errors.New("unexpected leader check result")
149 }
150 isLeader, ok := resp.Data[0].(bool)
151 if !ok {
152 return false, errors.New("malformed leader check result")
153 }
154 return isLeader, nil
155 }
156
157 func (c *MultiConnection) checkLeaderOnce() bool {
158 for addr, conn := range c.conns {
159 if len(c.conns) == 1 {
160 c.leaderAddr = addr
161 return true
162 }
163 isLeader, err := c.IsLeader(conn)
164 if err != nil {
165 continue
166 }
167 if isLeader {
168 c.leaderMu.Lock()
169 c.leaderAddr = addr
170 c.leaderMu.Unlock()
171 return true
172 }
173 }
174 return false
175 }
176
177 func (c *MultiConnection) Close() error {
178 c.closeOnce.Do(func() {
179 close(c.closeCh)
180 for _, conn := range c.conns {
181 _ = conn.Close()
182 }
183 })
184 return nil
185 }