-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiclient.go
194 lines (177 loc) · 5.03 KB
/
apiclient.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
package cmlclient
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"sync/atomic"
"syscall"
)
const (
contentType string = "application/json"
apiBase string = "/api/v0/"
authAPI string = "auth_extended"
authokAPI string = "authok"
systeminfoAPI string = "system_information"
)
func setTokenHeader(req *http.Request, token string) {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
func (c *Client) apiRequest(ctx context.Context, method string, path string, data io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(
ctx,
method,
fmt.Sprintf("%s%s%s", c.host, apiBase, path),
data,
)
if err != nil {
return nil, err
}
// set headers (this avoids a loop when actually authenticating)
if path != authAPI && len(c.apiToken) > 0 {
setTokenHeader(req, c.apiToken)
}
req.Header.Set("Accept", contentType)
req.Header.Set("Cache-Control", "no-cache, no-store, must-revalidate")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Expires", "0")
// req.Header.Set("Connection", "close")
if data != nil {
req.Header.Set("Content-Type", contentType)
}
return req, nil
}
func (c *Client) doAPI(ctx context.Context, req *http.Request, depth int32) ([]byte, error) {
if c.state.get() == stateInitial {
c.state.set(stateCheckVersion)
c.compatibilityErr = c.versionCheck(ctx, depth)
c.state.set(stateAuthRequired)
}
if c.compatibilityErr != nil {
return nil, c.compatibilityErr
}
if c.state.get() != stateAuthenticated && c.authRequired(req.URL) {
log.Println("needs auth")
c.state.set(stateAuthenticating)
if err := c.jsonGet(ctx, authokAPI, nil, depth); err != nil {
return nil, err
}
}
retry:
if c.state.get() == stateAuthenticated && len(c.apiToken) > 0 {
setTokenHeader(req, c.apiToken)
}
res, err := c.httpClient.Do(req)
if err != nil {
if urlError, ok := (err).(*url.Error); ok {
if urlError.Timeout() || urlError.Temporary() {
return nil, ErrSystemNotReady
}
}
if errors.Is(err, syscall.ECONNREFUSED) {
return nil, ErrSystemNotReady
}
if errors.Is(err, syscall.EHOSTUNREACH) {
return nil, ErrSystemNotReady
}
if errors.Is(err, syscall.ENETUNREACH) {
return nil, ErrSystemNotReady
}
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// no authorization and not retrying already
if res.StatusCode == http.StatusUnauthorized {
invalid_token := len(c.apiToken) > 0
c.apiToken = ""
log.Println("need to authenticate")
c.state.set(stateAuthRequired)
if !c.userpass.valid() {
errmsg := "no credentials provided"
if invalid_token {
errmsg = "invalid token but " + errmsg
}
return nil, errors.New(errmsg)
}
err = c.authenticate(ctx, c.userpass, depth)
if err != nil {
c.state.set(stateAuthRequired)
return nil, err
}
c.state.set(stateAuthenticated)
goto retry
}
switch res.StatusCode {
case http.StatusOK:
fallthrough
case http.StatusNoContent:
fallthrough
case http.StatusCreated:
return body, err
case http.StatusBadGateway:
fallthrough
case http.StatusServiceUnavailable:
fallthrough
case http.StatusGatewayTimeout:
return nil, ErrSystemNotReady
}
return nil, fmt.Errorf(
"status: %d, %s",
res.StatusCode, strings.TrimSpace(string(body)),
)
}
/* technically, only jsonGet and jsonPost need the depth as they are the only
ones being called recursively in doAPI. For consistency, they are added to the
other functions as well.
*/
func (c *Client) jsonGet(ctx context.Context, api string, result any, depth int32) error {
return c.jsonReq(ctx, http.MethodGet, api, nil, result, depth)
}
func (c *Client) jsonPut(ctx context.Context, api string, depth int32) error {
return c.jsonReq(ctx, http.MethodPut, api, nil, nil, depth)
}
func (c *Client) jsonPost(ctx context.Context, api string, data io.Reader, result any, depth int32) error {
return c.jsonReq(ctx, http.MethodPost, api, data, result, depth)
}
func (c *Client) jsonPatch(ctx context.Context, api string, data io.Reader, result any, depth int32) error {
return c.jsonReq(ctx, http.MethodPatch, api, data, result, depth)
}
func (c *Client) jsonDelete(ctx context.Context, api string, depth int32) error {
return c.jsonReq(ctx, http.MethodDelete, api, nil, nil, depth)
}
func (c *Client) jsonReq(ctx context.Context, method, api string, data io.Reader, result any, depth int32) error {
// during initialization, the API client does API calls recursively which
// leads to all sorts of nasty race problems. The below basically prevents
// any additional API calls when recursion happens during initialization or
// re-authentication.
if c.state.get() != stateAuthenticated && depth == 0 {
atomic.AddInt32(&depth, 1)
c.mu.Lock()
defer c.mu.Unlock()
}
req, err := c.apiRequest(ctx, method, api, data)
if err != nil {
return err
}
res, err := c.doAPI(ctx, req, depth)
if err != nil {
return err
}
if result == nil {
return nil
}
err = json.Unmarshal(res, result)
if err != nil {
return err
}
return nil
}