Varnish VCL: how can I switch on req.backend_hint?

2019-07-11 06:22发布

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

2条回答
我只想做你的唯一
2楼-- · 2019-07-11 07:13

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");
    }
}
查看更多
【Aperson】
3楼-- · 2019-07-11 07:28

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

查看更多
登录 后发表回答