forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_manager.go
100 lines (88 loc) · 2.51 KB
/
connection_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
100
package engine
import (
"fmt"
"sync/atomic"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/connchecker"
"github.com/thrasher-corp/gocryptotrader/log"
)
// ConnectionManagerName is an exported subsystem name
const ConnectionManagerName = "internet_monitor"
// connectionManager manages the connchecker
type connectionManager struct {
started int32
conn *connchecker.Checker
cfg *config.ConnectionMonitorConfig
}
// IsRunning safely checks whether the subsystem is running
func (m *connectionManager) IsRunning() bool {
if m == nil {
return false
}
return atomic.LoadInt32(&m.started) == 1
}
// setupConnectionManager creates a connection manager
func setupConnectionManager(cfg *config.ConnectionMonitorConfig) (*connectionManager, error) {
if cfg == nil {
return nil, errNilConfig
}
if cfg.DNSList == nil {
cfg.DNSList = connchecker.DefaultDNSList
}
if cfg.PublicDomainList == nil {
cfg.PublicDomainList = connchecker.DefaultDomainList
}
if cfg.CheckInterval == 0 {
cfg.CheckInterval = connchecker.DefaultCheckInterval
}
return &connectionManager{
cfg: cfg,
}, nil
}
// Start runs the subsystem
func (m *connectionManager) Start() error {
if m == nil {
return fmt.Errorf("connection manager %w", ErrNilSubsystem)
}
if !atomic.CompareAndSwapInt32(&m.started, 0, 1) {
return fmt.Errorf("connection manager %w", ErrSubSystemAlreadyStarted)
}
log.Debugln(log.ConnectionMgr, "Connection manager starting...")
var err error
m.conn, err = connchecker.New(m.cfg.DNSList,
m.cfg.PublicDomainList,
m.cfg.CheckInterval)
if err != nil {
atomic.CompareAndSwapInt32(&m.started, 1, 0)
return err
}
log.Debugln(log.ConnectionMgr, "Connection manager started.")
return nil
}
// Stop stops the connection manager
func (m *connectionManager) Stop() error {
if m == nil {
return fmt.Errorf("connection manager %w", ErrNilSubsystem)
}
if atomic.LoadInt32(&m.started) == 0 {
return fmt.Errorf("connection manager %w", ErrSubSystemNotStarted)
}
defer func() {
atomic.CompareAndSwapInt32(&m.started, 1, 0)
}()
log.Debugln(log.ConnectionMgr, "Connection manager shutting down...")
m.conn.Shutdown()
log.Debugln(log.ConnectionMgr, "Connection manager stopped.")
return nil
}
// IsOnline returns if the connection manager is online
func (m *connectionManager) IsOnline() bool {
if m == nil {
return false
}
if m.conn == nil {
log.Warnln(log.ConnectionMgr, "Connection manager: IsOnline called but conn is nil")
return false
}
return m.conn.IsConnected()
}