-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.go
234 lines (203 loc) · 5.13 KB
/
lib.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
package blobfs
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/pkg/errors"
gcaws "gocloud.dev/aws"
"gocloud.dev/blob"
_ "gocloud.dev/blob/fileblob"
_ "gocloud.dev/blob/memblob"
"gocloud.dev/blob/s3blob"
)
const (
awsRoleArn = "AWS_ROLE_ARN"
awsWebIdentityTokenFile = "AWS_WEB_IDENTITY_TOKEN_FILE"
)
type BlobFS struct {
storageURL string
prefix string
CACert []byte
}
func New(storageURL string, prefix ...string) *BlobFS {
var bucketPrefix string
if len(prefix) > 0 {
bucketPrefix = prefix[0]
}
return &BlobFS{
storageURL: storageURL,
prefix: bucketPrefix,
}
}
var _ Interface = (*BlobFS)(nil)
func NewInMemoryFS() Interface {
return New("mem://")
}
func NewOsFs() Interface {
return New("file:///")
}
func (fs *BlobFS) WriteFile(ctx context.Context, filepath string, data []byte) error {
dir, filename := path.Split(filepath)
bucket, err := fs.OpenBucket(ctx, dir)
if err != nil {
return err
}
defer bucket.Close()
w, err := bucket.NewWriter(ctx, filename, &blob.WriterOptions{
DisableContentTypeDetection: true,
})
if err != nil {
return err
}
_, writeErr := w.Write(data)
// Always check the return value of Close when writing.
closeErr := w.Close()
if writeErr != nil {
return writeErr
}
if closeErr != nil {
return closeErr
}
return nil
}
func (fs *BlobFS) ReadFile(ctx context.Context, filepath string) ([]byte, error) {
dir, filename := path.Split(filepath)
bucket, err := fs.OpenBucket(ctx, dir)
if err != nil {
return nil, err
}
defer bucket.Close()
// Open the key "foo.txt" for reading with the default options.
r, err := bucket.NewReader(ctx, filename, nil)
if err != nil {
return nil, err
}
defer r.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (fs *BlobFS) DeleteFile(ctx context.Context, filepath string) error {
dir, filename := path.Split(filepath)
bucket, err := fs.OpenBucket(ctx, dir)
if err != nil {
return err
}
defer bucket.Close()
return bucket.Delete(context.TODO(), filename)
}
func (fs *BlobFS) Exists(ctx context.Context, filepath string) (bool, error) {
dir, filename := path.Split(filepath)
bucket, err := fs.OpenBucket(ctx, dir)
if err != nil {
return false, err
}
defer bucket.Close()
return bucket.Exists(context.TODO(), filename)
}
func (fs *BlobFS) SignedURL(ctx context.Context, filepath string, opts *blob.SignedURLOptions) (string, error) {
dir, filename := path.Split(filepath)
bucket, err := fs.OpenBucket(ctx, dir)
if err != nil {
return "", err
}
defer bucket.Close()
return bucket.SignedURL(ctx, filename, opts)
}
func (fs *BlobFS) OpenBucket(ctx context.Context, dir string) (*blob.Bucket, error) {
var bucket *blob.Bucket
u, err := url.Parse(fs.storageURL)
if err != nil {
return nil, err
}
if u.Scheme == s3blob.Scheme {
sess, rest, err := gcaws.NewSessionFromURLParams(u.Query())
if err != nil {
return nil, fmt.Errorf("open bucket %v: %v", u, err)
}
configProvider := &gcaws.ConfigOverrider{
Base: sess,
}
overrideCfg, err := gcaws.ConfigFromURLParams(rest)
if err != nil {
return nil, fmt.Errorf("open bucket %v: %v", u, err)
}
var insecureTLS bool
if overrideCfg.Endpoint != nil {
u, err := url.Parse(*overrideCfg.Endpoint)
if err != nil {
return nil, err
}
// use InsecureSkipVerify, if IP address is used for baseURL host
if ip := net.ParseIP(u.Hostname()); ip != nil && u.Scheme == "https" {
insecureTLS = true
}
}
if err := configureTLS(overrideCfg, fs.CACert, insecureTLS); err != nil {
return nil, err
}
configProvider.Configs = append(configProvider.Configs, overrideCfg)
bucket, err = s3blob.OpenBucket(ctx, configProvider, u.Host, nil)
if err != nil {
return nil, err
}
} else {
bucket, err = blob.OpenBucket(ctx, fs.storageURL)
if err != nil {
return nil, err
}
}
prefix := strings.Trim(path.Join(fs.prefix, dir), "/") + "/"
if prefix == string(os.PathSeparator) {
return bucket, nil
}
return blob.PrefixedBucket(bucket, prefix), nil
}
func configureTLS(config *aws.Config, caCert []byte, insecureTLS bool) error {
tlsConfig := &tls.Config{
InsecureSkipVerify: insecureTLS,
}
if caCert != nil {
caCertPool := x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
return fmt.Errorf("failed to parse CA certificate")
}
tlsConfig.RootCAs = caCertPool
}
defaultHTTPTransport := http.DefaultTransport.(*http.Transport).Clone()
defaultHTTPTransport.TLSClientConfig = tlsConfig
config.HTTPClient = &http.Client{
Transport: defaultHTTPTransport,
}
return nil
}
func CreateBucketURL(bucketURL, endpoint, region string) string {
u, err := url.Parse(bucketURL)
if err != nil {
panic(errors.Wrapf(err, "invalid bucket URL %s", bucketURL))
}
if u.Scheme == s3blob.Scheme {
values := u.Query()
values.Set("s3ForcePathStyle", "true")
if endpoint != "" {
values.Set("endpoint", endpoint)
}
if region != "" {
values.Set("region", region)
}
u.RawQuery = values.Encode()
}
return u.String()
}