-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathcmgr.go
More file actions
236 lines (203 loc) · 6.06 KB
/
cmgr.go
File metadata and controls
236 lines (203 loc) · 6.06 KB
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
package cmgr
import (
"context"
"os"
"path/filepath"
"sort"
"sync"
"time"
"github.com/Ehco1996/ehco/internal/cmgr/ms"
"github.com/Ehco1996/ehco/internal/conn"
"github.com/Ehco1996/ehco/pkg/metric_reader"
"go.uber.org/zap"
)
const (
ConnectionTypeActive = "active"
ConnectionTypeClosed = "closed"
)
// connection manager interface/
// TODO support closed connection
type Cmgr interface {
ListConnections(connType string, page, pageSize int) []conn.RelayConn
// AddConnection adds a connection to the connection manager.
AddConnection(conn conn.RelayConn)
// RemoveConnection removes a connection from the connection manager.
RemoveConnection(conn conn.RelayConn)
// CountConnection returns the number of active connections.
CountConnection(connType string) int
GetActiveConnectCntByRelayLabel(label string) int
// Start starts the connection manager.
Start(ctx context.Context, errCH chan error)
// Metrics related
QueryNodeMetrics(ctx context.Context, req *ms.QueryNodeMetricsReq, refresh bool) (*ms.QueryNodeMetricsResp, error)
QueryRuleMetrics(ctx context.Context, req *ms.QueryRuleMetricsReq, refresh bool) (*ms.QueryRuleMetricsResp, error)
}
type cmgrImpl struct {
lock sync.RWMutex
cfg *Config
l *zap.SugaredLogger
// k: relay label, v: connection list
activeConnectionsMap map[string][]conn.RelayConn
closedConnectionsMap map[string][]conn.RelayConn
ms *ms.MetricsStore
mr metric_reader.Reader
}
func NewCmgr(cfg *Config) (Cmgr, error) {
cmgr := &cmgrImpl{
cfg: cfg,
l: zap.S().Named("cmgr"),
activeConnectionsMap: make(map[string][]conn.RelayConn),
closedConnectionsMap: make(map[string][]conn.RelayConn),
}
if cfg.NeedMetrics() {
cmgr.mr = metric_reader.NewReader(cfg.MetricsURL, cfg.ApiToken)
homeDir, _ := os.UserHomeDir()
dbPath := filepath.Join(homeDir, ".ehco", "metrics.db")
ms, err := ms.NewMetricsStore(dbPath)
if err != nil {
return nil, err
}
cmgr.ms = ms
}
return cmgr, nil
}
func (cm *cmgrImpl) ListConnections(connType string, page, pageSize int) []conn.RelayConn {
cm.lock.RLock()
defer cm.lock.RUnlock()
var total int
var m map[string][]conn.RelayConn
if connType == ConnectionTypeActive {
total = cm.countActiveConnection()
m = cm.activeConnectionsMap
} else {
total = cm.countClosedConnection()
m = cm.closedConnectionsMap
}
start := (page - 1) * pageSize
if start > total {
return []conn.RelayConn{} // Return empty slice if start index is more than length
}
end := start + pageSize
if end > total {
end = total
}
relayLabelList := make([]string, 0, len(m))
for k := range m {
relayLabelList = append(relayLabelList, k)
}
// Sort the relay label list to make the result more predictable
sort.Strings(relayLabelList)
var conns []conn.RelayConn
for _, label := range relayLabelList {
conns = append(conns, m[label]...)
}
if end > len(conns) {
end = len(conns) // Don't let the end index be more than slice length
}
return conns[start:end]
}
func (cm *cmgrImpl) AddConnection(c conn.RelayConn) {
cm.lock.Lock()
defer cm.lock.Unlock()
label := c.GetRelayLabel()
if _, ok := cm.activeConnectionsMap[label]; !ok {
cm.activeConnectionsMap[label] = []conn.RelayConn{}
}
cm.activeConnectionsMap[label] = append(cm.activeConnectionsMap[label], c)
}
func (cm *cmgrImpl) RemoveConnection(c conn.RelayConn) {
cm.lock.Lock()
defer cm.lock.Unlock()
label := c.GetRelayLabel()
connections, ok := cm.activeConnectionsMap[label]
if !ok {
return // If the label doesn't exist, nothing to remove
}
// Find and remove the connection from activeConnectionsMap
for i, activeConn := range connections {
if activeConn == c {
cm.activeConnectionsMap[label] = append(connections[:i], connections[i+1:]...)
break
}
}
// Add to closedConnectionsMap
cm.closedConnectionsMap[label] = append(cm.closedConnectionsMap[label], c)
}
func (cm *cmgrImpl) CountConnection(connType string) int {
if connType == ConnectionTypeActive {
return cm.countActiveConnection()
} else {
return cm.countClosedConnection()
}
}
func (cm *cmgrImpl) countActiveConnection() int {
cm.lock.RLock()
defer cm.lock.RUnlock()
cnt := 0
for _, v := range cm.activeConnectionsMap {
cnt += len(v)
}
return cnt
}
func (cm *cmgrImpl) countClosedConnection() int {
cm.lock.RLock()
defer cm.lock.RUnlock()
cnt := 0
for _, v := range cm.closedConnectionsMap {
cnt += len(v)
}
return cnt
}
func (cm *cmgrImpl) GetActiveConnectCntByRelayLabel(label string) int {
cm.lock.RLock()
defer cm.lock.RUnlock()
return len(cm.activeConnectionsMap[label])
}
func (cm *cmgrImpl) Start(ctx context.Context, errCH chan error) {
cm.l.Infof("Start Cmgr sync interval=%d", cm.cfg.SyncInterval)
ticker := time.NewTicker(time.Second * time.Duration(cm.cfg.SyncInterval))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
cm.l.Info("sync stop")
return
case <-ticker.C:
// Tolerate transient sync failures: retryablehttp already does
// internal backoff; on final error we just log and wait for the
// next tick. The traffic stats accumulated for this interval are
// dropped on the floor.
// TODO: persist unsent stats locally so they can be retried on
// later ticks instead of being lost when the upstream is down.
if err := cm.syncOnce(ctx); err != nil {
cm.l.Errorf("sync failed, will retry on next tick in %ds: %s", cm.cfg.SyncInterval, err)
}
}
}
}
func (cm *cmgrImpl) QueryNodeMetrics(ctx context.Context, req *ms.QueryNodeMetricsReq, refresh bool) (*ms.QueryNodeMetricsResp, error) {
if refresh {
nm, _, err := cm.mr.ReadOnce(ctx)
if err != nil {
return nil, err
}
if err := cm.ms.AddNodeMetric(ctx, nm); err != nil {
return nil, err
}
}
return cm.ms.QueryNodeMetric(ctx, req)
}
func (cm *cmgrImpl) QueryRuleMetrics(ctx context.Context, req *ms.QueryRuleMetricsReq, refresh bool) (*ms.QueryRuleMetricsResp, error) {
if refresh {
_, rm, err := cm.mr.ReadOnce(ctx)
if err != nil {
return nil, err
}
for _, m := range rm {
if err := cm.ms.AddRuleMetric(ctx, m); err != nil {
return nil, err
}
}
}
return cm.ms.QueryRuleMetric(ctx, req)
}