This repository has been archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
backend.go
121 lines (99 loc) · 2.57 KB
/
backend.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package domain
import (
"errors"
"fmt"
"net"
"sync"
"code.cloudfoundry.org/lager"
)
var BridgesProvider = NewBridges
var Dialer = net.Dial
type Backend struct {
mutex sync.RWMutex
host string
port uint
statusPort uint
statusEndpoint string
logger lager.Logger
bridges Bridges
name string
healthy bool
}
type BackendJSON struct {
Host string `json:"host"`
Port uint `json:"port"`
StatusPort uint `json:"status_port"`
Healthy bool `json:"healthy"`
Name string `json:"name"`
CurrentSessionCount uint `json:"currentSessionCount"`
}
func NewBackend(
name string,
host string,
port uint,
statusPort uint,
statusEndpoint string,
logger lager.Logger) *Backend {
return &Backend{
name: name,
host: host,
port: port,
statusPort: statusPort,
statusEndpoint: statusEndpoint,
logger: logger,
bridges: BridgesProvider(logger),
}
}
func (b *Backend) HealthcheckUrl() string {
b.mutex.RLock()
defer b.mutex.RUnlock()
return fmt.Sprintf("http://%s:%d/%s", b.host, b.statusPort, b.statusEndpoint)
}
func (b *Backend) Bridge(clientConn net.Conn) error {
backendAddr := fmt.Sprintf("%s:%d", b.host, b.port)
backendConn, err := Dialer("tcp", backendAddr)
if err != nil {
return errors.New(fmt.Sprintf("Error establishing connection to backend: %s", err))
}
bridge := b.bridges.Create(clientConn, backendConn)
bridge.Connect()
_ = b.bridges.Remove(bridge) //untested
return nil
}
func (b *Backend) SeverConnections() {
b.logger.Info(fmt.Sprintf("Severing all connections to %s at %s:%d", b.name, b.host, b.port))
b.bridges.RemoveAndCloseAll()
}
func (b *Backend) SetHealthy() {
if !b.Healthy() {
b.logger.Info("Previously unhealthy backend became healthy.", lager.Data{"backend": b.AsJSON()})
}
b.mutex.Lock()
defer b.mutex.Unlock()
b.healthy = true
}
func (b *Backend) SetUnhealthy() {
if b.Healthy() {
b.logger.Info("Previously healthy backend became unhealthy.", lager.Data{"backend": b.AsJSON()})
}
b.mutex.Lock()
defer b.mutex.Unlock()
b.healthy = false
}
func (b *Backend) Healthy() bool {
b.mutex.RLock()
defer b.mutex.RUnlock()
return b.healthy
}
func (b *Backend) AsJSON() BackendJSON {
b.mutex.RLock()
defer b.mutex.RUnlock()
return BackendJSON{
Host: b.host,
Port: b.port,
StatusPort: b.statusPort,
Name: b.name,
Healthy: b.healthy,
CurrentSessionCount: b.bridges.Size(),
}
}