Session V2 implementation for copy and sync

This commit is contained in:
Anand Babu (AB) Periasamy
2015-07-12 20:47:49 -07:00
parent c29e9bc92d
commit 6dcd73551c
18 changed files with 928 additions and 704 deletions
+2 -1
View File
@@ -16,7 +16,8 @@ getdeps: checkdeps checkgopath
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
@go get github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:"
verifiers: getdeps vet fmt lint cyclo deadcode
# verifiers: getdeps vet fmt lint cyclo deadcode
verifiers: getdeps vet fmt lint cyclo
vet:
@echo "Running $@:"
+124 -169
View File
@@ -17,17 +17,18 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"math"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/countlock"
"github.com/minio/mc/pkg/yielder"
"github.com/minio/minio/pkg/iodine"
)
@@ -50,6 +51,9 @@ FLAGS:
{{range .Flags}}{{.}}
{{end}}{{ end }}
EXAMPLES:
1. Copy list of objects from local file system to Amazon S3 object storage.
$ mc {{.Name}} Music/*.ogg https://s3.amazonaws.com/jukebox/
@@ -69,152 +73,152 @@ EXAMPLES:
`,
}
// doCopySession - Copy a singe file from source to destination
func doCopySession(cURLs cpURLs, bar *barSend, s *sessionV1) error {
s.Lock.Lock()
defer s.Lock.Unlock()
// doCopy - Copy a singe file from source to destination
func doCopy(cpURLs copyURLs, bar *barSend, cpQueue chan bool, wg *sync.WaitGroup) error {
defer wg.Done() // Notify that this copy routine is done.
defer func() { // Notify the copy queue that it is free to pickup next routine.
<-cpQueue
}()
if !globalQuietFlag {
bar.SetCaption(cURLs.SourceContent.Name + ": ")
bar.SetCaption(cpURLs.SourceContent.Name + ": ")
}
_, ok := s.Files[cURLs.SourceContent.Name]
if ok {
putFakeTarget(bar.NewProxyReader(&fakeReader{size: cURLs.SourceContent.Size}))
return nil
}
reader, length, err := getSource(cURLs.SourceContent.Name)
reader, length, err := getSource(cpURLs.SourceContent.Name)
if err != nil {
if !globalQuietFlag {
bar.ErrorGet(length)
}
return iodine.New(err, map[string]string{"URL": cURLs.SourceContent.Name})
return iodine.New(err, map[string]string{"URL": cpURLs.SourceContent.Name})
}
defer reader.Close()
var newReader io.Reader
switch globalQuietFlag || globalJSONFlag {
case true:
if globalQuietFlag || globalJSONFlag {
console.Infos(CopyMessage{
Source: cURLs.SourceContent.Name,
Target: cURLs.TargetContent.Name,
Length: cURLs.SourceContent.Size,
Source: cpURLs.SourceContent.Name,
Target: cpURLs.TargetContent.Name,
Length: cpURLs.SourceContent.Size,
})
newReader = yielder.NewReader(reader)
default:
} else {
// set up progress
newReader = bar.NewProxyReader(yielder.NewReader(reader))
}
err = putTarget(cURLs.TargetContent.Name, length, newReader)
err = putTarget(cpURLs.TargetContent.Name, length, newReader)
if err != nil {
if !globalQuietFlag {
bar.ErrorPut(length)
}
return iodine.New(err, map[string]string{"URL": cURLs.TargetContent.Name})
return iodine.New(err, map[string]string{"URL": cpURLs.TargetContent.Name})
}
// store files which have finished copying
s.Files[cURLs.SourceContent.Name] = struct{}{}
return nil
}
type cpSession struct {
Error error
Done bool
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(sURLs copyURLs, bar *barSend) (err error) {
bar.Progress(sURLs.SourceContent.Size)
return nil
}
func doCopyInRoutineSession(cURLs cpURLs, bar *barSend, cpQueue chan bool, cpsCh chan cpSession, wg *sync.WaitGroup, s *sessionV1) {
defer wg.Done()
if err := doCopySession(cURLs, bar, s); err != nil {
cpsCh <- cpSession{
Error: iodine.New(err, nil),
Done: false,
}
}
// Signal that this copy routine is done.
<-cpQueue
}
func doPrepareCopyURLs(sourceURLs []string, targetURL string, bar barSend, lock countlock.Locker) {
for cURLs := range prepareCopyURLs(sourceURLs, targetURL) {
if cURLs.Error != nil {
// no need to print errors here, any error here
// will be printed later during Copy()
continue
}
if !globalQuietFlag {
bar.Extend(cURLs.SourceContent.Size)
lock.Up() // Let copy routine know that it has to catch up.
}
}
}
func trapCp(cpsCh chan cpSession) {
// Go signal notification works by sending `os.Signal`
// values on a channel.
sigs := make(chan os.Signal, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, os.Kill, os.Interrupt)
// This executes a blocking receive for signals.
// When it gets one it'll then notify the program
// that it can finish.
<-sigs
cpsCh <- cpSession{
Error: nil,
Done: true,
}
}
func doCopyCmdSession(bar barSend, s *sessionV1) <-chan cpSession {
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources, even the recursive URLs mixed in-between.
sourceURLs := s.URLs[:len(s.URLs)-1]
targetURL := s.URLs[len(s.URLs)-1] // Last one is target
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
cpsCh := make(chan cpSession)
go func(sourceURLs []string, targetURL string, bar barSend, cpsCh chan cpSession, s *sessionV1) {
defer close(cpsCh)
go trapCp(cpsCh)
var totalBytes int64
var totalObjects int
var lock countlock.Locker
if !globalQuietFlag {
// Keep progress-bar and copy routines in sync.
lock = countlock.New()
defer lock.Close()
}
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
scanBar := scanBarFactory(strings.Join(sourceURLs, " "))
URLsCh := prepareCopyURLs(sourceURLs, targetURL)
done := false
// Wait for all copy routines to complete.
wg := new(sync.WaitGroup)
// Pool limited copy routines in parallel.
cpQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(cpQueue)
go doPrepareCopyURLs(sourceURLs, targetURL, bar, lock)
for cURLs := range prepareCopyURLs(sourceURLs, targetURL) {
if cURLs.Error != nil {
cpsCh <- cpSession{
Error: cURLs.Error,
Done: false,
}
continue
for done == false {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL prepration
done = true
break
}
cpQueue <- true // Wait for existing pool to drain.
wg.Add(1) // keep track of all the goroutines
if !globalQuietFlag {
lock.Down() // Do not jump ahead of the progress bar builder above.
if cpURLs.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(cpURLs.Error, nil),
})
break
}
go doCopyInRoutineSession(cURLs, &bar, cpQueue, cpsCh, wg, s)
jsonData, err := json.Marshal(cpURLs)
if err != nil {
session.Close()
console.Fatals(ErrorMessage{
Message: fmt.Sprintf("Unable to marshal URLs to JSON for ‘%s’", cpURLs.SourceContent.Name),
Error: iodine.New(err, nil),
})
}
fmt.Fprintln(dataFP, string(jsonData))
scanBar(cpURLs.SourceContent.Name)
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
session.Close() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
wg.Wait() // wait for the go routines to complete
}(sourceURLs, targetURL, bar, cpsCh, s)
return cpsCh
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
}
func doCopyCmdSession(session *sessionV2) {
trapCh := signalTrap(os.Interrupt, os.Kill)
if !session.HasData() {
doPrepareCopyURLs(session, trapCh)
}
var bar barSend
if !globalQuietFlag { // set up progress bar
bar = newCpBar()
defer bar.Finish()
}
wg := new(sync.WaitGroup)
cpQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(cpQueue)
scanner := bufio.NewScanner(session.NewDataReader())
isCopied := isCopiedFactory(session.Header.LastCopied)
bar.Extend(session.Header.TotalBytes)
for scanner.Scan() {
var cpURLs copyURLs
json.Unmarshal([]byte(scanner.Text()), &cpURLs)
if isCopied(cpURLs.SourceContent.Name) {
doCopyFake(cpURLs, &bar)
} else {
select {
case cpQueue <- true:
wg.Add(1)
go doCopy(cpURLs, &bar, cpQueue, wg)
session.Header.LastCopied = cpURLs.SourceContent.Name
case <-trapCh:
session.Save()
session.Info()
os.Exit(0)
}
}
}
wg.Wait()
}
// runCopyCmd is bound to sub-command
@@ -223,71 +227,22 @@ func runCopyCmd(ctx *cli.Context) {
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code
}
if !isMcConfigExists() {
console.Fatals(ErrorMessage{
Message: "Please run \"mc config generate\"",
Error: iodine.New(errNotConfigured{}, nil),
})
}
if !isSessionDirExists() {
if err := createSessionDir(); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
}
session := newSessionV2()
defer session.Close()
s, err := newSession()
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
s.CommandType = "cp"
s.RootPath, _ = os.Getwd()
session.Header.CommandType = "cp"
session.Header.RootPath, _ = os.Getwd()
// extract URLs.
s.URLs, err = args2URLs(ctx.Args())
var err error
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
session.Close()
console.Fatals(ErrorMessage{
Message: fmt.Sprintf("Unknown URL types: ‘%s’", ctx.Args()),
Message: fmt.Sprintf("Unknown URL types found: ‘%s’", ctx.Args()),
Error: iodine.New(err, nil),
})
}
var bar barSend
// set up progress bar
if !globalQuietFlag {
bar = newCpBar()
}
for cps := range doCopyCmdSession(bar, s) {
if cps.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(cps.Error, nil),
})
}
if cps.Done {
if err := saveSession(s); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
console.Println()
console.Infos(InfoMessage{
Message: "Session terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
// this os.Exit is needed really to exit in-case of "os.Interrupt"
os.Exit(0)
}
}
if !globalQuietFlag {
bar.Finish()
// ignore any error returned here
clearSession(s.SessionID)
}
doCopyCmdSession(session)
}
+78 -131
View File
@@ -17,9 +17,7 @@
package main
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/minio/cli"
@@ -58,122 +56,69 @@ EXAMPLES:
`,
}
func listSessions(sdir string) error {
sdir, err := getSessionDir()
if err != nil {
return iodine.New(err, nil)
}
sessions, err := ioutil.ReadDir(sdir)
if err != nil {
return iodine.New(err, nil)
}
for _, session := range sessions {
if session.Mode().IsRegular() {
s, err := loadSession(session.Name())
if err != nil {
return iodine.New(err, nil)
}
console.Prints(s)
func listSessions() error {
for _, sid := range getSessionIDs() {
s, err := loadSessionV2(sid)
if err != nil {
return iodine.New(err, nil)
}
console.Prints(s)
}
return nil
}
func resumeSession(sid string) (*sessionV1, error) {
sfile, err := getSessionFile(sid)
if err != nil {
return nil, iodine.New(err, nil)
}
_, err = os.Stat(sfile)
if err != nil {
return nil, iodine.New(errInvalidSessionID{id: sid}, nil)
}
s, err := loadSession(sid)
if err != nil {
return nil, iodine.New(err, nil)
}
return s, nil
}
func clearSession(sid string) error {
func clearSession(sid string) {
if sid == "all" {
sdir, err := getSessionDir()
if err != nil {
return iodine.New(err, nil)
}
sessions, err := ioutil.ReadDir(sdir)
if err != nil {
return iodine.New(err, nil)
}
for _, session := range sessions {
if session.Mode().IsRegular() {
err := os.Remove(filepath.Join(sdir, session.Name()))
if err != nil {
return iodine.New(err, nil)
}
for _, sid := range getSessionIDs() {
session, err := loadSessionV2(sid)
if err != nil {
console.Fatalf("Unable to load session ‘%s’, %s", sid, iodine.New(err, nil))
}
session.Close()
}
return nil
return
}
sfile, err := getSessionFile(sid)
if !isSession(sid) {
console.Fatalf("Session ‘%s’ not found.\n", sid)
}
session, err := loadSessionV2(sid)
if err != nil {
return iodine.New(err, nil)
console.Fatalf("Unable to load session ‘%s’, %s", sid, iodine.New(err, nil))
}
err = os.Remove(sfile)
if err != nil {
return iodine.New(errInvalidSessionID{id: sid}, nil)
}
return nil
session.Close()
}
func sessionExecute(bar barSend, s *sessionV1) {
switch s.CommandType {
case "cp":
for cps := range doCopyCmdSession(bar, s) {
if cps.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(cps.Error, nil),
})
}
if cps.Done {
if err := saveSession(s); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
console.Println()
console.Infos(InfoMessage{
Message: "Session terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
// this os.Exit is needed really to exit in-case of "os.Interrupt"
os.Exit(0)
}
}
func sessionExecute(s *sessionV2) {
switch s.Header.CommandType {
/*
case "cp":
for cps := range doCopyCmdSession(bar, s) {
if cps.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(cps.Error, nil),
})
}
if cps.Done {
if err := saveSessionV2(s); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
console.Println()
console.Infos(InfoMessage{
Message: "Session terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
// this os.Exit is needed really to exit in-case of "os.Interrupt"
os.Exit(0)
}
}
*/
case "sync":
for ss := range doSyncCmdSession(bar, s) {
if ss.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(ss.Error, nil),
})
}
if ss.Done {
if err := saveSession(s); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
console.Println()
console.Infos(InfoMessage{
Message: "Session terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
// this os.Exit is needed really to exit in-case of "os.Interrupt"
os.Exit(0)
}
}
doSyncCmdSession(s)
}
}
@@ -195,7 +140,7 @@ func runSessionCmd(ctx *cli.Context) {
switch strings.TrimSpace(ctx.Args().First()) {
// list resumable sessions
case "list":
err := listSessions(sessionDir)
err := listSessions()
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
@@ -209,14 +154,25 @@ func runSessionCmd(ctx *cli.Context) {
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
sid := strings.TrimSpace(ctx.Args().Tail().First())
s, err := resumeSession(sid)
_, err := os.Stat(getSessionFile(sid))
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
Error: iodine.New(errInvalidSessionID{id: sid}, nil),
})
}
s, err := loadSessionV2(sid)
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(errInvalidSessionID{id: sid}, nil),
})
}
savedCwd, err := os.Getwd()
if err != nil {
console.Fatals(ErrorMessage{
@@ -224,27 +180,23 @@ func runSessionCmd(ctx *cli.Context) {
Error: iodine.New(err, nil),
})
}
if s.RootPath != "" {
if s.Header.RootPath != "" {
// chdir to RootPath
os.Chdir(s.RootPath)
os.Chdir(s.Header.RootPath)
}
var bar barSend
// set up progress bar
if !globalQuietFlag {
bar = newCpBar()
}
sessionExecute(bar, s)
if !globalQuietFlag {
bar.Finish()
if err := clearSession(sid); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
// change dir back
os.Chdir(savedCwd)
sessionExecute(s)
err = s.Close()
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
// change dir back
os.Chdir(savedCwd)
// purge a requested pending session, if "*" purge everything
case "clear":
if len(ctx.Args().Tail()) != 1 {
@@ -253,12 +205,7 @@ func runSessionCmd(ctx *cli.Context) {
if strings.TrimSpace(ctx.Args().Tail().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
if err := clearSession(strings.TrimSpace(ctx.Args().Tail().First())); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
clearSession(strings.TrimSpace(ctx.Args().Tail().First()))
default:
cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code
}
+123 -171
View File
@@ -17,17 +17,17 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"math"
"os"
"os/signal"
"runtime"
"sync"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/countlock"
"github.com/minio/mc/pkg/yielder"
"github.com/minio/minio/pkg/iodine"
)
@@ -69,34 +69,25 @@ EXAMPLES:
`,
}
// doSyncSession - Sync an object to multiple destination
func doSyncSession(sURLs syncURLs, bar *barSend, syncQueue chan bool, ssCh chan syncSession, wg *sync.WaitGroup, s *sessionV1) {
// waitgroup reply deferred until this function returns
defer wg.Done()
// hold lock for map updates inside session
s.Lock.Lock()
defer s.Lock.Unlock()
// doSync - Sync an object to multiple destination
func doSync(sURLs syncURLs, bar *barSend, syncQueue chan bool, wg *sync.WaitGroup) (err error) {
defer wg.Done() // Notify that this copy routine is done.
defer func() { // Notify the copy queue that it is free to pickup next routine.
<-syncQueue
}()
if !globalQuietFlag {
bar.SetCaption(sURLs.SourceContent.Name + ": ")
}
_, ok := s.Files[sURLs.SourceContent.Name]
if ok {
if !globalQuietFlag {
putFakeTarget(bar.NewProxyReader(&fakeReader{size: sURLs.SourceContent.Size}))
}
<-syncQueue // Signal that this copy routine is done.
return
}
reader, length, err := getSource(sURLs.SourceContent.Name)
if err != nil {
if !globalQuietFlag {
bar.ErrorGet(int64(length))
}
ssCh <- syncSession{
Error: iodine.New(err, map[string]string{"URL": sURLs.SourceContent.Name}),
Done: false,
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
}
defer reader.Close()
@@ -107,114 +98,126 @@ func doSyncSession(sURLs syncURLs, bar *barSend, syncQueue chan bool, ssCh chan
}
var newReader io.Reader
switch globalQuietFlag || globalJSONFlag {
case true:
if globalQuietFlag || globalJSONFlag {
console.Infos(SyncMessage{
Source: sURLs.SourceContent.Name,
Targets: targetURLs,
})
newReader = yielder.NewReader(reader)
default:
} else {
// set up progress
newReader = bar.NewProxyReader(yielder.NewReader(reader))
}
for err := range putTargets(targetURLs, length, newReader) {
if err != nil {
if !globalQuietFlag {
bar.ErrorPut(int64(length))
}
ssCh <- syncSession{
Error: iodine.New(err, nil),
Done: false,
}
}
return nil
}
// doSyncFake - Perform a fake sync to update the progress bar appropriately.
func doSyncFake(sURLs syncURLs, bar *barSend) (err error) {
bar.Progress(sURLs.SourceContent.Size)
return nil
}
// doPrepareSyncURLs scans the source URL and prepares a list of objects for syncing.
func doPrepareSyncURLs(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 := prepareSyncURLs(sourceURL, targetURLs)
done := false
for done == false {
select {
case sURLs, ok := <-URLsCh:
if !ok { // Done with URL prepration
done = true
break
}
}
}
<-syncQueue // Signal that this copy routine is done.
// store files which have finished copying
s.Files[sURLs.SourceContent.Name] = struct{}{}
}
func doPrepareSyncURLs(sourceURL string, targetURLs []string, bar barSend, lock countlock.Locker) {
for sURLs := range prepareSyncURLs(sourceURL, targetURLs) {
if sURLs.Error != nil {
// no need to print errors here, any error here
// will be printed later during Sync()
continue
}
if !globalQuietFlag {
bar.Extend(sURLs.SourceContent.Size)
lock.Up() // Let copy routine know that it has to catch up.
}
}
}
type syncSession struct {
Error error
Done bool
}
func trapSync(ssCh chan syncSession) {
// Go signal notification works by sending `os.Signal`
// values on a channel.
sigs := make(chan os.Signal, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, os.Kill, os.Interrupt)
// This executes a blocking receive for signals.
// When it gets one it'll then notify the program
// that it can finish.
<-sigs
ssCh <- syncSession{
Error: nil,
Done: true,
}
}
func doSyncCmdSession(bar barSend, s *sessionV1) <-chan syncSession {
ssCh := make(chan syncSession)
// Separate source and target. 'sync' can take only one source.
// but any number of targets, even the recursive URLs mixed in-between.
sourceURL := s.URLs[0] // first one is source
targetURLs := s.URLs[1:]
go func(sourceURL string, targetURLs []string, bar barSend, ssCh chan syncSession, s *sessionV1) {
defer close(ssCh)
go trapSync(ssCh)
var lock countlock.Locker
if !globalQuietFlag {
// Keep progress-bar and copy routines in sync.
lock = countlock.New()
defer lock.Close()
}
wg := new(sync.WaitGroup)
syncQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(syncQueue)
go doPrepareSyncURLs(sourceURL, targetURLs, bar, lock)
for sURLs := range prepareSyncURLs(sourceURL, targetURLs) {
if sURLs.Error != nil {
ssCh <- syncSession{
Error: iodine.New(sURLs.Error, nil),
Done: false,
}
continue
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(sURLs.Error, nil),
})
break
}
syncQueue <- true
wg.Add(1)
if !globalQuietFlag {
lock.Down() // Do not jump ahead of the progress bar builder above.
jsonData, err := json.Marshal(sURLs)
if err != nil {
session.Close()
console.Fatals(ErrorMessage{
Message: fmt.Sprintf("Unable to marshal URLs to JSON for ‘%s’", sURLs.SourceContent.Name),
Error: iodine.New(err, nil),
})
}
go doSyncSession(sURLs, &bar, syncQueue, ssCh, wg, s)
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)
}
wg.Wait()
}(sourceURL, targetURLs, bar, ssCh, s)
return ssCh
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
}
func doSyncCmdSession(session *sessionV2) {
trapCh := signalTrap(os.Interrupt, os.Kill)
if !session.HasData() {
doPrepareSyncURLs(session, trapCh)
}
var bar barSend
if !globalQuietFlag { // set up progress bar
bar = newCpBar()
defer bar.Finish()
}
wg := new(sync.WaitGroup)
syncQueue := make(chan bool, int(math.Max(float64(runtime.NumCPU())-1, 1)))
defer close(syncQueue)
scanner := bufio.NewScanner(session.NewDataReader())
isCopied := isCopiedFactory(session.Header.LastCopied)
bar.Extend(session.Header.TotalBytes)
for scanner.Scan() {
var sURLs syncURLs
json.Unmarshal([]byte(scanner.Text()), &sURLs)
if isCopied(sURLs.SourceContent.Name) {
doSyncFake(sURLs, &bar)
} else {
select {
case syncQueue <- true:
wg.Add(1)
go doSync(sURLs, &bar, syncQueue, wg)
session.Header.LastCopied = sURLs.SourceContent.Name
case <-trapCh:
session.Save()
session.Info()
os.Exit(0)
}
}
}
wg.Wait()
}
func runSyncCmd(ctx *cli.Context) {
@@ -222,73 +225,22 @@ func runSyncCmd(ctx *cli.Context) {
cli.ShowCommandHelpAndExit(ctx, "sync", 1) // last argument is exit code
}
if !isMcConfigExists() {
console.Fatals(ErrorMessage{
Message: "Please run \"mc config generate\"",
Error: iodine.New(errNotConfigured{}, nil),
})
}
session := newSessionV2()
defer session.Close()
if !isSessionDirExists() {
if err := createSessionDir(); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
}
s, err := newSession()
if err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
s.CommandType = "sync"
s.RootPath, _ = os.Getwd()
session.Header.CommandType = "sync"
session.Header.RootPath, _ = os.Getwd()
// extract URLs.
s.URLs, err = args2URLs(ctx.Args())
var err error
session.Header.CommandArgs, err = args2URLs(ctx.Args())
if err != nil {
session.Close()
console.Fatals(ErrorMessage{
Message: fmt.Sprintf("Unknown URL types found: ‘%s’", ctx.Args()),
Error: iodine.New(err, nil),
})
}
var bar barSend
// set up progress bar
if !globalQuietFlag {
bar = newCpBar()
}
for ss := range doSyncCmdSession(bar, s) {
if ss.Error != nil {
console.Errors(ErrorMessage{
Message: "Failed with",
Error: iodine.New(ss.Error, nil),
})
}
if ss.Done {
if err := saveSession(s); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed wtih",
Error: iodine.New(err, nil),
})
}
console.Println()
console.Infos(InfoMessage{
Message: "Session terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
// this os.Exit is needed really to exit in-case of "os.Interrupt"
os.Exit(0)
}
}
if !globalQuietFlag {
bar.Finish()
// ignore any error returned here
clearSession(s.SessionID)
}
doSyncCmdSession(session)
}
+81 -81
View File
@@ -47,27 +47,27 @@ import (
// ==================================
// copy(*, f)
type cpURLs struct {
type copyURLs struct {
SourceContent *client.Content
TargetContent *client.Content
Error error
}
func (c cpURLs) IsEmpty() bool {
func (c copyURLs) IsEmpty() bool {
if c.SourceContent == nil && c.TargetContent == nil {
return true
}
return false
}
type cpURLsType uint8
type copyURLsType uint8
const (
cpURLsTypeInvalid cpURLsType = iota
cpURLsTypeA
cpURLsTypeB
cpURLsTypeC
cpURLsTypeD
copyURLsTypeInvalid copyURLsType = iota
copyURLsTypeA
copyURLsTypeB
copyURLsTypeC
copyURLsTypeD
)
// Check if the target URL represents directory. It may or may not exist yet.
@@ -91,94 +91,94 @@ func isTargetURLDir(targetURL string) bool {
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessCopyURLType(sourceURLs []string, targetURL string) cpURLsType {
func guessCopyURLType(sourceURLs []string, targetURL string) copyURLsType {
if strings.TrimSpace(targetURL) == "" || targetURL == "" { // Target is empty
return cpURLsTypeInvalid
return copyURLsTypeInvalid
}
if sourceURLs == nil { // Source list is empty
return cpURLsTypeInvalid
return copyURLsTypeInvalid
}
if len(sourceURLs) == 1 { // 1 Source, 1 Target
switch {
// Type C
case isURLRecursive(sourceURLs[0]):
return cpURLsTypeC
return copyURLsTypeC
// Type B
case isTargetURLDir(targetURL):
return cpURLsTypeB
return copyURLsTypeB
// Type A
default:
return cpURLsTypeA
return copyURLsTypeA
}
} // else Type D
return cpURLsTypeD
return copyURLsTypeD
}
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
func prepareCopyURLsTypeA(sourceURL string, targetURL string) <-chan cpURLs {
cpURLsCh := make(chan cpURLs, 10000)
go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) {
defer close(cpURLsCh)
func prepareCopyURLsTypeA(sourceURL string, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs, 10000)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
cpURLsCh <- cpURLs{Error: iodine.New(err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(err, nil)}
return
}
if !sourceContent.Type.IsRegular() {
// Source is not a regular file
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
return
}
targetClient, err := target2Client(targetURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(err, nil)}
return
}
// Target exists?
targetContent, err := targetClient.Stat()
if err == nil { // Target exists.
if !targetContent.Type.IsRegular() { // Target is not a regular file
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
return
}
}
// All OK.. We can proceed. Type A
sourceContent.Name = sourceURL
cpURLsCh <- cpURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}}
}(sourceURL, targetURL, cpURLsCh)
return cpURLsCh
copyURLsCh <- copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{Name: targetURL}}
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
func prepareCopyURLsTypeB(sourceURL string, targetURL string) <-chan cpURLs {
cpURLsCh := make(chan cpURLs, 10000)
go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) {
defer close(cpURLsCh)
func prepareCopyURLsTypeB(sourceURL string, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs, 10000)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
_, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
cpURLsCh <- cpURLs{Error: iodine.New(err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(err, nil)}
return
}
if !sourceContent.Type.IsRegular() {
// Source is not a regular file.
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
return
}
_, targetContent, err := url2Stat(targetURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(err, nil)}
return
}
if err == nil {
if !targetContent.Type.IsDir() {
// Target exists, but is not a directory.
cpURLsCh <- cpURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
return
}
} // Else name is available to create.
@@ -186,33 +186,33 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) <-chan cpURLs {
// All OK.. We can proceed. Type B: source is a file, target is a directory and exists.
sourceURLParse, err := client.Parse(sourceURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
return
}
targetURLParse, err := client.Parse(targetURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
return
}
targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path))
for cURLs := range prepareCopyURLsTypeA(sourceURL, targetURLParse.String()) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
}(sourceURL, targetURL, cpURLsCh)
return cpURLsCh
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
cpURLsCh := make(chan cpURLs, 10000)
go func(sourceURL, targetURL string, cpURLsCh chan cpURLs) {
defer close(cpURLsCh)
func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs, 10000)
go func(sourceURL, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
if !isURLRecursive(sourceURL) {
// Source is not of recursive type.
cpURLsCh <- cpURLs{Error: iodine.New(errSourceNotRecursive{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errSourceNotRecursive{URL: sourceURL}, nil)}
return
}
@@ -221,13 +221,13 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
sourceClient, sourceContent, err := url2Stat(sourceURL)
if err != nil {
// Source does not exist or insufficient privileges.
cpURLsCh <- cpURLs{Error: iodine.New(err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(err, nil)}
return
}
if !sourceContent.Type.IsDir() {
// Source is not a dir.
cpURLsCh <- cpURLs{Error: iodine.New(errSourceIsNotDir{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errSourceIsNotDir{URL: sourceURL}, nil)}
return
}
@@ -235,20 +235,20 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
// Target exist?
if err != nil {
// Target does not exist.
cpURLsCh <- cpURLs{Error: iodine.New(errTargetNotFound{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errTargetNotFound{URL: targetURL}, nil)}
return
}
if !targetContent.Type.IsDir() {
// Target exists, but is not a directory.
cpURLsCh <- cpURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
return
}
for sourceContent := range sourceClient.List(true) {
if sourceContent.Err != nil {
// Listing failed.
cpURLsCh <- cpURLs{Error: iodine.New(sourceContent.Err, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(sourceContent.Err, nil)}
continue
}
@@ -260,13 +260,13 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
// All OK.. We can proceed. Type B: source is a file, target is a directory and exists.
sourceURLParse, err := client.Parse(sourceURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidSource{URL: sourceURL}, nil)}
continue
}
targetURLParse, err := client.Parse(targetURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidTarget{URL: targetURL}, nil)}
continue
}
@@ -276,7 +276,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
sourceContentURL := sourceURLDelimited + sourceContentName
sourceContentParse, err := client.Parse(sourceContentURL)
if err != nil {
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidSource{URL: sourceContentName}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidSource{URL: sourceContentName}, nil)}
continue
}
@@ -284,24 +284,24 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan cpURLs {
newTargetURLParse := *targetURLParse
newTargetURLParse.Path = filepath.Join(newTargetURLParse.Path, sourceContentName)
for cURLs := range prepareCopyURLsTypeA(sourceContentParse.String(), newTargetURLParse.String()) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
}
}(sourceURL, targetURL, cpURLsCh)
return cpURLsCh
}(sourceURL, targetURL, copyURLsCh)
return copyURLsCh
}
// MULTI-SOURCE - Type D: copy([]f, d) -> []B
// prepareCopyURLsTypeD - prepares target and source URLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan cpURLs {
cpURLsCh := make(chan cpURLs, 10000)
go func(sourceURLs []string, targetURL string, cpURLsCh chan cpURLs) {
defer close(cpURLsCh)
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs, 10000)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
if sourceURLs == nil {
// Source list is empty.
cpURLsCh <- cpURLs{Error: iodine.New(errSourceListEmpty{}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errSourceListEmpty{}, nil)}
return
}
@@ -309,13 +309,13 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan cpURLs {
// Target exist?
if err != nil {
// Target does not exist.
cpURLsCh <- cpURLs{Error: iodine.New(errTargetNotFound{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errTargetNotFound{URL: targetURL}, nil)}
return
}
if !targetContent.Type.IsDir() {
// Target exists, but is not a directory.
cpURLsCh <- cpURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errTargetIsNotDir{URL: targetURL}, nil)}
return
}
@@ -325,44 +325,44 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string) <-chan cpURLs {
switch isURLRecursive(sourceURL) {
case true:
for cURLs := range prepareCopyURLsTypeC(sourceURL, targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
case false:
for cURLs := range prepareCopyURLsTypeB(sourceURL, targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
}
}
}(sourceURLs, targetURL, cpURLsCh)
return cpURLsCh
}(sourceURLs, targetURL, copyURLsCh)
return copyURLsCh
}
// prepareCopyURLs - prepares target and source URLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan cpURLs {
cpURLsCh := make(chan cpURLs, 10000)
go func(sourceURLs []string, targetURL string, cpURLsCh chan cpURLs) {
defer close(cpURLsCh)
func prepareCopyURLs(sourceURLs []string, targetURL string) <-chan copyURLs {
copyURLsCh := make(chan copyURLs, 10000)
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
defer close(copyURLsCh)
switch guessCopyURLType(sourceURLs, targetURL) {
case cpURLsTypeA:
case copyURLsTypeA:
for cURLs := range prepareCopyURLsTypeA(sourceURLs[0], targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
case cpURLsTypeB:
case copyURLsTypeB:
for cURLs := range prepareCopyURLsTypeB(sourceURLs[0], targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
case cpURLsTypeC:
case copyURLsTypeC:
for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
case cpURLsTypeD:
case copyURLsTypeD:
for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL) {
cpURLsCh <- cURLs
copyURLsCh <- cURLs
}
default:
cpURLsCh <- cpURLs{Error: iodine.New(errInvalidArgument{}, nil)}
copyURLsCh <- copyURLs{Error: iodine.New(errInvalidArgument{}, nil)}
}
}(sourceURLs, targetURL, cpURLsCh)
}(sourceURLs, targetURL, copyURLsCh)
return cpURLsCh
return copyURLsCh
}
+2
View File
@@ -16,6 +16,7 @@
package main
/*
import (
"bytes"
"io/ioutil"
@@ -186,3 +187,4 @@ func (s *CmdTestSuite) TestCpTypeD(c *C) {
c.Assert(err, IsNil)
}
}
*/
+10 -2
View File
@@ -78,11 +78,19 @@ func getSystemData() map[string]string {
}
}
func migrate() {
// Migrate session files if any.
migrateSession()
}
func main() {
// enable GOMAXPROCS to default to number of CPUs
// Migrate any old version of config / state files to newer format.
migrate()
// Enable GOMAXPROCS to default to number of CPUs.
runtime.GOMAXPROCS(runtime.NumCPU())
// register all the commands
// Register all the commands
registerCmd(lsCmd) // List contents of a bucket
registerCmd(mbCmd) // make a bucket
registerCmd(catCmd) // concantenate an object to standard output
+65 -30
View File
@@ -17,15 +17,17 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"runtime"
"strings"
"sync/atomic"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/console"
"github.com/minio/pb"
"github.com/olekukonko/ts"
)
type pbBarCmd int
@@ -39,18 +41,6 @@ const (
pbBarCmdSetCaption
)
type fakeReader struct {
size int64
}
func (r *fakeReader) Read(p []byte) (n int, err error) {
return int(r.size), io.EOF
}
func putFakeTarget(reader io.Reader) {
io.Copy(ioutil.Discard, reader)
}
type proxyReader struct {
io.Reader
bar *barSend
@@ -58,14 +48,10 @@ type proxyReader struct {
func (r *proxyReader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
r.bar.progress(int64(n))
r.bar.Progress(int64(n))
return
}
func (b *barSend) NewProxyReader(r io.Reader) *proxyReader {
return &proxyReader{r, b}
}
type barMsg struct {
Cmd pbBarCmd
Arg interface{}
@@ -76,11 +62,15 @@ type barSend struct {
finishCh <-chan bool
}
func (b *barSend) NewProxyReader(r io.Reader) *proxyReader {
return &proxyReader{r, b}
}
func (b barSend) Extend(total int64) {
b.cmdCh <- barMsg{Cmd: pbBarCmdExtend, Arg: total}
}
func (b barSend) progress(progress int64) {
func (b barSend) Progress(progress int64) {
b.cmdCh <- barMsg{Cmd: pbBarCmdProgress, Arg: progress}
}
@@ -109,7 +99,13 @@ func cursorAnimate() <-chan rune {
if runtime.GOOS == "windows" {
cursors = "|/-\\"
} else {
cursors = "➩➪➫➬➭➮➯➱"
// cursors = "➩➪➫➬➭➮➯➱"
// cursors = "▁▃▄▅▆▇█▇▆▅▄▃"
cursors = "◐◓◑◒"
// cursors = "←↖↑↗→↘↓↙"
// cursors = "⣾⣽⣻⢿⡿⣟⣯⣷"
// cursors = "◴◷◶◵"
// cursors = "◰◳◲◱"
}
go func() {
for {
@@ -121,18 +117,18 @@ func cursorAnimate() <-chan rune {
return cursorCh
}
func fixateBarCaption(c string, s string, width int) string {
func fixateBarCaption(caption string, width int) string {
switch {
case len(c) > width:
case len(caption) > width:
// Trim caption to fit within the screen
trimSize := len(c) - width + 3
if trimSize < len(c) {
c = "..." + c[trimSize:]
trimSize := len(caption) - width + 3
if trimSize < len(caption) {
caption = "..." + caption[trimSize:]
}
case len(c) < width:
c = c + strings.Repeat(" ", width-len(c))
case len(caption) < width:
caption += strings.Repeat(" ", width-len(caption))
}
return s + " " + c
return caption
}
func getFixedWidth(width, percent int) int {
@@ -154,7 +150,7 @@ func newCpBar() barSend {
bar.Callback = func(s string) {
console.Bar("\r" + s)
}
cursorCh := cursorAnimate()
// cursorCh := cursorAnimate()
if runtime.GOOS == "windows" {
bar.Format("[=> ]")
} else {
@@ -163,7 +159,7 @@ func newCpBar() barSend {
for msg := range cmdCh {
switch msg.Cmd {
case pbBarCmdSetCaption:
bar.Prefix(fixateBarCaption(msg.Arg.(string), string(<-cursorCh), getFixedWidth(bar.GetWidth(), 18)))
bar.Prefix(fixateBarCaption(msg.Arg.(string), getFixedWidth(bar.GetWidth(), 18)))
case pbBarCmdExtend:
atomic.AddInt64(&bar.Total, msg.Arg.(int64))
case pbBarCmdProgress:
@@ -194,3 +190,42 @@ func newCpBar() barSend {
}(cmdCh, finishCh)
return barSend{cmdCh, finishCh}
}
/******************************** Scan Bar ************************************/
// fixateScanBar truncates long text to fit within the terminal size.
func fixateScanBar(text string, width int) string {
if len([]rune(text)) > width {
// Trim text to fit within the screen
trimSize := len([]rune(text)) - width + 3 //"..."
if trimSize < len([]rune(text)) {
text = "..." + text[trimSize:]
}
}
return text
}
// Progress bar function report objects being scaned.
type scanBarFunc func(string)
// scanBarFactory returns a progress bar function to report URL scanning.
func scanBarFactory(prefix string) scanBarFunc {
prevLineSize := 0
fileCount := 0
termSize, _ := ts.GetSize()
termWidth := termSize.Col()
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("Scanning %s [%s] %s ", prefix, humanize.Comma(int64(fileCount)), string(<-cursorCh))
if prevLineSize != 0 { // erase previous line
console.PrintC("\r" + scanPrefix + strings.Repeat(" ", prevLineSize-len([]rune(scanPrefix))))
}
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix))-1)
barText := "\r" + scanPrefix + source
console.PrintC(barText)
prevLineSize = len([]rune(barText))
fileCount++
}
}
+7
View File
@@ -45,6 +45,7 @@ type Theme struct {
SessionID *color.Color
JSON *color.Color
Bar *color.Color
PrintC *color.Color
Print *color.Color
}
@@ -82,6 +83,12 @@ var (
return
}
// PrintC prints a message with color
PrintC = func(data ...interface{}) {
print(themesDB[currThemeName].PrintC, data...)
return
}
// Printf prints a formatted message
Printf = func(f string, data ...interface{}) {
printf(themesDB[currThemeName].Print, f, data...)
+3
View File
@@ -32,6 +32,7 @@ var MiniTheme = Theme{
Time: (color.New(color.FgGreen)),
JSON: (color.New(color.FgWhite, color.Italic)),
Bar: (color.New(color.FgGreen, color.Bold)),
PrintC: (color.New(color.FgGreen, color.Bold)),
Print: (color.New()),
}
@@ -49,6 +50,7 @@ var WhiteTheme = Theme{
Time: (color.New(color.FgWhite, color.Bold)),
JSON: (color.New(color.FgWhite, color.Bold, color.Italic)),
Bar: (color.New(color.FgWhite, color.Bold)),
PrintC: (color.New(color.FgWhite, color.Bold)),
Print: (color.New()),
}
@@ -66,5 +68,6 @@ var NoColorTheme = Theme{
Time: (color.New()),
JSON: (color.New()),
Bar: (color.New()),
PrintC: (color.New()),
Print: (color.New()),
}
+2 -10
View File
@@ -30,7 +30,6 @@ import (
"sync"
"github.com/fatih/structs"
"github.com/minio/mc/pkg/atomic"
"github.com/minio/minio/pkg/iodine"
)
@@ -116,22 +115,15 @@ func (d config) Save(filename string) (err error) {
return iodine.New(err, nil)
}
file, err := atomic.FileCreate(filename)
if err != nil {
return iodine.New(err, nil)
}
if runtime.GOOS == "windows" {
jsonData = []byte(strings.Replace(string(jsonData), "\n", "\r\n", -1))
}
_, err = file.Write(jsonData)
err = ioutil.WriteFile(filename, jsonData, 0600)
if err != nil {
return iodine.New(err, nil)
}
if err := file.Close(); err != nil {
return iodine.New(err, nil)
}
return nil
}
+103
View File
@@ -0,0 +1,103 @@
/*
* 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 (
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/quick"
"github.com/minio/minio/pkg/iodine"
)
type sessionV1 struct {
Version string `json:"version"`
Started time.Time `json:"started"`
CommandType string `json:"command-type"`
SessionID string `json:"session-id"`
URLs []string `json:"args"`
Files map[string]bool `json:"files"`
Lock *sync.Mutex `json:"-"`
}
func (s sessionV1) String() string {
message := console.Time("[%s] ", s.Started.Local().Format(printDate))
message = message + console.SessionID("%s", s.SessionID)
message = message + console.Command(" [%s %s]", s.CommandType, strings.Join(s.URLs, " "))
return message
}
// loadSession - reads session file if exists and re-initiates internal variables
func loadSessionV1(sid string) (*sessionV1, error) {
if !isSessionDirExists() {
return nil, iodine.New(errInvalidArgument{}, nil)
}
sessionFile := getSessionFileV1(sid)
_, err := os.Stat(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
s := new(sessionV1)
s.Version = "1.0.0"
// map of command and files copied
s.URLs = nil
s.Lock = new(sync.Mutex)
s.Files = make(map[string]bool)
qs, err := quick.New(s)
if err != nil {
return nil, iodine.New(err, nil)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
return qs.Data().(*sessionV1), nil
}
func getSessionIDsV1() (sids []string) {
sessionList, err := filepath.Glob(getSessionDir() + "/*")
if err != nil {
console.Fatalf("Unable to list session directory ‘%s’, %s", getSessionDir(), iodine.New(err, nil))
}
for _, path := range sessionList {
sidReg := regexp.MustCompile("^[a-zA-Z]{8}$")
sid := filepath.Base(path)
if sidReg.Match([]byte(sid)) {
sessionV1, err := loadSessionV1(sid)
if err != nil {
console.Fatalf("Unable to load session ‘%s’, %s", sid, iodine.New(err, nil))
}
if sessionV1.Version != "1.0.0" {
continue
}
sids = append(sids, sid)
}
}
return sids
}
func getSessionFileV1(sid string) string {
return filepath.Join(getSessionDir(), sid)
}
+237
View File
@@ -0,0 +1,237 @@
/*
* 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.
*/
// Session V2 - Version 2 stores session header and session data in
// two separate files. Session data contains fully prepared URL list.
package main
import (
"io"
"os"
"strings"
"sync"
"time"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/quick"
"github.com/minio/minio/pkg/iodine"
)
// migrateSessionV1ToV2 migrates all session files from v1 to v2. This
// function should be called from the main early on.
func migrateSessionV1ToV2() {
// TODO: Fill it in.
for _, sid := range getSessionIDsV1() {
err := os.Remove(getSessionFileV1(sid))
if err != nil {
console.Fatalf("Migration failed. Unable to remove old session file %s. %s\n", getSessionFileV1(sid), iodine.New(err, nil))
}
}
}
type sessionV2Header struct {
Version string `json:"version"`
When time.Time `json:"time"`
RootPath string `json:"working-directory"`
CommandType string `json:"command-type"`
CommandArgs []string `json:"cmd-args"`
LastCopied string `json:"last-copied"`
TotalBytes int64 `json:"total-bytes"`
TotalObjects int `json:"total-objects"`
}
type sessionV2 struct {
Header *sessionV2Header
SessionID string
mutex *sync.Mutex
DataFP *os.File
sigCh bool
}
// provides a new session
func newSessionV2() *sessionV2 {
// TODO: Blindly create .mc and session dirs at init and remove these checks -ab.
if !isMcConfigExists() {
console.Fatals(ErrorMessage{
Message: "Please run \"mc config generate\"",
Error: iodine.New(errNotConfigured{}, nil),
})
}
if !isSessionDirExists() {
if err := createSessionDir(); err != nil {
console.Fatals(ErrorMessage{
Message: "Failed with",
Error: iodine.New(err, nil),
})
}
}
s := &sessionV2{}
s.Header = &sessionV2Header{}
s.Header.Version = "1.1.0"
// map of command and files copied
s.Header.CommandArgs = nil
s.Header.When = time.Now().UTC()
s.mutex = new(sync.Mutex)
s.SessionID = newSID(8)
var err error
s.DataFP, err = os.Create(getSessionDataFile(s.SessionID))
if err != nil {
console.Fatals(ErrorMessage{
Message: "Unable to create session data file \"" + getSessionDataFile(s.SessionID) + "\"",
Error: iodine.New(errNotConfigured{}, nil),
})
}
return s
}
func (s *sessionV2) String() string {
message := console.SessionID("%s -> ", s.SessionID)
message = message + console.Time("[%s]", s.Header.When.Local().Format(printDate))
message = message + console.Command(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " "))
return message
}
func (s *sessionV2) Info() {
console.Infos(InfoMessage{
Message: "\nSession terminated. To resume session type ‘mc session resume " + s.SessionID + "’",
})
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV2) HasData() bool {
if s.Header.LastCopied == "" {
return false
}
return true
}
// NewDataReader provides reader interface to session data file.
func (s *sessionV2) NewDataReader() io.Reader {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Reader(s.DataFP)
}
// NewDataReader provides writer interface to session data file.
func (s *sessionV2) NewDataWriter() io.Writer {
// DataFP is always intitialized, either via new or load functions.
s.DataFP.Seek(0, os.SEEK_SET)
return io.Writer(s.DataFP)
}
// save this session
func (s *sessionV2) Save() error {
s.mutex.Lock()
defer s.mutex.Unlock()
err := s.DataFP.Sync()
if err != nil {
return iodine.New(err, nil)
}
qs, err := quick.New(s.Header)
if err != nil {
return iodine.New(err, nil)
}
return qs.Save(getSessionFile(s.SessionID))
}
// Close ends this session and removes all associated session files.
func (s *sessionV2) Close() error {
s.mutex.Lock()
defer s.mutex.Unlock()
err := os.Remove(getSessionDataFile(s.SessionID))
if err != nil {
return iodine.New(err, nil)
}
err = os.Remove(getSessionFile(s.SessionID))
if err != nil {
return iodine.New(err, nil)
}
if err != nil {
return iodine.New(err, nil)
}
return nil
}
// loadSession - reads session file if exists and re-initiates internal variables
func loadSessionV2(sid string) (*sessionV2, error) {
if !isSessionDirExists() {
return nil, iodine.New(errInvalidArgument{}, nil)
}
sessionFile := getSessionFile(sid)
_, err := os.Stat(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
s := &sessionV2{}
s.Header = &sessionV2Header{}
s.SessionID = sid
s.Header.Version = "1.1.0"
qs, err := quick.New(s.Header)
if err != nil {
return nil, iodine.New(err, nil)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
s.mutex = new(sync.Mutex)
s.Header = qs.Data().(*sessionV2Header)
s.DataFP, err = os.Open(getSessionDataFile(s.SessionID))
if err != nil {
console.Fatals(ErrorMessage{
Message: "Unable to open session data file \"" + getSessionDataFile(s.SessionID) + "\"",
Error: iodine.New(errNotConfigured{}, nil),
})
}
return s, nil
}
// Create a factory function to simplify checking if an
// object has been copied or not.
// isCopied(URL) -> true or false
func isCopiedFactory(lastCopied string) func(string) bool {
copied := true // closure
return func(sourceURL string) bool {
if sourceURL == "" {
console.Fatalln("Empty source URL passed to isCopied() function. Please report this bug.")
}
if lastCopied == "" {
return false
}
if copied {
if lastCopied == sourceURL {
copied = false // from next call onwards we say false.
}
return true
}
return false
}
}
+24 -93
View File
@@ -21,39 +21,19 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/quick"
"github.com/minio/minio/pkg/iodine"
)
type sessionV1 struct {
Version string `json:"version"`
Started time.Time `json:"started"`
CommandType string `json:"command-type"`
SessionID string `json:"session-id"`
RootPath string `json:"working-directory"`
URLs []string `json:"args"`
Files map[string]struct{} `json:"files"`
Lock *sync.Mutex `json:"-"`
}
func (s sessionV1) String() string {
message := console.SessionID("%s -> ", s.SessionID)
message = message + console.Time("[%s]", s.Started.Local().Format(printDate))
message = message + console.Command(" %s %s", s.CommandType, strings.Join(s.URLs, " "))
return message
func migrateSession() {
// Migrate session V1 to V2
migrateSessionV1ToV2()
}
func isSessionDirExists() bool {
sdir, err := getSessionDir()
if err != nil {
return false
}
_, err = os.Stat(sdir)
_, err := os.Stat(getSessionDir())
if err != nil {
return false
}
@@ -61,25 +41,20 @@ func isSessionDirExists() bool {
}
func createSessionDir() error {
sdir, err := getSessionDir()
if err != nil {
return iodine.New(err, nil)
}
if err := os.MkdirAll(sdir, 0700); err != nil {
if err := os.MkdirAll(getSessionDir(), 0700); err != nil {
return iodine.New(err, nil)
}
return nil
}
func getSessionDir() (string, error) {
mcConfigDir, err := getMcConfigDir()
func getSessionDir() string {
configDir, err := getMcConfigDir()
if err != nil {
return "", iodine.New(err, nil)
// TODO: revamp error handling -ab. Do not pass errors mindlessly to upper layer for a tool like mc.
}
return filepath.Join(mcConfigDir, sessionDir), nil
return filepath.Join(configDir, sessionDir)
}
var mcCurrentSessionVersion = mcCurrentConfigVersion
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// newSID generates a random session id of regular lower case and uppercase english characters
@@ -92,75 +67,31 @@ func newSID(n int) string {
return string(b)
}
func newSessionV1() (config quick.Config, err error) {
s := new(sessionV1)
s.Version = mcCurrentSessionVersion
// map of command and files copied
s.URLs = nil
s.Started = time.Now().UTC()
s.Files = make(map[string]struct{})
s.Lock = new(sync.Mutex)
s.SessionID = newSID(8)
return quick.New(s)
func getSessionFile(sid string) string {
return filepath.Join(getSessionDir(), sid+".json")
}
func getSessionFile(sid string) (string, error) {
sdir, err := getSessionDir()
if err != nil {
return "", iodine.New(err, nil)
}
return filepath.Join(sdir, sid), nil
func getSessionDataFile(sid string) string {
return filepath.Join(getSessionDir(), sid+".data")
}
// save a session
func saveSession(s *sessionV1) error {
sessionFile, err := getSessionFile(s.SessionID)
func getSessionIDs() (sids []string) {
sessionList, err := filepath.Glob(getSessionDir() + "/*.json")
if err != nil {
return err
console.Fatalf("Unable to list session directory ‘%s’, %s", getSessionDir(), iodine.New(err, nil))
}
qs, err := quick.New(s)
if err != nil {
return err
for _, path := range sessionList {
sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json"))
}
return qs.Save(sessionFile)
return sids
}
// provides a new session
func newSession() (*sessionV1, error) {
qs, err := newSessionV1()
func isSession(sid string) bool {
_, err := os.Stat(getSessionFile(sid))
if err != nil {
return nil, iodine.New(err, nil)
return false
}
return qs.Data().(*sessionV1), nil
}
// loadSession - reads session file if exists and re-initiates internal variables
func loadSession(sid string) (*sessionV1, error) {
if !isSessionDirExists() {
return nil, iodine.New(errInvalidArgument{}, nil)
}
sessionFile, err := getSessionFile(sid)
if err != nil {
return nil, iodine.New(err, nil)
}
_, err = os.Stat(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
s := new(sessionV1)
s.Version = mcCurrentSessionVersion
// map of command and files copied
s.URLs = nil
s.Lock = new(sync.Mutex)
s.Files = make(map[string]struct{})
qs, err := quick.New(s)
if err != nil {
return nil, iodine.New(err, nil)
}
err = qs.Load(sessionFile)
if err != nil {
return nil, iodine.New(err, nil)
}
return qs.Data().(*sessionV1), nil
return true
}
+7 -4
View File
@@ -34,15 +34,18 @@ func (s *CmdTestSuite) TestSession(c *C) {
c.Assert(err, IsNil)
c.Assert(isSessionDirExists(), Equals, true)
session, err := newSession()
session := newSessionV2()
c.Assert(err, IsNil)
c.Assert(session.URLs, IsNil)
c.Assert(session.Header.CommandArgs, IsNil)
c.Assert(len(session.SessionID), Equals, 8)
err = saveSession(session)
err = session.Save()
c.Assert(err, IsNil)
savedSession, err := loadSession(session.SessionID)
savedSession, err := loadSessionV2(session.SessionID)
c.Assert(err, IsNil)
c.Assert(session.SessionID, Equals, savedSession.SessionID)
err = session.Close()
c.Assert(err, IsNil)
}
+46
View File
@@ -0,0 +1,46 @@
/*
* 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
// signalTrap traps the registered signals and notifies the caller.
import (
"os"
"os/signal"
)
func signalTrap(sig ...os.Signal) <-chan bool {
// channel to notify the caller.
trapCh := make(chan bool, 1)
go func(chan<- bool) {
// channel to receive signals.
sigCh := make(chan os.Signal, 1)
defer close(sigCh)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigCh, sig...)
// Wait for the signal
<-sigCh
// Notify the caller
trapCh <- true
}(trapCh)
return trapCh
}
+12 -12
View File
@@ -49,7 +49,7 @@ import (
type syncURLs struct {
SourceContent *client.Content
TargetContents []*client.Content
Error error
Error error `json:"-"`
}
func (s syncURLs) IsEmpty() bool {
@@ -68,26 +68,26 @@ func (s syncURLs) IsEmpty() bool {
return empty
}
type syncURLsType cpURLsType
type syncURLsType copyURLsType
// guessSyncURLType guesses the type of URL. This approach all allows prepareURL
// functions to accurately report failure causes.
func guessSyncURLType(sourceURL string, targetURLs []string) syncURLsType {
if targetURLs == nil { // Target is empty
return syncURLsType(cpURLsTypeInvalid)
return syncURLsType(copyURLsTypeInvalid)
}
if sourceURL == "" { // Source list is empty
return syncURLsType(cpURLsTypeInvalid)
return syncURLsType(copyURLsTypeInvalid)
}
if isURLRecursive(sourceURL) { // Type C
return syncURLsType(cpURLsTypeC)
return syncURLsType(copyURLsTypeC)
} // else Type A or Type B
for _, targetURL := range targetURLs {
if isTargetURLDir(targetURL) { // Type B
return syncURLsType(cpURLsTypeB)
return syncURLsType(copyURLsTypeB)
}
} // else Type A
return syncURLsType(cpURLsTypeA)
return syncURLsType(copyURLsTypeA)
}
// prepareSyncURLsTypeA - A: sync(f, f) -> copy(f, f)
@@ -97,7 +97,7 @@ func prepareSyncURLsTypeA(sourceURL string, targetURLs []string) <-chan syncURLs
defer close(syncURLsCh)
var sURLs syncURLs
for _, targetURL := range targetURLs {
var cURLs cpURLs
var cURLs copyURLs
for cURLs = range prepareCopyURLsTypeA(sourceURL, targetURL) {
if cURLs.Error != nil {
syncURLsCh <- syncURLs{Error: iodine.New(cURLs.Error, nil)}
@@ -121,7 +121,7 @@ func prepareSyncURLsTypeB(sourceURL string, targetURLs []string) <-chan syncURLs
defer close(syncURLsCh)
var sURLs syncURLs
for _, targetURL := range targetURLs {
var cURLs cpURLs
var cURLs copyURLs
for cURLs = range prepareCopyURLsTypeB(sourceURL, targetURL) {
if cURLs.Error != nil {
syncURLsCh <- syncURLs{Error: iodine.New(cURLs.Error, nil)}
@@ -231,15 +231,15 @@ func prepareSyncURLs(sourceURL string, targetURLs []string) <-chan syncURLs {
go func() {
defer close(syncURLsCh)
switch guessSyncURLType(sourceURL, targetURLs) {
case syncURLsType(cpURLsTypeA):
case syncURLsType(copyURLsTypeA):
for sURLs := range prepareSyncURLsTypeA(sourceURL, targetURLs) {
syncURLsCh <- sURLs
}
case syncURLsType(cpURLsTypeB):
case syncURLsType(copyURLsTypeB):
for sURLs := range prepareSyncURLsTypeB(sourceURL, targetURLs) {
syncURLsCh <- sURLs
}
case syncURLsType(cpURLsTypeC):
case syncURLsType(copyURLsTypeC):
for sURLs := range prepareSyncURLsTypeC(sourceURL, targetURLs) {
syncURLsCh <- sURLs
}
+2
View File
@@ -16,6 +16,7 @@
package main
/*
import (
"bytes"
"io/ioutil"
@@ -149,3 +150,4 @@ func (s *CmdTestSuite) TestSyncTypeC(c *C) {
c.Assert(err, IsNil)
}
}
*/