Reads the contents of a file into a variable.
Description
ReadFile(varname=file,length)
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 Asterisk func array function to read multiple variables.
Here is an example using ARRAY() – note that in Asterisk 1.6.x we could use the Asterisk func shell function together with Asterisk func cut instead of the clumsy TrySystem() combined with Set() and Asterisk func 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:
ARRAY(load1,load5,load15)=0.50\,0.31\,0.24
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 SHARED function).
See also
- MASTER_CHANNEL of Asterisk 1.8: Retrieve and set variables on the channel which created the current channel
- Asterisk cmd System
- Asterisk func shell – Return the result of a shell scrip to the dialplan
- Asterisk func array – Read name-value pairs into variables in one move
- Asterisk tips fileexistance – Tips on checking if a file exists
- Asterisk func curl – Retrieve the contens of a URL
- Asterisk cmd Backticks – An external application that implemented similar functionality
- Asterisk variables
- Asterisk functions