❦ 8 décembre 2014 11:30 -0600, Vivek Malik <[email protected]> :
> I am using rand(x) in configuration to make some routing decisions. I
> am basically load balancing between backends and using the following
> configuration
>
> use_backend bk_1 { rand(100) le 50 }
> default_backend bk_2
>
> However, I am not seeing any traffic going to bk_2 and all traffic
> goes to bk_1. It seems that there is a bug in smp_fetch_rand function
> around reduction.
>
> I did some further testing by setting up a header using
>
> http-request set-header X-RAND %[rand(200)]
>
> and printing that header in a file. I am unable to see the random
> value going above arg/2.
You are right. HAProxy is doing that:
#+begin_src c
unsigned int uint = random();
uint = ((uint64_t)uint * 100) >> 32;
#+end_src
However, random() is returning an integer between 0 and RAND_MAX,
RAND_MAX being (usually?) equal to INT_MAX. This means that the most
significant bit is always 0.
It seems that there is nothing preventing RAND_MAX to be smaller. The
GNU LibC manual says it can be as small as 32767. So, we should shift
only by the highest significant bit of RAND_MAX.
Assuming that RAND_MAX is always a power of two - 1, 32 could be
replaced by a precomputed value of ffs(RAND_MAX+1)-1.
--
Don't patch bad code - rewrite it.
- The Elements of Programming Style (Kernighan & Plauger)