Merge branch 'master' into release

This commit is contained in:
Minio Trusted
2017-06-14 20:38:23 -07:00
91 changed files with 2270 additions and 1043 deletions
+1 -1
View File
@@ -33,7 +33,7 @@ var adminConfigGetCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -38,7 +38,7 @@ var adminConfigSetCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -36,7 +36,7 @@ var adminCredsCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS ACCESS_KEY SECRET_KEY
{{.HelpName}} TARGET ACCESS_KEY SECRET_KEY
FLAGS:
{{range .VisibleFlags}}{{.}}
-256
View File
@@ -1,256 +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 (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/madmin"
"github.com/minio/minio/pkg/probe"
)
var (
adminHealListFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "List recursively.",
},
cli.BoolFlag{
Name: "incomplete, I",
Usage: "List incomplete uploads",
},
}
)
var adminHealListCmd = cli.Command{
Name: "list",
Usage: "Get the list of buckets or objects that need to be healed.",
Before: setGlobalsFromContext,
Action: mainAdminHealList,
Flags: append(adminHealListFlags, globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/[BUCKET/][PREFIX/]
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. List objects than need to be healed related to 'testbucket' in a Minio server represented by its alias 'play'.
$ {{.HelpName}} play/testbucket/
2. Recursively list objects than need to be healed.
$ {{.HelpName}} --recursive play/
3. Recursively list incomplete uploads than need to be healed.
$ {{.HelpName}} --incomplete --recursive play/
`,
}
// healListMessage container to hold heal information.
type healListMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
}
// String colorized service status message.
func (u healListMessage) String() string {
msg := ""
var healStatus madmin.HealStatus
// Check if we have object heal information
if u.Object != nil {
msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key)
healStatus = u.Object.HealObjectInfo.Status
} else {
msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key)
healStatus = u.Upload.HealUploadInfo.Status
}
// Print heal status
switch healStatus {
case madmin.CanHeal:
msg += "can be healed."
case madmin.Corrupted:
msg += "cannot be healed."
case madmin.QuorumUnavailable:
msg += "quorum not available for healing."
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healBucketListMessage container to hold heal information.
type healBucketListMessage struct {
Status string `json:"status"`
Bucket madmin.BucketInfo `json:"bucket"`
}
// String colorized service status message.
func (u healBucketListMessage) String() string {
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
switch u.Bucket.HealBucketInfo.Status {
case madmin.CanHeal:
msg += "can be healed"
case madmin.Corrupted:
msg += "cannot be healed"
case madmin.QuorumUnavailable:
msg += "quorum not available for healing"
}
msg += ".\n"
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healBucketListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// checkAdminHealListSyntax - validate all the passed arguments
func checkAdminHealListSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code
}
}
func mainAdminHealList(ctx *cli.Context) error {
// Check for heal list syntax
checkAdminHealListSyntax(ctx)
// Set console theme for heal command
console.SetColor("Heal", color.New(color.FgGreen, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
isRecursive := ctx.Bool("recursive")
isIncomplete := ctx.Bool("incomplete")
// Create a new Minio Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
return err.ToGoError()
}
// Transform windows backslash to the regular slash in the aliased url
aliasedURL = filepath.ToSlash(aliasedURL)
// Compute bucket and object from aliased url
splits := splitStr(aliasedURL, "/", 3)
bucket, object := splits[1], splits[2]
// If bucket is not specified, list buckets that need to be healed
if bucket == "" {
bucketsToHeal, e := client.ListBucketsHeal()
fatalIf(probe.NewError(e), "Cannot list buckets that need healing.")
// Iterate over buckets that need healing and print them
for _, bucketHeal := range bucketsToHeal {
printMsg(healBucketListMessage{Bucket: bucketHeal})
}
}
// When bucket is not specified and recursive flag is not activated,
// it means we will not scan inside buckets
if bucket == "" && !isRecursive {
return nil
}
// Now, it is time to examine for objects that need to be healed
var buckets []string
if bucket == "" {
// Bucket is not specified, so we target all buckets so we need to list them.
s3Client, err := newClient(aliasedURL)
if err != nil {
fatalIf(err, "Cannot resolve the provided path.")
}
recursive := false
incomplete := false
listCh := s3Client.List(recursive, incomplete, DirFirst)
for content := range listCh {
// Trim the leading slash and add to the list of buckets
buckets = append(buckets,
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
}
} else {
// Bucket is passed in argument, so we will only search for objects in the specified bucket
buckets = append(buckets, bucket)
}
// Iterate over all computed buckets
for _, currBucket := range buckets {
// Search for objects that need to be healed in the current bucket
doneCh := make(chan struct{})
if isIncomplete {
listCh, e := client.ListUploadsHeal(currBucket, object, isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal uploads.")
// Iterate over uploads and print them when not errors
for upload := range listCh {
if upload.Err != nil {
errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.")
continue
}
// Skip for non-recursive use case.
if upload.HealUploadInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Upload: &upload})
}
} else {
listCh, e := client.ListObjectsHeal(currBucket, object, isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal objects.")
// Iterate over objects and print them when not errors
for obj := range listCh {
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.")
continue
}
// Skip for non-recursive use case.
if obj.HealObjectInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Object: &obj})
}
}
}
return nil
}
+210 -32
View File
@@ -19,8 +19,8 @@ package cmd
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -46,47 +46,54 @@ var (
}
)
var adminHealHelpTemplate = `NAME:
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "Manage heal tasks",
Before: setGlobalsFromContext,
Action: mainAdminHeal,
Flags: append(adminHealFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] [COMMAND]
{{.HelpName}} [FLAGS] TARGET
COMMANDS:
{{range .VisibleCommands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
EXAMPLES:
1. Heal 'testbucket' in a Minio server represented by its alias 'play'.
1. To format newly replaced disks in a Minio server with alias 'play'
$ {{.HelpName}} play
2. Heal 'testbucket' in a Minio server with alias 'play'
$ {{.HelpName}} play/testbucket/
2. Heal all objects under 'dir' prefix
3. Heal all objects under 'dir' prefix
$ {{.HelpName}} --recursive play/testbucket/dir/
3. Heal all uploads under 'dir' prefix
4. Heal all uploads under 'dir' prefix
$ {{.HelpName}} --incomplete --recursive play/testbucket/dir/
4. Issue a fake heal operation to see what the server could report
$ {{.HelpName}} --fake play/testbucket/dir/
5. Issue a fake heal operation to list all objects to be healed
$ {{.HelpName}} --fake play
`
var adminHealCmd = cli.Command{
Name: "heal",
Usage: "Manage heal tasks",
Before: setGlobalsFromContext,
Action: mainAdminHeal,
Flags: append(adminHealFlags, globalFlags...),
Subcommands: []cli.Command{
adminHealListCmd,
},
HideHelpCommand: true,
6. Issue a fake heal operation to list all uploads to be healed
$ {{.HelpName}} --fake --incomplete play
7. Issue a fake heal operation to list all objects to be healed under 'dir' prefix
$ {{.HelpName}} --recursive --fake play/testbucket/dir/
8. Issue a fake heal operation to list all uploads to be healed under 'dir' prefix
$ {{.HelpName}} --incomplete --recursive --fake play/testbucket/dir/
`,
}
// healMessage container to hold repair information.
type healMessage struct {
Status string `json:"status"`
Result madmin.HealResult `json:"result"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
@@ -94,12 +101,26 @@ type healMessage struct {
// String colorized service status message.
func (u healMessage) String() string {
allOfflineTmpl := "is not healed since many disks were offline"
allHealedTmpl := "is healed on all disks"
someHealedTmpl := "is healed on some disks while other disks were offline"
msg := ""
if u.Object != nil {
msg += fmt.Sprintf("Object %s/%s is healed.", u.Bucket, u.Object.Key)
msg = fmt.Sprintf("Object %s/%s ", u.Bucket, u.Object.Key)
} else {
msg += fmt.Sprintf("Upload %s/%s/%s is healed.", u.Bucket, u.Upload.Key, u.Upload.UploadID)
msg = fmt.Sprintf("Upload %s/%s/%s ", u.Bucket, u.Upload.Key, u.Upload.UploadID)
}
switch u.Result.State {
case madmin.HealNone:
msg += allOfflineTmpl
case madmin.HealPartial:
msg += someHealedTmpl
case madmin.HealOK:
msg += allHealedTmpl
}
return console.Colorize("Heal", msg)
}
@@ -112,6 +133,81 @@ func (u healMessage) JSON() string {
return string(statusJSONBytes)
}
// healListMessage container to hold heal information.
type healListMessage struct {
Status string `json:"status"`
Bucket string `json:"bucket"`
Object *madmin.ObjectInfo `json:"object"`
Upload *madmin.UploadInfo `json:"upload"`
}
// String colorized service status message.
func (u healListMessage) String() string {
msg := ""
var healStatus madmin.HealStatus
// Check if we have object heal information
if u.Object != nil {
msg += fmt.Sprintf("Object: %s/%s, ", u.Bucket, u.Object.Key)
healStatus = u.Object.HealObjectInfo.Status
} else {
msg += fmt.Sprintf("Upload: %s/%s, ", u.Bucket, u.Upload.Key)
healStatus = u.Upload.HealUploadInfo.Status
}
// Print heal status
switch healStatus {
case madmin.CanHeal:
msg += "can be healed."
case madmin.CanPartiallyHeal:
msg += "can be partially healed."
case madmin.Corrupted:
msg += "cannot be healed."
case madmin.QuorumUnavailable:
msg += "quorum not available for healing."
}
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
// healBucketListMessage container to hold heal information.
type healBucketListMessage struct {
Status string `json:"status"`
Bucket madmin.BucketInfo `json:"bucket"`
}
// String colorized service status message.
func (u healBucketListMessage) String() string {
msg := fmt.Sprintf("Bucket: `%s`, ", u.Bucket.Name)
switch u.Bucket.HealBucketInfo.Status {
case madmin.CanHeal:
msg += "can be healed"
case madmin.Corrupted:
msg += "cannot be healed"
case madmin.QuorumUnavailable:
msg += "quorum not available for healing"
}
msg += ".\n"
return console.Colorize("Heal", msg)
}
// JSON jsonified service status Message message.
func (u healBucketListMessage) JSON() string {
u.Status = "success"
statusJSONBytes, e := json.Marshal(u)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(statusJSONBytes)
}
func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive, isFake bool) {
// Search for objects that need healing
doneCh := make(chan struct{})
@@ -132,15 +228,20 @@ func healObjects(client *madmin.AdminClient, bucket, object string, isRecursive,
// Check the heal status, and call heal object API only when an object can be healed
switch healInfo := *obj.HealObjectInfo; healInfo.Status {
case madmin.CanHeal:
case madmin.CanHeal, madmin.CanPartiallyHeal:
// Heal Object
if e = client.HealObject(bucket, obj.Key, isFake); e != nil {
var healResult madmin.HealResult
if healResult, e = client.HealObject(bucket, obj.Key, isFake); e != nil {
errorIf(probe.NewError(e), "Cannot repair object: `"+obj.Key+"`")
continue
}
// Print successful message
printMsg(healMessage{Bucket: bucket, Object: &obj})
if isFake {
printMsg(healListMessage{Bucket: bucket, Object: &obj})
} else {
printMsg(healMessage{Bucket: bucket, Object: &obj, Result: healResult})
}
case madmin.QuorumUnavailable:
errorIf(errDummy().Trace(), obj.Key+" cannot be healed until quorum is available.")
case madmin.Corrupted:
@@ -169,14 +270,19 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive,
// Check the heal status, and call heal upload API only when an upload can be healed
switch healInfo := *upload.HealUploadInfo; healInfo.Status {
case madmin.CanHeal:
case madmin.CanHeal, madmin.CanPartiallyHeal:
// Heal Upload
if e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil {
var healResult madmin.HealResult
if healResult, e = client.HealUpload(bucket, upload.Key, upload.UploadID, isFake); e != nil {
errorIf(probe.NewError(e), "Cannot repair upload: `"+upload.Key+"`")
continue
}
// Print successful message
printMsg(healMessage{Bucket: bucket, Upload: &upload})
if isFake {
printMsg(healListMessage{Bucket: bucket, Upload: &upload})
} else {
printMsg(healMessage{Bucket: bucket, Upload: &upload, Result: healResult})
}
case madmin.QuorumUnavailable:
errorIf(errDummy().Trace(), upload.Key+" cannot be healed until quorum is available.")
case madmin.Corrupted:
@@ -188,11 +294,76 @@ func healUploads(client *madmin.AdminClient, bucket, object string, isRecursive,
// checkAdminHealSyntax - validate all the passed arguments
func checkAdminHealSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.HelpPrinter(ctx.App.Writer, adminHealHelpTemplate, ctx.App)
os.Exit(1)
cli.ShowCommandHelpAndExit(ctx, "heal", 1) // last argument is exit code
}
}
// listAllToBeHealed - list objects/uploads to be healed in the object
// store with alias `aliasedURL`
// - isIncomplete - if true we list uploads to be healed otherwise
// list objects to be healed
func listAllToBeHealed(client *madmin.AdminClient, aliasedURL string, isIncomplete bool) *probe.Error {
s3Client, err := newClient(aliasedURL)
if err != nil {
return err
}
recursive := false
incomplete := false
listCh := s3Client.List(recursive, incomplete, DirFirst)
var buckets []string
for content := range listCh {
// Trim the leading slash and add to the list of buckets
buckets = append(buckets,
strings.TrimPrefix(content.URL.Path, string(content.URL.Separator)))
}
// isRecursive is always true since we have empty object names
// when `mc admin heal --fake [-r] s1/` is invoked.
isRecursive := true
// Iterate over all computed buckets
for _, currBucket := range buckets {
// Search for objects that need to be healed in the current bucket
doneCh := make(chan struct{})
if isIncomplete {
listCh, e := client.ListUploadsHeal(currBucket, "", isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal uploads.")
// Iterate over uploads and print them when not errors
for upload := range listCh {
if upload.Err != nil {
errorIf(probe.NewError(upload.Err), "Cannot heal upload `"+upload.Key+"`.")
continue
}
// Skip for non-recursive use case.
if upload.HealUploadInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Upload: &upload})
}
} else {
listCh, e := client.ListObjectsHeal(currBucket, "", isRecursive, doneCh)
fatalIf(probe.NewError(e), "Cannot list heal objects.")
// Iterate over objects and print them when not errors
for obj := range listCh {
if obj.Err != nil {
errorIf(probe.NewError(obj.Err), "Cannot heal object `"+obj.Key+"`.")
continue
}
// Skip for non-recursive use case.
if obj.HealObjectInfo == nil {
continue
}
printMsg(healListMessage{Bucket: currBucket, Object: &obj})
}
}
}
return nil
}
// mainAdminHeal - the entry function of heal command
func mainAdminHeal(ctx *cli.Context) error {
@@ -225,6 +396,13 @@ func mainAdminHeal(ctx *cli.Context) error {
// Heal format if bucket is not specified and quit immediately
if bucket == "" {
// If --fake was given, print all objects/uploads that
// need to be healed.
if isFake {
lErr := listAllToBeHealed(client, aliasedURL, isIncomplete)
fatalIf(lErr, "Unable to list all objects to be healed")
return nil
}
e = client.HealFormat(isFake)
fatalIf(probe.NewError(e), "Cannot heal the disks.")
return nil
+79 -39
View File
@@ -20,6 +20,7 @@ import (
"encoding/json"
"fmt"
"net/url"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
@@ -43,7 +44,7 @@ var adminInfoCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -94,23 +95,46 @@ type ServerInfo struct {
type infoMessage struct {
Status string `json:"status"`
Service bool `json:"service"`
Addr string `json:"address"`
Err string `json:"error"`
*ServerInfo
}
// String colorized service status message.
func (u infoMessage) String() (msg string) {
defer func() {
msg = console.Colorize("Info", msg)
msg += "\n"
}()
dot := "●"
// When service is offline
if !u.Service {
msg = "The server is offline."
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
msg += fmt.Sprintf(" Uptime : Server is %s", console.Colorize("InfoFail", "offline"))
return
}
msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version)
msg += fmt.Sprintf(" Uptime : %s\n", timeDurationToHumanizedDuration(u.ServerInfo.Properties.Uptime))
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
// Print error if any and exit
if u.Err != "" {
msg += fmt.Sprintf("%s %s\n", console.Colorize("InfoFail", dot), u.Addr)
msg += fmt.Sprintf(" Uptime : Server is %s\n", console.Colorize("InfoFail", "offline"))
msg += fmt.Sprintf(" Error : %s", u.Err)
return
}
// Print server title
msg += fmt.Sprintf("%s %s\n", console.Colorize("Info", dot), u.Addr)
// Print server information
// Uptime
msg += fmt.Sprintf(" Uptime : %s since %s\n", console.Colorize("Info", "online"), humanize.Time(time.Now().UTC().Add(-u.ServerInfo.Properties.Uptime)))
// Version
msg += fmt.Sprintf(" Version : %s\n", u.ServerInfo.Properties.Version)
// Region
msg += fmt.Sprintf(" Region : %s\n", u.ServerInfo.Properties.Region)
// ARNs
sqsARNs := ""
for _, v := range u.ServerInfo.Properties.SQSARN {
sqsARNs += fmt.Sprintf("%s ", v)
@@ -119,12 +143,11 @@ func (u infoMessage) String() (msg string) {
sqsARNs = "<none>"
}
msg += fmt.Sprintf(" SQS ARNs : %s\n", sqsARNs)
// Incoming/outgoing
msg += fmt.Sprintf(" Network : Incoming %s, Outgoing %s\n",
humanize.IBytes(u.ServerInfo.ConnStats.TotalInputBytes),
humanize.IBytes(u.ServerInfo.ConnStats.TotalOutputBytes))
// Online service, get backend information
// Get storage information
msg += fmt.Sprintf(" Storage : Total %s, Free %s",
humanize.IBytes(uint64(u.StorageInfo.Total)),
humanize.IBytes(uint64(u.StorageInfo.Free)),
@@ -132,6 +155,7 @@ func (u infoMessage) String() (msg string) {
if v, ok := u.ServerInfo.StorageInfo.Backend.(xlBackend); ok {
msg += fmt.Sprintf(", Online Disks: %d, Offline Disks: %d", v.OnlineDisks, v.OfflineDisks)
}
return
}
@@ -156,6 +180,7 @@ func mainAdminInfo(ctx *cli.Context) error {
checkAdminInfoSyntax(ctx)
console.SetColor("Info", color.New(color.FgGreen, color.Bold))
console.SetColor("InfoFail", color.New(color.FgRed, color.Bold))
// Get the alias parameter from cli
args := ctx.Args()
@@ -165,53 +190,68 @@ func mainAdminInfo(ctx *cli.Context) error {
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
// Fetch the server info of the specified Minio server
serverInfo, e := client.ServerInfo()
// Fetch info of all servers (cluster or single server)
serversInfo, e := client.ServerInfo()
// Check the availability of the server: online or offline. A server is considered
// offline if we can't get any response or we get a bad format response
var serviceOffline bool
switch v := e.(type) {
switch e.(type) {
case *json.SyntaxError:
serviceOffline = true
case *url.Error:
if v.Timeout() {
serviceOffline = true
}
serviceOffline = true
}
if serviceOffline {
printMsg(infoMessage{Service: false})
printMsg(infoMessage{Addr: aliasedURL, Service: false})
return nil
}
// If the error is not nil and not unrecognizable, just print it and exit
fatalIf(probe.NewError(e), "Cannot get service status.")
// Construct the backend status
storageInfo := backendStatus{
Total: serverInfo.StorageInfo.Total,
Free: serverInfo.StorageInfo.Free,
}
if serverInfo.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.StorageInfo.Backend.OfflineDisks,
for _, serverInfo := range serversInfo {
// Print the error if exists and jump to the next server
if serverInfo.Error != "" {
printMsg(infoMessage{
Service: true,
Addr: serverInfo.Addr,
Err: serverInfo.Error,
})
continue
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
printMsg(infoMessage{
Service: true,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.ConnStats,
Properties: serverInfo.Properties,
},
})
// Construct the backend status
storageInfo := backendStatus{
Total: serverInfo.Data.StorageInfo.Total,
Free: serverInfo.Data.StorageInfo.Free,
}
if serverInfo.Data.StorageInfo.Backend.Type == madmin.Erasure {
storageInfo.Backend = xlBackend{
Type: erasureType,
OnlineDisks: serverInfo.Data.StorageInfo.Backend.OnlineDisks,
OfflineDisks: serverInfo.Data.StorageInfo.Backend.OfflineDisks,
}
} else {
storageInfo.Backend = fsBackend{
Type: fsType,
}
}
printMsg(infoMessage{
Service: true,
Addr: serverInfo.Addr,
Err: serverInfo.Error,
ServerInfo: &ServerInfo{
StorageInfo: storageInfo,
ConnStats: serverInfo.Data.ConnStats,
Properties: serverInfo.Data.Properties,
},
})
}
return nil
}
+1 -1
View File
@@ -51,7 +51,7 @@ var adminLockClearCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET/PREFIX
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -47,7 +47,7 @@ var adminLockListCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET/PREFIX
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -35,7 +35,7 @@ var adminServiceRestartCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -42,7 +42,7 @@ var adminServiceStatusCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS
{{.HelpName}} TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
+2 -3
View File
@@ -25,7 +25,6 @@ import (
"strconv"
"strings"
"sync"
"time"
)
type objectAPIHandler struct {
@@ -63,7 +62,7 @@ func (h objectAPIHandler) getHandler(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.object[filepath.Base(r.URL.Path)]))
@@ -83,7 +82,7 @@ func (h objectAPIHandler) headHandler(w http.ResponseWriter, r *http.Request) {
return
case r.URL.Path != "":
w.Header().Set("Content-Length", strconv.Itoa(len(h.object[filepath.Base(r.URL.Path)])))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "b1946ac92492d2347c6235b4d2611184")
w.WriteHeader(http.StatusOK)
return
+1 -1
View File
@@ -150,7 +150,7 @@ func (e EmptyPath) Error() string {
type ObjectMissing struct{}
func (e ObjectMissing) Error() string {
return "Object key is missing, object key cannot be empty"
return "Object does not exist"
}
// UnexpectedShortWrite - write wrote less bytes than expected.
+56 -54
View File
@@ -96,12 +96,12 @@ func (f *fsClient) GetURL() clientURL {
// Watches for all fs events on an input path.
func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan Event)
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
neventChan := make(chan notify.EventInfo, 1)
in, out := PipeChan(1000)
var fsEvents []notify.Event
for _, event := range params.events {
@@ -110,6 +110,8 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
fsEvents = append(fsEvents, EventTypePut...)
case "delete":
fsEvents = append(fsEvents, EventTypeDelete...)
case "get":
fsEvents = append(fsEvents, EventTypeGet...)
default:
return nil, errInvalidArgument().Trace(event)
}
@@ -121,7 +123,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
if params.recursive {
recursivePath = f.PathURL.Path + "..."
}
if e := notify.Watch(recursivePath, neventChan, fsEvents...); e != nil {
if e := notify.Watch(recursivePath, in, fsEvents...); e != nil {
return nil, probe.NewError(e)
}
@@ -131,7 +133,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
close(eventChan)
close(errorChan)
notify.Stop(neventChan)
notify.Stop(in)
}()
timeFormatFS := "2006-01-02T15:04:05.000Z"
@@ -139,7 +141,7 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// Get fsnotify notifications for events and errors, and sent them
// using eventChan and errorChan
go func() {
for event := range neventChan {
for event := range out {
if isIgnoredFile(event.Path()) {
continue
}
@@ -159,31 +161,49 @@ func (f *fsClient) Watch(params watchParams) (*watchObject, *probe.Error) {
// we want files
continue
}
eventChan <- Event{
Time: time.Now().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Client: f,
Type: EventCreate,
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Size: i.Size(),
Path: event.Path(),
Type: EventCreate,
}
} else if IsDeleteEvent(event.Event()) {
eventChan <- Event{
Time: time.Now().Format(timeFormatFS),
Path: event.Path(),
Client: f,
Type: EventRemove,
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventRemove,
}
} else if IsGetEvent(event.Event()) {
eventChan <- EventInfo{
Time: UTCNow().Format(timeFormatFS),
Path: event.Path(),
Type: EventAccessed,
}
}
}
}()
return &watchObject{
events: eventChan,
errors: errorChan,
done: doneChan,
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}, nil
}
func isStreamFile(objectPath string) bool {
switch objectPath {
case os.DevNull:
fallthrough
case os.Stdin.Name():
fallthrough
case os.Stdout.Name():
fallthrough
case os.Stderr.Name():
return true
}
return false
}
/// Object operations.
func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]string, progress io.Reader) (int64, *probe.Error) {
@@ -194,29 +214,15 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
objectDir, _ := filepath.Split(f.PathURL.Path)
objectPath := f.PathURL.Path
// Verify if destination already exists.
st, e := os.Stat(objectPath)
if e == nil {
// If the destination exists and is not a regular file.
if !st.Mode().IsRegular() {
return 0, probe.NewError(PathIsNotRegular{
Path: objectPath,
})
}
}
// Proceed if file does not exist. return for all other errors.
if e != nil {
if !os.IsNotExist(e) {
return 0, probe.NewError(e)
}
}
// Write to a temporary file "object.part.mc" before commit.
avoidResumeUpload := isStreamFile(objectPath)
// Write to a temporary file "object.part.minio" before commit.
objectPartPath := objectPath + partSuffix
if avoidResumeUpload {
objectPartPath = objectPath
}
if objectDir != "" {
// Create any missing top level directories.
if e = os.MkdirAll(objectDir, 0777); e != nil {
if e := os.MkdirAll(objectDir, 0777); e != nil {
err := f.toClientError(e, f.PathURL.Path)
return 0, err.Trace(f.PathURL.Path)
}
@@ -337,10 +343,12 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin
})
}
}
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
if !avoidResumeUpload {
// Safely completed put. Now commit by renaming to actual filename.
if e = os.Rename(objectPartPath, objectPath); e != nil {
err := f.toClientError(e, objectPath)
return totalWritten, err.Trace(objectPartPath, objectPath)
}
}
return totalWritten, nil
}
@@ -388,16 +396,7 @@ func readFile(fpath string) (io.ReadCloser, error) {
// createFile creates an empty file at the provided filepath
// if one does not exist already.
func createFile(fpath string) (io.WriteCloser, error) {
st, e := os.Stat(fpath)
// If destination exists but is not regular.
if e == nil && !st.Mode().IsRegular() {
return nil, PathIsNotRegular{Path: fpath}
}
// If file exists already.
if e != nil && !os.IsNotExist(e) {
return nil, e
}
if e = os.MkdirAll(filepath.Dir(fpath), 0777); e != nil {
if e := os.MkdirAll(filepath.Dir(fpath), 0777); e != nil {
return nil, e
}
file, e := os.Create(fpath)
@@ -933,7 +932,10 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent) {
}
// MakeBucket - create a new bucket.
func (f *fsClient) MakeBucket(region string) *probe.Error {
func (f *fsClient) MakeBucket(region string, ignoreExisting bool) *probe.Error {
// TODO: ignoreExisting has no effect currently. In the future, we want
// to call os.Mkdir() when ignoredExisting is disabled and os.MkdirAll()
// otherwise.
e := os.MkdirAll(f.PathURL.Path, 0777)
if e != nil {
return probe.NewError(e)
+23 -17
View File
@@ -1,7 +1,7 @@
// +build linux
/*
* 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 fs except in compliance with the License.
@@ -23,34 +23,40 @@ import (
)
var (
// EventTypePut contains the notify events that will cause a put
// EventTypePut contains the notify events that will cause a put (write)
EventTypePut = []notify.Event{notify.InCloseWrite | notify.InMovedTo}
// EventTypeDelete contains the notify events that will cause a delete
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.InDelete | notify.InDeleteSelf | notify.InMovedFrom}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.InAccess | notify.InOpen}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
for _, ev := range EventTypeGet {
if event&ev != 0 {
return true
}
}
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
switch event {
case notify.InCloseWrite:
return true
case notify.InMovedTo:
return true
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
switch event {
case notify.InDelete:
return true
case notify.InDeleteSelf:
return true
case notify.InMovedFrom:
return true
for _, ev := range EventTypeDelete {
if event&ev != 0 {
return true
}
}
return false
}
+16 -18
View File
@@ -1,7 +1,7 @@
// +build !linux
// +build darwin freebsd solaris
/*
* 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 fs except in compliance with the License.
@@ -21,32 +21,30 @@ package cmd
import "github.com/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available.
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return false
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
switch event {
case notify.Create:
return true
case notify.Rename:
return true
case notify.Write:
return true
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
switch event {
case notify.Remove:
return true
}
return false
return event&notify.Remove != 0
}
+3 -3
View File
@@ -193,7 +193,7 @@ func (s *TestSuite) TestPutBucket(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
}
@@ -207,7 +207,7 @@ func (s *TestSuite) TestStatBucket(c *C) {
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
_, err = fsClient.Stat(false)
c.Assert(err, IsNil)
@@ -222,7 +222,7 @@ func (s *TestSuite) TestBucketACLFails(c *C) {
bucketPath := filepath.Join(root, "bucket")
fsClient, err := fsNew(bucketPath)
c.Assert(err, IsNil)
err = fsClient.MakeBucket("us-east-1")
err = fsClient.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
// On windows setting permissions is not supported.
+50
View File
@@ -0,0 +1,50 @@
// +build windows
/*
* Minio Client (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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/rjeczalik/notify"
var (
// EventTypePut contains the notify events that will cause a put (writer)
EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename}
// EventTypeDelete contains the notify events that will cause a delete (remove)
EventTypeDelete = []notify.Event{notify.Remove}
// EventTypeGet contains the notify events that will cause a get (read)
EventTypeGet = []notify.Event{notify.FileNotifyChangeLastAccess}
)
// IsGetEvent checks if the event return is a get event.
func IsGetEvent(event notify.Event) bool {
return event&notify.FileNotifyChangeLastAccess != 0
}
// IsPutEvent checks if the event returned is a put event
func IsPutEvent(event notify.Event) bool {
for _, ev := range EventTypePut {
if event&ev != 0 {
return true
}
}
return false
}
// IsDeleteEvent checks if the event returned is a delete event
func IsDeleteEvent(event notify.Event) bool {
return event&notify.Remove != 0
}
+62 -22
View File
@@ -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.
@@ -206,6 +206,8 @@ func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, su
nc.AddEvents(minio.ObjectCreatedAll)
case "delete":
nc.AddEvents(minio.ObjectRemovedAll)
case "get":
nc.AddEvents(minio.ObjectAccessedAll)
default:
return errInvalidArgument().Trace(events...)
}
@@ -366,7 +368,7 @@ func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *p
// Start watching on all bucket events for a given account ID.
func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
eventChan := make(chan Event)
eventChan := make(chan EventInfo)
errorChan := make(chan *probe.Error)
doneChan := make(chan bool)
@@ -384,6 +386,8 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
events = append(events, string(minio.ObjectCreatedAll))
case "delete":
events = append(events, string(minio.ObjectRemovedAll))
case "get":
events = append(events, string(minio.ObjectAccessedAll))
default:
return nil, errInvalidArgument().Trace(event)
}
@@ -410,9 +414,9 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
eventsCh := c.api.ListenBucketNotification(bucket, params.prefix, params.suffix, events, doneCh)
wo := &watchObject{
events: eventChan,
errors: errorChan,
done: doneChan,
eventInfoChan: eventChan,
errorChan: errorChan,
doneChan: doneChan,
}
// wait for events to occur and sent them through the eventChan and errorChan
@@ -441,22 +445,45 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) {
u := *c.targetURL
u.Path = path.Join(string(u.Separator), bucketName, key)
if strings.HasPrefix(record.EventName, "s3:ObjectCreated:") {
eventChan <- Event{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Client: c,
Type: EventCreate,
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventCreate,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if strings.HasPrefix(record.EventName, "s3:ObjectRemoved:") {
eventChan <- Event{
Time: record.EventTime,
Path: u.String(),
Client: c,
Type: EventRemove,
eventChan <- EventInfo{
Time: record.EventTime,
Path: u.String(),
Type: EventRemove,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == minio.ObjectAccessedGet {
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventAccessedRead,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else if record.EventName == minio.ObjectAccessedHead {
eventChan <- EventInfo{
Time: record.EventTime,
Size: record.S3.Object.Size,
Path: u.String(),
Type: EventAccessedStat,
Host: record.Source.Host,
Port: record.Source.Port,
UserAgent: record.Source.UserAgent,
}
} else {
// ignore other events
}
}
}
@@ -715,13 +742,13 @@ func isValidBucketName(bucketName string) *probe.Error {
return probe.NewError(errors.New("Bucket name should be more than 3 characters and less than 64 characters"))
}
if !validBucketName.MatchString(bucketName) {
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet or number"))
return probe.NewError(errors.New("Bucket names can only contain lowercase alpha characters `a-z`, numbers '0-9', or '-'. First/last character cannot be a '-'"))
}
return nil
}
// MakeBucket - make a new bucket.
func (c *s3Client) MakeBucket(region string) *probe.Error {
func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(BucketNameTopLevel{})
@@ -731,6 +758,15 @@ func (c *s3Client) MakeBucket(region string) *probe.Error {
}
e := c.api.MakeBucket(bucket, region)
if e != nil {
// Ignore bucket already existing error when ignoreExisting flag is enabled
if ignoreExisting {
switch minio.ToErrorResponse(e).Code {
case "BucketAlreadyOwnedByYou":
fallthrough
case "BucketAlreadyExists":
return nil
}
}
return probe.NewError(e)
}
return nil
@@ -895,6 +931,10 @@ func isAmazon(host string) bool {
return s3utils.IsAmazonEndpoint(url.URL{Host: host})
}
func isAmazonChina(host string) bool {
return s3utils.IsAmazonChinaEndpoint(url.URL{Host: host})
}
func isAmazonAccelerated(host string) bool {
return host == "s3-accelerate.amazonaws.com"
}
@@ -907,7 +947,7 @@ func isGoogle(host string) bool {
// Currently only supported hosts with virtual style
// are Amazon S3 and Google Cloud Storage.
func isVirtualHostStyle(host string) bool {
return isAmazon(host) || isGoogle(host) || isAmazonAccelerated(host)
return isAmazon(host) && !isAmazonChina(host) || isGoogle(host) || isAmazonAccelerated(host)
}
// url2BucketAndObject gives bucketName and objectName from URL path.
@@ -1494,7 +1534,7 @@ func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {
if e := p.SetExpires(UTCNow().Add(expires)); e != nil {
return "", nil, probe.NewError(e)
}
if strings.TrimSpace(contentType) != "" || contentType != "" {
+3 -4
View File
@@ -23,7 +23,6 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"time"
. "gopkg.in/check.v1"
)
@@ -104,7 +103,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
case r.Method == "POST":
@@ -151,7 +150,7 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
w.Header().Set("Last-Modified", UTCNow().Format(http.TimeFormat))
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
w.WriteHeader(http.StatusOK)
io.Copy(w, bytes.NewReader(h.data))
@@ -174,7 +173,7 @@ func (s *TestSuite) TestBucketOperations(c *C) {
s3c, err := s3New(conf)
c.Assert(err, IsNil)
err = s3c.MakeBucket("us-east-1")
err = s3c.MakeBucket("us-east-1", true)
c.Assert(err, IsNil)
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
+1 -1
View File
@@ -43,7 +43,7 @@ type Client interface {
List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent
// Bucket operations
MakeBucket(region string) *probe.Error
MakeBucket(region string, ignoreExisting bool) *probe.Error
// Access policy operations.
GetAccess() (access string, error *probe.Error)
+12
View File
@@ -17,6 +17,8 @@
package cmd
import (
urlpkg "net/url"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
@@ -126,6 +128,16 @@ func mainConfigHostAdd(ctx *cli.Context) error {
accessKey := args.Get(2)
secretKey := args.Get(3)
api := args.Get(4)
parsedURL, _ := urlpkg.Parse(url)
if isGoogle(parsedURL.Host) {
if api == "S3v4" {
fatalIf(errInvalidArgument().Trace(api), "Unsupported API signature for url. Please use `mc config host add "+alias+" "+url+" "+accessKey+" "+secretKey+" S3v2` instead.")
}
api = "S3v2"
}
if api == "" {
api = "S3v4"
}
+20 -13
View File
@@ -94,7 +94,12 @@ func printHosts(hosts ...hostMessage) {
}
for _, host := range hosts {
// Format properly for alignment based on alias length.
host.Alias = fmt.Sprintf("%-*.*s", maxAlias, maxAlias, host.Alias)
host.Alias = fmt.Sprintf("%-*.*s:", maxAlias, maxAlias, host.Alias)
if host.AccessKey == "" || host.SecretKey == "" {
host.AccessKey = ""
host.SecretKey = ""
host.API = ""
}
printMsg(host)
}
}
@@ -115,12 +120,13 @@ func listHosts(alias string) {
if alias != "" {
if v, ok := conf.Hosts[alias]; ok {
printHosts(hostMessage{
op: "list",
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
op: "list",
prettyPrint: false,
Alias: alias,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
})
return
}
@@ -130,12 +136,13 @@ func listHosts(alias string) {
var hosts []hostMessage
for k, v := range conf.Hosts {
hosts = append(hosts, hostMessage{
op: "list",
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
op: "list",
prettyPrint: true,
Alias: k,
URL: v.URL,
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
})
}
+29 -16
View File
@@ -18,7 +18,6 @@ package cmd
import (
"encoding/json"
"fmt"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
@@ -48,27 +47,41 @@ func mainConfigHost(ctx *cli.Context) error {
// hostMessage container for content message structure
type hostMessage struct {
op string
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
op string
prettyPrint bool
Status string `json:"status"`
Alias string `json:"alias"`
URL string `json:"URL"`
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
}
// String colorized host message
// Print the config information of one alias, when prettyPrint flag
// is activated, fields contents are cut and '...' will be added to
// show a pretty table of all aliases configurations
func (h hostMessage) String() string {
switch h.op {
case "list":
message := console.Colorize("Alias", fmt.Sprintf("%s: ", h.Alias))
message += console.Colorize("URL", fmt.Sprintf("%-30.30s", h.URL))
if h.AccessKey != "" || h.SecretKey != "" {
message += console.Colorize("AccessKey", fmt.Sprintf(" %-20.20s", h.AccessKey))
message += console.Colorize("SecretKey", fmt.Sprintf(" %-40.40s", h.SecretKey))
message += console.Colorize("API", fmt.Sprintf(" %.20s", h.API))
urlFieldMaxLen, apiFieldMaxLen := -1, -1
accessFieldMaxLen, secretFieldMaxLen := -1, -1
// Set cols width if prettyPrint flag is enabled
if h.prettyPrint {
urlFieldMaxLen = 30
accessFieldMaxLen = 20
secretFieldMaxLen = 40
apiFieldMaxLen = 5
}
return message
// Create a new pretty table with cols configuration
t := newPrettyTable(" ",
Field{"Alias", -1},
Field{"URL", urlFieldMaxLen},
Field{"AccessKey", accessFieldMaxLen},
Field{"SecretKey", secretFieldMaxLen},
Field{"API", apiFieldMaxLen},
)
return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
+1 -1
View File
@@ -149,7 +149,7 @@ func isMcConfigExists() bool {
// isValidAlias - Check if alias valid.
func isValidAlias(alias string) bool {
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$").MatchString(alias)
return regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-_]+$").MatchString(alias)
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
+64 -64
View File
@@ -24,7 +24,6 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"github.com/cheggaaa/pb"
@@ -242,7 +241,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool) {
session.Save()
}
func doCopySession(session *sessionV8) {
func doCopySession(session *sessionV8) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
if !session.HasData() {
@@ -267,75 +266,74 @@ func doCopySession(session *sessionV8) {
// Wait on status of doCopy() operation.
var statusCh = make(chan URLs)
// Add a wait group.
var wg = new(sync.WaitGroup)
wg.Add(1)
// Go routine to monitor signal traps if any.
go func() {
defer wg.Done()
for {
select {
case <-trapCh:
// Receive interrupt notification.
// Loop through all urls.
for urlScanner.Scan() {
var cpURLs URLs
// Unmarshal copyURLs from each line.
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
statusCh <- doCopyFake(cpURLs, progressReader)
} else {
statusCh <- doCopy(cpURLs, progressReader, accntReader)
}
}
// URLs feeding finished
close(statusCh)
}()
var retErr error
loop:
for {
select {
case <-trapCh:
// Receive interrupt notification.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
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()
} else {
// Set exit status for any copy error
retErr = exitStatus(globalErrorExitStatus)
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue loop
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
return
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
} else {
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
}
}
}
}()
// Loop through all urls.
for urlScanner.Scan() {
var cpURLs URLs
// Unmarshal copyURLs from each line.
json.Unmarshal([]byte(urlScanner.Text()), &cpURLs)
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
statusCh <- doCopyFake(cpURLs, progressReader)
} else {
statusCh <- doCopy(cpURLs, progressReader, accntReader)
}
}
// Close the goroutine.
close(statusCh)
// Wait for the goroutines to finish.
wg.Wait()
if !globalQuiet && !globalJSON {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
@@ -345,6 +343,8 @@ func doCopySession(session *sessionV8) {
console.Println(console.Colorize("Copy", accntReader.Stat().String()))
}
}
return retErr
}
// mainCopy is the entry point for cp command.
@@ -368,8 +368,8 @@ func mainCopy(ctx *cli.Context) error {
// extract URLs.
session.Header.CommandArgs = ctx.Args()
doCopySession(session)
e = doCopySession(session)
session.Delete()
return nil
return e
}
+3 -3
View File
@@ -30,7 +30,7 @@ var (
eventsAddFlags = []cli.Flag{
cli.StringFlag{
Name: "events",
Value: "put,delete",
Value: "put,delete,get",
Usage: "Filter specific type of events. Defaults to all events.",
},
cli.StringFlag{
@@ -54,7 +54,7 @@ var eventsAddCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET ARN [FLAGS]
{{.HelpName}} TARGET ARN [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -64,7 +64,7 @@ EXAMPLES:
$ {{.HelpName}} myminio/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue
2. Enable bucket notification with filters parameters
$ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete --prefix photos/ --suffix .jpg
$ {{.HelpName}} s3/mybucket arn:aws:sqs:us-west-2:444455556666:your-queue --events put,delete,get --prefix photos/ --suffix .jpg
`,
}
+1 -1
View File
@@ -40,7 +40,7 @@ var eventsListCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET ARN [FLAGS]
{{.HelpName}} TARGET ARN [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -45,7 +45,7 @@ var eventsRemoveCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS/BUCKET [ARN] [FLAGS]
{{.HelpName}} TARGET [ARN] [FLAGS]
FLAGS:
{{range .VisibleFlags}}{{.}}
+3
View File
@@ -64,6 +64,9 @@ var (
)
var (
// Terminal width
globalTermWidth int
// CA root certificates, a nil value means system certs pool will be used
globalRootCAs *x509.CertPool
)
+8 -3
View File
@@ -77,12 +77,17 @@ func Main() {
probe.SetAppInfo("Release-Tag", ReleaseTag)
probe.SetAppInfo("Commit", ShortCommitID)
// Fetch terminal size, if not available, automatically
// set globalQuiet to true.
if w, e := pb.GetTerminalWidth(); e != nil {
globalQuiet = true
} else {
globalTermWidth = w
}
app := registerApp()
app.Before = registerBefore
app.ExtraInfo = func() map[string]string {
if _, e := pb.GetTerminalWidth(); e != nil {
globalQuiet = true
}
if globalDebug {
return getSystemData()
}
+6 -1
View File
@@ -32,6 +32,10 @@ var (
Value: "us-east-1",
Usage: "Specify bucket region. Defaults to `us-east-1`.",
},
cli.BoolFlag{
Name: "ignore-existing, p",
Usage: "Ignore if bucket/directory already exists",
},
}
)
@@ -108,6 +112,7 @@ func mainMakeBucket(ctx *cli.Context) error {
// Save region.
region := ctx.String("region")
ignoreExisting := ctx.Bool("p")
var cErr error
for i := range ctx.Args() {
@@ -121,7 +126,7 @@ func mainMakeBucket(ctx *cli.Context) error {
}
// Make bucket.
err = clnt.MakeBucket(region)
err = clnt.MakeBucket(region, ignoreExisting)
if err != nil {
errorIf(err.Trace(targetURL), "Unable to make bucket `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
+1
View File
@@ -89,6 +89,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
func (s *TestSuite) TestIsvalidAliasName(c *C) {
c.Check(isValidAlias("helloWorld0"), Equals, true)
c.Check(isValidAlias("hello_World0"), Equals, true)
c.Check(isValidAlias("h0SFD2k24Fdsa"), Equals, true)
c.Check(isValidAlias("fdslka-4"), Equals, true)
c.Check(isValidAlias("fdslka-"), Equals, true)
+12 -7
View File
@@ -20,11 +20,11 @@ import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/fatih/color"
"github.com/minio/cli"
@@ -229,7 +229,6 @@ func (mj *mirrorJob) startStatus() {
go func() {
// now we want to start the progress bar
mj.status.Start()
defer mj.status.Finish()
defer mj.wgStatus.Done()
for sURLs := range mj.statusCh {
@@ -262,6 +261,7 @@ func (mj *mirrorJob) startStatus() {
func (mj *mirrorJob) stopStatus() {
close(mj.statusCh)
mj.wgStatus.Wait()
mj.status.Finish()
}
// this goroutine will watch for notifications, and add modified objects to the queue
@@ -509,7 +509,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isWatch, isForce bool
statusCh: make(chan URLs),
wgStatus: new(sync.WaitGroup),
watcherRunning: true,
watcher: NewWatcher(time.Now().UTC()),
watcher: NewWatcher(UTCNow()),
}
return &mj
@@ -555,7 +555,12 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error {
dstClt, err := newClient(dstURL)
fatalIf(err, "Unable to initialize `"+srcURL+"`")
mirrorAllBuckets := (dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/")
if ctx.Bool("a") && (srcClt.GetURL().Type != objectStorage || dstClt.GetURL().Type != objectStorage) {
fatalIf(errDummy(), "Synchronizing bucket policies is only possible when both source & target point to S3 servers")
}
mirrorAllBuckets := (srcClt.GetURL().Type == objectStorage && srcClt.GetURL().Path == "/") ||
(dstClt.GetURL().Type == objectStorage && dstClt.GetURL().Path == "/")
if mirrorAllBuckets {
// Synchronize buckets using dirDifference function
@@ -570,15 +575,15 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error {
sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String())
newSrcURL := srcURL + sourceSuffix
newTgtURL := dstURL + sourceSuffix
newSrcURL := path.Join(srcURL, sourceSuffix)
newTgtURL := path.Join(dstURL, sourceSuffix)
newSrcClt, _ := newClient(newSrcURL)
newDstClt, _ := newClient(newTgtURL)
if d.Diff == differInFirst {
// Bucket only exists in the source, create the same bucket in the destination
err := newDstClt.MakeBucket(ctx.String("region"))
err := newDstClt.MakeBucket(ctx.String("region"), false)
if err != nil {
mj.mirrorErr = err
errorIf(err, "Cannot created bucket in `"+newTgtURL+"`")
+89
View File
@@ -0,0 +1,89 @@
/*
* 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/rjeczalik/notify"
// Dynamically sized logical channel: a pipe which never blocks even when
// it receives too many elements. Memory consumption is increased and decresed
// on the fly following the number of elements. Here is the benchmark which
// compares a regular channel which a large capacity (like 1 Million) in
// contrast to a PipeChan with an realtime increasing/decreasing capacity.
//
// BenchmarkRegular1M-4 200 172809399 ns/op
// BenchmarkPipeChan1M-4 100 316668338 ns/op
// BenchmarkRegular100K-4 2000 16540648 ns/op
// BenchmarkPipeChan100K-4 1000 31905966 ns/op
// BenchmarkRegular10K-4 20000 1637665 ns/op
// BenchmarkPipeChan10K-4 10000 3324329 ns/op
// BenchmarkRegular1K-4 200000 168512 ns/op
// BenchmarkPipeChan1K-4 100000 550623 ns/op
// PipeChan builds a new dynamically sized channel
func PipeChan(capacity int) (inputCh chan notify.EventInfo, outputCh chan notify.EventInfo) {
// A set of channels which store all elements received from input
channels := make(chan chan notify.EventInfo, 1000)
inputCh = make(chan notify.EventInfo, capacity)
// A goroutine which receives elements from inputCh and creates
// new channels when needed.
go func() {
// Create the first channel
currCh := make(chan notify.EventInfo, capacity)
channels <- currCh
for elem := range inputCh {
// Prepare next channel with a double capacity when
// half of the current channel is already filled.
if len(currCh) >= cap(currCh)/2 {
close(currCh)
currCh = make(chan notify.EventInfo, cap(currCh)*2)
channels <- currCh
}
// Prepare next channel with half capacity when
// current channel is 1/4 filled
if len(currCh) >= capacity && len(currCh) <= cap(currCh)/4 {
close(currCh)
currCh = make(chan notify.EventInfo, cap(currCh)/2)
channels <- currCh
}
// Send element to current channel
currCh <- elem
}
close(currCh)
close(channels)
}()
// Copy elements from infinite channel set to the output
outputCh = make(chan notify.EventInfo, capacity)
go func() {
for {
currCh, ok := <-channels
if !ok {
break
}
for v := range currCh {
outputCh <- v
}
}
close(outputCh)
}()
return inputCh, outputCh
}
+141
View File
@@ -0,0 +1,141 @@
/*
* 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"
"sync"
"testing"
"github.com/rjeczalik/notify"
)
func testPipeChan(inputCh, outputCh chan notify.EventInfo, totalMsgs int) error {
var wg sync.WaitGroup
msgCtnt := notify.EventInfo(nil)
// Send messages up to totalMsgs
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < totalMsgs; i++ {
select {
case inputCh <- msgCtnt:
}
}
close(inputCh)
}()
// Goroutine to receive and check messages
var recvMsgs int
var recvErr error
wg.Add(1)
go func() {
defer wg.Done()
for msg := range outputCh {
recvMsgs++
if msg != msgCtnt {
recvErr = fmt.Errorf("Corrupted message, expected = `%s`, found = `%s`", msgCtnt, msg)
return
}
}
}()
// Wait until we finish sending and receiving messages
wg.Wait()
if recvErr != nil {
return recvErr
}
// Check if all messages are received
if recvMsgs != totalMsgs {
return fmt.Errorf("unable to receive all messages, expected: %d, lost: %d", totalMsgs, totalMsgs-recvMsgs)
}
return nil
}
// Testing code
func TestPipeChannel(t *testing.T) {
fastCh, slowCh := PipeChan(1000)
err := testPipeChan(fastCh, slowCh, 10*1000)
if err != nil {
t.Errorf("ERR: %v\n", err)
}
}
func TestRegularChannel(t *testing.T) {
ch := make(chan notify.EventInfo, 1000)
err := testPipeChan(ch, ch, 10*1000)
if err != nil {
t.Errorf("ERR: %v\n", err)
}
}
// Benchmark code
func benchmarkRegular(b *testing.B, msgsNum int) {
for n := 0; n < b.N; n++ {
ch := make(chan notify.EventInfo, msgsNum)
testPipeChan(ch, ch, msgsNum)
}
}
func benchmarkPipeChan(b *testing.B, msgsNum int) {
for n := 0; n < b.N; n++ {
fastCh, slowCh := PipeChan(1000)
testPipeChan(fastCh, slowCh, msgsNum)
}
}
func BenchmarkRegular1M(b *testing.B) {
benchmarkRegular(b, 1*1000*1000)
}
func BenchmarkPipeChan1M(b *testing.B) {
benchmarkPipeChan(b, 1*1000*1000)
}
func BenchmarkRegular100K(b *testing.B) {
benchmarkRegular(b, 100*1000)
}
func BenchmarkPipeChan100K(b *testing.B) {
benchmarkPipeChan(b, 100*1000)
}
func BenchmarkRegular10K(b *testing.B) {
benchmarkRegular(b, 10*1000)
}
func BenchmarkPipeChan10K(b *testing.B) {
benchmarkPipeChan(b, 10*1000)
}
func BenchmarkRegular1K(b *testing.B) {
benchmarkRegular(b, 1*1000)
}
func BenchmarkPipeChan1K(b *testing.B) {
benchmarkPipeChan(b, 1*1000)
}
+1
View File
@@ -49,6 +49,7 @@ var policyCmd = cli.Command{
USAGE:
{{.HelpName}} [FLAGS] PERMISSION TARGET
{{.HelpName}} [FLAGS] TARGET
{{.HelpName}} list [FLAGS] TARGET
PERMISSION:
Allowed policies are: [none, download, upload, public].
+84
View File
@@ -0,0 +1,84 @@
/*
* 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"
"github.com/minio/mc/pkg/console"
)
// Field configuration: color theme and max content length
type Field struct {
colorTheme string
maxLen int
}
// PrettyTable - an easy struct to format a set of line
type PrettyTable struct {
cols []Field
separator string
}
// newPrettyTable - creates a new pretty table
func newPrettyTable(separator string, cols ...Field) PrettyTable {
return PrettyTable{
cols: cols,
separator: separator,
}
}
// buildRow - creates a string which represents a line table given
// some fields contents.
func (t PrettyTable) buildRow(contents ...string) (line string) {
dots := "..."
// totalColumns is the minimum of the number of fields config
// and the number of contents elements.
totalColumns := len(contents)
if len(t.cols) < totalColumns {
totalColumns = len(t.cols)
}
// Format fields and construct message
for i := 0; i < totalColumns; i++ {
// Default field format without pretty effect
fieldContent := ""
fieldFormat := "%s"
if t.cols[i].maxLen >= 0 {
// Override field format
fieldFormat = fmt.Sprintf("%%-%d.%ds", t.cols[i].maxLen, t.cols[i].maxLen)
// Cut field string and add '...' if length is greater than maxLen
if len(contents[i]) > t.cols[i].maxLen {
fieldContent = contents[i][:t.cols[i].maxLen-len(dots)] + dots
} else {
fieldContent = contents[i]
}
} else {
fieldContent = contents[i]
}
// Add separator if this is not the last column
if i < totalColumns-1 {
fieldFormat += t.separator
}
// Add the field to the resulted message
line += console.Colorize(t.cols[i].colorTheme, fmt.Sprintf(fieldFormat, fieldContent))
}
return
}
+51
View File
@@ -0,0 +1,51 @@
/*
* 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 "testing"
// TestPrettyTable - testing the behavior of the pretty table module
func TestPrettyTable(t *testing.T) {
testCases := []struct {
sep string
tf []Field
contents []string
expectedRow string
}{
// Test 1: empty parameter, empty table
{"", []Field{}, []string{}, ""},
// Test 2: one field, without any specific customization
{"", []Field{{"", -1}}, []string{"abcd"}, "abcd"},
// Test 3: one field, without 5 chars len
{"", []Field{{"", 5}}, []string{"my-long-field"}, "my..."},
// Test 4: one separator, one content
{" | ", []Field{{"", -1}}, []string{"abcd"}, "abcd"},
// Test 5: one separtor, multiple contents
{" | ", []Field{{"", -1}, {"", -1}, {"", -1}}, []string{"column1", "column2", "column3"}, "column1 | column2 | column3"},
// Test 6: multiple fields
{" | ", []Field{{"", 5}, {"", -1}}, []string{"144550032", "my long content that should not be cut"}, "14... | my long content that should not be cut"},
}
for idx, testCase := range testCases {
tb := newPrettyTable(testCase.sep, testCase.tf...)
row := tb.buildRow(testCase.contents...)
if row != testCase.expectedRow {
t.Fatalf("Test %d: generated row not matching, expected = `%s`, found = `%s`", idx+1, testCase.expectedRow, row)
}
}
}
+2 -2
View File
@@ -149,7 +149,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error {
}
if older > 0 {
// Check whether object is created older than given time.
now := time.Now().UTC()
now := UTCNow()
timeDiff := now.Sub(content.Time)
if timeDiff < (time.Duration(older) * Day) {
// time difference of info.Time with current time is less than older time.
@@ -211,7 +211,7 @@ func removeRecursive(url string, isIncomplete bool, isFake bool, older int) erro
if older > 0 {
// Check whether object is created older than given time.
now := time.Now().UTC()
now := UTCNow()
timeDiff := now.Sub(content.Time)
if timeDiff < (time.Duration(older) * Day) {
// time difference of info.Time with current time is less than older time.
+1 -5
View File
@@ -20,10 +20,8 @@ import (
"fmt"
"strings"
"github.com/cheggaaa/pb"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
)
// fixateScanBar truncates or stretches text to fit within the terminal size.
@@ -46,14 +44,12 @@ type scanBarFunc func(string)
// scanBarFactory returns a progress bar function to report URL scanning.
func scanBarFactory() scanBarFunc {
fileCount := 0
termWidth, e := pb.GetTerminalWidth()
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
source = fixateScanBar(source, termWidth-len([]rune(scanPrefix)))
source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix)))
barText := scanPrefix + source
console.PrintC("\r" + barText + "\r")
fileCount++
+3 -3
View File
@@ -45,7 +45,7 @@ var sessionCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] OPERATION [ARG]
{{.HelpName}} [FLAGS] OPERATION [SESSION-ID]
OPERATION:
resume Resume a previously saved session.
@@ -134,7 +134,7 @@ func clearSession(sid string) {
session, err := loadSessionV8(sid)
fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
}
@@ -156,7 +156,7 @@ func clearSession(sid string) {
}
if session != nil {
fatalIf(session.Delete().Trace(sid), "Unable to load session `"+sid+"`.")
fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`.")
printMsg(clearSessionMessage{Status: "success", SessionID: sid})
}
}
+3
View File
@@ -37,6 +37,9 @@ func migrateSessionV7ToV8() {
fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
}
// Close underlying session data file.
sV7.DataFP.Close()
sessionVersion, e := strconv.Atoi(sV7.Header.Version)
fatalIf(probe.NewError(e), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionVersion > 7 { // It is new format.
+1 -1
View File
@@ -174,7 +174,7 @@ func newSessionV8() *sessionV8 {
s.Header.CommandBoolFlags = make(map[string]bool)
s.Header.CommandIntFlags = make(map[string]int)
s.Header.CommandStringFlags = make(map[string]string)
s.Header.When = time.Now().UTC()
s.Header.When = UTCNow()
s.mutex = new(sync.Mutex)
s.SessionID = newRandomID(8)
+1 -1
View File
@@ -59,7 +59,7 @@ func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration,
s.Shares[shareURL] = shareEntryV1{
URL: objectURL,
Date: time.Now().UTC(),
Date: UTCNow(),
Expiry: expiry,
ContentType: contentType,
}
+10 -4
View File
@@ -44,7 +44,7 @@ var shareDownload = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [OPTIONS] TARGET [TARGET...]
{{.HelpName}} [FLAGS] TARGET [TARGET...]
OPTIONS:
{{range .VisibleFlags}}{{.}}
@@ -89,9 +89,15 @@ func checkShareDownloadSyntax(ctx *cli.Context) {
fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.")
}
for _, url := range ctx.Args() {
_, _, err := url2Stat(url)
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
// Validate if object exists only if the `--recursive` option was NOT specified
isRecursive := ctx.Bool("recursive")
if !isRecursive {
for _, url := range ctx.Args() {
_, _, err := url2Stat(url)
if err != nil {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ var shareUpload = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [OPTIONS] TARGET [TARGET...]
{{.HelpName}} [FLAGS] TARGET [TARGET...]
OPTIONS:
{{range .VisibleFlags}}{{.}}
+1 -1
View File
@@ -200,7 +200,7 @@ func downloadReleaseData(releaseChecksumURL string, timeout time.Duration) (data
// DownloadReleaseData - downloads release data from minio official server.
func DownloadReleaseData(timeout time.Duration) (data string, err *probe.Error) {
return downloadReleaseData(mcReleaseURL+"mc.shasum", timeout)
return downloadReleaseData(mcReleaseURL+"mc.sha256sum", timeout)
}
func parseReleaseData(data string) (releaseTime time.Time, err *probe.Error) {
+6 -1
View File
@@ -47,11 +47,16 @@ func isErrIgnored(err *probe.Error) (ignored bool) {
return ignored
}
// UTCNow - returns current UTC time.
func UTCNow() time.Time {
return time.Now().UTC()
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// newRandomID generates a random id of regular lower case and uppercase english characters.
func newRandomID(n int) string {
rand.Seed(time.Now().UTC().UnixNano())
rand.Seed(UTCNow().UnixNano())
sid := make([]rune, n)
for i := range sid {
sid[i] = letters[rand.Intn(len(letters))]
+22 -5
View File
@@ -36,7 +36,7 @@ var (
watchFlags = []cli.Flag{
cli.StringFlag{
Name: "events",
Value: "put,delete",
Value: "put,delete,get",
Usage: "Filter specific type of events. Defaults to all events by default.",
},
cli.StringFlag{
@@ -64,7 +64,7 @@ var watchCmd = cli.Command{
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS]
{{.HelpName}} PATH [FLAGS]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -97,7 +97,17 @@ func checkWatchSyntax(ctx *cli.Context) {
// watchMessage container to hold one event notification
type watchMessage struct {
Status string `json:"status"`
Event Event `json:"events"`
Event struct {
Time string `json:"time"`
Size int64 `json:"size"`
Path string `json:"path"`
Type EventType `json:"type"`
} `json:"events"`
Source struct {
Host string `json:"host,omitempty"`
Port string `json:"port,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
} `json:"source,omitempty"`
}
func (u watchMessage) JSON() string {
@@ -169,13 +179,20 @@ func mainWatch(ctx *cli.Context) error {
select {
case <-trapCh:
// Signal received we are done.
close(wo.done)
close(wo.doneChan)
return
case event, ok := <-wo.Events():
if !ok {
return
}
msg := watchMessage{Event: event}
msg := watchMessage{}
msg.Event.Path = event.Path
msg.Event.Size = event.Size
msg.Event.Time = event.Time
msg.Event.Type = event.Type
msg.Source.Host = event.Host
msg.Source.Port = event.Port
msg.Source.UserAgent = event.UserAgent
printMsg(msg)
case err, ok := <-wo.Errors():
if !ok {
+39 -30
View File
@@ -24,23 +24,32 @@ import (
"github.com/minio/minio/pkg/probe"
)
// EventType is the type of the event that occurred
// EventType represents the type of the event occurred.
type EventType string
const (
// EventCreate notifies when a new object has been created
// EventCreate notifies when a new object is created
EventCreate EventType = "ObjectCreated"
// EventRemove notifies when a new object has been deleted
// EventRemove notifies when a new object is deleted
EventRemove = "ObjectRemoved"
// EventAccessed notifies when an object is accessed.
EventAccessed = "ObjectAccessed"
// EventAccessedRead notifies when an object is accessed (specifically read).
EventAccessedRead = "ObjectAccessed:Read"
// EventAccessedStat notifies when an object is accessed (specifically stat).
EventAccessedStat = "ObjectAccessed:Stat"
)
// Event contains the information of the event that occurred
type Event struct {
Time string `json:"time"`
Size int64 `json:"size"`
Path string `json:"path"`
Client Client `json:"-"`
Type EventType `json:"type"`
// EventInfo contains the information of the event that occurred and the source
// IP:PORT of the client which triggerred the event.
type EventInfo struct {
Time string
Size int64
Path string
Type EventType
Host string
Port string
UserAgent string
}
type watchParams struct {
@@ -52,37 +61,37 @@ type watchParams struct {
}
type watchObject struct {
// events will be put on this chan
events chan Event
// eventInfo will be put on this chan
eventInfoChan chan EventInfo
// errors will be put on this chan
errors chan *probe.Error
errorChan chan *probe.Error
// will stop the watcher goroutines
done chan bool
doneChan chan bool
}
// Events returns the chan receiving events
func (w *watchObject) Events() chan Event {
return w.events
func (w *watchObject) Events() chan EventInfo {
return w.eventInfoChan
}
// Errors returns the chan receiving errors
func (w *watchObject) Errors() chan *probe.Error {
return w.errors
return w.errorChan
}
// Close the watcher, will stop all goroutines
func (w *watchObject) Close() {
close(w.done)
close(w.doneChan)
}
// Watcher can be used to have one or multiple clients watch for notifications
type Watcher struct {
sessionStartTime time.Time
// all errors will be added to this chan
errorsChan chan *probe.Error
// all error will be added to this chan
errorChan chan *probe.Error
// all events will be added to this chan
eventsChan chan Event
eventInfoChan chan EventInfo
// array of watchers joined
o []*watchObject
@@ -95,20 +104,20 @@ type Watcher struct {
func NewWatcher(sessionStartTime time.Time) *Watcher {
return &Watcher{
sessionStartTime: sessionStartTime,
errorsChan: make(chan *probe.Error),
eventsChan: make(chan Event),
errorChan: make(chan *probe.Error),
eventInfoChan: make(chan EventInfo),
o: []*watchObject{},
}
}
// Errors returns a channel which will receive errors
func (w *Watcher) Errors() chan *probe.Error {
return w.errorsChan
return w.errorChan
}
// Events returns a channel which will receive events
func (w *Watcher) Events() chan Event {
return w.eventsChan
func (w *Watcher) Events() chan EventInfo {
return w.eventInfoChan
}
// Stop watcher
@@ -120,8 +129,8 @@ func (w *Watcher) Stop() {
w.wg.Wait()
close(w.errorsChan)
close(w.eventsChan)
close(w.errorChan)
close(w.eventInfoChan)
}
// Watching returns if the watcher is watching for notifications
@@ -162,13 +171,13 @@ func (w *Watcher) Join(client Client, recursive bool) *probe.Error {
return
}
w.eventsChan <- event
w.eventInfoChan <- event
case err, ok := <-wo.Errors():
if !ok {
return
}
w.errorsChan <- err
w.errorChan <- err
}
}
}()