-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
userfile.go
525 lines (455 loc) · 14.9 KB
/
userfile.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package cli
import (
"context"
"database/sql/driver"
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/lexbase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/storage/cloud"
"github.com/cockroachdb/cockroach/pkg/storage/cloudimpl"
"github.com/cockroachdb/errors"
"github.com/spf13/cobra"
)
const (
defaultUserfileScheme = "userfile"
defaultQualifiedNamePrefix = "defaultdb.public.userfiles_"
defaultQualifiedHexNamePrefix = "defaultdb.public.userfilesx_"
tmpSuffix = ".tmp"
fileTableNameSuffix = "_upload_files"
)
var userFileUploadCmd = &cobra.Command{
Use: "upload <source> <destination>",
Short: "upload file from source to destination",
Long: `
Uploads a file to the user scoped file storage using a SQL connection.
`,
Args: cobra.MinimumNArgs(1),
RunE: maybeShoutError(runUserFileUpload),
}
var userFileListCmd = &cobra.Command{
Use: "list <file|dir glob>",
Short: "list files matching the provided pattern",
Long: `
Lists the files stored in the user scoped file storage which match the provided pattern,
using a SQL connection. If no pattern is provided, all files in the specified
(or default, if unspecified) user scoped file storage will be listed.
`,
Args: cobra.MinimumNArgs(0),
RunE: maybeShoutError(runUserFileList),
Aliases: []string{"ls"},
}
var userFileDeleteCmd = &cobra.Command{
Use: "delete <file|dir glob>",
Short: "delete files matching the provided pattern",
Long: `
Deletes the files stored in the user scoped file storage which match the provided pattern,
using a SQL connection. If passed pattern '*', all files in the specified
(or default, if unspecified) user scoped file storage will be deleted. Deletions are not
atomic, and all deletions prior to the first failure will occur.
`,
Args: cobra.MinimumNArgs(1),
RunE: maybeShoutError(runUserFileDelete),
Aliases: []string{"rm"},
}
func runUserFileDelete(cmd *cobra.Command, args []string) error {
conn, err := makeSQLClient("cockroach userfile", useDefaultDb)
if err != nil {
return err
}
defer conn.Close()
glob := args[0]
var deletedFiles []string
if deletedFiles, err = deleteUserFile(context.Background(), conn, glob); err != nil {
return err
}
telemetry.Count("userfile.command.delete")
for _, file := range deletedFiles {
fmt.Printf("successfully deleted %s\n", file)
}
return nil
}
func runUserFileList(cmd *cobra.Command, args []string) error {
conn, err := makeSQLClient("cockroach userfile", useDefaultDb)
if err != nil {
return err
}
defer conn.Close()
var glob string
if len(args) > 0 {
glob = args[0]
}
var files []string
if files, err = listUserFile(context.Background(), conn, glob); err != nil {
return err
}
telemetry.Count("userfile.command.list")
for _, file := range files {
fmt.Println(file)
}
return nil
}
func runUserFileUpload(cmd *cobra.Command, args []string) error {
conn, err := makeSQLClient("cockroach userfile", useDefaultDb)
if err != nil {
return err
}
defer conn.Close()
source := args[0]
var destination string
if len(args) == 2 {
destination = args[1]
}
reader, err := openUserFile(source)
if err != nil {
return err
}
defer reader.Close()
var uploadedFile string
if uploadedFile, err = uploadUserFile(context.Background(), conn, reader, source,
destination); err != nil {
return err
}
telemetry.Count("userfile.command.upload")
fmt.Printf("successfully uploaded to %s\n", uploadedFile)
return nil
}
func openUserFile(source string) (io.ReadCloser, error) {
f, err := os.Open(source)
if err != nil {
return nil, err
}
stat, err := f.Stat()
if err != nil {
return nil, errors.Wrapf(err, "unable to get source file stats for %s", source)
}
if stat.IsDir() {
return nil, fmt.Errorf("source file %s is a directory, not a file", source)
}
return f, nil
}
// getDefaultQualifiedTableName returns the default table name prefix for the
// tables backing userfile.
// To account for all supported usernames, we adopt a naming scheme whereby if
// the normalized username remains unquoted after encoding to a SQL identifier,
// we use it as is. Otherwise we use its hex representation.
//
// This schema gives us the two properties we desire from this table name prefix:
// - Uniqueness amongst users with different usernames.
// - Support for all current and future valid usernames.
func getDefaultQualifiedTableName(user security.SQLUsername) string {
if !lexbase.IsRestrictedSQLIdentQuotedOnEncode(user.Normalized()) {
return defaultQualifiedNamePrefix + user.Normalized()
}
return defaultQualifiedHexNamePrefix + fmt.Sprintf("%x", user.Normalized())
}
// Construct the userfile ExternalStorage URI from CLI args.
func constructUserfileDestinationURI(source, destination string, user security.SQLUsername) string {
// User has not specified a destination URI/path. We use the default URI
// scheme and host, and the basename from the source arg as the path.
if destination == "" {
sourceFilename := path.Base(source)
userFileURL := url.URL{
Scheme: defaultUserfileScheme,
Host: getDefaultQualifiedTableName(user),
Path: sourceFilename,
}
return userFileURL.String()
}
// If the destination is a well-formed userfile URI of the form
// userfile://db.schema.tablename_prefix/path/to/file, then we
// use that as the final URI.
//
// A URI without a host will default to searching in
// `defaultdb.public.userfiles_username`.
var userfileURI *url.URL
var err error
if userfileURI, err = url.ParseRequestURI(destination); err == nil {
if userfileURI.Scheme == defaultUserfileScheme {
if userfileURI.Host == "" {
userfileURI.Host = getDefaultQualifiedTableName(user)
}
return userfileURI.String()
}
}
// If destination is not a well formed userfile URI, we use the default
// userfile URI schema and host, and the destination as the path.
userFileURL := url.URL{
Scheme: defaultUserfileScheme,
Host: getDefaultQualifiedTableName(user),
Path: destination,
}
return userFileURL.String()
}
func constructUserfileListURI(glob string, user security.SQLUsername) string {
// User has not specified a glob pattern and so we construct a URI which will
// list all the files stored in the UserFileTableStorage.
if glob == "" || glob == "*" {
userFileURL := url.URL{
Scheme: defaultUserfileScheme,
Host: getDefaultQualifiedTableName(user),
Path: "",
}
return userFileURL.String()
}
// If the destination is a well-formed userfile URI of the form
// userfile://db.schema.tablename_prefix/glob/pattern, then we
// use that as the final URI.
if userfileURL, err := url.ParseRequestURI(glob); err == nil {
if userfileURL.Scheme == defaultUserfileScheme {
return userfileURL.String()
}
}
// If destination is not a well formed userfile URI, we use the default
// userfile URI schema and host, and the glob as the path.
userfileURL := url.URL{
Scheme: defaultUserfileScheme,
Host: getDefaultQualifiedTableName(user),
Path: glob,
}
return userfileURL.String()
}
func listUserFile(ctx context.Context, conn *sqlConn, glob string) ([]string, error) {
if err := conn.ensureConn(); err != nil {
return nil, err
}
connURL, err := url.Parse(conn.url)
if err != nil {
return nil, err
}
reqUsername, _ := security.MakeSQLUsernameFromUserInput(connURL.User.Username(), security.UsernameValidation)
userfileListURI := constructUserfileListURI(glob, reqUsername)
unescapedUserfileListURI, err := url.PathUnescape(userfileListURI)
if err != nil {
return nil, err
}
userFileTableConf, err := cloudimpl.ExternalStorageConfFromURI(unescapedUserfileListURI, reqUsername)
if err != nil {
return nil, err
}
f, err := cloudimpl.MakeSQLConnFileTableStorage(ctx, userFileTableConf.FileTableConfig,
conn.conn.(cloud.SQLConnI))
if err != nil {
return nil, err
}
return f.ListFiles(ctx, "")
}
func deleteUserFile(ctx context.Context, conn *sqlConn, glob string) ([]string, error) {
if err := conn.ensureConn(); err != nil {
return nil, err
}
connURL, err := url.Parse(conn.url)
if err != nil {
return nil, err
}
reqUsername, _ := security.MakeSQLUsernameFromUserInput(connURL.User.Username(), security.UsernameValidation)
userfileListURI := constructUserfileListURI(glob, reqUsername)
unescapedUserfileListURI, err := url.PathUnescape(userfileListURI)
if err != nil {
return nil, err
}
userFileTableConf, err := cloudimpl.ExternalStorageConfFromURI(unescapedUserfileListURI, reqUsername)
if err != nil {
return nil, err
}
// We zero out the path so that we can provide explicit glob patterns to the
// ListFiles call below. Explicit glob patterns allows us to use the same
// ExternalStorage for both the ListFiles() and Delete() methods.
userFileTableConf.FileTableConfig.Path = ""
f, err := cloudimpl.MakeSQLConnFileTableStorage(ctx, userFileTableConf.FileTableConfig,
conn.conn.(cloud.SQLConnI))
if err != nil {
return nil, err
}
userfileParsedURL, err := url.ParseRequestURI(unescapedUserfileListURI)
if err != nil {
return nil, err
}
files, err := f.ListFiles(ctx, userfileParsedURL.Path)
if err != nil {
return nil, err
}
var deletedFiles []string
for _, file := range files {
var deleteFileBasename string
if userfileParsedURL.Path == "" {
// ListFiles will return absolute userfile URIs which will require
// parsing.
parsedFile, err := url.ParseRequestURI(file)
if err != nil {
return deletedFiles, errors.WithDetailf(err, "deletion failed at %s", file)
}
deleteFileBasename = parsedFile.Path
} else {
// ListFiles returns relative filepaths without a leading /. All files are
// stored with a prefix / in the underlying user scoped tables.
deleteFileBasename = path.Join("/", file)
}
err = f.Delete(ctx, deleteFileBasename)
if err != nil {
return deletedFiles, errors.WithDetail(err, fmt.Sprintf("deletion failed at %s", file))
}
composedTableName := tree.Name(cloudimpl.DefaultQualifiedNamePrefix + connURL.User.Username())
resolvedHost := cloudimpl.DefaultQualifiedNamespace +
// Escape special identifiers as needed.
composedTableName.String()
if userfileParsedURL.Host != "" {
resolvedHost = userfileParsedURL.Host
}
deletedFiles = append(deletedFiles, fmt.Sprintf("userfile://%s%s", resolvedHost, deleteFileBasename))
}
return deletedFiles, nil
}
func renameUserFile(
ctx context.Context, conn *sqlConn, oldFilename,
newFilename, qualifiedTableName string,
) error {
if err := conn.ensureConn(); err != nil {
return err
}
ex := conn.conn.(driver.ExecerContext)
if _, err := ex.ExecContext(ctx, `BEGIN`, nil); err != nil {
return err
}
stmt, err := conn.conn.Prepare(fmt.Sprintf(`UPDATE %s SET filename=$1 WHERE filename=$2`,
qualifiedTableName+fileTableNameSuffix))
if err != nil {
return err
}
defer func() {
if stmt != nil {
_ = stmt.Close()
_, _ = ex.ExecContext(ctx, `ROLLBACK`, nil)
}
}()
_, err = stmt.Exec([]driver.Value{newFilename, oldFilename})
if err != nil {
return err
}
if err := stmt.Close(); err != nil {
return err
}
stmt = nil
if _, err := ex.ExecContext(ctx, `COMMIT`, nil); err != nil {
return err
}
return nil
}
// uploadUserFile is responsible for uploading the local source file to the user
// scoped storage referenced by destination.
// This method returns the complete userfile URI representation to which the
// file is uploaded to.
func uploadUserFile(
ctx context.Context, conn *sqlConn, reader io.Reader, source, destination string,
) (string, error) {
if err := conn.ensureConn(); err != nil {
return "", err
}
ex := conn.conn.(driver.ExecerContext)
if _, err := ex.ExecContext(ctx, `BEGIN`, nil); err != nil {
return "", err
}
connURL, err := url.Parse(conn.url)
if err != nil {
return "", err
}
// Validate the username for creation. We need to do this because
// there is no guarantee that the username in the connection string
// is the same one on the remote machine, and it may contain special
// characters.
// See also: https://github.com/cockroachdb/cockroach/issues/55389
username, err := security.MakeSQLUsernameFromUserInput(connURL.User.Username(), security.UsernameCreation)
if err != nil {
return "", err
}
// Construct the userfile URI as the destination for the CopyIn stmt.
// Currently we hardcode the db.schema prefix, in the future we might allow
// users to specify this.
userfileURI := constructUserfileDestinationURI(source, destination, username)
// Accounts for filenames with arbitrary unicode characters. url.URL escapes
// these characters by default when setting the Path above.
unescapedUserfileURL, err := url.PathUnescape(userfileURI)
// We append a tmp suffix to the filename being uploaded to indicate that the
// upload is still ongoing. This suffix is dropped once the copyTxn running
// the upload commits.
unescapedUserfileURL = unescapedUserfileURL + tmpSuffix
if err != nil {
return "", err
}
stmt, err := conn.conn.Prepare(sql.CopyInFileStmt(unescapedUserfileURL, sql.CrdbInternalName,
sql.UserFileUploadTable))
if err != nil {
return "", err
}
defer func() {
if stmt != nil {
_ = stmt.Close()
_, _ = ex.ExecContext(ctx, `ROLLBACK`, nil)
}
}()
send := make([]byte, chunkSize)
for {
n, err := reader.Read(send)
if n > 0 {
// TODO(adityamaru): Switch to StmtExecContext once the copyin driver
// supports it.
_, err = stmt.Exec([]driver.Value{string(send[:n])})
if err != nil {
return "", err
}
} else if err == io.EOF {
break
} else if err != nil {
return "", err
}
}
if err := stmt.Close(); err != nil {
return "", err
}
stmt = nil
if _, err := ex.ExecContext(ctx, `COMMIT`, nil); err != nil {
return "", err
}
// Drop the .tmp suffix from the filename uploaded to userfile, thereby
// indicating all chunks have been uploaded successfully.
tmpURL, err := url.Parse(unescapedUserfileURL)
if err != nil {
return "", err
}
err = renameUserFile(ctx, conn, tmpURL.Path, strings.TrimSuffix(tmpURL.Path, tmpSuffix),
tmpURL.Host)
if err != nil {
return "", err
}
return strings.TrimSuffix(unescapedUserfileURL, tmpSuffix), nil
}
var userFileCmds = []*cobra.Command{
userFileUploadCmd,
userFileListCmd,
userFileDeleteCmd,
}
var userFileCmd = &cobra.Command{
Use: "userfile [command]",
Short: "upload, list and delete user scoped files",
Long: "Upload, list and delete files from the user scoped file storage.",
RunE: usageAndErr,
}
func init() {
userFileCmd.AddCommand(userFileCmds...)
}