|
| 1 | +package collect |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "net/url" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/pkg/errors" |
| 13 | + troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2" |
| 14 | + "k8s.io/client-go/kubernetes" |
| 15 | + "k8s.io/client-go/rest" |
| 16 | + "k8s.io/klog/v2" |
| 17 | + "k8s.io/metrics/pkg/apis/custom_metrics" |
| 18 | +) |
| 19 | + |
| 20 | +const ( |
| 21 | + namespaceSingular = "namespace" |
| 22 | + namespacePlural = "namespaces" |
| 23 | + urlBase = "/apis/custom.metrics.k8s.io/v1beta1" |
| 24 | + metricsErrorFile = "metrics/errors.json" |
| 25 | +) |
| 26 | + |
| 27 | +type CollectMetrics struct { |
| 28 | + Collector *troubleshootv1beta2.CustomMetrics |
| 29 | + BundlePath string |
| 30 | + ClientConfig *rest.Config |
| 31 | + Client kubernetes.Interface |
| 32 | + Context context.Context |
| 33 | + RBACErrors |
| 34 | +} |
| 35 | + |
| 36 | +func (c *CollectMetrics) Title() string { |
| 37 | + return getCollectorName(c) |
| 38 | +} |
| 39 | + |
| 40 | +func (c *CollectMetrics) IsExcluded() (bool, error) { |
| 41 | + return isExcluded(c.Collector.Exclude) |
| 42 | +} |
| 43 | + |
| 44 | +func (c *CollectMetrics) Collect(progressChan chan<- interface{}) (CollectorResult, error) { |
| 45 | + output := NewResult() |
| 46 | + resultLists := make(map[string][]custom_metrics.MetricValue) |
| 47 | + errorsList := make([]string, 0) |
| 48 | + for _, metricRequest := range c.Collector.MetricRequests { |
| 49 | + klog.V(2).Infof("Getting metric values: %+v\n", metricRequest.ResourceMetricName) |
| 50 | + endpoint, metricName, err := constructEndpoint(metricRequest) |
| 51 | + if err != nil { |
| 52 | + errorsList = append(errorsList, errors.Wrapf(err, "could not construct endpoint for %s", metricRequest.ResourceMetricName).Error()) |
| 53 | + continue |
| 54 | + } |
| 55 | + klog.V(2).Infof("Querying: %+v\n", endpoint) |
| 56 | + response, err := c.Client.CoreV1().RESTClient().Get().AbsPath(endpoint).DoRaw(c.Context) |
| 57 | + if err != nil { |
| 58 | + errorsList = append(errorsList, errors.Wrapf(err, "could not query endpoint %s", endpoint).Error()) |
| 59 | + continue |
| 60 | + } |
| 61 | + metricsValues := custom_metrics.MetricValueList{} |
| 62 | + json.Unmarshal(response, &metricsValues) |
| 63 | + // metrics |
| 64 | + // |_ <resource_type> |
| 65 | + // |_ <metric_name> |
| 66 | + // |_ <namespace>.json or <non_namespaced_object>.json |
| 67 | + var path []string |
| 68 | + for _, item := range metricsValues.Items { |
| 69 | + if item.DescribedObject.Namespace != "" { |
| 70 | + path = []string{"metrics", item.DescribedObject.Kind, metricName, fmt.Sprintf("%s.json", item.DescribedObject.Namespace)} |
| 71 | + } else { |
| 72 | + path = []string{"metrics", item.DescribedObject.Kind, metricName, fmt.Sprintf("%s.json", item.DescribedObject.Name)} |
| 73 | + } |
| 74 | + filePath := filepath.Join(path...) |
| 75 | + if _, ok := resultLists[filePath]; !ok { |
| 76 | + resultLists[filePath] = make([]custom_metrics.MetricValue, 0) |
| 77 | + } |
| 78 | + resultLists[filePath] = append(resultLists[filePath], item) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // Construct output. |
| 83 | + for relativePath, list := range resultLists { |
| 84 | + payload, err := json.MarshalIndent(list, "", " ") |
| 85 | + if err != nil { |
| 86 | + klog.V(2).Infof("Could not parse for: %+v\n", relativePath) |
| 87 | + errorsList = append(errorsList, errors.Wrapf(err, "could not format readings for %s", relativePath).Error()) |
| 88 | + } |
| 89 | + output.SaveResult(c.BundlePath, relativePath, bytes.NewBuffer(payload)) |
| 90 | + } |
| 91 | + errPayload := marshalErrors(errorsList) |
| 92 | + output.SaveResult(c.BundlePath, metricsErrorFile, errPayload) |
| 93 | + return output, nil |
| 94 | +} |
| 95 | + |
| 96 | +func constructEndpoint(metricRequest troubleshootv1beta2.MetricRequest) (string, string, error) { |
| 97 | + metricNameComponents := strings.Split(metricRequest.ResourceMetricName, "/") |
| 98 | + if len(metricNameComponents) != 2 { |
| 99 | + return "", "", errors.New("wrong metric name format %s") |
| 100 | + } |
| 101 | + objectType := metricNameComponents[0] |
| 102 | + // Namespace related metrics are grouped under singular format "namespace/" |
| 103 | + // unlike other resources. |
| 104 | + if objectType == namespacePlural { |
| 105 | + objectType = namespaceSingular |
| 106 | + } |
| 107 | + metricName := metricNameComponents[1] |
| 108 | + objectSelector := "*" |
| 109 | + if metricRequest.ObjectName != "" { |
| 110 | + objectSelector = metricRequest.ObjectName |
| 111 | + } |
| 112 | + var endpoint string |
| 113 | + var err error |
| 114 | + if metricRequest.Namespace != "" { |
| 115 | + // namespaced objects |
| 116 | + // endpoint <resource_type>/namespaces/<namespace>/<resrouce_name or *>/<metric> |
| 117 | + endpoint, err = url.JoinPath(urlBase, namespacePlural, metricRequest.Namespace, objectType, objectSelector, metricName) |
| 118 | + if err != nil { |
| 119 | + return "", "", errors.Wrap(err, "could not construct url") |
| 120 | + } |
| 121 | + } else { |
| 122 | + // non-namespaced objects |
| 123 | + // endpoint <resource_type>/<resrouce_name or *>/<metric> |
| 124 | + endpoint, err = url.JoinPath(urlBase, objectType, objectSelector, metricName) |
| 125 | + if err != nil { |
| 126 | + return "", "", errors.Wrap(err, "could not construct url") |
| 127 | + } |
| 128 | + } |
| 129 | + return endpoint, metricName, nil |
| 130 | +} |
0 commit comments