Add api as option for mc config host add command. (#2381)

This commit is contained in:
poornas
2018-02-10 14:39:12 -08:00
committed by kannappanr
parent 3987f1405a
commit 65e22bee24
17 changed files with 374 additions and 94 deletions
+7 -5
View File
@@ -101,30 +101,32 @@ If you are planning to use `mc` only on POSIX compatible filesystems, you may sk
To add one or more Amazon S3 compatible hosts, please follow the instructions below. `mc` stores all its configuration information in ``~/.mc/config.json`` file.
```sh
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> <API-SIGNATURE>
mc config host add <ALIAS> <YOUR-S3-ENDPOINT> <YOUR-ACCESS-KEY> <YOUR-SECRET-KEY> --api <API-SIGNATURE> --lookup <BUCKET-LOOKUP-TYPE>
```
Alias is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
Alias is simply a short name to your cloud storage service. S3 end-point, access and secret keys are supplied by your cloud storage provider. API signature is an optional argument. By default, it is set to "S3v4".
Lookup is an optional argument. It is used to indicate whether dns or path style url requests are supported by the server. It accepts "dns", "path" or "auto" as valid values. By default, it is set to "auto" and SDK automatically determines the type of url lookup to use.
### Example - Minio Cloud Storage
Minio server displays URL, access and secret keys.
```sh
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
mc config host add minio http://192.168.1.51 BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
### Example - Amazon S3 Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [AWS Credentials Guide](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html).
```sh
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v4
mc config host add s3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
### Example - Google Cloud Storage
Get your AccessKeyID and SecretAccessKey by following [Google Credentials Guide](https://cloud.google.com/storage/docs/migrating?hl=en#keys)
```sh
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
mc config host add gcs https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
```
NOTE: Google Cloud Storage only supports Legacy Signature Version 2, so you have to pick - S3v2
+20 -5
View File
@@ -88,7 +88,7 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
// Save if target supports virtual host style.
hostName := targetURL.Host
s3Clnt.virtualStyle = isVirtualHostStyle(hostName)
s3Clnt.virtualStyle = isVirtualHostStyle(hostName, config.Lookup)
isS3AcceleratedEndpoint := isAmazonAccelerated(hostName)
if s3Clnt.virtualStyle {
@@ -121,7 +121,14 @@ func newFactory() func(config *Config) (Client, *probe.Error) {
}
// Not found. Instantiate a new minio
var e error
api, e = minio.NewWithCredentials(hostName, creds, useTLS, "")
options := minio.Options{
Creds: creds,
Secure: useTLS,
Region: "",
BucketLookup: config.Lookup,
}
api, e = minio.NewWithOptions(hostName, &options)
if e != nil {
return nil, probe.NewError(e)
}
@@ -989,9 +996,17 @@ func isGoogle(host string) bool {
}
// Figure out if the URL is of 'virtual host' style.
// Currently only supported hosts with virtual style
// are Amazon S3 and Google Cloud Storage.
func isVirtualHostStyle(host string) bool {
// Use lookup from config to see if dns/path style look
// up should be used. If it is set to "auto", use virtual
// style for supported hosts such as Amazon S3 and Google
// Cloud Storage. Otherwise, default to path style
func isVirtualHostStyle(host string, lookup minio.BucketLookupType) bool {
if lookup == minio.BucketLookupDNS {
return true
}
if lookup == minio.BucketLookupPath {
return false
}
return isAmazon(host) && !isAmazonChina(host) || isGoogle(host) || isAmazonAccelerated(host)
}
+2
View File
@@ -23,6 +23,7 @@ import (
"time"
"github.com/minio/mc/pkg/probe"
minio "github.com/minio/minio-go"
)
// DirOpt - list directory option.
@@ -98,4 +99,5 @@ type Config struct {
AppComments []string
Debug bool
Insecure bool
Lookup minio.BucketLookupType
}
+51 -26
View File
@@ -23,19 +23,30 @@ import (
"github.com/minio/mc/pkg/probe"
)
var hostAddFlags = []cli.Flag{
cli.StringFlag{
Name: "lookup",
Value: "auto",
Usage: "bucket lookup supported by the server. Valid options are `[dns,path,auto]`",
},
cli.StringFlag{
Name: "api",
Usage: "API signature. Valid options are `[S3v4, S3v2]`",
},
}
var configHostAddCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "Add a new host to configuration file.",
Action: mainConfigHostAdd,
Before: setGlobalsFromContext,
Flags: globalFlags,
Flags: append(hostAddFlags, globalFlags...),
HideHelpCommand: true,
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} ALIAS URL ACCESS-KEY SECRET-KEY [API]
{{.HelpName}} ALIAS URL ACCESS-KEY SECRET-KEY
FLAGS:
{{range .VisibleFlags}}{{.}}
@@ -57,9 +68,15 @@ EXAMPLES:
providing the signature type.
$ set +o history
$ {{.HelpName}} mys3-iam https://s3.amazonaws.com \
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 s3v4
BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 --api "s3v4"
$ set -o history
4. Add S3 API compatible storage service under "myminio" alias, to use dns style bucket lookup. For security reasons turn off bash history momentarily.
$ set +o history
$ {{.HelpName}} myminio http://localhost:9000 \
minio minio123 --api "s3v4" --lookup "dns"
$ set -o history
`,
}
@@ -76,8 +93,8 @@ func checkConfigHostAddSyntax(ctx *cli.Context) {
url := args.Get(1)
accessKey := args.Get(2)
secretKey := args.Get(3)
api := args.Get(4)
api := ctx.String("api")
bucketLookup := ctx.String("lookup")
if !isValidAlias(alias) {
fatalIf(errInvalidAlias(alias), "Invalid alias")
}
@@ -100,26 +117,32 @@ func checkConfigHostAddSyntax(ctx *cli.Context) {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized API signature. Valid options are `[S3v4, S3v2]`.")
}
if !isValidLookup(bucketLookup) {
fatalIf(errInvalidArgument().Trace(bucketLookup),
"Unrecognized bucket lookup. Valid options are `[dns,auto, path]`.")
}
}
// addHost - add a host config.
func addHost(alias string, hostCfgV8 hostConfigV8) {
mcCfgV8, err := loadMcConfig()
func addHost(alias string, hostCfgV9 hostConfigV9) {
mcCfgV9, err := loadMcConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config `"+mustGetMcConfigPath()+"`.")
// Add new host.
mcCfgV8.Hosts[alias] = hostCfgV8
mcCfgV9.Hosts[alias] = hostCfgV9
err = saveMcConfig(mcCfgV8)
err = saveMcConfig(mcCfgV9)
fatalIf(err.Trace(alias), "Unable to update hosts in config version `"+mustGetMcConfigPath()+"`.")
printMsg(hostMessage{
op: "add",
Alias: alias,
URL: hostCfgV8.URL,
AccessKey: hostCfgV8.AccessKey,
SecretKey: hostCfgV8.SecretKey,
API: hostCfgV8.API,
URL: hostCfgV9.URL,
AccessKey: hostCfgV9.AccessKey,
SecretKey: hostCfgV9.SecretKey,
API: hostCfgV9.API,
Lookup: hostCfgV9.Lookup,
})
}
@@ -168,18 +191,13 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) {
// buildS3Config constructs an S3 Config and does
// signature auto-probe when needed.
func buildS3Config(args cli.Args) (*Config, *probe.Error) {
var (
url = args.Get(0)
accessKey = args.Get(1)
secretKey = args.Get(2)
api = args.Get(3)
)
func buildS3Config(url, accessKey, secretKey, api, lookup string) (*Config, *probe.Error) {
s3Config := newS3Config(url, &hostConfigV8{
s3Config := newS3Config(url, &hostConfigV9{
AccessKey: accessKey,
SecretKey: secretKey,
URL: url,
Lookup: lookup,
})
// If api is provided we do not auto probe signature, this is
@@ -188,15 +206,13 @@ func buildS3Config(args cli.Args) (*Config, *probe.Error) {
s3Config.Signature = api
return s3Config, nil
}
// Probe S3 signature version
api, err := probeS3Signature(accessKey, secretKey, url)
if err != nil {
return nil, err.Trace(args...)
return nil, err.Trace(url, accessKey, secretKey, api, lookup)
}
s3Config.Signature = api
// Success.
return s3Config, nil
}
@@ -205,15 +221,24 @@ func mainConfigHostAdd(ctx *cli.Context) error {
checkConfigHostAddSyntax(ctx)
console.SetColor("HostMessage", color.New(color.FgGreen))
var (
args = ctx.Args()
url = args.Get(1)
accessKey = args.Get(2)
secretKey = args.Get(3)
api = ctx.String("api")
lookup = ctx.String("lookup")
)
s3Config, err := buildS3Config(ctx.Args().Tail())
s3Config, err := buildS3Config(url, accessKey, secretKey, api, lookup)
fatalIf(err.Trace(ctx.Args()...), "Unable to initialize new config from the provided credentials")
addHost(ctx.Args().Get(0), hostConfigV8{
addHost(ctx.Args().Get(0), hostConfigV9{
URL: s3Config.HostURL,
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,
API: s3Config.Signature,
Lookup: lookup,
}) // Add a host with specified credentials.
return nil
}
+3
View File
@@ -78,6 +78,7 @@ func mainConfigHostList(ctx *cli.Context) error {
console.SetColor("AccessKey", color.New(color.FgBlue))
console.SetColor("SecretKey", color.New(color.FgBlue))
console.SetColor("API", color.New(color.FgYellow))
console.SetColor("Lookup", color.New(color.FgCyan))
args := ctx.Args()
listHosts(args.Get(0)) // List all configured hosts.
@@ -129,6 +130,7 @@ func listHosts(alias string) {
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
return
}
@@ -145,6 +147,7 @@ func listHosts(alias string) {
AccessKey: v.AccessKey,
SecretKey: v.SecretKey,
API: v.API,
Lookup: v.Lookup,
})
}
+5 -1
View File
@@ -55,6 +55,7 @@ type hostMessage struct {
AccessKey string `json:"accessKey,omitempty"`
SecretKey string `json:"secretKey,omitempty"`
API string `json:"api,omitempty"`
Lookup string `json:"lookup,omitempty"`
}
// Print the config information of one alias, when prettyPrint flag
@@ -65,12 +66,14 @@ func (h hostMessage) String() string {
case "list":
urlFieldMaxLen, apiFieldMaxLen := -1, -1
accessFieldMaxLen, secretFieldMaxLen := -1, -1
lookupFieldMaxLen := -1
// Set cols width if prettyPrint flag is enabled
if h.prettyPrint {
urlFieldMaxLen = 30
accessFieldMaxLen = 20
secretFieldMaxLen = 40
apiFieldMaxLen = 5
lookupFieldMaxLen = 5
}
// Create a new pretty table with cols configuration
@@ -80,8 +83,9 @@ func (h hostMessage) String() string {
Field{"AccessKey", accessFieldMaxLen},
Field{"SecretKey", secretFieldMaxLen},
Field{"API", apiFieldMaxLen},
Field{"Lookup", lookupFieldMaxLen},
)
return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API)
return t.buildRow(h.Alias, h.URL, h.AccessKey, h.SecretKey, h.API, h.Lookup)
case "remove":
return console.Colorize("HostMessage", "Removed `"+h.Alias+"` successfully.")
case "add":
+41
View File
@@ -43,6 +43,8 @@ func migrateConfig() {
migrateConfigV6ToV7()
// Migrate config V7 to V8
migrateConfigV7ToV8()
// Migrate config V8 to V9
migrateConfigV8ToV9()
}
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
@@ -436,3 +438,42 @@ func migrateConfigV7ToV8() {
console.Infof("Successfully migrated %s from version `7` to version `8`.\n", mustGetMcConfigPath())
}
// Migrate config version `8` to `9'. Add optional field virtual
func migrateConfigV8ToV9() {
if !isMcConfigExists() {
return
}
mcCfgV8, e := quick.Load(mustGetMcConfigPath(), newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
if mcCfgV8.Version() != "8" {
return
}
cfgV9 := newConfigV9()
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
hostCfgV9 := hostConfigV9{}
hostCfgV9.URL = hostCfgV8.URL
hostCfgV9.AccessKey = hostCfgV8.AccessKey
hostCfgV9.SecretKey = hostCfgV8.SecretKey
hostCfgV9.API = hostCfgV8.API
hostCfgV9.Lookup = "auto"
cfgV9.Hosts[host] = hostCfgV9
}
// Load default settings.
cfgV9.loadDefaults()
mcNewCfgV9, e := quick.New(cfgV9)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
e = mcNewCfgV9.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `9`.")
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
}
+113
View File
@@ -16,6 +16,11 @@
package cmd
import (
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
/////////////////// Config V1 ///////////////////
type hostConfigV1 struct {
AccessKeyID string
@@ -241,4 +246,112 @@ func (c *configV7) setHost(alias string, cfg hostConfigV7) {
}
/////////////////// Config V8 ///////////////////
// configV8 config version.
// hostConfig configuration of a host.
type hostConfigV8 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
}
type configV8 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV8 `json:"hosts"`
}
// newConfigV8 - new config version.
func newConfigV8() *configV8 {
cfg := new(configV8)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV8)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV8) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV8{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV8{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV8{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV8{
URL: "https://play.minio.io:9000",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
})
}
// loadConfigV8 - loads a new config.
func loadConfigV8() (*configV8, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
// Initialize a new config loader.
qc, e := quick.New(newConfigV8())
if e != nil {
return nil, probe.NewError(e)
}
// Load config at configPath, fails if config is not
// accessible, malformed or version missing.
if e = qc.Load(mustGetMcConfigPath()); e != nil {
return nil, probe.NewError(e)
}
cfgV8 := qc.Data().(*configV8)
// Success.
return cfgV8, nil
}
// saveConfigV8 - saves an updated config.
func saveConfigV8(cfgV8 *configV8) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, e := quick.New(cfgV8)
if e != nil {
return probe.NewError(e)
}
e = qs.Save(mustGetMcConfigPath())
if e != nil {
return probe.NewError(e).Trace(mustGetMcConfigPath())
}
return nil
}
/////////////////// Config V9 ///////////////////
// RESERVED FOR FUTURE
+12
View File
@@ -62,3 +62,15 @@ func isValidAPI(api string) (ok bool) {
}
return ok
}
// isValidLookup - validates if bucket lookup is of valid type
func isValidLookup(lookup string) (ok bool) {
l := strings.TrimSpace(lookup)
l = strings.ToLower(lookup)
for _, v := range []string{"dns", "path", "auto"} {
if l == v {
return true
}
}
return false
}
+30 -25
View File
@@ -30,83 +30,88 @@ const (
var (
// set once during first load.
cacheCfgV8 *configV8
cacheCfgV9 *configV9
// All access to mc config file should be synchronized.
cfgMutex = &sync.RWMutex{}
)
// hostConfig configuration of a host.
type hostConfigV8 struct {
type hostConfigV9 struct {
URL string `json:"url"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
API string `json:"api"`
Lookup string `json:"lookup"`
}
// configV8 config version.
type configV8 struct {
type configV9 struct {
Version string `json:"version"`
Hosts map[string]hostConfigV8 `json:"hosts"`
Hosts map[string]hostConfigV9 `json:"hosts"`
}
// newConfigV8 - new config version.
func newConfigV8() *configV8 {
cfg := new(configV8)
// newConfigV9 - new config version.
func newConfigV9() *configV9 {
cfg := new(configV9)
cfg.Version = globalMCConfigVersion
cfg.Hosts = make(map[string]hostConfigV8)
cfg.Hosts = make(map[string]hostConfigV9)
return cfg
}
// SetHost sets host config if not empty.
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
func (c *configV9) setHost(alias string, cfg hostConfigV9) {
if _, ok := c.Hosts[alias]; !ok {
c.Hosts[alias] = cfg
}
}
// load default values for missing entries.
func (c *configV8) loadDefaults() {
func (c *configV9) loadDefaults() {
// Minio server running locally.
c.setHost("local", hostConfigV8{
c.setHost("local", hostConfigV9{
URL: "http://localhost:9000",
AccessKey: "",
SecretKey: "",
API: "S3v4",
Lookup: "auto",
})
// Amazon S3 cloud storage service.
c.setHost("s3", hostConfigV8{
c.setHost("s3", hostConfigV9{
URL: "https://s3.amazonaws.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v4",
Lookup: "dns",
})
// Google cloud storage service.
c.setHost("gcs", hostConfigV8{
c.setHost("gcs", hostConfigV9{
URL: "https://storage.googleapis.com",
AccessKey: defaultAccessKey,
SecretKey: defaultSecretKey,
API: "S3v2",
Lookup: "dns",
})
// Minio anonymous server for demo.
c.setHost("play", hostConfigV8{
c.setHost("play", hostConfigV9{
URL: "https://play.minio.io:9000",
AccessKey: "Q3AM3UQ867SPQQA43P2F",
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
API: "S3v4",
Lookup: "auto",
})
}
// loadConfigV8 - loads a new config.
func loadConfigV8() (*configV8, *probe.Error) {
// loadConfigV9 - loads a new config.
func loadConfigV9() (*configV9, *probe.Error) {
cfgMutex.RLock()
defer cfgMutex.RUnlock()
// If already cached, return the cached value.
if cacheCfgV8 != nil {
return cacheCfgV8, nil
if cacheCfgV9 != nil {
return cacheCfgV9, nil
}
if !isMcConfigExists() {
@@ -114,7 +119,7 @@ func loadConfigV8() (*configV8, *probe.Error) {
}
// Initialize a new config loader.
qc, e := quick.New(newConfigV8())
qc, e := quick.New(newConfigV9())
if e != nil {
return nil, probe.NewError(e)
}
@@ -125,27 +130,27 @@ func loadConfigV8() (*configV8, *probe.Error) {
return nil, probe.NewError(e)
}
cfgV8 := qc.Data().(*configV8)
cfgV9 := qc.Data().(*configV9)
// Cache config.
cacheCfgV8 = cfgV8
cacheCfgV9 = cfgV9
// Success.
return cfgV8, nil
return cfgV9, nil
}
// saveConfigV8 - saves an updated config.
func saveConfigV8(cfgV8 *configV8) *probe.Error {
func saveConfigV9(cfgV9 *configV9) *probe.Error {
cfgMutex.Lock()
defer cfgMutex.Unlock()
qs, e := quick.New(cfgV8)
qs, e := quick.New(cfgV9)
if e != nil {
return probe.NewError(e)
}
// update the cache.
cacheCfgV8 = cfgV8
cacheCfgV9 = cfgV9
e = qs.Save(mustGetMcConfigPath())
if e != nil {
+3 -3
View File
@@ -22,7 +22,7 @@ import (
)
// Check if version of the config is valid
func validateConfigVersion(config *configV8) (bool, string) {
func validateConfigVersion(config *configV9) (bool, string) {
if config.Version != globalMCConfigVersion {
return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n",
config.Version, globalMCConfigVersion)
@@ -31,7 +31,7 @@ func validateConfigVersion(config *configV8) (bool, string) {
}
// Verifies the config file of the Minio Client
func validateConfigFile(config *configV8) (bool, []string) {
func validateConfigFile(config *configV9) (bool, []string) {
ok, err := validateConfigVersion(config)
var validationSuccessful = true
var errors []string
@@ -50,7 +50,7 @@ func validateConfigFile(config *configV8) (bool, []string) {
return validationSuccessful, errors
}
func validateConfigHost(host hostConfigV8) (bool, []string) {
func validateConfigHost(host hostConfigV9) (bool, []string) {
var validationSuccessful = true
var hostErrors []string
if !isValidAPI(strings.ToLower(host.API)) {
+15 -15
View File
@@ -94,29 +94,29 @@ func mustGetMcConfigPath() string {
return path
}
// newMcConfig - initializes a new version '6' config.
func newMcConfig() *configV8 {
cfg := newConfigV8()
// newMcConfig - initializes a new version '9' config.
func newMcConfig() *configV9 {
cfg := newConfigV9()
cfg.loadDefaults()
return cfg
}
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
func loadMcConfigFactory() func() (*configV8, *probe.Error) {
func loadMcConfigFactory() func() (*configV9, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV8()
cfgCache, err := loadConfigV9()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV8, *probe.Error) {
return func() (*configV9, *probe.Error) {
return cfgCache, err
}
}
// loadMcConfig - returns configuration, initialized later.
var loadMcConfig func() (*configV8, *probe.Error)
var loadMcConfig func() (*configV9, *probe.Error)
// saveMcConfig - saves configuration file and returns error if any.
func saveMcConfig(config *configV8) *probe.Error {
func saveMcConfig(config *configV9) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
@@ -127,7 +127,7 @@ func saveMcConfig(config *configV8) *probe.Error {
}
// Save the config.
if err := saveConfigV8(config); err != nil {
if err := saveConfigV9(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
@@ -154,7 +154,7 @@ func isValidAlias(alias string) bool {
}
// getHostConfig retrieves host specific configuration such as access keys, signature type.
func getHostConfig(alias string) (*hostConfigV8, *probe.Error) {
func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
@@ -171,7 +171,7 @@ func getHostConfig(alias string) (*hostConfigV8, *probe.Error) {
}
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
func mustGetHostConfig(alias string) *hostConfigV8 {
func mustGetHostConfig(alias string) *hostConfigV9 {
hostCfg, _ := getHostConfig(alias)
return hostCfg
}
@@ -207,13 +207,13 @@ func parseEnvURL(envURL string) (*url.URL, string, string, *probe.Error) {
const mcEnvHostsPrefix = "MC_HOSTS_"
func expandAliasFromEnv(envURL string) (*hostConfigV8, *probe.Error) {
func expandAliasFromEnv(envURL string) (*hostConfigV9, *probe.Error) {
u, accessKey, secretKey, err := parseEnvURL(envURL)
if err != nil {
return nil, err.Trace(envURL)
}
return &hostConfigV8{
return &hostConfigV9{
URL: u.String(),
API: "S3v4",
AccessKey: accessKey,
@@ -222,7 +222,7 @@ func expandAliasFromEnv(envURL string) (*hostConfigV8, *probe.Error) {
}
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8, err *probe.Error) {
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
@@ -242,7 +242,7 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
}
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8) {
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
}
+1 -1
View File
@@ -30,7 +30,7 @@ const (
)
const (
globalMCConfigVersion = "8"
globalMCConfigVersion = "9"
globalMCConfigDir = ".mc/"
globalMCConfigWindowsDir = "mc\\"
+17 -2
View File
@@ -25,6 +25,8 @@ import (
"strings"
"time"
"github.com/minio/minio-go"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
@@ -96,7 +98,7 @@ func splitStr(path, sep string, n int) []string {
// newS3Config simply creates a new Config struct using the passed
// parameters.
func newS3Config(urlStr string, hostCfg *hostConfigV8) *Config {
func newS3Config(urlStr string, hostCfg *hostConfigV9) *Config {
// We have a valid alias and hostConfig. We populate the
// credentials from the match found in the config file.
s3Config := new(Config)
@@ -113,7 +115,7 @@ func newS3Config(urlStr string, hostCfg *hostConfigV8) *Config {
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
}
s3Config.Lookup = getLookupType(hostCfg.Lookup)
return s3Config
}
@@ -142,3 +144,16 @@ func isNewer(c *clientContent, newerRef int) bool {
objectAge := UTCNow().Sub(c.Time)
return objectAge > (time.Duration(newerRef) * Day)
}
// getLookupType returns the minio.BucketLookupType for lookup
// option entered on the command line
func getLookupType(l string) minio.BucketLookupType {
l = strings.ToLower(l)
switch l {
case "dns":
return minio.BucketLookupDNS
case "path":
return minio.BucketLookupPath
}
return minio.BucketLookupAuto
}
+51 -8
View File
@@ -81,6 +81,19 @@ type Client struct {
// Random seed.
random *rand.Rand
// lookup indicates type of url lookup supported by server. If not specified,
// default to Auto.
lookup BucketLookupType
}
// Options for New method
type Options struct {
Creds *credentials.Credentials
Secure bool
Region string
BucketLookup BucketLookupType
// Add future fields here
}
// Global constants.
@@ -98,11 +111,21 @@ const (
libraryUserAgent = libraryUserAgentPrefix + libraryName + "/" + libraryVersion
)
// BucketLookupType is type of url lookup supported by server.
type BucketLookupType int
// Different types of url lookup supported by the server.Initialized to BucketLookupAuto
const (
BucketLookupAuto BucketLookupType = iota
BucketLookupDNS
BucketLookupPath
)
// NewV2 - instantiate minio client with Amazon S3 signature version
// '2' compatibility.
func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV2(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
@@ -114,7 +137,7 @@ func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*
// '4' compatibility.
func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
@@ -125,7 +148,7 @@ func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*
// New - instantiate minio client, adds automatic verification of signature.
func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
@@ -144,7 +167,7 @@ func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, e
// for retrieving credentials from various credentials provider such as
// IAM, File, Env etc.
func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
return privateNew(endpoint, creds, secure, region)
return privateNew(endpoint, creds, secure, region, BucketLookupAuto)
}
// NewWithRegion - instantiate minio client, with region configured. Unlike New(),
@@ -152,7 +175,12 @@ func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure
// Use this function when if your application deals with single region.
func NewWithRegion(endpoint, accessKeyID, secretAccessKey string, secure bool, region string) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
return privateNew(endpoint, creds, secure, region)
return privateNew(endpoint, creds, secure, region, BucketLookupAuto)
}
// NewWithOptions - instantiate minio client with options
func NewWithOptions(endpoint string, opts *Options) (*Client, error) {
return privateNew(endpoint, opts.Creds, opts.Secure, opts.Region, opts.BucketLookup)
}
// lockedRandSource provides protected rand source, implements rand.Source interface.
@@ -239,7 +267,7 @@ func (c *Client) redirectHeaders(req *http.Request, via []*http.Request) error {
return nil
}
func privateNew(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
func privateNew(endpoint string, creds *credentials.Credentials, secure bool, region string, lookup BucketLookupType) (*Client, error) {
// construct endpoint.
endpointURL, err := getEndpointURL(endpoint, secure)
if err != nil {
@@ -276,6 +304,9 @@ func privateNew(endpoint string, creds *credentials.Credentials, secure bool, re
// Introduce a new locked random seed.
clnt.random = rand.New(&lockedRandSource{src: rand.NewSource(time.Now().UTC().UnixNano())})
// Sets bucket lookup style, whether server accepts DNS or Path lookup. Default is Auto - determined
// by the SDK. When Auto is specified, DNS lookup is used for Amazon/Google cloud endpoints and Path for all other endpoints.
clnt.lookup = lookup
// Return.
return clnt, nil
}
@@ -824,8 +855,7 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que
// endpoint URL.
if bucketName != "" {
// Save if target url will have buckets which suppport virtual host.
isVirtualHostStyle := s3utils.IsVirtualHostSupported(*c.endpointURL, bucketName)
isVirtualHostStyle := c.isVirtualHostStyleRequest(*c.endpointURL, bucketName)
// If endpoint supports virtual host style use that always.
// Currently only S3 and Google Cloud Storage would support
// virtual host style.
@@ -850,3 +880,16 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que
return url.Parse(urlStr)
}
// returns true if virtual hosted style requests are to be used.
func (c *Client) isVirtualHostStyleRequest(url url.URL, bucketName string) bool {
if c.lookup == BucketLookupDNS {
return true
}
if c.lookup == BucketLookupPath {
return false
}
// default to virtual only for Amazon/Google storage. In all other cases use
// path style requests
return s3utils.IsVirtualHostSupported(url, bucketName)
}
BIN
View File
Binary file not shown.
+3 -3
View File
@@ -56,10 +56,10 @@
"revisionTime": "2015-10-24T22:24:27-07:00"
},
{
"checksumSHA1": "FkKOyZJ3WlwRdtaTu3H0EcxsC9I=",
"checksumSHA1": "DfYGe4AQnepOlUIyHf+sDoWXoS0=",
"path": "github.com/minio/minio-go",
"revision": "d218e4cb1bfc13dcef0eb5c3e74507a35be0dd3a",
"revisionTime": "2018-01-13T00:13:38Z"
"revision": "ff08912b135852df44282ed371d222600c32f471",
"revisionTime": "2018-02-01T23:19:47Z"
},
{
"checksumSHA1": "hFBOVO4pLrljMXnrArhgP7DIVKY=",