-
Notifications
You must be signed in to change notification settings - Fork 116
/
examples_test.go
506 lines (447 loc) · 14.1 KB
/
examples_test.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// Copyright 2020-2021 InfluxData, Inc. All rights reserved.
// Use of this source code is governed by MIT
// license that can be found in the LICENSE file.
package api_test
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/influxdata/influxdb-client-go/v2/api"
"github.com/influxdata/influxdb-client-go/v2/api/write"
"github.com/influxdata/influxdb-client-go/v2/domain"
influxdb2 "github.com/influxdata/influxdb-client-go/v2/internal/examples"
)
func ExampleBucketsAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
ctx := context.Background()
// Get Buckets API client
bucketsAPI := client.BucketsAPI()
// Get organization that will own new bucket
org, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org")
if err != nil {
panic(err)
}
// Create a bucket with 1 day retention policy
bucket, err := bucketsAPI.CreateBucketWithName(ctx, org, "bucket-sensors", domain.RetentionRule{EverySeconds: 3600 * 24})
if err != nil {
panic(err)
}
// Update description of the bucket
desc := "Bucket for sensor data"
bucket.Description = &desc
bucket, err = bucketsAPI.UpdateBucket(ctx, bucket)
if err != nil {
panic(err)
}
// Close the client
client.Close()
}
func ExampleWriteAPIBlocking() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get blocking write client
writeAPI := client.WriteAPIBlocking("my-org", "my-bucket")
// write some points
for i := 0; i < 100; i++ {
// create data point
p := write.NewPoint(
"system",
map[string]string{
"id": fmt.Sprintf("rack_%v", i%10),
"vendor": "AWS",
"hostname": fmt.Sprintf("host_%v", i%100),
},
map[string]interface{}{
"temperature": rand.Float64() * 80.0,
"disk_free": rand.Float64() * 1000.0,
"disk_total": (i/10 + 1) * 1000000,
"mem_total": (i/100 + 1) * 10000000,
"mem_free": rand.Uint64(),
},
time.Now())
// write synchronously
err := writeAPI.WritePoint(context.Background(), p)
if err != nil {
panic(err)
}
}
// Ensures background processes finishes
client.Close()
}
func ExampleWriteAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get non-blocking write client
writeAPI := client.WriteAPI("my-org", "my-bucket")
// write some points
for i := 0; i < 100; i++ {
// create point
p := write.NewPoint(
"system",
map[string]string{
"id": fmt.Sprintf("rack_%v", i%10),
"vendor": "AWS",
"hostname": fmt.Sprintf("host_%v", i%100),
},
map[string]interface{}{
"temperature": rand.Float64() * 80.0,
"disk_free": rand.Float64() * 1000.0,
"disk_total": (i/10 + 1) * 1000000,
"mem_total": (i/100 + 1) * 10000000,
"mem_free": rand.Uint64(),
},
time.Now())
// write asynchronously
writeAPI.WritePoint(p)
}
// Force all unwritten data to be sent
writeAPI.Flush()
// Ensures background processes finishes
client.Close()
}
func ExampleWriteAPI_errors() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get non-blocking write client
writeAPI := client.WriteAPI("my-org", "my-bucket")
// Get errors channel
errorsCh := writeAPI.Errors()
// Create go proc for reading and logging errors
go func() {
for err := range errorsCh {
fmt.Printf("write error: %s\n", err.Error())
}
}()
// write some points
for i := 0; i < 100; i++ {
// create point
p := write.NewPointWithMeasurement("stat").
AddTag("id", fmt.Sprintf("rack_%v", i%10)).
AddTag("vendor", "AWS").
AddTag("hostname", fmt.Sprintf("host_%v", i%100)).
AddField("temperature", rand.Float64()*80.0).
AddField("disk_free", rand.Float64()*1000.0).
AddField("disk_total", (i/10+1)*1000000).
AddField("mem_total", (i/100+1)*10000000).
AddField("mem_free", rand.Uint64()).
SetTime(time.Now())
// write asynchronously
writeAPI.WritePoint(p)
}
// Force all unwritten data to be sent
writeAPI.Flush()
// Ensures background processes finishes
client.Close()
}
func ExampleQueryAPI_query() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get query client
queryAPI := client.QueryAPI("my-org")
// get QueryTableResult
result, err := queryAPI.Query(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
if err == nil {
// Iterate over query response
for result.Next() {
// Notice when group key has changed
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
// Access data
fmt.Printf("value: %v\n", result.Record().Value())
}
// check for an error
if result.Err() != nil {
fmt.Printf("query parsing error: %s\n", result.Err().Error())
}
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
func ExampleQueryAPI_queryWithParams() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get query client
queryAPI := client.QueryAPI("my-org")
// Define parameters
parameters := struct {
Start string `json:"start"`
Field string `json:"field"`
Value float64 `json:"value"`
}{
"-1h",
"temperature",
25,
}
// Query with parameters
query := `from(bucket:"my-bucket")
|> range(start: duration(params.start))
|> filter(fn: (r) => r._measurement == "stat")
|> filter(fn: (r) => r._field == params.field)
|> filter(fn: (r) => r._value > params.value)`
// Get result
result, err := queryAPI.QueryWithParams(context.Background(), query, parameters)
if err == nil {
// Iterate over query response
for result.Next() {
// Notice when group key has changed
if result.TableChanged() {
fmt.Printf("table: %s\n", result.TableMetadata().String())
}
// Access data
fmt.Printf("value: %v\n", result.Record().Value())
}
// check for an error
if result.Err() != nil {
fmt.Printf("query parsing error: %s\n", result.Err().Error())
}
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
func ExampleQueryAPI_queryRaw() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get query client
queryAPI := client.QueryAPI("my-org")
// Query and get complete result as a string
// Use default dialect
result, err := queryAPI.QueryRaw(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`, api.DefaultDialect())
if err == nil {
fmt.Println("QueryResult:")
fmt.Println(result)
} else {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
func ExampleOrganizationsAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Get Organizations API client
orgAPI := client.OrganizationsAPI()
// Create new organization
org, err := orgAPI.CreateOrganizationWithName(context.Background(), "org-2")
if err != nil {
panic(err)
}
orgDescription := "My second org "
org.Description = &orgDescription
org, err = orgAPI.UpdateOrganization(context.Background(), org)
if err != nil {
panic(err)
}
// Find user to set owner
user, err := client.UsersAPI().FindUserByName(context.Background(), "user-01")
if err != nil {
panic(err)
}
// Add another owner (first owner is the one who create organization
_, err = orgAPI.AddOwner(context.Background(), org, user)
if err != nil {
panic(err)
}
// Create new user to add to org
newUser, err := client.UsersAPI().CreateUserWithName(context.Background(), "user-02")
if err != nil {
panic(err)
}
// Add new user to organization
_, err = orgAPI.AddMember(context.Background(), org, newUser)
if err != nil {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
func ExampleAuthorizationsAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Find user to grant permission
user, err := client.UsersAPI().FindUserByName(context.Background(), "user-01")
if err != nil {
panic(err)
}
// Find organization
org, err := client.OrganizationsAPI().FindOrganizationByName(context.Background(), "my-org")
if err != nil {
panic(err)
}
// create write permission for buckets
permissionWrite := &domain.Permission{
Action: domain.PermissionActionWrite,
Resource: domain.Resource{
Type: domain.ResourceTypeBuckets,
},
}
// create read permission for buckets
permissionRead := &domain.Permission{
Action: domain.PermissionActionRead,
Resource: domain.Resource{
Type: domain.ResourceTypeBuckets,
},
}
// group permissions
permissions := []domain.Permission{*permissionWrite, *permissionRead}
// create authorization object using info above
auth := &domain.Authorization{
OrgID: org.Id,
Permissions: &permissions,
UserID: user.Id,
}
// grant permission and create token
authCreated, err := client.AuthorizationsAPI().CreateAuthorization(context.Background(), auth)
if err != nil {
panic(err)
}
// Use token
fmt.Println("Token: ", *authCreated.Token)
// Ensures background processes finishes
client.Close()
}
func ExampleUsersAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
// Find organization
org, err := client.OrganizationsAPI().FindOrganizationByName(context.Background(), "my-org")
if err != nil {
panic(err)
}
// Get users API client
usersAPI := client.UsersAPI()
// Create new user
user, err := usersAPI.CreateUserWithName(context.Background(), "user-01")
if err != nil {
panic(err)
}
// Set user password
err = usersAPI.UpdateUserPassword(context.Background(), user, "pass-at-least-8-chars")
if err != nil {
panic(err)
}
// Add user to organization
_, err = client.OrganizationsAPI().AddMember(context.Background(), org, user)
if err != nil {
panic(err)
}
// Ensures background processes finishes
client.Close()
}
func ExampleUsersAPI_signInOut() {
// Create a new client using an InfluxDB server base URL and empty token
client := influxdb2.NewClient("http://localhost:8086", "")
// Always close client at the end
defer client.Close()
ctx := context.Background()
// The first call must be signIn
err := client.UsersAPI().SignIn(ctx, "username", "password")
if err != nil {
panic(err)
}
// Perform some authorized operations
err = client.WriteAPIBlocking("my-org", "my-bucket").WriteRecord(ctx, "test,a=rock,b=local f=1.2,i=-5i")
if err != nil {
panic(err)
}
// Sign out at the end
err = client.UsersAPI().SignOut(ctx)
if err != nil {
panic(err)
}
}
func ExampleLabelsAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
ctx := context.Background()
// Get Labels API client
labelsAPI := client.LabelsAPI()
// Get Organizations API client
orgsAPI := client.OrganizationsAPI()
// Get organization that will own label
myorg, err := orgsAPI.FindOrganizationByName(ctx, "my-org")
if err != nil {
panic(err)
}
labelName := "Active State"
props := map[string]string{"color": "33ffdd", "description": "Marks org active"}
label, err := labelsAPI.CreateLabelWithName(ctx, myorg, labelName, props)
if err != nil {
panic(err)
}
// Change color property
label.Properties.AdditionalProperties = map[string]string{"color": "ff1122"}
label, err = labelsAPI.UpdateLabel(ctx, label)
if err != nil {
panic(err)
}
// Close the client
client.Close()
}
func ExampleDeleteAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
ctx := context.Background()
// Get Delete API client
deleteAPI := client.DeleteAPI()
// Delete last hour data with tag b = static
err := deleteAPI.DeleteWithName(ctx, "org", "my-bucket", time.Now().Add(-time.Hour), time.Now(), "b=static")
if err != nil {
panic(err)
}
// Close the client
client.Close()
}
func ExampleTasksAPI() {
// Create a new client using an InfluxDB server base URL and an authentication token
client := influxdb2.NewClient("http://localhost:8086", "my-token")
ctx := context.Background()
// Get Delete API client
tasksAPI := client.TasksAPI()
// Get organization that will own task
myorg, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org")
if err != nil {
panic(err)
}
// task flux script from https://www.influxdata.com/blog/writing-tasks-and-setting-up-alerts-for-influxdb-cloud/
flux := `fruitCollected = from(bucket: “farming”)
|> range(start: -task.every)
|> filter(fn: (r) => (r._measurement == “totalFruitsCollected))
|> filter(fn: (r) => (r._field == “fruits))
|> group(columns: [“farmName”])
|> aggregateWindow(fn: sum, every: task.every)
|> map(fn: (r) => {
return: _time: r._time, _stop: r._stop, _start: r._start, _measurement: “fruitCollectionRate”, _field: “fruits”, _value: r._value, farmName: farmName,
}
})
fruitCollected
|> to(bucket: “farming”)
`
task, err := tasksAPI.CreateTaskWithEvery(ctx, "fruitCollectedRate", flux, "1h", *myorg.Id)
if err != nil {
panic(err)
}
// Force running a task
run, err := tasksAPI.RunManually(ctx, task)
if err != nil {
panic(err)
}
fmt.Println("Forced run completed on ", *run.FinishedAt, " with status ", *run.Status)
// Print logs
logs, err := tasksAPI.FindRunLogs(ctx, run)
if err != nil {
panic(err)
}
fmt.Println("Log:")
for _, logEvent := range logs {
fmt.Println(" Time:", *logEvent.Time, ", Message: ", *logEvent.Message)
}
// Close the client
client.Close()
}