diff --git a/cmd/time.go b/cmd/humanized-duration.go similarity index 70% rename from cmd/time.go rename to cmd/humanized-duration.go index bb0658d2..a8306c36 100644 --- a/cmd/time.go +++ b/cmd/humanized-duration.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015 Minio, Inc. + * 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. @@ -22,16 +22,28 @@ import ( "time" ) -// humanizedTime container to capture humanized time. -type humanizedTime struct { +// humanizedDuration container to capture humanized time. +type humanizedDuration struct { Days int64 `json:"days,omitempty"` Hours int64 `json:"hours,omitempty"` Minutes int64 `json:"minutes,omitempty"` Seconds int64 `json:"seconds,omitempty"` } -// String() humanizes humanizedTime to human readable, -func (r humanizedTime) String() string { +// StringShort() humanizes humanizedDuration to human readable short format. +// This does not print at seconds. +func (r humanizedDuration) StringShort() string { + if r.Days == 0 && r.Hours == 0 { + return fmt.Sprintf("%d minutes", r.Minutes) + } + if r.Days == 0 { + return fmt.Sprintf("%d hours %d minutes", r.Hours, r.Minutes) + } + return fmt.Sprintf("%d days %d hours %d minutes", r.Days, r.Hours, r.Minutes) +} + +// String() humanizes humanizedDuration to human readable, +func (r humanizedDuration) String() string { if r.Days == 0 && r.Hours == 0 && r.Minutes == 0 { return fmt.Sprintf("%d seconds", r.Seconds) } @@ -44,9 +56,9 @@ func (r humanizedTime) String() string { return fmt.Sprintf("%d days %d hours %d minutes %d seconds", r.Days, r.Hours, r.Minutes, r.Seconds) } -// timeDurationToHumanizedTime convert golang time.Duration to a custom more readable humanizedTime. -func timeDurationToHumanizedTime(duration time.Duration) humanizedTime { - r := humanizedTime{} +// timeDurationToHumanizedDuration convert golang time.Duration to a custom more readable humanizedDuration. +func timeDurationToHumanizedDuration(duration time.Duration) humanizedDuration { + r := humanizedDuration{} if duration.Seconds() < 60.0 { r.Seconds = int64(duration.Seconds()) return r diff --git a/cmd/main.go b/cmd/main.go index 5306de8e..e531e0a4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -25,6 +25,7 @@ import ( "sort" "strconv" "strings" + "time" "github.com/cheggaaa/pb" "github.com/minio/cli" @@ -243,6 +244,21 @@ func findClosestCommands(command string) []string { return closestCommands } +// Check for updates and print a notification message +func checkUpdate(ctx *cli.Context) { + // Do not print update messages, if quiet flag is set. + if ctx.Bool("quiet") || ctx.GlobalBool("quiet") { + older, downloadURL, err := getUpdateInfo(1 * time.Second) + if err != nil { + // Its OK to ignore any errors during getUpdateInfo() here. + return + } + if older > time.Duration(0) { + console.Println(colorizeUpdateMessage(downloadURL, older)) + } + } +} + func registerApp() *cli.App { // Register all the commands (refer flags.go) registerCmd(lsCmd) // List contents of a bucket. @@ -276,15 +292,8 @@ func registerApp() *cli.App { app := cli.NewApp() app.Action = func(ctx *cli.Context) { if strings.HasPrefix(Version, "RELEASE.") { - updateMsg, _, err := getReleaseUpdate(mcUpdateStableURL) - if err != nil { - // Ignore any errors during getReleaseUpdate() because - // the internet might not be available. - return - } - if updateMsg.Update { - printMsg(updateMsg) - } + // Check for new updates from dl.minio.io. + checkUpdate(ctx) } cli.ShowAppHelp(ctx) } diff --git a/cmd/mc_test.go b/cmd/mc_test.go index 367fc4ab..7327410a 100644 --- a/cmd/mc_test.go +++ b/cmd/mc_test.go @@ -99,19 +99,19 @@ func (s *TestSuite) TestIsvalidAliasName(c *C) { } func (s *TestSuite) TestHumanizedTime(c *C) { - hTime := timeDurationToHumanizedTime(time.Duration(10) * time.Second) + hTime := timeDurationToHumanizedDuration(time.Duration(10) * time.Second) c.Assert(hTime.Minutes, Equals, int64(0)) c.Assert(hTime.Hours, Equals, int64(0)) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Minute) + hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Minute) c.Assert(hTime.Hours, Equals, int64(0)) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(10) * time.Hour) + hTime = timeDurationToHumanizedDuration(time.Duration(10) * time.Hour) c.Assert(hTime.Days, Equals, int64(0)) - hTime = timeDurationToHumanizedTime(time.Duration(24) * time.Hour) + hTime = timeDurationToHumanizedDuration(time.Duration(24) * time.Hour) c.Assert(hTime.Days, Not(Equals), int64(0)) } diff --git a/cmd/notifier.go b/cmd/notifier.go index a571b7e2..881a5fd9 100644 --- a/cmd/notifier.go +++ b/cmd/notifier.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2015 Minio, Inc. + * 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. @@ -21,38 +21,44 @@ import ( "math" "runtime" "strings" + "time" "github.com/cheggaaa/pb" "github.com/fatih/color" - "github.com/minio/minio/pkg/probe" ) -// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier. -func colorizeUpdateMessage(updateString string) (string, *probe.Error) { - // initialize coloring +// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier +func colorizeUpdateMessage(updateString string, newerThan time.Duration) string { + // Initialize coloring. cyan := color.New(color.FgCyan, color.Bold).SprintFunc() yellow := color.New(color.FgYellow, color.Bold).SprintfFunc() - // calculate length without color coding, due to ANSI color characters padded to actual - // string the final length is wrong than the original string length. - line1Str := fmt.Sprintf(" New update available, please execute the following command to update: ") - line2Str := fmt.Sprintf(" %s ", updateString) + // Calculate length without color coding, due to ANSI color + // characters padded to actual string the final length is wrong + // than the original string length. + hTime := timeDurationToHumanizedDuration(newerThan) + line1Str := fmt.Sprintf(" mc is %s old ", hTime.StringShort()) + line2Str := fmt.Sprintf(" Update: %s ", updateString) line1Length := len(line1Str) line2Length := len(line2Str) - // populate lines with color coding. - line1InColor := line1Str - line2InColor := fmt.Sprintf(" %s ", cyan(updateString)) + // Populate lines with color coding. + line1InColor := fmt.Sprintf(" mc is %s old ", yellow(hTime.StringShort())) + line2InColor := fmt.Sprintf(" Update: %s ", cyan(updateString)) // calculate the rectangular box size. maxContentWidth := int(math.Max(float64(line1Length), float64(line2Length))) line1Rest := maxContentWidth - line1Length line2Rest := maxContentWidth - line2Length - termWidth, e := pb.GetTerminalWidth() - if e != nil { - return "", probe.NewError(e) + // termWidth is set to a default one to use when we are + // not able to calculate terminal width via OS syscalls + termWidth := 25 + + if width, err := pb.GetTerminalWidth(); err == nil { + termWidth = width } + var message string switch { case len(line2Str) > termWidth: @@ -80,6 +86,6 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) { sideBar + line2InColor + spacePaddingLine2 + sideBar + "\n" + bottom + "\n" } - // return the final message - return message, nil + // Return the final message. + return message } diff --git a/cmd/share.go b/cmd/share.go index d1293dc0..c748230e 100644 --- a/cmd/share.go +++ b/cmd/share.go @@ -61,7 +61,7 @@ type shareMesssage struct { // String - Themefied string message for console printing. func (s shareMesssage) String() string { msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL)) - msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedTime(s.TimeLeft))) + msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedDuration(s.TimeLeft))) if s.ContentType != "" { msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType)) } diff --git a/cmd/update-main.go b/cmd/update-main.go index 0cc33851..8b4b3359 100644 --- a/cmd/update-main.go +++ b/cmd/update-main.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2015 Minio, Inc. + * Minio Client (C) 2015, 2016, 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. @@ -17,10 +17,13 @@ package cmd import ( + "bytes" "encoding/json" - "errors" + "fmt" "io/ioutil" "net/http" + "os" + "os/exec" "runtime" "strings" "time" @@ -31,204 +34,257 @@ import ( "github.com/minio/minio/pkg/probe" ) -// command specific flags. -var ( - updateFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "experimental, E", - Usage: "Check experimental update.", - }, - } -) - // Check for new software updates. var updateCmd = cli.Command{ Name: "update", - Usage: "Check for new mc update.", + Usage: "Check for a new software update.", Action: mainUpdate, Before: setGlobalsFromContext, - Flags: append(updateFlags, globalFlags...), + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "quiet, q", + Usage: "Suppress chatty console output.", + }, + cli.BoolFlag{ + Name: "json", + Usage: "Enable JSON formatted output.", + }, + }, CustomHelpTemplate: `Name: {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] - + {{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}} +{{if .VisibleFlags}} FLAGS: {{range .VisibleFlags}}{{.}} - {{end}} + {{end}}{{end}} EXAMPLES: - 1. Check for any new official release. - $ {{.HelpName}} - - 2. Check for any new experimental release. - $ {{.HelpName}} --experimental - + 1. Check if there is a new update available: + $ {{.HelpName}} `, } -// update URL endpoints. -const ( - mcUpdateStableURL = "https://dl.minio.io/client/mc/release" - mcUpdateExperimentalURL = "https://dl.minio.io/client/mc/experimental" -) - // updateMessage container to hold update messages. type updateMessage struct { - Status string `json:"status"` - Update bool `json:"update"` - Download string `json:"downloadURL"` - Version string `json:"version"` + Status string `json:"status"` + Update bool `json:"update"` + Download string `json:"downloadURL,omitempty"` + Version string `json:"version"` + olderThan time.Duration } // String colorized update message. func (u updateMessage) String() string { - if !u.Update { + if u.olderThan == time.Duration(0) { return console.Colorize("Update", "You are already running the most recent version of ‘mc’.") } - var msg string - if runtime.GOOS == "windows" { - msg = "Download " + u.Download - } else { - msg = "Download " + u.Download - } - msg, err := colorizeUpdateMessage(msg) - fatalIf(err.Trace(msg), "Unable to colorize experimental update notification string ‘"+msg+"’.") - return msg + return colorizeUpdateMessage(u.Download, u.olderThan) } // JSON jsonified update message. func (u updateMessage) JSON() string { u.Status = "success" + u.Update = u.olderThan != time.Duration(0) updateMessageJSONBytes, e := json.Marshal(u) fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(updateMessageJSONBytes) } -func parseReleaseData(data string) (time.Time, *probe.Error) { - releaseStr := strings.Fields(data) - if len(releaseStr) < 2 { - return time.Time{}, probe.NewError(errors.New("Update data malformed")) - } - releaseDate := releaseStr[1] - releaseDateSplits := strings.SplitN(releaseDate, ".", 3) - if len(releaseDateSplits) < 3 { - return time.Time{}, probe.NewError(errors.New("Update data malformed")) - } - if releaseDateSplits[0] != "mc" { - return time.Time{}, probe.NewError(errors.New("Update data malformed, missing mc tag")) - } - // "OFFICIAL" tag is still kept for backward compatibility, we should remove this for the next release. - if releaseDateSplits[1] != "RELEASE" && releaseDateSplits[1] != "OFFICIAL" { - return time.Time{}, probe.NewError(errors.New("Update data malformed, missing RELEASE tag")) - } - dateSplits := strings.SplitN(releaseDateSplits[2], "T", 2) - if len(dateSplits) < 2 { - return time.Time{}, probe.NewError(errors.New("Update data malformed, not in modified RFC3359 form")) - } - dateSplits[1] = strings.Replace(dateSplits[1], "-", ":", -1) - date := strings.Join(dateSplits, "T") +const releaseTagTimeLayout = "2006-01-02T15-04-05Z" +const mcReleaseURL = "https://dl.minio.io/client/mc/release/" + runtime.GOOS + "-" + runtime.GOARCH + "/" - parsedDate, e := time.Parse(time.RFC3339, date) - if e != nil { - return time.Time{}, probe.NewError(e) +func getCurrentReleaseTime(mcVersion, mcBinaryPath string) (releaseTime time.Time, err *probe.Error) { + var e error + if releaseTime, e = time.Parse(time.RFC3339, mcVersion); e == nil { + return releaseTime, probe.NewError(e) } - return parsedDate, nil + + mcBinaryPath, e = exec.LookPath(mcBinaryPath) + if e != nil { + return releaseTime, probe.NewError(e) + } + + fi, e := os.Stat(mcBinaryPath) + if e != nil { + e = fmt.Errorf("Unable to get ModTime of %s. %s", mcBinaryPath, e) + } else { + releaseTime = fi.ModTime().UTC() + } + + return releaseTime, probe.NewError(e) } -// verify updates for releases. -func getReleaseUpdate(updateURL string) (updateMsg updateMessage, errMsg string, err *probe.Error) { - // Construct a new update url. - newUpdateURLPrefix := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH - newUpdateURL := newUpdateURLPrefix + "/mc.shasum" +// GetCurrentReleaseTime - returns this process's release time. If it is official minio version, +// parsed version is returned else minio binary's mod time is returned. +func GetCurrentReleaseTime() (releaseTime time.Time, err *probe.Error) { + return getCurrentReleaseTime(Version, os.Args[0]) +} + +func isDocker(cgroupFile string) (bool, *probe.Error) { + cgroup, e := ioutil.ReadFile(cgroupFile) + if os.IsNotExist(e) { + e = nil + } + + return bytes.Contains(cgroup, []byte("docker")), probe.NewError(e) +} + +// IsDocker - returns if the environment is docker or not. +func IsDocker() bool { + found, err := isDocker("/proc/self/cgroup") + fatalIf(err.Trace("/proc/self/cgroup"), "Unable to validate if this is a docker container") + return found +} + +func isSourceBuild(mcVersion string) bool { + _, e := time.Parse(time.RFC3339, mcVersion) + return e != nil +} + +// IsSourceBuild - returns if this binary is made from source or not. +func IsSourceBuild() bool { + return isSourceBuild(Version) +} + +// DO NOT CHANGE USER AGENT STYLE. +// The style should be +// Minio (; [; docker][; source]) mc/ mc/ mc/ +// +// For any change here should be discussed by openning an issue at https://github.com/minio/mc/issues. +func getUserAgent() string { + userAgent := "Minio (" + runtime.GOOS + "; " + runtime.GOARCH + if IsDocker() { + userAgent += "; docker" + } + if IsSourceBuild() { + userAgent += "; source" + } + userAgent += ") " + " mc/" + Version + " mc/" + ReleaseTag + " mc/" + CommitID + + return userAgent +} + +func downloadReleaseData(releaseChecksumURL string, timeout time.Duration) (data string, err *probe.Error) { + req, e := http.NewRequest("GET", releaseChecksumURL, nil) + if e != nil { + return data, probe.NewError(e) + } + req.Header.Set("User-Agent", getUserAgent()) - // Instantiate a new client with 3 sec timeout. client := &http.Client{ - Timeout: 3 * time.Second, + Timeout: timeout, } - // Get the downloadURL. - var downloadURL string - switch runtime.GOOS { - case "windows": - // For windows and darwin. - downloadURL = newUpdateURLPrefix + "/mc.exe" - default: - // For all other operating systems. - downloadURL = newUpdateURLPrefix + "/mc" - } - - data, e := client.Get(newUpdateURL) - if e != nil { - err = probe.NewError(e) - errMsg = "Unable to read from update URL ‘" + newUpdateURL + "’." - return updateMessage{}, errMsg, err - } - if strings.HasPrefix(Version, "DEVELOPMENT.GOGET") { - err = errDummy().Trace(newUpdateURL) - errMsg = "Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#minio" - return updateMessage{}, errMsg, err - } - - current, e := time.Parse(time.RFC3339, Version) - if e != nil { - err = probe.NewError(e) - errMsg = "Unable to parse version string as time." - return updateMessage{}, errMsg, err - } - - if current.IsZero() { - err = errDummy().Trace(newUpdateURL) - errMsg = "Updates not supported for custom builds. Version field is empty. Please download official releases from https://minio.io/#minio" - return updateMessage{}, errMsg, err - } - - body, e := ioutil.ReadAll(data.Body) - if e != nil { - err = probe.NewError(e) - errMsg = "Fetching updates failed. Please try again." - return updateMessage{}, errMsg, err - } - - latest, err := parseReleaseData(string(body)) + resp, e := client.Do(req) if err != nil { - errMsg = "Please report this issue at https://github.com/minio/mc/issues." - return updateMessage{}, errMsg, err.Trace(newUpdateURL) + return data, probe.NewError(e) + } + if resp == nil { + return data, probe.NewError(fmt.Errorf("No response from server to download URL %s", releaseChecksumURL)) } - if latest.IsZero() { - err = errDummy().Trace(newUpdateURL) - errMsg = "Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues" - return updateMessage{}, errMsg, err + if resp.StatusCode != http.StatusOK { + return data, probe.NewError(fmt.Errorf("Error downloading URL %s. Response: %v", releaseChecksumURL, resp.Status)) } - updateMsg = updateMessage{ - Download: downloadURL, - Version: Version, + dataBytes, e := ioutil.ReadAll(resp.Body) + if e != nil { + return data, probe.NewError(fmt.Errorf("Error reading response. %s", e)) } - if latest.After(current) { - updateMsg.Update = true - } - return updateMsg, "", nil + + data = string(dataBytes) + return data, nil } -// main entry point for update command. -func mainUpdate(ctx *cli.Context) error { +// DownloadReleaseData - downloads release data from minio official server. +func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) { + return downloadReleaseData(mcReleaseURL+"mc.shasum", timeout) +} + +func parseReleaseData(data string) (releaseTime time.Time, err *probe.Error) { + fields := strings.Fields(data) + if len(fields) != 2 { + e := fmt.Errorf("Unknown release data `%s`", data) + return releaseTime, probe.NewError(e) + } + + releaseInfo := fields[1] + if fields = strings.Split(releaseInfo, "."); len(fields) != 3 { + e := fmt.Errorf("Unknown release information `%s`", releaseInfo) + return releaseTime, probe.NewError(e) + } + + if !(fields[0] == "mc" && fields[1] == "RELEASE") { + e := fmt.Errorf("Unknown release '%s'", releaseInfo) + return releaseTime, probe.NewError(e) + } + + var e error + releaseTime, e = time.Parse(releaseTagTimeLayout, fields[2]) + if e != nil { + e = fmt.Errorf("Unknown release time format. %s", err) + } + + return releaseTime, probe.NewError(e) +} + +func getLatestReleaseTime(timeout time.Duration) (releaseTime time.Time, err *probe.Error) { + data, err := DownloadReleaseData(timeout) + if err != nil { + return releaseTime, err.Trace() + } + return parseReleaseData(data) +} + +func getDownloadURL() (downloadURL string) { + if IsDocker() { + return "docker pull minio/mc" + } + + if runtime.GOOS == "windows" { + return mcReleaseURL + "mc.exe" + } + + return mcReleaseURL + "mc" +} + +func getUpdateInfo(timeout time.Duration) (older time.Duration, downloadURL string, err *probe.Error) { + currentReleaseTime, err := GetCurrentReleaseTime() + if err != nil { + return older, downloadURL, err.Trace() + } + + latestReleaseTime, err := getLatestReleaseTime(timeout) + if err != nil { + return older, downloadURL, err.Trace() + } + + if latestReleaseTime.After(currentReleaseTime) { + older = latestReleaseTime.Sub(currentReleaseTime) + downloadURL = getDownloadURL() + } + + return older, downloadURL, nil +} + +func mainUpdate(ctx *cli.Context) { + if len(ctx.Args()) != 0 { + cli.ShowCommandHelpAndExit(ctx, "update", -1) + } // Additional command speific theme customization. console.SetColor("Update", color.New(color.FgGreen, color.Bold)) - var updateMsg updateMessage - var errMsg string - var err *probe.Error - // Check for update. - if ctx.Bool("experimental") { - updateMsg, errMsg, err = getReleaseUpdate(mcUpdateExperimentalURL) - } else { - updateMsg, errMsg, err = getReleaseUpdate(mcUpdateStableURL) + older, downloadURL, err := getUpdateInfo(10 * time.Second) + fatalIf(err.Trace(downloadURL), "Unable to fetch update info for mc") + + if !globalQuiet { + printMsg(updateMessage{ + olderThan: older, + Download: downloadURL, + Version: Version, + }) } - fatalIf(err, errMsg) - printMsg(updateMsg) - return nil } diff --git a/cmd/version-main.go b/cmd/version-main.go index d11b61c2..7289dcdf 100644 --- a/cmd/version-main.go +++ b/cmd/version-main.go @@ -1,5 +1,5 @@ /* - * Minio Client (C) 2014, 2015 Minio, Inc. + * Minio Client (C) 2014, 2015, 2016, 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. @@ -26,26 +26,34 @@ import ( "github.com/minio/minio/pkg/probe" ) -var ( - versionFlags = []cli.Flag{} -) - // Print version. var versionCmd = cli.Command{ Name: "version", Usage: "Print version info.", Action: mainVersion, Before: setGlobalsFromContext, - Flags: append(versionFlags, globalFlags...), + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "quiet, q", + Usage: "Suppress chatty console output.", + }, + cli.BoolFlag{ + Name: "json", + Usage: "Enable JSON formatted output.", + }, + }, CustomHelpTemplate: `NAME: {{.HelpName}} - {{.Usage}} USAGE: - {{.HelpName}} [FLAGS] - + {{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}} +{{if .VisibleFlags}} FLAGS: {{range .VisibleFlags}}{{.}} - {{end}} + {{end}}{{end}} +EXAMPLES: + 1. Prints the minio client version: + $ {{.HelpName}} `, } @@ -88,6 +96,8 @@ func mainVersion(ctx *cli.Context) error { verMsg.Version.Value = Version verMsg.Version.Format = "RFC3339" - printMsg(verMsg) + if !globalQuiet { + printMsg(verMsg) + } return nil }