github.com/polarismesh/polaris@v1.17.8/cache/service/instance_bucket.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  	"strconv"
    22  	"sync"
    23  
    24  	"github.com/polarismesh/polaris/common/model"
    25  )
    26  
    27  func newServicePortsBucket() *servicePortsBucket {
    28  	return &servicePortsBucket{
    29  		servicePorts: map[string]map[string]*model.ServicePort{},
    30  	}
    31  }
    32  
    33  type servicePortsBucket struct {
    34  	lock sync.RWMutex
    35  	// servicePorts service-id -> []port
    36  	servicePorts map[string]map[string]*model.ServicePort
    37  }
    38  
    39  func (b *servicePortsBucket) reset() {
    40  	b.lock.Lock()
    41  	defer b.lock.Unlock()
    42  
    43  	b.servicePorts = make(map[string]map[string]*model.ServicePort)
    44  }
    45  
    46  func (b *servicePortsBucket) appendPort(serviceID string, protocol string, port uint32) {
    47  	if serviceID == "" || port == 0 {
    48  		return
    49  	}
    50  
    51  	b.lock.Lock()
    52  	defer b.lock.Unlock()
    53  
    54  	if _, ok := b.servicePorts[serviceID]; !ok {
    55  		b.servicePorts[serviceID] = map[string]*model.ServicePort{}
    56  	}
    57  
    58  	key := strconv.FormatInt(int64(port), 10) + "-" + protocol
    59  	ports := b.servicePorts[serviceID]
    60  	ports[key] = &model.ServicePort{
    61  		Port:     port,
    62  		Protocol: protocol,
    63  	}
    64  }
    65  
    66  func (b *servicePortsBucket) listPort(serviceID string) []*model.ServicePort {
    67  	b.lock.RLock()
    68  	defer b.lock.RUnlock()
    69  
    70  	ret := make([]*model.ServicePort, 0, 4)
    71  
    72  	val, ok := b.servicePorts[serviceID]
    73  
    74  	if !ok {
    75  		return ret
    76  	}
    77  
    78  	for k := range val {
    79  		ret = append(ret, val[k])
    80  	}
    81  	return ret
    82  }