concurrencysipkamailio

Are Kamailio pseudo-variables $var safe to use until the end of a single message handler?


I'm using pseudo-variables $var in Kamailio because according to the documentation, they are faster than $dlg_var, but I'm wondering if it's safe to use them like this:

jansson_get("a", $http_rb, "$var(a)");

$var(i) = 0;
jansson_array_size("elements", $http_rb, "$var(elements_size)");

while($var(i) < $var(elements_size)) {
    jansson_get("elements[$var(i)].key", $http_rb, "$var(key)");
    jansson_get("elements[$var(i)].value", $http_rb, "$var(value)");
    insert_hf("$var(key): $var(value)\r\n");
    $var(i) = $var(i) + 1;
}

if ($var(a) == "some value") {
    route(RELAY);
}

I tried setting Kamailio with one process in configuration file, just to see how one Kamailio process processes messages. Then I made two calls at the same time and according to my logs it seems that messages are processed concurrently (I'm not sure if there are multiple threads in one Kamailio process).

So, my question is: Is it possible for concurrent messages to overwrite the value of $var (because it is shared variable for all messages processed by the same Kamailio process) and is there a safe way of using $var to minimize or eliminate that possibility?

I read the documentation and it states:

"Note: A script variable persists over the Kamailio process in which it was initialized, so be sure of giving it a new value before reading it or you'll get the value asigned in any other previous message processed by the same Kamailio process (pid)."

This note makes me think that messages are processed sequentially, or that at least I could safely use the $var while processing a single message. How can I be sure that value I give will not be changed while I'm still using it?


Solution

  • Concurrent processing is not overwriting $var(x) variables, the value of $var(x) is stored in the private memory of the process. Kamailio is not using threads to process SIP traffic, parallel processing of SIP messages can happen only if you have configured Kamailio to start more than one SIP worker process.

    In other words, looking at your example, $var(a) cannot be overwritten while processing that specific SIP message, no matter how many other SIP messages are handled by other SIP worker processes. The $var(a) value will be updated next time the same SIP worker process handles a new message and jansson_get("a", "$http_rb", "$var(a)") is executed again with a different value for $http_rb.

    As a side note, $http_rb is not a valid variable with the standard Kamailio distribution, but I guess you either wrote your own extension or was given for the sake of this example.