github.com/polarismesh/polaris@v1.17.8/service/event.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package service 19 20 import ( 21 "context" 22 "time" 23 24 "github.com/polarismesh/polaris/common/model" 25 ) 26 27 type serviceNameResolver func(string) *model.Service 28 29 const maxRetryGetServiceName = 5 30 31 type BaseInstanceEventHandler struct { 32 namingServer DiscoverServer 33 svcResolver serviceNameResolver 34 } 35 36 func NewBaseInstanceEventHandler(namingServer DiscoverServer) *BaseInstanceEventHandler { 37 eventHandler := &BaseInstanceEventHandler{namingServer: namingServer} 38 eventHandler.svcResolver = eventHandler.resolveService 39 return eventHandler 40 } 41 42 func (b *BaseInstanceEventHandler) resolveService(svcId string) *model.Service { 43 return b.namingServer.Cache().Service().GetServiceByID(svcId) 44 } 45 46 // PreProcess do preprocess logic for event 47 func (b *BaseInstanceEventHandler) PreProcess(ctx context.Context, value any) any { 48 instEvent, ok := value.(model.InstanceEvent) 49 if !ok { 50 return value 51 } 52 b.resolveServiceName(&instEvent) 53 return instEvent 54 } 55 56 func (b *BaseInstanceEventHandler) resolveServiceName(event *model.InstanceEvent) { 57 if len(event.Service) == 0 && len(event.SvcId) > 0 { 58 for i := 0; i < maxRetryGetServiceName; i++ { 59 svcObject := b.svcResolver(event.SvcId) 60 if nil == svcObject { 61 time.Sleep(500 * time.Millisecond) 62 continue 63 } 64 event.Service = svcObject.Name 65 event.Namespace = svcObject.Namespace 66 break 67 } 68 } 69 }