forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3stream.go
286 lines (253 loc) · 8.72 KB
/
s3stream.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
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package s3sessions
import (
"context"
"fmt"
"io"
"net/url"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/session"
awsutils "github.com/gravitational/teleport/lib/utils/aws"
)
// CreateUpload creates a multipart upload
func (h *Handler) CreateUpload(ctx context.Context, sessionID session.ID) (*events.StreamUpload, error) {
start := time.Now()
input := &s3.CreateMultipartUploadInput{
Bucket: aws.String(h.Bucket),
Key: aws.String(h.path(sessionID)),
}
if !h.Config.DisableServerSideEncryption {
input.ServerSideEncryption = aws.String(s3.ServerSideEncryptionAwsKms)
if h.Config.SSEKMSKey != "" {
input.SSEKMSKeyId = aws.String(h.Config.SSEKMSKey)
}
}
if h.Config.ACL != "" {
input.ACL = aws.String(h.Config.ACL)
}
resp, err := h.client.CreateMultipartUploadWithContext(ctx, input)
if err != nil {
return nil, trace.Wrap(awsutils.ConvertS3Error(err), "CreateMultiPartUpload session(%v)", sessionID)
}
h.WithFields(logrus.Fields{
"upload": aws.StringValue(resp.UploadId),
"session": sessionID,
"key": aws.StringValue(resp.Key),
}).Infof("Created upload in %v", time.Since(start))
return &events.StreamUpload{SessionID: sessionID, ID: aws.StringValue(resp.UploadId)}, nil
}
// UploadPart uploads part
func (h *Handler) UploadPart(ctx context.Context, upload events.StreamUpload, partNumber int64, partBody io.ReadSeeker) (*events.StreamPart, error) {
// This upload exceeded maximum number of supported parts, error now.
if partNumber > s3manager.MaxUploadParts {
return nil, trace.LimitExceeded(
"exceeded total allowed S3 limit MaxUploadParts (%d). Adjust PartSize to fit in this limit", s3manager.MaxUploadParts)
}
start := time.Now()
uploadKey := h.path(upload.SessionID)
log := h.WithFields(logrus.Fields{
"upload": upload.ID,
"session": upload.SessionID,
"key": uploadKey,
})
params := &s3.UploadPartInput{
Bucket: aws.String(h.Bucket),
UploadId: aws.String(upload.ID),
Key: aws.String(uploadKey),
Body: partBody,
PartNumber: aws.Int64(partNumber),
}
log.Debugf("Uploading part %v", partNumber)
resp, err := h.client.UploadPartWithContext(ctx, params)
if err != nil {
return nil, trace.Wrap(awsutils.ConvertS3Error(err),
"UploadPart(upload %v) part(%v) session(%v)", upload.ID, partNumber, upload.SessionID)
}
log.Infof("Uploaded part %v in %v", partNumber, time.Since(start))
return &events.StreamPart{ETag: aws.StringValue(resp.ETag), Number: partNumber}, nil
}
func (h *Handler) abortUpload(ctx context.Context, upload events.StreamUpload) error {
uploadKey := h.path(upload.SessionID)
log := h.WithFields(logrus.Fields{
"upload": upload.ID,
"session": upload.SessionID,
"key": uploadKey,
})
req := &s3.AbortMultipartUploadInput{
Bucket: aws.String(h.Bucket),
Key: aws.String(uploadKey),
UploadId: aws.String(upload.ID),
}
log.Debug("Aborting upload")
_, err := h.client.AbortMultipartUploadWithContext(ctx, req)
if err != nil {
return awsutils.ConvertS3Error(err)
}
log.Info("Aborted upload")
return nil
}
// maxPartsPerUpload is the maximum number of parts for a single multipart upload.
// See https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
const maxPartsPerUpload = 10000
// CompleteUpload completes the upload
func (h *Handler) CompleteUpload(ctx context.Context, upload events.StreamUpload, parts []events.StreamPart) error {
if len(parts) == 0 {
return h.abortUpload(ctx, upload)
}
if len(parts) > maxPartsPerUpload {
return trace.BadParameter("too many parts for a single S3 upload (%d), "+
"must be less than %d", len(parts), maxPartsPerUpload)
}
start := time.Now()
uploadKey := h.path(upload.SessionID)
log := h.WithFields(logrus.Fields{
"upload": upload.ID,
"session": upload.SessionID,
"key": uploadKey,
})
// Parts must be sorted in PartNumber order.
sort.Slice(parts, func(i, j int) bool {
return parts[i].Number < parts[j].Number
})
completedParts := make([]*s3.CompletedPart, len(parts))
for i := range parts {
completedParts[i] = &s3.CompletedPart{
ETag: aws.String(parts[i].ETag),
PartNumber: aws.Int64(parts[i].Number),
}
}
log.Debug("Completing upload")
params := &s3.CompleteMultipartUploadInput{
Bucket: aws.String(h.Bucket),
Key: aws.String(uploadKey),
UploadId: aws.String(upload.ID),
MultipartUpload: &s3.CompletedMultipartUpload{Parts: completedParts},
}
_, err := h.client.CompleteMultipartUploadWithContext(ctx, params)
if err != nil {
return trace.Wrap(awsutils.ConvertS3Error(err),
"CompleteMultipartUpload(upload %v) session(%v)", upload.ID, upload.SessionID)
}
log.Infof("Completed upload in %v", time.Since(start))
return nil
}
// ListParts lists upload parts
func (h *Handler) ListParts(ctx context.Context, upload events.StreamUpload) ([]events.StreamPart, error) {
uploadKey := h.path(upload.SessionID)
log := h.WithFields(logrus.Fields{
"upload": upload.ID,
"session": upload.SessionID,
"key": uploadKey,
})
log.Debug("Listing parts for upload")
var parts []events.StreamPart
var partNumberMarker *int64
for i := 0; i < defaults.MaxIterationLimit; i++ {
re, err := h.client.ListPartsWithContext(ctx, &s3.ListPartsInput{
Bucket: aws.String(h.Bucket),
Key: aws.String(uploadKey),
UploadId: aws.String(upload.ID),
PartNumberMarker: partNumberMarker,
})
if err != nil {
return nil, awsutils.ConvertS3Error(err)
}
for _, part := range re.Parts {
parts = append(parts, events.StreamPart{
Number: aws.Int64Value(part.PartNumber),
ETag: aws.StringValue(part.ETag),
})
}
if !aws.BoolValue(re.IsTruncated) {
break
}
partNumberMarker = re.PartNumberMarker
}
// Parts must be sorted in PartNumber order.
sort.Slice(parts, func(i, j int) bool {
return parts[i].Number < parts[j].Number
})
return parts, nil
}
// ListUploads lists uploads that have been initiated but not completed
func (h *Handler) ListUploads(ctx context.Context) ([]events.StreamUpload, error) {
var prefix *string
if h.Path != "" {
trimmed := strings.TrimPrefix(h.Path, "/")
prefix = &trimmed
}
var uploads []events.StreamUpload
var keyMarker *string
var uploadIDMarker *string
for i := 0; i < defaults.MaxIterationLimit; i++ {
input := &s3.ListMultipartUploadsInput{
Bucket: aws.String(h.Bucket),
Prefix: prefix,
KeyMarker: keyMarker,
UploadIdMarker: uploadIDMarker,
}
re, err := h.client.ListMultipartUploadsWithContext(ctx, input)
if err != nil {
return nil, awsutils.ConvertS3Error(err)
}
for _, upload := range re.Uploads {
uploads = append(uploads, events.StreamUpload{
ID: aws.StringValue(upload.UploadId),
SessionID: h.fromPath(aws.StringValue(upload.Key)),
Initiated: aws.TimeValue(upload.Initiated),
})
}
if !aws.BoolValue(re.IsTruncated) {
break
}
keyMarker = re.KeyMarker
uploadIDMarker = re.UploadIdMarker
}
sort.Slice(uploads, func(i, j int) bool {
return uploads[i].Initiated.Before(uploads[j].Initiated)
})
return uploads, nil
}
// GetUploadMetadata gets the metadata for session upload
func (h *Handler) GetUploadMetadata(sessionID session.ID) events.UploadMetadata {
sessionURL, err := url.JoinPath(teleport.SchemeS3+"://"+h.Bucket, h.Path, sessionID.String())
if err != nil {
// this should never happen, but if it does revert to legacy behavior
// which omitted h.Path
sessionURL = fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, h.Bucket, sessionID)
}
return events.UploadMetadata{
URL: sessionURL,
SessionID: sessionID,
}
}
// ReserveUploadPart reserves an upload part.
func (h *Handler) ReserveUploadPart(ctx context.Context, upload events.StreamUpload, partNumber int64) error {
return nil
}