Remove globalQuiet and globalConfigDir global variables (#3830)

This commit is contained in:
Bala FA 2017-03-03 03:51:30 +05:30 committed by Harshavardhana
parent 208dd15245
commit 98d17d2a97
18 changed files with 178 additions and 364 deletions

View File

@ -19,6 +19,7 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"net/url" "net/url"
"os" "os"
"path" "path"
@ -176,20 +177,12 @@ func (rc remoteAdminClient) WriteTmpConfig(tmpFileName string, configBytes []byt
// CommitConfig - Move the new config in tmpFileName onto config.json // CommitConfig - Move the new config in tmpFileName onto config.json
// on a local node. // on a local node.
func (lc localAdminClient) CommitConfig(tmpFileName string) error { func (lc localAdminClient) CommitConfig(tmpFileName string) error {
configDir, err := getConfigPath() configFile := getConfigFile()
if err != nil { tmpConfigFile := filepath.Join(getConfigDir(), tmpFileName)
errorIf(err, "Failed to get config directory path.")
return err
}
configFilePath := filepath.Join(configDir, globalMinioConfigFile) err := os.Rename(tmpConfigFile, configFile)
err = os.Rename(filepath.Join(configDir, tmpFileName), configFilePath) errorIf(err, fmt.Sprintf("Failed to rename %s to %s", tmpConfigFile, configFile))
if err != nil { return err
errorIf(err, "Failed to rename to config.json")
return err
}
return nil
} }
// CommitConfig - Move the new config in tmpFileName onto config.json // CommitConfig - Move the new config in tmpFileName onto config.json

View File

@ -19,6 +19,7 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"io/ioutil" "io/ioutil"
"net/rpc" "net/rpc"
"os" "os"
@ -175,17 +176,9 @@ type WriteConfigReply struct {
} }
func writeTmpConfigCommon(tmpFileName string, configBytes []byte) error { func writeTmpConfigCommon(tmpFileName string, configBytes []byte) error {
configDir, err := getConfigPath() tmpConfigFile := filepath.Join(getConfigDir(), tmpFileName)
if err != nil { err := ioutil.WriteFile(tmpConfigFile, configBytes, 0666)
errorIf(err, "Failed to get config path") errorIf(err, fmt.Sprintf("Failed to write to temporary config file %s", tmpConfigFile))
return err
}
err = ioutil.WriteFile(filepath.Join(configDir, tmpFileName), configBytes, 0666)
if err != nil {
errorIf(err, "Failed to write to temporary config file.")
return err
}
return err return err
} }
@ -214,20 +207,12 @@ type CommitConfigReply struct {
// CommitConfig - Renames the temporary file into config.json on this node. // CommitConfig - Renames the temporary file into config.json on this node.
func (s *adminCmd) CommitConfig(cArgs *CommitConfigArgs, cReply *CommitConfigReply) error { func (s *adminCmd) CommitConfig(cArgs *CommitConfigArgs, cReply *CommitConfigReply) error {
configDir, err := getConfigPath() configFile := getConfigFile()
if err != nil { tmpConfigFile := filepath.Join(getConfigDir(), cArgs.FileName)
errorIf(err, "Failed to get config path.")
return err
}
configFilePath := filepath.Join(configDir, globalMinioConfigFile) err := os.Rename(tmpConfigFile, configFile)
err = os.Rename(filepath.Join(configDir, cArgs.FileName), configFilePath) errorIf(err, fmt.Sprintf("Failed to rename %s to %s", tmpConfigFile, configFile))
if err != nil { return err
errorIf(err, "Failed to rename config file.")
return err
}
return nil
} }
// registerAdminRPCRouter - registers RPC methods for service status, // registerAdminRPCRouter - registers RPC methods for service status,

View File

@ -21,90 +21,62 @@ import (
"encoding/pem" "encoding/pem"
"errors" "errors"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
) )
// getCertsPath get certs path.
func getCertsPath() string {
return filepath.Join(getConfigDir(), globalMinioCertsDir)
}
// getCertFile must get cert file.
func getCertFile() string {
return filepath.Join(getCertsPath(), globalMinioCertFile)
}
// getKeyFile must get key file.
func getKeyFile() string {
return filepath.Join(getCertsPath(), globalMinioKeyFile)
}
// createCertsPath create certs path. // createCertsPath create certs path.
func createCertsPath() error { func createCertsPath() error {
certsPath, err := getCertsPath() rootCAsPath := filepath.Join(getCertsPath(), globalMinioCertsCADir)
if err != nil { return mkdirAll(rootCAsPath, 0700)
return err }
// getCAFiles must get the list of the CA certificates stored in minio config dir
func getCAFiles() (caCerts []string) {
CAsDir := filepath.Join(getCertsPath(), globalMinioCertsCADir)
if caFiles, err := ioutil.ReadDir(CAsDir); err == nil {
// Ignore any error.
for _, cert := range caFiles {
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
}
} }
if err := os.MkdirAll(certsPath, 0700); err != nil { return caCerts
return err
}
rootCAsPath := filepath.Join(certsPath, globalMinioCertsCADir)
return os.MkdirAll(rootCAsPath, 0700)
} }
// getCertsPath get certs path. // getSystemCertPool returns empty cert pool in case of error (windows)
func getCertsPath() (string, error) { func getSystemCertPool() *x509.CertPool {
var certsPath string
configDir, err := getConfigPath()
if err != nil {
return "", err
}
certsPath = filepath.Join(configDir, globalMinioCertsDir)
return certsPath, nil
}
// mustGetCertsPath must get certs path.
func mustGetCertsPath() string {
certsPath, err := getCertsPath()
fatalIf(err, "Failed to get certificate path.")
return certsPath
}
// mustGetCertFile must get cert file.
func mustGetCertFile() string {
return filepath.Join(mustGetCertsPath(), globalMinioCertFile)
}
// mustGetKeyFile must get key file.
func mustGetKeyFile() string {
return filepath.Join(mustGetCertsPath(), globalMinioKeyFile)
}
// mustGetCAFiles must get the list of the CA certificates stored in minio config dir
func mustGetCAFiles() (caCerts []string) {
CAsDir := filepath.Join(mustGetCertsPath(), globalMinioCertsCADir)
caFiles, _ := ioutil.ReadDir(CAsDir)
for _, cert := range caFiles {
caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name()))
}
return
}
// mustGetSystemCertPool returns empty cert pool in case of error (windows)
func mustGetSystemCertPool() *x509.CertPool {
pool, err := x509.SystemCertPool() pool, err := x509.SystemCertPool()
if err != nil { if err != nil {
return x509.NewCertPool() pool = x509.NewCertPool()
} }
return pool return pool
} }
// isCertFileExists verifies if cert file exists, returns true if // isCertFileExists verifies if cert file exists, returns true if
// found, false otherwise. // found, false otherwise.
func isCertFileExists() bool { func isCertFileExists() bool {
st, e := os.Stat(filepath.Join(mustGetCertsPath(), globalMinioCertFile)) return isFile(getCertFile())
// If file exists and is regular return true.
if e == nil && st.Mode().IsRegular() {
return true
}
return false
} }
// isKeyFileExists verifies if key file exists, returns true if found, // isKeyFileExists verifies if key file exists, returns true if found,
// false otherwise. // false otherwise.
func isKeyFileExists() bool { func isKeyFileExists() bool {
st, e := os.Stat(filepath.Join(mustGetCertsPath(), globalMinioKeyFile)) return isFile(getKeyFile())
// If file exists and is regular return true.
if e == nil && st.Mode().IsRegular() {
return true
}
return false
} }
// isSSL - returns true with both cert and key exists. // isSSL - returns true with both cert and key exists.
@ -114,7 +86,7 @@ func isSSL() bool {
// Reads certificated file and returns a list of parsed certificates. // Reads certificated file and returns a list of parsed certificates.
func readCertificateChain() ([]*x509.Certificate, error) { func readCertificateChain() ([]*x509.Certificate, error) {
bytes, err := ioutil.ReadFile(mustGetCertFile()) bytes, err := ioutil.ReadFile(getCertFile())
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,12 +121,12 @@ func parseCertificateChain(bytes []byte) ([]*x509.Certificate, error) {
// loadRootCAs fetches CA files provided in minio config and adds them to globalRootCAs // loadRootCAs fetches CA files provided in minio config and adds them to globalRootCAs
// Currently under Windows, there is no way to load system + user CAs at the same time // Currently under Windows, there is no way to load system + user CAs at the same time
func loadRootCAs() { func loadRootCAs() {
caFiles := mustGetCAFiles() caFiles := getCAFiles()
if len(caFiles) == 0 { if len(caFiles) == 0 {
return return
} }
// Get system cert pool, and empty cert pool under Windows because it is not supported // Get system cert pool, and empty cert pool under Windows because it is not supported
globalRootCAs = mustGetSystemCertPool() globalRootCAs = getSystemCertPool()
// Load custom root CAs for client requests // Load custom root CAs for client requests
for _, caFile := range caFiles { for _, caFile := range caFiles {
caCert, err := ioutil.ReadFile(caFile) caCert, err := ioutil.ReadFile(caFile)

View File

@ -25,10 +25,7 @@ import (
// Make sure we have a valid certs path. // Make sure we have a valid certs path.
func TestGetCertsPath(t *testing.T) { func TestGetCertsPath(t *testing.T) {
path, err := getCertsPath() path := getCertsPath()
if err != nil {
t.Error(err)
}
if path == "" { if path == "" {
t.Errorf("expected path to not be an empty string, got: '%s'", path) t.Errorf("expected path to not be an empty string, got: '%s'", path)
} }
@ -42,18 +39,18 @@ func TestGetCertsPath(t *testing.T) {
} }
// This will error if something goes wrong, so just call it. // This will error if something goes wrong, so just call it.
mustGetCertsPath() getCertsPath()
} }
// Ensure that the certificate and key file getters contain their respective // Ensure that the certificate and key file getters contain their respective
// file name and endings. // file name and endings.
func TestGetFiles(t *testing.T) { func TestGetFiles(t *testing.T) {
file := mustGetCertFile() file := getCertFile()
if !strings.Contains(file, globalMinioCertFile) { if !strings.Contains(file, globalMinioCertFile) {
t.Errorf("CertFile does not contain %s", globalMinioCertFile) t.Errorf("CertFile does not contain %s", globalMinioCertFile)
} }
file = mustGetKeyFile() file = getKeyFile()
if !strings.Contains(file, globalMinioKeyFile) { if !strings.Contains(file, globalMinioKeyFile) {
t.Errorf("KeyFile does not contain %s", globalMinioKeyFile) t.Errorf("KeyFile does not contain %s", globalMinioKeyFile)
} }

View File

@ -94,15 +94,10 @@ func purgeV1() error {
} }
if cv1.Version == "1" { if cv1.Version == "1" {
console.Println("Removed unsupported config version 1.") // Purge old fsUsers.json file
/// Purge old fsUsers.json file configFile := filepath.Join(getConfigDir(), "fsUsers.json")
configPath, err := getConfigPath()
if err != nil {
return fmt.Errorf("Unable to retrieve config path. %v", err)
}
configFile := filepath.Join(configPath, "fsUsers.json")
removeAll(configFile) removeAll(configFile)
console.Println("Removed unsupported config version 1.")
return nil return nil
} }
return fmt.Errorf("Failed to migrate unrecognized config version " + cv1.Version + ".") return fmt.Errorf("Failed to migrate unrecognized config version " + cv1.Version + ".")
@ -158,12 +153,7 @@ func migrateV2ToV3() error {
return fmt.Errorf("Unable to initialize config. %v", err) return fmt.Errorf("Unable to initialize config. %v", err)
} }
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
// Migrate the config.
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv2.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv2.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -205,11 +195,8 @@ func migrateV3ToV4() error {
if err != nil { if err != nil {
return fmt.Errorf("Unable to initialize the quick config. %v", err) return fmt.Errorf("Unable to initialize the quick config. %v", err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv3.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv3.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -254,11 +241,8 @@ func migrateV4ToV5() error {
if err != nil { if err != nil {
return fmt.Errorf("Unable to initialize the quick config. %v", err) return fmt.Errorf("Unable to initialize the quick config. %v", err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv4.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv4.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -330,11 +314,8 @@ func migrateV5ToV6() error {
if err != nil { if err != nil {
return fmt.Errorf("Unable to initialize the quick config. %v", err) return fmt.Errorf("Unable to initialize the quick config. %v", err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv5.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv5.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -394,11 +375,8 @@ func migrateV6ToV7() error {
if err != nil { if err != nil {
return fmt.Errorf("Unable to initialize the quick config. %v", err) return fmt.Errorf("Unable to initialize the quick config. %v", err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv6.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv6.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -465,11 +443,8 @@ func migrateV7ToV8() error {
if err != nil { if err != nil {
return fmt.Errorf("Unable to initialize the quick config. %v", err) return fmt.Errorf("Unable to initialize the quick config. %v", err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf("Failed to migrate config from "+cv7.Version+" to "+srvConfig.Version+" failed. %v", err) return fmt.Errorf("Failed to migrate config from "+cv7.Version+" to "+srvConfig.Version+" failed. %v", err)
@ -544,11 +519,8 @@ func migrateV8ToV9() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(
@ -629,11 +601,8 @@ func migrateV9ToV10() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(
@ -717,11 +686,8 @@ func migrateV10ToV11() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(
@ -823,11 +789,8 @@ func migrateV11ToV12() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(
@ -920,11 +883,8 @@ func migrateV12ToV13() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(
@ -1022,11 +982,8 @@ func migrateV13ToV14() error {
return fmt.Errorf("Unable to initialize the quick config. %v", return fmt.Errorf("Unable to initialize the quick config. %v",
err) err)
} }
configFile, err := getConfigFile()
if err != nil {
return fmt.Errorf("Unable to get config file. %v", err)
}
configFile := getConfigFile()
err = qc.Save(configFile) err = qc.Save(configFile)
if err != nil { if err != nil {
return fmt.Errorf( return fmt.Errorf(

View File

@ -31,7 +31,7 @@ func TestServerConfigMigrateV1(t *testing.T) {
// remove the root directory after the test ends. // remove the root directory after the test ends.
defer removeAll(rootPath) defer removeAll(rootPath)
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
// Create a V1 config json file and store it // Create a V1 config json file and store it
configJSON := "{ \"version\":\"1\", \"accessKeyId\":\"abcde\", \"secretAccessKey\":\"abcdefgh\"}" configJSON := "{ \"version\":\"1\", \"accessKeyId\":\"abcde\", \"secretAccessKey\":\"abcdefgh\"}"
@ -65,7 +65,7 @@ func TestServerConfigMigrateInexistentConfig(t *testing.T) {
// remove the root directory after the test ends. // remove the root directory after the test ends.
defer removeAll(rootPath) defer removeAll(rootPath)
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
configPath := rootPath + "/" + globalMinioConfigFile configPath := rootPath + "/" + globalMinioConfigFile
// Remove config file // Remove config file
@ -120,7 +120,7 @@ func TestServerConfigMigrateV2toV14(t *testing.T) {
// remove the root directory after the test ends. // remove the root directory after the test ends.
defer removeAll(rootPath) defer removeAll(rootPath)
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
configPath := rootPath + "/" + globalMinioConfigFile configPath := rootPath + "/" + globalMinioConfigFile
// Create a corrupted config file // Create a corrupted config file
@ -174,7 +174,7 @@ func TestServerConfigMigrateFaultyConfig(t *testing.T) {
// remove the root directory after the test ends. // remove the root directory after the test ends.
defer removeAll(rootPath) defer removeAll(rootPath)
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
configPath := rootPath + "/" + globalMinioConfigFile configPath := rootPath + "/" + globalMinioConfigFile
// Create a corrupted config file // Create a corrupted config file

View File

@ -50,11 +50,7 @@ type configV1 struct {
// loadConfigV1 load config // loadConfigV1 load config
func loadConfigV1() (*configV1, error) { func loadConfigV1() (*configV1, error) {
configPath, err := getConfigPath() configFile := filepath.Join(getConfigDir(), "fsUsers.json")
if err != nil {
return nil, err
}
configFile := filepath.Join(configPath, "fsUsers.json")
config, err := loadOldConfig(configFile, &configV1{Version: "1"}) config, err := loadOldConfig(configFile, &configV1{Version: "1"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -86,10 +82,7 @@ type configV2 struct {
// loadConfigV2 load config version '2'. // loadConfigV2 load config version '2'.
func loadConfigV2() (*configV2, error) { func loadConfigV2() (*configV2, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &configV2{Version: "2"}) config, err := loadOldConfig(configFile, &configV2{Version: "2"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -152,10 +145,7 @@ type configV3 struct {
// loadConfigV3 load config version '3'. // loadConfigV3 load config version '3'.
func loadConfigV3() (*configV3, error) { func loadConfigV3() (*configV3, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &configV3{Version: "3"}) config, err := loadOldConfig(configFile, &configV3{Version: "3"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -195,10 +185,7 @@ type configV4 struct {
// loadConfigV4 load config version '4'. // loadConfigV4 load config version '4'.
func loadConfigV4() (*configV4, error) { func loadConfigV4() (*configV4, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &configV4{Version: "4"}) config, err := loadOldConfig(configFile, &configV4{Version: "4"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -265,10 +252,7 @@ type configV5 struct {
// loadConfigV5 load config version '5'. // loadConfigV5 load config version '5'.
func loadConfigV5() (*configV5, error) { func loadConfigV5() (*configV5, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &configV5{Version: "5"}) config, err := loadOldConfig(configFile, &configV5{Version: "5"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -299,10 +283,7 @@ type configV6 struct {
// loadConfigV6 load config version '6'. // loadConfigV6 load config version '6'.
func loadConfigV6() (*configV6, error) { func loadConfigV6() (*configV6, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &configV6{Version: "6"}) config, err := loadOldConfig(configFile, &configV6{Version: "6"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -352,10 +333,7 @@ type serverConfigV7 struct {
// loadConfigV7 load config version '7'. // loadConfigV7 load config version '7'.
func loadConfigV7() (*serverConfigV7, error) { func loadConfigV7() (*serverConfigV7, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV7{Version: "7"}) config, err := loadOldConfig(configFile, &serverConfigV7{Version: "7"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -384,10 +362,7 @@ type serverConfigV8 struct {
// loadConfigV8 load config version '8'. // loadConfigV8 load config version '8'.
func loadConfigV8() (*serverConfigV8, error) { func loadConfigV8() (*serverConfigV8, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV8{Version: "8"}) config, err := loadOldConfig(configFile, &serverConfigV8{Version: "8"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -415,10 +390,7 @@ type serverConfigV9 struct {
} }
func loadConfigV9() (*serverConfigV9, error) { func loadConfigV9() (*serverConfigV9, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV9{Version: "9"}) config, err := loadOldConfig(configFile, &serverConfigV9{Version: "9"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -444,10 +416,7 @@ type serverConfigV10 struct {
} }
func loadConfigV10() (*serverConfigV10, error) { func loadConfigV10() (*serverConfigV10, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV10{Version: "10"}) config, err := loadOldConfig(configFile, &serverConfigV10{Version: "10"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -484,10 +453,7 @@ type serverConfigV11 struct {
} }
func loadConfigV11() (*serverConfigV11, error) { func loadConfigV11() (*serverConfigV11, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV11{Version: "11"}) config, err := loadOldConfig(configFile, &serverConfigV11{Version: "11"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -512,10 +478,7 @@ type serverConfigV12 struct {
} }
func loadConfigV12() (*serverConfigV12, error) { func loadConfigV12() (*serverConfigV12, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV12{Version: "12"}) config, err := loadOldConfig(configFile, &serverConfigV12{Version: "12"})
if config == nil { if config == nil {
return nil, err return nil, err
@ -540,10 +503,7 @@ type serverConfigV13 struct {
} }
func loadConfigV13() (*serverConfigV13, error) { func loadConfigV13() (*serverConfigV13, error) {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return nil, err
}
config, err := loadOldConfig(configFile, &serverConfigV13{Version: "13"}) config, err := loadOldConfig(configFile, &serverConfigV13{Version: "13"})
if config == nil { if config == nil {
return nil, err return nil, err

View File

@ -98,7 +98,7 @@ func newConfig(envParams envParams) error {
} }
// Create config path. // Create config path.
if err := createConfigPath(); err != nil { if err := createConfigDir(); err != nil {
return err return err
} }
@ -116,12 +116,8 @@ func newConfig(envParams envParams) error {
// loadConfig - loads a new config from disk, overrides params from env // loadConfig - loads a new config from disk, overrides params from env
// if found and valid // if found and valid
func loadConfig(envParams envParams) error { func loadConfig(envParams envParams) error {
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil { if _, err := os.Stat(configFile); err != nil {
return err
}
if _, err = os.Stat(configFile); err != nil {
return err return err
} }
@ -229,10 +225,7 @@ func (s serverConfigV14) Save() error {
defer serverConfigMu.RUnlock() defer serverConfigMu.RUnlock()
// get config file. // get config file.
configFile, err := getConfigFile() configFile := getConfigFile()
if err != nil {
return err
}
// initialize quick. // initialize quick.
qc, err := quick.New(&s) qc, err := quick.New(&s)

View File

@ -112,7 +112,7 @@ func TestServerConfig(t *testing.T) {
} }
// Do this only once here. // Do this only once here.
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
// Initialize server config. // Initialize server config.
if err := loadConfig(envParams{}); err != nil { if err := loadConfig(envParams{}); err != nil {
@ -143,7 +143,7 @@ func TestServerConfigWithEnvs(t *testing.T) {
} }
// Do this only once here. // Do this only once here.
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
// Init config // Init config
initConfig() initConfig()

View File

@ -1,5 +1,5 @@
/* /*
* Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,77 +17,62 @@
package cmd package cmd
import ( import (
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"github.com/minio/go-homedir" homedir "github.com/minio/go-homedir"
"github.com/minio/mc/pkg/console"
) )
// configPath for custom config path only for testing purposes // ConfigDir - configuration directory with locking.
var customConfigPath string type ConfigDir struct {
var configMu sync.Mutex sync.Mutex
dir string
// Sets a new config path.
func setGlobalConfigPath(configPath string) {
configMu.Lock()
defer configMu.Unlock()
customConfigPath = configPath
} }
// getConfigPath get server config path // Set - saves given directory as configuration directory.
func getConfigPath() (string, error) { func (config *ConfigDir) Set(dir string) {
configMu.Lock() config.Lock()
defer configMu.Unlock() defer config.Unlock()
if customConfigPath != "" { config.dir = dir
return customConfigPath, nil }
}
// Get - returns current configuration directory.
func (config *ConfigDir) Get() string {
config.Lock()
defer config.Unlock()
return config.dir
}
func mustGetDefaultConfigDir() string {
homeDir, err := homedir.Dir() homeDir, err := homedir.Dir()
if err != nil { if err != nil {
return "", err console.Fatalln("Unable to get home directory.", err)
} }
configPath := filepath.Join(homeDir, globalMinioConfigDir)
return configPath, nil return filepath.Join(homeDir, globalMinioConfigDir)
} }
// mustGetConfigPath must get server config path. var configDir = &ConfigDir{dir: mustGetDefaultConfigDir()}
func mustGetConfigPath() string {
configPath, err := getConfigPath() func setConfigDir(dir string) {
if err != nil { configDir.Set(dir)
return ""
}
return configPath
} }
// createConfigPath create server config path. func getConfigDir() string {
func createConfigPath() error { return configDir.Get()
configPath, err := getConfigPath() }
if err != nil {
return err func createConfigDir() error {
} return mkdirAll(getConfigDir(), 0700)
return os.MkdirAll(configPath, 0700) }
func getConfigFile() string {
return filepath.Join(getConfigDir(), globalMinioConfigFile)
} }
// isConfigFileExists - returns true if config file exists.
func isConfigFileExists() bool { func isConfigFileExists() bool {
path, err := getConfigFile() return isFile(getConfigFile())
if err != nil {
return false
}
st, err := os.Stat(path)
// If file exists and is regular return true.
if err == nil && st.Mode().IsRegular() {
return true
}
return false
}
// getConfigFile get server config file.
func getConfigFile() (string, error) {
configPath, err := getConfigPath()
if err != nil {
return "", err
}
return filepath.Join(configPath, globalMinioConfigFile), nil
} }

View File

@ -24,8 +24,6 @@ import (
humanize "github.com/dustin/go-humanize" humanize "github.com/dustin/go-humanize"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
) )
// minio configuration related constants. // minio configuration related constants.
@ -60,10 +58,6 @@ const (
) )
var ( var (
globalQuiet = false // quiet flag set via command line.
globalConfigDir = mustGetConfigPath() // config-dir flag set via command line
// Add new global flags here.
// Indicates if the running minio server is distributed setup. // Indicates if the running minio server is distributed setup.
globalIsDistXL = false globalIsDistXL = false
@ -131,20 +125,3 @@ var (
colorBold = color.New(color.Bold).SprintFunc() colorBold = color.New(color.Bold).SprintFunc()
colorBlue = color.New(color.FgBlue).SprintfFunc() colorBlue = color.New(color.FgBlue).SprintfFunc()
) )
// Parse command arguments and set global variables accordingly
func setGlobalsFromContext(c *cli.Context) {
// Set config dir
switch {
case c.IsSet("config-dir"):
globalConfigDir = c.String("config-dir")
case c.GlobalIsSet("config-dir"):
globalConfigDir = c.GlobalString("config-dir")
}
if globalConfigDir == "" {
console.Fatalf("Unable to get config file. Config directory is empty.")
}
// Set global quiet flag.
globalQuiet = c.Bool("quiet") || c.GlobalBool("quiet")
}

View File

@ -31,7 +31,7 @@ var (
globalFlags = []cli.Flag{ globalFlags = []cli.Flag{
cli.StringFlag{ cli.StringFlag{
Name: "config-dir, C", Name: "config-dir, C",
Value: mustGetConfigPath(), Value: getConfigDir(),
Usage: "Path to configuration directory.", Usage: "Path to configuration directory.",
}, },
cli.BoolFlag{ cli.BoolFlag{
@ -133,26 +133,10 @@ func registerApp() *cli.App {
return app return app
} }
// Verify main command syntax.
func checkMainSyntax(c *cli.Context) {
configPath, err := getConfigPath()
if err != nil {
console.Fatalf("Unable to obtain user's home directory. \nError: %s\n", err)
}
if configPath == "" {
console.Fatalln("Config directory cannot be empty, please specify --config-dir <directoryname>.")
}
}
// Check for updates and print a notification message // Check for updates and print a notification message
func checkUpdate() { func checkUpdate() {
// Do not print update messages, if quiet flag is set. // Its OK to ignore any errors during getUpdateInfo() here.
if !globalQuiet { if older, downloadURL, err := getUpdateInfo(1 * time.Second); err == nil {
older, downloadURL, err := getUpdateInfo(1 * time.Second)
if err != nil {
// Its OK to ignore any errors during getUpdateInfo() here.
return
}
if older > time.Duration(0) { if older > time.Duration(0) {
console.Println(colorizeUpdateMessage(downloadURL, older)) console.Println(colorizeUpdateMessage(downloadURL, older))
} }
@ -179,7 +163,7 @@ func initConfig() {
if err := newConfig(envs); err != nil { if err := newConfig(envs); err != nil {
console.Fatalf("Unable to initialize minio config for the first time. Err: %s.\n", err) console.Fatalf("Unable to initialize minio config for the first time. Err: %s.\n", err)
} }
console.Println("Created minio configuration file successfully at " + mustGetConfigPath()) console.Println("Created minio configuration file successfully at " + getConfigDir())
return return
} }
@ -194,12 +178,6 @@ func initConfig() {
// Generic Minio initialization to create/load config, prepare loggers, etc.. // Generic Minio initialization to create/load config, prepare loggers, etc..
func minioInit(ctx *cli.Context) { func minioInit(ctx *cli.Context) {
// Set global variables after parsing passed arguments
setGlobalsFromContext(ctx)
// Sets new config directory.
setGlobalConfigPath(globalConfigDir)
// Is TLS configured?. // Is TLS configured?.
globalIsSSL = isSSL() globalIsSSL = isSSL()
@ -217,11 +195,6 @@ func minioInit(ctx *cli.Context) {
// Main main for minio server. // Main main for minio server.
func Main(args []string, exitFn func(int)) { func Main(args []string, exitFn func(int)) {
app := registerApp() app := registerApp()
app.Before = func(c *cli.Context) error {
// Valid input arguments to main.
checkMainSyntax(c)
return nil
}
// Start profiler if env is set. // Start profiler if env is set.
if profiler := os.Getenv("_MINIO_PROFILER"); profiler != "" { if profiler := os.Getenv("_MINIO_PROFILER"); profiler != "" {

View File

@ -46,9 +46,7 @@ func printOnceFn() printOnceFunc {
var once sync.Once var once sync.Once
return func(msg string) { return func(msg string) {
once.Do(func() { once.Do(func() {
if !globalQuiet { console.Println(msg)
console.Println(msg)
}
}) })
} }
} }

View File

@ -30,6 +30,7 @@ import (
"runtime" "runtime"
"github.com/minio/cli" "github.com/minio/cli"
"github.com/minio/mc/pkg/console"
) )
var serverFlags = []cli.Flag{ var serverFlags = []cli.Flag{
@ -358,11 +359,28 @@ func serverMain(c *cli.Context) {
cli.ShowCommandHelpAndExit(c, "server", 1) cli.ShowCommandHelpAndExit(c, "server", 1)
} }
// Get quiet flag from command line argument.
quietFlag := c.Bool("quiet") || c.GlobalBool("quiet")
// Get configuration directory from command line argument.
configDir := c.String("config-dir")
if !c.IsSet("config-dir") && c.GlobalIsSet("config-dir") {
configDir = c.GlobalString("config-dir")
}
if configDir == "" {
console.Fatalf("Configuration directory cannot be empty.")
}
// Set configuration directory.
setConfigDir(configDir)
// Initializes server config, certs, logging and system settings. // Initializes server config, certs, logging and system settings.
initServerConfig(c) initServerConfig(c)
// Check for new updates from dl.minio.io. // Check for new updates from dl.minio.io.
checkUpdate() if !quietFlag {
checkUpdate()
}
// Server address. // Server address.
serverAddr := c.String("address") serverAddr := c.String("address")
@ -442,7 +460,7 @@ func serverMain(c *cli.Context) {
go func() { go func() {
cert, key := "", "" cert, key := "", ""
if globalIsSSL { if globalIsSSL {
cert, key = mustGetCertFile(), mustGetKeyFile() cert, key = getCertFile(), getKeyFile()
} }
fatalIf(apiServer.ListenAndServe(cert, key), "Failed to start minio server.") fatalIf(apiServer.ListenAndServe(cert, key), "Failed to start minio server.")
}() }()
@ -458,7 +476,9 @@ func serverMain(c *cli.Context) {
globalObjLayerMutex.Unlock() globalObjLayerMutex.Unlock()
// Prints the formatted startup message once object layer is initialized. // Prints the formatted startup message once object layer is initialized.
printStartupMessage(apiEndPoints) if !quietFlag {
printStartupMessage(apiEndPoints)
}
// Set uptime time after object layer has initialized. // Set uptime time after object layer has initialized.
globalBootTime = time.Now().UTC() globalBootTime = time.Now().UTC()

View File

@ -358,8 +358,8 @@ func TestServerListenAndServeTLS(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
certFile := mustGetCertFile() certFile := getCertFile()
keyFile := mustGetKeyFile() keyFile := getKeyFile()
defer os.RemoveAll(certFile) defer os.RemoveAll(certFile)
defer os.RemoveAll(keyFile) defer os.RemoveAll(keyFile)
@ -420,8 +420,8 @@ func TestServerListenAndServeTLS(t *testing.T) {
// generateTestCert creates a cert and a key used for testing only // generateTestCert creates a cert and a key used for testing only
func generateTestCert(host string) error { func generateTestCert(host string) error {
certPath := mustGetCertFile() certPath := getCertFile()
keyPath := mustGetKeyFile() keyPath := getKeyFile()
priv, err := rsa.GenerateKey(rand.Reader, 2048) priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil { if err != nil {
return err return err

View File

@ -44,11 +44,6 @@ func getFormatStr(strLen int, padding int) string {
// Prints the formatted startup message. // Prints the formatted startup message.
func printStartupMessage(apiEndPoints []string) { func printStartupMessage(apiEndPoints []string) {
// If quiet flag is set do not print startup message.
if globalQuiet {
return
}
// Prints credential, region and browser access. // Prints credential, region and browser access.
printServerCommonMsg(apiEndPoints) printServerCommonMsg(apiEndPoints)

View File

@ -440,7 +440,7 @@ func StartTestPeersRPCServer(t TestErrHandler, instanceType string) TestServer {
// Sets the global config path to empty string. // Sets the global config path to empty string.
func resetGlobalConfigPath() { func resetGlobalConfigPath() {
setGlobalConfigPath("") setConfigDir("")
} }
// sets globalObjectAPI to `nil`. // sets globalObjectAPI to `nil`.
@ -519,7 +519,7 @@ func newTestConfig(bucketLocation string) (rootPath string, err error) {
} }
// Do this only once here. // Do this only once here.
setGlobalConfigPath(rootPath) setConfigDir(rootPath)
// Initialize server config. // Initialize server config.
if err = newConfig(envParams{}); err != nil { if err = newConfig(envParams{}); err != nil {

View File

@ -262,3 +262,12 @@ func getBrowserFromEnv() (string, error) {
globalIsEnvBrowser = true globalIsEnvBrowser = true
return strings.ToLower(b), nil return strings.ToLower(b), nil
} }
// isFile - returns whether given path is a file or not.
func isFile(path string) bool {
if fi, err := os.Stat(path); err == nil {
return fi.Mode().IsRegular()
}
return false
}