Review error messages part of #286

This commit is contained in:
Harshavardhana
2015-04-17 20:31:35 -07:00
parent 5f4d89ccd5
commit 39d3f1439b
15 changed files with 101 additions and 383 deletions
+8 -11
View File
@@ -34,17 +34,16 @@ func isValidAliasName(aliasName string) bool {
// aliasExpand expands aliased (name:/path) to full URL, used by url-parser
func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, err error) {
url, err := url.Parse(aliasedURL)
if err != nil {
// Not a valid URL. Return error
return "", iodine.New(errInvalidURL{url: aliasedURL}, nil)
if aliasedURL == "" || aliases == nil {
return aliasedURL, iodine.New(errInvalidArgument{}, nil)
}
// Not an aliased URL
if url.Scheme == "" {
u, err := url.Parse(aliasedURL)
if err != nil {
return aliasedURL, iodine.New(errInvalidURL{url: aliasedURL}, nil)
}
if u.Scheme == "" {
return aliasedURL, nil
}
for aliasName, expandedURL := range aliases {
if !isValidAliasName(aliasName) {
return "", iodine.New(errInvalidAliasName{name: aliasName}, nil)
@@ -55,7 +54,5 @@ func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, e
return expandedURL + "/" + splits[1], nil
}
}
// No matching alias. Return the original
return aliasedURL, nil
return aliasedURL, iodine.New(errAliasNotFound{name: aliasedURL}, nil)
}
+6 -6
View File
@@ -43,15 +43,15 @@ func (s *MySuite) TestEmptyExpansions(c *C) {
// c.Skip("Test still being written")
url, err := aliasExpand("hello", nil)
c.Assert(url, Equals, "hello")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
url, err = aliasExpand("minio://hello", nil)
c.Assert(url, Equals, "minio://hello")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
url, err = aliasExpand("$#\\", nil)
c.Assert(url, Equals, "$#\\")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo"})
c.Assert(url, Equals, "http://foo/bar")
@@ -59,13 +59,13 @@ func (s *MySuite) TestEmptyExpansions(c *C) {
url, err = aliasExpand("myfoo:bar", map[string]string{"foo": "http://foo"})
c.Assert(url, Equals, "myfoo:bar")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
url, err = aliasExpand("", map[string]string{"foo": "http://foo"})
c.Assert(url, Equals, "")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
url, err = aliasExpand("hello", nil)
c.Assert(url, Equals, "hello")
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
}
+57
View File
@@ -0,0 +1,57 @@
/*
* Mini Copy, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
// exact key length
const (
accessKeyLength = 20
secretAccessLength = 40
)
// isValidSecretKey - validate secret key
func isValidSecretKey(secretAccesskey string) bool {
if len(secretAccesskey) != secretAccessLength {
return false
}
return true
}
// isValidAccessKey - validate access key
func isValidAccessKey(accessKeyID string) bool {
if len(accessKeyID) != accessKeyLength {
return false
}
// Is alphanumeric?
isalnum := func(c rune) bool {
return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
}
for _, char := range accessKeyID {
if isalnum(char) {
continue
}
switch char {
case '-':
case '.':
case '_':
case '~':
continue
default:
return false
}
}
return true
}
+9
View File
@@ -238,6 +238,15 @@ func getHostConfig(requestURL string) (map[string]string, error) {
return nil, iodine.New(errInvalidGlobURL{glob: globURL, request: requestURL}, nil)
}
if match {
// verify Auth key validity for all hosts other than localhost
if !strings.Contains(getHostURL(u), "localhost") {
if !isValidAccessKey(hostConfig["Auth.AccessKeyID"]) {
return nil, iodine.New(errInvalidAuthKeys{}, nil)
}
if !isValidSecretKey(hostConfig["Auth.SecretAccessKey"]) {
return nil, iodine.New(errInvalidAuthKeys{}, nil)
}
}
return hostConfig, nil
}
}
+11 -11
View File
@@ -26,7 +26,6 @@ import (
"github.com/minio-io/minio/pkg/utils/log"
)
// doCopyCmd copies objects into and from a bucket or between buckets
func runCopyCmd(ctx *cli.Context) {
if len(ctx.Args()) < 2 {
cli.ShowCommandHelpAndExit(ctx, "cp", 1) // last argument is exit code
@@ -42,27 +41,28 @@ func runCopyCmd(ctx *cli.Context) {
urls, err := parseURLs(ctx.Args(), config.GetMapString("Aliases"))
if err != nil {
log.Debug.Println(iodine.New(err, nil))
console.Fatalln("mc: Unable to parse URL")
console.Fatalf("mc: Unable to parse URLs [%s]\n", urls)
}
sourceURL := urls[0] // First arg is source
targetURLs := urls[1:] // 1 or more targets
// perform copy
if ctx.Bool("recursive") {
doCopyCmdRecursive(mcClientManager{}, sourceURL, targetURLs)
} else {
humanReadableError, err := doCopyCmd(mcClientManager{}, sourceURL, targetURLs)
err = iodine.New(err, nil)
if err != nil {
if humanReadableError == "" {
humanReadableError = "No error message present, please rerun with --debug and report a bug."
}
log.Debug.Println(err)
console.Errorln("mc: " + humanReadableError)
}
humanReadableError, err := doCopyCmd(mcClientManager{}, sourceURL, targetURLs)
err = iodine.New(err, nil)
if err != nil {
if humanReadableError == "" {
humanReadableError = "No error message present, please rerun with --debug and report a bug."
}
log.Debug.Println(err)
console.Errorf("mc: %s\n", humanReadableError)
}
}
// doCopyCmd copies objects into and from a bucket or between buckets
func doCopyCmd(manager clientManager, sourceURL string, targetURLs []string) (string, error) {
reader, length, hexMd5, err := manager.getSourceReader(sourceURL)
if err != nil {
+4 -3
View File
@@ -69,7 +69,7 @@ func doListCmd(ctx *cli.Context) {
u, err := parseURL(arg, config.GetMapString("Aliases"))
if err != nil {
log.Debug.Println(iodine.New(err, nil))
console.Fatalln("mc: Unable to parse URL")
console.Fatalf("mc: Unable to parse URL [%s]\n", u)
}
manager := mcClientManager{}
clnt, err := manager.getNewClient(u, globalDebugFlag)
@@ -104,14 +104,15 @@ func doListCmd(ctx *cli.Context) {
for r := retries.init(); r.retry(); {
items, err = clnt.ListObjects(bucket, object)
if !isValidRetry(err) {
break
}
}
if err != nil {
log.Debug.Println(iodine.New(err, nil))
console.Fatalf("mc: Unable to list objects for URL[%s] ", u)
// Add a newline
console.Infoln()
console.Fatalf("mc: Unable to list objects for URL [%s]\n", u)
}
console.Infoln()
printObjects(items)
+1 -1
View File
@@ -38,7 +38,7 @@ func doMakeBucketCmd(ctx *cli.Context) {
u, err := parseURL(arg, config.GetMapString("Aliases"))
if err != nil {
log.Debug.Println(iodine.New(err, nil))
console.Fatalf("mc: Unable to parse URL[%s]\n", u)
console.Fatalf("mc: Unable to parse URL [%s]\n", u)
}
bucket, _, err := url2Object(u)
if err != nil {
+4 -3
View File
@@ -23,6 +23,7 @@ import (
"sync"
"errors"
. "github.com/minio-io/check"
"github.com/minio-io/mc/pkg/client"
@@ -36,7 +37,7 @@ var _ = Suite(&CmdTestSuite{})
func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) {
manager := &MockclientManager{}
sourceURL, err := parseURL("foo", nil)
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
data := "Hello World"
md5Sum := md5.Sum([]byte(data))
@@ -44,7 +45,7 @@ func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) {
dataLength := int64(len(data))
targetURL, err := parseURL("bar", nil)
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
targetURLs := []string{targetURL}
sourceReader, sourceWriter := io.Pipe()
@@ -65,7 +66,7 @@ func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) {
manager.On("getTargetWriter", targetURL, hexMd5, dataLength).Return(targetWriter, nil).Once()
doCopyCmd(manager, sourceURL, targetURLs)
wg.Wait()
c.Assert(err, IsNil)
c.Assert(err, Not(IsNil))
c.Assert(resultBuffer.String(), DeepEquals, data)
}
+1 -1
View File
@@ -1,5 +1,5 @@
/*
* Mini Copy, (C) 2014, 2015 Minio, Inc.
* Mini Copy, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
-24
View File
@@ -1,24 +0,0 @@
package config
// Aliases - keep a map
type Aliases map[string]string
// Set - set an alias
func (a Aliases) Set(aliasName, urlName string) {
a[aliasName] = urlName
}
// Get - get an alias
func (a Aliases) Get(aliasName string) string {
return a[aliasName]
}
// IsExists verify if alias exists
func (a Aliases) IsExists(aliasName string) bool {
for alias := range a {
if alias == aliasName {
return true
}
}
return false
}
-47
View File
@@ -1,47 +0,0 @@
package config
// Auth - authorization keys
type Auth struct {
AccessKeyID string
SecretAccessKey string
}
// exact key length
const (
AccessKeyLength = 20
SecretAccessLength = 40
)
// IsValidSecretKey - validate secret key
func (a Auth) IsValidSecretKey() bool {
if len(a.SecretAccessKey) != SecretAccessLength {
return false
}
return true
}
// IsValidAccessKey - validate access key
func (a Auth) IsValidAccessKey() bool {
if len(a.AccessKeyID) != AccessKeyLength {
return false
}
// Is alphanumeric?
isalnum := func(c rune) bool {
return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
}
for _, char := range a.AccessKeyID {
if isalnum(char) {
continue
}
switch char {
case '-':
case '.':
case '_':
case '~':
continue
default:
return false
}
}
return true
}
-63
View File
@@ -1,63 +0,0 @@
/*
* Mini Copy, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config
import "github.com/minio-io/minio/pkg/iodine"
// Config - configuration
type Config struct {
Version uint // Config version
Hosts map[string]Auth // URL and their respective Auth map
Aliases Aliases // aliasName and URL map
}
// AddAlias - add a alias into existing alias list
func (c *Config) AddAlias(aliasName string, aliasURL string) error {
if c.Aliases.IsExists(aliasName) {
return iodine.New(AliasExists{Name: aliasName}, nil)
}
c.Aliases.Set(aliasName, aliasURL)
return nil
}
// HostExists - check if host exists
func (c *Config) HostExists(hostURL string) bool {
for host := range c.Hosts {
if host == hostURL {
return true
}
}
return false
}
// AddHostAuth - add host authorization
func (c *Config) AddHostAuth(hostURL, accessKeyID, secretAccessKey string) error {
if c.HostExists(hostURL) {
return iodine.New(HostExists{Name: hostURL}, nil)
}
auth := Auth{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
}
if !auth.IsValidAccessKey() || !auth.IsValidSecretKey() {
return iodine.New(InvalidAuthKeys{}, nil)
}
c.Aliases = make(Aliases)
c.Hosts = make(map[string]Auth)
c.Hosts[hostURL] = auth
return nil
}
-66
View File
@@ -1,66 +0,0 @@
/*
* Mini Copy, (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package config
import (
"io/ioutil"
"os"
"testing"
. "github.com/minio-io/check"
)
type MySuite struct{}
var _ = Suite(&MySuite{})
func Test(t *testing.T) { TestingT(t) }
func (s *MySuite) TestConfig(c *C) {
// create new config.json
configPath, _ := ioutil.TempDir("/tmp", "minio-test-")
ctx, err := New(configPath, "config.json")
c.Assert(err, IsNil)
defer os.RemoveAll(configPath)
// initialize config
ctx.Config = new(Config)
// error on invalid auth keys
err = ctx.Config.AddHostAuth("http*://s3*.amazonaws.com", "YOUR-ACCESS-KEY-ID-HERE", "YOUR-SECRET-ACCESS-KEY-HERE")
c.Assert(err, Not(IsNil))
// success on valid auth keys
err = ctx.Config.AddHostAuth("http*://s3*.amazonaws.com", "AC5NH40NQLTL4D2W92PM", "0nAMx5oJbWx5IgCmOJJneXM8w/ohTz2b0QAb2xvN")
c.Assert(err, IsNil)
// success on add new alias
err = ctx.Config.AddAlias("s3", "https://s3.amazonaws.com")
c.Assert(err, IsNil)
// error on duplicate alias
err = ctx.Config.AddAlias("s3", "https://s3.amazonaws.com")
c.Assert(err, Not(IsNil))
// save config
err = ctx.SaveConfig()
c.Assert(err, IsNil)
// load config
err = ctx.LoadConfig()
c.Assert(err, IsNil)
}
-103
View File
@@ -1,103 +0,0 @@
package config
import (
"encoding/json"
"io"
"os"
"path"
"strings"
"sync"
"github.com/minio-io/minio/pkg/iodine"
)
// Context - config context
type Context struct {
// copy of Config
Config *Config
// file and path for config
configFile string
configPath string
// lock
lock *sync.RWMutex
}
// GetConfigPath path to config file
func (c *Context) GetConfigPath() string {
return c.configPath
}
// GetConfigFile config file
func (c *Context) GetConfigFile() string {
return c.configFile
}
// SaveConfig - write encoded json in config file
func (c *Context) SaveConfig() error {
c.lock.Lock()
defer c.lock.Unlock()
var file *os.File
var err error
file, err = os.OpenFile(c.configFile, os.O_WRONLY, 0666)
defer file.Close()
if err != nil {
return iodine.New(err, nil)
}
encoder := json.NewEncoder(file)
encoder.Encode(c.Config)
return nil
}
// LoadConfig - read json config file and decode
func (c *Context) LoadConfig() error {
c.lock.RLock()
defer c.lock.RUnlock()
var file *os.File
var err error
file, err = os.OpenFile(c.configFile, os.O_RDONLY, 0666)
defer file.Close()
if err != nil {
return iodine.New(err, nil)
}
config := new(Config)
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
switch err {
case io.EOF:
return nil
case nil:
c.Config = config
return nil
default:
return iodine.New(err, nil)
}
}
// New - instantiate a new config context
func New(configPath, configFileName string) (*Context, error) {
if configPath == "" || strings.TrimSpace(configPath) == "" {
return nil, iodine.New(InvalidArgument{}, nil)
}
if configFileName == "" || strings.TrimSpace(configFileName) == "" {
return nil, iodine.New(InvalidArgument{}, nil)
}
c := new(Context)
c.configPath = configPath
c.configFile = path.Join(c.configPath, configFileName)
if _, err := os.Stat(c.configFile); os.IsNotExist(err) {
_, err = os.Create(c.configFile)
if err != nil {
return nil, iodine.New(err, nil)
}
}
c.lock = new(sync.RWMutex)
return c, nil
}
-44
View File
@@ -1,44 +0,0 @@
package config
import "fmt"
// AliasExists - alias exists
type AliasExists struct {
Name string
}
func (e AliasExists) Error() string {
return fmt.Sprintf("alias: %s exists", e.Name)
}
// AliasNotFound - alias not found
type AliasNotFound struct {
Name string
}
func (e AliasNotFound) Error() string {
return fmt.Sprintf("alias: %s exists", e.Name)
}
// InvalidAuthKeys - invalid authorization keys
type InvalidAuthKeys struct{}
func (e InvalidAuthKeys) Error() string {
return fmt.Sprintf("invalid authorization key")
}
// HostExists - host exists
type HostExists struct {
Name string
}
func (e HostExists) Error() string {
return fmt.Sprintf("host: %s exists", e.Name)
}
// InvalidArgument - invalid argument
type InvalidArgument struct{}
func (e InvalidArgument) Error() string {
return fmt.Sprintf("invalid argument")
}