-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
285 lines (230 loc) · 6.87 KB
/
client.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package metadata
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"path"
"strconv"
"time"
"github.com/go-resty/resty/v2"
)
const (
APIHost = "169.254.169.254"
APIProto = "http"
APIVersion = "v1"
)
type Logger = resty.Logger
// Client represents an instance of a Linode Metadata Service client.
type Client struct {
managedTokenExpiry time.Time
resty *resty.Client
apiBaseURL string
apiProtocol string
apiVersion string
userAgent string
managedTokenOpts []TokenOption
managedToken bool
}
// NewClient creates a new Metadata API client configured
// with the given options.
func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error) {
clientOpts := clientCreateConfig{
HTTPClient: nil,
BaseURLOverride: "",
VersionOverride: "",
UserAgentPrefix: "",
ManagedToken: true,
StartingToken: "",
}
for _, opt := range opts {
opt(&clientOpts)
}
var result Client
result.managedToken = clientOpts.ManagedToken
result.managedTokenOpts = clientOpts.ManagedTokenOpts
userAgent := DefaultUserAgent
if clientOpts.BaseURLOverride != "" {
result.SetBaseURL(clientOpts.BaseURLOverride)
}
if clientOpts.VersionOverride != "" {
result.SetVersion(clientOpts.VersionOverride)
}
if clientOpts.UserAgentPrefix != "" {
userAgent = fmt.Sprintf("%s %s", clientOpts.UserAgentPrefix, userAgent)
}
if clientOpts.HTTPClient != nil {
result.resty = resty.NewWithClient(clientOpts.HTTPClient)
} else {
result.resty = resty.New()
}
if debugEnv, ok := os.LookupEnv("LINODE_DEBUG"); ok {
debugBool, err := strconv.ParseBool(debugEnv)
if err != nil {
return nil, fmt.Errorf("failed to parse debug bool: %s", err)
}
result.resty.SetDebug(debugBool)
}
result.updateHostURL()
result.setUserAgent(userAgent)
if clientOpts.ManagedToken && clientOpts.StartingToken == "" {
if _, err := result.RefreshToken(ctx, result.managedTokenOpts...); err != nil {
return nil, fmt.Errorf("failed to refresh metadata token: %s", err)
}
} else if clientOpts.StartingToken != "" {
result.UseToken(clientOpts.StartingToken)
}
result.resty.SetDebug(clientOpts.Debug)
if clientOpts.DebugLogger != nil {
result.resty.SetLogger(clientOpts.DebugLogger)
}
result.resty.OnBeforeRequest(result.middlewareTokenRefresh)
return &result, nil
}
// SetBaseURL configures the target URL for metadata API this client accesses.
func (c *Client) SetBaseURL(baseURL string) *Client {
baseURLPath, _ := url.Parse(baseURL)
c.apiBaseURL = path.Join(baseURLPath.Host, baseURLPath.Path)
c.apiProtocol = baseURLPath.Scheme
c.updateHostURL()
return c
}
// SetVersion configures the target metadata API version for this client.
func (c *Client) SetVersion(version string) *Client {
c.apiVersion = version
c.updateHostURL()
return c
}
func (c *Client) updateHostURL() {
apiProto := APIProto
baseURL := APIHost
apiVersion := APIVersion
if c.apiBaseURL != "" {
baseURL = c.apiBaseURL
}
if c.apiVersion != "" {
apiVersion = c.apiVersion
}
if c.apiProtocol != "" {
apiProto = c.apiProtocol
}
c.resty.SetBaseURL(fmt.Sprintf("%s://%s/%s", apiProto, baseURL, apiVersion))
}
// middlewareTokenRefresh handles automatically refreshing managed tokens.
func (c *Client) middlewareTokenRefresh(_ *resty.Client, r *resty.Request) error {
// Don't run this middleware when generating tokens
if r.URL == "token" {
return nil
}
if !c.managedToken || time.Now().Before(c.managedTokenExpiry) {
return nil
}
// Token needs to be refreshed
if _, err := c.RefreshToken(r.Context(), c.managedTokenOpts...); err != nil {
return err
}
return nil
}
// R wraps resty's R method
func (c *Client) R(ctx context.Context) *resty.Request {
return c.resty.R().
ExpectContentType("application/json").
SetHeader("Content-Type", "application/json").
SetContext(ctx).
SetError(APIError{})
}
func (c *Client) setUserAgent(userAgent string) *Client {
c.userAgent = userAgent
c.resty.SetHeader("User-Agent", c.userAgent)
return c
}
type clientCreateConfig struct {
HTTPClient *http.Client
BaseURLOverride string
VersionOverride string
UserAgentPrefix string
ManagedToken bool
ManagedTokenOpts []TokenOption
StartingToken string
Debug bool
DebugLogger Logger
}
// ClientOption is an option that can be used
// during client creation.
type ClientOption func(options *clientCreateConfig)
// ClientWithHTTPClient configures the underlying HTTP client
// to communicate with the Metadata API.
func ClientWithHTTPClient(client *http.Client) ClientOption {
return func(options *clientCreateConfig) {
options.HTTPClient = client
}
}
// ClientWithBaseURL configures the target host of the
// Metadata API this client points to.
// Default: "169.254.169.254"
func ClientWithBaseURL(baseURL string) ClientOption {
return func(options *clientCreateConfig) {
options.BaseURLOverride = baseURL
}
}
// ClientWithVersion configures the Metadata API version this
// client should target.
// Default: "v1"
func ClientWithVersion(version string) ClientOption {
return func(options *clientCreateConfig) {
options.VersionOverride = version
}
}
// ClientWithUAPrefix configures the prefix for user agents
// on API requests made by this client.
func ClientWithUAPrefix(uaPrefix string) ClientOption {
return func(options *clientCreateConfig) {
options.UserAgentPrefix = uaPrefix
}
}
// ClientWithManagedToken configures the metadata client
// to automatically generate and refresh the API token
// for the Metadata client.
func ClientWithManagedToken(opts ...TokenOption) ClientOption {
return func(options *clientCreateConfig) {
options.ManagedToken = true
options.ManagedTokenOpts = opts
}
}
// ClientWithoutManagedToken configures the metadata client
// to disable automatic token management.
func ClientWithoutManagedToken() ClientOption {
return func(options *clientCreateConfig) {
options.ManagedToken = false
}
}
// ClientWithToken configures the starting token
// for the metadata client.
// If this option is specified and managed tokens
// are enabled for a client, the client will not
// generate an initial Metadata API token.
func ClientWithToken(token string) ClientOption {
return func(options *clientCreateConfig) {
options.StartingToken = token
}
}
// ClientWithDebug enables debug mode for the metadata client.
// If this option is specified, all metadata service API requests
// and responses will be written to the client logger (default: stderr).
//
// To override the client logger, refer to ClientWithLogger.
func ClientWithDebug() ClientOption {
return func(options *clientCreateConfig) {
options.Debug = true
}
}
// ClientWithLogger specifies the logger that should be used
// when outputting debug logs. The logger argument should implement
// the Logger interface.
// Default: stderr
func ClientWithLogger(logger Logger) ClientOption {
return func(options *clientCreateConfig) {
options.DebugLogger = logger
}
}