VMOD - Varnish Modules
For all you can do in VCL, there are things you cannot do. Look an IP number up in a database file for instance. VCL provides for inline C code, and there you can do everything, but it is not a convenient or even readable way to solve such problems.
This is where VMODs come into the picture: A VMOD is a shared library with some C functions which can be called from VCL code.
For instance:
import std;
sub vcl_deliver {
set resp.http.foo = std.toupper(req.url);
}
The “std” vmod is one you get with Varnish, it will always be there and we will put “boutique” functions in it, such as the “toupper” function shown above. The full contents of the “std” module is documented in vmod_std(3).
This part of the manual is about how you go about writing your own VMOD, how the language interface between C and VCC works, where you can find contributed VMODs etc. This explanation will use the “std” VMOD as example, having a Varnish source tree handy may be a good idea.
VMOD Directory#
The VMOD directory is an up-to-date compilation of maintained extensions written for Varnish Cache:
<https://www.varnish-cache.org/vmods>
Getting started writing VMODs#
There are some projects which can help interested developers get started writing VMODs:
- For the C programming language, there is the Varnish Cache Development Kit (VCDK)
- Rustacians might want to have a look at varnish-rs.
The vmod.vcc file#
The interface between your VMOD and the VCL compiler (“VCC”) and the VCL runtime (“VRT”) is defined in the vmod.vcc file which a python script called “vmodtool.py” turns into thaumaturgically challenged C data structures that do all the hard work.
The std VMODs vmod.vcc file looks somewhat like this:
$ABI strict
$Version my.version
$Module std 3 "Varnish Standard Module"
$Event event_function
$Function STRING toupper(STRANDS s)
$Function STRING tolower(STRANDS s)
$Function VOID set_ip_tos(INT)
The $ABI line is optional. Possible values are strict (default) and vrt. It allows to specify that a vmod is integrating with the blessed vrt interface provided by varnishd or go deeper in the stack.
As a rule of thumb you, if the VMOD uses more than the VRT (Varnish RunTime), in which case it needs to be built for the exact Varnish version, use strict. If it complies to the VRT and only needs to be rebuilt when breaking changes are introduced to the VRT API, use vrt.
The $Version line is also optional. It specifies the version identifier compiled into the VMOD binary for later identification. If omitted, PACKAGE_STRING from an automake Makefile will be used, or NOVERSION otherwise.
The $Module line gives the name of the module, the manual section where the documentation will reside, and the description.
The $Event line specifies an optional “Event” function, which will be called whenever a VCL program which imports this VMOD is loaded or transitions to any of the warm, active, cold or discarded states. More on this below.
The $Function lines define three functions in the VMOD, along with the types of the arguments, and that is probably where the hardest bit of writing a VMOD is to be found, so we will talk about that at length in a moment.
Notice that the third function returns VOID, that makes it a “procedure” in VCL lingo, meaning that it cannot be used in expressions, right side of assignments and such. Instead it can be used as a primary action, something functions which return a value cannot:
sub vcl_recv {
std.set_ip_tos(32);
}
Running vmodtool.py on the vmod.vcc file, produces a “vcc_if.c” and “vcc_if.h” files, which you must use to build your shared library file.
Forget about vcc_if.c everywhere but your Makefile, you will never need to care about its contents, and you should certainly never modify it, that voids your warranty instantly.
But vcc_if.h is important for you, it contains the prototypes for the functions you want to export to VCL.
For the std VMOD, the compiled vcc_if.h file looks like this:
VCL_STRING vmod_toupper(VRT_CTX, VCL_STRANDS);
VCL_STRING vmod_tolower(VRT_CTX, VCL_STRANDS);
VCL_VOID vmod_set_ip_tos(VRT_CTX, VCL_INT);
vmod_event_f event_function;
Those are your C prototypes. Notice the vmod_ prefix on the function names, more on that in C symbols.
Named arguments and default values#
The basic vmod.vcc function declaration syntax introduced above makes all arguments mandatory for calls from vcl - which implies that they need to be given in order.
Naming the arguments as in:
$Function BOOL match_acl(ACL acl, IP ip)
allows calls from VCL with named arguments in any order, for example:
if (debug.match_acl(ip=client.ip, acl=local)) { # ...
Named arguments also take default values, so for this example from the debug vmod:
$Function STRING argtest(STRING one, REAL two=2, STRING three="3",
STRING comma=",", INT four=4)
only argument one is required, so that all of the following are valid invocations from vcl:
debug.argtest("1", 2.1, "3a")
debug.argtest("1", two=2.2, three="3b")
debug.argtest("1", three="3c", two=2.3)
debug.argtest("1", 2.4, three="3d")
debug.argtest("1", 2.5)
debug.argtest("1", four=6);
The C interface does not change with named arguments and default values, arguments remain positional and default values appear no different to user specified values.
Note that default values have to be given in the native C-type syntax, see below. As a special case, NULL has to be given as 0.
Optional arguments#
The vmod.vcc declaration also allows for optional arguments in square brackets like so:
$Function VOID opt(PRIV_TASK priv, INT four = 4, [STRING opt])
With any optional argument present, the C function prototype looks completely different:
- Only the
VRT_CTXand object pointer arguments (only for methods) remain positional- All other arguments get passed in a struct as the last argument of the C function.
The argument struct is simple, vmod authors should check the vmodtool-generated vcc_if.c file for the function and struct declarations:
- for each optional argument, a
valid_argument member is used to signal the presence of the respective optional argument.
valid_argstruct members should only be used as truth values, irrespective of their actual data type.
- named arguments are passed in argument struct members by the same name and with the same data type.
- unnamed (positional) arguments are passed as
argn with n starting at 1 and incrementing with the argument’s position.
Optionally, the VCL and C argument names can be specified independently using the <vclname>:<cname> syntax. See C symbols for details.
Objects and methods#
Varnish also supports a simple object model for vmods. Objects and methods are declared in the vcc file as:
$Object class(...)
$Method .method(...)
For declared object classes of a vmod, object instances can then be created in vcl_init { } using the new statement:
sub vcl_init {
new foo = vmod.class(...);
}
and have their methods called anywhere (including in vcl_init {} after the instantiation):
sub somewhere {
foo.method(...);
}
Nothing prevents a method to be named like the constructor and the meaning of such a method is up to the vmod author:
$Object foo(...)
$Method .bar(...)
$Method .foo(...)
Object instances are represented as pointers to vmod-implemented C structs. Varnish only provides space to store the address of object instances and ensures that the right object address gets passed to C functions implementing methods.
- Objects’ scope and lifetime are the vcl
- Objects can only be created in
vcl_init {}and have their destructors called by varnish aftervcl_fini {}has completed.
vmod authors are advised to understand the prototypes in the vmodtool-generated vcc_if.c file:
- For
$Objectdeclarations, a constructor and destructor function must be implemented- The constructor is named by the suffix
__init, always is ofVOIDreturn type and has the following arguments before the vcc-declared parameters:
VRT_CTXas usual- a pointer-pointer to return the address of the created oject
- a string containing the vcl name of the object instance
- The destructor is named by the suffix
__fini, always is ofVOIDreturn type and has a single argument, the pointer-pointer to the address of the object. The destructor is expected clear the address of the object stored in that pointer-pointer.- Methods gain the pointer to the object as an argument after the
VRT_CTX.
As varnish is in no way involved in managing object instances other than passing their addresses, vmods need to implement all aspects of managing instances, in particular their memory management. As the lifetime of object instances is the vcl, they will usually be allocated from the heap.
Functions and Methods scope restriction#
The $Restrict stanza offers a way to limit the scope of the preceding vmod function or method, so that they can only be called from restricted vcl call sites. It must only appear after a $Method or $Function and has the following syntax:
$Restrict scope1 [scope2 ...]
Possible scope values are: backend, client, housekeeping, vcl_recv, vcl_pipe, vcl_pass, vcl_hash, vcl_purge, vcl_miss, vcl_hit, vcl_deliver, vcl_synth, vcl_backend_fetch, vcl_backend_response, vcl_backend_error, vcl_init, vcl_fini
Deprecated Aliases#
The $Alias stanza offers a mechanism to rename a function or an object’s method without removing the previous name. This allows name changes to maintain compatibility until the alias is dropped.
The syntax for a function is:
$Alias deprecated_function original_function
[description]
The syntax for a method is:
$Alias .deprecated_method object.original_method
[description]
The $Alias stanza can appear anywhere, this allows grouping them in a dedicated “deprecated” section of their manual. The optional description can be used to explain why a function was renamed.
VCL and C data types#
VCL data types are targeted at the job, so for instance, we have data types like “DURATION” and “HEADER”, but they all have some kind of C language representation. Here is a description of them.
All but the PRIV types have typedefs: VCL_INT, VCL_REAL, etc.
Notice that most of the non-native (C pointer) types are const, which, if returned by a vmod function/method, are assumed to be immutable. In other words, a vmod must not modify any data which was previously returned.
When returning non-native values, the producing function is responsible for arranging memory management. Either by freeing the structure later by whatever means available or by using storage allocated from the client or backend workspaces.
ACL
C-type: const struct vrt_acl *
A type for named ACLs declared in VCL.
BACKEND
C-type: const struct director *
A type for backend and director implementations. See Writing a Director.
BLOB
C-type: const struct vmod_priv *
An opaque type to pass random bits of memory between VMOD functions.
BODY
C-type: const void *
A type only used on the LHS of an assignment that can take either a blob or an expression that can be converted to a string.
BOOL
C-type: unsigned
Zero means false, anything else means true.
BYTES
C-type: double
Unit: bytes.
A storage space, as in 1024 bytes.
DURATION
C-type: double
Unit: seconds.
A time interval, as in 25 seconds.
ENUM
vcc syntax: ENUM { val1, val2, … }
vcc example: ENUM { one, two, three } number="one"
C-type: const char *
Allows values from a set of constant strings. Note that the C-type is a string, not a C enum.
Enums will be passed as fixed pointers, so instead of string comparisons, also pointer comparisons with VENUM(name) are possible.
HEADER
C-type: const struct gethdr_s *
These are VCL compiler generated constants referencing a particular header in a particular HTTP entity, for instance req.http.cookie or beresp.http.last-modified. By passing a reference to the header, the VMOD code can both read and write the header in question.
If the header was passed as STRING, the VMOD code only sees the value, but not where it came from.
HTTP
C-type: struct http *
A reference to a header object as req.http or bereq.http.
INT
C-type: long
A (long) integer as we know and love them.
IP
C-type: const struct suckaddr *
This is an opaque type, see the include/vsa.h file for which primitives we support on this type.
PRIV_CALL
See Private Pointers below.
PRIV_TASK
See Private Pointers below.
PRIV_TOP
See Private Pointers below.
PRIV_VCL
See Private Pointers below.
PROBE
C-type: const struct vrt_backend_probe *
A named standalone backend probe definition.
REAL
C-type: double
A floating point value.
REGEX
C-type: const struct vre *
This is an opaque type for regular expressions with a VCL scope. The REGEX type is only meant for regular expression literals managed by the VCL compiler. For dynamic regular expressions or complex usage see the API from the include/vre.h file.
STRING
C-type: const char *
A NUL-terminated text-string.
Can be NULL to indicate a nonexistent string, for instance in:
