Asterisk cmd ReadFile

Reads the contents of a file into a variable.



varname: The result will be stored here
file: The name of the file to read
length: Maximum number of characters to capture

Example 1

exten => s,1,ReadFile(foo=/ect/asterisk/extensions.conf,20);

Example 2: CPU load (Asterisk 1.4)

Use Set to read single variable into the dialplan, or use a While loop or the ARRAY function to read multiple variables.
Here is an example using ARRAY() - note that in Asterisk 1.6.x we could use the SHELL function together with CUT instead of the clumsy TrySystem() combined with Set() and EVAL:

exten => s,1, TrySystem(uptime \| tr -d "\," \| cut -d ":" -f 5 \| awk \'{print \"ARRAY(load1\,load5\,load15)=\" $1\"\\\\\,\" $2\"\\\\\,\" $3}\' > /tmp/cpu-load.txt)
exten => s,n,TrySystem(cat cpu-load.txt | wc -m > /tmp/cpu-load-length.txt)
exten => s,n,ReadFile(load_length=/tmp/cpu-load-length.txt,2)
exten => s,n,NoOp(load_length=${load_length})
exten => s,n,ReadFile(load_array=/tmp/cpu-load.txt,${MATH(${load_length}-1,int)}) ;remove trailing special character
exten => s,n,NoOp(load_array=${load_array})
exten => s,n,Set(${EVAL(${load_array})})
exten => s,n,NoOp(load1=${load1} load5=${load5} load15=${load15})

This will, after some slightly crazy backslash escaping in extensions.conf of Asterisk 1.4, execute

uptime | tr -d "," | cut -d ":" -f 5 | awk '{print "ARRAY(load1,load5,load15)=" $1"\\," $2"\\," $3}' > /tmp/cpu-load.txt

and as a result write the current CPU load averages for 1 minute, 5 minutes and 15 minutes (as shown by 'top') into a file like this:


Note: The above might fail if your system's uptime is less than 1 hour or less than 2 days. Change '-f 5' into '-f 4' or '-f 3'.
Here is a more reliable way to extract the load values that you can put into a shell script, and then execute with TrySystem():

x=`uptime`; echo ${x#*average:} | tr -d "," | awk '{print "ARRAY(load1,load5,load15)=" $1"\\," $2"\\," $3}' > /tmp/cpu-load.txt

You could now create a macro for the above, call it with the M() option of the Dial command, and store the CPU load, together with the channel's codec and some RTCP statistics, in the userfield of your CDR log (or export them to the intial inbound channel with the help of the Asterisk func SAHRED function).

See also

Created by: renjar, Last modification: Tue 10 of Aug, 2010 (13:38 UTC) by JustRumours
Please update this page with new information, just login and click on the "Edit" or "Discussion" tab. Get a free login here: Register Thanks! - Find us on Google+