diff --git a/cmd-cp.go b/cmd-cp.go index 52f78e46..f3f72e91 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -20,7 +20,10 @@ import ( "fmt" "io" "math" + "os" + "os/signal" "runtime" + "strings" "sync" "github.com/minio/cli" @@ -108,6 +111,16 @@ func doCopyInRoutine(cURLs cpURLs, bar *barSend, cpQueue chan bool, errCh chan e <-cpQueue // Signal that this copy routine is done. } +func doCopyInRoutineSession(cURLs cpURLs, bar *barSend, cpQueue chan bool, errCh chan error, wg *sync.WaitGroup, s *sessionV1) { + defer wg.Done() + if err := doCopy(cURLs, bar); err != nil { + errCh <- err + } + <-cpQueue // Signal that this copy routine is done. + // store files which have finished copying + s.Files = append(s.Files, cURLs.SourceContent.Name) +} + func doPrepareCopyURLs(sourceURLs []string, targetURL string, bar barSend, lock countlock.Locker) { for cURLs := range prepareCopyURLs(sourceURLs, targetURL) { if cURLs.Error != nil { @@ -122,6 +135,64 @@ func doPrepareCopyURLs(sourceURLs []string, targetURL string, bar barSend, lock } } +func trap(sid string) { + // 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 + if err := saveSession(sid); err != nil { + console.Fatalln(err) + } + console.Fatal() +} + +func doCopySession(sourceURLs []string, targetURL string, bar barSend, s *sessionV1) <-chan error { + errCh := make(chan error) + go func(sourceURLs []string, targetURL string, bar barSend, errCh chan error, s *sessionV1) { + defer close(errCh) + go trap(s.SessionID) + + var lock countlock.Locker + if !globalQuietFlag { + // Keep progress-bar and copy routines in sync. + lock = countlock.New() + defer lock.Close() + } + + // 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 { + errCh <- cURLs.Error + continue + } + 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. + } + go doCopyInRoutineSession(cURLs, &bar, cpQueue, errCh, wg, s) + } + wg.Wait() // wait for the go routines to complete + }(sourceURLs, targetURL, bar, errCh, s) + return errCh +} + func doCopyCmd(sourceURLs []string, targetURL string, bar barSend) <-chan error { errCh := make(chan error) go func(sourceURLs []string, targetURL string, bar barSend, errCh chan error) { @@ -172,6 +243,24 @@ func runCopyCmd(ctx *cli.Context) { }) } + var s *sessionV1 + var err error + var resume bool + var sid = "" + switch resume { + case false: + s, err = newSession() + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + case true: + s, err = loadSession(sid) + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + } + s.Command = "mc cp " + strings.Join(ctx.Args(), " ") + // extract URLs. URLs, err := args2URLs(ctx.Args()) if err != nil { @@ -192,7 +281,7 @@ func runCopyCmd(ctx *cli.Context) { bar = newCpBar() } - for err := range doCopyCmd(sourceURLs, targetURL, bar) { + for err := range doCopySession(sourceURLs, targetURL, bar, s) { if err != nil { console.Errors(ErrorMessage{ Message: "Failed with", diff --git a/cmd-session.go b/cmd-session.go index f12ca706..e814164c 100644 --- a/cmd-session.go +++ b/cmd-session.go @@ -17,9 +17,6 @@ package main import ( - "crypto/rand" - "fmt" - "io" "io/ioutil" "os" "path/filepath" @@ -54,51 +51,6 @@ EXAMPLES: `, } -func isSessionDirExists() bool { - sdir, err := getSessionDir() - if err != nil { - return false - } - _, err = os.Stat(sdir) - if err != nil { - return false - } - return true -} - -func createSessionDir() error { - sdir, err := getSessionDir() - if err != nil { - return err - } - if err := os.MkdirAll(sdir, 0700); err != nil { - return err - } - return nil -} - -func getSessionDir() (string, error) { - mcConfigDir, err := getMcConfigDir() - if err != nil { - return "", err - } - return filepath.Join(mcConfigDir, sessionDir), nil -} - -// newUUID generates a random UUID according to RFC 4122 -func newUUID() string { - uuid := make([]byte, 16) - _, err := io.ReadFull(rand.Reader, uuid) - if err != nil { - panic(err) - } - // variant bits; see section 4.1.1 - uuid[8] = uuid[8]&^0xc0 | 0x80 - // version 4 (pseudo-random); see section 4.1.3 - uuid[6] = uuid[6]&^0xf0 | 0x40 - return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) -} - func runSessionCmd(ctx *cli.Context) { if len(ctx.Args()) < 1 || ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code diff --git a/session.go b/session.go new file mode 100644 index 00000000..77fde69b --- /dev/null +++ b/session.go @@ -0,0 +1,180 @@ +/* + * 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 ( + "crypto/rand" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sync" + + "github.com/minio/mc/pkg/quick" + "github.com/minio/minio/pkg/iodine" +) + +type sessionV1 struct { + Version string + SessionID string + Command string + Files []string +} + +// cached variables should *NEVER* be accessed directly from outside this file. +var scache sync.Pool + +func isSessionDirExists() bool { + sdir, err := getSessionDir() + if err != nil { + return false + } + _, err = os.Stat(sdir) + if err != nil { + return false + } + return true +} + +func createSessionDir() error { + sdir, err := getSessionDir() + if err != nil { + return iodine.New(err, nil) + } + if err := os.MkdirAll(sdir, 0700); err != nil { + return iodine.New(err, nil) + } + return nil +} + +func getSessionDir() (string, error) { + mcConfigDir, err := getMcConfigDir() + if err != nil { + return "", iodine.New(err, nil) + } + return filepath.Join(mcConfigDir, sessionDir), nil +} + +var mcCurrentSessionVersion = mcCurrentConfigVersion + +// newUUID generates a random UUID according to RFC 4122 +func newUUID() string { + uuid := make([]byte, 16) + _, err := io.ReadFull(rand.Reader, uuid) + if err != nil { + panic(err) + } + // variant bits; see section 4.1.1 + uuid[8] = uuid[8]&^0xc0 | 0x80 + // version 4 (pseudo-random); see section 4.1.3 + uuid[6] = uuid[6]&^0xf0 | 0x40 + return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) +} + +func newSessionV1() (config quick.Config, err error) { + s := new(sessionV1) + s.Version = mcCurrentSessionVersion + // map of command and files copied + s.Command = "" + s.Files = nil + s.SessionID = newUUID() + return quick.New(s) +} + +func writeSession(config quick.Config) error { + if err := createSessionDir(); err != nil { + return iodine.New(err, nil) + } + sdir, err := getSessionDir() + if err != nil { + return iodine.New(err, nil) + } + if err := config.Save(filepath.Join(sdir, config.Data().(*sessionV1).SessionID)); err != nil { + return iodine.New(err, nil) + } + return nil +} + +func getSessionFile(sid string) (string, error) { + sdir, err := getSessionDir() + if err != nil { + return "", iodine.New(err, nil) + } + return filepath.Join(sdir, sid), nil +} + +// save a session +func saveSession(sid string) error { + sessionFile, err := getSessionFile(sid) + if err != nil { + return err + } + // Use previously cached config. + if v := scache.Get(); v != nil { + return v.(quick.Config).Save(sessionFile) + } + return errors.New("No cached session found") +} + +// provides a new session +func newSession() (*sessionV1, error) { + qs, err := newSessionV1() + if err != nil { + return nil, iodine.New(err, nil) + } + if err := writeSession(qs); err != nil { + return nil, iodine.New(err, nil) + } + scache.Put(qs) + 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) + } + // Cached in private global variable. + if v := scache.Get(); v != nil { // Use previously cached config. + return v.(quick.Config).Data().(*sessionV1), nil + } + s := new(sessionV1) + s.Version = mcCurrentSessionVersion + // map of command and files copied + s.Command = "" + s.Files = nil + 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) + } + scache.Put(qs) + return qs.Data().(*sessionV1), nil + +} diff --git a/trap.go b/trap.go deleted file mode 100644 index 223320fc..00000000 --- a/trap.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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" - "os/signal" -) - -func trapInRoutine(done chan bool) { - // Go signal notification works by sending `os.Signal` - // values on a channel. We'll create a channel to - // receive these notifications (we'll also make one to - // notify us when the program can exit). - 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 goroutine executes a blocking receive for - // signals. When it gets one it'll print it out - // and then notify the program that it can finish. - go func() { - <-sigs - done <- true - }() -} - -// The program will wait on trap() until it gets the -// expected signal (as indicated by the goroutine -// above sending a value on `done`) -func trap() <-chan bool { - done := make(chan bool, 1) - go trapInRoutine(done) - return done -}