-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathhost_httploadbalancer.go
More file actions
192 lines (163 loc) · 4.69 KB
/
Copy pathhost_httploadbalancer.go
File metadata and controls
192 lines (163 loc) · 4.69 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package collect
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2"
"github.com/replicatedhq/troubleshoot/pkg/debug"
"github.com/segmentio/ksuid"
)
type CollectHostHTTPLoadBalancer struct {
hostCollector *troubleshootv1beta2.HTTPLoadBalancer
BundlePath string
}
func (c *CollectHostHTTPLoadBalancer) Title() string {
return hostCollectorTitleOrDefault(c.hostCollector.HostCollectorMeta, "HTTP Load Balancer")
}
func (c *CollectHostHTTPLoadBalancer) IsExcluded() (bool, error) {
return isExcluded(c.hostCollector.Exclude)
}
func (c *CollectHostHTTPLoadBalancer) Collect(progressChan chan<- interface{}) (map[string][]byte, error) {
listenAddress := fmt.Sprintf("0.0.0.0:%d", c.hostCollector.Port)
timeout := 60 * time.Minute
if c.hostCollector.Timeout != "" {
var err error
timeout, err = time.ParseDuration(c.hostCollector.Timeout)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse timeout %q", c.hostCollector.Timeout)
}
}
requestToken := ksuid.New().Bytes()
responseToken := ksuid.New().Bytes()
listenErr := make(chan error, 1)
go func() {
mux := http.NewServeMux()
server := http.Server{
Addr: listenAddress,
Handler: mux,
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
if !bytes.Equal(body, requestToken) {
return
}
_, err = w.Write(responseToken)
if err != nil {
return
}
server.Shutdown(context.Background())
})
err := http.ListenAndServe(listenAddress, mux)
if err != http.ErrServerClosed {
listenErr <- err
}
}()
var networkStatus NetworkStatus
var errorMessage string
var collectorErr error
stopAfter := time.Now().Add(timeout)
for {
if len(listenErr) > 0 {
err := <-listenErr
errorMessage = err.Error()
collectorErr = errors.Wrap(err, "failed to listen on HTTP port")
if strings.Contains(err.Error(), "address already in use") {
networkStatus = NetworkStatusAddressInUse
break
}
if strings.Contains(err.Error(), "permission denied") {
networkStatus = NetworkStatusBindPermissionDenied
break
}
debug.Println(err.Error())
networkStatus = NetworkStatusErrorOther
break
}
if time.Now().After(stopAfter) {
break
}
networkStatus = attemptPOST(c.hostCollector.Address, requestToken, responseToken)
if networkStatus == NetworkStatusErrorOther || networkStatus == NetworkStatusConnectionTimeout {
progressChan <- errors.Errorf("http post %s: network status %q", c.hostCollector.Address, networkStatus)
time.Sleep(time.Second)
continue
}
break
}
result := NetworkStatusResult{
Status: networkStatus,
Message: errorMessage,
}
b, err := json.Marshal(result)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal result")
}
collectorName := c.hostCollector.CollectorName
if collectorName == "" {
collectorName = "httpLoadBalancer"
}
name := filepath.Join("host-collectors/httpLoadBalancer", collectorName+".json")
output := NewResult()
output.SaveResult(c.BundlePath, name, bytes.NewBuffer(b))
return map[string][]byte{
name: b,
}, collectorErr
}
func attemptPOST(address string, request []byte, response []byte) NetworkStatus {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
// Create a new transport every time to ensure a new TCP connection so the load balancer does
// not forward every request to the same backend
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 50 * time.Millisecond,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
}
client := http.Client{
Transport: transport,
}
buf := bytes.NewBuffer(request)
req, err := http.NewRequestWithContext(ctx, "POST", address, buf)
if err != nil {
debug.Println(err.Error())
return NetworkStatusErrorOther
}
resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "connection refused") {
return NetworkStatusConnectionRefused
}
if strings.Contains(err.Error(), "i/o timeout") {
return NetworkStatusConnectionTimeout
}
return NetworkStatusErrorOther
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return NetworkStatusErrorOther
}
if !bytes.Equal(body, response) {
return NetworkStatusErrorOther
}
return NetworkStatusConnected
}
func (c *CollectHostHTTPLoadBalancer) RemoteCollect(progressChan chan<- interface{}) (map[string][]byte, error) {
return nil, ErrRemoteCollectorNotImplemented
}