-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
193 lines (175 loc) · 6.05 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
package zcc
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"sync"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"
"github.com/zscaler/zscaler-sdk-go/v2/logger"
)
const (
defaultTimeout = 240 * time.Second
loggerPrefix = "zcc-logger: "
ZCC_CLIENT_ID = "ZCC_CLIENT_ID"
ZCC_CLIENT_SECRET = "ZCC_CLIENT_SECRET"
ZCC_CLOUD = "ZCC_CLOUD"
configPath string = ".zcc/credentials.json"
)
var defaultBackoffConf = &BackoffConfig{
Enabled: true,
MaxNumOfRetries: 100,
RetryWaitMaxSeconds: 20,
RetryWaitMinSeconds: 5,
}
type BackoffConfig struct {
Enabled bool // Set to true to enable backoff and retry mechanism
RetryWaitMinSeconds int // Minimum time to wait
RetryWaitMaxSeconds int // Maximum time to wait
MaxNumOfRetries int // Maximum number of retries
}
type AuthRequest struct {
APIKey string `json:"apiKey"`
SecretKey string `json:"secretKey"`
}
type AuthToken struct {
AccessToken string `json:"jwtToken"`
}
type CredentialsConfig struct {
ClientID string `json:"zpa_client_id"`
ClientSecret string `json:"zpa_client_secret"`
CustomerID string `json:"zpa_customer_id"`
ZpaCloud string `json:"zpa_cloud"`
}
// Config contains all the configuration data for the API client.
type Config struct {
BaseURL *url.URL
httpClient *http.Client
// The logger writer interface to write logging messages to. Defaults to standard out.
Logger logger.Logger
// Credentials for basic authentication.
ClientID, ClientSecret, Cloud string
// Backoff config
BackoffConf *BackoffConfig
AuthToken *AuthToken
sync.Mutex
UserAgent string
}
/*
NewConfig returns a default configuration for the client.
By default it will try to read the access and te secret from the environment variable.
*/
// Need to implement exponential back off to comply with the API rate limit. https://help.zscaler.com/zpa/about-rate-limiting
// 20 times in a 10 second interval for a GET call.
// 10 times in a 10 second interval for any POST/PUT/DELETE call.
// TODO Add healthCheck method to NewConfig.
func NewConfig(clientID, clientSecret, cloud, userAgent string) (*Config, error) {
logger := logger.GetDefaultLogger(loggerPrefix)
// if creds not provided in TF config, try loading from env vars
if clientID == "" || clientSecret == "" || cloud == "" || userAgent == "" {
clientID = os.Getenv(ZCC_CLIENT_ID)
clientSecret = os.Getenv(ZCC_CLIENT_SECRET)
cloud = os.Getenv(ZCC_CLOUD)
}
// last resort to configuration file:
if clientID == "" || clientSecret == "" {
creds, err := loadCredentialsFromConfig(logger)
if err != nil || creds == nil {
return nil, err
}
clientID = creds.ClientID
clientSecret = creds.ClientSecret
cloud = creds.ZpaCloud
}
baseURL, err := url.Parse(fmt.Sprintf("https://mobileadmin.%s.net/papi", cloud))
if err != nil {
logger.Printf("[ERROR] error occurred while configuring the client: %v", err)
}
return &Config{
BaseURL: baseURL,
Logger: logger,
httpClient: nil,
ClientID: clientID,
ClientSecret: clientSecret,
Cloud: cloud,
BackoffConf: defaultBackoffConf,
UserAgent: userAgent,
}, err
}
func (c *Config) SetBackoffConfig(backoffConf BackoffConfig) {
c.BackoffConf = &backoffConf
}
// loadCredentialsFromConfig Returns the credentials found in a config file.
func loadCredentialsFromConfig(logger logger.Logger) (*CredentialsConfig, error) {
usr, _ := user.Current()
dir := usr.HomeDir
path := filepath.Join(dir, configPath)
logger.Printf("[INFO]Loading configuration file at:%s", path)
file, err := os.Open(path)
if err != nil {
return nil, errors.New("Could not open credentials file, needs to contain one json object with keys: zpa_client_id, zpa_client_secret, zpa_customer_id, and zpa_cloud. " + err.Error())
}
configBytes, err := io.ReadAll(file)
if err != nil {
return nil, err
}
var config CredentialsConfig
err = json.Unmarshal(configBytes, &config)
if err != nil || config.ClientID == "" || config.ClientSecret == "" || config.CustomerID == "" || config.ZpaCloud == "" {
return nil, fmt.Errorf("could not parse credentials file, needs to contain one json object with keys: zpa_client_id, zpa_client_secret, zpa_customer_id, and zpa_cloud. error: %v", err)
}
return &config, nil
}
func (c *Config) GetHTTPClient() *http.Client {
if c.httpClient == nil {
if c.BackoffConf != nil && c.BackoffConf.Enabled {
retryableClient := retryablehttp.NewClient()
retryableClient.RetryWaitMin = time.Second * time.Duration(c.BackoffConf.RetryWaitMinSeconds)
retryableClient.RetryWaitMax = time.Second * time.Duration(c.BackoffConf.RetryWaitMaxSeconds)
retryableClient.RetryMax = c.BackoffConf.MaxNumOfRetries
retryableClient.Logger = c.Logger
retryableClient.HTTPClient.Transport = logging.NewSubsystemLoggingHTTPTransport("gozscaler", retryableClient.HTTPClient.Transport)
retryableClient.CheckRetry = checkRetry
retryableClient.HTTPClient.Timeout = defaultTimeout
c.httpClient = retryableClient.StandardClient()
} else {
c.httpClient = &http.Client{
Timeout: defaultTimeout,
}
}
}
return c.httpClient
}
func containsInt(codes []int, code int) bool {
for _, a := range codes {
if a == code {
return true
}
}
return false
}
// getRetryOnStatusCodes return a list of http status codes we want to apply retry on.
// Return empty slice to enable retry on all connection & server errors.
// Or return []int{429} to retry on only TooManyRequests error.
func getRetryOnStatusCodes() []int {
return []int{http.StatusTooManyRequests}
}
// Used to make http client retry on provided list of response status codes.
func checkRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
// do not retry on context.Canceled or context.DeadlineExceeded
if ctx.Err() != nil {
return false, ctx.Err()
}
if resp != nil && containsInt(getRetryOnStatusCodes(), resp.StatusCode) {
return true, nil
}
return retryablehttp.DefaultRetryPolicy(ctx, resp, err)
}