-
Notifications
You must be signed in to change notification settings - Fork 0
/
swift.go
2188 lines (2062 loc) · 67 KB
/
swift.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
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package swift
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"sync"
"time"
)
const (
DefaultUserAgent = "goswift/1.0" // Default user agent
DefaultRetries = 3 // Default number of retries on token expiry
TimeFormat = "2006-01-02T15:04:05" // Python date format for json replies parsed as UTC
UploadTar = "tar" // Data format specifier for Connection.BulkUpload().
UploadTarGzip = "tar.gz" // Data format specifier for Connection.BulkUpload().
UploadTarBzip2 = "tar.bz2" // Data format specifier for Connection.BulkUpload().
allContainersLimit = 10000 // Number of containers to fetch at once
allObjectsLimit = 10000 // Number objects to fetch at once
allObjectsChanLimit = 1000 // ...when fetching to a channel
)
// ObjectType is the type of the swift object, regular, static large,
// or dynamic large.
type ObjectType int
// Values that ObjectType can take
const (
RegularObjectType ObjectType = iota
StaticLargeObjectType
DynamicLargeObjectType
)
// Connection holds the details of the connection to the swift server.
//
// You need to provide UserName, ApiKey and AuthUrl when you create a
// connection then call Authenticate on it.
//
// The auth version in use will be detected from the AuthURL - you can
// override this with the AuthVersion parameter.
//
// If using v2 auth you can also set Region in the Connection
// structure. If you don't set Region you will get the default region
// which may not be what you want.
//
// For reference some common AuthUrls looks like this:
//
// Rackspace US https://auth.api.rackspacecloud.com/v1.0
// Rackspace UK https://lon.auth.api.rackspacecloud.com/v1.0
// Rackspace v2 https://identity.api.rackspacecloud.com/v2.0
// Memset Memstore UK https://auth.storage.memset.com/v1.0
// Memstore v2 https://auth.storage.memset.com/v2.0
//
// When using Google Appengine you must provide the Connection with an
// appengine-specific Transport:
//
// import (
// "appengine/urlfetch"
// "fmt"
// "github.com/ncw/swift"
// )
//
// func handler(w http.ResponseWriter, r *http.Request) {
// ctx := appengine.NewContext(r)
// tr := urlfetch.Transport{Context: ctx}
// c := swift.Connection{
// UserName: "user",
// ApiKey: "key",
// AuthUrl: "auth_url",
// Transport: tr,
// }
// _ := c.Authenticate()
// containers, _ := c.ContainerNames(nil)
// fmt.Fprintf(w, "containers: %q", containers)
// }
//
// If you don't supply a Transport, one is made which relies on
// http.ProxyFromEnvironment (http://golang.org/pkg/net/http/#ProxyFromEnvironment).
// This means that the connection will respect the HTTP proxy specified by the
// environment variables $HTTP_PROXY and $NO_PROXY.
type Connection struct {
// Parameters - fill these in before calling Authenticate
// They are all optional except UserName, ApiKey and AuthUrl
Domain string // User's domain name
DomainId string // User's domain Id
UserName string // UserName for api
UserId string // User Id
ApiKey string // Key for api access
AuthUrl string // Auth URL
Retries int // Retries on error (default is 3)
UserAgent string // Http User agent (default goswift/1.0)
ConnectTimeout time.Duration // Connect channel timeout (default 10s)
Timeout time.Duration // Data channel timeout (default 60s)
Region string // Region to use eg "LON", "ORD" - default is use first region (v2,v3 auth only)
AuthVersion int // Set to 1, 2 or 3 or leave at 0 for autodetect
Internal bool // Set this to true to use the the internal / service network
Tenant string // Name of the tenant (v2,v3 auth only)
TenantId string // Id of the tenant (v2,v3 auth only)
EndpointType EndpointType // Endpoint type (v2,v3 auth only) (default is public URL unless Internal is set)
TenantDomain string // Name of the tenant's domain (v3 auth only), only needed if it differs from the user domain
TenantDomainId string // Id of the tenant's domain (v3 auth only), only needed if it differs the from user domain
TrustId string // Id of the trust (v3 auth only)
Transport http.RoundTripper `json:"-" xml:"-"` // Optional specialised http.Transport (eg. for Google Appengine)
// These are filled in after Authenticate is called as are the defaults for above
StorageUrl string
AuthToken string
client *http.Client
Auth Authenticator `json:"-" xml:"-"` // the current authenticator
authLock sync.Mutex // lock when R/W StorageUrl, AuthToken, Auth
// swiftInfo is filled after QueryInfo is called
swiftInfo SwiftInfo
}
// setFromEnv reads the value that param points to (it must be a
// pointer), if it isn't the zero value then it reads the environment
// variable name passed in, parses it according to the type and writes
// it to the pointer.
func setFromEnv(param interface{}, name string) (err error) {
val := os.Getenv(name)
if val == "" {
return
}
switch result := param.(type) {
case *string:
if *result == "" {
*result = val
}
case *int:
if *result == 0 {
*result, err = strconv.Atoi(val)
}
case *bool:
if *result == false {
*result, err = strconv.ParseBool(val)
}
case *time.Duration:
if *result == 0 {
*result, err = time.ParseDuration(val)
}
case *EndpointType:
if *result == EndpointType("") {
*result = EndpointType(val)
}
default:
return newErrorf(0, "can't set var of type %T", param)
}
return err
}
// ApplyEnvironment reads environment variables and applies them to
// the Connection structure. It won't overwrite any parameters which
// are already set in the Connection struct.
//
// To make a new Connection object entirely from the environment you
// would do:
//
// c := new(Connection)
// err := c.ApplyEnvironment()
// if err != nil { log.Fatal(err) }
//
// The naming of these variables follows the official Openstack naming
// scheme so it should be compatible with OpenStack rc files.
//
// For v1 authentication (obsolete)
// ST_AUTH - Auth URL
// ST_USER - UserName for api
// ST_KEY - Key for api access
//
// For v2 authentication
// OS_AUTH_URL - Auth URL
// OS_USERNAME - UserName for api
// OS_PASSWORD - Key for api access
// OS_TENANT_NAME - Name of the tenant
// OS_TENANT_ID - Id of the tenant
// OS_REGION_NAME - Region to use - default is use first region
//
// For v3 authentication
// OS_AUTH_URL - Auth URL
// OS_USERNAME - UserName for api
// OS_USER_ID - User Id
// OS_PASSWORD - Key for api access
// OS_USER_DOMAIN_NAME - User's domain name
// OS_USER_DOMAIN_ID - User's domain Id
// OS_PROJECT_NAME - Name of the project
// OS_PROJECT_DOMAIN_NAME - Name of the tenant's domain, only needed if it differs from the user domain
// OS_PROJECT_DOMAIN_ID - Id of the tenant's domain, only needed if it differs the from user domain
// OS_TRUST_ID - If of the trust
// OS_REGION_NAME - Region to use - default is use first region
//
// Other
// OS_ENDPOINT_TYPE - Endpoint type public, internal or admin
// ST_AUTH_VERSION - Choose auth version - 1, 2 or 3 or leave at 0 for autodetect
//
// For manual authentication
// OS_STORAGE_URL - storage URL from alternate authentication
// OS_AUTH_TOKEN - Auth Token from alternate authentication
//
// Library specific
// GOSWIFT_RETRIES - Retries on error (default is 3)
// GOSWIFT_USER_AGENT - HTTP User agent (default goswift/1.0)
// GOSWIFT_CONNECT_TIMEOUT - Connect channel timeout with unit, eg "10s", "100ms" (default "10s")
// GOSWIFT_TIMEOUT - Data channel timeout with unit, eg "10s", "100ms" (default "60s")
// GOSWIFT_INTERNAL - Set this to "true" to use the the internal network (obsolete - use OS_ENDPOINT_TYPE)
func (c *Connection) ApplyEnvironment() (err error) {
for _, item := range []struct {
result interface{}
name string
}{
// Environment variables - keep in same order as Connection
{&c.Domain, "OS_USER_DOMAIN_NAME"},
{&c.DomainId, "OS_USER_DOMAIN_ID"},
{&c.UserName, "OS_USERNAME"},
{&c.UserId, "OS_USER_ID"},
{&c.ApiKey, "OS_PASSWORD"},
{&c.AuthUrl, "OS_AUTH_URL"},
{&c.Retries, "GOSWIFT_RETRIES"},
{&c.UserAgent, "GOSWIFT_USER_AGENT"},
{&c.ConnectTimeout, "GOSWIFT_CONNECT_TIMEOUT"},
{&c.Timeout, "GOSWIFT_TIMEOUT"},
{&c.Region, "OS_REGION_NAME"},
{&c.AuthVersion, "ST_AUTH_VERSION"},
{&c.Internal, "GOSWIFT_INTERNAL"},
{&c.Tenant, "OS_TENANT_NAME"}, //v2
{&c.Tenant, "OS_PROJECT_NAME"}, // v3
{&c.TenantId, "OS_TENANT_ID"},
{&c.EndpointType, "OS_ENDPOINT_TYPE"},
{&c.TenantDomain, "OS_PROJECT_DOMAIN_NAME"},
{&c.TenantDomainId, "OS_PROJECT_DOMAIN_ID"},
{&c.TrustId, "OS_TRUST_ID"},
{&c.StorageUrl, "OS_STORAGE_URL"},
{&c.AuthToken, "OS_AUTH_TOKEN"},
// v1 auth alternatives
{&c.ApiKey, "ST_KEY"},
{&c.UserName, "ST_USER"},
{&c.AuthUrl, "ST_AUTH"},
} {
err = setFromEnv(item.result, item.name)
if err != nil {
return newErrorf(0, "failed to read env var %q: %v", item.name, err)
}
}
return nil
}
// Error - all errors generated by this package are of this type. Other error
// may be passed on from library functions though.
type Error struct {
StatusCode int // HTTP status code if relevant or 0 if not
Text string
}
// Error satisfy the error interface.
func (e *Error) Error() string {
return e.Text
}
// newError make a new error from a string.
func newError(StatusCode int, Text string) *Error {
return &Error{
StatusCode: StatusCode,
Text: Text,
}
}
// newErrorf makes a new error from sprintf parameters.
func newErrorf(StatusCode int, Text string, Parameters ...interface{}) *Error {
return newError(StatusCode, fmt.Sprintf(Text, Parameters...))
}
// errorMap defines http error codes to error mappings.
type errorMap map[int]error
var (
// Specific Errors you might want to check for equality
NotModified = newError(304, "Not Modified")
BadRequest = newError(400, "Bad Request")
AuthorizationFailed = newError(401, "Authorization Failed")
ContainerNotFound = newError(404, "Container Not Found")
ContainerNotEmpty = newError(409, "Container Not Empty")
ObjectNotFound = newError(404, "Object Not Found")
ObjectCorrupted = newError(422, "Object Corrupted")
TimeoutError = newError(408, "Timeout when reading or writing data")
Forbidden = newError(403, "Operation forbidden")
TooLargeObject = newError(413, "Too Large Object")
// Mappings for authentication errors
authErrorMap = errorMap{
400: BadRequest,
401: AuthorizationFailed,
403: Forbidden,
}
// Mappings for container errors
ContainerErrorMap = errorMap{
400: BadRequest,
403: Forbidden,
404: ContainerNotFound,
409: ContainerNotEmpty,
}
// Mappings for object errors
objectErrorMap = errorMap{
304: NotModified,
400: BadRequest,
403: Forbidden,
404: ObjectNotFound,
413: TooLargeObject,
422: ObjectCorrupted,
}
)
// checkClose is used to check the return from Close in a defer
// statement.
func checkClose(c io.Closer, err *error) {
cerr := c.Close()
if *err == nil {
*err = cerr
}
}
// drainAndClose discards all data from rd and closes it.
// If an error occurs during Read, it is discarded.
func drainAndClose(rd io.ReadCloser, err *error) {
if rd == nil {
return
}
_, _ = io.Copy(ioutil.Discard, rd)
cerr := rd.Close()
if err != nil && *err == nil {
*err = cerr
}
}
// parseHeaders checks a response for errors and translates into
// standard errors if necessary. If an error is returned, resp.Body
// has been drained and closed.
func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error {
if errorMap != nil {
if err, ok := errorMap[resp.StatusCode]; ok {
drainAndClose(resp.Body, nil)
return err
}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
drainAndClose(resp.Body, nil)
return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status)
}
return nil
}
// readHeaders returns a Headers object from the http.Response.
//
// If it receives multiple values for a key (which should never
// happen) it will use the first one
func readHeaders(resp *http.Response) Headers {
headers := Headers{}
for key, values := range resp.Header {
headers[key] = values[0]
}
return headers
}
// Headers stores HTTP headers (can only have one of each header like Swift).
type Headers map[string]string
// Does an http request using the running timer passed in
func (c *Connection) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) {
// Do the request in the background so we can check the timeout
type result struct {
resp *http.Response
err error
}
done := make(chan result, 1)
go func() {
resp, err := c.client.Do(req)
done <- result{resp, err}
}()
// Wait for the read or the timeout
select {
case r := <-done:
return r.resp, r.err
case <-timer.C:
// Kill the connection on timeout so we don't leak sockets or goroutines
cancelRequest(c.Transport, req)
return nil, TimeoutError
}
panic("unreachable") // For Go 1.0
}
// Set defaults for any unset values
//
// Call with authLock held
func (c *Connection) setDefaults() {
if c.UserAgent == "" {
c.UserAgent = DefaultUserAgent
}
if c.Retries == 0 {
c.Retries = DefaultRetries
}
if c.ConnectTimeout == 0 {
c.ConnectTimeout = 10 * time.Second
}
if c.Timeout == 0 {
c.Timeout = 60 * time.Second
}
if c.Transport == nil {
c.Transport = &http.Transport{
// TLSClientConfig: &tls.Config{RootCAs: pool},
// DisableCompression: true,
Proxy: http.ProxyFromEnvironment,
MaxIdleConnsPerHost: 2048,
}
}
if c.client == nil {
c.client = &http.Client{
// CheckRedirect: redirectPolicyFunc,
Transport: c.Transport,
}
}
}
// Authenticate connects to the Swift server.
//
// If you don't call it before calling one of the connection methods
// then it will be called for you on the first access.
func (c *Connection) Authenticate() (err error) {
c.authLock.Lock()
defer c.authLock.Unlock()
return c.authenticate()
}
// Internal implementation of Authenticate
//
// Call with authLock held
func (c *Connection) authenticate() (err error) {
c.setDefaults()
// Flush the keepalives connection - if we are
// re-authenticating then stuff has gone wrong
flushKeepaliveConnections(c.Transport)
if c.Auth == nil {
c.Auth, err = newAuth(c)
if err != nil {
return
}
}
retries := 1
again:
var req *http.Request
req, err = c.Auth.Request(c)
if err != nil {
return
}
if req != nil {
timer := time.NewTimer(c.ConnectTimeout)
var resp *http.Response
resp, err = c.doTimeoutRequest(timer, req)
if err != nil {
return
}
defer func() {
drainAndClose(resp.Body, &err)
// Flush the auth connection - we don't want to keep
// it open if keepalives were enabled
flushKeepaliveConnections(c.Transport)
}()
if err = c.parseHeaders(resp, authErrorMap); err != nil {
// Try again for a limited number of times on
// AuthorizationFailed or BadRequest. This allows us
// to try some alternate forms of the request
if (err == AuthorizationFailed || err == BadRequest) && retries > 0 {
retries--
goto again
}
return
}
err = c.Auth.Response(resp)
if err != nil {
return
}
}
if customAuth, isCustom := c.Auth.(CustomEndpointAuthenticator); isCustom && c.EndpointType != "" {
c.StorageUrl = customAuth.StorageUrlForEndpoint(c.EndpointType)
} else {
c.StorageUrl = c.Auth.StorageUrl(c.Internal)
}
c.AuthToken = c.Auth.Token()
if !c.authenticated() {
err = newError(0, "Response didn't have storage url and auth token")
return
}
return
}
// Get an authToken and url
//
// The Url may be updated if it needed to authenticate using the OnReAuth function
func (c *Connection) getUrlAndAuthToken(targetUrlIn string, OnReAuth func() (string, error)) (targetUrlOut, authToken string, err error) {
c.authLock.Lock()
defer c.authLock.Unlock()
targetUrlOut = targetUrlIn
if !c.authenticated() {
err = c.authenticate()
if err != nil {
return
}
if OnReAuth != nil {
targetUrlOut, err = OnReAuth()
if err != nil {
return
}
}
}
authToken = c.AuthToken
return
}
// flushKeepaliveConnections is called to flush pending requests after an error.
func flushKeepaliveConnections(transport http.RoundTripper) {
if tr, ok := transport.(interface {
CloseIdleConnections()
}); ok {
tr.CloseIdleConnections()
}
}
// UnAuthenticate removes the authentication from the Connection.
func (c *Connection) UnAuthenticate() {
c.authLock.Lock()
c.StorageUrl = ""
c.AuthToken = ""
c.authLock.Unlock()
}
// Authenticated returns a boolean to show if the current connection
// is authenticated.
//
// Doesn't actually check the credentials against the server.
func (c *Connection) Authenticated() bool {
c.authLock.Lock()
defer c.authLock.Unlock()
return c.authenticated()
}
// Internal version of Authenticated()
//
// Call with authLock held
func (c *Connection) authenticated() bool {
return c.StorageUrl != "" && c.AuthToken != ""
}
// SwiftInfo contains the JSON object returned by Swift when the /info
// route is queried. The object contains, among others, the Swift version,
// the enabled middlewares and their configuration
type SwiftInfo map[string]interface{}
func (i SwiftInfo) SupportsBulkDelete() bool {
_, val := i["bulk_delete"]
return val
}
func (i SwiftInfo) SupportsSLO() bool {
_, val := i["slo"]
return val
}
func (i SwiftInfo) SLOMinSegmentSize() int64 {
if slo, ok := i["slo"].(map[string]interface{}); ok {
val, _ := slo["min_segment_size"].(float64)
return int64(val)
}
return 1
}
// Discover Swift configuration by doing a request against /info
func (c *Connection) QueryInfo() (infos SwiftInfo, err error) {
infoUrl, err := url.Parse(c.StorageUrl)
if err != nil {
return nil, err
}
infoUrl.Path = path.Join(infoUrl.Path, "..", "..", "info")
resp, err := c.client.Get(infoUrl.String())
if err == nil {
if resp.StatusCode != http.StatusOK {
drainAndClose(resp.Body, nil)
return nil, fmt.Errorf("Invalid status code for info request: %d", resp.StatusCode)
}
err = readJson(resp, &infos)
if err == nil {
c.authLock.Lock()
c.swiftInfo = infos
c.authLock.Unlock()
}
return infos, err
}
return nil, err
}
func (c *Connection) cachedQueryInfo() (infos SwiftInfo, err error) {
c.authLock.Lock()
infos = c.swiftInfo
c.authLock.Unlock()
if infos == nil {
infos, err = c.QueryInfo()
if err != nil {
return
}
}
return infos, nil
}
// RequestOpts contains parameters for Connection.storage.
type RequestOpts struct {
Container string
ObjectName string
Operation string
Parameters url.Values
Headers Headers
ErrorMap errorMap
NoResponse bool
Body io.Reader
Retries int
// if set this is called on re-authentication to refresh the targetUrl
OnReAuth func() (string, error)
}
// Call runs a remote command on the targetUrl, returns a
// response, headers and possible error.
//
// operation is GET, HEAD etc
// container is the name of a container
// Any other parameters (if not None) are added to the targetUrl
//
// Returns a response or an error. If response is returned then
// the resp.Body must be read completely and
// resp.Body.Close() must be called on it, unless noResponse is set in
// which case the body will be closed in this function
//
// If "Content-Length" is set in p.Headers it will be used - this can
// be used to override the default chunked transfer encoding for
// uploads.
//
// This will Authenticate if necessary, and re-authenticate if it
// receives a 401 error which means the token has expired
//
// This method is exported so extensions can call it.
func (c *Connection) Call(targetUrl string, p RequestOpts) (resp *http.Response, headers Headers, err error) {
c.authLock.Lock()
c.setDefaults()
c.authLock.Unlock()
retries := p.Retries
if retries == 0 {
retries = c.Retries
}
var req *http.Request
for {
var authToken string
if targetUrl, authToken, err = c.getUrlAndAuthToken(targetUrl, p.OnReAuth); err != nil {
return //authentication failure
}
var URL *url.URL
URL, err = url.Parse(targetUrl)
if err != nil {
return
}
if p.Container != "" {
URL.Path += "/" + p.Container
if p.ObjectName != "" {
URL.Path += "/" + p.ObjectName
}
}
if p.Parameters != nil {
URL.RawQuery = p.Parameters.Encode()
}
timer := time.NewTimer(c.ConnectTimeout)
reader := p.Body
if reader != nil {
reader = newWatchdogReader(reader, c.Timeout, timer)
}
req, err = http.NewRequest(p.Operation, URL.String(), reader)
if err != nil {
return
}
if p.Headers != nil {
for k, v := range p.Headers {
// Set ContentLength in req if the user passed it in in the headers
if k == "Content-Length" {
contentLength, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return nil, nil, fmt.Errorf("Invalid %q header %q: %v", k, v, err)
}
req.ContentLength = contentLength
} else {
req.Header.Add(k, v)
}
}
}
req.Header.Add("User-Agent", c.UserAgent)
req.Header.Add("X-Auth-Token", authToken)
resp, err = c.doTimeoutRequest(timer, req)
if err != nil {
if (p.Operation == "HEAD" || p.Operation == "GET") && retries > 0 {
retries--
continue
}
return nil, nil, err
}
// Check to see if token has expired
if resp.StatusCode == 401 && retries > 0 {
drainAndClose(resp.Body, nil)
c.UnAuthenticate()
retries--
} else {
break
}
}
if err = c.parseHeaders(resp, p.ErrorMap); err != nil {
return nil, nil, err
}
headers = readHeaders(resp)
if p.NoResponse {
var err error
drainAndClose(resp.Body, &err)
if err != nil {
return nil, nil, err
}
} else {
// Cancel the request on timeout
cancel := func() {
cancelRequest(c.Transport, req)
}
// Wrap resp.Body to make it obey an idle timeout
resp.Body = newTimeoutReader(resp.Body, c.Timeout, cancel)
}
return
}
// storage runs a remote command on a the storage url, returns a
// response, headers and possible error.
//
// operation is GET, HEAD etc
// container is the name of a container
// Any other parameters (if not None) are added to the storage url
//
// Returns a response or an error. If response is returned then
// resp.Body.Close() must be called on it, unless noResponse is set in
// which case the body will be closed in this function
//
// This will Authenticate if necessary, and re-authenticate if it
// receives a 401 error which means the token has expired
func (c *Connection) storage(p RequestOpts) (resp *http.Response, headers Headers, err error) {
p.OnReAuth = func() (string, error) {
return c.StorageUrl, nil
}
c.authLock.Lock()
url := c.StorageUrl
c.authLock.Unlock()
return c.Call(url, p)
}
// readLines reads the response into an array of strings.
//
// Closes the response when done
func readLines(resp *http.Response) (lines []string, err error) {
defer drainAndClose(resp.Body, &err)
reader := bufio.NewReader(resp.Body)
buffer := bytes.NewBuffer(make([]byte, 0, 128))
var part []byte
var prefix bool
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
// readJson reads the response into the json type passed in
//
// Closes the response when done
func readJson(resp *http.Response, result interface{}) (err error) {
defer drainAndClose(resp.Body, &err)
decoder := json.NewDecoder(resp.Body)
return decoder.Decode(result)
}
/* ------------------------------------------------------------ */
// ContainersOpts is options for Containers() and ContainerNames()
type ContainersOpts struct {
Limit int // For an integer value n, limits the number of results to at most n values.
Prefix string // Given a string value x, return container names matching the specified prefix.
Marker string // Given a string value x, return container names greater in value than the specified marker.
EndMarker string // Given a string value x, return container names less in value than the specified marker.
Headers Headers // Any additional HTTP headers - can be nil
}
// parse the ContainerOpts
func (opts *ContainersOpts) parse() (url.Values, Headers) {
v := url.Values{}
var h Headers
if opts != nil {
if opts.Limit > 0 {
v.Set("limit", strconv.Itoa(opts.Limit))
}
if opts.Prefix != "" {
v.Set("prefix", opts.Prefix)
}
if opts.Marker != "" {
v.Set("marker", opts.Marker)
}
if opts.EndMarker != "" {
v.Set("end_marker", opts.EndMarker)
}
h = opts.Headers
}
return v, h
}
// ContainerNames returns a slice of names of containers in this account.
func (c *Connection) ContainerNames(opts *ContainersOpts) ([]string, error) {
v, h := opts.parse()
resp, _, err := c.storage(RequestOpts{
Operation: "GET",
Parameters: v,
ErrorMap: ContainerErrorMap,
Headers: h,
})
if err != nil {
return nil, err
}
lines, err := readLines(resp)
return lines, err
}
// Container contains information about a container
type Container struct {
Name string // Name of the container
Count int64 // Number of objects in the container
Bytes int64 // Total number of bytes used in the container
}
// Containers returns a slice of structures with full information as
// described in Container.
func (c *Connection) Containers(opts *ContainersOpts) ([]Container, error) {
v, h := opts.parse()
v.Set("format", "json")
resp, _, err := c.storage(RequestOpts{
Operation: "GET",
Parameters: v,
ErrorMap: ContainerErrorMap,
Headers: h,
})
if err != nil {
return nil, err
}
var containers []Container
err = readJson(resp, &containers)
return containers, err
}
// containersAllOpts makes a copy of opts if set or makes a new one and
// overrides Limit and Marker
func containersAllOpts(opts *ContainersOpts) *ContainersOpts {
var newOpts ContainersOpts
if opts != nil {
newOpts = *opts
}
if newOpts.Limit == 0 {
newOpts.Limit = allContainersLimit
}
newOpts.Marker = ""
return &newOpts
}
// ContainersAll is like Containers but it returns all the Containers
//
// It calls Containers multiple times using the Marker parameter
//
// It has a default Limit parameter but you may pass in your own
func (c *Connection) ContainersAll(opts *ContainersOpts) ([]Container, error) {
opts = containersAllOpts(opts)
containers := make([]Container, 0)
for {
newContainers, err := c.Containers(opts)
if err != nil {
return nil, err
}
containers = append(containers, newContainers...)
if len(newContainers) < opts.Limit {
break
}
opts.Marker = newContainers[len(newContainers)-1].Name
}
return containers, nil
}
// ContainerNamesAll is like ContainerNamess but it returns all the Containers
//
// It calls ContainerNames multiple times using the Marker parameter
//
// It has a default Limit parameter but you may pass in your own
func (c *Connection) ContainerNamesAll(opts *ContainersOpts) ([]string, error) {
opts = containersAllOpts(opts)
containers := make([]string, 0)
for {
newContainers, err := c.ContainerNames(opts)
if err != nil {
return nil, err
}
containers = append(containers, newContainers...)
if len(newContainers) < opts.Limit {
break
}
opts.Marker = newContainers[len(newContainers)-1]
}
return containers, nil
}
/* ------------------------------------------------------------ */
// ObjectOpts is options for Objects() and ObjectNames()
type ObjectsOpts struct {
Limit int // For an integer value n, limits the number of results to at most n values.
Marker string // Given a string value x, return object names greater in value than the specified marker.
EndMarker string // Given a string value x, return object names less in value than the specified marker
Prefix string // For a string value x, causes the results to be limited to object names beginning with the substring x.
Path string // For a string value x, return the object names nested in the pseudo path
Delimiter rune // For a character c, return all the object names nested in the container
Headers Headers // Any additional HTTP headers - can be nil
}
// parse reads values out of ObjectsOpts
func (opts *ObjectsOpts) parse() (url.Values, Headers) {
v := url.Values{}
var h Headers
if opts != nil {
if opts.Limit > 0 {
v.Set("limit", strconv.Itoa(opts.Limit))
}
if opts.Marker != "" {
v.Set("marker", opts.Marker)
}
if opts.EndMarker != "" {
v.Set("end_marker", opts.EndMarker)
}
if opts.Prefix != "" {
v.Set("prefix", opts.Prefix)
}
if opts.Path != "" {
v.Set("path", opts.Path)
}
if opts.Delimiter != 0 {
v.Set("delimiter", string(opts.Delimiter))
}
h = opts.Headers
}
return v, h
}
// ObjectNames returns a slice of names of objects in a given container.
func (c *Connection) ObjectNames(container string, opts *ObjectsOpts) ([]string, error) {
v, h := opts.parse()
resp, _, err := c.storage(RequestOpts{
Container: container,
Operation: "GET",
Parameters: v,
ErrorMap: ContainerErrorMap,
Headers: h,
})
if err != nil {
return nil, err
}