SetGlobalVariable

From FreeSWITCH Wiki
Jump to: navigation, search

Global variables can be used to share information between all channels. You can save anything in a global variable.

Keep in mind that multiple channels can access/change the information in a variable. You need to take care when saving sensitive data.

For instance, this example may screw things up for you.

  • Global var "isExtensionFree" is true
  • Channel 1 reads the var and checks if it's true.
  • Channel 2 reads the var and checks if it's true.
  • Channel 1 saves value false and transfers the call to destination (since variable was true)
  • Channel 2 does the same thing since it read the var before channel 1 managed to change it.

This is a typical scenario in multi-threaded environments. We have made a quite simple solution for this. There are two different ways to call setGlobalVariable.

  • Two parameters:
    • If setGlobalVariable is called with two parameters, the variable will be set to the second parameter.
    • If the second parameter is a zero length string, the variable will be deleted.
    • The routine will always return true.
  • Three parameters -The third parameter will be used to validate that no changes have been made since the getGlobalVariable (pass the variable that you read).
    • If the third parameter agrees with the current value of the variable, the variable will be changed and the routine will return true.
    • If the third parameter does not agree with the current value of the variable, the variable will not be changed and the routine will return false.
    • If the variable does not exist and the third parameter is not a zero length string, the variable will not be set and the function will return false.
    • If the variable exists, the second parameter is a zero length string, and the third parameter agrees with the current value of the variable, the variable will be deleted, and the function will return true.

Example:

  var value = getGlobalVariable("clients");
  if (value == true)
  {
    if (!setGlobalVariable("clients", false, value))
      console_log("error", "Someone changed the variable between my get/set!");
  }

Synopsis

var bool = setGlobalVariable("variableName", "string/object or number");
var bool = setGlobalVariable("variableName", "string/object or number", "optional value check");


See also