-
Notifications
You must be signed in to change notification settings - Fork 25
/
conn_manager.go
104 lines (85 loc) · 2.11 KB
/
conn_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
101
102
103
104
package v2
import (
"errors"
"io"
"log"
"sync/atomic"
"time"
"unsafe"
"code.cloudfoundry.org/go-loggregator/v9/rpc/loggregator_v2"
)
type Connector interface {
Connect() (io.Closer, loggregator_v2.Ingress_BatchSenderClient, error)
}
type v2GRPCConn struct {
client loggregator_v2.Ingress_BatchSenderClient
closer io.Closer
writes int64
}
type ConnManager struct {
conn unsafe.Pointer
maxWrites int64
pollDuration time.Duration
connector Connector
ticker *time.Ticker
reset chan bool
}
func NewConnManager(c Connector, maxWrites int64, pollDuration time.Duration) *ConnManager {
m := &ConnManager{
maxWrites: maxWrites,
pollDuration: pollDuration,
connector: c,
ticker: time.NewTicker(pollDuration),
reset: make(chan bool, 100),
}
go m.maintainConn()
return m
}
func (m *ConnManager) Write(envelopes []*loggregator_v2.Envelope) error {
conn := atomic.LoadPointer(&m.conn)
if conn == nil || (*v2GRPCConn)(conn) == nil {
return errors.New("no connection to doppler present")
}
gRPCConn := (*v2GRPCConn)(conn)
err := gRPCConn.client.Send(&loggregator_v2.EnvelopeBatch{Batch: envelopes})
if err != nil {
log.Printf("error writing to doppler: %s", err)
atomic.StorePointer(&m.conn, nil)
gRPCConn.closer.Close()
m.reset <- true
return err
}
if atomic.AddInt64(&gRPCConn.writes, 1) >= m.maxWrites {
log.Printf("recycling connection to doppler after %d writes", m.maxWrites)
atomic.StorePointer(&m.conn, nil)
gRPCConn.closer.Close()
m.reset <- true
}
return nil
}
func (m *ConnManager) maintainConn() {
// Ensure initial connection does not wait on timer
m.reset <- true
for {
m.checkConnectionTimer()
conn := atomic.LoadPointer(&m.conn)
if conn != nil && (*v2GRPCConn)(conn) != nil {
continue
}
closer, senderClient, err := m.connector.Connect()
if err != nil {
log.Printf("failed to connect: %s", err)
continue
}
atomic.StorePointer(&m.conn, unsafe.Pointer(&v2GRPCConn{
client: senderClient,
closer: closer,
}))
}
}
func (m *ConnManager) checkConnectionTimer() {
select {
case <-m.ticker.C:
case <-m.reset:
}
}