-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
92 lines (74 loc) · 2 KB
/
api.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
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/masif-upgrader/common"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
)
type badHttpStatus struct {
status int
body []byte
}
func (self *badHttpStatus) Error() string {
return fmt.Sprintf("bad HTTP response status %d (expected 200): %#v", self.status, string(self.body))
}
type api struct {
baseUrl string
client *http.Client
}
func newApi(master struct{ host, cn string }, tlsCfg struct{ cert, key, ca string }) (result *api, err error) {
log.WithFields(log.Fields{"cert": tlsCfg.cert, "key": tlsCfg.key}).Debug("Loading local TLS PKI")
clientCert, errLXKP := tls.LoadX509KeyPair(tlsCfg.cert, tlsCfg.key)
if errLXKP != nil {
return nil, errLXKP
}
log.WithFields(log.Fields{"ca": tlsCfg.ca}).Debug("Loading remote TLS PKI")
rootCA, errRF := ioutil.ReadFile(tlsCfg.ca)
if errRF != nil {
return nil, errRF
}
rootCAs := x509.NewCertPool()
rootCAs.AppendCertsFromPEM(rootCA)
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{clientCert},
RootCAs: rootCAs,
CipherSuites: common.ApiTlsCipherSuites,
MinVersion: common.ApiTlsMinVersion,
ServerName: master.cn,
},
},
}
return &api{baseUrl: "https://" + master.host + "/v1", client: client}, nil
}
func (self *api) reportTasks(tasks map[common.PkgMgrTask]struct{}) (approvedTasks map[common.PkgMgrTask]struct{}, err error) {
jsn, errPMT2A := common.PkgMgrTasks2Api(tasks)
if errPMT2A != nil {
return nil, errPMT2A
}
res, errPost := self.client.Post(
self.baseUrl+"/pending-tasks",
"application/json",
bytes.NewBuffer(jsn),
)
if errPost != nil {
return nil, errPost
}
defer res.Body.Close()
if res.StatusCode != 200 {
var buf bytes.Buffer
io.Copy(&buf, res.Body)
return nil, &badHttpStatus{res.StatusCode, buf.Bytes()}
}
body, errRA := ioutil.ReadAll(res.Body)
if errRA != nil {
return nil, errRA
}
return common.Api2PkgMgrTasks(body)
}