-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
s3.go
289 lines (251 loc) · 8.15 KB
/
s3.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
283
284
285
286
287
288
289
// Package s3 implements media interface by storing media objects in Amazon S3 bucket.
package s3
import (
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/tinode/chat/server/logs"
"github.com/tinode/chat/server/media"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
)
const (
defaultServeURL = "/v0/file/s/"
handlerName = "s3"
// Presign GET URLs for this number of seconds.
presignDuration = 120
)
type awsconfig struct {
AccessKeyId string `json:"access_key_id"`
SecretAccessKey string `json:"secret_access_key"`
Region string `json:"region"`
DisableSSL bool `json:"disable_ssl"`
ForcePathStyle bool `json:"force_path_style"`
Endpoint string `json:"endpoint"`
BucketName string `json:"bucket"`
CorsOrigins []string `json:"cors_origins"`
ServeURL string `json:"serve_url"`
}
type awshandler struct {
svc *s3.S3
conf awsconfig
}
// readerCounter is a byte counter for bytes read through the io.Reader
type readerCounter struct {
io.Reader
count int64
reader io.Reader
}
// Read reads the bytes and records the number of read bytes.
func (rc *readerCounter) Read(buf []byte) (int, error) {
n, err := rc.reader.Read(buf)
atomic.AddInt64(&rc.count, int64(n))
return n, err
}
// Init initializes the media handler.
func (ah *awshandler) Init(jsconf string) error {
var err error
if err = json.Unmarshal([]byte(jsconf), &ah.conf); err != nil {
return errors.New("failed to parse config: " + err.Error())
}
if ah.conf.AccessKeyId == "" {
return errors.New("missing Access Key ID")
}
if ah.conf.SecretAccessKey == "" {
return errors.New("missing Secret Access Key")
}
if ah.conf.Region == "" {
return errors.New("missing Region")
}
if ah.conf.BucketName == "" {
return errors.New("missing Bucket")
}
if ah.conf.ServeURL == "" {
ah.conf.ServeURL = defaultServeURL
}
var sess *session.Session
if sess, err = session.NewSession(&aws.Config{
Region: aws.String(ah.conf.Region),
DisableSSL: aws.Bool(ah.conf.DisableSSL),
S3ForcePathStyle: aws.Bool(ah.conf.ForcePathStyle),
Endpoint: aws.String(ah.conf.Endpoint),
Credentials: credentials.NewStaticCredentials(ah.conf.AccessKeyId, ah.conf.SecretAccessKey, ""),
}); err != nil {
return err
}
// Create S3 service client
ah.svc = s3.New(sess)
// Check if bucket already exists.
_, err = ah.svc.HeadBucket(&s3.HeadBucketInput{Bucket: aws.String(ah.conf.BucketName)})
if err == nil {
// Bucket exists
return nil
}
if aerr, ok := err.(awserr.Error); !ok || aerr.Code() != s3.ErrCodeNoSuchBucket {
// Hard error.
return err
}
// Bucket does not exist. Create one.
_, err = ah.svc.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(ah.conf.BucketName)})
if err != nil {
// Check if someone has already created a bucket (possible in a cluster).
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == s3.ErrCodeBucketAlreadyExists ||
aerr.Code() == s3.ErrCodeBucketAlreadyOwnedByYou ||
// Someone is already creating this bucket:
// OperationAborted: A conflicting conditional operation is currently in progress against this resource.
aerr.Code() == "OperationAborted" {
// Clear benign error
err = nil
}
}
} else {
// This is a new bucket.
// The following serves two purposes:
// 1. Setup CORS policy to be able to serve media directly from S3.
// 2. Verify that the bucket is accessible to the current user.
origins := ah.conf.CorsOrigins
if len(origins) == 0 {
origins = append(origins, "*")
}
_, err = ah.svc.PutBucketCors(&s3.PutBucketCorsInput{
Bucket: aws.String(ah.conf.BucketName),
CORSConfiguration: &s3.CORSConfiguration{
CORSRules: []*s3.CORSRule{{
AllowedMethods: aws.StringSlice([]string{http.MethodGet, http.MethodHead}),
AllowedOrigins: aws.StringSlice(origins),
AllowedHeaders: aws.StringSlice([]string{"*"}),
}},
},
})
}
return err
}
// Headers redirects GET, HEAD requests to the AWS server.
func (ah *awshandler) Headers(req *http.Request, serve bool) (http.Header, int, error) {
if req.Method == http.MethodPut || req.Method == http.MethodPost {
return nil, 0, nil
}
if headers, status := media.CORSHandler(req, ah.conf.CorsOrigins, serve); status != 0 {
return headers, status, nil
}
fid := ah.GetIdFromUrl(req.URL.String())
if fid.IsZero() {
return nil, 0, types.ErrNotFound
}
fd, err := ah.getFileRecord(fid)
if err != nil {
return nil, 0, err
}
var awsReq *request.Request
if req.Method == http.MethodGet {
awsReq, _ = ah.svc.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(ah.conf.BucketName),
Key: aws.String(fid.String32()),
ResponseContentType: aws.String(fd.MimeType),
})
} else if req.Method == http.MethodHead {
awsReq, _ = ah.svc.HeadObjectRequest(&s3.HeadObjectInput{
Bucket: aws.String(ah.conf.BucketName),
Key: aws.String(fid.String32()),
})
}
if awsReq != nil {
// Return presigned URL. The URL will stop working after a short period of time to prevent use of Tinode
// as a free file server.
url, err := awsReq.Presign(time.Second * presignDuration)
headers := map[string][]string{
"Location": []string{url},
"Content-Type": []string{"application/json; charset=utf-8"},
"Cache-Control": []string{"no-cache, no-store, must-revalidate"},
}
return headers, http.StatusTemporaryRedirect, err
}
return nil, 0, nil
}
// Upload processes request for a file upload. The file is given as io.Reader.
func (ah *awshandler) Upload(fdef *types.FileDef, file io.ReadSeeker) (string, error) {
var err error
key := fdef.Uid().String32()
fdef.Location = key
uploader := s3manager.NewUploaderWithClient(ah.svc)
if err = store.Files.StartUpload(fdef); err != nil {
logs.Warn.Println("failed to create file record", fdef.Id, err)
return "", err
}
rc := readerCounter{reader: file}
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(ah.conf.BucketName),
Key: aws.String(key),
Body: &rc,
})
if err != nil {
store.Files.FinishUpload(fdef.Id, false, 0)
return "", err
}
fdef, err = store.Files.FinishUpload(fdef.Id, true, rc.count)
if err != nil {
// Best effort. Error ignored.
ah.svc.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(ah.conf.BucketName),
Key: aws.String(key),
})
return "", err
}
fname := fdef.Id
ext, _ := mime.ExtensionsByType(fdef.MimeType)
if len(ext) > 0 {
fname += ext[0]
}
logs.Info.Println("aws upload success ", fname, "key", key, "id", fdef.Id)
return ah.conf.ServeURL + fname, nil
}
// Download processes request for file download.
// The returned ReadSeekCloser must be closed after use.
func (ah *awshandler) Download(url string) (*types.FileDef, media.ReadSeekCloser, error) {
return nil, nil, types.ErrUnsupported
}
// Delete deletes files from aws by provided slice of locations.
func (ah *awshandler) Delete(locations []string) error {
toDelete := make([]s3manager.BatchDeleteObject, len(locations))
for i, key := range locations {
toDelete[i] = s3manager.BatchDeleteObject{
Object: &s3.DeleteObjectInput{
Key: aws.String(key),
Bucket: aws.String(ah.conf.BucketName),
}}
}
batcher := s3manager.NewBatchDeleteWithClient(ah.svc)
return batcher.Delete(aws.BackgroundContext(), &s3manager.DeleteObjectsIterator{
Objects: toDelete,
})
}
// GetIdFromUrl converts an attahment URL to a file UID.
func (ah *awshandler) GetIdFromUrl(url string) types.Uid {
return media.GetIdFromUrl(url, ah.conf.ServeURL)
}
// getFileRecord given file ID reads file record from the database.
func (ah *awshandler) getFileRecord(fid types.Uid) (*types.FileDef, error) {
fd, err := store.Files.Get(fid.String())
if err != nil {
return nil, err
}
if fd == nil {
return nil, types.ErrNotFound
}
return fd, nil
}
func init() {
store.RegisterMediaHandler(handlerName, &awshandler{})
}