Copilot commented on code in PR #1499: URL: https://github.com/apache/dubbo-admin/pull/1499#discussion_r3566159452
########## pkg/mcp/tools/metrics/prometheus.go: ########## @@ -0,0 +1,325 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package metrics + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "math" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/apache/dubbo-admin/pkg/core/logger" +) + +const ( + queryTimeout = 15 * time.Second + maxQueryBytes = 8 * 1024 + maxQueryRange = 24 * time.Hour + minQueryStep = 15 * time.Second + maxSeries = 100 + maxSamples = 5000 + maxResponseBytes = int64(4 * 1024 * 1024) + maxErrorBodyBytes = int64(4096) +) + +type prometheusClient struct { + baseURL *url.URL + client *http.Client +} + +var prometheusTransport = &http.Transport{ + Proxy: http.ProxyFromEnvironment, + MaxIdleConns: 20, + MaxIdleConnsPerHost: 10, + IdleConnTimeout: 90 * time.Second, + ResponseHeaderTimeout: queryTimeout, +} + +type prometheusResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result json.RawMessage `json:"result"` + } `json:"data"` + ErrorType string `json:"errorType,omitempty"` + Error string `json:"error,omitempty"` + Warnings []string `json:"warnings,omitempty"` +} + +type prometheusSeries struct { + Metric map[string]string `json:"metric"` + Value []json.RawMessage `json:"value,omitempty"` + Values [][]json.RawMessage `json:"values,omitempty"` +} + +func newPrometheusClient(baseURL *url.URL) *prometheusClient { + return &prometheusClient{ + baseURL: baseURL, + client: &http.Client{ + Timeout: queryTimeout, + Transport: prometheusTransport, + }, + } +} + +func (c *prometheusClient) instant(ctx context.Context, query, evaluationTime string) (*QueryResponse, error) { + values := url.Values{"query": []string{query}} + if evaluationTime != "" { + if _, err := parsePrometheusTime("time", evaluationTime); err != nil { + return nil, err + } + values.Set("time", evaluationTime) + } + return c.query(ctx, "instant", "/api/v1/query", values) +} + +func (c *prometheusClient) rangeQuery(ctx context.Context, query, startRaw, endRaw, stepRaw string) (*QueryResponse, error) { + start, err := parsePrometheusTime("startTime", startRaw) + if err != nil { + return nil, err + } + end, err := parsePrometheusTime("endTime", endRaw) + if err != nil { + return nil, err + } + if !end.After(start) { + return nil, fmt.Errorf("endTime must be after startTime") + } + if end.Sub(start) > maxQueryRange { + return nil, fmt.Errorf("query range must not exceed %s", maxQueryRange) + } + step, err := parsePrometheusStep(stepRaw) + if err != nil { + return nil, err + } + if step < minQueryStep { + return nil, fmt.Errorf("step must be at least %s", minQueryStep) + } + + values := url.Values{ + "query": []string{query}, + "start": []string{startRaw}, + "end": []string{endRaw}, + "step": []string{stepRaw}, + } + return c.query(ctx, "range", "/api/v1/query_range", values) +} + +func (c *prometheusClient) query(ctx context.Context, queryType, path string, values url.Values) (*QueryResponse, error) { + query := values.Get("query") + if strings.TrimSpace(query) == "" { + return nil, fmt.Errorf("query is required") + } + if len(query) > maxQueryBytes { + return nil, fmt.Errorf("query must not exceed %d bytes", maxQueryBytes) + } + + endpoint := *c.baseURL + endpoint.Path = strings.TrimRight(endpoint.Path, "/") + path + startedAt := time.Now() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), strings.NewReader(values.Encode())) + if err != nil { + return nil, fmt.Errorf("failed to create prometheus request: %w", err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + logPrometheusFailure(queryType, query, startedAt, 0, "transport", err) + return nil, fmt.Errorf("prometheus query failed: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes)) + logPrometheusFailure(queryType, query, startedAt, resp.StatusCode, "upstream_status", nil) + return nil, fmt.Errorf("prometheus query failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + + body, err := readBoundedBody(resp.Body, maxResponseBytes) + if err != nil { + logPrometheusFailure(queryType, query, startedAt, resp.StatusCode, "response_limit", err) + return nil, fmt.Errorf("failed to read prometheus response: %w", err) + } + var upstream prometheusResponse + if err := json.Unmarshal(body, &upstream); err != nil { + logPrometheusFailure(queryType, query, startedAt, resp.StatusCode, "decode", err) + return nil, fmt.Errorf("failed to decode prometheus response: %w", err) + } + if upstream.Status != "success" { + message := upstream.Error + if message == "" { + message = "unknown prometheus error" + } + logPrometheusFailure(queryType, query, startedAt, resp.StatusCode, upstream.ErrorType, nil) + return nil, fmt.Errorf("prometheus %s error: %s", upstream.ErrorType, message) Review Comment: When Prometheus returns an error response without `errorType`, the formatted message becomes `prometheus error: ...` (double space / missing type) and the log `error_type` field is empty. It’s better to normalize an empty `errorType` to a stable placeholder (e.g. `unknown`) so operators and the agent get a consistent error category. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
