forked from Azure/azure-sdk-for-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
311 lines (247 loc) · 7 KB
/
common.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package azureSdkForGo
import (
"bytes"
"crypto/rand"
"encoding/xml"
"errors"
"fmt"
"github.com/MSOpenTech/azure-sdk-for-go/core/http"
"github.com/MSOpenTech/azure-sdk-for-go/core/tls"
"io"
"os/exec"
"strings"
"time"
)
const (
paramNotSpecifiedError = "Parameter %s is not specified."
azureManagementDnsName = "https://management.core.windows.net"
msVersionHeader = "x-ms-version"
msVersionHeaderValue = "2014-05-01"
contentHeader = "Content-Type"
defaultContentHeaderValue = "application/xml"
requestIdHeader = "X-Ms-Request-Id"
)
//Region public methods starts
func SendAzureGetRequest(url string) ([]byte, error) {
if len(url) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "url")
}
response, err := SendAzureRequest(url, "GET", "", nil)
if err != nil {
return nil, err
}
responseContent := getResponseBody(response)
return responseContent, nil
}
func SendAzurePostRequest(url string, data []byte) (string, error) {
if len(url) == 0 {
return "", fmt.Errorf(paramNotSpecifiedError, "url")
}
response, err := SendAzureRequest(url, "POST", "", data)
if err != nil {
return "", err
}
requestId := response.Header[requestIdHeader]
return requestId[0], nil
}
func SendAzurePutRequest(url string, contentType string, data []byte) (string, error) {
if len(url) == 0 {
return "", fmt.Errorf(paramNotSpecifiedError, contentType, "url")
}
response, err := SendAzureRequest(url, "PUT", contentType, data)
if err != nil {
return "", err
}
requestId := response.Header[requestIdHeader]
return requestId[0], nil
}
func SendAzureDeleteRequest(url string) (string, error) {
if len(url) == 0 {
return "", fmt.Errorf(paramNotSpecifiedError, "url")
}
response, err := SendAzureRequest(url, "DELETE", "", nil)
if err != nil {
return "", err
}
requestId := response.Header[requestIdHeader]
return requestId[0], nil
}
func SendAzureRequest(url string, requestType string, contentType string, data []byte) (*http.Response, error) {
if len(url) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "url")
}
if len(requestType) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "requestType")
}
client := createHttpClient()
response, err := sendRequest(client, url, requestType, contentType, data, 7)
if err != nil {
return nil, err
}
return response, nil
}
func ExecuteCommand(command string, input []byte) ([]byte, error) {
if len(command) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "command")
}
parts := strings.Fields(command)
head := parts[0]
parts = parts[1:len(parts)]
cmd := exec.Command(head, parts...)
if input != nil {
cmd.Stdin = bytes.NewReader(input)
}
out, err := cmd.Output()
if err != nil {
return nil, err
}
return out, nil
}
func GetOperationStatus(operationId string) (*Operation, error) {
if len(operationId) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "operationId")
}
operation := new(Operation)
url := "operations/" + operationId
response, azureErr := SendAzureGetRequest(url)
if azureErr != nil {
return nil, azureErr
}
err := xml.Unmarshal(response, operation)
if err != nil {
return nil, err
}
return operation, nil
}
func WaitAsyncOperation(operationId string) error {
if len(operationId) == 0 {
return fmt.Errorf(paramNotSpecifiedError, "operationId")
}
status := "InProgress"
operation := new(Operation)
err := errors.New("")
for status == "InProgress" {
time.Sleep(2000 * time.Millisecond)
operation, err = GetOperationStatus(operationId)
if err != nil {
return err
}
status = operation.Status
}
if status == "Failed" {
return errors.New(operation.Error.Message)
}
return nil
}
func CheckStringParams(url string) ([]byte, error) {
if len(url) == 0 {
return nil, fmt.Errorf(paramNotSpecifiedError, "url")
}
response, err := SendAzureRequest(url, "GET", "", nil)
if err != nil {
return nil, err
}
responseContent := getResponseBody(response)
return responseContent, nil
}
// NewUUID generates a random UUID according to RFC 4122
func NewUUID() (string, error) {
uuid := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, uuid)
if n != len(uuid) || err != nil {
return "", err
}
// variant bits; see section 4.1.1
uuid[8] = uuid[8]&^0xc0 | 0x80
// version 4 (pseudo-random); see section 4.1.3
uuid[6] = uuid[6]&^0xf0 | 0x40
//return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
return fmt.Sprintf("%x", uuid[10:]), nil
}
//Region public methods ends
//Region private methods starts
func sendRequest(client *http.Client, url string, requestType string, contentType string, data []byte, numberOfRetries int) (*http.Response, error) {
request, reqErr := createAzureRequest(url, requestType, contentType, data)
if reqErr != nil {
return nil, reqErr
}
response, err := client.Do(request)
if err != nil {
if numberOfRetries == 0 {
return nil, err
}
return sendRequest(client, url, requestType, contentType, data, numberOfRetries-1)
}
if response.StatusCode > 299 {
responseContent := getResponseBody(response)
azureErr := getAzureError(responseContent)
if azureErr != nil {
if numberOfRetries == 0 {
return nil, azureErr
}
return sendRequest(client, url, requestType, contentType, data, numberOfRetries-1)
}
}
return response, nil
}
func getAzureError(responseBody []byte) error {
error := new(AzureError)
err := xml.Unmarshal(responseBody, error)
if err != nil {
return err
}
return error
}
func createAzureRequest(url string, requestType string, contentType string, data []byte) (*http.Request, error) {
var request *http.Request
var err error
url = fmt.Sprintf("%s/%s/%s", azureManagementDnsName, GetPublishSettings().SubscriptionID, url)
if data != nil {
body := bytes.NewBuffer(data)
request, err = http.NewRequest(requestType, url, body)
} else {
request, err = http.NewRequest(requestType, url, nil)
}
if err != nil {
return nil, err
}
request.Header.Add(msVersionHeader, msVersionHeaderValue)
if len(contentType) > 0 {
request.Header.Add(contentHeader, contentType)
} else {
request.Header.Add(contentHeader, defaultContentHeaderValue)
}
return request, nil
}
func createHttpClient() *http.Client {
cert, _ := tls.X509KeyPair(GetPublishSettings().SubscriptionCert, GetPublishSettings().SubscriptionKey)
ssl := &tls.Config{}
ssl.Certificates = []tls.Certificate{cert}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: ssl,
},
}
return client
}
func getResponseBody(response *http.Response) []byte {
responseBody := make([]byte, response.ContentLength)
io.ReadFull(response.Body, responseBody)
return responseBody
}
//Region private methods ends
type AzureError struct {
XMLName xml.Name `xml:"Error"`
Code string
Message string
}
func (e *AzureError) Error() string {
return fmt.Sprintf("Code: %s, Message: %s", e.Code, e.Message)
}
type Operation struct {
XMLName xml.Name `xml:"Operation"`
ID string
Status string
HttpStatusCode string
Error AzureError
}