tsdb.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 tsdb
  15. import (
  16. "math/rand"
  17. "yunion.io/x/pkg/errors"
  18. "yunion.io/x/pkg/util/httputils"
  19. "yunion.io/x/onecloud/pkg/apis"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. )
  22. type TSDBServiceSource struct {
  23. Type string
  24. URLs []string
  25. }
  26. func NewTSDBServiceSource(t string, urls []string) *TSDBServiceSource {
  27. return &TSDBServiceSource{
  28. Type: t,
  29. URLs: urls,
  30. }
  31. }
  32. func GetDefaultServiceSource(s *mcclient.ClientSession, endpointType string) (*TSDBServiceSource, error) {
  33. errs := []error{}
  34. for _, sType := range []string{apis.SERVICE_TYPE_INFLUXDB, apis.SERVICE_TYPE_VICTORIA_METRICS} {
  35. urls, err := s.GetServiceURLs(sType, endpointType, httputils.POST)
  36. if err != nil {
  37. errs = append(errs, errors.Wrapf(err, "get %s service type %q", endpointType, sType))
  38. }
  39. if len(urls) != 0 {
  40. return NewTSDBServiceSource(sType, urls), nil
  41. }
  42. }
  43. return nil, errors.NewAggregate(errs)
  44. }
  45. func GetDefaultServiceSourceURLs(s *mcclient.ClientSession, endpointType string) ([]string, error) {
  46. src, err := GetDefaultServiceSource(s, endpointType)
  47. if err != nil {
  48. return nil, errors.Wrap(err, "GetDefaultServiceSource")
  49. }
  50. if len(src.URLs) == 0 {
  51. return nil, errors.Errorf("tsdb source %q URLs are empty", src.Type)
  52. }
  53. return src.URLs, nil
  54. }
  55. func GetDefaultServiceSourceURL(s *mcclient.ClientSession, endpointType string) (string, error) {
  56. urls, err := GetDefaultServiceSourceURLs(s, endpointType)
  57. if err != nil {
  58. return "", err
  59. }
  60. return urls[rand.Intn(len(urls))], nil
  61. }