-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathshow.go
448 lines (409 loc) · 13.4 KB
/
show.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
// Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package backupccl
import (
"context"
"net/url"
"path"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql"
descpb "github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/storage/cloudimpl"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
)
// showBackupPlanHook implements PlanHookFn.
func showBackupPlanHook(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (sql.PlanHookRowFn, sqlbase.ResultColumns, []sql.PlanNode, bool, error) {
backup, ok := stmt.(*tree.ShowBackup)
if !ok {
return nil, nil, nil, false, nil
}
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, p.ExecCfg().ClusterID(), p.ExecCfg().Organization(), "SHOW BACKUP",
); err != nil {
return nil, nil, nil, false, err
}
if err := p.RequireAdminRole(ctx, "SHOW BACKUP"); err != nil {
return nil, nil, nil, false, err
}
if backup.Path == nil && backup.InCollection != nil {
return showBackupsInCollectionPlanHook(ctx, backup, p)
}
toFn, err := p.TypeAsString(ctx, backup.Path, "SHOW BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
var inColFn func() (string, error)
if backup.InCollection != nil {
inColFn, err = p.TypeAsString(ctx, backup.InCollection, "SHOW BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
}
expected := map[string]sql.KVStringOptValidate{
backupOptEncPassphrase: sql.KVStringOptRequireValue,
backupOptEncKMS: sql.KVStringOptRequireValue,
backupOptWithPrivileges: sql.KVStringOptRequireNoValue,
}
optsFn, err := p.TypeAsStringOpts(ctx, backup.Options, expected)
if err != nil {
return nil, nil, nil, false, err
}
opts, err := optsFn()
if err != nil {
return nil, nil, nil, false, err
}
var shower backupShower
switch backup.Details {
case tree.BackupRangeDetails:
shower = backupShowerRanges
case tree.BackupFileDetails:
shower = backupShowerFiles
default:
shower = backupShowerDefault(ctx, p, backup.ShouldIncludeSchemas, opts)
}
fn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
// TODO(dan): Move this span into sql.
ctx, span := tracing.ChildSpan(ctx, stmt.StatementTag())
defer tracing.FinishSpan(span)
str, err := toFn()
if err != nil {
return err
}
if inColFn != nil {
collection, err := inColFn()
if err != nil {
return err
}
parsed, err := url.Parse(collection)
if err != nil {
return err
}
parsed.Path = path.Join(parsed.Path, str)
str = parsed.String()
}
store, err := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, str, p.User())
if err != nil {
return errors.Wrapf(err, "make storage")
}
defer store.Close()
var encryption *jobspb.BackupEncryptionOptions
if passphrase, ok := opts[backupOptEncPassphrase]; ok {
opts, err := readEncryptionOptions(ctx, store)
if err != nil {
return err
}
encryptionKey := storageccl.GenerateKey([]byte(passphrase), opts.Salt)
encryption = &jobspb.BackupEncryptionOptions{Mode: jobspb.EncryptionMode_Passphrase,
Key: encryptionKey}
} else if kms, ok := opts[backupOptEncKMS]; ok {
opts, err := readEncryptionOptions(ctx, store)
if err != nil {
return err
}
env := &backupKMSEnv{p.ExecCfg().Settings, &p.ExecCfg().ExternalIODirConfig}
defaultKMSInfo, err := validateKMSURIsAgainstFullBackup([]string{kms},
newEncryptedDataKeyMapFromProtoMap(opts.EncryptedDataKeyByKMSMasterKeyID), env)
if err != nil {
return err
}
encryption = &jobspb.BackupEncryptionOptions{
Mode: jobspb.EncryptionMode_KMS,
KMSInfo: defaultKMSInfo}
}
incPaths, err := findPriorBackups(ctx, store)
if err != nil {
if errors.Is(err, cloudimpl.ErrListingUnsupported) {
// If we do not support listing, we have to just assume there are none
// and show the specified base.
log.Warningf(ctx, "storage sink %T does not support listing, only resolving the base backup", store)
incPaths = nil
} else {
return err
}
}
manifests := make([]BackupManifest, len(incPaths)+1)
manifests[0], err = readBackupManifestFromStore(ctx, store, encryption)
if err != nil {
return err
}
for i := range incPaths {
m, err := readBackupManifest(ctx, store, incPaths[i], encryption)
if err != nil {
return err
}
// Blank the stats to prevent memory blowup.
m.DeprecatedStatistics = nil
manifests[i+1] = m
}
// If we are restoring a backup with old-style foreign keys, skip over the
// FKs for which we can't resolve the cross-table references. We can't
// display them anyway, because we don't have the referenced table names,
// etc.
if err := maybeUpgradeTableDescsInBackupManifests(
ctx, manifests, p.ExecCfg().Codec, true, /*skipFKsWithNoMatchingTable*/
); err != nil {
return err
}
datums, err := shower.fn(manifests)
if err != nil {
return err
}
for _, row := range datums {
select {
case <-ctx.Done():
return ctx.Err()
case resultsCh <- row:
}
}
return nil
}
return fn, shower.header, nil, false, nil
}
type backupShower struct {
header sqlbase.ResultColumns
fn func([]BackupManifest) ([]tree.Datums, error)
}
func backupShowerHeaders(showSchemas bool, opts map[string]string) sqlbase.ResultColumns {
baseHeaders := sqlbase.ResultColumns{
{Name: "database_name", Typ: types.String},
{Name: "table_name", Typ: types.String},
{Name: "start_time", Typ: types.Timestamp},
{Name: "end_time", Typ: types.Timestamp},
{Name: "size_bytes", Typ: types.Int},
{Name: "rows", Typ: types.Int},
{Name: "is_full_cluster", Typ: types.Bool},
}
if showSchemas {
baseHeaders = append(baseHeaders, sqlbase.ResultColumn{Name: "create_statement", Typ: types.String})
}
if _, shouldShowPrivleges := opts[backupOptWithPrivileges]; shouldShowPrivleges {
baseHeaders = append(baseHeaders, sqlbase.ResultColumn{Name: "privileges", Typ: types.String})
}
return baseHeaders
}
func backupShowerDefault(
ctx context.Context, p sql.PlanHookState, showSchemas bool, opts map[string]string,
) backupShower {
return backupShower{
header: backupShowerHeaders(showSchemas, opts),
fn: func(manifests []BackupManifest) ([]tree.Datums, error) {
var rows []tree.Datums
for _, manifest := range manifests {
descs := make(map[descpb.ID]string)
for i := range manifest.Descriptors {
descriptor := &manifest.Descriptors[i]
if descriptor.GetDatabase() != nil {
id := sqlbase.GetDescriptorID(descriptor)
if _, ok := descs[id]; !ok {
descs[id] = sqlbase.GetDescriptorName(descriptor)
}
}
}
descSizes := make(map[descpb.ID]RowCount)
for _, file := range manifest.Files {
// TODO(dan): This assumes each file in the backup only contains
// data from a single table, which is usually but not always
// correct. It does not account for interleaved tables or if a
// BACKUP happened to catch a newly created table that hadn't yet
// been split into its own range.
_, tableID, err := encoding.DecodeUvarintAscending(file.Span.Key)
if err != nil {
continue
}
s := descSizes[descpb.ID(tableID)]
s.add(file.EntryCounts)
descSizes[descpb.ID(tableID)] = s
}
start := tree.DNull
end, err := tree.MakeDTimestamp(timeutil.Unix(0, manifest.EndTime.WallTime), time.Nanosecond)
if err != nil {
return nil, err
}
if manifest.StartTime.WallTime != 0 {
start, err = tree.MakeDTimestamp(timeutil.Unix(0, manifest.StartTime.WallTime), time.Nanosecond)
if err != nil {
return nil, err
}
}
var row tree.Datums
for i := range manifest.Descriptors {
descriptor := &manifest.Descriptors[i]
if table := sqlbase.TableFromDescriptor(descriptor, hlc.Timestamp{}); table != nil {
dbName := descs[table.ParentID]
row = tree.Datums{
tree.NewDString(dbName),
tree.NewDString(table.Name),
start,
end,
tree.NewDInt(tree.DInt(descSizes[table.ID].DataSize)),
tree.NewDInt(tree.DInt(descSizes[table.ID].Rows)),
tree.MakeDBool(manifest.DescriptorCoverage == tree.AllDescriptors),
}
if showSchemas {
displayOptions := sql.ShowCreateDisplayOptions{
FKDisplayMode: sql.OmitMissingFKClausesFromCreate,
IgnoreComments: true,
}
schema, err := p.ShowCreate(ctx, dbName, manifest.Descriptors,
sqlbase.NewImmutableTableDescriptor(*table), displayOptions)
if err != nil {
continue
}
row = append(row, tree.NewDString(schema))
}
if _, shouldShowPrivileges := opts[backupOptWithPrivileges]; shouldShowPrivileges {
row = append(row, tree.NewDString(showPrivileges(descriptor)))
}
rows = append(rows, row)
}
}
for _, t := range manifest.Tenants {
rows = append(rows, tree.Datums{
tree.NewDString("TENANT"),
tree.NewDString(roachpb.MakeTenantID(t.ID).String()),
start,
end,
tree.DNull,
tree.DNull,
tree.DNull,
})
}
}
return rows, nil
},
}
}
func showPrivileges(descriptor *descpb.Descriptor) string {
var privStringBuilder strings.Builder
var privDesc *descpb.PrivilegeDescriptor
if db := descriptor.GetDatabase(); db != nil {
privDesc = db.GetPrivileges()
} else if table := sqlbase.TableFromDescriptor(descriptor, hlc.Timestamp{}); table != nil {
privDesc = table.GetPrivileges()
}
if privDesc == nil {
return ""
}
for _, userPriv := range privDesc.Show() {
user := userPriv.User
privs := userPriv.Privileges
privStringBuilder.WriteString("GRANT ")
if len(privs) == 0 {
continue
}
for j, priv := range privs {
if j != 0 {
privStringBuilder.WriteString(", ")
}
privStringBuilder.WriteString(priv)
}
privStringBuilder.WriteString(" ON ")
privStringBuilder.WriteString(sqlbase.GetDescriptorName(descriptor))
privStringBuilder.WriteString(" TO ")
privStringBuilder.WriteString(user)
privStringBuilder.WriteString("; ")
}
return privStringBuilder.String()
}
var backupShowerRanges = backupShower{
header: sqlbase.ResultColumns{
{Name: "start_pretty", Typ: types.String},
{Name: "end_pretty", Typ: types.String},
{Name: "start_key", Typ: types.Bytes},
{Name: "end_key", Typ: types.Bytes},
},
fn: func(manifests []BackupManifest) (rows []tree.Datums, err error) {
for _, manifest := range manifests {
for _, span := range manifest.Spans {
rows = append(rows, tree.Datums{
tree.NewDString(span.Key.String()),
tree.NewDString(span.EndKey.String()),
tree.NewDBytes(tree.DBytes(span.Key)),
tree.NewDBytes(tree.DBytes(span.EndKey)),
})
}
}
return rows, nil
},
}
var backupShowerFiles = backupShower{
header: sqlbase.ResultColumns{
{Name: "path", Typ: types.String},
{Name: "start_pretty", Typ: types.String},
{Name: "end_pretty", Typ: types.String},
{Name: "start_key", Typ: types.Bytes},
{Name: "end_key", Typ: types.Bytes},
{Name: "size_bytes", Typ: types.Int},
{Name: "rows", Typ: types.Int},
},
fn: func(manifests []BackupManifest) (rows []tree.Datums, err error) {
for _, manifest := range manifests {
for _, file := range manifest.Files {
rows = append(rows, tree.Datums{
tree.NewDString(file.Path),
tree.NewDString(file.Span.Key.String()),
tree.NewDString(file.Span.EndKey.String()),
tree.NewDBytes(tree.DBytes(file.Span.Key)),
tree.NewDBytes(tree.DBytes(file.Span.EndKey)),
tree.NewDInt(tree.DInt(file.EntryCounts.DataSize)),
tree.NewDInt(tree.DInt(file.EntryCounts.Rows)),
})
}
}
return rows, nil
},
}
// showBackupPlanHook implements PlanHookFn.
func showBackupsInCollectionPlanHook(
ctx context.Context, backup *tree.ShowBackup, p sql.PlanHookState,
) (sql.PlanHookRowFn, sqlbase.ResultColumns, []sql.PlanNode, bool, error) {
toFn, err := p.TypeAsString(ctx, backup.InCollection, "SHOW BACKUPS")
if err != nil {
return nil, nil, nil, false, err
}
fn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
ctx, span := tracing.ChildSpan(ctx, backup.StatementTag())
defer tracing.FinishSpan(span)
dst, err := toFn()
if err != nil {
return err
}
store, err := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, dst, p.User())
if err != nil {
return errors.Wrapf(err, "connect to external storage")
}
defer store.Close()
res, err := store.ListFiles(ctx, "/*/*/BACKUP")
if err != nil {
return err
}
for _, i := range res {
resultsCh <- tree.Datums{tree.NewDString(strings.TrimSuffix(i, "/BACKUP"))}
}
return nil
}
return fn, sqlbase.ResultColumns{{Name: "path", Typ: types.String}}, nil, false, nil
}
func init() {
sql.AddPlanHook(showBackupPlanHook)
}