4.2. SANET standard expression functions¶
Indice
- SANET standard expression functions
- Base
- Network Protocols
- VMware utils
- Local utilities
- SNMP
- SNMP Advanced
- Redis DB Utilities
- Database functions
- Services
- Web Scenarios
- Sanet internal Monitoring
- Execution utilities
- Encoding functions
- Debug
4.2.1. Base¶
4.2.1.1. Basic functions¶
4.2.1.1.1. hex¶
Syntax
hex ( byte string )Description
Converts the input parameter bytes into a UPPERCASE hexadecimal string.Input
bytes: a sequence of bytes.Output
Returns a string.Errors
If the input parameter can not be converted to a valid string the expression evaluation fails.Examples
Expression Description Return string value hex(1.3.6.1.2.1.2.2.1.6.2@”mason”) Converts into a string the MAC address of the interface with ifindex 2 01279AF7A4D
4.2.1.1.2. abs¶
Syntax
abs ( arg )Description
Returns the absolute value of the given argument.Input
args: numberOutput
Returns a numberErrors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value abs(1) 1 abs(-1) 1
4.2.1.1.3. min¶
Syntax
min ( arg )Description
Returns the minimum value.Input
args: sequence of numeric values.Output
Returns a numberErrors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value min(1,2,3) 1 min(-1,0) -1
4.2.1.1.4. max¶
Syntax
max ( arg )Description
Returns the maximum value.Input
args: sequence of numeric values.Output
Returns a numberErrors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value max(1,2,3) 3 max(-1,0) 0
4.2.1.1.5. sum¶
Syntax
sum ( arg )Description
Sums all the input arguments.Input
args: sequence of numeric values.Output
Returns a numberErrors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value sum(1,2,3) 6
4.2.1.1.6. ceil¶
Syntax
ceil ( v )Description
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.Input
v: a float value.Output
Returns a float value.Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value ceil(0.1) 1.0 ceil(1.9) 2.0 ceil(-1.1) -1.0
4.2.1.1.7. floor¶
Syntax
floor ( v )Description
Return the floor of x as a float, the largest integer value less than or equal to x.Input
v: a float value.Output
Returns a float value.Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.Examples
Expression Value floor(0.1) 0.0 floor(1.9) 1.0 floor(-1.1) -2.0
4.2.1.1.8. str¶
Syntax
str ( arg )Description
Tries to converts the input value arg to a string.Input
args: any valueOutput
Returns a stringErrors
If the input parameter can not be converted to a valid string the expression evaluation fails.Examples
Expression Value str(0xFF) 255 str(1.0) 1.0 str(“foo”) foo
4.2.1.1.9. float¶
Syntax
float ( arg )Description
Tries to converts the input value arg to an floating point value.Input
args: any valueOutput
Returns a floating point value.Errors
If the input parameter can not be converted to a valid floating point value the expression evaluation fails.Examples
Expression Value int(0xff) 255.0 int(1.33) 1.33 int(“12345”) 12345.0 int(“foo”) ERROR
4.2.1.1.10. int¶
Syntax
int ( arg )Description
Tries to converts the input value arg to an integer value.Input
args: any valueOutput
Returns a stringErrors
If the input parameter can not be converted to a valid integer value the expression evaluation fails.Examples
Expression Value int(0xFF) 255 int(1.33) 1 int(“12345”) 12345 int(“foo”) ERROR
4.2.1.1.11. dict¶
Syntax
dict ( key1 , value1 [ , key2 , value2 … ] )Description
Takes a sequence of parameters and created a dictionary object in memory. .Input
args: a sequence of paired key / value options.Output
Returns a dictionaryErrors
Raise an exceptions if the number of paramets is not even.Examples
Expression Value dict(“key1”, 666) { “key1: 666 } dict(“key1”, 666, “foo”, “bar”) { “foo”: “bar”, “key1”:666 }
4.2.1.1.12. re_escape¶
Syntax
re_escape ( str )Description
Returns a string with all non-alphanumerics backslashed.
This is useful if you want to compose a regular expression from a string that contains regular expression meta-characters (., *, … ).
Input
str : stringOutput
Returns a string.Examples
Expression Value Description re_escape(“hello”) hello Nothing to escape re_escape(“192.168.0.1”) 192.168.0.1 dots escaped “192.168.0.1.port1.255.255.255.0” =~ re_escape(“192.168.0.1.”) + “.*” + re_escape(“.255.255.255.0”) true Try to match the pattern: ip address . any character . ip address “192.168.0.1.abcdefg.255.255.255.0” =~ re_escape(“192.168.0.1.”) + “d” + re_escape(“.255.255.255.0”) false Try to match the pattern: ip address . integer value . ip address
4.2.1.1.13. greplines¶
Syntax
greplines ( multiline text , substring ] )Description
Searches for the given substring inside multiline text and returns the first line where substring was found.
If substring is not found, the function raises an exception and the expression goes UNCHECKABLE.
Input
- multine text a (multiline) string
- substring string
Output
A stringExamples
Expression Description Return string value greplines(‘hello \n sunny word’, ‘word’)
4.2.1.1.14. valueinrange¶
Syntax
valueinrage ( value , minvalue , maxvalue )Description
Returns true if value is between minvalue and maxvalue (included).
Raises an exception otherwise.
Input
- value Number
- minvalue Number
- maxvalue Number
Output
- boolean True
Examples
Expression Description Return value valueinragen(2,1,3)
4.2.1.1.15. isDefined()¶
Syntax
isDefined ( varname )Description
Returns true if a symbol is defined while evaluating the current expression.Special symbols
Some special symbols are calculated “on-the-fly”. The computation could raise an execution error for different reason (network timetout, internal errors, ecc.) .
The isDefined() catches all exception and always return False.
Some special exception are not handled by the function and lead to an uncheckable result. These are the special cases:
- Exceptions raised by well-known bugs of the SNMP library
Input
- varname : symbol name.
Output
- boolean True if the symbold is defined. False otherwise.
Examples
Expression Description Return value isDefined(“ifindex”) Tells if $ifindex can be calculated and used inside the espression. true
4.2.1.1.16. ifDefined()¶
Syntax
isDefined ( varname , default_value )Description
Check if the symbol varname is defined in the current execution context and returns its value.
If the symbol is not defined, the default_value is returned.
Input
- varname : (string) symbol name.
- default_value: (any type) any value.
Output
- Return a valid expression value.
Examples
Expression Description Return value ifDefined(“$ifindex”, -1) Returns the value of the simbol $ifindex 12 ifDefined(“$ifindex”, -1) Returns the value of the simbol $ifindex -1 ($ifindex is not defined
4.2.1.1.17. re_search¶
Syntax
re_search ( string , regexp )Description
Tries to search in string the matching sub-string specified by regexp. If regexp uses named groups, the function returns a dictionary with the matching groups. If regexp uses groups, the function returns a vectory with the matched groups. If regexp do not use groups, the matching string is returned.Input
- string : a string of characters
- regexp : a regular expression string
Output
- A dictionary or a vector of values.
Examples
Expression Description Return value re_search( “hello world”, “hello” ) hello re_search( “hello world”, “(lo)” ) [ ‘lo’ ] re_search( “hello world”, r”(w+) (w+)” ) [ ‘hello’, ‘world’ ] re_search( “hello world”, r”(w+) (w+)” )[0] ‘hello’ re_search( “John Doe”, r”(?P<name>w+) (?P<surname>w+)” ) {‘surname’: ‘Doe’, ‘name’: ‘John’} re_search( “John Doe”, r”(?P<name>w+) (?P<surname>w+)” )[‘surname’] ‘Doe’
4.2.1.1.18. hexstr2bin¶
Syntax
hexstr2bin ( string )Description
Converts the string of hexadecimal characters in the corresponding binary rappresentation.Input
string: a string of hexadecimal ascii characters.Output
Returns a binary buffer.Errors
Raise an exception when a conversion error is detected.Examples
Expression Value Description hexstr2bin(‘68656c6c6f’) hello ascii string for hello
4.2.1.1.19. ziparray¶
Syntax
ziparray ( array1 , array2 [ , … ] )*Description
Returns a list of tuples, where the i-th tuple contains the i-th element from each of the arrays.Input
Arrays of elements.Output
Returns an array.Errors
Raise an exception when a conversion error is detected.Examples
Expression Value Description ziparray( array(1,2,3), array(“a”,”b”,”c”) ) [ (1,’a’), (2,’b’), (3,’c’) ] ascii string for hello
4.2.1.2. Time functions¶
4.2.1.2.1. time¶
Syntax
time ( )Description
Return the time as a floating point number expressed in seconds since the epoch (1970-01-01 00:00:00), in UTC.Output
Returns a floating point value.Examples
Expression Return string value time() 1291971078.92
4.2.1.2.2. UTCTZOffset¶
Syntax
UTCOffset ( [ timezone_name ] )Description
Returns the offset in seconds of the given timezone_name.
Warning
the returned value counts the Daylight Saving Time (DST) if it’s in effect at the moment of the call.
If timezone_name is not specified, the local timezone is used.
Output
Offset in secondsErrors
Raise an exception if the input timezone is not valid.Examples
Expression Value Description UTCOffset() 3600 Offset of local timezone (Europe/Rome) when Daylight Saving Time (DST) is not active. (+01:00) UTCOffset() 7600 Offset of local timezone (Europe/Rome) when Daylight Saving Time (DST) is not active. (+02:00) UTCOffset(‘America/Chicago’) -18000 Offset of local timezone (Europe/Rome) when Daylight Saving Time (DST) is not active. (+02:00)
4.2.1.2.3. create_dateandtime¶
Syntax
create_dateandtime ( year , month , day , hour , minutes , seconds , deci_seconds [ , utc_dir , utc_hours , utc_minutes ] )Description
Create a dateandtime byte vector with the given time informations.
When called without parameters, the function returns a dateandtime vector for the current local time (with timezone informations included, if available)
If utc_dir is ‘+’ or ‘-‘, the byte vector will contain timezone informations (11 bytes length). Default value for utc_hours and utc_minutes is 0 (00:00).
if utc_dir is not specified the byte vector will code local time and without timezone informations (8 bytes length).
The DateAndTime specification:
> --------------------------------------------------------------------------- > DateAndTime ::= TEXTUAL-CONVENTION > DISPLAY-HINT "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" > STATUS current > DESCRIPTION > "A date-time specification. > > field octets contents range > ----- ------ -------- ----- > 1 1-2 year* 0..65536 > 2 3 month 1..12 > 3 4 day 1..31 > 4 5 hour 0..23 > 5 6 minutes 0..59 > 6 7 seconds 0..60 > (use 60 for leap-second) > 7 8 deci-seconds 0..9 > 8 9 direction from UTC '+' / '-' > 9 10 hours from UTC* 0..13 > 10 11 minutes from UTC 0..59 > > * Notes: > - the value of year is in network-byte order > - daylight saving time in New Zealand is +13 > > For example, Tuesday May 26, 1992 at 1:30:15 PM EDT would be > displayed as: > > 1992-5-26,13:30:15.0,-4:0 > > > Note that if only local time is known, then timezone > information (fields 8-10) is not present." > SYNTAX OCTET STRING (SIZE (8 | 11)) > ---------------------------------------------------------------------------Output
A byte vector (8 byte or 11 byte length)Examples
Expression Value Description create_dateandtime() x07 xe0 x04 x1d x0a x02 x02 x00 + x02 x00 2016/4/29 10:02 +02:00 create_dateandtime(1970,1,1,1,1) x07 xb2 x01 x01 x01 x01 x00 x00 1970/1/1 01:01 (no timezone info)
4.2.1.2.4. dateandtime2tuple¶
Syntax
dateandtime2tuple ( [ dateandtime value ] )Description
Convert the given dateandtime value byte vector to the corrisponding time tuple.
This is the “inverse” of create_dateandtime().
Output
A tuple of values.Errors
Raise an exception if the input values is not valid dateandtime byte vector.Examples
Expression Value Description dateandtime2tuple(create_dateandtime(1970,1,1,1,0,0,utc_dir=”+”, utc_hours=1)) (1970, 1, 1, 1, 0, 0, 0, ‘+’, 1, 0) dateandtime2tuple(create_dateandtime()) (2016, 4, 28, 18, 30, 13, 0, ‘+’, 2, 0)
4.2.1.2.5. dateandtime2timestamp¶
Syntax
dateandtime2timestamp ( dateandtime value [ , default_tz ] )Description
Convert the given dateandtime value byte vector to the corrisponding timestamp UTC.
If the dateandtime value is a local time tuple (8 byte, without timezone informations), the default_tz parameter is used for the computation, otherwise the local timezone is used.
THe default_tz string parameter can specify the timezone with two different formats:
- Timezone code (es. “Europe/Rome”)
- An offset in the format (“+”|”-“)(<HH>:<MM>). (Es: “+01:00”)
When default_tz contains an empty string (“”), the local timezone is used.
When dateandtime value do not contains timezone infos, the function tries to adjust the timestamp with Daylight Saving TIme (DTS) settings for the used timezone (default_tz or local timezone) active when the function is called.
NOTE: When default_tz uses the offset format (2) the function do not handle DST.
Input
- dateandtime value : a DateAndTime value (8 o 11 byte length vector)
- default_tz: (optional) a string
Output
A UTC timestamp.Errors
Raise an exception if the input values is not valid dateandtime byte vector or the timezone is notExamples
Expression Value Description dateandtime2timestamp( 1.3.6.1.2.1.25.1.2@ ) 1461915587 Fri Apr 29 07:39:47 UTC 2016 (UTC) / Fri Apr 29 09:39:47 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime() ) 1461915587 Fri Apr 29 07:39:47 UTC 2016 (UTC) / Fri Apr 29 09:39:47 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime(2016,4,29, 09,30) ) 1461915000 Fri Apr 29 07:30:00 UTC 2016 (UTC) / Fri Apr 29 09:30:00 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime(2016,4,29, 09,30), “+02:00” ) 1461915000 Fri Apr 29 07:30:00 UTC 2016 (UTC) / Fri Apr 29 09:30:00 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime(2016,4,29, 09,30), “Europe/Rome” ) 1461915000 Fri Apr 29 07:30:00 UTC 2016 (UTC) / Fri Apr 29 09:30:00 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime(2016,4,29, 09,30, utc_dir=”+”) ) 1461922200 Fri Apr 29 09:30:00 UTC 2016 (UTC) / Fri Apr 29 11:30:00 CEST 2016 (localtime) dateandtime2timestamp( create_dateandtime(2016,4,29, 09,30, utc_dir=”+”), “America/Chicago” ) 1461922200 Fri Apr 29 09:30:00 UTC 2016 (UTC) / Fri Apr 29 11:30:00 CEST 2016 (localtime) int(dateandtime2timestamp( create_dateandtime() )) - int(time()) 0 ok, same current time for time() and create_dateandtime()
4.2.1.3. String functions¶
4.2.1.3.1. strlen¶
Syntax
strlen ( data )Description
Return the lenght of the given string data.Input
- data: a string
Output
Returns an integer value.Errors
Examples
Expression Return value Description strlen(“foo”) 3
4.2.1.3.2. strrep¶
Syntax
strrep ( str_orig, str_pattern , str_rep )Description
Replaces the string str_pattern with str_rep inside str_orig, and returns the result string.Input
- str_orig : string
- str_pattern: string
- str_rep : string
Output
Returns an string.Errors
Examples
Expression Return value Description strrep(“123”, “2”, “B”) 1B3
4.2.1.3.3. strpos¶
Syntax
strpos ( str1 , str2 ** ] )**Description
Returns the position of str2 inside str1. The first valid position is 0.Input
- str1: string
- str2: string
Output
Returns an integer value. Returns -1 when str2 is not found.Errors
Examples
Expression Return value Description strpos(“hello world”, “orl”) 7 strpos(“foo foo foo”, “bar”) -1
4.2.1.3.4. strsub¶
Syntax
strsub ( str1 [ , startpos ] [ , length )Description
TODOInput
- str: string
- startpos: interger
- length: interger
Output
Returns an integer value.Errors
Examples
4.2.1.3.5. strsplit¶
Syntax
strsplit ( str1 [, splitchar ] [, count ])**Description
Splits str1 in tokens. The split char used is spitchar (default is whitespace ” “). The max number of splits is given by count.Input
- str1: string
- splitchar: a character
- count: integer
Output
Returns a vector of strings.Errors
Examples
Expression Return value Description strsplit(“a b c”) [“a”, “b”, “c”] strsplit(“a b c”, count=1) [“a”, “bc”]
4.2.1.3.6. strstrip¶
Syntax
strstrip ( data )Description
Remove whitespaces (newline, whitespace, tabs, ecc…) from the head and the tail of the given string.Input
- data: string
Output
Returns an stringErrors
Examples
Expression Return value Description strstrip(” hello “) hello
4.2.1.3.7. strjoin¶
Syntax
strjoin ( data [, join_char ] )Description
Returns a string in which the element of data have been joined by separator join_char. If join_char is not specified, the white space characeter is used as separator.Input
- data: vectory of values (string values)
Output
Returns an stringErrors
An error is raised if data is not suitable to join.Examples
Expression Return value Description strjoin( array(1,2,3) ) “1 2 3” strjoin( array(1,2,3) , “#”) “1#2#3”
4.2.1.3.8. head¶
Syntax
head ( data , num )Description
Return a vector containing the first num strings of the given multi-line data string.Input
- data: multi-line string
- num: integer
Output
Returns an vector of strings.Errors
Examples
Expression Return value Description head(“line1nline2nline3nline4, 2) [“line1”, “line2”] head(“line1nline2nline3nline4, 2)[1] “line1”
4.2.1.3.9. tail¶
Syntax
tail ( data , num )Description
Return a vector containing the last num strings of the given multi-line data string.Input
- data: multi-line string
- num: integer
Output
Returns an vector of strings.Errors
Examples
Expression Return value Description tail(“line1nline2nline3nline4, 2) [“line3”, “line4”] tail(“line1nline2nline3nline4, 1) [“line4”] tail(“line1nline2nline3nline4, 1)[0] “line4”
4.2.2. Network Protocols¶
4.2.2.1. ICMP Functions¶
4.2.2.1.1. Ping & RTT¶
4.2.2.1.1.1. getICMPStat¶
Syntax
getICMPStat ( info_type , host [, probesize] [, shorttries] [, timeout ] [, do_frag] [, bind_address] [, ipversion ])Description
Performs a reachability test using the ICMP protocol and calculates the RTT Min, RTT Max, RTT Average and Packet Loss percentage.
Returns the value type specified by info_type string parameter
Attention
Parameters ipversion and probesize should be configured properly.
Input
- info_type : (string) rttavg, rttmin, rttmax, loss.
- host : (string) The hostname or IP address.
- probesize : (number) The ICMP packet size. Default: 1472.
- shorttries : (number) Number of ICMP echo pachets. Default: 5.
- timeout : (number) Timeout for every echo packet. Default: 3.
- do_frag : (boolean) Set to true (es. 1) to enable IP fragmentation, false (es: 0) to disable fragmentantion. Default is: true.
- bind_address : (string) IP source address. Default: not set.
- ipversion : (number) IP version: 4 for IPv4, 6 for IPv6. Default: 4.
Warning
probesize default values is always 1472, even if ipversion is 6.
Output
Returns an floating point valueErrors
An exception is raised when an error occurs.Examples
Expression Description Return string value getICMPStat (‘rttmin’, “mason”) getICMPStat (‘rttmin’, $node, 1472)
4.2.2.1.1.2. getRttInfo¶
Alias for getICMPStat.
4.2.2.2. isReachable¶
Syntax
isReachable ( host [ , probesize [ , shorttries [ , keep_rtt_measure [ , timeout [ , do_frag [ , bind_address]]]]]] )Description
Tests if a remote host identified by host responds to ICMP ECHO requests.
The parameter host can be a string containing a valid IPv4 address or a hostname string. If an hostname is given, it is resolved and the reachability test is performed for every resolved IP until the remote host responds or the test fails.
If the parameters probesize, shorttires and timeout are not specified then the function looks for the corresponding variables $probesize, $shorttries and $timeout inside the current execution context. If they are missing, the test raises an exceptions and the expression evaluation fails.
If the keep_rtt_measure parameter’s value is true, the max, min and average RTT values calculated during the test are stored inside a RRD file with name: host.rrd. If the file does not exists, it will be created on the fly. (TODO: link to the file format)
If the do_frag parameter is false, the IP packets are sent with the DF flag set and they are not fragmented. Default value is True.
if bind_address is specified, outgoing IP packets will use bind_address as the source address.
Input
- hostname : string.
- probesize : integer number.
- shorttries : interger number
- keep_rtt_measure: boolean value. DEPRECATED: not used. for compatibility only
- timeout : integer number. (default: 3)
- do_frag : boolean value. (default: true)
- bind_address : string
Output
Returns a true or false.Errors
If the parameter host is not valid or can not be translated into a valid IP(s) the function returns false.
If the value for
Examples
Expression Description isReachable(“mason”) Pings host “mason”. isReachable($hostname) isReachable(“mason”, 1472) isReachable(“mason”, $packetlen) isReachable(“mason”, 1472, 3) isReachable(“mason”, 1472, $tries) isReachable(“mason”, 1472, 3, 1) isReachable(“mason”, 1472, 3, False) Disabled keep_rtt_measure. isReachable(“mason”, 1472, 3, False, 3) Disabled keep_rtt_measure, 3 seconds of timeout for every ICMP packet. isReachable(“mason”, 1472, 3, False, $timeout) isReachable(“mason”, 1472, 3, False, $timeout, False) Sends 3 ICMP packets. The ICMP packets’ payload is 1472 bytes and the IP packet is not fragmented. isReachable(“mason”, 1472, bind_address=”127.0.0.1”) Tries to ping host ‘mason’ with source address 127.0.0.1. It will fail. isReachable(“localhost”, 1472, bind_address=”127.0.0.1”) Tries to ping localhost with source address 127.0.0.1. Valid address.
4.2.2.3. isReachable6¶
Syntax
isReachable6 ( host [ , probesize [ , shorttries [ , keep_rtt_measure [ , timeout [ , bind_address ]]]]]]]] )Description
This function perform the same reachability test of the isReachable() function, but uses ICMPv6 instead of ICMPv4.
See the documentation of isReachable() for more details.
4.2.2.4. icmpPmtu¶
Syntax
icmpPmtu ( host [ , probesize [ , shorttries [ , timeout]]] )Description
Checks if the PMTU to a remote host is enough for an IPv4 ICMP ECHO requests with paylod probesize.
The host is pinged with DF bit set, and if it answers the value is true. If it doesn’t answer (after shorttries attempts with timeout), host is pinged with DF bit clear, and if it answers the values is false. If it doesn’t answer even with DF clear, the value is true. In other words:
- If the host answers to pings with the specified payload, but the PMTU doesn’t allow them through, the value is false
- If the host is alive but doesn’t anser to pings with the specified paylod, whatever DF bit we use, the value is true (i.e., it is not a PMTU problem)
- If the host is dead, the value is true (again, it is not a PMTU problem)
If the host has multiple IPv4 addresses, each of them is tried with DF bit set, and at the first answer the value is true. Then each of them is tried with DF clear, and at the first answer the value is false. If there is no answer at all, the value is true.
4.2.2.5. packetLoss¶
Syntax
packetLoss ( host [ , probesize [ , shorttries [ , keep_rtt_measure [ , timeout [ , do_frag]]]]] )Description
Calculates the percentage of packet loss for the given host.
The functions accepts the same parameters (with the same semantics) used for isReachable().
Input
hostname : string probesize: integer number shorttries: interger number keep_rtt_measure: boolean value timeout: integer number do_frag: boolean valueOutput
Returns packet loss percentage between 0 and 1.Errors
If the parameter host is not valid or can not be translated into a valid IP(s) the function returns false.
If the value for
Examples
Expression Description packetLoss(“mason”) 0.33~ isReachable(“www.google.com”, 1472) 0.0
4.2.2.6. TCP¶
4.2.2.6.1. isTcpOpen¶
Syntax
isTcpOpen ( host , port )Description
Verifies if a TCP connection can be established with the remote peer host:port.
The parameter host can be a valid IPv4 addresso or a hostname. If a hostname is given, it is resolved and the test tries the first IP returned.
The functions returns false the address resolution fails of if the TCP connection can not be established before a 10 seconds timeout.
Input
- host: hostname or IP address.
- port: port number
Output
Returns a booleanErrors
Examples
Expression Return value Description isTcpOpen(“www.google.com”, 80) true isTcpOpen(“thisisnotavalidhostname”, 80) false
4.2.2.6.2. tcpReceive¶
Syntax
tcpReceive ( node , tcp_port [ , timeout] [, num_lines ] )Description
Connects to node and download the first num_lines of text data from the listening application.Input
- node: hostname
- tcp_port: integer
- timeout: integer
Output
Returns a string.Errors
Examples
Expression Return value Description tcpReceive(“www.google.com”, 80) “<html>….”
4.2.2.7. UDP¶
4.2.2.7.1. isUdpOpen¶
Syntax
isUdpOpen ( host , port [ , options ] )Description
Verifies if a UDP port is open on the remote host.Input
- host: hostname or IP address.
- port: port number
- timeout : Optional. set the maximum response timeout. (Default: 3 seconds)
- open_on_timeout : Optional, forces to return True on timeout. (Default: True)
Output
Returns a booleanErrors
The function returns an uncheckable value when any unmanaged network error occurs.Examples
Expression Return value Description isUdpOpen(“mydns”, 53, timeout=10) True Received 12 bytes.,udpOpen($node, 53, timeout=3) expands to True isUdpOpen(“mydns”, 666,) False Connection refused. UDP port 666 closed,udpOpen($node, 666, timeout=3) expands to False isUdpOpen(“ns2.google.com”, 666, open_on_timeout=True) True Connection timeout. Port 666 filtered?,udpOpen(“ns2.google.com”, 666, timeout=3, open_on_timeout=True) expands to True
4.2.2.8. NTP¶
4.2.2.8.1. isNtpOk¶
Syntax
isNtpOk ( hostname )Description
Checks if the host hostname is a valid NTP server. The functions performs a NTP request and checks the NTP response. It verifies if: * The server’s clock is syncronized * THe server is among the secondary NTP servers (server stratum between 1 and 15).Input
hostname: the string containing the hostname of the remote server.Output
Returns a true or false.Errors
If the hostname does not respond before a 3 seconds timeout, the function returns false.Examples
Expression Return value isNtpOk(“mason”) true isNtpOk(“google.com”) false
4.2.2.8.2. NTPTimeStamp¶
Syntax
NTPTimeStamp ( buffer )Description
Converts buffer (a 64-bit NTP timestamps [RFC-1305]) to Unix Timestamp UTC (seconds since 1970-01-01).Input
buffer: the 64-bit string containing a NTP timestampsOutput
Returns a floating point value.Errors
Raise an exception if the input buffer can not be converted to valid timestamp.Examples
Expression Return value Description NTPTimeStamp( hexstr2bin(“0000000000000000” ) ) -2208988800 NTP uses an epoch of 1900-01-01 00:00:00. NTPTimeStamp( hexstr2bin(“0000000000000000” ) ) + 2208988800 0 Thu Jan 1 00:00:00 CET 1970 (NTP epoch + seconds to 1970 (2208988800) NTPTimeStamp( hexstr2bin(“C232B916FAE071DB” ) ) 1049115286.98 Mon Mar 31 14:54:46 CEST 2003
4.2.2.9. HTTP¶
4.2.2.9.1. urlContentDoesntMatch¶
Syntax
urlContentDoesntMatch ( url , regexpr [ , case_insensitive_flag [, optional params ] ] )Description
Verifies if content of the given url does not match the regular expression regexpr_str.
See the function urlContentMatches() for more details.
4.2.2.9.2. urlContentMatches¶
Syntax
urlContentMatches ( url , regexpr [ , case_insensitive_flag [, optional params ] ] )Description
Verifies if content of the given url matches the regular expression regexpr_str.
The parameter case_insensitive_flag is used to switch to case insensitive mode.
The parameter regexpr_str can be enclosed between “/” characters (eg. “/foo/”). In this case the case insensitive test can be enabled by appending a “i” at the end of the expression. (eg: “/foo/i”). The “i” character modifier has precedence on the case_insensitive parameter.
The timeout parameter is an optional parameter and is used to set the maximum connection timeout in seconds (default: 20 seconds).
Optional parameters
This is the list of optional parameters:
Variable Description include_data Include http data in the verbose status (valid only for conditions) http_headers String containing HTTP Headers (use “n” for multi headers) use_tls1 true/false to force TLSv1 instead of SSL2/3 postdata String containing data for POST request ciphers OpensSSL Ciphers String no_fix_ssl3 (default False) Disable all special Sanet3 fixes for SSL3 and TLS. ignore_errors Specify how to handle errors. See Ignore errors. Important
You should not change no_fix_ssl3 defeault if you python version is < 2.7.9.
Use HTTP Basic/NTML Authentication
In order to use a HTTP basic/NTML authentication, the following optional parameters must be defined:
Variable Description basic_user username basic_password password basic_ntlm true/false. Switch to NTML authentication. (Default False) basic_challenge true/false. Send authentication info challenge (Default: True) This parameters can be passed to the function as context variables too ( $basic_user, $basic_password ).
Use a proxy
In order to use a HTTP proxy, the following optional parameters must be defined:
Variable Description proxy_protocol “http” (default) or “https” proxy_server Proxy’s hostname proxy_port Proxy’s port If you need proxy authentication you must define the following parameters:
Variable Description proxy_realm Proxy’s realm (Can be *) proxy_user Username proxy_password Password proxy_ntlm NTLM support flag. Set to 1 to enable NTLM authentication This parameters can be passed to the function as context variables too ( $basic_user, $basic_password ).
Use local Proxy and HTTP Basic Authentication on remote server
You can use Proxy support and basic authentication at the same time. Remember that proxy authentication is performed first.Use local Proxy with NTLM Authentication
IMPORTANT: this feature is enabled only if NTLM python modules are installed.
If proxy_ntlm is set to 1, NTLM Proxy Authentication is used instead of HTTP Proxy Authentication.
Parameter proxy_realm is used used as the DOMAIN name. The real user used for the authentication is:
<domain>\<user>Es:
proxy_user = "foo" proxy_realm = "DOMAIN"POST requests
The HTTP request will be a POST instead of a GET when the postdata parameter is provided.
The value can be:
a string encoded in the standard application/x-www-form-urlencoded.
postdata="var1=value1&var2=value2%20123"Will send this data:
var1: value1 var2: value2 123a dictionary objects <key, value> created with the function dict.
postdata=dict("var1","value1", "var2","value2", "var3","value3")Will send this data:
var1: value1 var2: value2 var3: value3Ignore errors
All errors are ignored by default.
The parameter ignore_errors can change this behaviour. It is a comma-separated sequence of tokens:
token ::= "NONE" | "ALL" | ["+","-"] <type> type ::= "TIMEOUT" | "HTTP" | "SSL" | "OTHERS"The type string can be:
- TIMEOUT: network connection’s timeout.
- HTTP: HTTP/S protocol errors.
- OTHERS: Any other error not handled by other types.
Warning
HTTP errors may include proxy errors.
The “+” or “-” flag is optional.
- “+”: the specified error type is ignored. THIS IS THE DEFAULT.
- “-“: the specified error type is NOT ignored and will raise an exception.
You can specify an arbitrary sequence of tokens. It will be evaluted from left to right.
Sequence Behaviour --------- ---------- NONE,ALL ALL wins. Ignore all errors NONE,+TIMEOUT DO NOT IGNORE all kind of errors, BUT IGNORE TIMEOUT. ALL,-SSL ignore all errors, BUT raise SSL errors ALL,-SSL,-HTTP ignore all errors, BUT raise SSL and HTTP errors ALL,-SSL,NONE NONE wins. DO NOT IGNORE ANY ERROR ALL,+SSL Equivalent to ALL NONE,-SSL Equivalent to NONEOutput
Returns a booleanErrors
An exception is raised when error is detected.Examples
Expression Return Value Description urlContentMatches(“http://www.google.com”, “google”) true urlContentMatches(“http://www.google.com”, “GOOGLE”) false urlContentMatches(“http://www.google.com”, “GOOGLE”, “i”) true urlContentMatches(“http://www.google.com”, “/GOOGLE/i”) true urlContentMatches(“http://www.google.com”, “/GOOGLE/i”, basic_user=”foo”, basic_password=”12345abc”) true (with HTTP Basic Authentication) urlContentMatches(“http://www.google.com”, “/GOOGLE/i”, include_data=True) true (with data in the verbstatus) urlContentMatches(“http://www.google.com”, “/GOOGLE/i”, http_headers=”User-Agent: dummy”) true (with “dummy” as user agent urlContentMatches(“http://www.google.com”, “/GOOGLE/i”, postdata=”ciccio”) ERROR (postdata is not a x-www-form-urlencoded urlContentMatches(“http://www.google.com/login”, “/Exit/i”, postdata=dict(“username”, “user”, “password”, “12345”)) true urlContentMatches(“http://www.google.com”, “GOOGLE”, ciphers=”DEFAULT:!DH”) true (Disabled Diffie-Helfman cipher) urlContentMatches(“https://www.google.com/login”, “/Exit/i”, ciphers=”LOW”) ERROR (ssl error)
Expression Return Value Description urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”+TIMEOUT”) True without any error urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”+TIMEOUT”) False with a timeout urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”-TIMEOUT”) exception with a timeout urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”+TIMEOUT”) False with a SSL error (because “+” is the defautl behaviour) urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”+TIMEOUT,+SSL”) False with a SSL error (because “+” is the defautl behaviour) urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”+TIMEOUT,-SSL”) exception with a SSL error urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”NONE,+TIMEOUT”) True without any error urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”NONE,+TIMEOUT”) False with a timeout urlContentMatches(“https://www.google.com/login”, “/google/i”, ignore_errors=”NONE,+TIMEOUT”) exception with any error but timeout Troubleshoot
If you get the following execution error:
error: <urlopen error [Errno 8] _ssl.c:504: EOF occurred in violation of protocolYou need to specify TLS protocol:
urlContentMatches("http://www.google.com", "google", use_tls1=1)
4.2.2.9.3. httpRequest¶
Syntax
httpRequest ( url [, optional params ] )Description
Sends an HTTP request (GET or POST) and returns the HTTP response body.
By default, the function performs GET request. If optional parameter postdata is specified, the function will perform a POST request.
See the function urlContentMatches for more details aboud options params.
Output
Returns a string containing the response body.dErrors
An exception is raised when error is detected. If an error occurrs and it is ignored, the function will return an emtpy string (‘’).Examples
Expression Return Value Description httpRequest(“http://www.google.com”) true Performs a GET. httpRequest(“http://www.google.com”, postdata=”ciccio”) ERROR Performs a POST (postdata is not a x-www-form-urlencoded). httpRequest(“http://www.google.com/login”, postdata=dict(“username”, “user”, “password”, “12345”)) true Performs a POST (postdata is converted to a x-www-form-urlencoded string)
4.2.2.10. Cluster management¶
4.2.2.10.1. isAssociated¶
Syntax
isAssociated ( )Description
Returns true if the current node (Access point) is associated to the cluster which it belongs to.Input
NONEOutput
True or FalseErrors
An exception is raised if the cluster association can not be calculated.Examples
Expression Description Return string value isAssociated() true
4.2.2.10.2. clusterNode¶
Syntax
clusterNode ( )Description
Returns the name of the master node the current node is associated to.Input
NoneOutput
A string with the give node.Errors
An exception is raised if the cluster association can not be calculated.Examples
Expression Description Return string value clusterNode() wlc1
4.2.2.10.3. clusterCommunity¶
Syntax
clusterCommunity ( )Description
Returns the SNMP community configured for the master node the current node is associated to.Input
NoneOutput
A string with the give community.Errors
An exception is raised if the cluster association can not be calculated.Examples
Expression Description Return string value clusterCommunity() public123
4.2.2.10.4. clusterSnmpPort¶
Syntax
clusterSnmpPort ( )Description
Returns the SNMP port configured for the master node the current node is associated to.Input
NoneOutput
A number with the give SNMP port.Errors
An exception is raised if the cluster association can not be calculated.Examples
Expression Description Return string value clusterSnmpPort() 161
4.2.2.10.5. clusterInstance¶
Syntax
clusterInstance ( )Description
Returns the SNMP instance for the current node (AP) inside the MIB of the controller (master node).Input
NoneOutput
A string with the give instance.Errors
An exception is raised if the cluster association can not be calculated.Examples
Expression Description Return string value clusterInstance() 144.23.51.8
4.2.2.11. Network utils¶
4.2.2.11.1. resolve¶
Syntax
resolve ( host [ , ipversion ] [, stable_order ] )Description
Resolves the address for the give host. The DNS record A or AAAA depends of the ipversion.
If there are multiple addresses of host, the first address is returned. If the parameter stable_order is true (default false), all the resolved IPs are sorted by network order and the first address (smallest) is always returned).
Input
- host : an IP address
- ipversion: IP version: 4 (default) or 6.
- stable_order: (optional) true or false. Default false.
Output
A stringErrors
An exception is raised if an error occurs.Examples
Expression Return value Description resolve(“www.google.com”) 173.194.113.230
4.2.2.11.2. resolveall¶
Syntax
resolveall ( host [ , ipversion ] [, stable_order ] )Description
Resolves all the address for the give host. The DNS record A or AAAA depends of the ipversion.
The function returns an array with all resolved IP addresses.
If the parameter stable_order is true (default), the returned array is sorted by network order criteria.
Input
- host : an IP address
- ipversion: IP version: 4 (default) or 6.
- stable_order: (optional) true or false. Default true.
Output
A vector of strings.Errors
An exception is raised if an error occurs.Examples
Expression Return value Description resolveall(“yahoo.it”, 4, stable_order=1) [‘74.6.50.24’, ‘77.238.184.24’, ‘98.137.236.24’, ‘106.10.212.24’, ‘212.82.102.24’] | resolveall(“yahoo.it”, 4, stable_order=0) [‘106.10.212.24’, ‘212.82.102.24’, ‘74.6.50.24’, ‘77.238.184.24’, ‘98.137.236.24’] | resolveall(“yahoo.it”, 4, stable_order=1)[0] ‘74.6.50.24’
4.2.2.11.3. buff2IP¶
Syntax
buff2IP ( string )Description
Convert the buffer of bytes string storing a IPv4 address to it’s dotted-string rappresentation (es: 192.168.0.24).Input
- string : a 4 byte buffer string
Output
A stringErrors
An exception is raised if the input string does not store an IPv4 address.Examples
Expression Return value Description buff2IP( 1.2.3.6.1.2.3@ ) “173.194.113.230” OID’s values is a 4-byte buffer storing the IP address 173.194.113.230.
4.2.2.12. JMX Protocol¶
4.2.2.12.1. jmx¶
IMPORTANT: this function requires the jmx-utils package installed where machine the agent using this function is running on.
Syntax
jmx ( bean_type , bean_name , [ options ] )Description
Retrieves the value of the given java bean: bean_type, bean_name
Valid optinal arguments are:
Option Description getlast When 1 the function returns the value fetched in the last datagroup execution. host JMX server. Default is taken from execution context $node. port JMX port. Default is taken from execution context $port username JMX username. password JMX password java_bin JVM shell command. Default is: /usr/bin/java. jmxcmd_bin JMX Client program installed with the jmx-utils package. Default is /usr/local/jmxcmd/bin/jmxcmd.jar, timeout Timeout in seconds. Input
- bean_stype: string
- bean_name: string
Outpu
Returns the bean’s value.Errors
Raise an exception if an error occours.Examples
Expression Return value Description jmx(‘java.lang:type=Runtime’, ‘Uptime’) 123141151 jmx(‘java.lang:type=Memory’, ‘HeapMemoryUsage.committed’) 561231
4.2.3. VMware utils¶
4.2.3.1. VMware tools¶
4.2.3.1.1. vmware_esx¶
Syntax
vmware_esx ( username, password, esx_server, select, subselect [, sslport] [, vmware_script_path] [, timeout] [, whitelist] [, is_datacenter] )Description
The function returns the selected information about the ESX server.
Argument Description username VMware Username password VMware Password esx_server ESX hostname select Could be “cpu” (CPU information), “mem” (memory information), “runtime” (runtime information) or “storage” (storage information) subselect See table below sslport If a SSL port different from 443 is used vmware_script_path If a VMware script path different from “/usr/local/sanet-check-vmware/check_vmware_esx.pl” is used timeout If a timeout different from 10 seconds is setted (in milliseconds) whitelist whitelist as regexp is_datacenter Flag (1 o 0) if the esx_server is a normal server o datacenter Valid subselect arguments are:
- cpu
- ready (ms): time that the virtual machine was ready, but could not get scheduled to run on the physical CPU.
- wait (ms): CPU time spent in wait state. The wait total includes time spent the CPU idle, CPU swap wait, and CPU I/O wait states.
- usage (%): actively used CPU of the host, as a percentage of the total available CPU.
- mem
- usage (%): average mem usage in percentage.
- consumed (byte): amount of machine memory used on the host.
- swapused (byte): amount of memory that is used by swap.
- overhead (byte): additional mem used by VM Server.
- memctl (byte): the sum of all vmmemctl values for all powered-on virtual machines, plus vSphere services on the host.
- runtime
- con: shows connection state (connected, disconnected, inaccessible, invali, orphaned).
- status: overall object status. The state can be gray (unknown), green (ok), red (definitely has a problem), yellow (might have a problem).
- health: checks cpu/storage/memory/sensor status.
- issues: lists all configuration issues for the host. Output could be “All X health checks are GREEN” or could show some problem.
- storagehealth: local storage status check.
- listhost: list all host and their status.
- storage
- lun: list SCSI logical units with their status.
Input
- username: string
- password: string
- esx_server: string
- select: string (cpu, mem, runtime)
- subselect: string (see above)
- sslport: string or integer (default: 443)
- vmware_script_path: string (default: “/usr/local/sanet-check-vmware/check_vmware_esx.pl”)
- timeout: integer (default: 10 seconds) in milliseconds
- whitelist: string (default: None), available only for commands:
- select=runtime, subselect=health
- select=runtime, subselect=issues
- select=runtime, subselect=storagehealth
- select=storage, subselect=lun
- is_datacenter: boolean (default: False)
If whitelist is used for not supported commands the output will be unchanged.
Output
Returns the requested information.Errors
Raise an exception if an error occours.Examples
Expression Return value Description vmware_esx(“<username>”, “<password>”, “virtuoso”, “cpu”, “ready”) 183.00 time that the virtual machine was ready in ms vmware_esx(“<username>”, “<password>”, “virtuoso”, “mem”, “consumed”) 6467753082.88 amount of machine memory used on the host in byte vmware_esx(“<username>”, “<password>”, “virtuoso”, “runtime”, “con”) OK: connection state=connected connection state
4.2.3.1.2. vmware_vm¶
Syntax
vmware_vm ( username, password, esx_server, vm_name, sel, subselect [, sslport, vmware_script_path, timeout] )Description
The function returns the selected information about the virtual machine.
Argument Description username VMware Username password VMware Password esx_server ESX hostname vm_name Virtual machine name select Could be “cpu” (CPU information), “mem” (memory information) or “runtime” (runtime information) subselect See the table below sslport If a SSL port different from 443 is used vmware_script_path If a VMware script path different from “/usr/local/sanet-check-vmware/check_vmware_esx.pl” is used timeout If a timeout different from 10 seconds is setted (in milliseconds) Valid subselect arguments are:
- cpu
- ready (ms): time that the virtual machine was ready, but could not get scheduled to run on the physical CPU.
- wait (ms): CPU time spent in wait state. The wait total includes time spent the CPU idle, CPU swap wait, and CPU I/O wait states.
- usage (%): actively used CPU of the host, as a percentage of the total available CPU.
- mem
- usage (%): average mem usage in percentage.
- consumed (byte): amount of machine memory used on the host.
- memctl (byte): the sum of all vmmemctl values for all powered-on virtual machines, plus vSphere services on the host.
- runtime
- con: shows connection state (connected, disconnected, inaccessible, invali, orphaned).
- powerstate: virtual machine power state (poweredOn, poweredOff, suspended).
- status: overall object status. The state can be gray (unknown), green (ok), red (definitely has a problem), yellow (might have a problem).
- consoleconnections: console connections to VM.
- gueststate: guest OS status. Can be: running, shuttingdown, resetting, standby, notrunning, unknown.
- tools: Vmware tools status. Can be:
- VMware tools are starting.
- VMware tools are not running.
- VMware tools are running.
- VMware tools are installed, but the installed version is known to have a grave bug and should be immediately upgraded.
- VMware tools are installed, but the version is not current.
- VMware tools were never been installed.
- VMware tools are installed, supported, and newer than the versionavailable on the host.
- No information about VMware tools available.
- New since vSphere API 5.0:
- VMware tools are installed, and the version is current.
- VMware tools are installed, supported, but a newer version is available.
- VMware tools are installed, and the version is known to be too new to work correctly with this virtual machine.
- VMware tools are installed, but the version is too old.
- VMware tools are installed, but it is not managed by VMWare.
- issues: all issues for the host. Can be: X config issues.
Input
- username: string
- password: string
- esx_server: string
- vm_name: string
- select: string (cpu, mem, runtime)
- subselect: string (see above)
- sslport: string or integer (default: 443)
- vmware_script_path: string (default: “/usr/local/sanet-check-vmware/check_vmware_esx.pl”)
- timeout: integer (default: 10 seconds) in milliseconds
Output
Returns the requested information.Errors
Raise an exception if an error occours.Examples
Expression Return value Description vmware_vm(“<username>”, “<password>”, “virtuoso”, “loggit”, “cpu”, “usage”) 0.48 actively used CPU as a percentage vmware_vm(“<username>”, “<password>”, “virtuoso”, “loggit”, “mem”, “memctl”) 0.0 sum of all vmmemctl values in byte vmware_vm(“<username>”, “<password>”, “virtuoso”, “loggit”, “runtime”, “powerstate”) OK: Power state: poweredOn power state
4.2.4. Local utilities¶
4.2.4.1. External Programs execution¶
4.2.4.1.1. exec¶
Syntax
exec ( current , command , [ param, …] [ , basedir ] [ , execute_timeout ] )Description
The function executes the external command command with the given param(s) param and returns the content of the standard output produced by the script.
When the current parameter is true, the command is executed with the given parameters.
If current is false, the function returns the standard output produced by the command at the previous check for the same datagroup.
The command must specify the full path (es.: /bin/ls).
Input
- current: boolean.
- command: string containing the script name.
- *param*(s): strings containt the script’s param(s)
- basedir: basedir for the given command (es: basedir=/usr , command=/bin/hello -> /usr/bin/hello)
- execute_timeout: Maximun execution timeout.
- exec_on_remote_agent: The script is executed on the server where the agent related to the datagroup is running on. If execute_timeout is not set, it’s forced to 60 seconds.
Output
Returns a string.Errors
Examples
Expression Return value Description exec(True, “mydate.sh”) ven nov 26 16:41:30 CET 2010 the script mydate.sh is: <br /><br />#!/bin/bash<br />date exec(0, “mydate.sh”) ven nov 25 16:41:30 CET 2010 Returns the output of the last execution exec(0, “mydate.sh”, timeout=0) exception Program not returned before timeout exec(0, “mydate.sh”, basedir=”/scripts/”) error Program not found in /scripts/ directory exec(0, “mydate.sh”, basedir=”/scripts/”, exec_on_remote_agent=1) error Program not found in /scripts/ directory
4.2.4.1.2. prevExec¶
Syntax
prevExec ( command , [ param, …] )Description
The function returns the value calculated by exec() at the previous datagroup execution.
It’s a shortcut for the equivalente version:
prevExec(...programm..., ...params...) exec(1, ...program..., ....params....)Input
- command: file path of the command
- params: variable number of parameters
Output
Returns a stringErrors
Raise an exception if the previous value can is not present.Examples
Expression Return value Description prevExec(“mydate.sh”) ven nov 26 16:41:30 CET 2010 The previews value returned by mydate.sh
4.2.4.2. Filesystem functions¶
4.2.4.2.1. mtime¶
Syntax
mtime ( fname )Description
Performs a stat() system call on the given path fname and returns the time of most recent content modification.
If an error occurrs the function returns 0.
Output
Returns a floating point value.Examples
Expression Return string value mtime(“/etc/passwd”) 1291971078.92 mtime(“/etc2/foo”) 0
4.2.4.2.2. readFile¶
Syntax
readFile ( path )Description
The function returns the content of the given file.Input
path: string containing the file absolute pathOutput
Returns a string.Errors
Raises an exceptions if an error occurs while opening/reading the fileExamples
Expression Return value Description readFile(“/etc/hosts”) 127.0.0.1 localhost readFile(“/tmp/nonexistent”)
EXCEPTION
4.2.5. SNMP¶
4.2.5.1. SNMP Utils¶
4.2.5.1.1. str2oid¶
Syntax:
str2oid( *string* )Description
Convert a char string to the corrisponding OID string.Input
- string:
Outpu
Return a valid OID string.Errors
Raises and exception if the input string can not be converted to a valid OID string.Examples
Expression Return value Description str2oid(“foo bar”) 102.111.111.32.98.97.114
4.2.5.1.2. tryget¶
Syntax:
tryget **(** *snmp expr* **,** *default value* **)**Description
Execute the SNMP expression and returns its value. If the value can not be retrieved, the default value is returned instead.Input
- snmp expr: a valid Sanet SNMP expression
- default value: any value
Outpu
Any valueErrors
NoneExamples
Expression Return value Description tryget( 1.3.6.1.2.1.1.1.0@, “foo” )
- a value * or foo
4.2.5.1.3. testget¶
Syntax:
testget **(** *snmpexpr* **)**Description
Tries to calculate the value for the given SNMP expression.Input
- snmpexpr: a SNMP expression.
Outpu
TODOErrors
TODOExamples
Expression Return value Description testget( 1.3.6.1.2.1.1.1.0@ ) true testget( 9.8.7.6.2.1.1.1.0@ ) false
4.2.5.1.4. sumall¶
Syntax
sumall* ( oid , community , hostname [ , hostname ] )Description
Retrieves the value for the given oid from every hostanme with the given community and sums all the values together.
If some hosts do not export the required MIB or an error occurs, the host is skipped.
Input
oid: String containin the OID. community: SNMP community hostname: node hostnameOutput
Returns a numberErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression value sumall(“1.3.6.1.2.1.1.3.0”, “public”, “foo”,”bar”) 1531782725
4.2.5.2. SNMP Walk utils¶
4.2.5.2.1. walkAverage¶
Syntax
walkAverage ( snmp expr )Description
Calculates the the arithmetic average of the elements of the MIB specified by snmp expr.
Not numreic MIB’s elements will be ignored
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkAverage( 1.3.6.1.2.1.2.2.1@”bar” )
- 1935680570.0*
4.2.5.2.2. walkCount¶
Syntax
walkCount ( snmp expr )Description
Returns the number of elements of the MIB specified by snmp expr.Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkCount( 1.3.6.1.2.1.2.2.1@”bar” ) 44.0
4.2.5.2.3. walkCountMatch¶
Syntax
walkCountMatch ( snmpexpr , str_regexpr_oid , str_regexpr_val )Description
Scans the MIB identified by the SNMP expression snmpexpr. The MIB sub-oid and the value is compared with the regular expressions str_regexpr_oid and str_regexpr_val. The number of matching entries is returned.Input
- snmpexpr: SNMP Expression identifying the MIB to scan.
- str_regexpr_prefix: Regular expression string matching the sub-OIDs in the MIB
- str_regexpr_val: Regular expression string matching the OIDs’ value
Output
Returns the number of matching entriesErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkCountMatch( 1.2.3.4.5@ , “^6.7.8”, “^5$”) 44.0
4.2.5.2.4. walkMax¶
Syntax
walkMax ( snmp expr )Description
Returns the maximum numeric value found inside the specified MIB.
Not numreic MIB’s elements will be ignored
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkMax( 1.3.6.1.2.1.2.2.1@”bar” )
- 1935680570.0*
4.2.5.2.5. walkMaxPos¶
Syntax
walkMaxPos ( snmp expr )Description
Returns the maximum positive* **numeric value found inside the specified MIB.
Not numreic MIB’s elements will be ignored
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkMaxPos( 1.3.6.1.2.1.2.2.1@”bar” )
- 1935680570.0*
4.2.5.2.6. walkMin¶
Syntax
walkMin ( snmp expr )Description
Returns the minimum numeric value found inside the specified MIB.
Not numreic MIB’s elements will be ignored
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkMin( 1.3.6.1.2.1.2.2.1@”bar” )
- 1935680570.0*
4.2.5.2.7. walkMinPos¶
Syntax
walkMinPos ( snmp expr )Description
Returns the maximum numeric positive value found inside the specified MIB.
Not numreic MIB’s elements will be ignored.
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkMaxPos( 1.3.6.1.2.1.2.2.1@”bar” )
- 1935680570.0*
4.2.5.2.8. walkSum¶
Syntax
walkSum ( snmp expr )Description
Sums together all the elements of the MIB specified by snmp expr.
MIB’s element not suitable for arithmetic addition are ignored.
Input
- snmp expression: A SNMP expression
Output
Returns a integerErrors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.Examples
Expression Return Value walkSum( 1.3.6.1.2.1.2.2.1:”public”@”foo” ) 5294132713.0
4.2.5.2.9. walkDiff¶
Syntax
walkDiff ( snmp expr [ , threshold [ , verbose_info ] ] )Description
Performs a SNMP Walk on the given snmp expr and compare the returned table content with the content of the same table fetched at the previous check.
Returns true if the content is not changed.
If threshold is specified, the table entries with a value difference <= given threshold are considered unchanged.
If verbose_info is set to 1, the function adds verbose informations to the execution text.
Input
- snmp expression: A SNMP expression.
- threshold: Value threshold.
Output
Returns a booleanErrors
The function raises an exception if the given SNMP MIB does not exists.Examples
Expression Return Value walkDiff( 1.3.6.1.2.1.2.2@) True walkDiff( 1.3.6.1.2.1.2.2@, 10) True
4.2.5.2.10. walkFilter¶
Syntax
walkFilter ( snmp expr , selected suboid , suboid 1 , val 1 , suboid 2 , val 2 … )Description
Scans the MIB identified by the SNMP expression snmparg and returns all the values of the selected suboid if the table entry matches <suboid1>, <suboid2>, ect. and the corresponding values specified by the regular expressions <regexpr1>, <regexpr2>, etc.
Each matching expression (es: regexpr1) must be a string of this form:
value type / regular expressionThe value type must be b (binary) or s (string).
Example:
s/foo i/1034Input
- snmp expr: Base oid
- selected suboid: oid string
- suboid n : suboid string
- val n : string with
Output
Returns a vector of valuesErrors
The function raises an exception when an error occours.Examples
Expression Return Value Description sum(walkFilter(1.3.6.1.2.1.2@, “2.1.4”, “2.1.7”, “i/1”)) 31436 Sums all MTU (…2.1.4) of active interfaces (…2.1.7)
4.2.5.3. RegExpr¶
4.2.5.3.1. byBinaryValue¶
Syntax
byBinaryValue ( snmpexpr , str hex )Description
Scans the MIB identified by the SNMP expression snmpexpr. The binary value of every entry in the mib is compared with the hexadecimal string stored in the parameter str hex and the first matching sub-OID is returned.Input
snmpexpr : A SNMP expression indentifing a valid MIB. str hex : A string containing a valid hexadecimal string.Output
Returns a string OID.Errors
The function raises an exception when the matching sub-OID is not found.Examples
Expression Return value Description byBinaryValue(1.3.6.1.2.1.2.2.1.6@, “fefd00000000”) 2 It returns the ifPhysAddress sub-oid of the interface with MAC address “fefd00000000”.
4.2.5.3.2. byRegexpUnique¶
Syntax
byRegexpUnique ( snmpexpr , str_regexpr )Description
Scans the MIB identified by the SNMP expression snmpexpr. The value of every entry in the mib is compared with the regular expression stored in the parameter str_regexpr and the first matching sub-OID is returned.Input
snmpexpr : A SNMP expression indentifing a valid MIB. snmpexpr : A string containing a valid regular expression.Output
Returns a string OID.Errors
The function raises an exception when the matching sub-OID is not found.Examples
Expression Return value Description byRegexpUnique(1.3.6.1.2.1.2.2.1.@, “eth0”) 2.4 It returns the ifDescr sub-oid for the interface matching the string “eth0” ( 1.3.6.1.2.1.2.2.1.**2.4** = eth0 ).
4.2.5.3.3. byMultiRegexpUnique¶
Syntax
byMultiRegexpUnique ( snmparg , [ suboid1 , regexpr1 ] , [ suboid2 , regexpr2 ] , … )Description
Scans the MIB identified by the SNMP expression snmparg and verifies all the sub-oids <suboid1>, <suboid2>, ect. match with the corresponding regular expressions <regexpr1>, <regexpr2>, etc. The instance of the matching table entry is returned.
The second element of each tuple rappresent the matching expression and must be a string of this form:
value type / regular expression
The value type must be b (binary) or s (string).
Input
- snmpexpr : A SNMP expression indentifing a valid MIB.
- sequence of suboid1, regexpr1 : A string containing a valid regular expression.
Output
Returns a string OID.Errors
The function raises an exception when the matching sub-OID is not found.Examples
Expression Return value Description byMultiRegexpUnique(1.3.6.1.2.1.25.4.2.1@ , “2” , “s/^apache.exe$”, “4” , “s/^/bin/apache$” , “5”, “s/^foo$” ) 4232 Searches for a process ‘apache.exe’ in the hrprocess MIB with path ‘/bin/apache’ and called with parameter ‘foo’ byMultiRegexpUnique(1.3.6.1.2.1.25.4.2.1@ , “2” , “s/^” + re_escape(“c:apache.exe”) + “$”) 123 Searches for a process ‘c:apache.exe’.
4.2.5.3.4. byMultiRegexpCount¶
Syntax
byMultiRegexpCount ( snmparg , [ suboid1 , regexpr1 ] , [ suboid2 , regexpr2 ] , … )Description
Scans the MIB identified by the SNMP expression snmparg and counts all the sub-oids <suboid1>, <suboid2>, ect. match with the corresponding regular expressions <regexpr1>, <regexpr2>, etc.
The second element of each tuple rappresent the matching expression and must be a string of this form:
value type / regular expressionThe value type must be b (binary) or s (string).
Input
- snmpexpr : A SNMP expression indentifing a valid MIB.
- sequence of suboid1, regexpr1 : A string containing a valid regular expression.
Output
Returns a string OID.Errors
The function raises an exception if an error occours.Examples
Expression Return value Description byMultiRegexpCount(1.3.6.1.2.1.25.4.2.1@ , “2” , “s/^apache.exe$”, “4” , “s/^/bin/apache$” , “5”, “s/^foo$” ) 42
4.2.5.3.5. existsRegexp¶
Syntax
existsRegexp ( snmpexpr , str_regexpr )Description
Scans the MIB identified by the SNMP expression snmpexpr. The value of every entry in the mib is compared with the regular expression stored in the parameter str_regexpr. The function returns true if there is a least one matching entry in the MIB.Input
- snmpexpr : A SNMP expression indentifing a valid MIB.
- str_regexpr : A valid regular expression.
Output
Returns a string OID.Errors
Examples
Expression Return value Description existsRegexp( 1.3.6.1.2.1.2.2.1@, “eth0”) 1 Checks if there is an interface called “eth0”
4.2.5.3.6. existsRegexpUnique¶
Syntax
existsRegexpUnique ( snmpexpr , str_regexpr )Description
Scans the MIB identified by the SNMP expression snmpexpr. The value of every entry in the MIB is compared with the regular expression stored in the parameter str_regexpr. The function returns true if there is only one matching entry in the MIB.Input
- snmpexpr : A SNMP expression indentifing a valid MIB.
- str_regexpr : A valid regular expression.
Output
Returns a string OID.Errors
Examples
Expression Return value Description existsRegexpUnique( 1.3.6.1.2.1.2.2.1@, “eth0”) 1 There is only one “eth0” interface existsRegexpUnique( 1.3.6.1.2.1.2.2.1@, “^eth”) 0 There are too many interfaces with prefix “eth”
4.2.5.3.7. byBinaryIP¶
Syntax
byBinaryIP ( snmpexpr , str_ip )Description
Scans the MIB identified by the SNMP expression snmpexpr. The string value of every entry is compared with the hexadecimal representation of the IPv4 address str_ip.Input
- snmpexpr : A SNMP expression indentifing a valid MIB.
- str_ip : A valid regular expression.
Output
Returns a string OID.Errors
Examples
Expression Description existsRegexp( 1.3.6.1.2.1.2.2.1@, “255.255.255.0”) Checks if there is an entry in the MIB matching the string FFFFFF00.
4.2.5.4. Storage utils¶
4.2.5.4.1. hrStorageNoFull¶
Syntax
hrStorageNoFull ( default_percent_threshold , [ storage_re , percent_threshold [, … ] ] )Description
This function takes one mandatory argument, and optional argument pairs.
When invoked with just the mandatory argument, it will check the occupation of all the filesystems of the current node, as seen in the hrstorage table, having type “Fixed disk” (1.3.6.1.2.1.25.2.1.4) or “Network disk” (.1.3.6.1.2.1.25.2.1.10), against the default_percent_threshold.
If all filesystems are below thresholds, it will return 0, otherwise it will return 1.
Optional argument pairs of the form:
storage_re, percent_thresholdspecify a different threshold for specific filesystems.
When the hrStorageDescr (1.3.6.1.2.1.25.2.3.1.3) of the filesystem matches the provided storage_re, its occupation will be checked against the percent_threshold specified next to it, instead of the first argument.
You can specify -1 as a threshold to actually disable checking some filesystems.
If one of the specified filesystems regexp is not found, the function skips it without error.
Returns
Returns 1 when all selected filesystems satisfy the given thresholds (default_percent_threshold for default or percent_threshold for the selected filesystems), 0 otherwise.
If no filesystems are found, or the node doesn’t answer to SNMP requests, the function becomes uncheckable.
If the node has only entries of type different from “Fixed disk” and “Network disk” in the hrStorageTable, the function returns 1.
Examples
Expression Return string value hrStorageNoFull(99) 1 hrStorageNoFull(99, “^/run$”, -1) 1, /run ignored. hrStorageNoFull(99, “^/run/log$”, 80, “^/home$”, 90)
- Check every partition with 99%, /run/log with 80%, /home with 90%.
4.2.5.5. Interface utils¶
4.2.5.5.1. isEtherFd¶
Syntax
isEtherFd ( ifindex )Description
The function tries to verify if the interface with the given ifindex is in ethernet Full-duplex mode.
The function looks inside the execution context for the following informations: * $node: the hostname of the remote host * $community: the SNMP community to use * $snmpversion: SNMP version to use * $snmpport: SNMP port to use * $shorttries: number of SNMP tries
Input
ifindex: integer value.Output
Returns a booleanErrors
The function raises an exception if it can not retrieve enough informations about the interface.Examples
Expression Return value Description isEtherFd( 1 ) true isEtherFd( $myIfindex ) true isEtherFd( 1.3.6.1.2.1.2.2.1.1.1@ ) false Retrieve the ifindex stored in the mib of the current node (1.3.6.1.2.1.2.2.1.1.1@)
4.2.5.5.2. getHCInOctets¶
Syntax
getHCInOctets ( [ host ] [ , ifindex] [ , community ] [ , shorttries ] )Description
Returns the value of the ifHCInOctets for the given host/iface.Input
- host: the node.
- ifindex: (optional) the ifindex of the current interface.
- comm: (optional) the SNMP community to use.
- shorttries: (option) the max number of SNMP packets to send before abort.
Output
Returns a numberErrors
The function raises an exception if an error occurs.Examples
Expression Return value Description getHCInOctets($node) 123131
4.2.5.5.3. getHCOutOctets¶
Syntax
getHCOutOctets ( [ host ] [ , ifindex] [ , community ] [ , shorttries ] )Description
Returns the value of the ifHCOutOctets for the given host/iface.Input
- host: the node.
- ifindex: (optional) the ifindex of the current interface.
- comm: (optional) the SNMP community to use.
- shorttries: (option) the max number of SNMP packets to send before abort.
Output
Returns a booleanErrors
The function raises an exception if it can not retrieve enough informations about the interface.Examples
Expression Return value Description getHCOutOctets($node) 5678
4.2.5.5.4. ifSpeed¶
Syntax
ifSpeed ( ifindex [ , default ] [ , ignore_snmp_errors ] )Description
Tries to fetch the interface speed via SNMP for the given ifindex interface. Returns the number of bits/second.
The functions search for the ifHighSpeed (1.3.6.1.2.1.31.1.1.1.15) or the ifSpeed (1.3.6.1.2.1.2.2.1.5) OIDS.
if ignore_snmp_errors is set to true (or 1), any error while accessing the OIDS is ignored. If default is specified and ignore_snmp_errors is enabled, default is returned.
Input
- ifindex : ifindex of the selected interface.
- default : (optional) Default return value if an error occurs and ignore_snmp_errors is enabled.
- ignore_snmp_errors: (optional) the SNMP community to use.
Output
Returns a numeric value (bit/s).Errors
The function raises an exception when an error occurs and ignore_snmp_errors is not enabled.Examples
Expression Return value Description ifSpeed($ifindex) 1000000
4.2.5.6. OIDs Utilities¶
4.2.5.6.1. oidFirst¶
Syntax
oidFirst ( oid )Description
The function take in input a dot-separted OID string and returns the first node of the sequence.Input
oid: a dot-separated string.Output
Returns a stringErrors
Examples
Expression Return string value Description oidFirst(“9.8.7.8.5.4.3.2.1”) 9 oidFirst( 1.3.6.1.2.1.1.2.0@”mason” ) 1 Extracts the first node from the node’s SysOID
4.2.5.6.2. oidLast¶
Syntax
oidLast ( oid )Description
The function takes in input a dot-separted OID string and returns the last node of the sequence.Input
oid: a dot-separated string.Output
Returns a stringErrors
Examples
Expression Return string value Description oidFirst(“9.8.7.8.5.4.3.2.1”) 1 oidFirst( 1.3.6.1.2.1.1.2.0@”mason” ) 1 Extracts the last node from the node’s SysOID
4.2.5.6.3. oidIp¶
Syntax
oidIp ( string )Description
The function takes in input a string representing an IPv6 address and returns an OID made with the 16 bytes of the address (16). It can be passed a valid IPv4 address, and it will simply return the same address. The function throws an error (becomes uncheckable) if the argument is not a valid IPv4 or IPv6 address.Input
string: an ASCII string.Output
Returns an OIDErrors
Examples
Expression Return string value oidIp(“2a01:4f8:110:3383::1”) ‘42.1.4.248.1.16.51.131.0.0.0.0.0.0.0.1’
4.2.5.6.4. oidString¶
Syntax
oidString ( string )Description
The function takes in input a string and returns an OID made with the length of the string as the first item, and the ASCII values as subsequent items. The function throws an error (becomes uncheckable) if the string is not ASCII.Input
string: an ASCII string.Output
Returns an OIDErrors
Examples
Expression Return string value oidString(“abc”) 3.97.98.99 oidString(“FIXME please” ) 12.70.73.88.77.69.32.112.108.101.97.115.101
4.2.6. SNMP Advanced¶
4.2.6.1. STP/Bridge utils¶
vtpCommunity(context, host, comm, ifindex):
4.2.6.1.1. ifIndex2stp¶
Syntax:
*ifIndex2stp* **(** host **,** ifindex [ **,** community] [ **,** sv ] **)**Description
Returns the port number for the given host/ifindex.Input
- host:
- ifindex:
- communty:
- sv:
Outpu
Returns a numberErrors
Raises and exception if an error occurs.Examples
Expression Return value Description ifIndex2stp($node, $ifindex) 23
4.2.6.1.2. vtpCommunity¶
Syntax:
vtpCommunity **(** host **,** comm **,** ifindex **)**Description
TODOInput
- host:
- communty:
- ifindex:
Outpu
Returns a stringErrors
Raises and exception if an error occurs.Examples
Expression Return value Description vtpCommunity($node, $community, $ifindex) “public”
4.2.6.2. SNMP Advanced¶
4.2.6.2.1. adjacent¶
Syntax
adjacent ( [ method , method *,** … ] )Description
This function must be used only for targets of interfaces. It verifies if a link exists between the target interface and its linked interface.
The presence of a link is verified by using several methods. Supported methods are:
- “stp”
- “cdp” (Cisco CDP protocol MIBS)
- “lldp”
- “edp” (Extreme EDP protocol MIBS)
If no methods are specified, the functions tries all the supported methods in this sequence: stp, cdp, lldp.
Important
The function remember the last successfull method and tries it first at the next execution.
Input
- variable number of strings.
Output
Returns a boolean: true or false. Returns false at the first invalid method encountered in the input list.Errors
Raise an exception and when error occurs while testing the adjacency.Examples
Expression Description Return value adjacent() adjacent(“stp”) adjacent(“stp”, “cdp”)
4.2.6.3. Airespace¶
4.2.6.3.1. airespaceAPChannelInterference¶
Syntax
calculateAirespaceAccessPointInstance( ap_macaddress ):Description
Given the Access Point’s MAC address ap_macaddress, finds the OID instance inside the controller MIB.Input
- ap_macaddress: string containing the hexadecimal MAC Address.
Output
Returns a string with an OID instance.Errors
An exception is raised if an error (es: timeour) occurs,Examples
Expression Description Return value calculateAirespaceAccessPointInstance(“00AE13CA89”) 134
4.2.6.3.2. airespaceAPChannelInterference¶
Syntax
airespaceAPChannelInterference ( threshold , [ selected_antenna ] )Description
Read RSSI values inside the Controller MIB for the current AP. All informations are formatted and returned in the global verbose status of the expression check.
Only RSSI with value greater than threshold are returned. If specified
Input
- threshold: Minimum RSSI accepted value.
- selected_antenna: The number of the antenna: 0 for 2.4Gh (default), 1 for 5gh.
Output
Returns True if at least one RSSI value satisfies the given threshold/antenna filter.Errors
An exception is raised if an error occurs.Examples
Expression Description Return value airespaceAPChannelInterference(30) True airespaceAPChannelInterference(30, 1)
4.2.6.4. Cisco utils¶
4.2.6.4.1. ciscoNoErrDisabled¶
Syntax
ciscoNoErrDisabled ( [ mib_check_oid ] )Description
The function checks the cErrDisableIfStatusTable (1.3.6.1.4.1.9.9.548.1.3.1) in the CISCO-ERR-DISABLE-MIB, and returns 1 (true) if the table is empty (i.e. there are no errdisabled ports).
If there are errdisabled ports the function returns 0 (false) and writes in the context a description of the relevant interfaces and their errdisable reason.
The function verifies that the MIB is supported by fetching the specified OID mib_check_oid. The default OID is cErrDisableRecoveryInterval (1.3.6.1.4.1.9.9.548.1.1.1).
If the OID mib_check_oid can not be fetched, the function raises an exception and the expression evaluation goes UNCHECKABLE.
Input
- mib_check_oid: (optional) a string containing a valido OID.
Output
A booean (true or false)Errors
If an error occurs or the OID mib_check_oid is not defined (default OID: cErrDisableRecoveryInterval).Examples
Expression Return value Description ciscoNoErrDisabled() 1 ciscoNoErrDisabled(“1.3.6.1.4.1.9.9.548.1.1.3”) UNCHECKABLE The host does not define OID 1.3.6.1.4.1.9.9.548.1.1.3.
4.2.6.4.2. ciscoSensorThresholdsOk¶
Syntax
ciscoSensorThresholdsOk ( [ ignore_when_notification_disabled ] [ , ignore_names_re ] [ , ignore_instances ] )Description
TODOInput
- TODO
Output
TODOErrors
TODOExamples
Expression Description Return string value iscoSensorThresholdsOk() 01279AF7A4D iscoSensorThresholdsOk(ignore_instances=1) 01279AF7A4D
4.2.6.5. Filesystem functions¶
4.2.6.5.1. calculateH3CDot11AccessPointInstance¶
Syntax
calculateH3CDot11AccessPointInstance ( )Description
Returns the H3C Access Point (dependent node) instance inside the controller node (master node) MIB.Output
String valueErrors
Raises an exception if the association can not be calculated.Examples
Expression Return string value calculateH3CDot11AccessPointInstance() 124.1.58.9
4.2.7. Redis DB Utilities¶
4.2.7.1. Redis Utils¶
Syntax
redis ( key [ , host ] [ , port ] [ , db ] [ , default ] )Description
Tries to get the value for the key key from a Redis DB. The parameter host, port and db are facultatives. Their default values are: host=’localhost’, port=6379, db=0.
An exception is raised when the key is not found and default is not specified.
** Output **
A single value.Examples
Expression Return string value Description redis(“a.key.in.the.db”) foo redis(“xxx”) ERROR Key xxx does not exist. redis(“xxx”, default=10) 10 Default returned.
4.2.8. Database functions¶
4.2.8.1. Oracle¶
4.2.8.1.1. oracle_raw_query¶
Syntax
oracle_raw_query ( dsn , username , password , query )Description
Connects to the given dsn oracle instance and executes the given query with the give username/password.Input
- dsn: oracle instance identifier
- username: string
- password: string
- query: a valid SQL command
Output
Returns the first column of the first row of the returned record set.Errors
An exception is raised when an error occurs.Examples
Expression Return string value Description oracle_raw_query(“dsn1”, “user”, “password”, “SELECT count(*) FROM table1”) 9
4.2.8.1.2. oracle_dsn¶
TODO
4.2.8.2. Postgres functions¶
4.2.8.2.1. psql_query¶
Syntax
psql_query ( dbname , query [ , host ] [, port ] [, user] [, password] [, timeout] )Description
Connect to the database dbname and executes the given query and returns the first row of the recordset.Input
- dbname - the database name
- host - database host address (defaults to UNIX socket if not provided)
- port - connection port number (defaults to 5432 if not provided)
- user - user name used to authenticate
- password - password used to authenticate
Output
A tuple of values (the first row of the queryset)Errors
An exception is raised on connect timout or when the query returns an error.Examples
Expression Description Return string value psql_query(“mydb”, “SELECT * FROM table1”) psql_query(“mydb”, “SELECT * FROM table1”)[0] psql_query(“mydb”, “SELECT * FROM table1”, user=”foo”, password=”bar”)[0] Connect to localhost and returns the first row of the queryset. Returns the first column value of the first row of the queryset. Returns the first column value of the first row of the queryset.
4.2.8.3. MS SQL function¶
4.2.8.3.1. mssql_check¶
Syntax
mssql_check ( mode, username [, password ][, host ][, port ][, db_name][, …] )Description
Performs a check specified by mode argument and returns its value. If not specified, host argument is taken from the checked node.Input
mode: kind of control to perform on MS SQL Server.
username: username used to execute queries on MS SQL Server.
password: password associated to username for authentication.
host: host name or ip address of MS SQL Server instance. Default is $node.
port: port to connecto to on host machine. Default is 1433.
db_name: name of a specific database to perform the control on (meaningful only for some controls). If not specified all databases are considered.
threshold: a threshold value to use on specific mode checks, mandatory for them.
- Modes
- Server controls
Modes Description Return value Threshold DB_name connections Number of open connections to MS SQL server. int No No cpu Percentage of CPU utilization by MS SQL Server. percentage No No bufferhitratio Percentage of pages found in the buffer cache without having to read from disk. The ratio is the total number of cache hits divided by the total number of cache lookups over the last few thousand page accesses. percentage No No pagelooks Page lookups per second. float(delta) No No freepages Total number of free pages (cumulative). int No No totalpages Total number of pages (cumulative). int No No targetpages Ideal number of pages in buffer pool (cumulative). int No No databasepages Number of pages in the buffer pool with database content (cumulative). int No No stolenpages Number of pages used for miscellaneous server purposes (including procedures cache). int No No lazywrites Number of buffers written per second by the buffer manager’s lazy writer. The lazy writer is a system process that flushes out batches of dirty, aged buffers (buffers that contain changes that must be written back to disk before the buffer can be reused for a different page) and makes them available to user processes. The lazy writer eliminates the need to perform frequent checkpoints in order to create available buffers. float(delta) No No readahead Number of pages read per second in anticipation of use. float(delta) No No pagereads Number of physical database page reads that are issued per second. This statistic displays the total number of physical page reads across all databases. float(delta) No No checkpoints Number of pages flushed to disk per second by a checkpoint or other operation that require all dirty pages to be flushed. float(delta) No No pagewrites Number of physical database page writes issued per second. float(delta) No No lockrequests Number of new locks and lock conversions per second requested from the lock manager. float(delta) No No locktimeouts Number of lock requests per second that timed out, including requests for NOWAIT locks. float(delta) No No deadlocks Number of lock requests per second that resulted in a deadlock. float(delta) No No lockwaits Number of lock requests per second that required the caller to wait. float(delta) No No lockwait Total wait time (in milliseconds) for locks in the last second. int No No averagewait Average amount of wait time (in milliseconds) for each lock request that resulted in a wait. int No No pagesplits Number of page splits per second that occur as the result of overflowing index pages. float(delta) No No cachehit Ratio between cache hits and lookups. int No No sqlcompilations Number of compilations per second. Indicates the number of times the compile code path is entered. Includes compiles caused by statement-level recompilations in SQL Server. After SQL Server user activity is stable, this value reaches a steady state. float(delta) No No batchreq Number of Transact-SQL command batches received per second. This statistic is affected by all constraints (such as I/O, number of users, cache size, complexity of requests, and so on). High batch requests mean good throughput. float(delta) No No fullscans Number of unrestricted full scans per second. These can be either base-table or full-index scans. float(delta) No No pagelife Number of seconds a page will stay in the buffer pool without references. float No No time2connect Time to connecto to the database. float No No
- Database controls
On these controls, the function checks if everydatabase (or the one specified by db_name parameter) has the property to check below the value given by threshold* parameter.
Modes Description Threshold DB_name transpec Number of transactions started for the database per second. Returns 1 if all trans/sec are below the given threshold, 0 + list of databases with excess of trans/sec in execution info otherwise. Yes Yes db-free Free storage percentage per database file groups. Returns 1 if all percenteges are below the given threshold, 0 + list of saturated file groups in execution info otherwise. Yes Yes databaseonline Online databases. Returns 1 if all databases are online, 0 + list of databases with state != ONLINE in execution info otherwise. No Yes time2connect Time to connecto to the database. No Yes connections Number of open connections to MS SQL server. No Yes Output
Output changes depending on the specified mode.Errors
- If an invalide mode is passed to mssql_check, a PollException is raised.
- If, on checks that requires it, threshold value is not specified a PollException is raised.
- Some checks need a former value to compute their result. If it’s the first time this kind of check is performed, and so a former value is not present, a PollException is rised in order to allow the computation to continue flawlessly. The second time the check is performed, everything should be fine.
Examples
Expression Description Return string value mssql_check(username=”sanet”, password=”sanet”, mode=”time2connect”) Returns time spent to connect to the server. 0.0164229869843 mssql_check(username=”sanet”, password=”sanet”, mode=”db-free”, threshold=30) Check if all the databases on MS SQL Server have free space over 30%. 1 if they have mssql_check(username=”sanet”, password=”sanet”, mode=”db-free”, threshold=30, instance=”tempdb”) Check if database tempdb on MS SQL Server has free space over 30%. 1 if they have mssql_check(username=”sanet”, password=”sanet”, mode=”databaseonline”) Check if all the databases on MS SQL Server are online. 1 if they are online mssql_check(username=”sanet”, password=”sanet”, mode=”databaseonline”, instance=”tempdb”) Check if database tempdb on MS SQL Server is online. 1 if they are online
4.2.9. Services¶
4.2.9.1. SANET Service utils¶
4.2.9.1.1. Ping & RTT¶
4.2.9.1.1.1. getICMPStat¶
Syntax
isServiceRunning ( )Description
Returns true if the value of swRunIndex for the current service can be calculated.Input
NoneOutput
Returns a boolean.Errors
An exception is raised when if swRunIndex can not be calculated*.Examples
Expression Description Return string value isServiceRunning() true
4.2.10. Web Scenarios¶
4.2.10.1. execWebScenario¶
Syntax
execWebScenario ( name [, ssl_version ] )Description
Retrieves from Sanet configuration the configuration of the given webscenario and tries to execute it.
Returns a dictionary containing the following keys:
- status : 1 Ok, 2 Error, 0 Unknown
- totaltime : Total execution time in seconds
SSL Version
These are the valid values for the ssl_version parameter:
- “SSLv2”
- “SSLv3”
- “TLSv1”
Macro expansion
Macros string (es. {{name*}} ) used inside steps’ URL or POST VARS will be expanded also with $*name* parameters taken from the execution context (es. datagroup parameters, $node, ecc.)Input
- name: the name of the web scenario
- ssl_version: (optinal) The SSL version to use.
Output
Returns a dictionaryErrors
Raise an exception if an unknown error occursExamples
Expression Return value Description execWebScenario(“testwebapp”)[“status”] 1 execWebScenario(“testwebapp”)[“totaltime”] 0.141 execWebScenario(“testwebapp”, ssl_version=”SSLv3”)[“totaltime”] 0.141 Force SSLv3
4.2.11. Sanet internal Monitoring¶
4.2.11.1. Monitoraggio condition¶
4.2.11.1.1. isUp¶
Syntax
isUp ( identity string [ , uncheckable_fallback )Description
The parameter identity string can be:
- A condition path.
- A classification. The condition is searched inside the node related to the datagroup executing the expression. If more than one conditions if found, it’s choosed randomly.
Returns true if the condition path is UP. Returns false if the condition is FAILING or DOWN.
If uncheckable_fallback is not specifided, raises an exception if the condition status is UNCHECKABLE or SUSPENDED
When uncheckable_fallback is specified and it is ‘UP’, if condition’s status is UNCHECKABLE or SUSPENDED, return True. When uncheckable_fallback is specified and it is ‘DN’, if condition’s status is UNCHECKABLE or SUSPENDED, return False.
If the condition’s status can not be calculated, the functions raises and exception.
Input
- path: the full path or classification of the condition
- uncheckable_fallback: (string). Valid values are ‘UP’, ‘DN’
Outpu
Returns a boolean.Errors
Raise an exceptions and become uncheckable when the given condition is not found or when uncheckable_fallback is not specified and the condition’s status is not UP,DOWN,FA.Examples
Expression Return value isUp(“localhost;;dg;condition_up”) true isUp(“localhost;;dg;condition_down”) false isUp(“localhost;;xxx;xxx”) exception isUp(“localhost;;xxx;xxx”, uncheckable_fallback=”UP”) true isUp(“localhost;;xxx;xxx”, uncheckable_fallback=”DN”) false isUp(“system.interface.status”) false
4.2.11.1.2. UncheckableIfNotUp¶
Syntax
UncheckableIfNotUp ( path [ , … ] )Description
It turns uncheckable if any of the given transition is not “UP”.Input
- paths: path string
Outpu
Returns true if all conditions are UP. Uncheckable otherwise.Errors
If a condition does not exists, the expression goes uncheckable.Examples
Expression Return value UncheckableIfNotUp(“foo;;test”, “bar;;test”) true
4.2.11.2. Monitoraggio dei Tag¶
4.2.11.2.1. tagStatus¶
Syntax
tagStatus ( tagpath )Description
Return the status of the given tag.Input
- tagpath: the fullpath of the given tag (es: “geo:/Global vision/tag1/tag2”)
Outpu
Returns the status code of the given tag. (es. “UP”)Errors
The expression goes uncheckable if the tag is not found.Examples
Expression Description tagStatus(“geo:/Global vision/tag1/tag2”) “UP”
4.2.11.3. Monitoraggio Datasource¶
4.2.11.3.1. measureAvgInInterval¶
Syntax
measureAvgInInterval ( path , interval )Description
Calculate the average value of the given datasource path in the last interval (in seconds).Input
- path: datasource path
- interval: time interval in seconds.
Outpu
Numeric valueErrors
The expression goes down if the datasourse does not exits.Examples
Expression Description measureAvgInInterval(“localhost;;icmp-reachability:lossperc”, 600)
4.2.11.3.2. pktLossAvgInInterval¶
Syntax
pktLossAvgInInterval ( interval [, discard_number ] [, discard_threshold ] [, node_name ] [, ds_name ] )Description
Return the average packet loss of the node related to the expression where this function is called. The value is calculate in the last interval seconds.Input
- interval: time range in seconds.
- discard_number: Max number of NaN entries ignored when calculating the average.
- discard_threshold: Values under this threshold are ignored.
- node_name: Node name (optional)
- ds_name: packetloss datasource name. Default is lossperc.
Outpu
Numeric valueErrors
It goes uncheckable if the function can not find useful data to fetch.Examples
Expression Description pktLossAvgInInterval(600) 0.004
4.2.11.3.3. pktLossAvgAndVarInInterval¶
Syntax
pktLossAvgAndVarInInterval ( interval [, discard_number ] [, discard_threshold ] [, node_name ] [, ds_name ] )Description
The function behaves in the same way of pktLossAvgAndVarInInterval() but returns a tuple with two values:
average , varianceInput
See pktLossAvgAndVarInInterval()Outpu
A tuple with two floating point values.Errors
See pktLossAvgAndVarInInterval()Examples
Expression Description pktLossAvgAndVarInInterval(600)[0] 0.004 pktLossAvgAndVarInInterval(600)[1] 0.34512
4.2.11.3.4. getConditionStatusTotalTime¶
Syntax
getConditionStatusTotalTime ( [ path ] [, time_range] [, down_states] [, perc] )Description
Returns the total down time of a particular condition with the given path
If path is not specified, the primary condition of the monitored element is selected.
The default timerange is the last 24H. You can specify the differente time range in seconds.
If perc is true or a positive interge, the percentage value is returned instead of seconds.
Input
- path : (optional) the path of the selected condition.
- time_range: (optional) Time range in seconds.
- down_state: (optional) Sommand-separated-value string of the down states (es: “DN,FA,UD”).
- perc : (optional) Boolean
Outpu
Numeric valueErrors
It goes uncheckable if the function can not find useful data to fetch.Examples
Expression Description getConditionStatusTotalTime() 123123 getConditionStatusTotalTime(time_range=60*60*24*20, down_states=”FA,DN”) 123123
4.2.11.3.5. DataSourceAvgInInterval¶
Syntax
DataSourceAvgInInterval ( classification [ , interval ] [ , discard_high_threshold ] [ , discard_high_max_number ] [ , null_max_number ] )Description
Calculate the average value of the datasource, with the given classification in the last interval seconds.
Important
The datasource is selected among the datasources of the current monitored element at execution time. If not found, it’s selected among the current parent node.
The maximum allowed value for interval is MAX_INTERVAL (one hour). An exception is raised if interval is above MAX_INTERVAL.
If null_max_number is specified, the function raise an exception when the number of null values in the datasource series is above null_max_number.
If discard_high_threshold is specified, datasource values above this threshold will be ignored for the average computation. If discard_high_max_number is specified, the number of ignored values will be at most discard_high_threshold.
Input
- classification: datasource classification.
- interval : time interval in seconds.
- discard_high_threshold: number
- discard_high_max_number: number
- null_max_number: number
Outpu
Numeric valueErrors
The function raise an exception if an error occurs.Examples
Expression Description DataSourceAvgInInterval(‘network.interface.traffic.in’) DataSourceAvgInInterval(‘network.interface.traffic.in’, interval=180) DataSourceAvgInInterval(‘network.interface.traffic.in’, interval=180, null_max_number=20)
4.2.11.3.6. DataSourceAvgAndVarInInterval¶
Syntax
DataSourceAvgAndVarInInterval ( classification [ , interval ] [ , discard_high_threshold ] [ , discard_high_max_number ] [ , null_max_number ] )Description
The function behaves in the same way of DataSourceAvgInInterval() but returns a tuple with:
average , varianceInput
See DataSourceAvgAndVarInInterval().Outpu
A tuple with two floating point values.Errors
See DataSourceAvgAndVarInInterval().Examples
Expression Description DataSourceAvgAndVarInInterval(‘network.interface.traffic.in’)[0] average value DataSourceAvgAndVarInInterval(‘network.interface.traffic.in’)[1] variance value
4.2.12. Execution utilities¶
4.2.12.1. Execution values¶
4.2.12.1.1. saveval¶
Syntax
saveval ( name, value )Description
Save the value value with the name name. Returns value. The value of name will be available the next time the expression is evaluated. See getlastval.Input
- name: string
- value: any value
Outpu
Returns the value of value.Errors
NoneExamples
Expression Return value Description saveval(“x”, 1) 1 Stores 1 in the internal state for the next execution saveval(“x”, walkCount(1.3.6.1.2.1.1.1.@) The value of the walkCount() Packet loss average in the last 180 seconds. saveval(“x”, ….) - getlastval(“x”) < $delta true or false Compare the current value of “x” with the last.
4.2.12.1.2. getlastval¶
Syntax
getlastval ( name )Description
Returns the value of name saved at the last execution time by the function saveval() (See: :ref’:saveval.)Input
- name: string
Outpu
Any valueErrors
Raise exception in there is no value for the given variable name.Examples
Expression Return value Description getlastval(“x”) a value The the last value of “x”. saveval(“x”, ….) - getlastval(“x”) < $delta true or false Compare the current value of “x” with the last.
4.2.12.2. Test functions¶
4.2.12.2.1. iftrue¶
Syntax
iftrue ( test, val1, val2 )Description
Returns val1 if the boolean value of test is true. Returns val2 otherwise.Input
- test: a value
- val1: a value
- val2: a value
Outpu
Any valueErrors
NoneExamples
Expression Return value Description iftrue(1, “yes”, “no”) “yes” iftrue(0, “yes”, “no”) “no”
4.2.12.2.2. onlyif¶
Syntax
onlyif ( test_val, val [ , uncheck_msg ] )Description
Returns val1 if the boolean value of test_val is true. Raise an exception otherwise.Input
- test_val: value (boolean)
- val: a value
- uncheck_msg: error message. (optional)
Outpu
The value val.Errors
Raise an exception (with optional message uncheck_msg).Examples
Expression Return value Description onlyif(true, 1) 1 onlyif(false, 2) exception onlyif(false, 2, “error message”) exception: error message
4.2.12.2.3. test_symbol¶
Syntax
test_symbol ( name )Description
Tests if the symbol with name name exists or can be calculated (es. $ifindex, $cluster_instance, ecc.) in the current execution context.Input
- name: string
Outpu
true or falseErrors
NoneExamples
Expression Return value Description test_symbol(“$ifindex”) true test_symbol(“$_xyz_ “) false
4.2.12.2.4. test_state¶
Syntax
test_state ( statename )Description
Returns true if statename is “UP”. Returns false if statename is “DN” or “FA* or “IN”. Raise an exception otherwise.Input
- name: a valid status code.
Output
A boolean value.Errors
NoneExamples
Expression Return value Description test_state(“UP”) true test_state(“FA”) false test_state(“UN”) exception
4.2.13. Encoding functions¶
4.2.13.1. JSON Functions¶
4.2.13.1.1. loadjson¶
Syntax
loadjson ( string )Description
Parse the JSON string string and returns the memory objects.Input
- string: JSON string.
Output
Return any valid value loaded from the string.Errors
Raise an exception if the input string is not a valid JSON data.Examples
Expression Description Return string value loadjson(‘{ “hello”: “world” }’)[‘hello’] Convert the JSON string ‘{ “hello”: “world” }’ “world” loadjson( readFile(“/tmp/data.json”)[‘hello’] Read JSON data from file ( ‘{ “hello”: “world” }’ ) “world”
4.2.14. Debug¶
4.2.14.1. test¶
Syntax
test()Description
It always returns 0.Input
NoneOutpu
Returns 0.Errors
NoneExamples
Expression Return value Description test() 0
4.2.14.2. pollerror¶
Syntax
pollerror()Description
Always raises an execution exception and the current expression goes uncheckable.
NOTE: used only for debug purpose.
Input
NoneOutpu
Returns 0.Errors
Raise andExamples
Expression Return value Description pollerror() exception
4.2.14.3. unknownerror¶
Syntax
unknownerror()Description
Always raises an unspecified exception.
NOTE: used only for debug purpose.
Input
NoneOutpu
Returns 0.Errors
Raise andExamples
Expression Return value Description pollerror() exception