From de16a72e29c0e34a0f65d55074df43b9184af1d5 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 19 Jun 2015 17:22:35 -0700 Subject: [PATCH 1/3] Add session command, first cut --- cmd-session.go | 145 +++++++++++++++++++++++++++++++++++++++++++++++++ globals.go | 5 ++ main.go | 19 ++++--- 3 files changed, 160 insertions(+), 9 deletions(-) create mode 100644 cmd-session.go diff --git a/cmd-session.go b/cmd-session.go new file mode 100644 index 00000000..f12ca706 --- /dev/null +++ b/cmd-session.go @@ -0,0 +1,145 @@ +/* + * 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" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/iodine" +) + +// Help message. +var sessionCmd = cli.Command{ + Name: "session", + Usage: "Start sessions for cp and sync", + Action: runSessionCmd, + 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: + -- TODO -- + +`, +} + +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 + } + if strings.TrimSpace(ctx.Args().First()) == "" { + cli.ShowCommandHelpAndExit(ctx, "session", 1) // last argument is exit code + } + if !isSessionDirExists() { + if err := createSessionDir(); err != nil { + console.Fatalln(iodine.ToError(err)) + } + } + switch strings.TrimSpace(ctx.Args().First()) { + // list resumable sessions + case "list": + sessionDir, err := getSessionDir() + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + sessions, err := ioutil.ReadDir(sessionDir) + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + for _, session := range sessions { + if session.Mode().IsRegular() { + console.Infoln(session.Name()) + } + } + // purge all pending sessions + case "clear": + sessions, err := ioutil.ReadDir(sessionDir) + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + for _, session := range sessions { + if session.Mode().IsRegular() { + err := os.Remove(filepath.Join(sessionDir, session.Name())) + if err != nil { + console.Fatalln(iodine.ToError(err)) + } + } + } + } +} diff --git a/globals.go b/globals.go index 878ee60b..085b4987 100644 --- a/globals.go +++ b/globals.go @@ -33,6 +33,11 @@ const ( mcConfigFile = "config.json" ) +// session config related constants +const ( + sessionDir = "session" +) + // default access and secret key const ( // do not pass accesskeyid and secretaccesskey through cli diff --git a/main.go b/main.go index 5f4241f7..4a907465 100644 --- a/main.go +++ b/main.go @@ -83,15 +83,16 @@ func main() { runtime.GOMAXPROCS(runtime.NumCPU()) // register all the commands - registerCmd(lsCmd) // List contents of a bucket - registerCmd(mbCmd) // make a bucket - registerCmd(catCmd) // concantenate an object to standard output - registerCmd(cpCmd) // copy objects and files from multiple sources to single destination - registerCmd(syncCmd) // copy objects and files from single source to multiple destionations - registerCmd(diffCmd) // compare two objects - registerCmd(accessCmd) // set permissions [public, private, readonly, authenticated] for buckets and folders. - registerCmd(configCmd) // generate configuration "/home/harsha/.mc/config.json" file. - registerCmd(updateCmd) // update Check for new software updates + registerCmd(lsCmd) // List contents of a bucket + registerCmd(mbCmd) // make a bucket + registerCmd(catCmd) // concantenate an object to standard output + registerCmd(cpCmd) // copy objects and files from multiple sources to single destination + registerCmd(syncCmd) // sync objects and files from single source to multiple destinations + registerCmd(sessionCmd) // session handling for resuming copy and sync operations + registerCmd(diffCmd) // compare two objects + registerCmd(accessCmd) // set permissions [public, private, readonly, authenticated] for buckets and folders. + registerCmd(configCmd) // generate configuration "/home/harsha/.mc/config.json" file. + registerCmd(updateCmd) // update Check for new software updates // register all the flags registerFlag(quietFlag) // suppress console output From 7284c4a767305bf72a9820ad1a010665e74d38bb Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 19 Jun 2015 18:25:55 -0700 Subject: [PATCH 2/3] Add trap function to trap os.Kill and os.Interrupt --- trap.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 trap.go diff --git a/trap.go b/trap.go new file mode 100644 index 00000000..223320fc --- /dev/null +++ b/trap.go @@ -0,0 +1,51 @@ +/* + * 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 +} From 183396ebb17937aa478bda4c42f7446d2ec514ff Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 19 Jun 2015 19:53:58 -0700 Subject: [PATCH 3/3] Add session handling for cp --- cmd-cp.go | 91 ++++++++++++++++++++++++- cmd-session.go | 48 ------------- session.go | 180 +++++++++++++++++++++++++++++++++++++++++++++++++ trap.go | 51 -------------- 4 files changed, 270 insertions(+), 100 deletions(-) create mode 100644 session.go delete mode 100644 trap.go 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 -}