Varnish Configuration Language (VCL)·续2
VCL version declaration#
Every VCL file starts with a version declaration. As of Varnish 6, the version declaration you’ll want to use is the following:
vcl 4.1;
The VCL version declaration does not reflect the Varnish version it runs on, but instead ensures compability of the VCL syntax. In Varnish 6 , Unix domain socket support introduced a backwards compatibility break: the .path variable in the backend declaration is not supported on older versions of Varnish and VCL syntax version 4.0.
The vcl 4.0; declaration will still work on Varnish 6 , but it prevents some specific Varnish 6 features from being supported.
Assigning values#
The VCL language doesn’t require you to program the full behavior, but rather allows you to extend pre-existing built-in behavior. Given this scope and purpose, the main objective is to set values based on certain conditions.
Let’s take the following line of code for example:
set resp.http.Content-Type = "text/html; charset=utf-8";
It comes from the vcl_synth built-in VCL and assigns the content type text/html; charset=utf-8 to the HTTP response header resp.http.Content-Type.
We’re basically assigning a string to a variable. The assigning is done by using the set keyword. If we want to unset a variable, we just use the unset keyword.
Let’s illustrate the unset behavior with another example:
unset bereq.body;
We’re unsetting the bereq.body variable. This is part of the vcl_backend_fetch logic of the built-in VCL.
Strings#
VCL supports various data types, but the string type is by far the most common one.
Here’s a conceptual example:
set variable = "value";
This is the easiest way to assign a string value. But as soon as you want to use newlines or double quotes, you’re in trouble.
Luckily there’s an alternative, which is called long strings. A long string begins with {" and ends with "}.
They may include newlines, double quotes, and other control characters, except for the NULL (0x00) character.
A very familiar usage of this is the built-in VCL implementation of vcl_synth, where the HTML template is composed using long strings:
set resp.body = {"<!DOCTYPE html>
<html>
<head>
<title>"} + resp.status + " " + resp.reason + {"</title>
</head>
<body>
<h1>Error "} + resp.status + " " + resp.reason + {"</h1>
<p>"} + resp.reason + {"</p>
<h3>Guru Meditation:</h3>
<p>XID: "} + req.xid + {"</p>
<hr>
<p>Varnish cache server</p>
</body>
</html>
"};
There is also an alternate form of a long string, which can be delimited by triple double quotes, """...""".
This example also shows how to perform string concatenation and variable interpolation. Let’s reimagine the vcl_synth example, and create a version using simple strings :
set beresp.body = "Status: " + resp.status + ", reason: " + resp.reason";
And again we’re using the +-sign for string concatenation and variable interpolation.
Conditionals#
Although the VCL language is limited in terms of control structures , it does provide conditionals , meaning if/else statements.
Let’s take some built-in VCL code as an example since we’re so familiar with it:
if (req.method != "GET" && req.method != "HEAD") {
/* We only deal with GET and HEAD by default */
return (pass);
}
This is just a regular if-statement. We can also add an else clause :
if (req.method != "GET" && req.method != "HEAD") {
/* We only deal with GET and HEAD by default */
return (pass);
} else {
return (hash);
}
And as you’d expect, there’s also an elseif clause :
if (req.method == "GET") {
return (hash);
} elseif (req.method == "HEAD") {
return (hash);
} else {
return (pass);
}
elsif, elif and else if can also be used as an equivalent for elseif.
Operators#
VCL has a number of operators that either evaluate to true or to false:
- The
=operator is used to assign values. - The
==,!=,<,<=,>, and>=operators are used to compare values. - The
~operator is used to match values to a regular expression or an ACL. - The
!operator is used for negation. &&is the logical and operator.||is the logical or operator.
And again the built-in VCL comes to the rescue to clarify how some of these operators can be used:
if (req.method != "GET" && req.method != "HEAD") {
/* We only deal with GET and HEAD by default */
return (pass);
}
You can clearly see the negation and the logical and , meaning that the expression only evaluates to true when condition one and condition two are false.
We’ve already used the = operator to assign values, but here’s another example for reference:
set req.http.X-Forwarded-Proto = "https";
This example assigns the https value to the X-Forwarded-Proto request header.
A logical or looks like this:
if(req.method == "POST" || req.method == "PUT") {
return(pass);
}
At least one of the two conditions has to be true for the expression to be true.
And let’s end this part with a less than or equals example:
if(beresp.ttl <= 0s {
set beresp.uncacheable = true;
}
Comments#
Documenting your code with comments is usually a good idea, and VCL supports three different comment styles.
We’ve listed all three of them in the example below:
sub vcl_recv {
// Single line of out-commented VCL.
# Another way of commenting out a single line.
/*
Multi-line block of commented-out VCL.
*/
}
So you can use // or # to create a single-line comment. And /* ... */ can be used for multi-line comments.
Numbers#
VCL supports numeric values, both integers and real numbers.
Certain fields are numeric, so it makes sense to assign literal integer or real values to them.
Here’s an example:
set resp.status = 200;
But most variables are strings, so these numbers get cast into strings. For real numbers , their value is rounded to three decimal places (e.g. 3.142).
Booleans#
Booleans can be either true or false. Here’s an example of a VCL variable that expects a boolean:
set beresp.uncacheable = true;
When evaluating values of non-boolean types, the result can also be a boolean.
For example strings will evaluate to true or false if their existence is checked. This could result in the following example:
if(!req.http.Cookie) {
//Do something
}
if(req.http.Authorization) {
//Do something
}
Be aware that the header variable must be undefined or unset for it to be evaluated as false. If the header variable is defined with an empty value, it will evaluate as true.
Integers will evaluate to false if their value is 0; the same applies to duration types when their values are zero or less.
Boolean types can also be set based on the result of another boolean expression:
set beresp.uncachable = (beresp.http.do-no-cache == "true");
Time and durations#
Time is an absolute value, whereas a duration is a relative value. However, in Varnish they are often combined.
Time#
You can add a duration to a time, which results in a new time:
set req.http.tomorrow = now + 1d;
The now variable is how you can retrieve the current time in VCL. The now + 1d statement means we’re adding a day to the current time. The returned value is also a time type.
But since we’re assigning a time type to a string field , the time value is cast to a string, which results in the following string value:
Thu, 10 Sep 2020 12:34:54 GMT
Duration#
As mentioned, durations are relative. They express a time change and are expressed numerically, but with a time unit attached.
Here are a couple of examples that illustrate the various time units:
1msequals 1 millisecond.5sequals 5 seconds.10mequals 10 minutes.3hequals 3 hours.9dequals 9 days.4wequals 4 weeks.1yequals 1 year.
In string context their numeric value is kept, and the time unit is stripped off. This is exactly what a real number looks like when cast to a string. And just like real numbers , they are rounded to three decimal places (e.g. 3.142).
Here’s an example of a VCL variable that supports durations :
set beresp.ttl = 1h;
So this example sets the TTL of an object to one hour.
Regular expressions#
Pattern matching is a very common practice in VCL. That’s why VCL supports Perl Compatible Regular Expressions (PCRE) , and we can match values to a PCRE regex through the ~ operator:
if(req.url ~ "^/[a-z]{2}/cart") {
return(pass);
}
This example is matching the request URL to a regex pattern that looks for the shopping cart URL of a website. This URL is prefixed by two letters, which represent the user’s selected language. When the URL is matched, the request bypasses the cache.
Backends#
Varnish is a proxy server and depends on an origin server to provide (most of) the content. A backend definition is indispensable, even if you end up serving synthetic content.
This is what a backend looks like:
backend default {
.host = "127.0.0.1";
.port = "8080";
}
It has a name , default in this case, and uses the .host and .port properties to define how Varnish can connect to the origin server. The first backend that is defined will be used.
If you’re not planning to use a backend, or if you are using a module for dynamic backends, you’ll have to define the following backend configuration:
backend default none;
This bypasses the requirement that you must define a single backend in your VCL.
Backends also support the following options:
.connect_timeoutis how long to wait for a connection to be made to the backend..first_byte_timeoutis how long to wait for the first byte of the response..between_bytes_timeoutis the maximum time to wait between bytes when reading the response..last_byte_timeoutis the total time to wait for the complete backend response..max_connectionsis the maximum number of concurrent connections Varnish will hold to the backend. When this limit is reached, requests will fail intovcl_backend_error.
Probes#
Knowing whether or not a backend is healthy is important. It helps to avoid unnecessary outages and allows you to use a fallback system.
When using probes , you can perform health checks at regular intervals. The probe sets the internal value of the health of that backend to healthy or sick.
Backends that are sick always result in an HTTP 503 error when called.
If you use vmod_directors to load balance with multiple backends, sick backends will be removed from the rotation until their health checks are successful and their state changes to healthy.
A sick backend will become healthy when a threshold of successful polls is reached within a polling window.
This is how you define a probe :
probe healthcheck {
}
Default values#
The probe data structure has a bunch of attributes; even without mentioning these attributes, they will have a default behavior:
.urlis the URL that will be polled. The default value is/..expected_responseis the HTTP status code to that the probe expects. The default value is200..timeoutis the amount of time the probe is willing to wait for a response before timing out. The default value is2s..intervalis the polling interval. The default value is5s..windowis the number of polls that are examined to determine the backend health. The default value is8..initialis the number of polls in.windowthat have to be successful before Varnish starts. The default value is2..thresholdis the number of polls in.windowthat have to be successful to consider the backend healthy. The default value is3..tcponlyis the mode of the probe. When enabled with1, the probe will only check for available TCP connections. The default value is0. This property is only available in Varnish Enterprise.
Extending values#
You can start extending the probe by assigning values to these defaults.
Here’s an example:
probe healthcheck {
.url = "/health";
.interval = 10s;
.timeout = 5s;
}
