github.com/mholt/caddy-l4@v0.0.0-20241104153248-ec8fae209322/modules/l4proxy/loadbalancing_test.go (about)

     1  // Copyright 2020 Matthew Holt
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package l4proxy
    16  
    17  import (
    18  	"encoding/binary"
    19  	"fmt"
    20  	"math/rand"
    21  	"net"
    22  	"testing"
    23  )
    24  
    25  func TestHostByHashing(t *testing.T) {
    26  	upstreamCount := 254
    27  	keyCount := 9
    28  	matchCount := 2
    29  
    30  	selectResults := map[string]string{}
    31  
    32  	mockPool := func() []*Upstream {
    33  		var result []*Upstream
    34  		var upstreamDial []string
    35  		for i := 0; i < upstreamCount; i++ {
    36  			if i%3 == 0 {
    37  				upstreamDial = []string{fmt.Sprintf("192.168.0.%d:8001,192.168.0.%d:9001", i+1, i+1)}
    38  			} else {
    39  				upstreamDial = []string{fmt.Sprintf("192.168.0.%d:8001", i+1)}
    40  			}
    41  
    42  			result = append(result, &Upstream{
    43  				Dial: upstreamDial,
    44  			})
    45  		}
    46  		return result
    47  	}()
    48  
    49  	mockKeys := func() []string {
    50  		// see https://gist.github.com/porjo/f1e6b79af77893ee71e857dfba2f8e9a
    51  		var result []string
    52  		buf := make([]byte, 4)
    53  		for i := 0; i < keyCount; i++ {
    54  			ip := rand.Uint32()
    55  			binary.LittleEndian.PutUint32(buf, ip)
    56  			result = append(result, fmt.Sprintf("%s", net.IP(buf)))
    57  		}
    58  		return result
    59  	}()
    60  
    61  	for i := 0; i < matchCount; i++ {
    62  		for _, mockKey := range mockKeys {
    63  			selected := hostByHashing(mockPool, mockKey)
    64  			t.Logf("[match#%d] %s -> %s", i, mockKey, selected.String())
    65  
    66  			if selectResults[mockKey] != "" && selectResults[mockKey] != selected.String() {
    67  				t.FailNow()
    68  			}
    69  			if i == 0 {
    70  				selectResults[mockKey] = selected.String()
    71  			}
    72  		}
    73  	}
    74  }