forked from openware/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
69 lines (57 loc) · 1.81 KB
/
connection.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
package engine
import (
"errors"
"sync/atomic"
"github.com/thrasher-corp/gocryptotrader/connchecker"
"github.com/thrasher-corp/gocryptotrader/log"
)
// connectionManager manages the connchecker
type connectionManager struct {
started int32
stopped int32
conn *connchecker.Checker
}
// Started returns if the connection manager has started
func (c *connectionManager) Started() bool {
return atomic.LoadInt32(&c.started) == 1
}
// Start starts an instance of the connection manager
func (c *connectionManager) Start() error {
if atomic.AddInt32(&c.started, 1) != 1 {
return errors.New("connection manager already started")
}
log.Debugln(log.ConnectionMgr, "Connection manager starting...")
var err error
c.conn, err = connchecker.New(Bot.Config.ConnectionMonitor.DNSList,
Bot.Config.ConnectionMonitor.PublicDomainList,
Bot.Config.ConnectionMonitor.CheckInterval)
if err != nil {
atomic.CompareAndSwapInt32(&c.started, 1, 0)
return err
}
log.Debugln(log.ConnectionMgr, "Connection manager started.")
return nil
}
// Stop stops the connection manager
func (c *connectionManager) Stop() error {
if atomic.LoadInt32(&c.started) == 0 {
return errors.New("connection manager not started")
}
if atomic.AddInt32(&c.stopped, 1) != 1 {
return errors.New("connection manager is already stopped")
}
log.Debugln(log.ConnectionMgr, "Connection manager shutting down...")
c.conn.Shutdown()
atomic.CompareAndSwapInt32(&c.stopped, 1, 0)
atomic.CompareAndSwapInt32(&c.started, 1, 0)
log.Debugln(log.ConnectionMgr, "Connection manager stopped.")
return nil
}
// IsOnline returns if the connection manager is online
func (c *connectionManager) IsOnline() bool {
if c.conn == nil {
log.Warnln(log.ConnectionMgr, "Connection manager: IsOnline called but conn is nil")
return false
}
return c.conn.IsConnected()
}