VMOD - Varnish Modules·续1

mymod.foo(req.http.foobar);

If there were no “foobar” HTTP header, the vmod_foo() function would be passed a NULL pointer as argument. STEVEDORE C-type: const struct stevedore *
A storage backend. STRANDS C-Type: const struct strands *
Strands are a list of strings that gets passed in a struct with the following members:

  • int n: the number of strings
  • const char **p: the array of strings with n elements
    A VMOD should never hold onto strands beyond a function or method execution. See include/vrt.h for the details.

TIME C-type: double
Unit: seconds since UNIX epoch.
An absolute time, as in 1284401161. VCL_SUB C-type: const struct vcl_sub *
Opaque handle on a VCL subroutine.
References to subroutines can be passed into VMODs as arguments and called later through VRT_call(). The scope strictly is the VCL: vmods must ensure that VCL_SUB references never be called from a different VCL.
VRT_call() fails the VCL for recursive calls and when the VCL_SUB cannot be called from the current context (e.g. calling a subroutine accessing req from the backend side).
For more than one invocation of VRT_call(), VMODs must check if VRT_handled() returns non-zero in-between calls: The called SUB may have returned with an action (any return(x) other than plain return) or may have failed the VCL, and in both cases the calling VMOD must return also, possibly after having conducted some cleanup. Note that undoing the handling through VRT_handling() is a bug.
VRT_check_call() can be used to check if a VRT_call() would succeed in order to avoid the potential VCL failure. It returns NULL if VRT_call() would make the call or an error string why not. VOID C-type: void
Can only be used for return-value, which makes the function a VCL procedure.

C symbols#

Through generation of vcc_if.h, vmodtool.py pre-defines the names of most symbols on the C side of the vmod interface, namely:

  • function names as ___
  • event handler names as ___
  • method names as ____, with two special methods named
    • _init for the constructor and
    • _fini for the destructor
  • class struct names as ____
  • argument struct names for support of optional arguments as _arg_for functions and arg___ for methods, with member names
    • _valid__ for the flag of optional arguments being present and
    • __for the argument name
  • enum values as _enum____

For the above, the __placeholders are defined as:

__ The$Prefix stanza value, if defined in the .vcc file, or vmod by default. __ The vmod name fro the$Module stanza of the .vcc file. __ The function or method argument cname or, if not given, vclname as specified using the : syntax.

The other placeholders should be self-explanatory as the name of the respective function, class, method or handler.

In summary, symbol names can either be influenced by the vmod author globally using $Prefix, or using the : syntax for argument names.

Private Pointers#

It is often useful for library functions to maintain local state, this can be anything from a precompiled regexp to open file descriptors and vast data structures.

The VCL compiler supports the following private pointers:

  • PRIV_CALL “per call” private pointers are useful to cache/store state relative to the specific call or its arguments, for instance a compiled regular expression specific to a regsub() statement or simply caching the most recent output of some expensive operation. These private pointers live for the duration of the loaded VCL.

  • PRIV_TASK “per task” private pointers are useful for state that applies to calls for either a specific request or a backend request. For instance this can be the result of a parsed cookie specific to a client. Note that PRIV_TASK contexts are separate for the client side and the backend side, so use in vcl_backend_* will yield a different private pointer from the one used on the client side. These private pointers live only for the duration of their task.

  • PRIV_TOP “per top-request” private pointers live for the duration of one request and all its ESI-includes. They are only defined for the client side. When used from backend VCL subs, a NULL pointer will potentially be passed and a VCL failure triggered. These private pointers live only for the duration of their top level request

  • PRIV_VCL “per vcl” private pointers are useful for such global state that applies to all calls in this VCL, for instance flags that determine if regular expressions are case-sensitive in this vmod or similar. The PRIV_VCL object is the same object that is passed to the VMOD’s event function. This private pointer lives for the duration of the loaded VCL.

The PRIV_CALL vmod_privs are finalized before PRIV_VCL.

The way it works in the vmod code, is that a struct vmod_priv * is passed to the functions where one of the PRIV_* argument types is specified.

This structure contains three members:

struct vmod_priv {
        void                            *priv;
        long                            len;
        const struct vmod_priv_methods  *methods;
};

The .priv and .len elements can be used for whatever the vmod code wants to use them for.

.methods can be an optional pointer to a struct of callbacks:

typedef void vmod_priv_fini_f(VRT_CTX, void *);

struct vmod_priv_methods {
        unsigned                        magic;
        const char                      *type;
        vmod_priv_fini_f                *fini;
};

.magic has to be initialized to VMOD_PRIV_METHODS_MAGIC. .type should be a descriptive name to help debugging.

.fini will be called for a non-NULL .priv of the struct vmod_priv when the scope ends with that .priv pointer as its second argument besides a VRT_CTX.

The common case where a private data structure is allocated with malloc(3) would look like this:

static void
myfree(VRT_CTX, void *p)
{
        CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);
        free (p);
}

static const struct vmod_priv_methods mymethods[1] = {{
        .magic = VMOD_PRIV_METHODS_MAGIC,
        .type = "mystate",
        .fini = myfree
}};

// ....

if (priv->priv == NULL) {
        priv->priv = calloc(1, sizeof(struct myfoo));
        AN(priv->priv);
        priv->methods = mymethods;
        mystate = priv->priv;
        mystate->foo = 21;
        ...
} else {
        mystate = priv->priv;
}
if (foo > 25) {
        ...
}

Private Pointers Memory Management#

The generic malloc(3) / free(3) approach documented above works for all private pointers. It is the simplest and less error prone (as long as allocated memory is properly freed though the fini callback), but comes at the cost of calling into the heap memory allocator.

Per-vmod constant data structures can be assigned to any private pointer type, but, obviously, free(3) must not be used on them.

Dynamic data stored in PRIV_TASK and PRIV_TOP pointers can also come from the workspace:

  • For PRIV_TASK, any allocation from ctx->ws works, like so:

    if (priv->priv == NULL) {
            priv->priv = WS_Alloc(ctx->ws, sizeof(struct myfoo));
            if (priv->priv == NULL) {
                    VRT_fail(ctx, "WS_Alloc failed");
                    return (...);
            }
            priv->methods = mymethods;
            mystate = priv->priv;
            mystate->foo = 21;
            ...
    
  • For PRIV_TOP, first of all keep in mind that it must only be used from the client context, so vmod code should error out for ctx->req == NULL.

For dynamic data, the top request’s workspace must be used, which complicates things a bit:

    if (priv->priv == NULL) {
            struct ws *ws;

            CHECK_OBJ_NOTNULL(ctx->req, REQ_MAGIC);
            CHECK_OBJ_NOTNULL(ctx->req->top, REQTOP_MAGIC);
            CHECK_OBJ_NOTNULL(ctx->req->top->topreq, REQ_MAGIC);
            ws = ctx->req->top->topreq->ws;

            priv->priv = WS_Alloc(ws, sizeof(struct myfoo));
            // ... same as above for PRIV_TASK

Notice that allocations on the workspace do not need to be freed, their lifetime is the respective task.

Private Pointers and Objects#

PRIV_TASK and PRIV_TOP arguments to methods are not per object instance, but per vmod as for ordinary vmod functions. Thus, vmods requiring per-task / per top-request state for object instances need to implement other means to associate storage with object instances.

This is what VRT_priv_task() / VRT_priv_task_get() and VRT_priv_top() / VRT_priv_top_get() are for:

The non-get functions either return an existing PRIV_TASK / PRIV_TOP for a given void * argument or create one. They return NULL in case of an allocation failure.

The _get() functions do not create a PRIV_*, but return either an existing one or NULL.

By convention, private pointers for object instance are created on the address of the object, as in this example for a PRIV_TASK:

VCL_VOID
myvmod_obj_method(VRT_CTX, struct myvmod_obj *o)
{
    struct vmod_priv *p;

    p = VRT_priv_task(ctx, o);

    // ... see above

The PRIV_TOP case looks identical except for calling VRT_priv_top(ctx, o) in place of VRT_priv_task(ctx, o), but be reminded that the VRT_priv_top*() functions must only be called from client context (if ctx->req != NULL).

Event functions#

VMODs can have an “event” function which is called when a VCL which imports the VMOD is loaded or discarded. This corresponds to the VCL_EVENT_LOAD and VCL_EVENT_DISCARD events, respectively. In addition, this function will be called when the VCL temperature is changed to cold or warm, corresponding to the VCL_EVENT_COLD and VCL_EVENT_WARM events.

The first argument to the event function is a VRT context.

The second argument is the vmod_priv specific to this particular VCL, and if necessary, a VCL specific VMOD “fini” function can be attached to its “free” hook.

The third argument is the event.

If the VMOD has private global state, which includes any sockets or files opened, any memory allocated to global or private variables in the C-code etc, it is the VMODs own responsibility to track how many VCLs were loaded or discarded and free this global state when the count reaches zero.

VMOD writers are strongly encouraged to release all per-VCL resources for a given VCL when it emits a VCL_EVENT_COLD event. You will get a chance to reacquire the resources before the VCL becomes active again and be notified first with a VCL_EVENT_WARM event. Unless a user decides that a given VCL should always be warm, an inactive VMOD will eventually become cold and should manage resources accordingly.

An event function must return zero upon success. It is only possible to fail an initialization with the VCL_EVENT_LOAD or VCL_EVENT_WARM events. Should such a failure happen, a VCL_EVENT_DISCARD or VCL_EVENT_COLD event will be sent to the VMODs that succeeded to put them back in a cold state. The VMOD that failed will not receive this event, and therefore must not be left half-initialized should a failure occur.

If your VMOD is running an asynchronous background job you can hold a reference to the VCL to prevent it from going cold too soon and get the same guarantees as backends with ongoing requests for instance. For that, you must acquire the reference by calling VRT_VCL_Prevent_Discard when you receive a VCL_EVENT_WARM and later calling VRT_VCL_Allow_Discard once the background job is over. Receiving a VCL_EVENT_COLD is your cue to terminate any background job bound to a VCL.