Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Varnish sticky session (prefix)
varnishtest "Test cookie vmod"
server s1 {
rxreq
txresp -hdr "set-cookie: id=123;"
rxreq
expect req.http.cookie == "id=123;"
txresp -hdr "server: s1"
rxreq
expect req.http.cookie == "id=123;"
txresp -hdr "server: s1"
} -start
server s2 {
rxreq
txresp -hdr "set-cookie: id=456;"
rxreq
expect req.http.cookie == "id=456;"
txresp -hdr "server: s2"
rxreq
expect req.http.cookie == "id=456;"
txresp -hdr "server: s2"
} -start
varnish v1 -vcl+backend {
import cookie from "${modules_builddir}/.libs/libvmod_cookie.so";
import directors from "${topbuild}/lib/libvmod_directors/.libs/libvmod_directors.so";
sub vcl_init {
new rr = directors.round_robin();
rr.add_backend(s1);
rr.add_backend(s2);
}
sub vcl_backend_response {
cookie.parse(beresp.http.set-cookie);
cookie.set("id", beresp.backend + "~" + cookie.get("id"));
set beresp.http.set-cookie = cookie.get_string();
}
sub vcl_recv {
cookie.parse(req.http.cookie);
set req.http.prefix = regsub(cookie.get("id"), "~.*", "");
cookie.set("id", regsub(cookie.get("id"), "^[^~]*~", ""));
set req.http.cookie = cookie.get_string();
if (req.http.prefix == "s1") {
set req.backend_hint = s1;
} else if (req.http.prefix == "s2") {
set req.backend_hint = s2;
} else {
set req.backend_hint = rr.backend();
}
return (pass);
}
} -start
client c1 {
txreq
rxresp
expect resp.http.set-cookie == "id=s1~123;"
txreq
rxresp
expect resp.http.set-cookie == "id=s2~456;"
txreq -hdr "cookie: id=s2~456;"
rxresp
expect resp.http.server == "s2"
txreq -hdr "cookie: id=s1~123;"
rxresp
expect resp.http.server == "s1"
txreq -hdr "cookie: id=s1~123;"
rxresp
expect resp.http.server == "s1"
txreq -hdr "cookie: id=s2~456;"
rxresp
expect resp.http.server == "s2"
} -run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.