forked from minio/mc
/
cast-main.go
284 lines (244 loc) · 7.66 KB
/
cast-main.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
/*
* Minio Client, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"math"
"os"
"runtime"
"sync"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/iodine"
)
// Help message.
var castCmd = cli.Command{
Name: "cast",
Usage: "Copy files and folders from a single source to many destinations",
Action: runCastCmd,
CustomHelpTemplate: `NAME:
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}}{{if .Flags}} [ARGS...]{{end}} SOURCE TARGET [TARGET...] {{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if .Flags}}
FLAGS:
{{range .Flags}}{{.}}
{{end}}{{ end }}
EXAMPLES:
1. Cast an object from local filesystem to Amazon S3 object storage.
$ mc {{.Name}} star-trek-episode-10-season4.ogg https://s3.amazonaws.com/trekarchive
2. Cast a bucket recursively from Minio object storage to multiple buckets on Amazon S3 object storage.
$ mc {{.Name}} https://play.minio.io:9000/photos/2014... https://s3.amazonaws.com/backup-photos https://s3-west-1.amazonaws.com/local-photos
3. Cast a local folder recursively to Minio object storage and Amazon S3 object storage.
$ mc {{.Name}} backup/... https://play.minio.io:9000/archive https://s3.amazonaws.com/archive
4. Cast a bucket from aliased Amazon S3 object storage to multiple folders on Windows.
$ mc {{.Name}} s3:documents/2014/... C:\backup\2014 C:\shared\volume\backup\2014
5. Cast a local directory of non english character recursively to Amazon s3 object storage and Minio object storage.
$ mc {{.Name}} 本語/... s3:mylocaldocuments play:backup
`,
}
// doCast - Cast an object to multiple destination. castURLs status contains a copy of sURLs and error if any.
func doCast(sURLs castURLs, bar *barSend, castQueueCh <-chan bool, wg *sync.WaitGroup, statusCh chan<- castURLs) {
defer wg.Done() // Notify that this copy routine is done.
defer func() {
<-castQueueCh
}()
if sURLs.Error != nil { // Errorneous sURLs passed.
sURLs.Error = iodine.New(sURLs.Error, nil)
statusCh <- sURLs
return
}
if !globalQuietFlag || !globalJSONFlag {
bar.SetCaption(sURLs.SourceContent.Name + ": ")
}
reader, length, err := getSource(sURLs.SourceContent.Name)
if err != nil {
if !globalQuietFlag || !globalJSONFlag {
bar.ErrorGet(int64(length))
}
sURLs.Error = iodine.New(err, nil)
statusCh <- sURLs
return
}
var targetURLs []string
for _, targetContent := range sURLs.TargetContents {
targetURLs = append(targetURLs, targetContent.Name)
}
var newReader io.ReadCloser
if globalQuietFlag || globalJSONFlag {
console.PrintC(CastMessage{
Source: sURLs.SourceContent.Name,
Targets: targetURLs,
})
newReader = reader
} else {
// set up progress
newReader = bar.NewProxyReader(reader)
}
defer newReader.Close()
err = putTargets(targetURLs, length, newReader)
if err != nil {
if !globalQuietFlag || !globalJSONFlag {
bar.ErrorPut(int64(length))
}
sURLs.Error = iodine.New(err, nil)
statusCh <- sURLs
return
}
sURLs.Error = nil // just for safety
statusCh <- sURLs
}
// doCastFake - Perform a fake cast to update the progress bar appropriately.
func doCastFake(sURLs castURLs, bar *barSend) (err error) {
if !globalDebugFlag || !globalJSONFlag {
bar.Progress(sURLs.SourceContent.Size)
}
return nil
}
// doPrepareCastURLs scans the source URL and prepares a list of objects for casting.
func doPrepareCastURLs(session *sessionV2, trapCh <-chan bool) {
sourceURL := session.Header.CommandArgs[0] // first one is source.
targetURLs := session.Header.CommandArgs[1:]
var totalBytes int64
var totalObjects int
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
scanBar := scanBarFactory(sourceURL)
URLsCh := prepareCastURLs(sourceURL, targetURLs)
done := false
for done == false {
select {
case sURLs, ok := <-URLsCh:
if !ok { // Done with URL prepration
done = true
break
}
if sURLs.Error != nil {
console.Errorln(sURLs.Error)
break
}
jsonData, err := json.Marshal(sURLs)
if err != nil {
session.Close()
console.Fatalf("Unable to marshal URLs to JSON. %s\n", err)
}
fmt.Fprintln(dataFP, string(jsonData))
scanBar(sURLs.SourceContent.Name)
totalBytes += sURLs.SourceContent.Size
totalObjects++
case <-trapCh:
session.Close() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
}
func doCastCmdSession(session *sessionV2) {
trapCh := signalTrap(os.Interrupt, os.Kill)
if !session.HasData() {
doPrepareCastURLs(session, trapCh)
}
// Set up progress bar.
var bar barSend
if !globalQuietFlag || !globalJSONFlag {
bar = newCpBar()
bar.Extend(session.Header.TotalBytes)
}
// Prepare URL scanner from session data file.
scanner := bufio.NewScanner(session.NewDataReader())
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isCopiedFactory(session.Header.LastCopied)
wg := new(sync.WaitGroup)
// Limit numner of cast routines based on available CPU resources.
castQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(castQueue)
// Status channel for receiveing cast return status.
statusCh := make(chan castURLs)
// Go routine to monitor doCast status and signal traps.
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case cURLs, ok := <-statusCh: // Receive status.
if !ok { // We are done here. Top level function has returned.
bar.Finish()
return
}
if cURLs.Error == nil {
session.Header.LastCopied = cURLs.SourceContent.Name
} else {
console.Errorf("Failed to cast ‘%s’, %s\n", cURLs.SourceContent.Name, NewIodine(cURLs.Error))
}
case <-trapCh: // Receive interrupt notification.
session.Save()
session.Info()
os.Exit(0)
}
}
}()
// Go routine to perform concurrently casting.
wg.Add(1)
go func() {
defer wg.Done()
castWg := new(sync.WaitGroup)
defer close(statusCh)
for scanner.Scan() {
var sURLs castURLs
json.Unmarshal([]byte(scanner.Text()), &sURLs)
if isCopied(sURLs.SourceContent.Name) {
doCastFake(sURLs, &bar)
} else {
// Wait for other cast routines to
// complete. We only have limited CPU
// and network resources.
castQueue <- true
// Account for each cast routines we start.
castWg.Add(1)
// Do casting in background concurrently.
go doCast(sURLs, &bar, castQueue, castWg, statusCh)
}
}
castWg.Wait()
}()
wg.Wait()
}
func runCastCmd(ctx *cli.Context) {
checkCastSyntax(ctx)
session := newSessionV2()
defer session.Close()
var err error
session.Header.CommandType = "cast"
session.Header.RootPath, err = os.Getwd()
if err != nil {
session.Close()
console.Fatalf("Unable to get current working directory. %s\n", err)
}
// extract URLs.
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
session.Close()
console.Fatalf("One or more unknown URL types found in %s. %s\n", ctx.Args(), err)
}
doCastCmdSession(session)
}