send.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package influxdb
  15. import (
  16. "yunion.io/x/pkg/errors"
  17. )
  18. const (
  19. BATCH_SEND_SIZE = 10000
  20. )
  21. func SendMetrics(urls []string, dbName string, metrics []SMetricData, debug bool) error {
  22. lines := make([]string, len(metrics))
  23. for i := range metrics {
  24. lines[i] = metrics[i].Line()
  25. }
  26. if len(lines) == 0 {
  27. return nil
  28. }
  29. for _, url := range urls {
  30. db := NewInfluxdbWithDebug(url, debug)
  31. err := db.SetDatabase(dbName)
  32. if err != nil {
  33. return errors.Wrap(err, "SetDatabase")
  34. }
  35. for _, line := range lines {
  36. err = db.Write(line, "ms")
  37. if err != nil {
  38. return errors.Wrap(err, "db.Write")
  39. }
  40. }
  41. }
  42. return nil
  43. }
  44. func BatchSendMetrics(urls []string, dbName string, metrics []SMetricData, debug bool) error {
  45. lines := make([]string, len(metrics))
  46. for i := range metrics {
  47. lines[i] = metrics[i].Line()
  48. }
  49. if len(lines) == 0 {
  50. return nil
  51. }
  52. for _, url := range urls {
  53. db := NewInfluxdbWithDebug(url, debug)
  54. err := db.SetDatabase(dbName)
  55. if err != nil {
  56. return errors.Wrap(err, "SetDatabase")
  57. }
  58. errs := []error{}
  59. for i := 0; i < (len(lines)+BATCH_SEND_SIZE-1)/BATCH_SEND_SIZE; i++ {
  60. last := (i + 1) * BATCH_SEND_SIZE
  61. if last > len(lines) {
  62. last = len(lines)
  63. }
  64. err = db.BatchWrite(lines[i*BATCH_SEND_SIZE:last], "ms")
  65. if err != nil {
  66. errs = append(errs, err)
  67. }
  68. }
  69. if len(errs) > 0 {
  70. return errors.Wrapf(err, "db.BatchWrite")
  71. }
  72. }
  73. return nil
  74. }