/
virtual_environment_client.go
201 lines (156 loc) · 5.6 KB
/
virtual_environment_client.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
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
193
194
195
196
197
198
199
200
201
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
package proxmox
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
)
// NewVirtualEnvironmentClient creates and initializes a VirtualEnvironmentClient instance.
func NewVirtualEnvironmentClient(endpoint, username, password, otp string, insecure bool) (*VirtualEnvironmentClient, error) {
url, err := url.ParseRequestURI(endpoint)
if err != nil {
return nil, errors.New("You must specify a valid endpoint for the Proxmox Virtual Environment API (valid: https://host:port/)")
}
if url.Scheme != "https" {
return nil, errors.New("You must specify a secure endpoint for the Proxmox Virtual Environment API (valid: https://host:port/)")
}
if password == "" {
return nil, errors.New("You must specify a password for the Proxmox Virtual Environment API")
}
if username == "" {
return nil, errors.New("You must specify a username for the Proxmox Virtual Environment API")
}
var pOTP *string
if otp != "" {
pOTP = &otp
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: insecure,
},
},
}
return &VirtualEnvironmentClient{
Endpoint: strings.TrimRight(url.String(), "/"),
Insecure: insecure,
OTP: pOTP,
Password: password,
Username: username,
httpClient: httpClient,
}, nil
}
// DoRequest performs a HTTP request against a JSON API endpoint.
func (c *VirtualEnvironmentClient) DoRequest(method, path string, requestBody interface{}, responseBody interface{}) error {
var reqBodyReader io.Reader
var reqContentLength *int64
log.Printf("[DEBUG] Performing HTTP %s request (path: %s)", method, path)
modifiedPath := path
reqBodyType := ""
if requestBody != nil {
multipartData, multipart := requestBody.(*VirtualEnvironmentMultiPartData)
pipedBodyReader, pipedBody := requestBody.(*io.PipeReader)
if multipart {
reqBodyReader = multipartData.Reader
reqBodyType = fmt.Sprintf("multipart/form-data; boundary=%s", multipartData.Boundary)
reqContentLength = multipartData.Size
log.Printf("[DEBUG] Added multipart request body to HTTP %s request (path: %s)", method, modifiedPath)
} else if pipedBody {
reqBodyReader = pipedBodyReader
log.Printf("[DEBUG] Added piped request body to HTTP %s request (path: %s)", method, modifiedPath)
} else {
v, err := query.Values(requestBody)
if err != nil {
fErr := fmt.Errorf("Failed to encode HTTP %s request (path: %s) - Reason: %s", method, modifiedPath, err.Error())
log.Printf("[DEBUG] WARNING: %s", fErr.Error())
return fErr
}
encodedValues := v.Encode()
if encodedValues != "" {
if method == hmDELETE || method == hmGET || method == hmHEAD {
if !strings.Contains(modifiedPath, "?") {
modifiedPath = fmt.Sprintf("%s?%s", modifiedPath, encodedValues)
} else {
modifiedPath = fmt.Sprintf("%s&%s", modifiedPath, encodedValues)
}
} else {
reqBodyReader = bytes.NewBufferString(encodedValues)
reqBodyType = "application/x-www-form-urlencoded"
}
log.Printf("[DEBUG] Added request body to HTTP %s request (path: %s) - Body: %s", method, modifiedPath, encodedValues)
}
}
} else {
reqBodyReader = new(bytes.Buffer)
}
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s/%s", c.Endpoint, basePathJSONAPI, modifiedPath), reqBodyReader)
if err != nil {
fErr := fmt.Errorf("Failed to create HTTP %s request (path: %s) - Reason: %s", method, modifiedPath, err.Error())
log.Printf("[DEBUG] WARNING: %s", fErr.Error())
return fErr
}
req.Header.Add("Accept", "application/json")
if reqContentLength != nil {
req.ContentLength = *reqContentLength
}
if reqBodyType != "" {
req.Header.Add("Content-Type", reqBodyType)
}
err = c.AuthenticateRequest(req)
if err != nil {
log.Printf("[DEBUG] WARNING: %s", err.Error())
return err
}
res, err := c.httpClient.Do(req)
if err != nil {
fErr := fmt.Errorf("Failed to perform HTTP %s request (path: %s) - Reason: %s", method, modifiedPath, err.Error())
log.Printf("[DEBUG] WARNING: %s", fErr.Error())
return fErr
}
defer res.Body.Close()
err = c.ValidateResponseCode(res)
if err != nil {
log.Printf("[DEBUG] WARNING: %s", err.Error())
return err
}
if responseBody != nil {
err = json.NewDecoder(res.Body).Decode(responseBody)
if err != nil {
fErr := fmt.Errorf("Failed to decode HTTP %s response (path: %s) - Reason: %s", method, modifiedPath, err.Error())
log.Printf("[DEBUG] WARNING: %s", fErr.Error())
return fErr
}
} else {
data, _ := ioutil.ReadAll(res.Body)
log.Printf("[DEBUG] WARNING: Unhandled HTTP response body: %s", string(data))
}
return nil
}
// ValidateResponseCode ensures that a response is valid.
func (c *VirtualEnvironmentClient) ValidateResponseCode(res *http.Response) error {
if res.StatusCode < 200 || res.StatusCode >= 300 {
status := strings.TrimPrefix(res.Status, fmt.Sprintf("%d ", res.StatusCode))
errRes := &VirtualEnvironmentErrorResponseBody{}
err := json.NewDecoder(res.Body).Decode(errRes)
if err == nil && errRes.Errors != nil {
errList := []string{}
for k, v := range *errRes.Errors {
errList = append(errList, fmt.Sprintf("%s: %s", k, strings.TrimRight(v, "\n\r")))
}
status = fmt.Sprintf("%s (%s)", status, strings.Join(errList, " - "))
}
return fmt.Errorf("Received an HTTP %d response - Reason: %s", res.StatusCode, status)
}
return nil
}