Merge pull request #1459 from harshavardhana/add-csv

config/host: Add import command to import csv credentials file.
This commit is contained in:
Harshavardhana
2015-11-21 11:48:34 -08:00
8 changed files with 770 additions and 463 deletions
+84 -87
View File
@@ -25,7 +25,6 @@ import (
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
var (
@@ -106,6 +105,44 @@ func (a aliasMessage) JSON() string {
return string(jsonMessageBytes)
}
// checkConfigAliasAddSyntax validate 'config alias add' input arguments.
func checkConfigAliasAddSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for add alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
aliasedURL := ctx.Args().Tail().Get(1)
if aliasName == "" || aliasedURL == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
aliasedURL = strings.TrimSuffix(aliasedURL, "/")
if !strings.HasPrefix(aliasedURL, "http") {
fatalIf(errDummy().Trace(aliasedURL),
fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", aliasedURL))
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
// checkConfigAliasRemoveSyntax validate 'config alias remove' input argument.
func checkConfigAliasRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remove alias command.")
}
aliasName := ctx.Args().Tail().Get(0)
if strings.TrimSpace(aliasName) == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
if !isValidAliasName(aliasName) {
fatalIf(errDummy().Trace(aliasName),
fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", aliasName))
}
}
func checkConfigAliasSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
@@ -119,97 +156,15 @@ func checkConfigAliasSyntax(ctx *cli.Context) {
}
switch strings.TrimSpace(ctx.Args().Get(0)) {
case "add":
if len(ctx.Args().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for add alias command.")
}
checkConfigAliasAddSyntax(ctx)
case "remove":
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for remove alias command.")
}
checkConfigAliasRemoveSyntax(ctx)
case "list":
default:
cli.ShowCommandHelpAndExit(ctx, "alias", 1) // last argument is exit code
}
}
func listAliases() {
config, err := newConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
// convert interface{} back to its original struct
newConf := config.Data().(*configV6)
for k, v := range newConf.Aliases {
printMsg(aliasMessage{op: "list", Alias: k, URL: v})
}
}
// removeAlias - remove alias
func removeAlias(alias string) {
if strings.TrimSpace(alias) == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
config, err := newConfig()
fatalIf(err.Trace(), "Failed to initialize ‘quick’ configuration data structure.")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(alias), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
// convert interface{} back to its original struct
newConf := config.Data().(*configV6)
if _, ok := newConf.Aliases[alias]; !ok {
fatalIf(errDummy().Trace(alias), fmt.Sprintf("Alias ‘%s’ does not exist.", alias))
}
delete(newConf.Aliases, alias)
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(alias), "Unable to save alias ‘"+alias+"’.")
printMsg(aliasMessage{op: "remove", Alias: alias})
}
// addAlias - add new aliases
func addAlias(alias, url string) {
if alias == "" || url == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
config, err := newConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config path")
url = strings.TrimSuffix(url, "/")
if !strings.HasPrefix(url, "http") {
fatalIf(errDummy().Trace(url), fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", url))
}
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(alias), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
// convert interface{} back to its original struct
newConf := config.Data().(*configV6)
if oldURL, ok := newConf.Aliases[alias]; ok {
fatalIf(errDummy().Trace(alias), fmt.Sprintf("Alias ‘%s’ already exists for ‘%s’.", alias, oldURL))
}
newConf.Aliases[alias] = url
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(alias, url), "Unable to save alias ‘"+alias+"’.")
printMsg(aliasMessage{op: "add", Alias: alias, URL: url})
}
func mainConfigAlias(ctx *cli.Context) {
checkConfigAliasSyntax(ctx)
@@ -223,10 +178,52 @@ func mainConfigAlias(ctx *cli.Context) {
switch strings.TrimSpace(arg) {
case "add":
addAlias(tailArgs.Get(0), tailArgs.Get(1))
// add alias name.
aliasName := tailArgs.Get(0)
aliasedURL := tailArgs.Get(1)
addAlias(aliasName, aliasedURL)
case "remove":
removeAlias(tailArgs.Get(0))
// remove alias name.
aliasName := tailArgs.Get(0)
removeAlias(aliasName)
case "list":
// list all aliases.
listAliases()
}
}
// addAlias - adds an alias entry.
func addAlias(aliasName, aliasedURL string) {
conf, err := loadConfigV6()
fatalIf(err.Trace(), "Unable to load config version ‘6’.")
conf.Aliases[aliasName] = aliasedURL
err = saveConfigV6(conf)
fatalIf(err.Trace(aliasName, aliasedURL), "Unable to update aliases in config version ‘6’.")
printMsg(aliasMessage{op: "add", Alias: aliasName, URL: aliasedURL})
}
// removeAlias - remove a alias.
func removeAlias(aliasName string) {
conf, err := loadConfigV6()
fatalIf(err.Trace(), "Unable to load config version ‘6’.")
delete(conf.Aliases, aliasName)
err = saveConfigV6(conf)
fatalIf(err.Trace(aliasName), "Unable to save deleted alias in config version ‘6’.")
printMsg(aliasMessage{op: "remove", Alias: aliasName})
}
// listAliases - list aliases.
func listAliases() {
conf, err := loadConfigV6()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘6’")
for aliasName, aliasedURL := range conf.Aliases {
printMsg(aliasMessage{op: "list", Alias: aliasName, URL: aliasedURL})
}
}
+193 -136
View File
@@ -1,17 +1,31 @@
/*
* Minio Client (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
import (
"encoding/json"
"fmt"
"regexp"
"os"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
var (
@@ -43,19 +57,19 @@ FLAGS:
EXAMPLES:
1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history
$ set +o history
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ mc config {{.Name}} add https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
$ set -o history
2. Add host configuration for a URL, using signature V2. For security reasons turn off bash history
$ set +o history
$ mc config {{.Name}} add storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
$ mc config {{.Name}} add https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
$ set -o history
3. List all hosts.
$ mc config {{.Name}} list
4. Remove host config.
$ mc config {{.Name}} remove s3.amazonaws.com
$ mc config {{.Name}} remove https://s3.amazonaws.com
`,
}
@@ -100,6 +114,85 @@ func (a hostMessage) JSON() string {
return string(jsonMessageBytes)
}
// checkConfigHostImportSyntax - check config host import syntax.
func checkConfigHostImportSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 2 || len(ctx.Args().Tail()) > 3 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for import host command.")
}
newHostURL := tailArgs.Get(0)
credentialsFile := tailArgs.Get(1)
api := tailArgs.Get(2)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host ‘"+newHostURL+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(credentialsFile) == "" {
fatalIf(errDummy().Trace(), "Credentials file cannot be empty.")
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.")
}
}
// checkConfigHostAddSyntax - check config host add syntax.
func checkConfigHostAddSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for host add command.")
}
newHostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host URL: ‘"+newHostURL+"’ provided. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if len(accessKeyID) != 0 {
if !isValidAccessKey(accessKeyID) {
fatalIf(errInvalidArgument().Trace(accessKeyID), "Invalid access key id provided.")
}
}
if len(secretAccessKey) != 0 {
if !isValidSecretKey(secretAccessKey) {
fatalIf(errInvalidArgument().Trace(secretAccessKey), "Invalid secret access key provided.")
}
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api),
"Unrecognized api version. Valid options are ‘[ S3v4, S3v2 ]’.")
}
}
// checkConfigHostRemoveSyntax - check config host remove syntax.
func checkConfigHostRemoveSyntax(ctx *cli.Context) {
tailArgs := ctx.Args().Tail()
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...),
"Incorrect number of arguments for remove host command.")
}
if !isValidHostURL(tailArgs.Get(0)) {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"Invalid host ‘"+tailArgs.Get(0)+"’. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(tailArgs.Get(0)) == "https://dl.minio.io:9000" {
fatalIf(errDummy().Trace(tailArgs.Get(0)),
"‘"+tailArgs.Get(0)+"’ is reserved hostname and cannot be removed.")
}
}
func checkConfigHostSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
@@ -113,13 +206,11 @@ func checkConfigHostSyntax(ctx *cli.Context) {
}
switch strings.TrimSpace(ctx.Args().First()) {
case "add":
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for add host command.")
}
checkConfigHostAddSyntax(ctx)
case "import":
checkConfigHostImportSyntax(ctx)
case "remove":
if len(ctx.Args().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(ctx.Args().Tail()...), "Incorrect number of arguments for remove host command.")
}
checkConfigHostRemoveSyntax(ctx)
case "list":
default:
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
@@ -139,155 +230,121 @@ func mainConfigHost(ctx *cli.Context) {
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
// Switch case through commands.
switch strings.TrimSpace(arg) {
// Add a host with specified credentials.
case "add":
addHost(tailArgs.Get(0), tailArgs.Get(1), tailArgs.Get(2), tailArgs.Get(3))
hostURL := tailArgs.Get(0)
accessKeyID := tailArgs.Get(1)
secretAccessKey := tailArgs.Get(2)
api := tailArgs.Get(3)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
hostCfg := hostConfig{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
}
addHost(hostURL, hostCfg)
// Import credentials through a CSV file for a host.
case "import":
hostURL := tailArgs.Get(0)
credentials := tailArgs.Get(1)
api := tailArgs.Get(2)
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
creds := getCredentials(credentials)
var hostCfg hostConfig
hostCfg = hostConfig{
AccessKeyID: creds[0].AccessKeyID,
SecretAccessKey: creds[0].SecretAccessKey,
API: api,
}
addHost(hostURL, hostCfg)
// Remove a host.
case "remove":
removeHost(tailArgs.Get(0))
hostURL := tailArgs.Get(0)
removeHost(hostURL)
// List all configured hosts.
case "list":
listHosts()
}
}
func listHosts() {
conf := new(configV6)
conf.Version = globalMCConfigVersion
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
config, err := quick.New(conf)
fatalIf(err.Trace(), "Failed to initialize ‘quick’ configuration data structure.")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
// addHost - add a host config.
func addHost(hostURL string, hostCfg hostConfig) {
conf, err := loadConfigV6()
fatalIf(err.Trace(), "Unable to load config version ‘6’.")
// convert interface{} back to its original struct
newConf := config.Data().(*configV6)
for k, v := range newConf.Hosts {
printMsg(hostMessage{op: "list", Host: k, AccessKeyID: v.AccessKeyID, SecretAccessKey: v.SecretAccessKey, API: v.API})
}
// Add new host.
conf.Hosts[hostURL] = hostCfg
err = saveConfigV6(conf)
fatalIf(err.Trace(hostURL), "Unable to update hosts in config version ‘6’.")
printMsg(hostMessage{
op: "add",
Host: hostURL,
AccessKeyID: hostCfg.AccessKeyID,
SecretAccessKey: hostCfg.SecretAccessKey,
API: hostCfg.API,
})
}
// removeHost - removes a host.
func removeHost(hostURL string) {
if !isValidHostURL(hostURL) {
fatalIf(errDummy().Trace(hostURL), "Invalid host URL: ‘"+hostURL+"’ provided. Valid options are [http://example.test.io, https://bucket.s3.amazonaws.com].")
}
if strings.TrimSpace(hostURL) == "dl.minio.io:9000" {
fatalIf(errDummy().Trace(hostURL), "‘"+hostURL+"’ is reserved hostname and cannot be removed.")
}
config, err := newConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
conf, err := loadConfigV6()
fatalIf(err.Trace(), "Unable to load config version ‘6’.")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
// Remove host.
delete(conf.Hosts, hostURL)
// convert interface{} back to its original struct
newConf := config.Data().(*configV6)
if _, ok := newConf.Hosts[hostURL]; !ok {
fatalIf(errDummy().Trace(hostURL), fmt.Sprintf("Host url ‘%s’ does not exist.", hostURL))
}
delete(newConf.Hosts, hostURL)
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(hostURL), "Unable to save host url ‘"+hostURL+"’.")
err = saveConfigV6(conf)
fatalIf(err.Trace(hostURL), "Unable to save deleted hosts in config version ‘6’.")
printMsg(hostMessage{op: "remove", Host: hostURL})
}
// addHost - add new host url.
func addHost(newHostURL, accessKeyID, secretAccessKey, api string) {
if !isValidHostURL(newHostURL) {
fatalIf(errDummy().Trace(newHostURL),
"Invalid host URL: ‘"+newHostURL+"’ provided. Valid options are [example.test.io, bucket.s3.amazonaws.com].")
}
if len(accessKeyID) != 0 {
if !isValidAccessKey(accessKeyID) {
fatalIf(errInvalidArgument().Trace(accessKeyID), "Invalid access key id provided.")
}
}
if len(secretAccessKey) != 0 {
if !isValidSecretKey(secretAccessKey) {
fatalIf(errInvalidArgument().Trace(secretAccessKey), "Invalid secret access key provided.")
}
}
if strings.TrimSpace(api) == "" {
api = "S3v4"
}
if strings.TrimSpace(api) != "S3v2" && strings.TrimSpace(api) != "S3v4" {
fatalIf(errInvalidArgument().Trace(api), "Unrecognized version name provided, supported inputs are ‘S3v4’, ‘S3v2’.")
}
config, err := newConfig()
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
// listHosts - list all host URLs.
func listHosts() {
conf, err := loadConfigV6()
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config version ‘6’")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path.")
newConf := config.Data().(*configV6)
for savedHost := range newConf.Hosts {
if savedHost == newHostURL {
newConf.Hosts[savedHost] = hostConfig{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
}
} else {
newConf.Hosts[newHostURL] = hostConfig{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
}
}
for k, v := range conf.Hosts {
printMsg(hostMessage{
op: "list",
Host: k,
AccessKeyID: v.AccessKeyID,
SecretAccessKey: v.SecretAccessKey,
API: v.API,
})
}
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(newHostURL), "Unable to save new host url ‘"+newHostURL+"’.")
printMsg(hostMessage{
op: "add",
Host: newHostURL,
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
API: api,
})
}
// isValidSecretKey - validate secret key
func isValidSecretKey(secretAccessKey string) bool {
if secretAccessKey == "" {
return true
}
regex := regexp.MustCompile("^.{40}$")
return regex.MatchString(secretAccessKey)
// credential - struct to read from a CSV file.
type credential struct {
Name string
AccessKeyID string
SecretAccessKey string
}
// isValidAccessKey - validate access key
func isValidAccessKey(accessKeyID string) bool {
if accessKeyID == "" {
return true
// getCredentials - get credentials file.
func getCredentials(credentialsFile string) []credential {
reader, err := os.Open(credentialsFile)
if err != nil {
fatalIf(probe.NewError(err), "Unable to open credentials file "+credentialsFile+".")
}
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
return regex.MatchString(accessKeyID)
}
// isValidHostURL - validate input host url.
func isValidHostURL(hostURL string) bool {
if strings.TrimSpace(hostURL) == "" {
return false
creds := []credential{}
// skip the first line of the csv file, usually csv header.
skipLine := 1
if err := newCSVReader(reader).Unmarshal(&creds, skipLine); err != nil {
fatalIf(err.Trace(credentialsFile), "Unable to read credentials file "+credentialsFile)
}
url := client.NewURL(hostURL)
if url.Scheme != "https" && url.Scheme != "http" {
return false
if len(creds) == 0 {
fatalIf(errDummy().Trace(credentialsFile),
"Invalid credentials file provided, need to have alteast single field.")
}
if url.Path != "" && url.Path != "/" {
return false
}
return true
return creds
}
+144
View File
@@ -19,10 +19,154 @@ package main
import (
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/quick"
)
func migrateConfig() {
// Migrate config V1 to V101
migrateConfigV1ToV101()
// Migrate config V101 to V2
migrateConfigV101ToV2()
// Migrate config V2 to V3
migrateConfigV2ToV3()
// Migrate config V3 to V4
migrateConfigV3ToV4()
// Migrate config V4 to V5
migrateConfigV4ToV5()
// Migrate config V5 to V6
migrateConfigV5ToV6()
}
func fixConfig() {
// Fix config V3
fixConfigV3()
// Fix config V6
fixConfigV6()
// Fix config V6 for hosts
fixConfigV6ForHosts()
}
func fixConfigV6ForHosts() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
url := new(client.URL)
for host, hostCfg := range config.Data().(*configV6).Hosts {
// Already fixed - move on.
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "localhost:9000" || host == "127.0.0.1:9000" {
console.Infoln("Found hosts, replacing " + host + " with http://" + host)
url.Host = host
url.Scheme = "http"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
func fixConfigV6() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*storage.googleapis.com") {
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
newConfig.Hosts["storage.googleapis.com"] = hostCfg
continue
}
if strings.Contains(host, "localhost:*") {
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
newConfig.Hosts["localhost:9000"] = hostCfg
continue
}
if strings.Contains(host, "127.0.0.1:*") {
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
continue
}
newConfig.Hosts[host] = hostCfg
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
type configV5 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
+41
View File
@@ -0,0 +1,41 @@
package main
import (
"regexp"
"strings"
"github.com/minio/mc/pkg/client"
)
// isValidSecretKey - validate secret key
func isValidSecretKey(secretAccessKey string) bool {
if secretAccessKey == "" {
return true
}
regex := regexp.MustCompile("^.{40}$")
return regex.MatchString(secretAccessKey)
}
// isValidAccessKey - validate access key
func isValidAccessKey(accessKeyID string) bool {
if accessKeyID == "" {
return true
}
regex := regexp.MustCompile("^[A-Z0-9\\-\\.\\_\\~]{20}$")
return regex.MatchString(accessKeyID)
}
// isValidHostURL - validate input host url.
func isValidHostURL(hostURL string) bool {
if strings.TrimSpace(hostURL) == "" {
return false
}
url := client.NewURL(hostURL)
if url.Scheme != "https" && url.Scheme != "http" {
return false
}
if url.Path != "" && url.Path != "/" {
return false
}
return true
}
+134
View File
@@ -0,0 +1,134 @@
/*
* Minio Client (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
import (
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
// configV6 config version '6'.
type configV6 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
// newConfigV6 - new config version '6'.
func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = globalMCConfigVersion
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors.
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
localHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
s3HostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
googlHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
// Your example host config.
exampleHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
playHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
dlHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
conf.Hosts[globalExampleHostURL] = exampleHostConf
conf.Hosts["http://localhost:9000"] = localHostConfig
conf.Hosts["https://dl.minio.io:9000"] = dlHostConfig
conf.Hosts["https://s3.amazonaws.com"] = s3HostConf
conf.Hosts["https://play.minio.io:9000"] = playHostConfig
conf.Hosts["https://storage.googleapis.com"] = googlHostConf
aliases := make(map[string]string)
aliases["s3"] = "https://s3.amazonaws.com"
aliases["dl"] = "https://dl.minio.io:9000"
aliases["gcs"] = "https://storage.googleapis.com"
aliases["play"] = "https://play.minio.io:9000"
aliases["local"] = "http://localhost:9000"
conf.Aliases = aliases
return conf
}
// saveConfigV6 - saves an updated config.
func saveConfigV6(config *configV6) *probe.Error {
qs, err := quick.New(config)
if err != nil {
return err.Trace()
}
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
}
// loadConfigV6 - loads a new config.
func loadConfigV6() (*configV6, *probe.Error) {
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
configFile, err := getMcConfigPath()
if err != nil {
return nil, err.Trace()
}
// Cached in private global variable.
if v := cache.Get(); v != nil { // Use previously cached config.
return v.(quick.Config).Data().(*configV6), nil
}
conf := new(configV6)
conf.Version = globalMCConfigVersion
qconf, err := quick.New(conf)
if err != nil {
return nil, err.Trace()
}
err = qconf.Load(configFile)
if err != nil {
return nil, err.Trace()
}
cache.Put(qconf)
return qconf.Data().(*configV6), nil
}
+3 -239
View File
@@ -20,21 +20,12 @@ import (
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio-xl/pkg/quick"
)
type configV6 struct {
Version string `json:"version"`
Aliases map[string]string `json:"alias"`
Hosts map[string]hostConfig `json:"hosts"`
}
// cached variables should *NEVER* be accessed directly from outside this file.
var cache sync.Pool
@@ -103,33 +94,11 @@ func mustGetMcConfigPath() string {
// getMcConfig - reads configuration file and returns config
func getMcConfig() (*configV6, *probe.Error) {
if !isMcConfigExists() {
return nil, errInvalidArgument().Trace()
}
configFile, err := getMcConfigPath()
conf, err := loadConfigV6()
if err != nil {
return nil, err.Trace()
}
// Cached in private global variable.
if v := cache.Get(); v != nil { // Use previously cached config.
return v.(quick.Config).Data().(*configV6), nil
}
conf := new(configV6)
conf.Version = globalMCConfigVersion
qconf, err := quick.New(conf)
if err != nil {
return nil, err.Trace()
}
err = qconf.Load(configFile)
if err != nil {
return nil, err.Trace()
}
cache.Put(qconf)
return qconf.Data().(*configV6), nil
return conf, nil
}
// isMcConfigExists xreturns err if config doesn't exist
@@ -163,69 +132,7 @@ func writeConfig(config quick.Config) *probe.Error {
return nil
}
func newConfigV6() *configV6 {
conf := new(configV6)
conf.Version = globalMCConfigVersion
// make sure to allocate map's otherwise Golang
// exits silently without providing any errors
conf.Hosts = make(map[string]hostConfig)
conf.Aliases = make(map[string]string)
localHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
s3HostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
googlHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v2",
}
// Your example host config
exampleHostConf := hostConfig{
AccessKeyID: globalAccessKeyID,
SecretAccessKey: globalSecretAccessKey,
API: "S3v4",
}
playHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
dlHostConfig := hostConfig{
AccessKeyID: "",
SecretAccessKey: "",
API: "S3v4",
}
conf.Hosts[globalExampleHostURL] = exampleHostConf
conf.Hosts["http://localhost:9000"] = localHostConfig
conf.Hosts["https://dl.minio.io:9000"] = dlHostConfig
conf.Hosts["https://s3.amazonaws.com"] = s3HostConf
conf.Hosts["https://play.minio.io:9000"] = playHostConfig
conf.Hosts["https://storage.googleapis.com"] = googlHostConf
aliases := make(map[string]string)
aliases["s3"] = "https://s3.amazonaws.com"
aliases["dl"] = "https://dl.minio.io:9000"
aliases["gcs"] = "https://storage.googleapis.com"
aliases["play"] = "https://play.minio.io:9000"
aliases["local"] = "http://localhost:9000"
conf.Aliases = aliases
return conf
}
// newConfig - get new config interface
// newConfig - get new config interface.
func newConfig() (config quick.Config, err *probe.Error) {
config, err = quick.New(newConfigV6())
if err != nil {
@@ -233,146 +140,3 @@ func newConfig() (config quick.Config, err *probe.Error) {
}
return config, nil
}
func fixConfigV6ForHosts() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
url := new(client.URL)
for host, hostCfg := range config.Data().(*configV6).Hosts {
// Already fixed - move on.
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if host == "s3.amazonaws.com" || host == "storage.googleapis.com" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "localhost:9000" || host == "127.0.0.1:9000" {
console.Infoln("Found hosts, replacing " + host + " with http://" + host)
url.Host = host
url.Scheme = "http"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
if host == "play.minio.io:9000" || host == "dl.minio.io:9000" {
console.Infoln("Found hosts, replacing " + host + " with https://" + host)
url.Host = host
url.Scheme = "https"
url.SchemeSeparator = "://"
newConfig.Hosts[url.String()] = hostCfg
delete(newConfig.Hosts, host)
}
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
// fixConfigV6 - fix all the unnecessary glob URLs present in existing config version 6.
func fixConfigV6() {
if !isMcConfigExists() {
return
}
config, err := quick.New(newConfigV6())
fatalIf(err.Trace(), "Unable to initialize config.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to load config.")
if config.Data().(*configV6).Version == "6" {
newConfig := new(configV6)
newConfig.Aliases = make(map[string]string)
newConfig.Hosts = make(map[string]hostConfig)
newConfig.Version = "6"
newConfig.Aliases = config.Data().(*configV6).Aliases
for host, hostCfg := range config.Data().(*configV6).Hosts {
if strings.HasPrefix(host, "https") || strings.HasPrefix(host, "http") {
newConfig.Hosts[host] = hostCfg
continue
}
if strings.Contains(host, "*s3*") || strings.Contains(host, "*.s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "s3*") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*amazonaws.com") || strings.Contains(host, "*.amazonaws.com") {
console.Infoln("Found glob url, replacing " + host + " with s3.amazonaws.com")
newConfig.Hosts["s3.amazonaws.com"] = hostCfg
continue
}
if strings.Contains(host, "*storage.googleapis.com") {
console.Infoln("Found glob url, replacing " + host + " with storage.googleapis.com")
newConfig.Hosts["storage.googleapis.com"] = hostCfg
continue
}
if strings.Contains(host, "localhost:*") {
console.Infoln("Found glob url, replacing " + host + " with localhost:9000")
newConfig.Hosts["localhost:9000"] = hostCfg
continue
}
if strings.Contains(host, "127.0.0.1:*") {
console.Infoln("Found glob url, replacing " + host + " with 127.0.0.1:9000")
newConfig.Hosts["127.0.0.1:9000"] = hostCfg
continue
}
newConfig.Hosts[host] = hostCfg
}
newConf, err := quick.New(newConfig)
fatalIf(err.Trace(), "Unable to initialize newly fixed config.")
err = newConf.Save(mustGetMcConfigPath())
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to save newly fixed config path.")
}
}
func migrateConfig() {
// Migrate config V1 to V101
migrateConfigV1ToV101()
// Migrate config V101 to V2
migrateConfigV101ToV2()
// Migrate config V2 to V3
migrateConfigV2ToV3()
// Migrate config V3 to V4
migrateConfigV3ToV4()
// Migrate config V4 to V5
migrateConfigV4ToV5()
// Migrate config V5 to V6
migrateConfigV5ToV6()
}
func fixConfig() {
// Fix config V3
fixConfigV3()
// Fix config V6
fixConfigV6()
// Fix config V6 for hosts
fixConfigV6ForHosts()
}
+1 -1
View File
@@ -88,7 +88,7 @@ func (s *TestSuite) TestConfigHostContext(c *C) {
// reset back
console.IsExited = false
err = app.Run([]string{os.Args[0], "config", "host", "remove", "http://dl.minio.io:9000"})
err = app.Run([]string{os.Args[0], "config", "host", "remove", "https://dl.minio.io:9000"})
c.Assert(err, IsNil)
c.Assert(console.IsExited, Equals, true)
+170
View File
@@ -0,0 +1,170 @@
/*
* Minio Client (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.
*/
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Some of the code here is borrowed from 'encoding/json' package.
package main
import (
"encoding/csv"
"io"
"reflect"
"runtime"
"strconv"
"github.com/minio/minio-xl/pkg/probe"
)
// csvReader reads records from a CSV-encoded file.
type csvReader struct {
*csv.Reader
}
// newCSVReader returns a new csv Reader.
// additionally one can provide a line that needs to be skipped.
func newCSVReader(r io.Reader) *csvReader {
return &csvReader{
csv.NewReader(r),
}
}
// An invalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type invalidUnmarshalError struct {
Type reflect.Type
}
func (e *invalidUnmarshalError) Error() string {
if e.Type == nil {
return "csv: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "csv: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "csv: Unmarshal(nil " + e.Type.String() + ")"
}
// An unmarshalTypeError describes a CSV value that was
// not appropriate for a value of a specific Go type.
type unmarshalTypeError struct {
Type reflect.Type // type of Go value it could not be assigned to
}
func (e *unmarshalTypeError) Error() string {
return "csv: cannot unmarshal into Go value of type " + e.Type.String()
}
// Unmarshal - unmarshal everything into the input struct.
func (r *csvReader) Unmarshal(v interface{}, skipLine int) (err *probe.Error) {
// Handler for runtime errors.
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
e := r.(error)
err = probe.NewError(e)
}
}()
{
// Check if incoming interface{} is nil.
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return probe.NewError(&invalidUnmarshalError{reflect.TypeOf(v)})
}
}
rv := reflect.ValueOf(v).Elem()
rt := reflect.TypeOf(v).Elem().Elem()
records := reflect.MakeSlice(reflect.TypeOf(v).Elem(), 0, 0)
var e error
var lineCount int
for {
record := reflect.New(rt)
{
var csvRecord []string
csvRecord, e = r.Read()
if e != nil {
break
}
lineCount++
// Skip a particular line
if lineCount == skipLine {
continue
}
rvInternal := reflect.ValueOf(record.Interface()).Elem()
for s := 0; s < rvInternal.NumField(); s++ {
val := rvInternal.Field(s)
x := csvRecord[s]
setValue(&val, x)
}
}
records = reflect.Append(records, record.Elem())
}
if e == io.EOF {
rv.Set(records)
return nil
}
if e != nil {
return probe.NewError(e)
}
return nil
}
// setValue - following reflect.Value sets the actual value based on the Golang type.
// If no native type found throws an UnmarshalTypeError.
func setValue(v *reflect.Value, x string) *probe.Error {
switch v.Kind() {
case reflect.Bool:
val, e := strconv.ParseBool(x)
if e != nil {
return probe.NewError(e)
}
v.SetBool(val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val, e := strconv.ParseInt(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetInt(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
val, e := strconv.ParseUint(x, 10, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetUint(val)
case reflect.Float32, reflect.Float64:
val, e := strconv.ParseFloat(x, v.Type().Bits())
if e != nil {
return probe.NewError(e)
}
v.SetFloat(val)
case reflect.String:
v.SetString(x)
case reflect.Struct:
case reflect.Map:
case reflect.Slice:
case reflect.Array:
case reflect.Interface, reflect.Ptr:
default:
return probe.NewError(&unmarshalTypeError{v.Type()})
}
return nil
}