autocompletequeryservice.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package allocation
  2. import (
  3. "context"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "github.com/opencost/opencost/core/pkg/filter"
  8. "github.com/opencost/opencost/core/pkg/opencost"
  9. )
  10. const DefaultAutocompleteResultLimit = 100
  11. const MaxAutocompleteResultLimit = 1000
  12. type AllocationAutocompleteRequest struct {
  13. Search string
  14. Field string
  15. Limit int
  16. Window opencost.Window
  17. Filter filter.Filter
  18. LabelConfig *opencost.LabelConfig
  19. }
  20. type AllocationAutocompleteResponse struct {
  21. Data []string `json:"data"`
  22. }
  23. type AutocompleteQueryService interface {
  24. QueryAllocationAutocomplete(AllocationAutocompleteRequest, context.Context) (*AllocationAutocompleteResponse, error)
  25. }
  26. func QueryAllocationAutocompleteFromSetRange(asr *opencost.AllocationSetRange, req AllocationAutocompleteRequest) (*AllocationAutocompleteResponse, error) {
  27. field, err := validateAutocompleteField(req.Field)
  28. if err != nil {
  29. return nil, fmt.Errorf("invalid field: %w", err)
  30. }
  31. limit := req.Limit
  32. if limit <= 0 {
  33. limit = DefaultAutocompleteResultLimit
  34. }
  35. if limit > MaxAutocompleteResultLimit {
  36. return nil, fmt.Errorf("exceeded maxiumum autocomplete result limit of %d", MaxAutocompleteResultLimit)
  37. }
  38. var matcher opencost.AllocationMatcher
  39. if req.Filter != nil {
  40. compiler := opencost.NewAllocationMatchCompiler(req.LabelConfig)
  41. matcher, err = compiler.Compile(req.Filter)
  42. if err != nil {
  43. return nil, fmt.Errorf("failed to compile filter: %w", err)
  44. }
  45. }
  46. search := strings.ToLower(req.Search)
  47. results := map[string]struct{}{}
  48. for _, as := range asr.Slice() {
  49. for _, alloc := range as.Allocations {
  50. if alloc == nil || alloc.Properties == nil {
  51. continue
  52. }
  53. if matcher != nil && !matcher.Matches(alloc) {
  54. continue
  55. }
  56. values := allocationAutocompleteValues(alloc.Properties, field)
  57. for _, value := range values {
  58. if value == "" {
  59. continue
  60. }
  61. if search != "" && !strings.Contains(strings.ToLower(value), search) {
  62. continue
  63. }
  64. results[value] = struct{}{}
  65. }
  66. }
  67. }
  68. return &AllocationAutocompleteResponse{Data: uniqueSortedLimited(results, limit)}, nil
  69. }
  70. func validateAutocompleteField(field string) (string, error) {
  71. if field == "" {
  72. return "", fmt.Errorf("field is required")
  73. }
  74. f := strings.ToLower(field)
  75. switch f {
  76. case "cluster", "namespace", "node", "controllerkind", "controllername", "pod", "container", "account", "label", "namespacelabel":
  77. return f, nil
  78. }
  79. if strings.HasPrefix(f, "label:") {
  80. _, labelKey, _ := strings.Cut(field, ":")
  81. return "label:" + labelKey, nil
  82. }
  83. if strings.HasPrefix(f, "namespacelabel:") {
  84. _, labelKey, _ := strings.Cut(field, ":")
  85. return "namespacelabel:" + labelKey, nil
  86. }
  87. return "", fmt.Errorf("unrecognized field: %s", field)
  88. }
  89. func allocationAutocompleteValues(props *opencost.AllocationProperties, field string) []string {
  90. switch {
  91. case field == "cluster":
  92. return []string{props.Cluster}
  93. case field == "namespace":
  94. return []string{props.Namespace}
  95. case field == "node":
  96. return []string{props.Node}
  97. case field == "controllerkind":
  98. return []string{props.ControllerKind}
  99. case field == "controllername":
  100. return []string{props.Controller}
  101. case field == "pod":
  102. return []string{props.Pod}
  103. case field == "container":
  104. return []string{props.Container}
  105. case field == "account":
  106. return nil
  107. case field == "label":
  108. return mapKeys(props.Labels)
  109. case strings.HasPrefix(strings.ToLower(field), "label:"):
  110. label := strings.TrimPrefix(field, "label:")
  111. if v, ok := props.Labels[label]; ok {
  112. return []string{v}
  113. }
  114. case field == "namespacelabel":
  115. return mapKeys(props.NamespaceLabels)
  116. case strings.HasPrefix(strings.ToLower(field), "namespacelabel:"):
  117. label := strings.TrimPrefix(field, "namespacelabel:")
  118. if v, ok := props.NamespaceLabels[label]; ok {
  119. return []string{v}
  120. }
  121. }
  122. return nil
  123. }
  124. func mapKeys(values map[string]string) []string {
  125. result := make([]string, 0, len(values))
  126. for k := range values {
  127. result = append(result, k)
  128. }
  129. return result
  130. }
  131. func uniqueSortedLimited(values map[string]struct{}, limit int) []string {
  132. out := make([]string, 0, len(values))
  133. for v := range values {
  134. out = append(out, v)
  135. }
  136. sort.Strings(out)
  137. if len(out) > limit {
  138. return out[:limit]
  139. }
  140. return out
  141. }