-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathconfig.go
203 lines (168 loc) · 5.43 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// +-------------------------------------------------------------------------
// | Copyright (C) 2016 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | you may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 config
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/yunify/qingcloud-sdk-go/logger"
"github.com/yunify/qingcloud-sdk-go/utils"
)
// A Config stores a configuration of this sdk.
type Config struct {
AccessKeyID string `yaml:"qy_access_key_id"`
SecretAccessKey string `yaml:"qy_secret_access_key"`
Host string `yaml:"host"`
Port int `yaml:"port"`
Protocol string `yaml:"protocol"`
URI string `yaml:"uri"`
ConnectionRetries int `yaml:"connection_retries"`
ConnectionTimeout int `yaml:"connection_timeout"`
LogLevel string `yaml:"log_level"`
Zone string `yaml:"zone"`
CredentialProxyProtocol string `yaml:"credential_proxy_protocol"`
CredentialProxyHost string `yaml:"credential_proxy_host"`
CredentialProxyPort int `yaml:"credential_proxy_port"`
CredentialProxyURI string `yaml:"credential_proxy_uri"`
Token string
Expiration int64
Connection *http.Client
}
// New create a Config with given AccessKeyID and SecretAccessKey.
func New(accessKeyID, secretAccessKey string) (*Config, error) {
config, err := NewDefault()
if err != nil {
return nil, err
}
config.AccessKeyID = accessKeyID
config.SecretAccessKey = secretAccessKey
config.Connection = &http.Client{}
return config, nil
}
// NewWithEndpoint create a Config with given AccessKeyID, SecretAccessKey and endpoint
func NewWithEndpoint(accessKeyID, secretAccessKey, endpoint string) (*Config, error) {
qcURL, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
if qcURL.Opaque != "" {
return nil, fmt.Errorf("wrong URL format")
}
if !strings.Contains(qcURL.Host, ":") {
if qcURL.Scheme == "https" {
qcURL.Host += ":443"
} else if qcURL.Scheme == "http" {
qcURL.Host += ":80"
} else {
return nil, fmt.Errorf("can not find default port ")
}
}
config, err := NewDefault()
if err != nil {
return nil, err
}
host, port, err := net.SplitHostPort(qcURL.Host)
if err != nil {
return nil, err
}
config.Port, _ = strconv.Atoi(port)
config.Host = host
config.AccessKeyID = accessKeyID
config.SecretAccessKey = secretAccessKey
config.Protocol = qcURL.Scheme
config.URI = qcURL.Path
config.Connection = &http.Client{}
return config, nil
}
// NewDefault create a Config with default configuration.
func NewDefault() (*Config, error) {
config := &Config{}
err := config.LoadDefaultConfig()
if err != nil {
return nil, err
}
timeout := time.Duration(config.ConnectionTimeout) * time.Second
transport := &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
},
}
config.Connection = &http.Client{
Transport: transport,
}
return config, nil
}
// LoadDefaultConfig loads the default configuration for Config.
// It returns error if yaml decode failed.
func (c *Config) LoadDefaultConfig() error {
_, err := utils.YAMLDecode([]byte(DefaultConfigFileContent), c)
if err != nil {
logger.Error("Config parse error: " + err.Error())
return err
}
logger.SetLevel(c.LogLevel)
return nil
}
// LoadUserConfig loads user configuration in ~/.qingcloud/config.yaml for Config.
// It returns error if file not found.
func (c *Config) LoadUserConfig() error {
_, err := os.Stat(GetUserConfigFilePath())
if err != nil {
logger.Warn("Installing default config file to \"" + GetUserConfigFilePath() + "\"")
InstallDefaultUserConfig()
}
return c.LoadConfigFromFilepath(GetUserConfigFilePath())
}
// LoadConfigFromFilepath loads configuration from a specified local path.
// It returns error if file not found or yaml decode failed.
func (c *Config) LoadConfigFromFilepath(filepath string) error {
if strings.Index(filepath, "~/") == 0 {
filepath = strings.Replace(filepath, "~/", getHome()+"/", 1)
}
configYAML, err := ioutil.ReadFile(filepath)
if err != nil {
logger.Error("File not found: " + filepath)
return err
}
return c.LoadConfigFromContent(configYAML)
}
// LoadConfigFromContent loads configuration from a given byte slice.
// It returns error if yaml decode failed.
func (c *Config) LoadConfigFromContent(content []byte) error {
c.LoadDefaultConfig()
_, err := utils.YAMLDecode(content, c)
if err != nil {
logger.Error("Config parse error: " + err.Error())
return err
}
logger.SetLevel(c.LogLevel)
timeout := time.Duration(c.ConnectionTimeout) * time.Second
transport := &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
},
}
c.Connection = &http.Client{
Transport: transport,
}
return nil
}