/
aws_request.go
252 lines (224 loc) · 6.56 KB
/
aws_request.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
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package aws
import (
"encoding/xml"
"io"
"io/ioutil"
"net/url"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/query"
xj "github.com/basgys/goxml2json"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/cloudmux/pkg/cloudprovider"
)
var UnmarshalHandler = request.NamedHandler{Name: "yunion.query.Unmarshal", Fn: Unmarshal}
func Unmarshal(r *request.Request) {
defer r.HTTPResponse.Body.Close()
if r.DataFilled() {
var decoder *xml.Decoder
if DEBUG {
body, err := ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New("ioutil.ReadAll", "read response body", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
return
}
log.Debugf("response: \n%s", string(body))
decoder = xml.NewDecoder(strings.NewReader(string(body)))
} else {
decoder = xml.NewDecoder(r.HTTPResponse.Body)
}
if r.ClientInfo.ServiceID == EC2_SERVICE_ID {
err := decoder.Decode(r.Data)
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New("SerializationError", "failed decoding EC2 Query response", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
}
return
}
for {
tok, err := decoder.Token()
if err != nil {
if err == io.EOF {
break
}
r.Error = awserr.NewRequestFailure(
awserr.New("decoder.Token()", "get token", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
return
}
if tok == nil {
break
}
switch typed := tok.(type) {
case xml.CharData:
continue
case xml.StartElement:
if typed.Name.Local == r.Operation.Name+"Result" {
err = decoder.DecodeElement(r.Data, &typed)
if err != nil {
r.Error = awserr.NewRequestFailure(
awserr.New("DecodeElement", "failed decoding Query response", err),
r.HTTPResponse.StatusCode,
r.RequestID,
)
}
return
}
case xml.EndElement:
break
}
}
}
}
var buildHandler = request.NamedHandler{Name: "yunion.query.Build", Fn: Build}
func Build(r *request.Request) {
body := url.Values{
"Action": {r.Operation.Name},
"Version": {r.ClientInfo.APIVersion},
}
if r.Params != nil {
if params, ok := r.Params.(map[string]string); ok {
for k, v := range params {
body.Add(k, v)
}
}
}
if DEBUG {
log.Debugf("params: %s", body.Encode())
}
if !r.IsPresigned() {
r.HTTPRequest.Method = "POST"
r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
r.SetBufferBody([]byte(body.Encode()))
} else { // This is a pre-signed request
r.HTTPRequest.Method = "GET"
r.HTTPRequest.URL.RawQuery = body.Encode()
}
}
var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.ec2query.UnmarshalError", Fn: UnmarshalError}
type sAwsError struct {
Errors struct {
Type string
Code string
Message string
} `json:"Error"`
RequestID string
}
func (self sAwsError) Error() string {
return jsonutils.Marshal(self).String()
}
func UnmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close()
result, err := xj.Convert(r.HTTPResponse.Body)
if err != nil {
r.Error = errors.Wrapf(err, "xj.Convert")
return
}
obj, err := jsonutils.Parse([]byte(result.String()))
if err != nil {
r.Error = errors.Wrapf(err, "jsonutils.Parse")
return
}
respErr := &sAwsError{}
if obj.Contains("ErrorResponse") {
err = obj.Unmarshal(respErr, "ErrorResponse")
if err != nil {
r.Error = errors.Wrapf(err, "obj.Unmarshal")
return
}
} else if obj.Contains("Response", "Errors") {
err = obj.Unmarshal(respErr, "Response", "Errors")
if err != nil {
r.Error = errors.Wrapf(err, "obj.Unmarshal")
return
}
}
if strings.Contains(respErr.Errors.Code, "NotFound") || respErr.Errors.Code == "NoSuchEntity" {
r.Error = errors.Wrapf(cloudprovider.ErrNotFound, jsonutils.Marshal(respErr).String())
return
}
r.Error = respErr
return
}
func (self *SAwsClient) request(regionId, serviceName, serviceId, apiVersion string, apiName string, params map[string]string, retval interface{}, assumeRole bool) error {
if len(regionId) == 0 {
regionId = self.getDefaultRegionId()
}
session, err := self.getAwsSession(regionId, assumeRole)
if err != nil {
return err
}
c := session.ClientConfig(serviceName)
metadata := metadata.ClientInfo{
ServiceName: serviceName,
ServiceID: serviceId,
SigningName: c.SigningName,
SigningRegion: c.SigningRegion,
Endpoint: c.Endpoint,
APIVersion: apiVersion,
}
if self.debug {
logLevel := aws.LogLevelType(uint(aws.LogDebugWithRequestErrors) + uint(aws.LogDebugWithHTTPBody))
c.Config.LogLevel = &logLevel
}
client := client.New(*c.Config, metadata, c.Handlers)
client.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
client.Handlers.Build.PushBackNamed(buildHandler)
client.Handlers.Unmarshal.PushBackNamed(UnmarshalHandler)
client.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler)
client.Handlers.UnmarshalError.PushBackNamed(UnmarshalErrorHandler)
client.Handlers.Validate.Remove(corehandlers.ValidateEndpointHandler)
return jsonRequest(client, apiName, params, retval, true)
}
func jsonRequest(cli *client.Client, apiName string, params map[string]string, retval interface{}, debug bool) error {
op := &request.Operation{
Name: apiName,
HTTPMethod: "POST",
HTTPPath: "/",
Paginator: &request.Paginator{
InputTokens: []string{"NextToken"},
OutputTokens: []string{"NextToken"},
LimitToken: "MaxResults",
TruncationToken: "",
},
}
req := cli.NewRequest(op, params, retval)
err := req.Send()
if err != nil {
if e, ok := err.(awserr.RequestFailure); ok && e.StatusCode() == 404 {
return cloudprovider.ErrNotFound
}
return err
}
return nil
}