Varnish Configuration Language (VCL)·续3
This example will call the /health endpoint for polling and will send a health check every ten seconds. The probe will wait for five seconds before it times out.
Customizing the entire HTTP request#
When the various probe options do not give you enough flexibility, you can even choose to fully customize the HTTP request that the probe will send out.
The .request property allows you to do this. However, this property is mutually exclusive with the .url property.
Here’s an example:
probe healtcheck {
.request =
"HEAD /health HTTP/1.1"
"Host: localhost"
"Connection: close"
"User-Agent: Varnish Health Probe";
.interval = 10s;
.timeout = 5s;
}
Although a lot of values remain the same, there are two customizations that are part of the request override :
- The request method is
HEADinstead ofGET. - We’re using the custom
Varnish Health ProbeUser-Agent.
Assigning the probe to a backend#
Once your probe is set up and configured, you need to assign it to a backend.
It’s a matter of setting the .probe property in your backend to the name of the probe, as you can see in the example below:
vcl 4.1;
probe healthcheck {
.url = "/health";
.interval = 10s;
.timeout = 5s;
}
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = healthcheck;
}
By defining your probe as a separate data structure, it can be reused when multiple backends are in use.
The verbose approach is to define the .probe property inline, as illustrated in the example below:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = {
.url = "/health";
.interval = 10s;
.timeout = 5s;
}
}
TCP-only probes#
Probes usually perform HTTP requests to check the health of a backend. By using TCP-only probes, the health of a backend is checked by the availability of the TCP connection.
This can be used to probe non-HTTP endpoints. However, TCP-only probes cannot be used with .url, .request, or .expected_response properties.
Here’s how you define such a probe:
probe tcp_healtcheck {
.tcponly = 1;
}
Keep in mind that TCP-only probes are only available in Varnish Enterprise.
UNIX domain sockets#
The backend data structure has additional properties that can be set with regard to the endpoint it is connecting to.
If you want to connect to your backend using a UNIX domain socket , you’ll use the .path property. It is mutually exclusive with the .host property and is only available when you use the vcl 4.1; version declaration.
Here’s an example of a UDS-based backend definition :
backend default {
.path = "/var/run/some-backend.sock";
}
Overriding the host header#
If for some reason the Host header is not set in your HTTP requests , you can use the .host_header property to override it.
Here’s an example:
backend default {
.host = "127.0.0.1";
.port = "8080";
.host_header = "example.com";
}
This .host_header property will be used for both regular backend requests and health probe checks.
Access control lists#
An access control list (ACL) is a VCL data structure that contains hostnames, IP addresses, and subnets. An ACL is used to match client addresses and restrict access to certain resources.
Here’s how you define an ACL:
acl admin {
"localhost";
"secure.my-server.com";
"192.168.0.0/24";
! "192.168.0.25";
}
This ACL named admin contains the following rules:
- Access from
localhostis allowed. - Access from the hostname
secure.my-server.comis also allowed. - All IP address in the
192.168.0.0/24subnet are allowed. - The only IP address from that range that is not allowed is
192.168.0.25.
In your VCL code, you can then match the client IP address to that list, as you’ll see in the next example:
acl admin {
"localhost";
"secure.my-server.com";
"192.168.0.0/24";
! "192.168.0.25";
}
sub vcl_recv {
if(req.url ~ "^/admin/?" && client.ip !~ admin) {
return(synth(403,"Forbidden"));
}
}
In this example, we’re hooking into vcl_recv to intercept requests for /admin or any subordinate resource of /admin/. If users try to access this resource, we check if their client IP address is matched by acl admin.
If it doesn’t match, an HTTP 403 Forbidden error is returned synthetically.
Functions#
Complex logic in a programming language is usually abstracted away by functions. This is also the case in VCL, which has a number of native functions.
The number of functions is limited, but extra functions are available in the wide range of VMODs that are supported by Varnish.
ban()#
ban() is a function that adds an expression to the ban list. These expressions are matched to cached objects. Every matching object is then removed from the cache.
In essence, the ban() function exists to invalidate multiple objects at the same time.
Here’s a quick example:
ban("obj.age > 1h");
Multiple expressions can be chained using the && operator.
hash_data()#
The hash_data() function is used within the vcl_hash subroutine and is used to append string data to the hash input that is used to lookup an object in cache.
Here’s some code from the built-in VCL for vcl_hash where hash_data() is used:
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
return (lookup);
}
synthetic()#
The synthetic() function prepares a synthetic response body and uses a string argument for its input. This function can be used within vcl_synth and vcl_backend_error.
Here’s an example for vcl_synth:
synthetic(resp.reason);
This function is no longer used in the built-in VCL. As of Varnish Cache 5.0 , it is recommended to instead use set beresp.body = {""};.
regsub()#
The regsub() function is a very popular function in Varnish. This function performs string substitution using regular expressions. Basically, do find/replace on the first occurrence using a regex pattern.
This is the API of this function:
regsub(string, regex, sub)
- The
stringargument is your input. - The
regexargument is the regular expression you’re using to match what you’re looking for in the input string. - The
subargument is what the input string will be substituted with.
Here’s a practical example where we use regsub() to extract a cookie value :
vcl 4.1;
sub vcl_hash {
hash_data(regsub(req.http.Cookie,"(;|^)language=([a-z]{2})(;|$)","\2"));
}
This vcl_hash subroutine is used to extend the built-in VCL and to add the value of the language cookie to the hash. This creates a cache variation per language.
We really don’t want to hash the entire cookie because that will drive our hit rate down, especially when there are tracking cookies in place.
In order to extract the exact cookie value we need, we’ll match the req.http.Cookie header to a regular expression that uses grouping. In the substitution part, we can refer to those groups to extract the value we want.
Here’s the regular expression:
(;|^)language=([a-z]{2})(;|$)
This regular expression looks for a language= occurrence, followed by two letters. These letters represent the language. This language cookie can occur at the beginning of the cookie string, in the middle, or at the end. The (;|^) and (;|$) statements ensure that this is possible.
Because we’re using parentheses for grouping, the group where we match the language itself, is indexed as group two. This means we can refer to it in the regsub() function as \2.
So if we look at the entire regsub() example:
regsub(req.http.Cookie,"(;|^)language=([a-z]{2})(;|$)","\2");
And let’s imagine this is our Cookie header:
Cookie: privacy_accepted=1;language=en;sessionid=03F1C5944FF4
Given the regular expression and the group referencing , the output of this regsub() function would be en.
This means that en will be added to the hash along with the URL and the host header.
When the Cookie header doesn’t contain a language cookie, an empty string is returned. When there is no Cookie header, an empty string is returned as well. This means we don’t risk hash-key collisions when the cookie isn’t set.
regsuball()#
The regsuball() function is very similar to the regsub() function we just covered. The only difference is where regsub() matches and replaces the first occurrence of the pattern, regsuball() matches all occurrences.
Even the function API is identical:
regsuball(string, regex, sub)
- The
stringargument is your input. - The
regexargument is the regular expression you’re using to match what you’re looking for in the input string. - The
subargument is what the input string will be substituted with.
Here’s a similar example, where we’ll strip off some cookies again. Instead of matching the values we want to keep, we’ll match the values we want to remove. We need to ensure that all occurrences are matched, not just the first occurrence. That’s why we use regsuball() instead of regsub():
regsuball(req.http.Cookie,"_g[a-z0-9_]+=[^;]*($|;\s*)","");
What this example does, is remove all Google Analytics cookies. This is the list of cookies we need to remove:
_ga_gid_gat_gac_<property-id>
Instead of stripping them off one by one, we can use the _g[a-z0-9_]+=[^;]*($|;\s*) regular expression to match them all at once. In the end we’ll replace the matched cookies with an empty string.
This could be the raw value of your req.http.Cookie header:
cookie1=a; _ga=GA1.2.1915485056.1587105100;cookie2=b; _gid=GA1.2.873028102.1599741176; _gat=1
And the end result is the following:
cookie1=a;cookie2=b
Subroutines#
Besides the built-in VCL subroutines you can also define your own subroutines. Here’s an example:
vcl 4.1;
sub skipadmin {
if(req.url ~ "^/admin/?") {
return(pass);
}
}
sub vcl_recv {
call skipadmin;
}
The skipadmin subroutine is entirely custom and is called within vcl_recv using the call statement. The purpose of custom subroutines is to allow code to be properly structured and functionality compartmentalized.
You are free to name your custom subroutine whatever you want, but keep in mind that the vcl_ naming prefixes are reserved for the Varnish finite state machine.
Please also keep in mind that a subroutine is not a function: it does not accept input parameters, and it doesn’t return values. It’s just a procedure that is called.
Include#
Not all of your VCL logic should necessarily be in the same VCL file. When the line count of your VCL file increases, readability can become an issue.
To tackle this issue, VCL allows you to include VCL from other files. The include syntax is not restricted to subroutines and fixed language structures, even individual lines of VCL code can be included.
The include "<filename>;" syntax will tell the compiler to read the file and copy its contents into the main VCL file.
When including a file, the order of execution in the main VCL file will be determined by the order of inclusion.
This means that each include can define its own VCL routing logic and if an included file exits the subroutine early, it will bypass any logic that followed that return statement.
Let’s apply this to our previous example, where the skipadmin subroutine is used and put the custom subroutine in a separate file:
#This is skipadmin.vcl
sub skipadmin {
if(req.url ~ "^/admin/?") {
return(pass);
}
}
In your main VCL file, you’ll use the include syntax to include skipadmin.vcl:
vcl 4.1;
include "skipadmin.vcl";
sub vcl_recv {
call skipadmin;
}
Import#
The import statement can be used to import VMODs. These are Varnish modules, written in C-code, that are loaded into Varnish and offer a VCL interface. These modules basically enrich the VCL syntax without being part of the Varnish core.
Here’s a quick example:
vcl 4.1;
import std;
sub vcl_recv {
set req.url = std.querysort(req.url);
}
This example uses import std; to import Varnish’s standard library containing a set of utility functions. The std.querysort() function will alphabetically sort the query string parameters of a URL, which has a beneficial impact on the hit rate of the cache.
