forked from yunionio/cloudmux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
203 lines (173 loc) · 4.99 KB
/
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
202
203
// 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 ucloud
import (
"context"
"crypto/sha1"
"fmt"
"strings"
"time"
"github.com/nyl1001/pkg/errors"
"github.com/nyl1001/pkg/util/httputils"
"github.com/nyl1001/pkg/jsonutils"
"yunion.io/x/log"
"github.com/nyl1001/cloudmux/pkg/cloudprovider"
)
const UCLOUD_API_HOST = "https://api.ucloud.cn"
// API返回结果对应的字段名
var UCLOUD_API_RESULT_KEYS = map[string]string{
"AllocateEIP": "EIPSet",
"GetProjectList": "ProjectSet",
"GetRegion": "Regions",
"DescribeVPC": "DataSet",
"DescribeImage": "ImageSet",
"DescribeIsolationGroup": "IsolationGroupSet",
"DescribeUHostInstance": "UHostSet",
"DescribeUHostTags": "TagSet",
"DescribeUDSet": "UDSet",
"DescribeUDisk": "DataSet",
"DescribeUDiskSnapshot": "DataSet",
"DescribeEIP": "EIPSet",
"DescribeFirewall": "DataSet",
"DescribeSubnet": "DataSet",
"DescribeBucket": "DataSet",
"CreateUDisk": "UDiskId",
"CreateVPC": "VPCId",
"CreateUDiskSnapshot": "SnapshotId",
"DescribeVIP": "VIPSet",
}
type SParams struct {
data jsonutils.JSONDict
}
type SUcloudError struct {
Action string `json:"Action"`
Message string `json:"Message"`
RetCode int64 `json:"RetCode"`
}
func (self *SUcloudError) Error() string {
return fmt.Sprintf("Do %s failed, code: %d, %s", self.Action, self.RetCode, self.Message)
}
func NewUcloudParams() SParams {
data := jsonutils.NewDict()
return SParams{data: *data}
}
func (self *SParams) Set(key string, value interface{}) {
switch v := value.(type) {
case string:
self.data.Set(key, jsonutils.NewString(v))
case int64:
self.data.Set(key, jsonutils.NewInt(v))
case int:
self.data.Set(key, jsonutils.NewInt(int64(v)))
case bool:
self.data.Set(key, jsonutils.NewBool(v))
case float64:
self.data.Set(key, jsonutils.NewFloat64(v))
case float32:
self.data.Set(key, jsonutils.NewFloat32(v))
case []string:
self.data.Set(key, jsonutils.NewStringArray(v))
default:
log.Debugf("unsuported params type %T", value)
}
}
func (self *SParams) SetAction(action string) {
self.data.Set("Action", jsonutils.NewString(action))
}
func (self *SParams) SetPagination(limit, offset int) {
if limit == 0 {
limit = 20
}
self.data.Set("Limit", jsonutils.NewInt(int64(limit)))
self.data.Set("Offset", jsonutils.NewInt(int64(offset)))
}
func (self *SParams) String() string {
return self.data.String()
}
func (self *SParams) PrettyString() string {
return self.data.PrettyString()
}
func (self *SParams) GetParams() jsonutils.JSONDict {
return self.data
}
// https://docs.ucloud.cn/api/summary/signature
func BuildParams(params SParams, privateKey string) jsonutils.JSONObject {
data := params.GetParams()
// remove old Signature
data.Remove("Signature")
// 排序并计算signture
keys := data.SortedKeys()
lst := []string{}
for _, k := range keys {
lst = append(lst, k)
v, _ := data.GetString(k)
lst = append(lst, v)
}
raw := strings.Join(lst, "") + privateKey
signture := fmt.Sprintf("%x", sha1.Sum([]byte(raw)))
data.Set("Signature", jsonutils.NewString(signture))
return &data
}
func GetSignature(params SParams, privateKey string) string {
sign, _ := BuildParams(params, privateKey).GetString("Signature")
return sign
}
func parseUcloudResponse(params SParams, resp jsonutils.JSONObject) (jsonutils.JSONObject, error) {
err := &SUcloudError{}
e := resp.Unmarshal(err)
if e != nil {
return nil, e
}
err.Action, _ = params.data.GetString("Action")
if err.RetCode > 0 {
if err.RetCode == 171 {
return nil, errors.Wrapf(cloudprovider.ErrInvalidAccessKey, err.Error())
}
return nil, err
}
return resp, nil
}
func jsonRequest(client *SUcloudClient, params SParams) (jsonutils.JSONObject, error) {
ctx := context.Background()
MAX_RETRY := 3
retry := 0
var err error
var resp jsonutils.JSONObject
for retry < MAX_RETRY {
_, resp, err = httputils.JSONRequest(
client.httpClient,
ctx,
httputils.POST,
UCLOUD_API_HOST,
nil,
BuildParams(params, client.accessKeySecret),
client.debug)
if err == nil {
return parseUcloudResponse(params, resp)
}
switch e := err.(type) {
case *httputils.JSONClientError:
if e.Code >= 499 && !strings.Contains(err.Error(), cloudprovider.ErrAccountReadOnly.Error()) {
time.Sleep(3 * time.Second)
retry += 1
continue
} else {
return nil, err
}
default:
return nil, err
}
}
return resp, err
}