/
helm.go
93 lines (83 loc) · 2.45 KB
/
helm.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
package catalog
import (
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/cnrancher/edge-api-server/pkg/apis/edgeapi.cattle.io/v1alpha1"
"github.com/cnrancher/edge-api-server/pkg/util"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
var (
httpTimeout = time.Second * 300
httpClient = &http.Client{
Timeout: httpTimeout,
}
)
type Helm struct {
catalogName string
Hash string
url string
username string
password string
}
func (h *Helm) request(pathURL string) (*http.Response, error) {
baseEndpoint, err := url.Parse(pathURL)
if err != nil {
return nil, err
}
if !baseEndpoint.IsAbs() {
helmURLstring := h.url
if !strings.HasSuffix(helmURLstring, "/") {
helmURLstring = helmURLstring + "/"
}
helmURL, err := url.Parse(helmURLstring)
if err != nil {
return nil, err
}
baseEndpoint = helmURL.ResolveReference(baseEndpoint)
}
if err := util.ValidateURL(baseEndpoint.String()); err != nil {
return nil, err
}
if len(h.username) > 0 && len(h.password) > 0 {
baseEndpoint.User = url.UserPassword(h.username, h.password)
}
req, err := http.NewRequest(http.MethodGet, baseEndpoint.String(), nil)
if err != nil {
return nil, err
}
return httpClient.Do(req)
}
func (h *Helm) downloadIndex(indexURL string) (*v1alpha1.IndexFile, error) {
indexURL = strings.TrimSuffix(indexURL, "/")
indexURL = indexURL + "/index.yaml"
resp, err := h.request(indexURL)
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
return nil, errors.Errorf("Timeout in HTTP GET to [%s], did not respond in %s", indexURL, httpTimeout)
}
return nil, errors.Errorf("Error in HTTP GET to [%s], error: %s", indexURL, err)
}
defer resp.Body.Close()
// only return forgot error if status code is unauthorized.
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized {
return nil, errors.Errorf("Unexpected HTTP status code %d from [%s], expected 200", resp.StatusCode, indexURL)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("Unexpected HTTP status code %d from [%s], expected 200", resp.StatusCode, indexURL)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Errorf("Error while reading response from [%s], error: %s", indexURL, err)
}
file := &v1alpha1.IndexFile{}
err = yaml.Unmarshal(body, file)
if err != nil {
return nil, errors.Errorf("error unmarshalling response from [%s]", indexURL)
}
return file, nil
}