forked from aiven/aiven-go-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
304 lines (263 loc) · 9.52 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (c) 2017 jelmersnoeck
// Copyright (c) 2018,2019 Aiven, Helsinki, Finland. https://aiven.io/
package aiven
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
// APIURL is the URL we'll use to speak to Aiven. This can be overwritten.
var apiurl = "https://api.aiven.io/v1"
var apiurlV2 = "https://api.aiven.io/v2"
func init() {
value, isSet := os.LookupEnv("AIVEN_WEB_URL")
if isSet {
apiurl = value + "/v1"
apiurlV2 = value + "/v2"
}
}
// Client represents the instance that does all the calls to the Aiven API.
type Client struct {
APIKey string
Client *http.Client
UserAgent string
Projects *ProjectsHandler
ProjectUsers *ProjectUsersHandler
CA *CAHandler
CardsHandler *CardsHandler
ServiceIntegrationEndpoints *ServiceIntegrationEndpointsHandler
ServiceIntegrations *ServiceIntegrationsHandler
ServiceTypes *ServiceTypesHandler
ServiceTask *ServiceTaskHandler
Services *ServicesHandler
ConnectionPools *ConnectionPoolsHandler
Databases *DatabasesHandler
ServiceUsers *ServiceUsersHandler
KafkaACLs *KafkaACLHandler
KafkaSubjectSchemas *KafkaSubjectSchemasHandler
KafkaGlobalSchemaConfig *KafkaGlobalSchemaConfigHandler
KafkaConnectors *KafkaConnectorsHandler
KafkaMirrorMakerReplicationFlow *MirrorMakerReplicationFlowHandler
ElasticsearchACLs *ElasticSearchACLsHandler
KafkaTopics *KafkaTopicsHandler
VPCs *VPCsHandler
VPCPeeringConnections *VPCPeeringConnectionsHandler
Accounts *AccountsHandler
AccountTeams *AccountTeamsHandler
AccountTeamMembers *AccountTeamMembersHandler
AccountTeamProjects *AccountTeamProjectsHandler
AccountAuthentications *AccountAuthenticationsHandler
AccountTeamInvites *AccountTeamInvitesHandler
TransitGatewayVPCAttachment *TransitGatewayVPCAttachmentHandler
BillingGroup *BillingGroupHandler
AWSPrivatelink *AWSPrivatelinkHandler
FlinkJobs *FlinkJobHandler
FlinkTables *FlinkTableHandler
AzurePrivatelink *AzurePrivatelinkHandler
StaticIPs *StaticIPsHandler
ClickhouseDatabase *ClickhouseDatabaseHandler
ClickhouseUser *ClickhouseUserHandler
ClickHouseQuery *ClickhouseQueryHandler
}
// GetUserAgentOrDefault configures a default userAgent value, if one has not been provided.
func GetUserAgentOrDefault(userAgent string) string {
if userAgent != "" {
return userAgent
}
return "aiven-go-client/" + Version()
}
// NewMFAUserClient creates a new client based on email, one-time password and password.
func NewMFAUserClient(email, otp, password string, userAgent string) (*Client, error) {
c := &Client{
Client: buildHttpClient(),
UserAgent: GetUserAgentOrDefault(userAgent),
}
bts, err := c.doPostRequest("/userauth", authRequest{email, otp, password})
if err != nil {
return nil, err
}
var r authResponse
if err := checkAPIResponse(bts, &r); err != nil {
return nil, err
}
return NewTokenClient(r.Token, userAgent)
}
// NewUserClient creates a new client based on email and password.
func NewUserClient(email, password string, userAgent string) (*Client, error) {
return NewMFAUserClient(email, "", password, userAgent)
}
// NewTokenClient creates a new client based on a given token.
func NewTokenClient(key string, userAgent string) (*Client, error) {
c := &Client{
APIKey: key,
Client: buildHttpClient(),
UserAgent: GetUserAgentOrDefault(userAgent),
}
c.Init()
return c, nil
}
// buildHttpClient it builds http.Client, if environment variable AIVEN_CA_CERT
// contains a path to a valid CA certificate HTTPS client will be configured to use it
func buildHttpClient() *http.Client {
caFilename := os.Getenv("AIVEN_CA_CERT")
if caFilename == "" {
return &http.Client{}
}
// Load CA cert
caCert, err := ioutil.ReadFile(caFilename)
if err != nil {
log.Fatal("cannot load ca cert: %w", err)
}
// Append CA cert to the system pool
caCertPool, _ := x509.SystemCertPool()
if caCertPool == nil {
caCertPool = x509.NewCertPool()
}
if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
log.Println("[WARNING] No certs appended, using system certs only")
}
// Setup HTTPS client
tlsConfig := &tls.Config{
RootCAs: caCertPool,
}
transport := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: transport}
return client
}
// Init initializes the client and sets up all the handlers.
func (c *Client) Init() {
c.Projects = &ProjectsHandler{c}
c.ProjectUsers = &ProjectUsersHandler{c}
c.CA = &CAHandler{c}
c.CardsHandler = &CardsHandler{c}
c.ServiceIntegrationEndpoints = &ServiceIntegrationEndpointsHandler{c}
c.ServiceIntegrations = &ServiceIntegrationsHandler{c}
c.ServiceTypes = &ServiceTypesHandler{c}
c.ServiceTask = &ServiceTaskHandler{c}
c.Services = &ServicesHandler{c}
c.ConnectionPools = &ConnectionPoolsHandler{c}
c.Databases = &DatabasesHandler{c}
c.ServiceUsers = &ServiceUsersHandler{c}
c.KafkaACLs = &KafkaACLHandler{c}
c.KafkaSubjectSchemas = &KafkaSubjectSchemasHandler{c}
c.KafkaGlobalSchemaConfig = &KafkaGlobalSchemaConfigHandler{c}
c.KafkaConnectors = &KafkaConnectorsHandler{c}
c.KafkaMirrorMakerReplicationFlow = &MirrorMakerReplicationFlowHandler{c}
c.ElasticsearchACLs = &ElasticSearchACLsHandler{c}
c.KafkaTopics = &KafkaTopicsHandler{c}
c.VPCs = &VPCsHandler{c}
c.VPCPeeringConnections = &VPCPeeringConnectionsHandler{c}
c.Accounts = &AccountsHandler{c}
c.AccountTeams = &AccountTeamsHandler{c}
c.AccountTeamMembers = &AccountTeamMembersHandler{c}
c.AccountTeamProjects = &AccountTeamProjectsHandler{c}
c.AccountAuthentications = &AccountAuthenticationsHandler{c}
c.AccountTeamInvites = &AccountTeamInvitesHandler{c}
c.TransitGatewayVPCAttachment = &TransitGatewayVPCAttachmentHandler{c}
c.BillingGroup = &BillingGroupHandler{c}
c.AWSPrivatelink = &AWSPrivatelinkHandler{c}
c.FlinkJobs = &FlinkJobHandler{c}
c.FlinkTables = &FlinkTableHandler{c}
c.AzurePrivatelink = &AzurePrivatelinkHandler{c}
c.StaticIPs = &StaticIPsHandler{c}
c.ClickhouseDatabase = &ClickhouseDatabaseHandler{c}
c.ClickhouseUser = &ClickhouseUserHandler{c}
c.ClickHouseQuery = &ClickhouseQueryHandler{c}
}
func (c *Client) doGetRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("GET", endpoint, req, 1)
}
func (c *Client) doPutRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("PUT", endpoint, req, 1)
}
func (c *Client) doPostRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("POST", endpoint, req, 1)
}
func (c *Client) doPatchRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("PATCH", endpoint, req, 1)
}
func (c *Client) doDeleteRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("DELETE", endpoint, req, 1)
}
func (c *Client) doV2GetRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("GET", endpoint, req, 2)
}
func (c *Client) doV2PutRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("PUT", endpoint, req, 2)
}
func (c *Client) doV2PostRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("POST", endpoint, req, 2)
}
func (c *Client) doV2DeleteRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("DELETE", endpoint, req, 2)
}
func (c *Client) doRequest(method, uri string, body interface{}, apiVersion int) ([]byte, error) {
var bts []byte
if body != nil {
var err error
bts, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
var url string
switch apiVersion {
case 1:
url = endpoint(uri)
case 2:
url = endpointV2(uri)
default:
return nil, fmt.Errorf("aiven API apiVersion `%d` is not supported", apiVersion)
}
retryCount := 2
for {
req, err := http.NewRequest(method, url, bytes.NewBuffer(bts))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Authorization", "aivenv1 "+c.APIKey)
// TODO: BAD hack to get around pagination in most cases
// we should implement this properly at some point but for now
// that should be its own issue
query := req.URL.Query()
query.Add("limit", "999")
req.URL.RawQuery = query.Encode()
rsp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer func() {
err := rsp.Body.Close()
if err != nil {
log.Printf("[WARNING] cannot close response body: %s \n", err)
}
}()
responseBody, err := ioutil.ReadAll(rsp.Body)
// Retry a few times in case of request timeout or server error for GET requests
if (rsp.StatusCode == 408 || rsp.StatusCode >= 500) && retryCount > 0 && method == "GET" {
retryCount--
continue
} else if rsp.StatusCode < 200 || rsp.StatusCode >= 300 {
return nil, Error{Message: string(responseBody), Status: rsp.StatusCode}
}
return responseBody, err
}
}
func endpoint(uri string) string {
return apiurl + uri
}
func endpointV2(uri string) string {
return apiurlV2 + uri
}
// ToStringPointer converts string to a string pointer
func ToStringPointer(s string) *string {
return &s
}