influxdb.go 2.2 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 service
  15. import (
  16. "context"
  17. "fmt"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/onecloud/pkg/cloudcommon/tsdb"
  21. "yunion.io/x/onecloud/pkg/compute/options"
  22. "yunion.io/x/onecloud/pkg/mcclient"
  23. "yunion.io/x/onecloud/pkg/mcclient/auth"
  24. "yunion.io/x/onecloud/pkg/util/influxdb"
  25. )
  26. type sInfluxdbEndpointListener struct {
  27. done map[string]bool
  28. }
  29. func (listener *sInfluxdbEndpointListener) OnServiceCatalogChange(catalog mcclient.IServiceCatalog) {
  30. s := auth.GetAdminSession(context.Background(), options.Options.Region)
  31. urls, err := tsdb.GetDefaultServiceSourceURLs(s, options.Options.SessionEndpointType)
  32. if err != nil {
  33. log.Debugf("sInfluxdbEndpointListener: no influxdb endpoints found, retry later...")
  34. return
  35. }
  36. for _, url := range urls {
  37. if done, ok := listener.done[url]; ok && done {
  38. continue
  39. }
  40. err = setInfluxdbRetentionPolicyForUrl(url)
  41. if err != nil {
  42. log.Errorf("set retention policy for url %q fail %s", url, err)
  43. } else {
  44. listener.done[url] = true
  45. }
  46. }
  47. }
  48. func setInfluxdbRetentionPolicy() {
  49. listener := &sInfluxdbEndpointListener{
  50. done: make(map[string]bool),
  51. }
  52. auth.RegisterCatalogListener(listener)
  53. }
  54. func setInfluxdbRetentionPolicyForUrl(url string) error {
  55. db := influxdb.NewInfluxdb(url)
  56. err := db.SetDatabase("telegraf")
  57. if err != nil {
  58. return errors.Wrap(err, "set database telegraf")
  59. }
  60. rp := influxdb.SRetentionPolicy{
  61. Name: "30day_only",
  62. Duration: fmt.Sprintf("%dd", options.Options.MetricsRetentionDays),
  63. ReplicaN: 1,
  64. Default: true,
  65. }
  66. err = db.SetRetentionPolicy(rp)
  67. if err != nil {
  68. return errors.Wrap(err, "set retention policy")
  69. }
  70. return nil
  71. }