This repository has been archived by the owner on Apr 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
bucket.go
216 lines (196 loc) · 5.84 KB
/
bucket.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
/*
Copyright 2015 The Kubernetes Authors.
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 utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"time"
"github.com/golang/glog"
)
const (
// GCSListAPIHost is the host of the api for a bucket
GCSListAPIHost = "www.googleapis.com"
// GCSBucketHost is the host for GCS bucket directory requests
GCSBucketHost = "storage.googleapis.com"
retries = 3
retryWait = 100 * time.Millisecond
)
// Bucket represents a GCS bucket. It will craft file and list requests for you.
type Bucket struct {
scheme string
bucket string
listHost string
bucketHost string
}
// NewBucket constructs a new bucket pointing at the default URLs.
func NewBucket(name string) *Bucket {
return &Bucket{
scheme: "https",
bucket: name,
listHost: GCSListAPIHost,
bucketHost: GCSBucketHost,
}
}
// NewTestBucket constructs a new bucket pointing at a specific host.
func NewTestBucket(name string, host string) *Bucket {
u, err := url.Parse(host)
if err != nil {
glog.Fatalf("test passed invalid host %v: %v", host, err)
}
return &Bucket{
scheme: u.Scheme,
bucket: name,
listHost: u.Host,
bucketHost: u.Host,
}
}
// ReadFile assembles the path and initiates a read operation.
func (b *Bucket) ReadFile(pathElements ...interface{}) (*http.Response, error) {
url := b.ExpandPathURL(pathElements...)
return getResponseWithRetry(url.String())
}
// ExpandPathURL turns the given path into a complete URL, good for accessing a
// file.
func (b *Bucket) ExpandPathURL(pathElements ...interface{}) *url.URL {
// Prepend the bucket to the path
pathElements = append([]interface{}{"/", b.bucket}, pathElements...)
return &url.URL{
Scheme: b.scheme,
Host: b.bucketHost,
Path: joinStringsAndInts(pathElements...),
}
}
// ExpandListURL produces the URL for a list API query which will list files
// enclosed by the provided path. Note that there's currently no way to get a
// path that ends in '/'.
func (b *Bucket) ExpandListURL(pathElements ...interface{}) *url.URL {
return b.buildURL(map[string]string{
// GCS api doesn't like preceding '/', so remove it.
"prefix": strings.TrimPrefix(joinStringsAndInts(pathElements...), "/"),
})
}
func (b *Bucket) buildURL(parameters map[string]string) *url.URL {
q := url.Values{}
for key, value := range parameters {
q.Set(key, value)
}
return &url.URL{
Scheme: b.scheme,
Host: b.listHost,
Path: path.Join("storage/v1/b", b.bucket, "o"),
RawQuery: q.Encode(),
}
}
// List returns a list of all files inside the given path.
// The returned file name included the complete path from bucket root
func (b *Bucket) List(pathElements ...interface{}) ([]string, error) {
listURL := b.ExpandListURL(pathElements...)
data, err := queryURL(listURL.String())
if err != nil {
return nil, err
}
var ret []string
if _, ok := data["items"]; !ok {
glog.Warningf("No matching files were found (from: %v)", listURL.String())
return ret, nil
}
for _, item := range data["items"].([]interface{}) {
ret = append(ret, (item.(map[string]interface{})["name"]).(string))
}
return ret, nil
}
// ListDirs returns a list of all directories inside the given path.
// The returned direcotry name included the complete path from bucket root
func (b *Bucket) ListDirs(pathElements ...interface{}) ([]string, error) {
var ret []string
var pageToken string
for {
var ok bool
listURL := b.buildURL(map[string]string{
// GCS api doesn't like preceding '/', so remove it.
"prefix": strings.TrimPrefix(joinStringsAndInts(pathElements...)+"/", "/"),
"delimiter": "/",
"pageToken": pageToken,
})
data, err := queryURL(listURL.String())
if err != nil {
return nil, err
}
if _, ok = data["prefixes"]; !ok {
glog.Warningf("No matching dirs were found (from: %v)", listURL.String())
return ret, nil
}
for _, item := range data["prefixes"].([]interface{}) {
ret = append(ret, item.(string))
}
pageToken, ok = data["nextPageToken"].(string)
if !ok {
break
}
}
return ret, nil
}
func queryURL(url string) (map[string]interface{}, error) {
res, err := getResponseWithRetry(url)
if err != nil {
return nil, fmt.Errorf("Failed to GET %v: %v", url, err)
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Got a non-success response %v while listing %v", res.StatusCode, url)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read the response for %v: %v", url, err)
}
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal %v: %v", string(body), err)
}
return data, nil
}
func joinStringsAndInts(pathElements ...interface{}) string {
var parts []string
for _, e := range pathElements {
switch t := e.(type) {
case string:
parts = append(parts, t)
case int:
parts = append(parts, strconv.Itoa(t))
default:
glog.Fatalf("joinStringsAndInts only accepts ints and strings as path elements, but was passed %#v", t)
}
}
return path.Join(parts...)
}
func getResponseWithRetry(url string) (*http.Response, error) {
var response *http.Response
var err error
for i := 0; i < retries; i++ {
response, err = http.Get(url)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusOK {
return response, nil
}
time.Sleep(retryWait)
}
return response, nil
}