cubefs

Форк
0
/
config.go 
173 строки · 4.2 Кб
1
// Copyright 2018 The CubeFS Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
// implied. See the License for the specific language governing
13
// permissions and limitations under the License.
14

15
package cmd
16

17
import (
18
	"encoding/json"
19
	"math"
20
	"os"
21
	"path"
22
	"strconv"
23
	"strings"
24

25
	"github.com/spf13/cobra"
26
)
27

28
const (
29
	cmdConfigShort = "Manage global config file"
30
)
31

32
var (
33
	defaultHomeDir, _ = os.UserHomeDir()
34
	defaultConfigName = ".cfs-cli.json"
35
	defaultConfigPath = path.Join(defaultHomeDir, defaultConfigName)
36
	defaultConfigData = []byte(`
37
{
38
  "masterAddr": [
39
    "master.cube.io"
40
  ],
41
  "timeout": 60
42
}
43
`)
44
	defaultConfigTimeout uint16 = 60
45
)
46

47
type Config struct {
48
	MasterAddr  []string `json:"masterAddr"`
49
	Timeout     uint16   `json:"timeout"`
50
	ClientIDKey string   `json:"clientIDKey"`
51
}
52

53
func newConfigCmd() *cobra.Command {
54
	cmd := &cobra.Command{
55
		Use:   CliResourceConfig,
56
		Short: cmdConfigShort,
57
	}
58
	cmd.AddCommand(newConfigSetCmd())
59
	cmd.AddCommand(newConfigInfoCmd())
60
	return cmd
61
}
62

63
const (
64
	cmdConfigSetShort  = "set value of config file"
65
	cmdConfigInfoShort = "show info of config file"
66
)
67

68
func newConfigSetCmd() *cobra.Command {
69
	var optMasterHosts string
70
	var optTimeout string
71
	cmd := &cobra.Command{
72
		Use:   CliOpSet,
73
		Short: cmdConfigSetShort,
74
		Long:  `Set the config file`,
75
		Run: func(cmd *cobra.Command, args []string) {
76
			var err error
77
			defer func() {
78
				errout(err)
79
			}()
80
			tmp, _ := strconv.Atoi(optTimeout)
81
			if tmp > math.MaxUint16 {
82
				stdoutln("Please reset timeout. Input less than math.MaxUint16")
83
				return
84
			}
85
			timeOut := uint16(tmp)
86
			if optMasterHosts == "" {
87
				stdout("Please set addr. Input 'cfs-cli config set -h' for help.\n")
88
				return
89
			}
90

91
			if timeOut == 0 {
92
				stdout("timeOut %v is invalid.\n", timeOut)
93
				return
94
			}
95

96
			if err = setConfig(optMasterHosts, timeOut); err != nil {
97
				return
98
			}
99
			stdout("Config has been set successfully!\n")
100
		},
101
	}
102
	cmd.Flags().StringVar(&optMasterHosts, "addr", "",
103
		"Specify master address {HOST}:{PORT}[,{HOST}:{PORT}]")
104
	cmd.Flags().StringVar(&optTimeout, "timeout", "60", "Specify timeout for requests [Unit: s]")
105
	return cmd
106
}
107

108
func newConfigInfoCmd() *cobra.Command {
109
	var optFilterStatus string
110
	var optFilterWritable string
111
	cmd := &cobra.Command{
112
		Use:   CliOpInfo,
113
		Short: cmdConfigInfoShort,
114
		Run: func(cmd *cobra.Command, args []string) {
115
			config, err := LoadConfig()
116
			errout(err)
117
			printConfigInfo(config)
118
		},
119
	}
120
	cmd.Flags().StringVar(&optFilterWritable, "filter-writable", "", "Filter node writable status")
121
	cmd.Flags().StringVar(&optFilterStatus, "filter-status", "", "Filter node status [Active, Inactive]")
122
	return cmd
123
}
124

125
func printConfigInfo(config *Config) {
126
	stdout("Config info:\n")
127
	stdout("  Master  Address    : %v\n", config.MasterAddr)
128
	stdout("  Request Timeout [s]: %v\n", config.Timeout)
129
}
130

131
func setConfig(masterHosts string, timeout uint16) (err error) {
132
	var config *Config
133
	if config, err = LoadConfig(); err != nil {
134
		return
135
	}
136
	hosts := strings.Split(masterHosts, ",")
137
	if masterHosts != "" && len(hosts) > 0 {
138
		config.MasterAddr = hosts
139
	}
140
	if timeout != 0 {
141
		config.Timeout = timeout
142
	}
143
	var configData []byte
144
	if configData, err = json.Marshal(config); err != nil {
145
		return
146
	}
147
	if err = os.WriteFile(defaultConfigPath, configData, 0o600); err != nil {
148
		return
149
	}
150
	return nil
151
}
152

153
func LoadConfig() (*Config, error) {
154
	var err error
155
	var configData []byte
156
	if configData, err = os.ReadFile(defaultConfigPath); err != nil && !os.IsNotExist(err) {
157
		return nil, err
158
	}
159
	if os.IsNotExist(err) {
160
		if err = os.WriteFile(defaultConfigPath, defaultConfigData, 0o600); err != nil {
161
			return nil, err
162
		}
163
		configData = defaultConfigData
164
	}
165
	config := &Config{}
166
	if err = json.Unmarshal(configData, config); err != nil {
167
		return nil, err
168
	}
169
	if config.Timeout == 0 {
170
		config.Timeout = defaultConfigTimeout
171
	}
172
	return config, nil
173
}
174

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.