examples_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. // Copyright 2020-2021 InfluxData, Inc. All rights reserved.
  2. // Use of this source code is governed by MIT
  3. // license that can be found in the LICENSE file.
  4. package api_test
  5. import (
  6. "context"
  7. "fmt"
  8. "math/rand"
  9. "time"
  10. "github.com/influxdata/influxdb-client-go/v2/api"
  11. "github.com/influxdata/influxdb-client-go/v2/api/write"
  12. "github.com/influxdata/influxdb-client-go/v2/domain"
  13. influxdb2 "github.com/influxdata/influxdb-client-go/v2/internal/examples"
  14. )
  15. func ExampleBucketsAPI() {
  16. // Create a new client using an InfluxDB server base URL and an authentication token
  17. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  18. ctx := context.Background()
  19. // Get Buckets API client
  20. bucketsAPI := client.BucketsAPI()
  21. // Get organization that will own new bucket
  22. org, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org")
  23. if err != nil {
  24. panic(err)
  25. }
  26. // Create a bucket with 1 day retention policy
  27. bucket, err := bucketsAPI.CreateBucketWithName(ctx, org, "bucket-sensors", domain.RetentionRule{EverySeconds: 3600 * 24})
  28. if err != nil {
  29. panic(err)
  30. }
  31. // Update description of the bucket
  32. desc := "Bucket for sensor data"
  33. bucket.Description = &desc
  34. bucket, err = bucketsAPI.UpdateBucket(ctx, bucket)
  35. if err != nil {
  36. panic(err)
  37. }
  38. // Close the client
  39. client.Close()
  40. }
  41. func ExampleWriteAPIBlocking() {
  42. // Create a new client using an InfluxDB server base URL and an authentication token
  43. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  44. // Get blocking write client
  45. writeAPI := client.WriteAPIBlocking("my-org", "my-bucket")
  46. // write some points
  47. for i := 0; i < 100; i++ {
  48. // create data point
  49. p := write.NewPoint(
  50. "system",
  51. map[string]string{
  52. "id": fmt.Sprintf("rack_%v", i%10),
  53. "vendor": "AWS",
  54. "hostname": fmt.Sprintf("host_%v", i%100),
  55. },
  56. map[string]interface{}{
  57. "temperature": rand.Float64() * 80.0,
  58. "disk_free": rand.Float64() * 1000.0,
  59. "disk_total": (i/10 + 1) * 1000000,
  60. "mem_total": (i/100 + 1) * 10000000,
  61. "mem_free": rand.Uint64(),
  62. },
  63. time.Now())
  64. // write synchronously
  65. err := writeAPI.WritePoint(context.Background(), p)
  66. if err != nil {
  67. panic(err)
  68. }
  69. }
  70. // Ensures background processes finishes
  71. client.Close()
  72. }
  73. func ExampleWriteAPI() {
  74. // Create a new client using an InfluxDB server base URL and an authentication token
  75. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  76. // Get non-blocking write client
  77. writeAPI := client.WriteAPI("my-org", "my-bucket")
  78. // write some points
  79. for i := 0; i < 100; i++ {
  80. // create point
  81. p := write.NewPoint(
  82. "system",
  83. map[string]string{
  84. "id": fmt.Sprintf("rack_%v", i%10),
  85. "vendor": "AWS",
  86. "hostname": fmt.Sprintf("host_%v", i%100),
  87. },
  88. map[string]interface{}{
  89. "temperature": rand.Float64() * 80.0,
  90. "disk_free": rand.Float64() * 1000.0,
  91. "disk_total": (i/10 + 1) * 1000000,
  92. "mem_total": (i/100 + 1) * 10000000,
  93. "mem_free": rand.Uint64(),
  94. },
  95. time.Now())
  96. // write asynchronously
  97. writeAPI.WritePoint(p)
  98. }
  99. // Force all unwritten data to be sent
  100. writeAPI.Flush()
  101. // Ensures background processes finishes
  102. client.Close()
  103. }
  104. func ExampleWriteAPI_errors() {
  105. // Create a new client using an InfluxDB server base URL and an authentication token
  106. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  107. // Get non-blocking write client
  108. writeAPI := client.WriteAPI("my-org", "my-bucket")
  109. // Get errors channel
  110. errorsCh := writeAPI.Errors()
  111. // Create go proc for reading and logging errors
  112. go func() {
  113. for err := range errorsCh {
  114. fmt.Printf("write error: %s\n", err.Error())
  115. }
  116. }()
  117. // write some points
  118. for i := 0; i < 100; i++ {
  119. // create point
  120. p := write.NewPointWithMeasurement("stat").
  121. AddTag("id", fmt.Sprintf("rack_%v", i%10)).
  122. AddTag("vendor", "AWS").
  123. AddTag("hostname", fmt.Sprintf("host_%v", i%100)).
  124. AddField("temperature", rand.Float64()*80.0).
  125. AddField("disk_free", rand.Float64()*1000.0).
  126. AddField("disk_total", (i/10+1)*1000000).
  127. AddField("mem_total", (i/100+1)*10000000).
  128. AddField("mem_free", rand.Uint64()).
  129. SetTime(time.Now())
  130. // write asynchronously
  131. writeAPI.WritePoint(p)
  132. }
  133. // Force all unwritten data to be sent
  134. writeAPI.Flush()
  135. // Ensures background processes finishes
  136. client.Close()
  137. }
  138. func ExampleQueryAPI_query() {
  139. // Create a new client using an InfluxDB server base URL and an authentication token
  140. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  141. // Get query client
  142. queryAPI := client.QueryAPI("my-org")
  143. // get QueryTableResult
  144. result, err := queryAPI.Query(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
  145. if err == nil {
  146. // Iterate over query response
  147. for result.Next() {
  148. // Notice when group key has changed
  149. if result.TableChanged() {
  150. fmt.Printf("table: %s\n", result.TableMetadata().String())
  151. }
  152. // Access data
  153. fmt.Printf("value: %v\n", result.Record().Value())
  154. }
  155. // check for an error
  156. if result.Err() != nil {
  157. fmt.Printf("query parsing error: %s\n", result.Err().Error())
  158. }
  159. } else {
  160. panic(err)
  161. }
  162. // Ensures background processes finishes
  163. client.Close()
  164. }
  165. func ExampleQueryAPI_queryWithParams() {
  166. // Create a new client using an InfluxDB server base URL and an authentication token
  167. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  168. // Get query client
  169. queryAPI := client.QueryAPI("my-org")
  170. // Define parameters
  171. parameters := struct {
  172. Start string `json:"start"`
  173. Field string `json:"field"`
  174. Value float64 `json:"value"`
  175. }{
  176. "-1h",
  177. "temperature",
  178. 25,
  179. }
  180. // Query with parameters
  181. query := `from(bucket:"my-bucket")
  182. |> range(start: duration(params.start))
  183. |> filter(fn: (r) => r._measurement == "stat")
  184. |> filter(fn: (r) => r._field == params.field)
  185. |> filter(fn: (r) => r._value > params.value)`
  186. // Get result
  187. result, err := queryAPI.QueryWithParams(context.Background(), query, parameters)
  188. if err == nil {
  189. // Iterate over query response
  190. for result.Next() {
  191. // Notice when group key has changed
  192. if result.TableChanged() {
  193. fmt.Printf("table: %s\n", result.TableMetadata().String())
  194. }
  195. // Access data
  196. fmt.Printf("value: %v\n", result.Record().Value())
  197. }
  198. // check for an error
  199. if result.Err() != nil {
  200. fmt.Printf("query parsing error: %s\n", result.Err().Error())
  201. }
  202. } else {
  203. panic(err)
  204. }
  205. // Ensures background processes finishes
  206. client.Close()
  207. }
  208. func ExampleQueryAPI_queryRaw() {
  209. // Create a new client using an InfluxDB server base URL and an authentication token
  210. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  211. // Get query client
  212. queryAPI := client.QueryAPI("my-org")
  213. // Query and get complete result as a string
  214. // Use default dialect
  215. result, err := queryAPI.QueryRaw(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`, api.DefaultDialect())
  216. if err == nil {
  217. fmt.Println("QueryResult:")
  218. fmt.Println(result)
  219. } else {
  220. panic(err)
  221. }
  222. // Ensures background processes finishes
  223. client.Close()
  224. }
  225. func ExampleOrganizationsAPI() {
  226. // Create a new client using an InfluxDB server base URL and an authentication token
  227. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  228. // Get Organizations API client
  229. orgAPI := client.OrganizationsAPI()
  230. // Create new organization
  231. org, err := orgAPI.CreateOrganizationWithName(context.Background(), "org-2")
  232. if err != nil {
  233. panic(err)
  234. }
  235. orgDescription := "My second org "
  236. org.Description = &orgDescription
  237. org, err = orgAPI.UpdateOrganization(context.Background(), org)
  238. if err != nil {
  239. panic(err)
  240. }
  241. // Find user to set owner
  242. user, err := client.UsersAPI().FindUserByName(context.Background(), "user-01")
  243. if err != nil {
  244. panic(err)
  245. }
  246. // Add another owner (first owner is the one who create organization
  247. _, err = orgAPI.AddOwner(context.Background(), org, user)
  248. if err != nil {
  249. panic(err)
  250. }
  251. // Create new user to add to org
  252. newUser, err := client.UsersAPI().CreateUserWithName(context.Background(), "user-02")
  253. if err != nil {
  254. panic(err)
  255. }
  256. // Add new user to organization
  257. _, err = orgAPI.AddMember(context.Background(), org, newUser)
  258. if err != nil {
  259. panic(err)
  260. }
  261. // Ensures background processes finishes
  262. client.Close()
  263. }
  264. func ExampleAuthorizationsAPI() {
  265. // Create a new client using an InfluxDB server base URL and an authentication token
  266. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  267. // Find user to grant permission
  268. user, err := client.UsersAPI().FindUserByName(context.Background(), "user-01")
  269. if err != nil {
  270. panic(err)
  271. }
  272. // Find organization
  273. org, err := client.OrganizationsAPI().FindOrganizationByName(context.Background(), "my-org")
  274. if err != nil {
  275. panic(err)
  276. }
  277. // create write permission for buckets
  278. permissionWrite := &domain.Permission{
  279. Action: domain.PermissionActionWrite,
  280. Resource: domain.Resource{
  281. Type: domain.ResourceTypeBuckets,
  282. },
  283. }
  284. // create read permission for buckets
  285. permissionRead := &domain.Permission{
  286. Action: domain.PermissionActionRead,
  287. Resource: domain.Resource{
  288. Type: domain.ResourceTypeBuckets,
  289. },
  290. }
  291. // group permissions
  292. permissions := []domain.Permission{*permissionWrite, *permissionRead}
  293. // create authorization object using info above
  294. auth := &domain.Authorization{
  295. OrgID: org.Id,
  296. Permissions: &permissions,
  297. UserID: user.Id,
  298. }
  299. // grant permission and create token
  300. authCreated, err := client.AuthorizationsAPI().CreateAuthorization(context.Background(), auth)
  301. if err != nil {
  302. panic(err)
  303. }
  304. // Use token
  305. fmt.Println("Token: ", *authCreated.Token)
  306. // Ensures background processes finishes
  307. client.Close()
  308. }
  309. func ExampleUsersAPI() {
  310. // Create a new client using an InfluxDB server base URL and an authentication token
  311. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  312. // Find organization
  313. org, err := client.OrganizationsAPI().FindOrganizationByName(context.Background(), "my-org")
  314. if err != nil {
  315. panic(err)
  316. }
  317. // Get users API client
  318. usersAPI := client.UsersAPI()
  319. // Create new user
  320. user, err := usersAPI.CreateUserWithName(context.Background(), "user-01")
  321. if err != nil {
  322. panic(err)
  323. }
  324. // Set user password
  325. err = usersAPI.UpdateUserPassword(context.Background(), user, "pass-at-least-8-chars")
  326. if err != nil {
  327. panic(err)
  328. }
  329. // Add user to organization
  330. _, err = client.OrganizationsAPI().AddMember(context.Background(), org, user)
  331. if err != nil {
  332. panic(err)
  333. }
  334. // Ensures background processes finishes
  335. client.Close()
  336. }
  337. func ExampleUsersAPI_signInOut() {
  338. // Create a new client using an InfluxDB server base URL and empty token
  339. client := influxdb2.NewClient("http://localhost:8086", "")
  340. // Always close client at the end
  341. defer client.Close()
  342. ctx := context.Background()
  343. // The first call must be signIn
  344. err := client.UsersAPI().SignIn(ctx, "username", "password")
  345. if err != nil {
  346. panic(err)
  347. }
  348. // Perform some authorized operations
  349. err = client.WriteAPIBlocking("my-org", "my-bucket").WriteRecord(ctx, "test,a=rock,b=local f=1.2,i=-5i")
  350. if err != nil {
  351. panic(err)
  352. }
  353. // Sign out at the end
  354. err = client.UsersAPI().SignOut(ctx)
  355. if err != nil {
  356. panic(err)
  357. }
  358. }
  359. func ExampleLabelsAPI() {
  360. // Create a new client using an InfluxDB server base URL and an authentication token
  361. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  362. ctx := context.Background()
  363. // Get Labels API client
  364. labelsAPI := client.LabelsAPI()
  365. // Get Organizations API client
  366. orgsAPI := client.OrganizationsAPI()
  367. // Get organization that will own label
  368. myorg, err := orgsAPI.FindOrganizationByName(ctx, "my-org")
  369. if err != nil {
  370. panic(err)
  371. }
  372. labelName := "Active State"
  373. props := map[string]string{"color": "33ffdd", "description": "Marks org active"}
  374. label, err := labelsAPI.CreateLabelWithName(ctx, myorg, labelName, props)
  375. if err != nil {
  376. panic(err)
  377. }
  378. // Change color property
  379. label.Properties.AdditionalProperties = map[string]string{"color": "ff1122"}
  380. label, err = labelsAPI.UpdateLabel(ctx, label)
  381. if err != nil {
  382. panic(err)
  383. }
  384. // Close the client
  385. client.Close()
  386. }
  387. func ExampleDeleteAPI() {
  388. // Create a new client using an InfluxDB server base URL and an authentication token
  389. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  390. ctx := context.Background()
  391. // Get Delete API client
  392. deleteAPI := client.DeleteAPI()
  393. // Delete last hour data with tag b = static
  394. err := deleteAPI.DeleteWithName(ctx, "org", "my-bucket", time.Now().Add(-time.Hour), time.Now(), "b=static")
  395. if err != nil {
  396. panic(err)
  397. }
  398. // Close the client
  399. client.Close()
  400. }
  401. func ExampleTasksAPI() {
  402. // Create a new client using an InfluxDB server base URL and an authentication token
  403. client := influxdb2.NewClient("http://localhost:8086", "my-token")
  404. ctx := context.Background()
  405. // Get Delete API client
  406. tasksAPI := client.TasksAPI()
  407. // Get organization that will own task
  408. myorg, err := client.OrganizationsAPI().FindOrganizationByName(ctx, "my-org")
  409. if err != nil {
  410. panic(err)
  411. }
  412. // task flux script from https://www.influxdata.com/blog/writing-tasks-and-setting-up-alerts-for-influxdb-cloud/
  413. flux := `fruitCollected = from(bucket: “farming”)
  414. |> range(start: -task.every)
  415. |> filter(fn: (r) => (r._measurement == “totalFruitsCollected))
  416. |> filter(fn: (r) => (r._field == “fruits))
  417. |> group(columns: [“farmName”])
  418. |> aggregateWindow(fn: sum, every: task.every)
  419. |> map(fn: (r) => {
  420. return: _time: r._time, _stop: r._stop, _start: r._start, _measurement: “fruitCollectionRate”, _field: “fruits”, _value: r._value, farmName: farmName,
  421. }
  422. })
  423. fruitCollected
  424. |> to(bucket: “farming”)
  425. `
  426. task, err := tasksAPI.CreateTaskWithEvery(ctx, "fruitCollectedRate", flux, "1h", *myorg.Id)
  427. if err != nil {
  428. panic(err)
  429. }
  430. // Force running a task
  431. run, err := tasksAPI.RunManually(ctx, task)
  432. if err != nil {
  433. panic(err)
  434. }
  435. fmt.Println("Forced run completed on ", *run.FinishedAt, " with status ", *run.Status)
  436. // Print logs
  437. logs, err := tasksAPI.FindRunLogs(ctx, run)
  438. if err != nil {
  439. panic(err)
  440. }
  441. fmt.Println("Log:")
  442. for _, logEvent := range logs {
  443. fmt.Println(" Time:", *logEvent.Time, ", Message: ", *logEvent.Message)
  444. }
  445. // Close the client
  446. client.Close()
  447. }