forked from influxdata/influxdb-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
282 lines (258 loc) · 9.24 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
// Copyright 2020 InfluxData, Inc. All rights reserved.
// Use of this source code is governed by MIT
// license that can be found in the LICENSE file.
// Package influxdb2 provides API for using InfluxDB client in Go.
// It's intended to use with InfluxDB 2 server. WriteAPI, QueryAPI and Health work also with InfluxDB 1.8
package influxdb2
import (
"context"
"errors"
"strings"
"sync"
"github.com/influxdata/influxdb-client-go/v2/api"
"github.com/influxdata/influxdb-client-go/v2/api/http"
"github.com/influxdata/influxdb-client-go/v2/domain"
ilog "github.com/influxdata/influxdb-client-go/v2/internal/log"
"github.com/influxdata/influxdb-client-go/v2/log"
)
// Client provides API to communicate with InfluxDBServer.
// There two APIs for writing, WriteAPI and WriteAPIBlocking.
// WriteAPI provides asynchronous, non-blocking, methods for writing time series data.
// WriteAPIBlocking provides blocking methods for writing time series data.
type Client interface {
// Setup sends request to initialise new InfluxDB server with user, org and bucket, and data retention period
// and returns details about newly created entities along with the authorization object.
// Retention period of zero will result to infinite retention.
Setup(ctx context.Context, username, password, org, bucket string, retentionPeriodHours int) (*domain.OnboardingResponse, error)
// Ready checks InfluxDB server is running. It doesn't validate authentication params.
Ready(ctx context.Context) (bool, error)
// Health returns an InfluxDB server health check result. Read the HealthCheck.Status field to get server status.
// Health doesn't validate authentication params.
Health(ctx context.Context) (*domain.HealthCheck, error)
// Close ensures all ongoing asynchronous write clients finish.
// Also closes all idle connections, in case of HTTP client was created internally.
Close()
// Options returns the options associated with client
Options() *Options
// ServerURL returns the url of the server url client talks to
ServerURL() string
// HTTPService returns underlying HTTP service object used by client
HTTPService() http.Service
// WriteAPI returns the asynchronous, non-blocking, Write client
WriteAPI(org, bucket string) api.WriteAPI
// WriteAPIBlocking returns the synchronous, blocking, Write client
WriteAPIBlocking(org, bucket string) api.WriteAPIBlocking
// QueryAPI returns Query client
QueryAPI(org string) api.QueryAPI
// AuthorizationsAPI returns Authorizations API client.
AuthorizationsAPI() api.AuthorizationsAPI
// OrganizationsAPI returns Organizations API client
OrganizationsAPI() api.OrganizationsAPI
// UsersAPI returns Users API client.
UsersAPI() api.UsersAPI
// DeleteAPI returns Delete API client
DeleteAPI() api.DeleteAPI
// BucketsAPI returns Buckets API client
BucketsAPI() api.BucketsAPI
// LabelsAPI returns Labels API client
LabelsAPI() api.LabelsAPI
}
// clientImpl implements Client interface
type clientImpl struct {
serverURL string
options *Options
writeAPIs map[string]api.WriteAPI
syncWriteAPIs map[string]api.WriteAPIBlocking
lock sync.Mutex
httpService http.Service
apiClient *domain.ClientWithResponses
authAPI api.AuthorizationsAPI
orgAPI api.OrganizationsAPI
usersAPI api.UsersAPI
deleteAPI api.DeleteAPI
bucketsAPI api.BucketsAPI
labelsAPI api.LabelsAPI
}
// NewClient creates Client for connecting to given serverURL with provided authentication token, with the default options.
// serverURL is the InfluxDB server base URL, e.g. http://localhost:9999,
// authToken is an authentication token. It can be empty in case of connecting to newly installed InfluxDB server, which has not been set up yet.
// In such case, calling Setup() will set the authentication token.
func NewClient(serverURL string, authToken string) Client {
return NewClientWithOptions(serverURL, authToken, DefaultOptions())
}
// NewClientWithOptions creates Client for connecting to given serverURL with provided authentication token
// and configured with custom Options.
// serverURL is the InfluxDB server base URL, e.g. http://localhost:9999,
// authToken is an authentication token. It can be empty in case of connecting to newly installed InfluxDB server, which has not been set up yet.
// In such case, calling Setup() will set authentication token
func NewClientWithOptions(serverURL string, authToken string, options *Options) Client {
normServerURL := serverURL
if !strings.HasSuffix(normServerURL, "/") {
// For subsequent path parts concatenation, url has to end with '/'
normServerURL = serverURL + "/"
}
authorization := ""
if len(authToken) > 0 {
authorization = "Token " + authToken
}
service := http.NewService(normServerURL, authorization, options.httpOptions)
client := &clientImpl{
serverURL: serverURL,
options: options,
writeAPIs: make(map[string]api.WriteAPI, 5),
syncWriteAPIs: make(map[string]api.WriteAPIBlocking, 5),
httpService: service,
apiClient: domain.NewClientWithResponses(service),
}
if log.Log != nil {
log.Log.SetLogLevel(options.LogLevel())
}
ilog.Infof("Using URL '%s', token '%s'", serverURL, authToken)
return client
}
func (c *clientImpl) Options() *Options {
return c.options
}
func (c *clientImpl) ServerURL() string {
return c.serverURL
}
func (c *clientImpl) HTTPService() http.Service {
return c.httpService
}
func (c *clientImpl) Ready(ctx context.Context) (bool, error) {
params := &domain.GetReadyParams{}
response, err := c.apiClient.GetReadyWithResponse(ctx, params)
if err != nil {
return false, err
}
if response.JSONDefault != nil {
return false, domain.DomainErrorToError(response.JSONDefault, response.StatusCode())
}
return true, nil
}
func (c *clientImpl) Setup(ctx context.Context, username, password, org, bucket string, retentionPeriodHours int) (*domain.OnboardingResponse, error) {
if username == "" || password == "" {
return nil, errors.New("a username and password is required for a setup")
}
c.lock.Lock()
defer c.lock.Unlock()
params := &domain.PostSetupParams{}
body := &domain.PostSetupJSONRequestBody{
Bucket: bucket,
Org: org,
Password: &password,
RetentionPeriodHrs: &retentionPeriodHours,
Username: username,
}
response, err := c.apiClient.PostSetupWithResponse(ctx, params, *body)
if err != nil {
return nil, err
}
if response.JSONDefault != nil {
return nil, domain.DomainErrorToError(response.JSONDefault, response.StatusCode())
}
c.httpService.SetAuthorization("Token " + *response.JSON201.Auth.Token)
return response.JSON201, nil
}
func (c *clientImpl) Health(ctx context.Context) (*domain.HealthCheck, error) {
params := &domain.GetHealthParams{}
response, err := c.apiClient.GetHealthWithResponse(ctx, params)
if err != nil {
return nil, err
}
if response.JSONDefault != nil {
return nil, domain.DomainErrorToError(response.JSONDefault, response.StatusCode())
}
if response.JSON503 != nil {
//unhealthy server
return response.JSON503, nil
}
return response.JSON200, nil
}
func createKey(org, bucket string) string {
return org + "\t" + bucket
}
func (c *clientImpl) WriteAPI(org, bucket string) api.WriteAPI {
c.lock.Lock()
defer c.lock.Unlock()
key := createKey(org, bucket)
if _, ok := c.writeAPIs[key]; !ok {
w := api.NewWriteAPI(org, bucket, c.httpService, c.options.writeOptions)
c.writeAPIs[key] = w
}
return c.writeAPIs[key]
}
func (c *clientImpl) WriteAPIBlocking(org, bucket string) api.WriteAPIBlocking {
c.lock.Lock()
defer c.lock.Unlock()
key := createKey(org, bucket)
if _, ok := c.syncWriteAPIs[key]; !ok {
w := api.NewWriteAPIBlocking(org, bucket, c.httpService, c.options.writeOptions)
c.syncWriteAPIs[key] = w
}
return c.syncWriteAPIs[key]
}
func (c *clientImpl) Close() {
for key, w := range c.writeAPIs {
wa := w.(*api.WriteAPIImpl)
wa.Close()
delete(c.writeAPIs, key)
}
for key := range c.syncWriteAPIs {
delete(c.syncWriteAPIs, key)
}
if c.options.HTTPOptions().OwnHTTPClient() {
c.options.HTTPOptions().HTTPClient().CloseIdleConnections()
}
}
func (c *clientImpl) QueryAPI(org string) api.QueryAPI {
return api.NewQueryAPI(org, c.httpService)
}
func (c *clientImpl) AuthorizationsAPI() api.AuthorizationsAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.authAPI == nil {
c.authAPI = api.NewAuthorizationsAPI(c.apiClient)
}
return c.authAPI
}
func (c *clientImpl) OrganizationsAPI() api.OrganizationsAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.orgAPI == nil {
c.orgAPI = api.NewOrganizationsAPI(c.apiClient)
}
return c.orgAPI
}
func (c *clientImpl) UsersAPI() api.UsersAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.usersAPI == nil {
c.usersAPI = api.NewUsersAPI(c.apiClient, c.httpService, c.options.HTTPClient())
}
return c.usersAPI
}
func (c *clientImpl) DeleteAPI() api.DeleteAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.deleteAPI == nil {
c.deleteAPI = api.NewDeleteAPI(c.apiClient)
}
return c.deleteAPI
}
func (c *clientImpl) BucketsAPI() api.BucketsAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.bucketsAPI == nil {
c.bucketsAPI = api.NewBucketsAPI(c.apiClient)
}
return c.bucketsAPI
}
func (c *clientImpl) LabelsAPI() api.LabelsAPI {
c.lock.Lock()
defer c.lock.Unlock()
if c.labelsAPI == nil {
c.labelsAPI = api.NewLabelsAPI(c.apiClient)
}
return c.labelsAPI
}