2

I have the following VCL:

vcl 4.0;

import std;
import directors;

backend one {
    .host = "localhost";
    .port = "3333";
}

backend two {
    .host = "localhost";
    .port = "3333";
}

sub vcl_init {
    new random_director = directors.random();
    random_director.add_backend(two, 10);
    random_director.add_backend(one, 8);
}

sub vcl_recv {

    std.log("start vcl_recv");

    set req.backend_hint = random_director.backend();
    if (req.backend_hint == one) {
        std.log("one");
    } else if (req.backend_hint == two) {
        std.log("two");
    } else {
        std.log("neither one");
    }

    std.log("end vcl_recv");
}

When I run it, the output is always:

start vl_recv
neither one
end vcl_recv

How can I properly check to see which backend has been selected?

Thanks

tadasajon
  • 14,276
  • 29
  • 92
  • 144
  • What happens if you just `std.log(req.backend_hint)` just after setting it? –  Apr 14 '17 at 06:53

2 Answers2

1

In vcl_backend_fetch you should be able to access bereq.backend.name

So moving your code, you might have something like:

sub vcl_backend_fetch {
    if (bereq.backend.name == "one") {
       std.log("one");
    } else if (bereq.backend.name == "two") {
       std.log("two");
    } else {
       std.log("neither one");
    }
}
Joshua DeWald
  • 3,079
  • 20
  • 16
0

Update: it's not possible to know the selected backend before requesting a backend call, so you'll never get this information in the vcl_recv. As you may not need the backend selection (if the object is already in cache), or because the backend could change (if one goes down) before the selection is run (so the time between the vcl_recv and vcl_fetch_response), it would be a waste of resources to determine it in the vcl_recv.

But in Varnish 5.0+ you can use the beresp.backend (or beresp.backend.name as you need to log it as a string) available in vcl_backend_response, which is defined as:

This is the backend we fetched from. If bereq.backend was set to a director, this will be the backend selected by the director.

See: https://varnish-cache.org/docs/5.0/reference/vcl.html#beresp

Yvan
  • 2,539
  • 26
  • 28