-
Notifications
You must be signed in to change notification settings - Fork 0
/
swift.go
1437 lines (1348 loc) · 42.6 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/md5"
"encoding/json"
"fmt"
"hash"
"io"
"log"
"mime"
"net"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"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
allContainersLimit = 10000 // Number of containers to fetch at once
allObjectsLimit = 10000 // Number objects to fetch at once
allObjectsChanLimit = 1000 // ...when fetching to a channel
)
// 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.
//
// 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
// Memset Memstore UK https://auth.storage.memset.com/v1.0
type Connection struct {
UserName string // UserName for api
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) NOT IMPLEMENTED
storageUrl string
authToken string
tr *http.Transport
client *http.Client
AuthHeaders http.Header // store the authentication headers so extensions can access them
}
// 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
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")
// Mappings for authentication errors
authErrorMap = errorMap{
401: AuthorizationFailed,
}
// Mappings for container errors
ContainerErrorMap = errorMap{
404: ContainerNotFound,
409: ContainerNotEmpty,
}
// Mappings for object errors
objectErrorMap = errorMap{
404: ObjectNotFound,
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
}
}
// parseHeaders checks a response for errors and translates into
// standard errors if necessary.
func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error {
if errorMap != nil {
if err, ok := errorMap[resp.StatusCode]; ok {
return err
}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status)
}
return nil
}
// readHeaders returns a Headers object from the http.Response.
//
// Logs a warning if receives multiple values for a key (which
// should never happen)
func readHeaders(resp *http.Response) Headers {
headers := Headers{}
for key, values := range resp.Header {
headers[key] = values[0]
if len(values) > 1 {
log.Printf("swift: received multiple values for header %q", key)
}
}
return headers
}
// Headers stores HTTP headers (can only have one of each header like Swift).
type Headers map[string]string
// Authenticate connects to the Swift server.
func (c *Connection) Authenticate() (err error) {
// Set defaults if not set
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.tr == nil {
c.tr = &http.Transport{
// TLSClientConfig: &tls.Config{RootCAs: pool},
// DisableCompression: true,
// Dial with deadline
//
// FIXME not sure how this plays with connection pooling
Dial: func(network, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(network, addr, c.ConnectTimeout)
if err != nil {
return nil, err
}
// FIXME Need to continuously bump this
// deadline forwards but can't figure
// out how to get the net.Conn out of the Request
// conn.SetDeadline(time.Now().Add(c.Timeout))
return conn, nil
},
}
}
if c.client == nil {
c.client = &http.Client{
// CheckRedirect: redirectPolicyFunc,
Transport: c.tr,
}
}
// Flush the keepalives connection - if we are
// re-authenticating then stuff has gone wrong
c.tr.CloseIdleConnections()
var req *http.Request
req, err = http.NewRequest("GET", c.AuthUrl, nil)
if err != nil {
return
}
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("X-Auth-Key", c.ApiKey)
req.Header.Set("X-Auth-User", c.UserName)
var resp *http.Response
resp, err = c.client.Do(req)
if err != nil {
return
}
defer func() {
checkClose(resp.Body, &err)
// Flush the auth connection - we don't want to keep
// it open if keepalives were enabled
c.tr.CloseIdleConnections()
}()
if err = c.parseHeaders(resp, authErrorMap); err != nil {
return
}
c.storageUrl = resp.Header.Get("X-Storage-Url")
c.authToken = resp.Header.Get("X-Auth-Token")
c.AuthHeaders = resp.Header // save authentication headers for external extension access
if !c.Authenticated() {
return newError(0, "Response didn't have storage url and auth token")
}
return nil
}
// UnAuthenticate removes the authentication from the Connection.
func (c *Connection) UnAuthenticate() {
c.storageUrl = ""
c.authToken = ""
}
// 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 {
return c.storageUrl != "" && c.authToken != ""
}
// 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
}
// 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) {
return c.Call(c.storageUrl, p)
}
// Call is an wrapper which calls the correct endpoint targetUrl.
// This method is exported so extensions can call it.
func (c *Connection) Call(targetUrl string, p RequestOpts) (resp *http.Response, headers Headers, err error) {
retries := p.Retries
if retries == 0 {
retries = c.Retries
}
for {
if !c.Authenticated() {
err = c.Authenticate()
if err != nil {
return
}
}
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()
}
var req *http.Request
req, err = http.NewRequest(p.Operation, url.String(), p.Body)
if err != nil {
return
}
if p.Headers != nil {
for k, v := range p.Headers {
req.Header.Add(k, v)
}
}
req.Header.Add("User-Agent", DefaultUserAgent)
req.Header.Add("X-Auth-Token", c.authToken)
resp, err = c.client.Do(req)
if err != nil {
return
}
// Check to see if token has expired
if resp.StatusCode == 401 && retries > 0 {
_ = resp.Body.Close()
c.UnAuthenticate()
retries--
} else {
break
}
}
if err = c.parseHeaders(resp, p.ErrorMap); err != nil {
_ = resp.Body.Close()
return nil, nil, err
}
headers = readHeaders(resp)
if p.NoResponse {
err = resp.Body.Close()
if err != nil {
return nil, nil, err
}
}
return
}
// readLines reads the response into an array of strings.
//
// Closes the response when done
func readLines(resp *http.Response) (lines []string, err error) {
defer checkClose(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 checkClose(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.
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 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.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
}
return readLines(resp)
}
// Object contains information about an object
type Object struct {
Name string `json:"name"` // object name
ContentType string `json:"content_type"` // eg application/directory
Bytes int64 `json:"bytes"` // size in bytes
ServerLastModified string `json:"last_modified"` // Last modified time, eg '2011-06-30T08:20:47.736680' as a string supplied by the server
LastModified time.Time // Last modified time converted to a time.Time
Hash string `json:"hash"` // MD5 hash, eg "d41d8cd98f00b204e9800998ecf8427e"
PseudoDirectory bool // Set when using delimiter to show that this directory object does not really exist
SubDir string `json:"subdir"` // returned only when using delimiter to mark "pseudo directories"
}
// Objects returns a slice of Object with information about each
// object in the container.
//
// If Delimiter is set in the opts then PseudoDirectory may be set,
// with ContentType 'application/directory'. These are not real
// objects but represent directories of objects which haven't had an
// object created for them.
func (c *Connection) Objects(container string, opts *ObjectsOpts) ([]Object, error) {
v, h := opts.parse()
v.Set("format", "json")
resp, _, err := c.storage(RequestOpts{
Container: container,
Operation: "GET",
Parameters: v,
ErrorMap: ContainerErrorMap,
Headers: h,
})
if err != nil {
return nil, err
}
var objects []Object
err = readJson(resp, &objects)
// Convert Pseudo directories and dates
for i := range objects {
object := &objects[i]
if object.SubDir != "" {
object.Name = object.SubDir
object.PseudoDirectory = true
object.ContentType = "application/directory"
}
if object.ServerLastModified != "" {
// 2012-11-11T14:49:47.887250
//
// Remove fractional seconds if present. This
// then keeps it consistent with Object
// which can only return timestamps accurate
// to 1 second
//
// The TimeFormat will parse fractional
// seconds if desired though
datetime := strings.SplitN(object.ServerLastModified, ".", 2)[0]
object.LastModified, err = time.Parse(TimeFormat, datetime)
if err != nil {
return nil, err
}
}
}
return objects, err
}
// objectsAllOpts makes a copy of opts if set or makes a new one and
// overrides Limit and Marker
func objectsAllOpts(opts *ObjectsOpts, Limit int) *ObjectsOpts {
var newOpts ObjectsOpts
if opts != nil {
newOpts = *opts
}
if newOpts.Limit == 0 {
newOpts.Limit = Limit
}
newOpts.Marker = ""
return &newOpts
}
// A closure defined by the caller to iterate through all objects
//
// Call Objects or ObjectNames from here with the *ObjectOpts passed in
//
// Do whatever is required with the results then return them
type ObjectsWalkFn func(*ObjectsOpts) (interface{}, error)
// ObjectsWalk is uses to iterate through all the objects in chunks as
// returned by Objects or ObjectNames using the Marker and Limit
// parameters in the ObjectsOpts.
//
// Pass in a closure `walkFn` which calls Objects or ObjectNames with
// the *ObjectsOpts passed to it and does something with the results.
//
// Errors will be returned from this function
//
// It has a default Limit parameter but you may pass in your own
func (c *Connection) ObjectsWalk(container string, opts *ObjectsOpts, walkFn ObjectsWalkFn) error {
opts = objectsAllOpts(opts, allObjectsChanLimit)
for {
objects, err := walkFn(opts)
if err != nil {
return err
}
var n int
var last string
switch objects := objects.(type) {
case []string:
n = len(objects)
if n > 0 {
last = objects[len(objects)-1]
}
case []Object:
n = len(objects)
if n > 0 {
last = objects[len(objects)-1].Name
}
default:
panic("Unknown type returned to ObjectsWalk")
}
if n < opts.Limit {
break
}
opts.Marker = last
}
return nil
}
// ObjectsAll is like Objects but it returns an unlimited number of Objects in a slice
//
// It calls Objects multiple times using the Marker parameter
func (c *Connection) ObjectsAll(container string, opts *ObjectsOpts) ([]Object, error) {
objects := make([]Object, 0)
err := c.ObjectsWalk(container, opts, func(opts *ObjectsOpts) (interface{}, error) {
newObjects, err := c.Objects(container, opts)
if err == nil {
objects = append(objects, newObjects...)
}
return newObjects, err
})
return objects, err
}
// ObjectNamesAll is like ObjectNames but it returns all the Objects
//
// It calls ObjectNames multiple times using the Marker parameter
//
// It has a default Limit parameter but you may pass in your own
func (c *Connection) ObjectNamesAll(container string, opts *ObjectsOpts) ([]string, error) {
objects := make([]string, 0)
err := c.ObjectsWalk(container, opts, func(opts *ObjectsOpts) (interface{}, error) {
newObjects, err := c.ObjectNames(container, opts)
if err == nil {
objects = append(objects, newObjects...)
}
return newObjects, err
})
return objects, err
}
// Account contains information about this account.
type Account struct {
BytesUsed int64 // total number of bytes used
Containers int64 // total number of containers
Objects int64 // total number of objects
}
// getInt64FromHeader is a helper function to decode int64 from header.
func getInt64FromHeader(resp *http.Response, header string) (result int64, err error) {
value := resp.Header.Get(header)
result, err = strconv.ParseInt(value, 10, 64)
if err != nil {
err = newErrorf(0, "Bad Header '%s': '%s': %s", header, value, err)
}
return
}
// Account returns info about the account in an Account struct.
func (c *Connection) Account() (info Account, headers Headers, err error) {
var resp *http.Response
resp, headers, err = c.storage(RequestOpts{
Operation: "HEAD",
ErrorMap: ContainerErrorMap,
NoResponse: true,
})
if err != nil {
return
}
// Parse the headers into a dict
//
// {'Accept-Ranges': 'bytes',
// 'Content-Length': '0',
// 'Date': 'Tue, 05 Jul 2011 16:37:06 GMT',
// 'X-Account-Bytes-Used': '316598182',
// 'X-Account-Container-Count': '4',
// 'X-Account-Object-Count': '1433'}
if info.BytesUsed, err = getInt64FromHeader(resp, "X-Account-Bytes-Used"); err != nil {
return
}
if info.Containers, err = getInt64FromHeader(resp, "X-Account-Container-Count"); err != nil {
return
}
if info.Objects, err = getInt64FromHeader(resp, "X-Account-Object-Count"); err != nil {
return
}
return
}
// AccountUpdate adds, replaces or remove account metadata.
//
// Add or update keys by mentioning them in the Headers.
//
// Remove keys by setting them to an empty string.
func (c *Connection) AccountUpdate(h Headers) error {
_, _, err := c.storage(RequestOpts{
Operation: "POST",
ErrorMap: ContainerErrorMap,
NoResponse: true,
Headers: h,
})
return err
}
// ContainerCreate creates a container.
//
// If you don't want to add Headers just pass in nil
//
// No error is returned if it already exists but the metadata if any will be updated.
func (c *Connection) ContainerCreate(container string, h Headers) error {
_, _, err := c.storage(RequestOpts{
Container: container,
Operation: "PUT",
ErrorMap: ContainerErrorMap,
NoResponse: true,
Headers: h,
})
return err
}
// ContainerDelete deletes a container.
//
// May return ContainerDoesNotExist or ContainerNotEmpty
func (c *Connection) ContainerDelete(container string) error {
_, _, err := c.storage(RequestOpts{
Container: container,
Operation: "DELETE",
ErrorMap: ContainerErrorMap,
NoResponse: true,
})
return err
}
// Container returns info about a single container including any
// metadata in the headers.
func (c *Connection) Container(container string) (info Container, headers Headers, err error) {
var resp *http.Response
resp, headers, err = c.storage(RequestOpts{
Container: container,
Operation: "HEAD",
ErrorMap: ContainerErrorMap,
NoResponse: true,
})
if err != nil {
return
}
// Parse the headers into the struct
info.Name = container
if info.Bytes, err = getInt64FromHeader(resp, "X-Container-Bytes-Used"); err != nil {
return
}
if info.Count, err = getInt64FromHeader(resp, "X-Container-Object-Count"); err != nil {
return
}
return
}
// ContainerUpdate adds, replaces or removes container metadata.
//
// Add or update keys by mentioning them in the Metadata.
//
// Remove keys by setting them to an empty string.
//
// Container metadata can only be read with Container() not with Containers().
func (c *Connection) ContainerUpdate(container string, h Headers) error {
_, _, err := c.storage(RequestOpts{
Container: container,
Operation: "POST",
ErrorMap: ContainerErrorMap,
NoResponse: true,
Headers: h,
})
return err
}
// ------------------------------------------------------------
// ObjectCreateFile represents a swift object open for writing
type ObjectCreateFile struct {
checkHash bool // whether we are checking the hash
pipeReader *io.PipeReader // pipe for the caller to use
pipeWriter *io.PipeWriter
hash hash.Hash // hash being build up as we go along
done chan bool // signals when the upload has finished
resp *http.Response // valid when done has signalled
err error // ditto
headers Headers // ditto
}
// Write bytes to the object - see io.Writer
func (file *ObjectCreateFile) Write(p []byte) (n int, err error) {
if file.checkHash {
_, _ = file.hash.Write(p)
}
return file.pipeWriter.Write(p)
}
// Close the object and checks the md5sum if it was required.
//
// Also returns any other errors from the server (eg container not
// found) so it is very important to check the errors on this method.
func (file *ObjectCreateFile) Close() error {
// Close the body
err := file.pipeWriter.Close()
if err != nil {
return err
}
// Wait for the HTTP operation to complete
<-file.done
// Check errors
if file.err != nil {
return file.err
}
if file.checkHash {
receivedMd5 := strings.ToLower(file.headers["Etag"])
calculatedMd5 := fmt.Sprintf("%x", file.hash.Sum(nil))
if receivedMd5 != calculatedMd5 {
return ObjectCorrupted
}
}
return nil
}
// Check it satisfies the interface
var _ io.WriteCloser = &ObjectCreateFile{}
// objectPutHeaders create a set of headers for a PUT
//
// It guesses the contentType from the objectName if it isn't set
//
// checkHash may be changed
func objectPutHeaders(objectName string, checkHash *bool, Hash string, contentType string, h Headers) Headers {
if contentType == "" {
contentType = mime.TypeByExtension(path.Ext(objectName))
if contentType == "" {
contentType = "application/octet-stream"
}
}
// Meta stuff
extraHeaders := map[string]string{
"Content-Type": contentType,
}
for key, value := range h {
extraHeaders[key] = value
}
if Hash != "" {
extraHeaders["Etag"] = Hash
*checkHash = false // the server will do it
}
return extraHeaders
}
// ObjectCreate creates or updates the object in the container. It
// returns an io.WriteCloser you should write the contents to. You
// MUST call Close() on it and you MUST check the error return from
// Close().
//
// If checkHash is True then it will calculate the MD5 Hash of the
// file as it is being uploaded and check it against that returned
// from the server. If it is wrong then it will return
// ObjectCorrupted on Close()
//
// If you know the MD5 hash of the object ahead of time then set the
// Hash parameter and it will be sent to the server (as an Etag
// header) and the server will check the MD5 itself after the upload,
// and this will return ObjectCorrupted on Close() if it is incorrect.
//
// If you don't want any error protection (not recommended) then set
// checkHash to false and Hash to "".
//
// If contentType is set it will be used, otherwise one will be
// guessed from objectName using mime.TypeByExtension
func (c *Connection) ObjectCreate(container string, objectName string, checkHash bool, Hash string, contentType string, h Headers) (file *ObjectCreateFile, err error) {
extraHeaders := objectPutHeaders(objectName, &checkHash, Hash, contentType, h)
pipeReader, pipeWriter := io.Pipe()
file = &ObjectCreateFile{
hash: md5.New(),
checkHash: checkHash,
pipeReader: pipeReader,
pipeWriter: pipeWriter,
done: make(chan bool),
}
// Run the PUT in the background piping it data
go func() {
file.resp, file.headers, file.err = c.storage(RequestOpts{
Container: container,
ObjectName: objectName,
Operation: "PUT",
Headers: extraHeaders,
Body: pipeReader,
NoResponse: true,
ErrorMap: objectErrorMap,
})
// Signal finished
file.done <- true
}()
return
}
// ObjectPut creates or updates the path in the container from
// contents. contents should be an open io.Reader which will have all
// its contents read.
//
// This is a low level interface.
//
// If checkHash is True then it will calculate the MD5 Hash of the
// file as it is being uploaded and check it against that returned
// from the server. If it is wrong then it will return
// ObjectCorrupted.
//
// If you know the MD5 hash of the object ahead of time then set the
// Hash parameter and it will be sent to the server (as an Etag
// header) and the server will check the MD5 itself after the upload,
// and this will return ObjectCorrupted if it is incorrect.
//
// If you don't want any error protection (not recommended) then set
// checkHash to false and Hash to "".
//
// If contentType is set it will be used, otherwise one will be
// guessed from objectName using mime.TypeByExtension
func (c *Connection) ObjectPut(container string, objectName string, contents io.Reader, checkHash bool, Hash string, contentType string, h Headers) (headers Headers, err error) {
extraHeaders := objectPutHeaders(objectName, &checkHash, Hash, contentType, h)
hash := md5.New()
var body io.Reader = contents
if checkHash {