-
Notifications
You must be signed in to change notification settings - Fork 162
/
factory.go
90 lines (71 loc) · 2.32 KB
/
factory.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
package director
import (
"fmt"
"net"
"net/http"
"net/url"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshhttp "github.com/cloudfoundry/bosh-utils/http"
boshhttpclient "github.com/cloudfoundry/bosh-utils/httpclient"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
"time"
)
type Factory struct {
logTag string
logger boshlog.Logger
}
func NewFactory(logger boshlog.Logger) Factory {
return Factory{
logTag: "director.Factory",
logger: logger,
}
}
func (f Factory) New(config Config, taskReporter TaskReporter, fileReporter FileReporter) (Director, error) {
err := config.Validate()
if err != nil {
return DirectorImpl{}, bosherr.WrapErrorf(
err, "Validating Director connection config")
}
client, err := f.httpClient(config, taskReporter, fileReporter)
if err != nil {
return DirectorImpl{}, err
}
return DirectorImpl{client: client}, nil
}
func (f Factory) httpClient(config Config, taskReporter TaskReporter, fileReporter FileReporter) (Client, error) {
certPool, err := config.CACertPool()
if err != nil {
return Client{}, err
}
if certPool == nil {
f.logger.Debug(f.logTag, "Using default root CAs")
} else {
f.logger.Debug(f.logTag, "Using custom root CAs")
}
rawClient := boshhttpclient.CreateDefaultClient(certPool)
authAdjustment := NewAuthRequestAdjustment(
config.TokenFunc, config.Client, config.ClientSecret)
rawClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > 10 {
return bosherr.Error("Too many redirects")
}
// Since redirected requests are not retried,
// forcefully adjust auth token as this is the last chance.
err := authAdjustment.Adjust(req, true)
if err != nil {
return err
}
req.URL.Host = net.JoinHostPort(config.Host, fmt.Sprintf("%d", config.Port))
req.Header.Del("Referer")
return nil
}
retryClient := boshhttp.NewNetworkSafeRetryClient(rawClient, 5, 500*time.Millisecond, f.logger)
authedClient := NewAdjustableClient(retryClient, authAdjustment)
httpOpts := boshhttpclient.Opts{NoRedactUrlQuery: true}
httpClient := boshhttpclient.NewHTTPClientOpts(authedClient, f.logger, httpOpts)
endpoint := url.URL{
Scheme: "https",
Host: net.JoinHostPort(config.Host, fmt.Sprintf("%d", config.Port)),
}
return NewClient(endpoint.String(), httpClient, taskReporter, fileReporter, f.logger), nil
}