github.com/deemoprobe/k8s-first-commit@v0.0.0-20230430165612-a541f1982be3/pkg/proxy/roundrobbin.go (about)

     1  /*
     2  Copyright 2014 Google Inc. All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  // RoundRobin Loadbalancer
    17  
    18  package proxy
    19  
    20  import (
    21  	"errors"
    22  	"log"
    23  	"net"
    24  	"reflect"
    25  	"strconv"
    26  	"strings"
    27  	"sync"
    28  
    29  	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
    30  )
    31  
    32  type LoadBalancerRR struct {
    33  	lock         sync.RWMutex
    34  	endpointsMap map[string][]string
    35  	rrIndex      map[string]int
    36  }
    37  
    38  func NewLoadBalancerRR() *LoadBalancerRR {
    39  	return &LoadBalancerRR{endpointsMap: make(map[string][]string), rrIndex: make(map[string]int)}
    40  }
    41  
    42  func (impl LoadBalancerRR) LoadBalance(service string, srcAddr net.Addr) (string, error) {
    43  	impl.lock.RLock()
    44  	endpoints, exists := impl.endpointsMap[service]
    45  	index := impl.rrIndex[service]
    46  	impl.lock.RUnlock()
    47  	if exists == false {
    48  		return "", errors.New("no service entry for:" + service)
    49  	}
    50  	if len(endpoints) == 0 {
    51  		return "", errors.New("no endpoints for: " + service)
    52  	}
    53  	endpoint := endpoints[index]
    54  	impl.rrIndex[service] = (index + 1) % len(endpoints)
    55  	return endpoint, nil
    56  }
    57  
    58  func (impl LoadBalancerRR) IsValid(spec string) bool {
    59  	index := strings.Index(spec, ":")
    60  	if index == -1 {
    61  		return false
    62  	}
    63  	value, err := strconv.Atoi(spec[index+1:])
    64  	if err != nil {
    65  		return false
    66  	}
    67  	return value > 0
    68  }
    69  
    70  func (impl LoadBalancerRR) FilterValidEndpoints(endpoints []string) []string {
    71  	var result []string
    72  	for _, spec := range endpoints {
    73  		if impl.IsValid(spec) {
    74  			result = append(result, spec)
    75  		}
    76  	}
    77  	return result
    78  }
    79  
    80  func (impl LoadBalancerRR) OnUpdate(endpoints []api.Endpoints) {
    81  	tmp := make(map[string]bool)
    82  	impl.lock.Lock()
    83  	defer impl.lock.Unlock()
    84  	// First update / add all new endpoints for services.
    85  	for _, value := range endpoints {
    86  		existingEndpoints, exists := impl.endpointsMap[value.Name]
    87  		if !exists || !reflect.DeepEqual(value.Endpoints, existingEndpoints) {
    88  			log.Printf("LoadBalancerRR: Setting endpoints for %s to %+v", value.Name, value.Endpoints)
    89  			impl.endpointsMap[value.Name] = impl.FilterValidEndpoints(value.Endpoints)
    90  			// Start RR from the beginning if added or updated.
    91  			impl.rrIndex[value.Name] = 0
    92  		}
    93  		tmp[value.Name] = true
    94  	}
    95  	// Then remove any endpoints no longer relevant
    96  	for key, value := range impl.endpointsMap {
    97  		_, exists := tmp[key]
    98  		if !exists {
    99  			log.Printf("LoadBalancerRR: Removing endpoints for %s -> %+v", key, value)
   100  			delete(impl.endpointsMap, key)
   101  		}
   102  	}
   103  }