From 3e145a364f5db1cba2442ef036603b5ee697b5b6 Mon Sep 17 00:00:00 2001 From: Ankit Gupta Date: Sat, 26 May 2018 14:59:50 +0530 Subject: [PATCH] Bug fix: findCeilIn --- algorithm/randomize.go | 12 ++++++++++++ algorithm/select_service.go | 35 ++++++++++++++++++++++++++++------- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/algorithm/randomize.go b/algorithm/randomize.go index da499b4..e60a58a 100644 --- a/algorithm/randomize.go +++ b/algorithm/randomize.go @@ -16,3 +16,15 @@ func randomize(init int, set int) int { return choice } + +func randomize64(init int64, set int64) int64 { + + if set <= init { + return int64(0) + } + + rand.Seed(time.Now().UTC().UnixNano()) + choice := rand.Int63n(set - init) + init + + return choice +} diff --git a/algorithm/select_service.go b/algorithm/select_service.go index 38f59bd..7c4682f 100644 --- a/algorithm/select_service.go +++ b/algorithm/select_service.go @@ -43,15 +43,36 @@ func ChooseServiceIndex(sqp *model.ServiceQProperties, initialChoice int, retry prefixes[i] = weights[i] + prefixes[i-1] } } - randx := randomize(1, int(prefixes[len(prefixes) - 1])) - for i, n := range prefixes { - if int(n) >= randx { - return i - } - } + prLen := len(prefixes) - 1 + randx := randomize64(1, int64(prefixes[prLen])) + ceil := findCeilIn(randx, prefixes, 0, prLen) + if ceil >= 0 { + return ceil } - return randomize(0, noOfServices) + } + return randomize(0, noOfServices) } else { return roundrobin(noOfServices, initialChoice) } } + +func findCeilIn(randx int64, prefixes []float64, start int, end int) int { + + var mid int + for { + if start >= end { + break + } + mid = start + ((end - start) >> 1) + if randx > int64(prefixes[mid]) { + start = mid + 1 + } else { + end = mid + } + } + + if randx <= int64(prefixes[start]) { + return start + } + return -1 +}