blob: 6585a145c0a9ba25f33dc66e7e8fe31138a8f522 [file] [log] [blame]
Jon Perritt0ce24ad2014-10-20 21:59:45 -05001package bulk
2
3import (
4 "archive/tar"
5 "compress/gzip"
6 "compress/bzip2"
7 "errors"
8 "io"
9 "net/url"
10 "os"
11 "path/filepath"
12 "strings"
13
14 "github.com/racker/perigee"
15 "github.com/rackspace/gophercloud"
16)
17
18// DeleteOptsBuilder allows extensions to add additional parameters to the
19// Delete request.
20type DeleteOptsBuilder interface {
21 ToBulkDeleteBody() (string, error)
22}
23
24// DeleteOpts is a structure that holds parameters for deleting an object.
25type DeleteOpts []string
26
27// ToBulkDeleteBody formats a DeleteOpts into a request body.
28func (opts DeleteOpts) ToBulkDeleteBody() (string, error) {
29 return url.QueryEscape(strings.Join(opts, "\n")), nil
30}
31
32// Delete will delete objects or containers in bulk.
33func Delete(c *gophercloud.ServiceClient, opts DeleteOptsBuilder) DeleteResult {
34 var res DeleteResult
35
36 if opts == nil {
37 return res
38 }
39
40 reqString, err := opts.ToBulkDeleteBody()
41 if err != nil {
42 res.Err = err
43 return res
44 }
45
46 reqBody := strings.NewReader(reqString)
47
48 resp, err := perigee.Request("DELETE", deleteURL(c), perigee.Options{
49 ContentType: "text/plain",
50 MoreHeaders: c.Provider.AuthenticatedHeaders(),
51 OkCodes: []int{200},
52 ReqBody: reqBody,
53 Results: &res.Body,
54 })
55 res.Header = resp.HttpResponse.Header
56 res.Err = err
57 return res
58}
59
60// Extract will extract the files in `file` and create objects in object storage
61// from them.
62func Extract(c *gophercloud.ServiceClient, file string) ExtractResult {
63 var res ExtractResult
64
65 if file == ""{
66 res.Err = errors.New("Missing required field 'f'.")
67 return res
68 }
69
70 var ext string
71 var reqBody io.Reader
72 f, err := os.Open(file)
73 if err != nil {
74 res.Err = errors.New("Error opening file.")
75 return res
76 }
77 defer f.Close()
78
79 switch filepath.Ext(file) {
80 case "tar":
81 ext = "tar"
82 reqBody = tar.NewReader(f)
83 case "gz":
84 ext = "tar.gz"
85 reqBody, err = gzip.NewReader(f)
86 if err != nil {
87 res.Err = err
88 return res
89 }
90 case "bz2":
91 ext = "tar.bz2"
92 reqBody = bzip2.NewReader(f)
93 default:
94 res.Err = errors.New("Unsupported extension type.")
95 return res
96 }
97
98 resp, err := perigee.Request("PUT", extractURL(c, ext), perigee.Options{
99 MoreHeaders: c.Provider.AuthenticatedHeaders(),
100 OkCodes: []int{200},
101 ReqBody: reqBody,
102 Results: &res.Body,
103 })
104 res.Header = resp.HttpResponse.Header
105 res.Err = err
106 return res
107}