File: client.go

package info (click to toggle)
golang-github-denverdino-aliyungo 0.0~git20180921.13fa8aa-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,824 kB
  • sloc: xml: 1,359; makefile: 3
file content (550 lines) | stat: -rw-r--r-- 14,735 bytes parent folder | download | duplicates (3)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package common

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/denverdino/aliyungo/util"
)

// RemovalPolicy.N add index to array item
// RemovalPolicy=["a", "b"] => RemovalPolicy.1="a" RemovalPolicy.2="b"
type FlattenArray []string

// string contains underline which will be replaced with dot
// SystemDisk_Category => SystemDisk.Category
type UnderlineString string

// A Client represents a client of ECS services
type Client struct {
	AccessKeyId     string //Access Key Id
	AccessKeySecret string //Access Key Secret
	securityToken   string
	debug           bool
	httpClient      *http.Client
	endpoint        string
	version         string
	serviceCode     string
	regionID        Region
	businessInfo    string
	userAgent       string
}

// Initialize properties of a client instance
func (client *Client) Init(endpoint, version, accessKeyId, accessKeySecret string) {
	client.AccessKeyId = accessKeyId
	ak := accessKeySecret
	if !strings.HasSuffix(ak, "&") {
		ak += "&"
	}
	client.AccessKeySecret = ak
	client.debug = false
	handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout"))
	if err != nil {
		handshakeTimeout = 0
	}
	if handshakeTimeout == 0 {
		client.httpClient = &http.Client{}
	} else {
		t := &http.Transport{
			TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second}
		client.httpClient = &http.Client{Transport: t}
	}
	client.endpoint = endpoint
	client.version = version
}

// Initialize properties of a client instance including regionID
func (client *Client) NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region) {
	client.Init(endpoint, version, accessKeyId, accessKeySecret)
	client.serviceCode = serviceCode
	client.regionID = regionID
}

// Intialize client object when all properties are ready
func (client *Client) InitClient() *Client {
	client.debug = false
	handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout"))
	if err != nil {
		handshakeTimeout = 0
	}
	if handshakeTimeout == 0 {
		client.httpClient = &http.Client{}
	} else {
		t := &http.Transport{
			TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second}
		client.httpClient = &http.Client{Transport: t}
	}
	return client
}

func (client *Client) NewInitForAssumeRole(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region, securityToken string) {
	client.NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode, regionID)
	client.securityToken = securityToken
}

//getLocationEndpoint
func (client *Client) getEndpointByLocation() string {
	locationClient := NewLocationClient(client.AccessKeyId, client.AccessKeySecret, client.securityToken)
	locationClient.SetDebug(true)
	return locationClient.DescribeOpenAPIEndpoint(client.regionID, client.serviceCode)
}

//NewClient using location service
func (client *Client) setEndpointByLocation(region Region, serviceCode, accessKeyId, accessKeySecret, securityToken string) {
	locationClient := NewLocationClient(accessKeyId, accessKeySecret, securityToken)
	locationClient.SetDebug(true)
	ep := locationClient.DescribeOpenAPIEndpoint(region, serviceCode)
	if ep == "" {
		ep = loadEndpointFromFile(region, serviceCode)
	}

	if ep != "" {
		client.endpoint = ep
	}
}

// Ensure all necessary properties are valid
func (client *Client) ensureProperties() error {
	var msg string

	if client.endpoint == "" {
		msg = fmt.Sprintf("endpoint cannot be empty!")
	} else if client.version == "" {
		msg = fmt.Sprintf("version cannot be empty!")
	} else if client.AccessKeyId == "" {
		msg = fmt.Sprintf("AccessKeyId cannot be empty!")
	} else if client.AccessKeySecret == "" {
		msg = fmt.Sprintf("AccessKeySecret cannot be empty!")
	}

	if msg != "" {
		return errors.New(msg)
	}

	return nil
}

// ----------------------------------------------------
// WithXXX methods
// ----------------------------------------------------

// WithEndpoint sets custom endpoint
func (client *Client) WithEndpoint(endpoint string) *Client {
	client.SetEndpoint(endpoint)
	return client
}

// WithVersion sets custom version
func (client *Client) WithVersion(version string) *Client {
	client.SetVersion(version)
	return client
}

// WithRegionID sets Region ID
func (client *Client) WithRegionID(regionID Region) *Client {
	client.SetRegionID(regionID)
	return client
}

//WithServiceCode sets serviceCode
func (client *Client) WithServiceCode(serviceCode string) *Client {
	client.SetServiceCode(serviceCode)
	return client
}

// WithAccessKeyId sets new AccessKeyId
func (client *Client) WithAccessKeyId(id string) *Client {
	client.SetAccessKeyId(id)
	return client
}

// WithAccessKeySecret sets new AccessKeySecret
func (client *Client) WithAccessKeySecret(secret string) *Client {
	client.SetAccessKeySecret(secret)
	return client
}

// WithSecurityToken sets securityToken
func (client *Client) WithSecurityToken(securityToken string) *Client {
	client.SetSecurityToken(securityToken)
	return client
}

// WithDebug sets debug mode to log the request/response message
func (client *Client) WithDebug(debug bool) *Client {
	client.SetDebug(debug)
	return client
}

// WithBusinessInfo sets business info to log the request/response message
func (client *Client) WithBusinessInfo(businessInfo string) *Client {
	client.SetBusinessInfo(businessInfo)
	return client
}

// WithUserAgent sets user agent to the request/response message
func (client *Client) WithUserAgent(userAgent string) *Client {
	client.SetUserAgent(userAgent)
	return client
}

// ----------------------------------------------------
// SetXXX methods
// ----------------------------------------------------

// SetEndpoint sets custom endpoint
func (client *Client) SetEndpoint(endpoint string) {
	client.endpoint = endpoint
}

// SetEndpoint sets custom version
func (client *Client) SetVersion(version string) {
	client.version = version
}

// SetEndpoint sets Region ID
func (client *Client) SetRegionID(regionID Region) {
	client.regionID = regionID
}

//SetServiceCode sets serviceCode
func (client *Client) SetServiceCode(serviceCode string) {
	client.serviceCode = serviceCode
}

// SetAccessKeyId sets new AccessKeyId
func (client *Client) SetAccessKeyId(id string) {
	client.AccessKeyId = id
}

// SetAccessKeySecret sets new AccessKeySecret
func (client *Client) SetAccessKeySecret(secret string) {
	client.AccessKeySecret = secret + "&"
}

// SetDebug sets debug mode to log the request/response message
func (client *Client) SetDebug(debug bool) {
	client.debug = debug
}

// SetBusinessInfo sets business info to log the request/response message
func (client *Client) SetBusinessInfo(businessInfo string) {
	if strings.HasPrefix(businessInfo, "/") {
		client.businessInfo = businessInfo
	} else if businessInfo != "" {
		client.businessInfo = "/" + businessInfo
	}
}

// SetUserAgent sets user agent to the request/response message
func (client *Client) SetUserAgent(userAgent string) {
	client.userAgent = userAgent
}

//set SecurityToken
func (client *Client) SetSecurityToken(securityToken string) {
	client.securityToken = securityToken
}

func (client *Client) initEndpoint() error {
	// if set any value to "CUSTOMIZED_ENDPOINT" could skip location service.
	// example: export CUSTOMIZED_ENDPOINT=true
	if os.Getenv("CUSTOMIZED_ENDPOINT") != "" {
		return nil
	}

	if client.serviceCode != "" && client.regionID != "" {
		endpoint := client.getEndpointByLocation()
		if endpoint == "" {
			return GetCustomError("InvalidEndpoint", "endpoint is empty,pls check")
		}
		client.endpoint = endpoint
	}
	return nil
}

// Invoke sends the raw HTTP request for ECS services
func (client *Client) Invoke(action string, args interface{}, response interface{}) error {
	if err := client.ensureProperties(); err != nil {
		return err
	}

	//init endpoint
	if err := client.initEndpoint(); err != nil {
		return err
	}

	request := Request{}
	request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)

	query := util.ConvertToQueryValues(request)
	util.SetQueryValues(args, &query)

	// Sign request
	signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret)

	// Generate the request URL
	requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature)

	httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil)

	if err != nil {
		return GetClientError(err)
	}

	// TODO move to util and add build val flag
	httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)

	httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent)

	t0 := time.Now()
	httpResp, err := client.httpClient.Do(httpReq)
	t1 := time.Now()
	if err != nil {
		return GetClientError(err)
	}
	statusCode := httpResp.StatusCode

	if client.debug {
		log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0))
	}

	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)

	if err != nil {
		return GetClientError(err)
	}

	if client.debug {
		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, body, "", "    ")
		log.Println(string(prettyJSON.Bytes()))
	}

	if statusCode >= 400 && statusCode <= 599 {
		errorResponse := ErrorResponse{}
		err = json.Unmarshal(body, &errorResponse)
		ecsError := &Error{
			ErrorResponse: errorResponse,
			StatusCode:    statusCode,
		}
		return ecsError
	}

	err = json.Unmarshal(body, response)
	//log.Printf("%++v", response)
	if err != nil {
		return GetClientError(err)
	}

	return nil
}

// Invoke sends the raw HTTP request for ECS services
func (client *Client) InvokeByFlattenMethod(action string, args interface{}, response interface{}) error {
	if err := client.ensureProperties(); err != nil {
		return err
	}

	//init endpoint
	if err := client.initEndpoint(); err != nil {
		return err
	}

	request := Request{}
	request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)

	query := util.ConvertToQueryValues(request)

	util.SetQueryValueByFlattenMethod(args, &query)

	// Sign request
	signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret)

	// Generate the request URL
	requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature)

	httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil)

	if err != nil {
		return GetClientError(err)
	}

	// TODO move to util and add build val flag
	httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)

	httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent)

	t0 := time.Now()
	httpResp, err := client.httpClient.Do(httpReq)
	t1 := time.Now()
	if err != nil {
		return GetClientError(err)
	}
	statusCode := httpResp.StatusCode

	if client.debug {
		log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0))
	}

	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)

	if err != nil {
		return GetClientError(err)
	}

	if client.debug {
		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, body, "", "    ")
		log.Println(string(prettyJSON.Bytes()))
	}

	if statusCode >= 400 && statusCode <= 599 {
		errorResponse := ErrorResponse{}
		err = json.Unmarshal(body, &errorResponse)
		ecsError := &Error{
			ErrorResponse: errorResponse,
			StatusCode:    statusCode,
		}
		return ecsError
	}

	err = json.Unmarshal(body, response)
	//log.Printf("%++v", response)
	if err != nil {
		return GetClientError(err)
	}

	return nil
}

// Invoke sends the raw HTTP request for ECS services
//改进了一下上面那个方法,可以使用各种Http方法
//2017.1.30 增加了一个path参数,用来拓展访问的地址
func (client *Client) InvokeByAnyMethod(method, action, path string, args interface{}, response interface{}) error {
	if err := client.ensureProperties(); err != nil {
		return err
	}

	//init endpoint
	if err := client.initEndpoint(); err != nil {
		return err
	}

	request := Request{}
	request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID)
	data := util.ConvertToQueryValues(request)
	util.SetQueryValues(args, &data)

	// Sign request
	signature := util.CreateSignatureForRequest(method, &data, client.AccessKeySecret)

	data.Add("Signature", signature)
	// Generate the request URL
	var (
		httpReq *http.Request
		err     error
	)
	if method == http.MethodGet {
		requestURL := client.endpoint + path + "?" + data.Encode()
		//fmt.Println(requestURL)
		httpReq, err = http.NewRequest(method, requestURL, nil)
	} else {
		//fmt.Println(client.endpoint + path)
		httpReq, err = http.NewRequest(method, client.endpoint+path, strings.NewReader(data.Encode()))
		httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}

	if err != nil {
		return GetClientError(err)
	}

	// TODO move to util and add build val flag
	httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo)
	httpReq.Header.Set("User-Agent", httpReq.Header.Get("User-Agent")+" "+client.userAgent)

	t0 := time.Now()
	httpResp, err := client.httpClient.Do(httpReq)
	t1 := time.Now()
	if err != nil {
		return GetClientError(err)
	}
	statusCode := httpResp.StatusCode

	if client.debug {
		log.Printf("Invoke %s %s %d (%v) %v", ECSRequestMethod, client.endpoint, statusCode, t1.Sub(t0), data.Encode())
	}

	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)

	if err != nil {
		return GetClientError(err)
	}

	if client.debug {
		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, body, "", "    ")
		log.Println(string(prettyJSON.Bytes()))
	}

	if statusCode >= 400 && statusCode <= 599 {
		errorResponse := ErrorResponse{}
		err = json.Unmarshal(body, &errorResponse)
		ecsError := &Error{
			ErrorResponse: errorResponse,
			StatusCode:    statusCode,
		}
		return ecsError
	}

	err = json.Unmarshal(body, response)
	//log.Printf("%++v", response)
	if err != nil {
		return GetClientError(err)
	}

	return nil
}

// GenerateClientToken generates the Client Token with random string
func (client *Client) GenerateClientToken() string {
	return util.CreateRandomString()
}

func GetClientErrorFromString(str string) error {
	return &Error{
		ErrorResponse: ErrorResponse{
			Code:    "AliyunGoClientFailure",
			Message: str,
		},
		StatusCode: -1,
	}
}

func GetClientError(err error) error {
	return GetClientErrorFromString(err.Error())
}

func GetCustomError(code, message string) error {
	return &Error{
		ErrorResponse: ErrorResponse{
			Code:    code,
			Message: message,
		},
		StatusCode: 400,
	}
}