-
Notifications
You must be signed in to change notification settings - Fork 316
/
manager.go
99 lines (82 loc) · 1.98 KB
/
manager.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
package controlplane
import (
"fmt"
"sync"
"time"
"google.golang.org/grpc"
)
type ConnectionManager struct {
AuthInfo AuthInfo
RegisterService func(*grpc.Server)
RetryInterval time.Duration
UseTLS bool
Logger LoggerI
mu sync.Mutex
active bool
url string
connHandler *ConnHandler
}
type LoggerI interface {
Warn(a ...interface{})
Warnf(format string, a ...interface{})
Info(a ...interface{})
Infof(format string, a ...interface{})
Error(a ...interface{})
Errorf(format string, a ...interface{})
}
const defaultRetryInterval time.Duration = time.Second
func (cm *ConnectionManager) Apply(url string, active bool) {
if url == "" {
return
}
cm.mu.Lock()
defer cm.mu.Unlock()
cm.url = url
if active && !cm.active {
cm.active = true
cm.Logger.Infof(`Connection to CP Router not active. Establishing new connection`)
go cm.maintainConnection()
} else if !active && cm.active {
cm.active = false
cm.Logger.Infof(`Closing connection to CP Router`)
_ = cm.closeConnection()
}
}
func (cm *ConnectionManager) connect() error {
cm.mu.Lock()
defer cm.mu.Unlock()
conn, err := cm.establishConnection()
if err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
cm.RegisterService(conn.GRPCServer)
cm.connHandler = conn
return nil
}
func (cm *ConnectionManager) maintainConnection() {
for cm.active {
if err := cm.connect(); err != nil {
cm.Logger.Error(err.Error())
} else {
if err := cm.connHandler.ServeOnConnection(); err != nil {
cm.Logger.Error(err.Error())
}
}
time.Sleep(cm.retryInterval())
}
}
func (cm *ConnectionManager) closeConnection() error {
defer func() {
cm.connHandler = nil
}()
if err := cm.connHandler.Close(); err != nil {
return fmt.Errorf("failed to close grpc connection: %w", err)
}
return nil
}
func (cm *ConnectionManager) retryInterval() time.Duration {
if cm.RetryInterval == 0 {
return defaultRetryInterval
}
return cm.RetryInterval
}