forked from pingcap/br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcs.go
250 lines (222 loc) · 7.38 KB
/
gcs.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package storage
import (
"context"
"io"
"io/ioutil"
"path"
"strings"
"cloud.google.com/go/storage"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/backup"
"github.com/pingcap/log"
"github.com/spf13/pflag"
"go.uber.org/zap"
"golang.org/x/oauth2/google"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
berrors "github.com/pingcap/br/pkg/errors"
)
const (
gcsEndpointOption = "gcs.endpoint"
gcsStorageClassOption = "gcs.storage-class"
gcsPredefinedACL = "gcs.predefined-acl"
gcsCredentialsFile = "gcs.credentials-file"
)
// GCSBackendOptions are options for configuration the GCS storage.
type GCSBackendOptions struct {
Endpoint string `json:"endpoint" toml:"endpoint"`
StorageClass string `json:"storage-class" toml:"storage-class"`
PredefinedACL string `json:"predefined-acl" toml:"predefined-acl"`
CredentialsFile string `json:"credentials-file" toml:"credentials-file"`
}
func (options *GCSBackendOptions) apply(gcs *backup.GCS) error {
gcs.Endpoint = options.Endpoint
gcs.StorageClass = options.StorageClass
gcs.PredefinedAcl = options.PredefinedACL
if options.CredentialsFile != "" {
b, err := ioutil.ReadFile(options.CredentialsFile)
if err != nil {
return errors.Trace(err)
}
gcs.CredentialsBlob = string(b)
}
return nil
}
func defineGCSFlags(flags *pflag.FlagSet) {
// TODO: remove experimental tag if it's stable
flags.String(gcsEndpointOption, "", "(experimental) Set the GCS endpoint URL")
flags.String(gcsStorageClassOption, "", "(experimental) Specify the GCS storage class for objects")
flags.String(gcsPredefinedACL, "", "(experimental) Specify the GCS predefined acl for objects")
flags.String(gcsCredentialsFile, "", "(experimental) Set the GCS credentials file path")
}
func (options *GCSBackendOptions) parseFromFlags(flags *pflag.FlagSet) error {
var err error
options.Endpoint, err = flags.GetString(gcsEndpointOption)
if err != nil {
return errors.Trace(err)
}
options.StorageClass, err = flags.GetString(gcsStorageClassOption)
if err != nil {
return errors.Trace(err)
}
options.PredefinedACL, err = flags.GetString(gcsPredefinedACL)
if err != nil {
return errors.Trace(err)
}
options.CredentialsFile, err = flags.GetString(gcsCredentialsFile)
if err != nil {
return errors.Trace(err)
}
return nil
}
type gcsStorage struct {
gcs *backup.GCS
bucket *storage.BucketHandle
}
func (s *gcsStorage) objectName(name string) string {
return path.Join(s.gcs.Prefix, name)
}
// Write file to storage.
func (s *gcsStorage) Write(ctx context.Context, name string, data []byte) error {
object := s.objectName(name)
wc := s.bucket.Object(object).NewWriter(ctx)
wc.StorageClass = s.gcs.StorageClass
wc.PredefinedACL = s.gcs.PredefinedAcl
_, err := wc.Write(data)
if err != nil {
return errors.Trace(err)
}
return wc.Close()
}
// Read storage file.
func (s *gcsStorage) Read(ctx context.Context, name string) ([]byte, error) {
object := s.objectName(name)
rc, err := s.bucket.Object(object).NewReader(ctx)
if err != nil {
return nil, errors.Trace(err)
}
defer rc.Close()
size := rc.Attrs.Size
var b []byte
if size < 0 {
// happened when using fake-gcs-server in integration test
b, err = ioutil.ReadAll(rc)
} else {
b = make([]byte, size)
_, err = io.ReadFull(rc, b)
}
return b, errors.Trace(err)
}
// FileExists return true if file exists.
func (s *gcsStorage) FileExists(ctx context.Context, name string) (bool, error) {
object := s.objectName(name)
_, err := s.bucket.Object(object).Attrs(ctx)
if err != nil {
if errors.Cause(err) == storage.ErrObjectNotExist { // nolint:errorlint
return false, nil
}
return false, errors.Trace(err)
}
return true, nil
}
// Open a Reader by file path.
func (s *gcsStorage) Open(ctx context.Context, path string) (ReadSeekCloser, error) {
// TODO, implement this if needed
panic("Unsupported Operation")
}
// WalkDir traverse all the files in a dir.
//
// fn is the function called for each regular file visited by WalkDir.
// The first argument is the file path that can be used in `Open`
// function; the second argument is the size in byte of the file determined
// by path.
func (s *gcsStorage) WalkDir(ctx context.Context, opt *WalkOption, fn func(string, int64) error) error {
// TODO, implement this if needed
panic("Unsupported Operation")
}
func (s *gcsStorage) URI() string {
return "gcs://" + s.gcs.Bucket + "/" + s.gcs.Prefix
}
// CreateUploader implenments ExternalStorage interface.
func (s *gcsStorage) CreateUploader(ctx context.Context, name string) (Uploader, error) {
// TODO, implement this if needed
panic("gcs storage not support multi-upload")
}
func newGCSStorage(ctx context.Context, gcs *backup.GCS, opts *ExternalStorageOptions) (*gcsStorage, error) {
var clientOps []option.ClientOption
if gcs.CredentialsBlob == "" {
creds, err := google.FindDefaultCredentials(ctx, storage.ScopeReadWrite)
if err != nil {
return nil, errors.Annotatef(berrors.ErrStorageInvalidConfig, "%v Or you should provide '--gcs.credentials_file'", err)
}
if opts.SendCredentials {
if len(creds.JSON) > 0 {
gcs.CredentialsBlob = string(creds.JSON)
} else {
return nil, errors.Annotate(berrors.ErrStorageInvalidConfig,
"You should provide '--gcs.credentials_file' when '--send-credentials-to-tikv' is true")
}
}
if creds != nil {
clientOps = append(clientOps, option.WithCredentials(creds))
}
} else {
clientOps = append(clientOps, option.WithCredentialsJSON([]byte(gcs.GetCredentialsBlob())))
}
if gcs.Endpoint != "" {
clientOps = append(clientOps, option.WithEndpoint(gcs.Endpoint))
}
if opts.HTTPClient != nil {
clientOps = append(clientOps, option.WithHTTPClient(opts.HTTPClient))
}
client, err := storage.NewClient(ctx, clientOps...)
if err != nil {
return nil, errors.Trace(err)
}
if !opts.SendCredentials {
// Clear the credentials if exists so that they will not be sent to TiKV
gcs.CredentialsBlob = ""
}
bucket := client.Bucket(gcs.Bucket)
// check whether it's a bug before #647, to solve case #2
// If the storage is set as gcs://bucket/prefix/,
// the backupmeta is written correctly to gcs://bucket/prefix/backupmeta,
// but the SSTs are written wrongly to gcs://bucket/prefix//*.sst (note the extra slash).
// see details about case 2 at https://github.com/pingcap/br/issues/675#issuecomment-753780742
sstInPrefix := hasSSTFiles(ctx, bucket, gcs.Prefix)
sstInPrefixSlash := hasSSTFiles(ctx, bucket, gcs.Prefix+"//")
if sstInPrefixSlash && !sstInPrefix {
// This is a old bug, but we must make it compatible.
// so we need find sst in slash directory
gcs.Prefix += "//"
}
if !opts.SkipCheckPath {
// check bucket exists
_, err = bucket.Attrs(ctx)
if err != nil {
return nil, errors.Trace(err)
}
}
return &gcsStorage{gcs: gcs, bucket: bucket}, nil
}
func hasSSTFiles(ctx context.Context, bucket *storage.BucketHandle, prefix string) bool {
query := storage.Query{Prefix: prefix}
_ = query.SetAttrSelection([]string{"Name"})
it := bucket.Objects(ctx, &query)
for {
attrs, err := it.Next()
if err == iterator.Done { // nolint:errorlint
break
}
if err != nil {
log.Warn("failed to list objects on gcs, will use default value for `prefix`", zap.Error(err))
break
}
if strings.HasSuffix(attrs.Name, ".sst") {
log.Info("sst file found in prefix slash", zap.String("file", attrs.Name))
return true
}
}
return false
}