-
Notifications
You must be signed in to change notification settings - Fork 18
/
sos_upload.go
271 lines (226 loc) · 5.9 KB
/
sos_upload.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
package cmd
import (
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/vbauerster/mpb/v4"
"github.com/vbauerster/mpb/v4/decor"
minio "github.com/minio/minio-go/v6"
"github.com/spf13/cobra"
)
const (
parallelSosUpload = 10
)
type fileToUpload struct {
localPath string
remotePath string
contentType string
}
var sosUploadCmd = &cobra.Command{
Use: "upload BUCKET FILE...",
Short: "Upload a file into a bucket",
Aliases: gUploadAlias,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return cmd.Usage()
}
bucket := args[0]
files := args[1:]
remoteFilePath, err := cmd.Flags().GetString("remote-path")
if err != nil {
return err
}
certsFile, err := cmd.Parent().Flags().GetString("certs-file")
if err != nil {
return err
}
sosClient, err := newSOSClient(certsFile)
if err != nil {
return err
}
logfile, err := cmd.Flags().GetString("log")
if err != nil {
return err
}
if logfile != "" {
l, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
return err
}
sosClient.TraceOn(l)
}
location, err := sosClient.GetBucketLocation(bucket)
if err != nil {
return err
}
if err := sosClient.setZone(location); err != nil {
return err
}
recursive, err := cmd.Flags().GetBool("recursive")
if err != nil {
return err
}
// Upload the file
filesToUpload := []fileToUpload{}
for _, file := range files {
file = filepath.ToSlash(file)
objectName := filepath.Base(file)
filePath := file
remote := strings.TrimLeft(filepath.ToSlash(remoteFilePath), "/")
if (len(files) > 1 && remote != "") || (len(files) == 1 && strings.HasSuffix(remote, "/")) {
remote = filepath.Join(remoteFilePath, objectName)
}
if remote == "" {
remote = objectName
}
file, err := os.Open(filePath)
if err != nil {
return err
}
fileStat, err := file.Stat()
if err != nil {
return err
}
if recursive && fileStat.IsDir() {
filesToUpload, err = getFiles(filePath, strings.TrimRight(remote, "/"), filesToUpload)
} else {
var contentType string
var bufferSize int64
// Only the first 512 bytes are used to sniff the content type.
if fileStat.Size() >= 512 {
bufferSize = 512
} else {
bufferSize = fileStat.Size()
}
buffer := make([]byte, bufferSize)
_, err = file.Read(buffer)
contentType = http.DetectContentType(buffer)
filesToUpload = append(filesToUpload, fileToUpload{
localPath: filePath,
remotePath: remote,
contentType: contentType,
})
}
if err != nil {
return err
}
if err = file.Close(); err != nil {
return err
}
}
lenFileToUpload := len(filesToUpload)
var taskWG sync.WaitGroup
progress := mpb.NewWithContext(gContext,
mpb.WithWaitGroup(&taskWG),
// override default (80) width
mpb.WithWidth(64),
// override default 120ms refresh rate
mpb.WithRefreshRate(180*time.Millisecond),
mpb.ContainerOptOn(mpb.WithOutput(nil), func() bool { return gQuiet }),
)
taskWG.Add(lenFileToUpload)
workerSem := make(chan int, parallelSosUpload)
for _, fileToUP := range filesToUpload {
fileToUP := fileToUP
go func() {
defer taskWG.Done()
workerSem <- 1
fileInfo, err := os.Stat(fileToUP.localPath)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(fileToUP.localPath)
if err != nil {
log.Fatal(err)
}
defer f.Close() //nolint: errcheck
base := filepath.Base(fileToUP.localPath)
bar := progress.AddBar(fileInfo.Size(),
mpb.AppendDecorators(
// simple name decorator
decor.Name(base, decor.WC{W: len(base) + 1, C: decor.DidentRight}),
),
mpb.PrependDecorators(
decor.OnComplete(decor.AverageETA(decor.ET_STYLE_GO), "done!"),
// decor.DSyncWidth bit enables column width synchronization
decor.Percentage(decor.WCSyncSpace),
),
)
reader := bar.ProxyReader(f)
// Upload object with FPutObject
_, upErr := sosClient.PutObjectWithContext(
gContext,
bucket,
fileToUP.remotePath,
reader,
fileInfo.Size(),
minio.PutObjectOptions{
ContentType: fileToUP.contentType,
SendContentMd5: true,
},
)
if upErr != nil {
log.Fatal(upErr)
}
// Workaround required to avoid the io.Reader from hanging when uploading empty files
// (see https://github.com/vbauerster/mpb/issues/7#issuecomment-518756758)
if fileInfo.Size() == 0 {
bar.SetTotal(100, true)
}
<-workerSem
}()
}
progress.Wait()
return nil
},
}
func getFiles(folderName, remoteFilePath string, resFiles []fileToUpload) ([]fileToUpload, error) {
files, err := ioutil.ReadDir(folderName)
if err != nil {
return nil, err
}
for _, f := range files {
localPath := filepath.Join(folderName, f.Name())
if f.IsDir() {
resFiles, err = getFiles(localPath, filepath.Join(remoteFilePath, f.Name()), resFiles)
if err != nil {
return nil, err
}
continue
}
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
var contentType string
if f.Size() >= 512 {
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
return nil, err
}
contentType = http.DetectContentType(buffer)
}
resFiles = append(resFiles, fileToUpload{
localPath: localPath,
remotePath: filepath.Join(remoteFilePath, f.Name()),
contentType: contentType,
})
if err := file.Close(); err != nil {
return nil, err
}
}
return resFiles, nil
}
func init() {
sosCmd.AddCommand(sosUploadCmd)
sosUploadCmd.Flags().StringP("log", "l", "", "Log upload transfer details to file")
sosUploadCmd.Flags().BoolP("recursive", "r", false, "Upload a folder recursively")
sosUploadCmd.Flags().StringP("remote-path", "p", "", "Set a remote path for local file(s)")
}