cp: Only use session when -c is passed (#2989)

This commit is contained in:
Anis Elleuch
2019-12-13 10:20:56 -08:00
committed by kannappanr
parent 64e0c36e3b
commit f2f8f858a6
12 changed files with 155 additions and 577 deletions
+3
View File
@@ -138,6 +138,9 @@ func (a *accounter) Get() int64 {
return atomic.LoadInt64(&a.current)
}
func (a *accounter) SetTotal(int64) {
}
// Add add to current value atomically.
func (a *accounter) Add(n int64) int64 {
return atomic.AddInt64(&a.current, n)
+127 -89
View File
@@ -137,8 +137,8 @@ EXAMPLES:
{{.Prompt}} {{.HelpName}} --storage-class REDUCED_REDUNDANCY myobject.txt play/mybucket
14. Copy a text file to an object storage and create or resume copy session.
{{.Prompt}} {{.HelpName}} --recursive --continue myobject.txt play/mybucket
{{.Prompt}} {{.HelpName}} --recursive --continue dir/ play/mybucket
15. Copy a text file to an object storage and preserve the file system attribute as metadata.
{{.Prompt}} {{.HelpName}} -a myobject.txt play/mybucket
`,
@@ -172,6 +172,7 @@ func (c copyMessage) JSON() string {
// of data written.
type Progress interface {
Get() int64
SetTotal(int64)
}
// ProgressReader can be used to update the progress of
@@ -219,15 +220,12 @@ func doCopyFake(cpURLs URLs, pg Progress) URLs {
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) (totalBytes, totalObjects int64) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int64
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
@@ -245,7 +243,8 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
if !globalQuiet && !globalJSON { // set up progress bar
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB)
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan)
done := false
for !done {
select {
@@ -273,16 +272,6 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
@@ -300,34 +289,84 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
return
}
func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) error {
func doCopySession(cli *cli.Context, session *sessionV8, encKeyDB map[string][]prefixSSEPair) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
ctx, cancelCopy := context.WithCancel(context.Background())
defer cancelCopy()
if !session.HasData() {
doPrepareCopyURLs(session, trapCh, cancelCopy)
}
// Prepare URL scanner from session data file.
urlScanner := bufio.NewScanner(session.NewDataReader())
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isLastFactory(session.Header.LastCopied)
var isCopied func(string) bool
var totalObjects, totalBytes int64
var cpURLsCh = make(chan URLs, 10000)
// Store a progress bar or an accounter
var pg ProgressReader
// Enable progress bar reader only during default mode.
if !globalQuiet && !globalJSON { // set up progress bar
pg = newProgressBar(session.Header.TotalBytes)
pg = newProgressBar(totalBytes)
} else {
pg = newAccounter(session.Header.TotalBytes)
pg = newAccounter(totalBytes)
}
if session != nil {
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied = isLastFactory(session.Header.LastCopied)
if !session.HasData() {
totalBytes, totalObjects = doPrepareCopyURLs(session, trapCh, cancelCopy)
} else {
totalBytes, totalObjects = session.Header.TotalBytes, session.Header.TotalObjects
}
pg.SetTotal(totalBytes)
go func() {
// Prepare URL scanner from session data file.
urlScanner := bufio.NewScanner(session.NewDataReader())
for {
if !urlScanner.Scan() || urlScanner.Err() != nil {
close(cpURLsCh)
break
}
var cpURLs URLs
if e := json.Unmarshal([]byte(urlScanner.Text()), &cpURLs); e != nil {
errorIf(probe.NewError(e), "Unable to unmarshal %s", urlScanner.Text())
continue
}
cpURLsCh <- cpURLs
}
}()
} else {
sourceURLs := cli.Args()[:len(cli.Args())-1]
targetURL := cli.Args()[len(cli.Args())-1] // Last one is target
// Access recursive flag inside the session header.
isRecursive := cli.Bool("recursive")
olderThan := cli.String("older-than")
newerThan := cli.String("newer-than")
go func() {
totalBytes := int64(0)
for cpURLs := range prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB, olderThan, newerThan) {
totalBytes += cpURLs.SourceContent.Size
pg.SetTotal(totalBytes)
cpURLsCh <- cpURLs
}
close(cpURLsCh)
}()
}
var quitCh = make(chan struct{})
@@ -347,32 +386,17 @@ func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) erro
case <-quitCh:
gracefulStop()
return
default:
if !urlScanner.Scan() {
// No more entries, quit immediately
case cpURLs, ok := <-cpURLsCh:
if !ok {
gracefulStop()
return
}
if e := urlScanner.Err(); e != nil {
// Error while reading. quit immediately
gracefulStop()
return
}
var cpURLs URLs
// Unmarshal copyURLs from each line. This expects each line to be
// an entire JSON object.
if e := json.Unmarshal([]byte(urlScanner.Text()), &cpURLs); e != nil {
errorIf(probe.NewError(e), "Unable to unmarshal %s", urlScanner.Text())
continue
}
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
cpURLs.TotalCount = totalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
cpURLs.TotalSize = totalBytes
// Initialize target metadata.
cpURLs.TargetContent.Metadata = make(map[string]string)
@@ -381,22 +405,22 @@ func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) erro
cpURLs.TargetContent.UserMetadata = make(map[string]string)
// Check and handle storage class if passed in command line args
if _, ok := session.Header.CommandStringFlags["storage-class"]; ok {
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"]
if storageClass := cli.String("storage-class"); storageClass != "" {
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = storageClass
}
// Check and handle metadata if passed in command line args
if len(session.Header.UserMetaData) != 0 {
for metaDataKey, metaDataVal := range session.Header.UserMetaData {
if cli.String("attr") != "" {
userMetaMap, _ := getMetaDataEntry(cli.String("attr"))
for metaDataKey, metaDataVal := range userMetaMap {
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
}
}
// If one needs to store the file system information by passing -a flag
if preserve := (session.Header.CommandBoolFlags["preserve"]); preserve {
if preserve := cli.Bool("preserve"); preserve {
attrValue, pErr := getFileAttrMeta(cpURLs, encKeyDB)
if pErr != nil {
errorIf(pErr, "Unable to fetch file meta info for %s", urlScanner.Text())
errorIf(pErr, "Unable to fetch file meta info for %s", cpURLs.SourceAlias)
continue
}
@@ -405,7 +429,7 @@ func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) erro
}
}
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
if isCopied != nil && isCopied(cpURLs.SourceContent.URL.String()) {
queueCh <- func() URLs {
return doCopyFake(cpURLs, pg)
}
@@ -430,15 +454,19 @@ loop:
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
if session != nil {
session.CloseAndDie()
}
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
break loop
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
if session != nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
}
} else {
// Set exit status for any copy error
@@ -454,10 +482,13 @@ loop:
if isErrIgnored(cpURLs.Error) {
continue loop
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.copyCloseAndDie(session.Header.CommandBoolFlags["session"])
if session != nil {
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.copyCloseAndDie(session.Header.CommandBoolFlags["session"])
}
}
}
}
@@ -523,37 +554,44 @@ func mainCopy(ctx *cli.Context) error {
}
sse := ctx.String("encrypt")
sessionID := getHash("cp", ctx.Args())
if ctx.Bool("continue") && isSessionExists(sessionID) {
resumeSession(sessionID)
return nil
var session *sessionV8
if ctx.Bool("continue") {
sessionID := getHash("cp", ctx.Args())
if isSessionExists(sessionID) {
session, err = loadSessionV8(sessionID)
fatalIf(err.Trace(sessionID), "Unable to load session.")
} else {
session = newSessionV8(sessionID)
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
if ctx.Bool("preserve") {
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
}
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
}
}
session := newSessionV8(sessionID)
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.CommandBoolFlags["session"] = ctx.Bool("continue")
if ctx.Bool("preserve") {
session.Header.CommandBoolFlags["preserve"] = ctx.Bool("preserve")
}
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
e := doCopySession(ctx, session, encKeyDB)
if session != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
e = doCopySession(session, encKeyDB)
session.Delete()
return e
}
+20 -2
View File
@@ -213,7 +213,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
}
// prepareCopyURLs - prepares target and source clientURLs for copying.
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs {
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair, olderThan, newerThan string) chan URLs {
copyURLsCh := make(chan URLs)
go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) {
defer close(copyURLsCh)
@@ -238,5 +238,23 @@ func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, en
}
}(sourceURLs, targetURL, copyURLsCh, encKeyDB)
return copyURLsCh
finalCopyURLsCh := make(chan URLs)
go func() {
defer close(finalCopyURLsCh)
for cpURLs := range copyURLsCh {
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
finalCopyURLsCh <- cpURLs
}
}()
return finalCopyURLsCh
}
-1
View File
@@ -330,7 +330,6 @@ var appCmds = []cli.Command{
watchCmd,
policyCmd,
adminCmd,
sessionCmd,
configCmd,
updateCmd,
versionCmd,
+2 -5
View File
@@ -73,9 +73,7 @@ func newProgressBar(total int64) *progressBar {
}
// Start the progress bar.
if bar.Total > 0 {
bar.Start()
}
bar.Start()
// Copy for future
pgbar.ProgressBar = bar
@@ -109,9 +107,8 @@ func (p *progressBar) Read(buf []byte) (n int, err error) {
return p.ProgressBar.Read(buf)
}
func (p *progressBar) SetTotal(total int64) *progressBar {
func (p *progressBar) SetTotal(total int64) {
p.ProgressBar.Total = total
return p
}
// cursorAnimate - returns a animated rune through read channel for every read.
-161
View File
@@ -1,161 +0,0 @@
/*
* MinIO Client (C) 2017 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 cmd
import (
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var sessionClearFlags = []cli.Flag{
cli.BoolFlag{
Name: "force",
Usage: "force a dangerous clear operation.",
},
}
var sessionClear = cli.Command{
Name: "clear",
Usage: "clear interrupted session",
Action: mainSessionClear,
Before: setGlobalsFromContext,
Flags: append(sessionClearFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} SESSION-ID|all
SESSION-ID:
SESSION - Session can either be $SESSION-ID or all
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Clear session.
{{.Prompt}} {{.HelpName}} ygVIpSJs
2. Clear all sessions.
{{.Prompt}} {{.HelpName}} all
3. Forcefully clear an obsolete session.
{{.Prompt}} {{.HelpName}} ygVIpSJs --force
`,
}
// clearSessionMessage container for clearing session messages.
type clearSessionMessage struct {
Status string `json:"success"`
SessionID string `json:"sessionId"`
}
// String colorized clear session message.
func (c clearSessionMessage) String() string {
msg := "Session `" + c.SessionID + "`"
var colorizedMsg string
switch c.Status {
case "success":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared successfully.")
case "forced":
colorizedMsg = console.Colorize("ClearSession", msg+" cleared forcefully.")
}
return colorizedMsg
}
// JSON jsonified clear session message.
func (c clearSessionMessage) JSON() string {
clearSessionJSONBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(clearSessionJSONBytes)
}
// forceClear - Remove a saved session.
// Used if --force flag is applied.
func forceClear(sid string, session *sessionV8) {
if session != nil {
if err := session.Delete().Trace(sid); err == nil {
// Force unnecesseray removal successful.
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
return
}
}
// Remove obsolete session files.
removeSessionFile(sid)
removeSessionDataFile(sid)
printMsg(clearSessionMessage{Status: "forced", SessionID: sid})
}
// clearSession clear sessions.
func clearSession(sid string, isForce bool) {
var toRemove []string
if sid == "all" {
toRemove = getSessionIDs()
} else {
toRemove = append(toRemove, sid)
}
for _, sid := range toRemove {
session, err := loadSessionV8(sid)
if !isForce {
fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
continue
}
// Forced removal of a session.
forceClear(sid, session)
}
}
// checkSessionClearSyntax - Check syntax of 'session clear sid'.
func checkSessionClearSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code
}
}
// mainSessionClear - Main session clear.
func mainSessionClear(ctx *cli.Context) error {
// Check command arguments
checkSessionClearSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
console.SetColor("SessionTime", color.New(color.FgGreen))
console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold))
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
}
// Set command flags.
isForce := ctx.Bool("force")
// Retrieve requested session id.
sessionID := ctx.Args().Get(0)
// Purge requested session id or all pending sessions.
clearSession(sessionID, isForce)
return nil
}
-89
View File
@@ -1,89 +0,0 @@
/*
* MinIO Client (C) 2017 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 cmd
import (
"sort"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
var sessionList = cli.Command{
Name: "list",
Usage: "list all interrupted sessions",
Before: setGlobalsFromContext,
Action: mainSessionList,
Flags: globalFlags,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List sessions.
{{.Prompt}} {{.HelpName}}
`,
}
// listSessions list all current sessions.
func listSessions() *probe.Error {
var bySessions []*sessionV8
for _, sid := range getSessionIDs() {
session, err := loadSessionV8(sid)
if err != nil {
continue // Skip 'broken' session during listing
}
session.Close() // Session close right here.
bySessions = append(bySessions, session)
}
// sort sessions based on time.
sort.Sort(bySessionWhen(bySessions))
for _, session := range bySessions {
printMsg(session)
}
return nil
}
func checkSessionListSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 0 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
func mainSessionList(ctx *cli.Context) error {
// Check 'session list'.
checkSessionListSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
console.SetColor("SessionTime", color.New(color.FgGreen))
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
}
// List all resumable sessions.
fatalIf(listSessions().Trace(ctx.Args()...), "Unable to list sessions.")
return nil
}
-47
View File
@@ -1,47 +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 cmd
import (
"github.com/minio/cli"
)
var (
sessionFlags = []cli.Flag{}
)
// Resume interrupted operations.
var sessionCmd = cli.Command{
Name: "session",
Usage: "resume interrupted operations",
Action: mainSession,
Flags: append(sessionFlags, globalFlags...),
Before: setGlobalsFromContext,
HideHelpCommand: true,
Subcommands: []cli.Command{
sessionList,
sessionClear,
sessionResume,
},
}
// mainSession - handle for the 'mc session' command.
func mainSession(ctx *cli.Context) error {
cli.ShowCommandHelp(ctx, ctx.Args().First())
return nil
// Sub-commands like "list", "clear", "resume" have their own main.
}
-152
View File
@@ -1,152 +0,0 @@
/*
* MinIO Client (C) 2017 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 cmd
import (
"fmt"
"os"
"sort"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/trie"
)
var sessionResume = cli.Command{
Name: "resume",
Usage: "resume interrupted session",
Action: mainSessionResume,
Flags: globalFlags,
Before: setGlobalsFromContext,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} SESSION-ID
SESSION-ID:
SESSION - Session is your previously saved SESSION-ID
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Resume session.
{{.Prompt}} {{.HelpName}} ygVIpSJs
`,
}
// bySessionWhen is a type for sorting session metadata by time.
type bySessionWhen []*sessionV8
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) }
// sessionExecute - run a given session.
func sessionExecute(s *sessionV8) {
switch s.Header.CommandType {
case "cp":
sseKeys := s.Header.CommandStringFlags["encrypt-key"]
sseServer := s.Header.CommandStringFlags["encrypt"]
encKeyDB, _ := parseAndValidateEncryptionKeys(sseKeys, sseServer)
doCopySession(s, encKeyDB)
}
}
// findClosestSessions to match a given string with sessions trie tree.
func findClosestSessions(session string) []string {
sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings.
for _, sid := range getSessionIDs() {
sessionsTree.Insert(sid)
}
var closestSessions []string
for _, value := range sessionsTree.PrefixMatch(session) {
closestSessions = append(closestSessions, value.(string))
}
sort.Strings(closestSessions)
return closestSessions
}
// checkSessionResumeSyntax - Validate session resume command.
func checkSessionResumeSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "resume", 1) // last argument is exit code
}
}
// mainSessionResume - Main session resume function.
func mainSessionResume(ctx *cli.Context) error {
// Validate session resume syntax.
checkSessionResumeSyntax(ctx)
// Additional command specific theme customization.
console.SetColor("Command", color.New(color.FgWhite, color.Bold))
console.SetColor("SessionID", color.New(color.FgYellow, color.Bold))
console.SetColor("SessionTime", color.New(color.FgGreen))
if !isSessionDirExists() {
fatalIf(createSessionDir().Trace(), "Unable to create session folder.")
}
sessionID := ctx.Args().Get(0)
if !isSessionExists(sessionID) {
closestSessions := findClosestSessions(sessionID)
errorMsg := "Session `" + sessionID + "` not found."
if len(closestSessions) > 0 {
errorMsg += fmt.Sprintf("\n\nDid you mean?\n")
for _, session := range closestSessions {
errorMsg += fmt.Sprintf(" `mc resume session %s`", session)
// break on the first one, it is good enough.
break
}
}
fatalIf(errDummy().Trace(sessionID), errorMsg)
}
resumeSession(sessionID)
return nil
}
// resumeSession - Resumes a session specified by sessionID.
func resumeSession(sessionID string) {
s, err := loadSessionV8(sessionID)
fatalIf(err.Trace(sessionID), "Unable to load session.")
// Restore the state of global variables from this previous session.
s.restoreGlobals()
savedCwd, e := os.Getwd()
fatalIf(probe.NewError(e), "Unable to determine current working folder.")
if s.Header.RootPath != "" {
// change folder to RootPath.
e = os.Chdir(s.Header.RootPath)
fatalIf(probe.NewError(e), "Unable to change working folder to root path while resuming session.")
}
sessionExecute(s)
err = s.Close()
fatalIf(err.Trace(), "Unable to close session file properly.")
err = s.Delete()
fatalIf(err.Trace(), "Unable to clear session files properly.")
// change folder back to saved path.
e = os.Chdir(savedCwd)
fatalIf(probe.NewError(e), "Unable to change working folder to saved path `"+savedCwd+"`.")
}
+1 -12
View File
@@ -253,17 +253,6 @@ func (s *sessionV8) setGlobals() {
s.Header.GlobalBoolFlags["insecure"] = globalInsecure
}
// RestoreGlobals restores the state of global variables.
// Used by resumeSession.
func (s sessionV8) restoreGlobals() {
quiet := s.Header.GlobalBoolFlags["quiet"]
debug := s.Header.GlobalBoolFlags["debug"]
json := s.Header.GlobalBoolFlags["json"]
noColor := s.Header.GlobalBoolFlags["noColor"]
insecure := s.Header.GlobalBoolFlags["insecure"]
setGlobals(quiet, debug, json, noColor, insecure)
}
// IsModified - returns if in memory session header has changed from
// its on disk value.
func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) {
@@ -372,7 +361,7 @@ func (s *sessionV8) Delete() *probe.Error {
// Close a session and exit.
func (s sessionV8) CloseAndDie() {
s.Close()
console.Fatalln("Session safely terminated. To resume session `mc session resume " + s.SessionID + "`")
console.Fatalln("Session safely terminated. Run the same command to resume copy again.")
}
func (s sessionV8) copyCloseAndDie(sessionFlag bool) {
-18
View File
@@ -121,24 +121,6 @@ func getSessionIDs() (sids []string) {
return sids
}
// removeSessionFile - remove the session file, ending with .json
func removeSessionFile(sid string) {
sessionFile, err := getSessionFile(sid)
if err != nil {
return
}
os.Remove(sessionFile)
}
// removeSessionDataFile - remove the session data file, ending with .data
func removeSessionDataFile(sid string) {
dataFile, err := getSessionDataFile(sid)
if err != nil {
return
}
os.Remove(dataFile)
}
func getHash(prefix string, args []string) string {
hasher := sha256.New()
for _, arg := range args {
+2 -1
View File
@@ -563,8 +563,9 @@ FLAGS:
--older-than value copy object(s) older than N days (default: 0)
--newer-than value copy object(s) newer than N days (default: 0)
--storage-class value, --sc value set storage class for new object(s) on target
--preserve,-a preserve file system attributes and bucket policy rules on target bucket(s)
--preserve,-a preserve file system attributes and bucket policy rules on target bucket(s)
--attr add custom metadata for the object (format: KeyName1=string;KeyName2=string)
--continue, -c create or resume copy session
--encrypt value encrypt/decrypt objects (using server-side encryption with server managed keys)
--encrypt-key value encrypt/decrypt objects (using server-side encryption with customer provided keys)
--help, -h show help