-
Notifications
You must be signed in to change notification settings - Fork 0
/
gs.go
282 lines (245 loc) · 7.12 KB
/
gs.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
// Copyright 2015 The LUCI 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 gs
import (
"context"
"fmt"
"io"
"net/http"
"time"
"go.chromium.org/luci/common/errors"
log "go.chromium.org/luci/common/logging"
"go.chromium.org/luci/common/retry"
"go.chromium.org/luci/common/retry/transient"
gs "cloud.google.com/go/storage"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
var (
// ReadWriteScopes is the set of scopes needed for read/write Google Storage
// access.
ReadWriteScopes = []string{gs.ScopeReadWrite}
// ReadOnlyScopes is the set of scopes needed for read/write Google Storage
// read-only access.
ReadOnlyScopes = []string{gs.ScopeReadOnly}
)
// Client abstracts functionality to connect with and use Google Storage from
// the actual Google Storage client.
//
// Non-production implementations are used primarily for testing.
type Client interface {
io.Closer
// Attrs retrieves Object attributes for a given path.
Attrs(p Path) (*gs.ObjectAttrs, error)
// NewReader instantiates a new Reader instance for the named bucket/path.
//
// The supplied offset must be >= 0, or else this function will panic.
//
// If the supplied length is <0, no upper byte bound will be set.
NewReader(p Path, offset, length int64) (io.ReadCloser, error)
// NewWriter instantiates a new Writer instance for the named bucket/path.
NewWriter(p Path) (Writer, error)
// Delete deletes the object at the specified path.
//
// If the object does not exist, it is considered a success.
Delete(p Path) error
// Rename renames an object from one path to another.
//
// NOTE: The object should be removed from its original path, but current
// implementation uses two operations (Copy + Delete), so it may
// occasionally fail.
Rename(src, dst Path) error
}
// prodGSObject is an implementation of Client interface using the production
// Google Storage client.
type prodClient struct {
context.Context
// rt is the RoundTripper to use, or nil for the cloud service default.
rt http.RoundTripper
// baseClient is a basic Google Storage client instance. It is used for
// operations that don't need custom header injections.
baseClient *gs.Client
}
// NewProdClient creates a new Client instance that uses production Cloud
// Storage.
//
// The supplied RoundTripper will be used to make connections. If nil, the
// default HTTP client will be used.
func NewProdClient(ctx context.Context, rt http.RoundTripper) (Client, error) {
c := prodClient{
Context: ctx,
rt: rt,
}
var err error
c.baseClient, err = c.newClient()
if err != nil {
return nil, err
}
return &c, nil
}
func (c *prodClient) Close() error {
return c.baseClient.Close()
}
func (c *prodClient) NewWriter(p Path) (Writer, error) {
bucket, filename, err := splitPathErr(p)
if err != nil {
return nil, err
}
return &prodWriter{
Context: c,
client: c,
bucket: bucket,
relpath: filename,
}, nil
}
func (c *prodClient) Attrs(p Path) (*gs.ObjectAttrs, error) {
obj, err := c.handleForPath(p)
if err != nil {
return nil, err
}
return obj.Attrs(c)
}
func (c *prodClient) NewReader(p Path, offset, length int64) (io.ReadCloser, error) {
if offset < 0 {
panic(fmt.Errorf("offset (%d) must be >= 0", offset))
}
obj, err := c.handleForPath(p)
if err != nil {
return nil, err
}
return obj.NewRangeReader(c, offset, length)
}
func (c *prodClient) Rename(src, dst Path) error {
srcObj, err := c.handleForPath(src)
if err != nil {
return fmt.Errorf("invalid source path: %s", err)
}
dstObj, err := c.handleForPath(dst)
if err != nil {
return fmt.Errorf("invalid destination path: %s", err)
}
// First stage: CopyTo
err = retry.Retry(c, transient.Only(retry.Default), func() error {
if _, err := dstObj.CopierFrom(srcObj).Run(c); err != nil {
// The storage library doesn't return gs.ErrObjectNotExist when Delete
// returns a 404. Catch that explicitly.
// 403 errors are non-transient.
if isNotFoundError(err) || isForbidden(err) {
return err
}
// Assume all unexpected errors are transient.
return transient.Tag.Apply(err)
}
return nil
}, func(err error, d time.Duration) {
log.Fields{
log.ErrorKey: err,
"delay": d,
"src": src,
"dst": dst,
}.Warningf(c, "Transient error copying GS file. Retrying...")
})
if err != nil {
return err
}
// Second stage: Delete. This is not fatal.
if err := c.deleteObject(srcObj); err != nil {
log.Fields{
log.ErrorKey: err,
"path": src,
}.Warningf(c, "(Non-fatal) Failed to delete source during rename.")
}
return nil
}
func (c *prodClient) Delete(p Path) error {
dstObj, err := c.handleForPath(p)
if err != nil {
return fmt.Errorf("invalid path: %s", err)
}
return c.deleteObject(dstObj)
}
func (c *prodClient) deleteObject(o *gs.ObjectHandle) error {
return retry.Retry(c, transient.Only(retry.Default), func() error {
if err := o.Delete(c); err != nil {
// The storage library doesn't return gs.ErrObjectNotExist when Delete
// returns a 404. Catch that explicitly.
if isNotFoundError(err) {
// If the file wasn't found, then the delete "succeeded".
return nil
}
// 403 errors are non-transient.
if isForbidden(err) {
return err
}
// Assume all unexpected errors are transient.
return transient.Tag.Apply(err)
}
return nil
}, func(err error, d time.Duration) {
log.Fields{
log.ErrorKey: err,
"delay": d,
}.Warningf(c, "Transient error deleting file. Retrying...")
})
}
func (c *prodClient) newClient() (*gs.Client, error) {
var optsArray [1]option.ClientOption
opts := optsArray[:0]
if c.rt != nil {
opts = append(opts, option.WithHTTPClient(&http.Client{
Transport: c.rt,
}))
}
return gs.NewClient(c, opts...)
}
func (c *prodClient) handleForPath(p Path) (*gs.ObjectHandle, error) {
bucket, filename, err := splitPathErr(p)
if err != nil {
return nil, err
}
return c.baseClient.Bucket(bucket).Object(filename), nil
}
func splitPathErr(p Path) (bucket, filename string, err error) {
bucket, filename = p.Split()
switch {
case bucket == "":
err = errors.New("path has no bucket")
case filename == "":
err = errors.New("path has no filename")
}
return
}
func isForbidden(err error) bool {
if t, ok := err.(*googleapi.Error); ok {
switch t.Code {
case http.StatusForbidden:
return true
}
}
return false
}
func isNotFoundError(err error) bool {
if err == gs.ErrObjectNotExist {
return true
}
// The storage library doesn't return gs.ErrObjectNotExist when Delete
// returns a 404. Catch that explicitly.
if t, ok := err.(*googleapi.Error); ok {
switch t.Code {
case http.StatusNotFound:
return true
}
}
return false
}