Merge pull request #1256 from harshavardhana/cleanup-cp-mirror
cp/mirror: cleanup - now support `--force` flag
This commit is contained in:
+20
-4
@@ -39,6 +39,12 @@ var cpCmd = cli.Command{
|
||||
Name: "cp",
|
||||
Usage: "Copy files and folders from many sources to a single destination.",
|
||||
Action: mainCopy,
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "force a dangerous remove operation.",
|
||||
},
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
@@ -66,6 +72,10 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
var (
|
||||
cpForceFlag = false // cp specific force flag set via command line
|
||||
)
|
||||
|
||||
// copyMessage container for file copy messages
|
||||
type copyMessage struct {
|
||||
Source string `json:"source"`
|
||||
@@ -148,7 +158,7 @@ func doCopyFake(cURLs copyURLs, progressReader interface{}) {
|
||||
}
|
||||
|
||||
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
|
||||
func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
func doPrepareCopyURLs(session *sessionV3, 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 := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
|
||||
@@ -165,6 +175,9 @@ func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
// will be true if '--force' is provided on the command line.
|
||||
cpForceFlag = session.Header.CommandBoolFlag.Value
|
||||
|
||||
URLsCh := prepareCopyURLs(sourceURLs, targetURL)
|
||||
done := false
|
||||
|
||||
@@ -214,7 +227,7 @@ func doPrepareCopyURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doCopySession(session *sessionV2) {
|
||||
func doCopySession(session *sessionV3) {
|
||||
trapCh := signalTrap(os.Interrupt, os.Kill)
|
||||
|
||||
if !session.HasData() {
|
||||
@@ -323,9 +336,8 @@ func mainCopy(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
session := newSessionV2()
|
||||
|
||||
var e error
|
||||
session := newSessionV3()
|
||||
session.Header.CommandType = "cp"
|
||||
session.Header.RootPath, e = os.Getwd()
|
||||
if e != nil {
|
||||
@@ -333,6 +345,10 @@ func mainCopy(ctx *cli.Context) {
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// If force flag is set save it with in session
|
||||
session.Header.CommandBoolFlag.Key = "force"
|
||||
session.Header.CommandBoolFlag.Value = ctx.Bool("force")
|
||||
|
||||
// extract URLs.
|
||||
var err *probe.Error
|
||||
session.Header.CommandArgs, err = args2URLs(ctx.Args())
|
||||
|
||||
@@ -73,18 +73,15 @@ func checkCopySyntax(ctx *cli.Context) {
|
||||
if isURLRecursive(tgtURL) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Recursive option is not supported for target ‘%s’ argument.", tgtURL))
|
||||
}
|
||||
// scope locally
|
||||
{
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
if strings.Count(url.Path, "/") < 2 {
|
||||
if err := bucketExists(tgtURL); err != nil {
|
||||
fatalIf(err.Trace(), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL))
|
||||
}
|
||||
url := client.NewURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if url.Path == string(url.Separator) {
|
||||
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
|
||||
}
|
||||
if strings.Count(url.Path, "/") < 2 {
|
||||
if err := bucketExists(tgtURL); err != nil {
|
||||
fatalIf(err.Trace(), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,6 +231,12 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Source is not a regular file
|
||||
return copyURLs{Error: errInvalidSource(sourceURL).Trace()}
|
||||
}
|
||||
|
||||
_, _, err = url2Stat(targetURL)
|
||||
if err == nil && !cpForceFlag {
|
||||
return copyURLs{Error: errOverWriteNotAllowed(targetURL).Trace()}
|
||||
}
|
||||
|
||||
// All OK.. We can proceed. Type A
|
||||
return copyURLs{SourceContent: sourceContent, TargetContent: &client.Content{URL: *client.NewURL(targetURL)}}
|
||||
}
|
||||
@@ -306,6 +309,13 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
|
||||
newTargetURL := client.NewURL(targetURL)
|
||||
newTargetURL.Path = filepath.Join(newTargetURL.Path,
|
||||
strings.TrimPrefix(sourceContent.Content.URL.Path, url2Dir(sourceURL)))
|
||||
|
||||
// verify if destination exists, and cpForceFlag is not set do not proceed.
|
||||
_, _, err := url2Stat(newTargetURL.String())
|
||||
if err == nil && !cpForceFlag {
|
||||
copyURLsCh <- copyURLs{Error: errOverWriteNotAllowed(newTargetURL.String()).Trace()}
|
||||
return
|
||||
}
|
||||
copyURLsCh <- prepareCopyURLsTypeA(sourceContent.Content.URL.String(), newTargetURL.String())
|
||||
}
|
||||
}(sourceURL, targetURL, copyURLsCh)
|
||||
|
||||
+20
-3
@@ -38,6 +38,12 @@ var mirrorCmd = cli.Command{
|
||||
Name: "mirror",
|
||||
Usage: "Mirror folders recursively from a single source to many destinations.",
|
||||
Action: mainMirror,
|
||||
Flags: []cli.Flag{
|
||||
cli.BoolFlag{
|
||||
Name: "force",
|
||||
Usage: "force a dangerous remove operation.",
|
||||
},
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
@@ -62,6 +68,10 @@ EXAMPLES:
|
||||
`,
|
||||
}
|
||||
|
||||
var (
|
||||
mirrorForceFlag = false // mirror specific force flag set via command line
|
||||
)
|
||||
|
||||
// mirrorMessage container for file mirror messages
|
||||
type mirrorMessage struct {
|
||||
Source string `json:"source"`
|
||||
@@ -148,7 +158,7 @@ func doMirrorFake(sURLs mirrorURLs, progressReader interface{}) {
|
||||
}
|
||||
|
||||
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
|
||||
func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
func doPrepareMirrorURLs(session *sessionV3, trapCh <-chan bool) {
|
||||
sourceURL := session.Header.CommandArgs[0] // first one is source.
|
||||
targetURLs := session.Header.CommandArgs[1:]
|
||||
var totalBytes int64
|
||||
@@ -162,6 +172,9 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
// will be true if '--force' is provided on the command line.
|
||||
mirrorForceFlag = session.Header.CommandBoolFlag.Value
|
||||
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURLs)
|
||||
done := false
|
||||
for done == false {
|
||||
@@ -208,7 +221,7 @@ func doPrepareMirrorURLs(session *sessionV2, trapCh <-chan bool) {
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func doMirrorSession(session *sessionV2) {
|
||||
func doMirrorSession(session *sessionV3) {
|
||||
trapCh := signalTrap(os.Interrupt, os.Kill)
|
||||
|
||||
if !session.HasData() {
|
||||
@@ -319,7 +332,7 @@ func mainMirror(ctx *cli.Context) {
|
||||
console.SetColor("Mirror", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
var e error
|
||||
session := newSessionV2()
|
||||
session := newSessionV3()
|
||||
session.Header.CommandType = "mirror"
|
||||
session.Header.RootPath, e = os.Getwd()
|
||||
if e != nil {
|
||||
@@ -327,6 +340,10 @@ func mainMirror(ctx *cli.Context) {
|
||||
fatalIf(probe.NewError(e), "Unable to get current working folder.")
|
||||
}
|
||||
|
||||
// If force flag is set save it with in session
|
||||
session.Header.CommandBoolFlag.Key = "force"
|
||||
session.Header.CommandBoolFlag.Value = ctx.Bool("force")
|
||||
|
||||
// extract URLs.
|
||||
var err *probe.Error
|
||||
session.Header.CommandArgs, err = args2URLs(ctx.Args())
|
||||
|
||||
+25
-12
@@ -159,7 +159,7 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
|
||||
}
|
||||
// targets have to be directory.
|
||||
if !targetContent.Type.IsDir() {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace()}
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(targetURL).Trace(newSourceURL)}
|
||||
return
|
||||
}
|
||||
// special case, be extremely careful before changing this behavior - will lead to data loss.
|
||||
@@ -190,25 +190,38 @@ func deltaSourceTargets(sourceURL string, targetURLs []string, mirrorURLsCh chan
|
||||
if targetContents[i] != nil {
|
||||
newTargetURLPath = strings.TrimPrefix(targetContents[i].URL.Path, targetClients[i].GetURL().Path)
|
||||
}
|
||||
// Trim any preceding separators.
|
||||
newSourceURLPath := strings.TrimPrefix(srcContent.URL.Path, string(srcContent.URL.Separator))
|
||||
// either target reached EOF or target does not have source content.
|
||||
if targetContents[i] == nil || srcContent.URL.Path != newTargetURLPath {
|
||||
if targetContents[i] == nil || newSourceURLPath != newTargetURLPath {
|
||||
targetURL := client.NewURL(urlJoinPath(newTargetURLs[i], srcContent.URL.String()))
|
||||
mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL})
|
||||
continue
|
||||
}
|
||||
|
||||
// source and target have same content
|
||||
if srcContent.Type.IsRegular() && targetContents[i].Type.IsRegular() {
|
||||
// but size mismatches
|
||||
if srcContent.Size != targetContents[i].Size {
|
||||
targetURL := client.NewURL(urlJoinPath(newTargetURLs[i], srcContent.URL.String()))
|
||||
mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL})
|
||||
if newSourceURLPath == newTargetURLPath {
|
||||
// source and target have same content type.
|
||||
if srcContent.Type.IsRegular() && targetContents[i].Type.IsRegular() {
|
||||
if srcContent.Size != targetContents[i].Size {
|
||||
if !mirrorForceFlag {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: errOverWriteNotAllowed(targetContents[i].URL.String()).Trace(srcContent.URL.String()),
|
||||
}
|
||||
continue
|
||||
}
|
||||
targetURL := client.NewURL(urlJoinPath(newTargetURLs[i], srcContent.URL.String()))
|
||||
mirrorTargets = append(mirrorTargets, &client.Content{URL: *targetURL})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if srcContent.Type.IsRegular() && !targetContents[i].Type.IsRegular() {
|
||||
// but type mismatches, error condition fail and continue.
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: errInvalidTarget(targetContents[i].URL.String()).Trace(srcContent.URL.String()),
|
||||
}
|
||||
continue
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// source and target have different content type
|
||||
// TODO: add error
|
||||
}
|
||||
if len(mirrorTargets) > 0 {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
|
||||
+8
-7
@@ -57,16 +57,16 @@ EXAMPLES:
|
||||
}
|
||||
|
||||
// bySessionWhen is a type for sorting session metadata by time
|
||||
type bySessionWhen []*sessionV2
|
||||
type bySessionWhen []*sessionV3
|
||||
|
||||
func (b bySessionWhen) Len() int { return len(b) }
|
||||
func (b bySessionWhen) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
|
||||
func (b bySessionWhen) Less(i, j int) bool { return b[i].Header.When.Before(b[j].Header.When) }
|
||||
|
||||
func listSessions() *probe.Error {
|
||||
var bySessions []*sessionV2
|
||||
var bySessions []*sessionV3
|
||||
for _, sid := range getSessionIDs() {
|
||||
s, err := loadSessionV2(sid)
|
||||
s, err := loadSessionV3(sid)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
@@ -76,6 +76,7 @@ func listSessions() *probe.Error {
|
||||
sort.Sort(bySessionWhen(bySessions))
|
||||
for _, session := range bySessions {
|
||||
printMsg(session)
|
||||
session.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -102,7 +103,7 @@ func (c clearSessionMessage) JSON() string {
|
||||
func clearSession(sid string) {
|
||||
if sid == "all" {
|
||||
for _, sid := range getSessionIDs() {
|
||||
session, err := loadSessionV2(sid)
|
||||
session, err := loadSessionV3(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
fatalIf(session.Delete().Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
@@ -116,7 +117,7 @@ func clearSession(sid string) {
|
||||
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
|
||||
}
|
||||
|
||||
session, err := loadSessionV2(sid)
|
||||
session, err := loadSessionV3(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session ‘"+sid+"’.")
|
||||
|
||||
if session != nil {
|
||||
@@ -125,7 +126,7 @@ func clearSession(sid string) {
|
||||
}
|
||||
}
|
||||
|
||||
func sessionExecute(s *sessionV2) {
|
||||
func sessionExecute(s *sessionV3) {
|
||||
switch s.Header.CommandType {
|
||||
case "cp":
|
||||
doCopySession(s)
|
||||
@@ -180,7 +181,7 @@ func mainSession(ctx *cli.Context) {
|
||||
fatalIf(errDummy().Trace(), "Session ‘"+sid+"’ not found.")
|
||||
}
|
||||
|
||||
s, err := loadSessionV2(sid)
|
||||
s, err := loadSessionV3(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load session.")
|
||||
|
||||
// extra check for testing purposes
|
||||
|
||||
+7
-233
@@ -19,15 +19,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
@@ -56,186 +50,8 @@ type sessionV2Header struct {
|
||||
TotalObjects int `json:"total-objects"`
|
||||
}
|
||||
|
||||
// SessionMessage container for session messages
|
||||
type SessionMessage struct {
|
||||
SessionID string `json:"sessionid"`
|
||||
Time time.Time `json:"time"`
|
||||
CommandType string `json:"command-type"`
|
||||
CommandArgs []string `json:"command-args"`
|
||||
}
|
||||
|
||||
// sessionV2
|
||||
type sessionV2 struct {
|
||||
Header *sessionV2Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
type sessionDataFP struct {
|
||||
dirty bool
|
||||
*os.File
|
||||
}
|
||||
|
||||
func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
file.dirty = true
|
||||
return file.File.Write(p)
|
||||
}
|
||||
|
||||
// String colorized session message
|
||||
func (s sessionV2) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified session message
|
||||
func (s sessionV2) JSON() string {
|
||||
sessionMesage := SessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
CommandType: s.Header.CommandType,
|
||||
CommandArgs: s.Header.CommandArgs,
|
||||
}
|
||||
sessionBytes, e := json.Marshal(sessionMesage)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// newSessionV2 provides a new session
|
||||
func newSessionV2() *sessionV2 {
|
||||
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 = newRandomID(8)
|
||||
|
||||
sessionDataFile, perr := getSessionDataFile(s.SessionID)
|
||||
fatalIf(perr.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
dataFile, err := os.Create(sessionDataFile)
|
||||
fatalIf(probe.NewError(err), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
return s
|
||||
}
|
||||
|
||||
// String printer for SessionV2
|
||||
func (s sessionV2) Info() {
|
||||
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
|
||||
}
|
||||
|
||||
func gracefulSessionSave(session *sessionV2) {
|
||||
session.Close()
|
||||
session.Info()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
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() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP.dirty {
|
||||
if err := s.DataFP.Sync(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace()
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV2) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if err := s.DataFP.Close(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace()
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV2) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP != nil {
|
||||
name := s.DataFP.Name()
|
||||
// close file pro-actively before deleting
|
||||
// ignore any error, it could be possibly that
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
err := os.Remove(name)
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
if err := os.Remove(sessionFile); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadSession - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV2(sid string) (*sessionV2, *probe.Error) {
|
||||
func loadSessionV2(sid string) (*sessionV2Header, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -243,60 +59,18 @@ func loadSessionV2(sid string) (*sessionV2, *probe.Error) {
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(sessionFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
s := &sessionV2{}
|
||||
s.Header = &sessionV2Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "1.1.0"
|
||||
qs, err := quick.New(s.Header)
|
||||
sessionHeader := &sessionV2Header{}
|
||||
sessionHeader.Version = "1.1.0"
|
||||
qs, err := quick.New(sessionHeader)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
return nil, err.Trace(sid, sessionHeader.Version)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV2Header)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
var e error
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
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 == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return nil, err.Trace(sid, sessionHeader.Version)
|
||||
}
|
||||
return sessionHeader, nil
|
||||
}
|
||||
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
/*
|
||||
* 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 (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
)
|
||||
|
||||
func migrateSessionV2ToV3() {
|
||||
for _, sid := range getSessionIDs() {
|
||||
oldSessionV2Header, err := loadSessionV2(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to load version ‘1.1.0’. Migration failed please report this issue at https://github.com/minio/mc/issues.")
|
||||
if oldSessionV2Header.Version == "3" {
|
||||
return
|
||||
}
|
||||
newSessionV3Header := &sessionV3Header{}
|
||||
newSessionV3Header.Version = "3"
|
||||
newSessionV3Header.When = oldSessionV2Header.When
|
||||
newSessionV3Header.RootPath = oldSessionV2Header.RootPath
|
||||
newSessionV3Header.CommandType = oldSessionV2Header.CommandType
|
||||
newSessionV3Header.CommandArgs = oldSessionV2Header.CommandArgs
|
||||
newSessionV3Header.LastCopied = oldSessionV2Header.LastCopied
|
||||
newSessionV3Header.TotalBytes = oldSessionV2Header.TotalBytes
|
||||
newSessionV3Header.TotalObjects = oldSessionV2Header.TotalObjects
|
||||
|
||||
qs, err := quick.New(newSessionV3Header)
|
||||
fatalIf(err.Trace(sid), "Unable to initialize quick config.")
|
||||
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
fatalIf(err.Trace(sid), "Unable to get session file.")
|
||||
|
||||
err = qs.Save(sessionFile)
|
||||
fatalIf(err.Trace(sid), "Saving new session file for version ‘3’ failed.")
|
||||
}
|
||||
}
|
||||
|
||||
// sessionV3Header
|
||||
type sessionV3Header struct {
|
||||
Version string `json:"version"`
|
||||
When time.Time `json:"time"`
|
||||
RootPath string `json:"workingFolder"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"cmdArgs"`
|
||||
CommandBoolFlag struct {
|
||||
Key string
|
||||
Value bool
|
||||
} `json:"cmdBoolFlag"`
|
||||
CommandIntFlag struct {
|
||||
Key string
|
||||
Value int
|
||||
} `json:"cmdIntFlag"`
|
||||
CommandStringFlag struct {
|
||||
Key string
|
||||
Value string
|
||||
} `json:"cmdStringFlag"`
|
||||
LastCopied string `json:"lastCopied"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
TotalObjects int `json:"totalObjects"`
|
||||
}
|
||||
|
||||
// SessionMessage container for session messages
|
||||
type SessionMessage struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
Time time.Time `json:"time"`
|
||||
CommandType string `json:"commandType"`
|
||||
CommandArgs []string `json:"commandArgs"`
|
||||
}
|
||||
|
||||
// sessionV3
|
||||
type sessionV3 struct {
|
||||
Header *sessionV3Header
|
||||
SessionID string
|
||||
mutex *sync.Mutex
|
||||
DataFP *sessionDataFP
|
||||
sigCh bool
|
||||
}
|
||||
|
||||
type sessionDataFP struct {
|
||||
dirty bool
|
||||
*os.File
|
||||
}
|
||||
|
||||
func (file *sessionDataFP) Write(p []byte) (int, error) {
|
||||
file.dirty = true
|
||||
return file.File.Write(p)
|
||||
}
|
||||
|
||||
// String colorized session message
|
||||
func (s sessionV3) String() string {
|
||||
message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID))
|
||||
message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate)))
|
||||
message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " ")))
|
||||
return message
|
||||
}
|
||||
|
||||
// JSON jsonified session message
|
||||
func (s sessionV3) JSON() string {
|
||||
sessionMesage := SessionMessage{
|
||||
SessionID: s.SessionID,
|
||||
Time: s.Header.When.Local(),
|
||||
CommandType: s.Header.CommandType,
|
||||
CommandArgs: s.Header.CommandArgs,
|
||||
}
|
||||
sessionBytes, e := json.Marshal(sessionMesage)
|
||||
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
|
||||
|
||||
return string(sessionBytes)
|
||||
}
|
||||
|
||||
// newSessionV3 provides a new session
|
||||
func newSessionV3() *sessionV3 {
|
||||
s := &sessionV3{}
|
||||
s.Header = &sessionV3Header{}
|
||||
s.Header.Version = "3"
|
||||
// map of command and files copied
|
||||
s.Header.CommandArgs = nil
|
||||
s.Header.CommandBoolFlag.Key = ""
|
||||
s.Header.CommandBoolFlag.Value = false
|
||||
s.Header.CommandIntFlag.Key = ""
|
||||
s.Header.CommandIntFlag.Value = 0
|
||||
s.Header.CommandStringFlag.Key = ""
|
||||
s.Header.CommandStringFlag.Value = ""
|
||||
s.Header.When = time.Now().UTC()
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.SessionID = newRandomID(8)
|
||||
|
||||
sessionDataFile, perr := getSessionDataFile(s.SessionID)
|
||||
fatalIf(perr.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
dataFile, err := os.Create(sessionDataFile)
|
||||
fatalIf(probe.NewError(err), "Unable to create session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
return s
|
||||
}
|
||||
|
||||
// String printer for SessionV3
|
||||
func (s sessionV3) Info() {
|
||||
console.Infoln("Session safely terminated. To resume session ‘mc session resume " + s.SessionID + "’")
|
||||
}
|
||||
|
||||
func gracefulSessionSave(session *sessionV3) {
|
||||
session.Close()
|
||||
session.Info()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// HasData provides true if this is a session resume, false otherwise.
|
||||
func (s sessionV3) HasData() bool {
|
||||
if s.Header.LastCopied == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NewDataReader provides reader interface to session data file.
|
||||
func (s *sessionV3) 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 *sessionV3) 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 *sessionV3) Save() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP.dirty {
|
||||
if err := s.DataFP.Sync(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
s.DataFP.dirty = false
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
}
|
||||
|
||||
// Close ends this session and removes all associated session files.
|
||||
func (s *sessionV3) Close() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if err := s.DataFP.Close(); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
return qs.Save(sessionFile).Trace(sessionFile)
|
||||
}
|
||||
|
||||
// Delete removes all the session files.
|
||||
func (s *sessionV3) Delete() *probe.Error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
if s.DataFP != nil {
|
||||
name := s.DataFP.Name()
|
||||
// close file pro-actively before deleting
|
||||
// ignore any error, it could be possibly that
|
||||
// the file is closed already
|
||||
s.DataFP.Close()
|
||||
|
||||
err := os.Remove(name)
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sessionFile, err := getSessionFile(s.SessionID)
|
||||
if err != nil {
|
||||
return err.Trace(s.SessionID)
|
||||
}
|
||||
|
||||
if err := os.Remove(sessionFile); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadSessionV3 - reads session file if exists and re-initiates internal variables
|
||||
func loadSessionV3(sid string) (*sessionV3, *probe.Error) {
|
||||
if !isSessionDirExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
sessionFile, err := getSessionFile(sid)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(sessionFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
s := &sessionV3{}
|
||||
s.Header = &sessionV3Header{}
|
||||
s.SessionID = sid
|
||||
s.Header.Version = "3"
|
||||
qs, err := quick.New(s.Header)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
err = qs.Load(sessionFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
s.mutex = new(sync.Mutex)
|
||||
s.Header = qs.Data().(*sessionV3Header)
|
||||
|
||||
sessionDataFile, err := getSessionDataFile(s.SessionID)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sid, s.Header.Version)
|
||||
}
|
||||
|
||||
var e error
|
||||
dataFile, e := os.Open(sessionDataFile)
|
||||
fatalIf(probe.NewError(e), "Unable to open session data file \""+sessionDataFile+"\".")
|
||||
|
||||
s.DataFP = &sessionDataFP{false, dataFile}
|
||||
|
||||
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 == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.")
|
||||
}
|
||||
if lastCopied == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if copied {
|
||||
if lastCopied == sourceURL {
|
||||
copied = false // from next call onwards we say false.
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ import (
|
||||
func migrateSession() {
|
||||
// Migrate session V1 to V2
|
||||
migrateSessionV1ToV2()
|
||||
|
||||
// Migrate session V2 to V3
|
||||
migrateSessionV2ToV3()
|
||||
}
|
||||
|
||||
func createSessionDir() *probe.Error {
|
||||
|
||||
+3
-3
@@ -36,14 +36,14 @@ func (s *TestSuite) TestSession(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(isSessionDirExists(), Equals, true)
|
||||
|
||||
session := newSessionV2()
|
||||
session := newSessionV3()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
|
||||
err = session.Close()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
savedSession, err := loadSessionV2(session.SessionID)
|
||||
savedSession, err := loadSessionV3(session.SessionID)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(session.SessionID, Equals, savedSession.SessionID)
|
||||
|
||||
@@ -90,7 +90,7 @@ func (s *TestSuite) TestSessionContext(c *C) {
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
session := newSessionV2()
|
||||
session := newSessionV3()
|
||||
c.Assert(session.Header.CommandArgs, IsNil)
|
||||
c.Assert(len(session.SessionID), Equals, 8)
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ var (
|
||||
return probe.NewError(errors.New("Invalid target ‘" + URL + "’.")).Untrace()
|
||||
}
|
||||
|
||||
errOverWriteNotAllowed = func(URL string) *probe.Error {
|
||||
return probe.NewError(errors.New("Overwrite not allowed for ‘" + URL + "’. Use ‘--force’ to override this behavior."))
|
||||
}
|
||||
|
||||
errSourceNotRecursive = func(URL string) *probe.Error {
|
||||
return probe.NewError(errors.New("Source ‘" + URL + "’ is not recursive.")).Untrace()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user