hanahmily commented on code in PR #712: URL: https://github.com/apache/skywalking-banyandb/pull/712#discussion_r2246639977
########## banyand/property/repair_gossip.go: ########## @@ -0,0 +1,780 @@ +// 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 property + +import ( + "context" + "fmt" + "io" + + "github.com/pkg/errors" + grpclib "google.golang.org/grpc" + "google.golang.org/protobuf/encoding/protojson" + + "github.com/apache/skywalking-banyandb/api/common" + propertyv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/property/v1" + "github.com/apache/skywalking-banyandb/banyand/property/gossip" + "github.com/apache/skywalking-banyandb/pkg/index/inverted" +) + +var ( + gossipMerkelTreeReadPageSize int64 = 10 + gossipShardQueryDatabaseSize = 100 +) + +type repairGossipBase struct { + scheduler *repairScheduler +} + +func (b *repairGossipBase) getTreeReader(ctx context.Context, group string, shardID uint32) (repairTreeReader, bool, error) { + s, err := b.scheduler.db.loadShard(ctx, common.ShardID(shardID)) + if err != nil { + return nil, false, fmt.Errorf("failed to load shard %d: %w", shardID, err) + } + tree, err := s.repairState.treeReader(group) + if err != nil { + return nil, false, fmt.Errorf("failed to get tree reader for group %s: %w", group, err) + } + if tree == nil { + // if the tree is nil, but the state file exist, means the tree(group) is empty + stateExist, err := s.repairState.stateFileExist() + if err != nil { + return nil, false, fmt.Errorf("failed to check state file existence for group %s: %w", group, err) + } + // if the tree is nil, it means the tree is no data + return &emptyRepairTreeReader{}, stateExist, nil + } + return tree, true, nil +} + +func (b *repairGossipBase) sendTreeSummary( + reader repairTreeReader, + group string, + shardID uint32, + stream grpclib.BidiStreamingClient[propertyv1.RepairRequest, propertyv1.RepairResponse], +) (map[int32]*repairTreeNode, error) { + root, err := reader.read(nil, 1, false) + if err != nil { + return nil, fmt.Errorf("failed to read tree root: %w", err) + } + if len(root) == 0 { + return nil, fmt.Errorf("tree root is empty for group %s", group) + } + + err = stream.Send(&propertyv1.RepairRequest{ + Data: &propertyv1.RepairRequest_TreeRoot{ + TreeRoot: &propertyv1.TreeRoot{ + Group: group, + ShardId: shardID, + RootSha: root[0].shaValue, + }, + }, + }) + if err != nil { + return nil, fmt.Errorf("failed to send tree root for group %s: %w", group, err) + } + + slotsNodes := make(map[int32]*repairTreeNode) + var slots []*repairTreeNode + for { + slots, err = reader.read(root[0], gossipMerkelTreeReadPageSize, false) + if err != nil { + return nil, fmt.Errorf("failed to read slots for group %s: %w", group, err) + } + if len(slots) == 0 { + break + } + + slotReq := &propertyv1.TreeSlots{ + SlotSha: make([]*propertyv1.TreeSlotSHA, 0, len(slots)), + } + for _, s := range slots { + slotsNodes[s.slotInx] = s + slotReq.SlotSha = append(slotReq.SlotSha, &propertyv1.TreeSlotSHA{ + Slot: s.slotInx, + Value: s.shaValue, + }) + } + + err = stream.Send(&propertyv1.RepairRequest{ + Data: &propertyv1.RepairRequest_TreeSlots{ + TreeSlots: slotReq, + }, + }) + if err != nil { + return nil, fmt.Errorf("failed to send tree slots for group %s: %w", group, err) + } + } + + // send the empty slots list means there are no more slots to send + err = stream.Send(&propertyv1.RepairRequest{ + Data: &propertyv1.RepairRequest_TreeSlots{ + TreeSlots: &propertyv1.TreeSlots{ + SlotSha: []*propertyv1.TreeSlotSHA{}, + }, + }, + }) + if err != nil { + return nil, fmt.Errorf("failed to send empty tree slots for group %s: %w", group, err) + } + + return slotsNodes, nil +} + +func (b *repairGossipBase) queryProperty(ctx context.Context, syncShard *shard, leafNodeEntity string) (*queryProperty, *propertyv1.Property, error) { + g, n, entity, err := syncShard.repairState.parseLeafNodeEntity(leafNodeEntity) + if err != nil { + return nil, nil, fmt.Errorf("failed to parse leaf node entity %s: %w", leafNodeEntity, err) + } + searchQuery, err := inverted.BuildPropertyQueryFromEntity(groupField, g, n, entityID, entity) + if err != nil { + return nil, nil, fmt.Errorf("failed to build query from leaf node entity %s: %w", leafNodeEntity, err) + } + queriedProperties, err := syncShard.search(ctx, searchQuery, gossipShardQueryDatabaseSize) + if err != nil { + return nil, nil, fmt.Errorf("failed to search properties for leaf node entity %s: %w", leafNodeEntity, err) + } + var latestProperty *queryProperty + for _, queried := range queriedProperties { + if latestProperty == nil || queried.timestamp > latestProperty.timestamp { + latestProperty = queried + } + } + if latestProperty == nil { + return nil, nil, nil + } + var p propertyv1.Property + err = protojson.Unmarshal(latestProperty.source, &p) + if err != nil { + return nil, nil, fmt.Errorf("failed to unmarshal property from leaf node entity %s: %w", leafNodeEntity, err) + } + return latestProperty, &p, nil +} + +type repairGossipClient struct { + repairGossipBase +} + +func newRepairGossipClient(s *repairScheduler) *repairGossipClient { + return &repairGossipClient{ + repairGossipBase: repairGossipBase{ + scheduler: s, + }, + } +} + +func (r *repairGossipClient) Rev(ctx context.Context, nextNode *grpclib.ClientConn, request *propertyv1.PropagationRequest) error { + client := propertyv1.NewRepairServiceClient(nextNode) + var hasPropertyUpdated bool + defer func() { + if hasPropertyUpdated { + err := r.scheduler.buildingTree([]common.ShardID{common.ShardID(request.ShardId)}, request.Group, true) + if err != nil { + r.scheduler.l.Warn().Err(err).Msgf("failed to rebuild tree for group %s, shard %d", request.Group, request.ShardId) + } + } + }() + reader, found, err := r.getTreeReader(ctx, request.Group, request.ShardId) + if err != nil { + return errors.Wrapf(gossip.ErrAbortPropagation, "failed to get tree reader on client side: %v", err) + } + if !found { + return errors.Wrapf(gossip.ErrAbortPropagation, "tree for group %s, shard %d not found on client side", request.Group, request.ShardId) + } + defer reader.close() + + stream, err := client.Repair(ctx) + if err != nil { + return fmt.Errorf("failed to create repair stream: %w", err) + } + defer func() { + _ = stream.CloseSend() + }() + + // step 1: send merkle tree data + clientSlotNodes, err := r.sendTreeSummary(reader, request.Group, request.ShardId, stream) + if err != nil { + // if the tree summary cannot be built, we should abort the propagation + return errors.Wrapf(gossip.ErrAbortPropagation, "failed to query/send tree summary on client side: %v", err) + } + + syncShard, err := r.scheduler.db.loadShard(ctx, common.ShardID(request.ShardId)) + if err != nil { + return errors.Wrapf(gossip.ErrAbortPropagation, "shard %d load failure on client side: %v", request.ShardId, err) + } + firstTreeSummaryResp := true + + for { + recvResp, err := stream.Recv() + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return fmt.Errorf("failed to keep receive tree summary from server: %w", err) + } + + switch resp := recvResp.Data.(type) { + case *propertyv1.RepairResponse_DifferTreeSummary: + // step 2: check with the server for different leaf nodes + if !resp.DifferTreeSummary.TreeFound { + // if the tree is not found, we should abort the propagation + return errors.Wrapf(gossip.ErrAbortPropagation, "tree for group %s not found on server side", request.Group) + } + // there no different nodes, we can skip repair + if firstTreeSummaryResp && len(resp.DifferTreeSummary.Nodes) == 0 { + return nil + } + r.handleDifferSummaryFromServer(ctx, stream, resp.DifferTreeSummary, reader, syncShard, clientSlotNodes) + firstTreeSummaryResp = false + case *propertyv1.RepairResponse_PropertySync: + // step 3: keep receiving messages from the server + // if the server still sending different nodes, we should keep reading them + // if the server sends a PropertySync, we should repair the property and send the newer property back to the server if needed + sync := resp.PropertySync + updated, newer, err := syncShard.repair(ctx, sync.Id, sync.Property, sync.DeleteTime) + if err != nil { + r.scheduler.l.Warn().Err(err).Msgf("failed to repair property %s", sync.Id) + r.scheduler.metrics.totalRepairFailedCount.Inc(1, request.Group, fmt.Sprintf("%d", request.ShardId)) + } + if updated { + r.scheduler.l.Debug().Msgf("successfully repaired property %s", sync.Id) + r.scheduler.metrics.totalRepairSuccessCount.Inc(1, request.Group, fmt.Sprintf("%d", request.ShardId)) + hasPropertyUpdated = true + continue + } + // if the property hasn't been updated, and the newer property is not nil, + // which means the property is newer than the server side, + if !updated && newer != nil { + var p propertyv1.Property + err = protojson.Unmarshal(newer.source, &p) + if err != nil { + r.scheduler.l.Warn().Err(err).Msgf("failed to unmarshal property from db by entity %s", newer.id) + continue + } + // send the newer property to the server + err = stream.Send(&propertyv1.RepairRequest{ + Data: &propertyv1.RepairRequest_PropertySync{ + PropertySync: &propertyv1.PropertySync{ + Id: newer.id, + Property: &p, + DeleteTime: newer.deleteTime, + }, + }, + }) + if err != nil { + r.scheduler.l.Warn().Err(err).Msgf("failed to send newer property sync response to server, entity: %s", newer.id) + } + } + default: + r.scheduler.l.Warn().Msgf("unexpected response type: %T, expected DifferTreeSummary or PropertySync", resp) + } + } +} + +func (r *repairGossipClient) sendPropertyMissing(stream grpclib.BidiStreamingClient[propertyv1.RepairRequest, propertyv1.RepairResponse], entity string) { + err := stream.Send(&propertyv1.RepairRequest{ + Data: &propertyv1.RepairRequest_PropertyMissing{ + PropertyMissing: &propertyv1.PropertyMissing{ + Entity: entity, + }, + }, + }) + if err != nil { + r.scheduler.l.Warn().Err(err).Msgf("failed to send property missing response to client, entity: %s", entity) + } +} + +func (r *repairGossipClient) handleDifferSummaryFromServer( + ctx context.Context, + stream grpclib.BidiStreamingClient[propertyv1.RepairRequest, propertyv1.RepairResponse], + differTreeSummary *propertyv1.DifferTreeSummary, + reader repairTreeReader, + syncShard *shard, + clientSlotNodes map[int32]*repairTreeNode, Review Comment: We need a sliding window to manage both the summary and the reader, ensuring each is scanned only once. -- 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: notifications-unsubscr...@skywalking.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org