alias support with colon requirement

This commit is contained in:
Anand Babu (AB) Periasamy
2015-08-29 18:02:32 -07:00
parent fc9088142b
commit 91100b72ed
13 changed files with 103 additions and 220 deletions
+20 -50
View File
@@ -19,67 +19,37 @@ package main
import (
"regexp"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio/pkg/probe"
"unicode"
"unicode/utf8"
)
// validAliasURL: use net/url.Parse to validate
// validAliasName regex validation.
var validAliasName = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]+$")
func isAliasReserved(aliasName string) bool {
// help is reserved argument
switch aliasName {
case "help":
fallthrough
case "private":
fallthrough
case "readonly":
fallthrough
case "public":
fallthrough
case "authenticated":
return true
default:
return false
}
}
// Check if it is an aliased URL
// Check if it is an aliased URL.
func isValidAliasName(aliasName string) bool {
return validAliasName.MatchString(aliasName)
}
// aliasExpand expands aliased (name:/path) to full URL, used by url-parser
func aliasExpand(aliasedURL string, aliases map[string]string) (string, *probe.Error) {
u, err := client.Parse(aliasedURL)
if err != nil {
return aliasedURL, probe.NewError(err)
}
// proper URL
if u.Host != "" {
return aliasedURL, nil
}
for aliasName, expandedURL := range aliases {
if strings.HasPrefix(aliasedURL, aliasName+":") {
// aliasExpand expands aliased (name:/path) to full URL, used by url-parser.
func aliasExpand(aliasedURL string, aliases map[string]string) string {
for aliasName, aliasValue := range aliases {
if strings.HasPrefix(aliasedURL, aliasName) {
// Match found. Expand it.
splits := strings.Split(aliasedURL, ":")
// if expandedURL is missing, return aliasedURL treat it like fs
if expandedURL == "" {
return aliasedURL, nil
splits := strings.SplitN(aliasedURL, aliasName, 2)
if len(splits) == 1 {
return aliasedURL // Not an aliased URL. Return as is.
}
// if more splits found return
if len(splits) == 2 {
// remove any prefixed slashes
trimmedURL := expandedURL + "/" + strings.TrimPrefix(strings.TrimPrefix(splits[1], "/"), "\\")
u, err := client.Parse(trimmedURL)
if err != nil {
return aliasedURL, errInvalidURL(aliasedURL).Trace()
}
return u.String(), nil
if len(splits[0]) == 0 && len(splits[1]) == 0 {
return aliasValue // exact match.
}
return aliasedURL, nil
separator, _ := utf8.DecodeRuneInString(splits[1])
if unicode.IsLetter(separator) || unicode.IsNumber(separator) {
return aliasedURL // Do not expand for whole strings with alias prefix.
}
// Matched, but path needs to be joined.
return urlJoinPath(aliasValue, splits[1])
}
}
return aliasedURL, nil
return aliasedURL // No matching alias found. Return as is.
}
+15 -22
View File
@@ -173,13 +173,15 @@ func (s *CmdTestSuite) TestHostConfig(c *C) {
}
func (s *CmdTestSuite) TestArgs2URL(c *C) {
URLs := []string{"localhost:", "s3:", "play:", "https://s3-us-west-2.amazonaws.com"}
URLs := []string{"localhost", "s3", "play", "playgo", "goplay", "https://s3-us-west-2.amazonaws.com"}
expandedURLs, err := args2URLs(URLs)
c.Assert(err, IsNil)
c.Assert(expandedURLs[0], Equals, "http://localhost:9000/")
c.Assert(expandedURLs[1], Equals, "https://s3.amazonaws.com/")
c.Assert(expandedURLs[2], Equals, "https://play.minio.io:9000/")
c.Assert(expandedURLs[3], Equals, "https://s3-us-west-2.amazonaws.com")
c.Assert(expandedURLs[0], Equals, "http://localhost:9000")
c.Assert(expandedURLs[1], Equals, "https://s3.amazonaws.com")
c.Assert(expandedURLs[2], Equals, "https://play.minio.io:9000")
c.Assert(expandedURLs[3], Equals, "playgo") // Has no corresponding alias. So expect same value.
c.Assert(expandedURLs[4], Equals, "goplay") // Has no corresponding alias. So expect same value.
c.Assert(expandedURLs[5], Equals, "https://s3-us-west-2.amazonaws.com")
}
func (s *CmdTestSuite) TestValidPERMS(c *C) {
@@ -247,38 +249,29 @@ func (s *CmdTestSuite) TestIsvalidAliasName(c *C) {
c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
c.Check(isValidAliasName("0dslka-4"), Equals, false)
c.Check(isValidAliasName("-fdslka"), Equals, false)
c.Check(isAliasReserved("help"), Equals, true)
c.Check(isAliasReserved("private"), Equals, true) // reserved names
}
func (s *CmdTestSuite) TestEmptyExpansions(c *C) {
url, err := aliasExpand("hello", nil)
url := aliasExpand("hello", nil)
c.Assert(url, Equals, "hello")
c.Assert(err, IsNil)
url, err = aliasExpand("minio://hello", nil)
url = aliasExpand("minio://hello", nil)
c.Assert(url, Equals, "minio://hello")
c.Assert(err, IsNil)
url, err = aliasExpand("$#\\", nil)
url = aliasExpand("$#\\", nil)
c.Assert(url, Equals, "$#\\")
c.Assert(err, IsNil)
url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo"})
url = aliasExpand("foo/bar", map[string]string{"foo": "http://foo"})
c.Assert(url, Equals, "http://foo/bar")
c.Assert(err, IsNil)
url, err = aliasExpand("myfoo:bar", nil)
c.Assert(url, Equals, "myfoo:bar")
c.Assert(err, IsNil)
url = aliasExpand("myfoo/bar", nil)
c.Assert(url, Equals, "myfoo/bar")
url, err = aliasExpand("", nil)
url = aliasExpand("", nil)
c.Assert(url, Equals, "")
c.Assert(err, IsNil)
url, err = aliasExpand("hello", nil)
url = aliasExpand("hello", nil)
c.Assert(url, Equals, "hello")
c.Assert(err, IsNil)
}
func (s *CmdTestSuite) TestApp(c *C) {
+2 -33
View File
@@ -31,10 +31,7 @@ import (
// Check if the target URL represents folder. It may or may not exist yet.
func isTargetURLDir(targetURL string) bool {
targetURLParse, err := client.Parse(targetURL)
if err != nil {
return false
}
targetURLParse := client.NewURL(targetURL)
_, targetContent, perr := url2Stat(targetURL)
if perr != nil {
if targetURLParse.Path == string(targetURLParse.Separator) && targetURLParse.Scheme != "" {
@@ -134,10 +131,7 @@ func putTargets(targetURLs []string, length int64, reader io.Reader) *probe.Erro
// getNewClient gives a new client interface
func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error) {
url, err := client.Parse(urlStr)
if err != nil {
return nil, probe.NewError(err)
}
url := client.NewURL(urlStr)
switch url.Type {
case client.Object: // Minio and S3 compatible cloud storage
s3Config := new(s3.Config)
@@ -173,31 +167,6 @@ func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error)
return nil, errInitClient(urlStr).Trace()
}
// url2Stat - Returns client, config and its stat Content from the URL
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
client, err = url2Client(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
content, err = client.Stat()
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
}
func isValidURL(url string) bool {
// Empty source arg?
urlParse, err := client.Parse(url)
if err != nil {
return false
}
if urlParse.Path == "" {
return false
}
return true
}
func url2Client(url string) (client.Client, *probe.Error) {
if !isValidURL(url) {
return nil, errInvalidURL(url).Trace()
+3 -7
View File
@@ -50,7 +50,9 @@ USAGE:
EXAMPLES:
1. Add aliases for a URL
$ mc {{.Name}} add alias zek https://s3.amazonaws.com/
$ mc {{.Name}} add alias mcloud https://s3.amazonaws.com/miniocloud
$ mc ls mcloud
$ mc cp /bin/true mccloud/true
2. List all aliased URLs.
$ mc {{.Name}} list alias
@@ -189,9 +191,6 @@ func removeAlias(alias string) {
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config path")
if isAliasReserved(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Cannot use a reserved name ‘%s’ as an alias. Following are reserved names: [help, private, readonly, public, authenticated].", alias))
}
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
@@ -231,9 +230,6 @@ func addAlias(alias, url string) {
if !strings.HasPrefix(url, "http") {
fatalIf(errDummy().Trace(), fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", url))
}
if isAliasReserved(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Cannot use a reserved name ‘%s’ as an alias. Following are reserved names: [help, private, readonly, public, authenticated].", alias))
}
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
+6 -29
View File
@@ -75,10 +75,7 @@ func checkCopySyntax(ctx *cli.Context) {
}
// scope locally
{
url, err := client.Parse(tgtURL)
if err != nil {
fatalIf(probe.NewError(err), fmt.Sprintf("Unable to parse target ‘%s’ argument.", tgtURL))
}
url := client.NewURL(tgtURL)
if url.Host != "" {
if url.Path == string(url.Separator) {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
@@ -258,15 +255,8 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
{
sourceURLParse, err := client.Parse(sourceURL)
if err != nil {
return copyURLs{Error: errInvalidSource(sourceURL).Trace()}
}
targetURLParse, err := client.Parse(targetURL)
if err != nil {
return copyURLs{Error: errInvalidTarget(targetURL).Trace()}
}
sourceURLParse := client.NewURL(sourceURL)
targetURLParse := client.NewURL(targetURL)
targetURLParse.Path = filepath.Join(targetURLParse.Path, filepath.Base(sourceURLParse.Path))
return prepareCopyURLsTypeA(sourceURL, targetURLParse.String())
}
@@ -312,27 +302,14 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string) <-chan copyURLs {
}
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
sourceURLParse, err := client.Parse(sourceURL)
if err != nil {
copyURLsCh <- copyURLs{Error: errInvalidSource(sourceURL).Trace()}
continue
}
targetURLParse, err := client.Parse(targetURL)
if err != nil {
copyURLsCh <- copyURLs{Error: errInvalidTarget(targetURL).Trace()}
continue
}
sourceURLParse := client.NewURL(sourceURL)
targetURLParse := client.NewURL(targetURL)
sourceURLDelimited := sourceURLParse.String()[:strings.LastIndex(sourceURLParse.String(),
string(sourceURLParse.Separator))+1]
sourceContentName := sourceContent.Content.Name
sourceContentURL := sourceURLDelimited + sourceContentName
sourceContentParse, err := client.Parse(sourceContentURL)
if err != nil {
copyURLsCh <- copyURLs{Error: errInvalidSource(sourceContentName).Trace()}
continue
}
sourceContentParse := client.NewURL(sourceContentURL)
// Construct target path from recursive path of source without its prefix dir.
newTargetURLParse := *targetURLParse
+3 -36
View File
@@ -19,7 +19,6 @@ package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -74,20 +73,6 @@ func (d DiffMessage) String() string {
return string(diffJSONBytes)
}
// urlJoinPath Join a path to existing URL
func urlJoinPath(url1, url2 string) (string, *probe.Error) {
u1, e := client.Parse(url1)
if e != nil {
return "", probe.NewError(e)
}
u2, e := client.Parse(url2)
if e != nil {
return "", probe.NewError(e)
}
u1.Path = filepath.Join(u1.Path, u2.Path)
return u1.String(), nil
}
func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan DiffMessage) {
defer close(ch)
firstClnt, firstContent, err := url2Stat(firstURL)
@@ -107,13 +92,7 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan DiffMes
if firstContent.Type.IsRegular() {
switch {
case secondContent.Type.IsDir():
newSecondURL, err := urlJoinPath(secondURL, firstURL)
if err != nil {
ch <- DiffMessage{
Error: err.Trace(secondURL, firstURL),
}
return
}
newSecondURL := urlJoinPath(secondURL, firstURL)
doDiffObjects(firstURL, newSecondURL, ch)
case !secondContent.Type.IsRegular():
ch <- DiffMessage{
@@ -194,20 +173,8 @@ func dodiff(firstClnt, secondClnt client.Client, ch chan DiffMessage) {
}
return
}
newFirstURL, err := urlJoinPath(firstClnt.URL().String(), contentCh.Content.Name)
if err != nil {
ch <- DiffMessage{
Error: err.Trace(firstClnt.URL().String()),
}
return
}
newSecondURL, err := urlJoinPath(secondClnt.URL().String(), contentCh.Content.Name)
if err != nil {
ch <- DiffMessage{
Error: err.Trace(secondClnt.URL().String()),
}
return
}
newFirstURL := urlJoinPath(firstClnt.URL().String(), contentCh.Content.Name)
newSecondURL := urlJoinPath(secondClnt.URL().String(), contentCh.Content.Name)
_, newFirstContent, errFirst := url2Stat(newFirstURL)
_, newSecondContent, errSecond := url2Stat(newSecondURL)
switch {
+1 -4
View File
@@ -35,10 +35,7 @@ func getHostConfig(URL string) (hostConfig, *probe.Error) {
return hostConfig{}, err.Trace()
}
{
url, err := client.Parse(URL)
if err != nil {
return hostConfig{}, probe.NewError(err)
}
url := client.NewURL(URL)
// No host matching or keys needed for filesystem requests
if url.Type == client.Filesystem {
hostCfg := hostConfig{
+1 -3
View File
@@ -86,9 +86,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Recursive option is not supported for target ‘%s’ argument.", tgtURL))
}
url, e := client.Parse(tgtURL)
fatalIf(probe.NewError(e), "Unable to parse target ‘"+tgtURL+"’ argument.")
url := client.NewURL(tgtURL)
if url.Host != "" {
if url.Path == string(url.Separator) {
fatalIf(errInvalidArgument().Trace(), fmt.Sprintf("Target ‘%s’ does not contain bucket name.", tgtURL))
+5 -10
View File
@@ -29,22 +29,19 @@ type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestURLParse(c *C) {
u, err := Parse("http://s3.example.com")
c.Assert(err, IsNil)
u := NewURL("http://s3.example.com")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/")
c.Assert(u.SchemeSeparator, Equals, "://")
u, err = Parse("http://s3.example.com/path/new")
c.Assert(err, IsNil)
u = NewURL("http://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "http")
c.Assert(u.Host, Equals, "s3.example.com")
c.Assert(u.Path, Equals, "/path/new")
c.Assert(u.SchemeSeparator, Equals, "://")
u, err = Parse(":::://s3.example.com/path/new")
c.Assert(err, IsNil)
u = NewURL(":::://s3.example.com/path/new")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, ":::://s3.example.com/path/new")
@@ -52,15 +49,13 @@ func (s *MySuite) TestURLParse(c *C) {
}
func (s *MySuite) TestPathParse(c *C) {
u, err := Parse("path/test")
c.Assert(err, IsNil)
u := NewURL("path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "path/test")
c.Assert(u.SchemeSeparator, Equals, "")
u, err = Parse("/path/test")
c.Assert(err, IsNil)
u = NewURL("/path/test")
c.Assert(u.Scheme, Equals, "")
c.Assert(u.Host, Equals, "")
c.Assert(u.Path, Equals, "/path/test")
+1 -2
View File
@@ -43,8 +43,7 @@ func New(path string) (client.Client, *probe.Error) {
// URL get url
func (f *fsClient) URL() *client.URL {
url, _ := client.Parse(f.path)
return url
return client.NewURL(f.path)
}
/// Object operations
+1 -4
View File
@@ -57,10 +57,7 @@ type s3Client struct {
// New returns an initialized s3Client structure. if debug use a internal trace transport
func New(config *Config) (client.Client, *probe.Error) {
u, err := client.Parse(config.HostURL)
if err != nil {
return nil, probe.NewError(err)
}
u := client.NewURL(config.HostURL)
var transport http.RoundTripper
switch {
case config.Debug == true:
+11 -11
View File
@@ -63,10 +63,10 @@ func getScheme(rawurl string) (scheme, path string) {
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
i := strings.Index(s, delimiter)
if i < 0 {
// if delimiter not found return as is
// if delimiter not found return as is.
return s, ""
}
// if delimiter should be removed, remove it
// if delimiter should be removed, remove it.
if cutdelimiter {
return s[0:i], s[i+len(delimiter):]
}
@@ -74,18 +74,18 @@ func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string
return s[0:i], s[i:]
}
// getHost - extract host from authority string, we do not support ftp style username@ yet
// getHost - extract host from authority string, we do not support ftp style username@ yet.
func getHost(authority string) (host string) {
i := strings.LastIndex(authority, "@")
if i >= 0 {
// TODO support, username@password style userinfo, useful for ftp support
// TODO support, username@password style userinfo, useful for ftp support.
return
}
return authority
}
// Parse url
func Parse(urlStr string) (*URL, error) {
// NewURL returns an abstracted URL for filesystems and object storage.
func NewURL(urlStr string) *URL {
scheme, rest := getScheme(urlStr)
rest, _ = splitSpecial(rest, "?", true)
if strings.HasPrefix(rest, "//") {
@@ -103,24 +103,24 @@ func Parse(urlStr string) (*URL, error) {
Path: rest,
SchemeSeparator: "://",
Separator: '/',
}, nil
}
}
}
return &URL{
Type: Filesystem,
Path: rest,
Separator: filepath.Separator,
}, nil
}
}
// String convert URL into its canonical form
// String convert URL into its canonical form.
func (u *URL) String() string {
var buf bytes.Buffer
// if fileystem no translation needed, return as is
// if fileystem no translation needed, return as is.
if u.Type == Filesystem {
return u.Path
}
// if Object convert from any non standard paths to a supported URL path style
// if Object convert from any non standard paths to a supported URL path style.
if u.Type == Object {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
+34 -9
View File
@@ -17,6 +17,7 @@
package main
import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
@@ -28,7 +29,21 @@ const (
recursiveSeparator = "..."
)
// isURLRecursive - find out if requested url is recursive
// url2Stat - Returns client, config and its stat Content from the URL.
func isValidURL(url string) bool {
// TODO: Requires a better logic.
return true
}
// urlJoinPath Join a path to existing URL.
func urlJoinPath(url1, url2 string) string {
u1 := client.NewURL(url1)
u2 := client.NewURL(url2)
u1.Path = filepath.Join(u1.Path, u2.Path)
return u1.String()
}
// isURLRecursive - find out if requested url is recursive.
func isURLRecursive(urlStr string) bool {
return strings.HasSuffix(urlStr, recursiveSeparator)
}
@@ -45,21 +60,18 @@ func stripRecursiveURL(urlStr string) string {
return urlStr
}
// getCanonicalizedURL - extracts URL string from a single cmd-line argument
func getCanonicalizedURL(arg string, aliases map[string]string) (urlStr string, err *probe.Error) {
// getCanonicalizedURL - extracts URL string from a single cmd-line argument.
func getCanonicalizedURL(arg string, aliases map[string]string) (string, *probe.Error) {
// Check and expand Alias
urlStr, err = aliasExpand(arg, aliases)
if err != nil {
return "", err.Trace(arg)
}
if _, err := client.Parse(urlStr); err != nil {
urlStr := aliasExpand(arg, aliases)
if !isValidURL(urlStr) {
// Not a valid URL. Return error
return "", errInvalidURL(urlStr).Trace()
}
return urlStr, nil
}
// getCanonicalizedURLs - extracts multiple URL strings from a single cmd-line argument
// getCanonicalizedURLs - extracts multiple URL strings from a single cmd-line argument.
func getCanonicalizedURLs(args []string, aliases map[string]string) (urls []string, err *probe.Error) {
for _, arg := range args {
u, err := getCanonicalizedURL(arg, aliases)
@@ -85,3 +97,16 @@ func args2URLs(args []string) ([]string, *probe.Error) {
}
return URLs, nil
}
// url2Stat returns stat info for URL.
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
client, err = url2Client(urlStr)
if err != nil {
return nil, nil, err.Trace(urlStr)
}
content, err = client.Stat()
if err != nil {
return nil, nil, err.Trace(urlStr)
}
return client, content, nil
}