hanahmily commented on code in PR #918: URL: https://github.com/apache/skywalking-banyandb/pull/918#discussion_r2652193702
########## fodc/proxy/Makefile: ########## @@ -0,0 +1,37 @@ +# Licensed to 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. Apache Software Foundation (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. +# + +NAME := fodc-proxy +BINARIES := $(NAME)-cli Review Comment: ```suggestion BINARIES := $(NAME)-server ``` ########## fodc/proxy/Dockerfile: ########## @@ -0,0 +1,36 @@ +# 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. + + +FROM alpine:edge AS certs +RUN apk add --no-cache ca-certificates && update-ca-certificates + +FROM busybox:stable-glibc AS build-linux + +ARG TARGETARCH + +COPY build/bin/linux/${TARGETARCH}/fodc-proxy-cli-static /fodc-proxy +COPY --from=certs /etc/ssl/certs /etc/ssl/certs + +FROM mcr.microsoft.com/windows/servercore:ltsc2022 AS build-windows Review Comment: ```suggestion ``` We don't build window's image anymore. ########## fodc/proxy/internal/metrics/aggregator.go: ########## @@ -0,0 +1,287 @@ +// Licensed to 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. Apache Software Foundation (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 provides functionality for aggregating and enriching metrics from all agents. +package metrics + +import ( + "context" + "fmt" + "sync" + "time" + + fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1" + "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry" + "github.com/apache/skywalking-banyandb/pkg/logger" +) + +const ( + // defaultCollectionTimeout is the default timeout for collecting metrics from agents. + defaultCollectionTimeout = 10 * time.Second + // maxCollectionTimeout is the maximum timeout allowed for collecting metrics, + // preventing excessively long waits for wide time windows. + maxCollectionTimeout = 5 * time.Minute +) + +// AggregatedMetric represents an aggregated metric with node metadata. +type AggregatedMetric struct { + Labels map[string]string + Timestamp time.Time + Name string + AgentID string + NodeRole string + Description string + Value float64 +} + +// Filter defines filters for metrics collection. +type Filter struct { + StartTime *time.Time + EndTime *time.Time + Role string + Address string + AgentIDs []string +} + +// Aggregator aggregates and enriches metrics from all agents. +type Aggregator struct { + registry *registry.AgentRegistry + logger *logger.Logger + grpcService RequestSender + metricsCh chan *AggregatedMetric + collecting map[string]chan []*AggregatedMetric + mu sync.RWMutex + collectingMu sync.RWMutex +} + +// RequestSender is an interface for sending metrics requests to agents. +type RequestSender interface { + RequestMetrics(ctx context.Context, agentID string, startTime, endTime *time.Time) error +} + +// NewAggregator creates a new MetricsAggregator instance. +func NewAggregator(registry *registry.AgentRegistry, grpcService RequestSender, logger *logger.Logger) *Aggregator { + return &Aggregator{ + registry: registry, + grpcService: grpcService, + logger: logger, + metricsCh: make(chan *AggregatedMetric, 1000), + collecting: make(map[string]chan []*AggregatedMetric), + } +} + +// SetGRPCService sets the gRPC service for sending metrics requests. +func (ma *Aggregator) SetGRPCService(grpcService RequestSender) { + ma.mu.Lock() + defer ma.mu.Unlock() + ma.grpcService = grpcService +} + +// ProcessMetricsFromAgent processes metrics received from an agent. +func (ma *Aggregator) ProcessMetricsFromAgent(ctx context.Context, agentID string, agentInfo *registry.AgentInfo, req *fodcv1.StreamMetricsRequest) error { + aggregatedMetrics := make([]*AggregatedMetric, 0, len(req.Metrics)) + + for _, metric := range req.Metrics { + labels := make(map[string]string) + for key, value := range metric.Labels { + labels[key] = value + } + + labels["agent_id"] = agentID + labels["node_role"] = agentInfo.NodeRole + labels["ip"] = agentInfo.PrimaryAddress.IP + labels["port"] = fmt.Sprintf("%d", agentInfo.PrimaryAddress.Port) + + for key, value := range agentInfo.Labels { + labels[key] = value + } + + var timestamp time.Time + switch { + case metric.Timestamp != nil: + timestamp = metric.Timestamp.AsTime() + case req.Timestamp != nil: + timestamp = req.Timestamp.AsTime() + default: + timestamp = time.Now() + } + + aggregatedMetric := &AggregatedMetric{ + Name: metric.Name, + Labels: labels, + Value: metric.Value, + Timestamp: timestamp, + AgentID: agentID, + NodeRole: agentInfo.NodeRole, + Description: metric.Description, + } + + aggregatedMetrics = append(aggregatedMetrics, aggregatedMetric) + } + + ma.collectingMu.RLock() + collectCh, exists := ma.collecting[agentID] + ma.collectingMu.RUnlock() + + if exists { + select { + case collectCh <- aggregatedMetrics: + case <-ctx.Done(): + return ctx.Err() + default: + ma.logger.Warn().Str("agent_id", agentID).Msg("Metrics collection channel full, dropping metrics") + } + } + + return nil +} + +// CollectMetricsFromAgents requests metrics from all agents (or filtered agents) when external client queries. +func (ma *Aggregator) CollectMetricsFromAgents(ctx context.Context, filter *Filter) ([]*AggregatedMetric, error) { + agents := ma.getFilteredAgents(filter) + if len(agents) == 0 { + return []*AggregatedMetric{}, nil + } + + collectChs := make(map[string]chan []*AggregatedMetric) + agentIDs := make([]string, 0, len(agents)) + ma.collectingMu.Lock() + for _, agentInfo := range agents { + collectCh := make(chan []*AggregatedMetric, 1) + collectChs[agentInfo.AgentID] = collectCh + ma.collecting[agentInfo.AgentID] = collectCh + agentIDs = append(agentIDs, agentInfo.AgentID) + } + ma.collectingMu.Unlock() + + defer func() { + ma.collectingMu.Lock() + for _, agentID := range agentIDs { + delete(ma.collecting, agentID) + } + ma.collectingMu.Unlock() + }() + + for _, agentInfo := range agents { + requestErr := ma.grpcService.RequestMetrics(ctx, agentInfo.AgentID, filter.StartTime, filter.EndTime) + if requestErr != nil { Review Comment: Please drop the ma.collecting entry (or close the channel) as soon as RequestMetrics returns an error so that ProcessMetricsFromAgent skips the agent immediately instead of trying to write into a dead sink. ########## fodc/proxy/internal/metrics/aggregator.go: ########## @@ -0,0 +1,287 @@ +// Licensed to 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. Apache Software Foundation (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 provides functionality for aggregating and enriching metrics from all agents. +package metrics + +import ( + "context" + "fmt" + "sync" + "time" + + fodcv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1" + "github.com/apache/skywalking-banyandb/fodc/proxy/internal/registry" + "github.com/apache/skywalking-banyandb/pkg/logger" +) + +const ( + // defaultCollectionTimeout is the default timeout for collecting metrics from agents. + defaultCollectionTimeout = 10 * time.Second + // maxCollectionTimeout is the maximum timeout allowed for collecting metrics, + // preventing excessively long waits for wide time windows. + maxCollectionTimeout = 5 * time.Minute +) + +// AggregatedMetric represents an aggregated metric with node metadata. +type AggregatedMetric struct { + Labels map[string]string + Timestamp time.Time + Name string + AgentID string + NodeRole string + Description string + Value float64 +} + +// Filter defines filters for metrics collection. +type Filter struct { + StartTime *time.Time + EndTime *time.Time + Role string + Address string + AgentIDs []string +} + +// Aggregator aggregates and enriches metrics from all agents. +type Aggregator struct { + registry *registry.AgentRegistry + logger *logger.Logger + grpcService RequestSender + metricsCh chan *AggregatedMetric + collecting map[string]chan []*AggregatedMetric + mu sync.RWMutex + collectingMu sync.RWMutex +} + +// RequestSender is an interface for sending metrics requests to agents. +type RequestSender interface { + RequestMetrics(ctx context.Context, agentID string, startTime, endTime *time.Time) error +} + +// NewAggregator creates a new MetricsAggregator instance. +func NewAggregator(registry *registry.AgentRegistry, grpcService RequestSender, logger *logger.Logger) *Aggregator { + return &Aggregator{ + registry: registry, + grpcService: grpcService, + logger: logger, + metricsCh: make(chan *AggregatedMetric, 1000), + collecting: make(map[string]chan []*AggregatedMetric), + } +} + +// SetGRPCService sets the gRPC service for sending metrics requests. +func (ma *Aggregator) SetGRPCService(grpcService RequestSender) { + ma.mu.Lock() + defer ma.mu.Unlock() + ma.grpcService = grpcService +} + +// ProcessMetricsFromAgent processes metrics received from an agent. +func (ma *Aggregator) ProcessMetricsFromAgent(ctx context.Context, agentID string, agentInfo *registry.AgentInfo, req *fodcv1.StreamMetricsRequest) error { + aggregatedMetrics := make([]*AggregatedMetric, 0, len(req.Metrics)) + + for _, metric := range req.Metrics { + labels := make(map[string]string) + for key, value := range metric.Labels { + labels[key] = value + } + + labels["agent_id"] = agentID + labels["node_role"] = agentInfo.NodeRole + labels["ip"] = agentInfo.PrimaryAddress.IP + labels["port"] = fmt.Sprintf("%d", agentInfo.PrimaryAddress.Port) + + for key, value := range agentInfo.Labels { + labels[key] = value + } + + var timestamp time.Time + switch { + case metric.Timestamp != nil: + timestamp = metric.Timestamp.AsTime() + case req.Timestamp != nil: + timestamp = req.Timestamp.AsTime() + default: + timestamp = time.Now() + } + + aggregatedMetric := &AggregatedMetric{ + Name: metric.Name, + Labels: labels, + Value: metric.Value, + Timestamp: timestamp, + AgentID: agentID, + NodeRole: agentInfo.NodeRole, + Description: metric.Description, + } + + aggregatedMetrics = append(aggregatedMetrics, aggregatedMetric) + } + + ma.collectingMu.RLock() + collectCh, exists := ma.collecting[agentID] + ma.collectingMu.RUnlock() + + if exists { + select { + case collectCh <- aggregatedMetrics: + case <-ctx.Done(): + return ctx.Err() + default: + ma.logger.Warn().Str("agent_id", agentID).Msg("Metrics collection channel full, dropping metrics") + } + } + + return nil +} + +// CollectMetricsFromAgents requests metrics from all agents (or filtered agents) when external client queries. +func (ma *Aggregator) CollectMetricsFromAgents(ctx context.Context, filter *Filter) ([]*AggregatedMetric, error) { + agents := ma.getFilteredAgents(filter) + if len(agents) == 0 { + return []*AggregatedMetric{}, nil + } + + collectChs := make(map[string]chan []*AggregatedMetric) + agentIDs := make([]string, 0, len(agents)) + ma.collectingMu.Lock() + for _, agentInfo := range agents { + collectCh := make(chan []*AggregatedMetric, 1) + collectChs[agentInfo.AgentID] = collectCh + ma.collecting[agentInfo.AgentID] = collectCh + agentIDs = append(agentIDs, agentInfo.AgentID) + } + ma.collectingMu.Unlock() + + defer func() { + ma.collectingMu.Lock() + for _, agentID := range agentIDs { + delete(ma.collecting, agentID) + } + ma.collectingMu.Unlock() + }() + + for _, agentInfo := range agents { + requestErr := ma.grpcService.RequestMetrics(ctx, agentInfo.AgentID, filter.StartTime, filter.EndTime) + if requestErr != nil { + ma.logger.Error(). + Err(requestErr). + Str("agent_id", agentInfo.AgentID). + Msg("Failed to request metrics from agent") + delete(collectChs, agentInfo.AgentID) + } + } + + allMetrics := make([]*AggregatedMetric, 0) + timeout := defaultCollectionTimeout + if filter.StartTime != nil && filter.EndTime != nil { + windowDuration := filter.EndTime.Sub(*filter.StartTime) + 5*time.Second + if windowDuration < maxCollectionTimeout { + timeout = windowDuration + } else { + timeout = maxCollectionTimeout + } + } + + timeoutCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + for agentID, collectCh := range collectChs { + select { + case <-timeoutCtx.Done(): Review Comment: Consider giving each agent its own timeout (e.g., start a goroutine per channel or reset the context before each select) so one slow or non-responsive agent cannot cause the entire query to return empty. -- 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]
