-
Notifications
You must be signed in to change notification settings - Fork 219
/
list.go
executable file
·494 lines (431 loc) · 17.4 KB
/
list.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
// Copyright © 2017 Microsoft <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cmd
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/lease"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/Azure/azure-storage-azcopy/v10/common"
"github.com/Azure/azure-storage-azcopy/v10/ste"
)
type rawListCmdArgs struct {
// obtained from argument
src string
location string
Properties string
MachineReadable bool
RunningTally bool
MegaUnits bool
trailingDot string
}
type validProperty string
const (
LastModifiedTime validProperty = "LastModifiedTime"
VersionId validProperty = "VersionId"
BlobType validProperty = "BlobType"
BlobAccessTier validProperty = "BlobAccessTier"
ContentType validProperty = "ContentType"
ContentEncoding validProperty = "ContentEncoding"
ContentMD5 validProperty = "ContentMD5"
LeaseState validProperty = "LeaseState"
LeaseDuration validProperty = "LeaseDuration"
LeaseStatus validProperty = "LeaseStatus"
ArchiveStatus validProperty = "ArchiveStatus"
versionIdTimeFormat = "2006-01-02T15:04:05.9999999Z"
LastModifiedTimeFormat = "2006-01-02 15:04:05 +0000 GMT"
)
// containsProperty checks if the property array contains a valid property
func containsProperty(properties []validProperty, prop validProperty) bool {
for _, item := range properties {
if item == prop {
return true
}
}
return false
}
// validProperties returns an array of possible values for the validProperty const type.
func validProperties() []validProperty {
return []validProperty{LastModifiedTime, VersionId, BlobType, BlobAccessTier,
ContentType, ContentEncoding, ContentMD5, LeaseState, LeaseDuration, LeaseStatus, ArchiveStatus}
}
// validPropertiesString returns an array of valid properties in string array.
func validPropertiesString() []string {
var propertiesArray []string
for _, prop := range validProperties() {
propertiesArray = append(propertiesArray, string(prop))
}
return propertiesArray
}
func (raw rawListCmdArgs) parseProperties() []validProperty {
parsedProperties := make([]validProperty, 0)
if raw.Properties != "" {
listProperties := strings.Split(raw.Properties, ";")
for _, p := range listProperties {
for _, vp := range validProperties() {
// check for empty string and also ignore the case
if len(p) != 0 && strings.EqualFold(string(vp), p) {
parsedProperties = append(parsedProperties, vp)
break
}
}
}
}
return parsedProperties
}
func (raw rawListCmdArgs) cook() (cookedListCmdArgs, error) {
// set up the front end scanning logger
azcopyScanningLogger = common.NewJobLogger(azcopyCurrentJobID, azcopyLogVerbosity, azcopyLogPathFolder, "-scanning")
azcopyScanningLogger.OpenLog()
glcm.RegisterCloseFunc(func() {
azcopyScanningLogger.CloseLog()
})
cooked = cookedListCmdArgs{}
// the expected argument in input is the container sas / or path of virtual directory in the container.
// verifying the location type
var err error
cooked.location, err = ValidateArgumentLocation(raw.src, raw.location)
if err != nil {
return cooked, err
}
// Only support listing for Azure locations
switch cooked.location {
case common.ELocation.Blob():
case common.ELocation.File():
case common.ELocation.BlobFS():
break
default:
return cooked, fmt.Errorf("azcopy only supports Azure resources for listing i.e. Blob, File, BlobFS")
}
cooked.sourcePath = raw.src
cooked.MachineReadable = raw.MachineReadable
cooked.RunningTally = raw.RunningTally
cooked.MegaUnits = raw.MegaUnits
err = cooked.trailingDot.Parse(raw.trailingDot)
if err != nil {
return cooked, err
}
cooked.properties = raw.parseProperties()
return cooked, nil
}
type cookedListCmdArgs struct {
sourcePath string
location common.Location
properties []validProperty
MachineReadable bool
RunningTally bool
MegaUnits bool
trailingDot common.TrailingDotOption
}
var raw rawListCmdArgs
var cooked cookedListCmdArgs
func init() {
raw = rawListCmdArgs{}
// listContainerCmd represents the list container command
// listContainer list the blobs inside the container or virtual directory inside the container
listContainerCmd := &cobra.Command{
Use: "list [containerURL]",
Aliases: []string{"ls"},
Short: listCmdShortDescription,
Long: listCmdLongDescription,
Example: listCmdExample,
Args: func(cmd *cobra.Command, args []string) error {
// the listContainer command requires necessarily to have an argument
// If no argument is passed then it is not valid
// lsc expects the container path / virtual directory
if len(args) != 1 {
return errors.New("this command only requires container destination")
}
raw.src = args[0]
return nil
},
Run: func(cmd *cobra.Command, args []string) {
cooked, err := raw.cook()
if err != nil {
glcm.Error("failed to parse user input due to error: " + err.Error())
return
}
err = cooked.handleListContainerCommand()
if err == nil {
glcm.Exit(nil, common.EExitCode.Success())
} else {
glcm.Error(err.Error() + getErrorCodeUrl(err))
}
},
}
listContainerCmd.PersistentFlags().StringVar(&raw.location, "location", "", "Optionally specifies the location. For Example: Blob, File, BlobFS")
listContainerCmd.PersistentFlags().BoolVar(&raw.MachineReadable, "machine-readable", false, "False by default. Lists file sizes in bytes.")
listContainerCmd.PersistentFlags().BoolVar(&raw.RunningTally, "running-tally", false, "False by default. Counts the total number of files and their sizes.")
listContainerCmd.PersistentFlags().BoolVar(&raw.MegaUnits, "mega-units", false, "False by default. Displays units in orders of 1000, not 1024.")
listContainerCmd.PersistentFlags().StringVar(&raw.Properties, "properties", "", "Properties to be displayed in list output. "+
"Possible properties include: "+strings.Join(validPropertiesString(), ", ")+". "+
"Delimiter (;) should be used to separate multiple values of properties (i.e. 'LastModifiedTime;VersionId;BlobType').")
listContainerCmd.PersistentFlags().StringVar(&raw.trailingDot, "trailing-dot", "", "'Enable' by default to treat file share related operations in a safe manner. Available options: "+strings.Join(common.ValidTrailingDotOptions(), ", ")+". "+
"Choose 'Disable' to go back to legacy (potentially unsafe) treatment of trailing dot files where the file service will trim any trailing dots in paths. This can result in potential data corruption if the transfer contains two paths that differ only by a trailing dot (ex: mypath and mypath.). If this flag is set to 'Disable' and AzCopy encounters a trailing dot file, it will warn customers in the scanning log but will not attempt to abort the operation."+
"If the destination does not support trailing dot files (Windows or Blob Storage), AzCopy will fail if the trailing dot file is the root of the transfer and skip any trailing dot paths encountered during enumeration.")
rootCmd.AddCommand(listContainerCmd)
}
// handleListContainerCommand handles the list container command
func (cooked cookedListCmdArgs) handleListContainerCommand() (err error) {
ctx := context.WithValue(context.TODO(), ste.ServiceAPIVersionOverride, ste.DefaultServiceApiVersion)
var credentialInfo common.CredentialInfo
source, err := SplitResourceString(cooked.sourcePath, cooked.location)
if err != nil {
return err
}
if err := common.VerifyIsURLResolvable(raw.src); cooked.location.IsRemote() && err != nil {
return fmt.Errorf("failed to resolve target: %w", err)
}
level, err := DetermineLocationLevel(source.Value, cooked.location, true)
if err != nil {
return err
}
// isSource is rather misnomer for canBePublic. We can list public containers, and hence isSource=true
if credentialInfo, _, err = GetCredentialInfoForLocation(ctx, cooked.location, source, true, common.CpkOptions{}); err != nil {
return fmt.Errorf("failed to obtain credential info: %s", err.Error())
} else if cooked.location == cooked.location.File() && source.SAS == "" {
return errors.New("azure files requires a SAS token for authentication")
} else if credentialInfo.CredentialType.IsAzureOAuth() {
uotm := GetUserOAuthTokenManagerInstance()
if tokenInfo, err := uotm.GetTokenInfo(ctx); err != nil {
return err
} else {
credentialInfo.OAuthTokenInfo = *tokenInfo
}
}
// check if user wants to get version id
getVersionId := containsProperty(cooked.properties, VersionId)
traverser, err := InitResourceTraverser(source, cooked.location, &ctx, &credentialInfo, common.ESymlinkHandlingType.Skip(), nil, true, true, false, common.EPermanentDeleteOption.None(), func(common.EntityType) {}, nil, false, common.ESyncHashType.None(), common.EPreservePermissionsOption.None(), common.LogNone, common.CpkOptions{}, nil, false, cooked.trailingDot, nil, nil, getVersionId)
if err != nil {
return fmt.Errorf("failed to initialize traverser: %s", err.Error())
}
var fileCount int64 = 0
var sizeCount int64 = 0
type versionIdObject struct {
versionId string
fileSize int64
}
objectVer := make(map[string]versionIdObject)
processor := func(object StoredObject) error {
lo := cooked.newListObject(object, level)
glcm.Output(func(format common.OutputFormat) string {
if format == common.EOutputFormat.Json() {
jsonOutput, err := json.Marshal(lo)
common.PanicIfErr(err)
return string(jsonOutput)
} else {
return lo.String()
}
}, common.EOutputMessageType.ListObject())
// ensure that versioned objects don't get counted multiple times in the tally
// 1. only include the size of the latest version of the object in the sizeCount
// 2. only include the object once in the fileCount
if cooked.RunningTally {
if getVersionId {
// get new version id object
updatedVersionId := versionIdObject{
versionId: object.blobVersionID,
fileSize: object.size,
}
// there exists a current version id of the object
if currentVersionId, ok := objectVer[object.relativePath]; ok {
// get current version id time
currentVid, _ := time.Parse(versionIdTimeFormat, currentVersionId.versionId)
// get new version id time
newVid, _ := time.Parse(versionIdTimeFormat, object.blobVersionID)
// if new vid came after the current vid, then it is the latest version
// update the objectVer with the latest version
// we will also remove sizeCount and fileCount of current object, allowing
// the updated sizeCount and fileCount to be added at line 320
if newVid.After(currentVid) {
sizeCount -= currentVersionId.fileSize // remove size of current object
fileCount-- // remove current object file count
objectVer[object.relativePath] = updatedVersionId
}
} else {
objectVer[object.relativePath] = updatedVersionId
}
}
fileCount++
sizeCount += object.size
}
return nil
}
err = traverser.Traverse(nil, processor, nil)
if err != nil {
return fmt.Errorf("failed to traverse container: %s", err.Error())
}
if cooked.RunningTally {
ls := cooked.newListSummary(fileCount, sizeCount)
glcm.Output(func(format common.OutputFormat) string {
if format == common.EOutputFormat.Json() {
jsonOutput, err := json.Marshal(ls)
common.PanicIfErr(err)
return string(jsonOutput)
} else {
return ls.String()
}
}, common.EOutputMessageType.ListSummary())
}
return nil
}
type AzCopyListObject struct {
Path string `json:"Path"`
LastModifiedTime *time.Time `json:"LastModifiedTime,omitempty"`
VersionId string `json:"VersionId,omitempty"`
BlobType blob.BlobType `json:"BlobType,omitempty"`
BlobAccessTier blob.AccessTier `json:"BlobAccessTier,omitempty"`
ContentType string `json:"ContentType,omitempty"`
ContentEncoding string `json:"ContentEncoding,omitempty"`
ContentMD5 []byte `json:"ContentMD5,omitempty"`
LeaseState lease.StateType `json:"LeaseState,omitempty"`
LeaseStatus lease.StatusType `json:"LeaseStatus,omitempty"`
LeaseDuration lease.DurationType `json:"LeaseDuration,omitempty"`
ArchiveStatus blob.ArchiveStatus `json:"ArchiveStatus,omitempty"`
ContentLength string `json:"ContentLength"` // This is a string to support machine-readable
StringEncoding string `json:"-"` // this is stored as part of the list object to avoid looping over the properties array twice
}
func (l AzCopyListObject) String() string {
return l.StringEncoding
}
func (cooked cookedListCmdArgs) newListObject(object StoredObject, level LocationLevel) AzCopyListObject {
path := getPath(object.ContainerName, object.relativePath, level, object.entityType)
contentLength := sizeToString(object.size, cooked.MachineReadable)
lo := AzCopyListObject{
Path: path,
ContentLength: contentLength,
}
builder := strings.Builder{}
builder.WriteString(lo.Path + "; ")
for _, property := range cooked.properties {
propertyStr := string(property)
switch property {
case LastModifiedTime:
lo.LastModifiedTime = to.Ptr(object.lastModifiedTime)
builder.WriteString(propertyStr + ": " + lo.LastModifiedTime.String() + "; ")
case VersionId:
lo.VersionId = object.blobVersionID
builder.WriteString(propertyStr + ": " + lo.VersionId + "; ")
case BlobType:
lo.BlobType = object.blobType
builder.WriteString(propertyStr + ": " + string(lo.BlobType) + "; ")
case BlobAccessTier:
lo.BlobAccessTier = object.blobAccessTier
builder.WriteString(propertyStr + ": " + string(lo.BlobAccessTier) + "; ")
case ContentType:
lo.ContentType = object.contentType
builder.WriteString(propertyStr + ": " + lo.ContentType + "; ")
case ContentEncoding:
lo.ContentEncoding = object.contentEncoding
builder.WriteString(propertyStr + ": " + lo.ContentEncoding + "; ")
case ContentMD5:
lo.ContentMD5 = object.md5
builder.WriteString(propertyStr + ": " + base64.StdEncoding.EncodeToString(lo.ContentMD5) + "; ")
case LeaseState:
lo.LeaseState = object.leaseState
builder.WriteString(propertyStr + ": " + string(lo.LeaseState) + "; ")
case LeaseStatus:
lo.LeaseStatus = object.leaseStatus
builder.WriteString(propertyStr + ": " + string(lo.LeaseStatus) + "; ")
case LeaseDuration:
lo.LeaseDuration = object.leaseDuration
builder.WriteString(propertyStr + ": " + string(lo.LeaseDuration) + "; ")
case ArchiveStatus:
lo.ArchiveStatus = object.archiveStatus
builder.WriteString(propertyStr + ": " + string(lo.ArchiveStatus) + "; ")
}
}
builder.WriteString("Content Length: " + lo.ContentLength)
lo.StringEncoding = builder.String()
return lo
}
type AzCopyListSummary struct {
FileCount string `json:"FileCount"`
TotalFileSize string `json:"TotalFileSize"`
StringEncoding string `json:"-"`
}
func (l AzCopyListSummary) String() string {
return l.StringEncoding
}
func (cooked cookedListCmdArgs) newListSummary(fileCount, totalFileSize int64) AzCopyListSummary {
fc := strconv.Itoa(int(fileCount))
tfs := sizeToString(totalFileSize, cooked.MachineReadable)
output := "\nFile count: " + fc + "\nTotal file size: " + tfs
return AzCopyListSummary{
FileCount: fc,
TotalFileSize: tfs,
StringEncoding: output,
}
}
var megaSize = []string{
"B",
"KB",
"MB",
"GB",
"TB",
"PB",
"EB",
}
func byteSizeToString(size int64) string {
units := []string{
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB", // Let's face it, a file, account, or container probably won't be more than 1000 exabytes in YEARS.
// (and int64 literally isn't large enough to handle too many exbibytes. 128 bit processors when)
}
unit := 0
floatSize := float64(size)
gigSize := 1024
if cooked.MegaUnits {
gigSize = 1000
units = megaSize
}
for floatSize/float64(gigSize) >= 1 {
unit++
floatSize /= float64(gigSize)
}
return strconv.FormatFloat(floatSize, 'f', 2, 64) + " " + units[unit]
}
func getPath(containerName, relativePath string, level LocationLevel, entityType common.EntityType) string {
builder := strings.Builder{}
if level == level.Service() {
builder.WriteString(containerName + "/")
}
builder.WriteString(relativePath)
if entityType == common.EEntityType.Folder() {
builder.WriteString("/")
}
return builder.String()
}
func sizeToString(size int64, machineReadable bool) string {
return common.Iff(machineReadable, strconv.Itoa(int(size)), byteSizeToString(size))
}