4.2. SANET standard expression functions¶
4.2.1. Core¶
4.2.1.1. Basic functions¶
4.2.1.1.1. str()¶
Syntax
str ( arg )
Description
Tries to converts the input value arg to is string rappresentation.
If args is a unicode string value or bytes array value, it's returned as is.
Input
args: any type.
Output
Returns a unicode string or byte array.
Errors
If the input parameter can not be converted to a valid string the expression evaluation fails.
Examples
Expression
Value
Description
str(0x0A)
'10'
unicode string ( The hexadecimal literal 0x0A is equivalente to the literal 10)
str(10)
'10'
unicode string
str(1)
'1'
unicode string
str(1.0)
'1.0'
unicode string
str(bool(1))
'True'
unicode string
str(bool(0))
'False'
unicode string
str("foo")
'foo'
The liteal "foo" is converted to unicode and returned as is
str(encode("foo"))
b'foo'
3 bytes (the value returned by encode() is a UTF8 byte sequence)
str(encode("foo"), "ascii")
b'foo'
3 bytes (the value returned by encode() is a ASCII byte sequence)
str(encode("foo"), "iso-8859-1"))
b'foo'
3 bytes (the value returned by encode() is a ISO-8859-1 byte sequence)
str(encode("foo"), "utf8")
b'foo'
3 bytes (the value returned by encode() is a UTF8 byte sequence)
str("città")
'città'
unicode string. 5 characters
str(encode("città"))
b'Citt\xc3\xa0'
6 byte string (the value returned by encode() is a UTF8 byte sequence)
str(encode("città", "iso-8859-1"))
b'Citt\xe0'
5 byte string (the value returned by encode() is a ISO-8859-1 byte sequence)
str(list(1, 3.14, "a"))
'[1, 3.14, "a"]'
String rappresentation of the list [1, 3.14, "a"]
str(1.3.6.1.2.1.1.1.0@)
b'Linux ...'
The byte string OID value is returned as is
str(1.3.6.1.2.1.1.3.0@)
'15764311'
The integer OID value is converted to unicode string
4.2.1.1.2. int()¶
Syntax
int ( arg [ , base ] )
Description
Tries to converts the input value arg to an integer value.
If arg is already and interger value, arg is returned untouched.
It arg float value, the interger part is returned.
If arg is a unicode string value or an ascii string value, the function tries to convert the rappresented integer number to an interger value.
Input
args: any type
Output
Returns a string
Errors
If the input parameter can not be converted to a valid integer value the expression evaluation fails.
Examples
Expression
Value
Description
int(0xFF)
255
int(255)
255
int(1.33)
1
int("12345")
12345
unicode string "12345" converted to integer value 12345.
int(encode("12345"))
12345
encode() returns an ascii-byte string b"12345", then
int()
converts these bytes to value 12345.
int("foo")
ERROR
int(encode("foo"))
ERROR
Unable to convert 'foo' (<class 'str'>) to integer value.
int("\\n")
ERROR
Unable to convert \n (<class 'str'>) to integer value.
int(encode("\\n"))
ERROR
Unable to convert \n (<class 'str'>) to integer value.
int(list(1,2,3))
ERROR
U Unable to convert [1, 2, 3] to integer value.
int(1.3.6.1.2.1.1.3.0@)
15764311
The integer OID value is returned untouched
4.2.1.1.3. float()¶
Syntax
float ( arg )
Description
Tries to converts the input value arg to an floating point value.
Input
args: any value
Output
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
Description
float(0xff)
255.0
Number 255 (0xff) converted to 255.0 float value
float(1.33)
1.33
Float value 1.33 returned as is
float("123.45")
123.45
ASCII string converted literally to float value 12345.0
float("foo")
ERROR
ASCII string does not rappresent a valid number
float(1.3.6.1.2.1.1.3.0@)
15764311.0
The integer OID value is converted to float value
4.2.1.1.5. bool()¶
Syntax
bool ( arg )
Description
Tries to converts the input value arg to a boolean value (true or false)
If arg is an integer or float value and it's not zero, true is returned. false otherwise.
If arg is a unicode string or byte string and is not empty (zero length) string, true is returned, false otherwise.
Input
args: any value
Output
Returns a boolean value.
Errors
If the input parameter can not be converted to a valid floating point value the expression evaluation fails.
Examples
Expression
Value
Description
bool(0x0A)
True
Number 10 (0x0A) is not zero -> True
bool(0xff)
True
Number 255 (0xff) is not zero -> True
bool(1.33)
True
Float value 1.33 is not zero -> True
bool("aaaa")
True
ASCII string not empty -> True
bool("")
False
ASCII string is empty -> False
bool(encode(""))
False
UTF8 byte array is empty -> False
bool(1.3.6.1.2.1.1.3.0@)
True
The integer OID value is not Zero -> True
bool(1.3.6.1.2.1.1.1.0@)
True
The byte string OID value is not emtpy -> True
bool(decode(1.3.6.1.2.1.1.1.0@))
True
Unicode string (from byte string OID value) is not emtpy -> True
4.2.1.1.6. list() / array()¶
Syntax
list ( arg1 [ , ... ] )
array ( arg1 [ , ... ] )
Description
Takes a sequence of parameters and returns a list containg the given arguements.
Input
args: a sequence of arguments (any types)
Output
Returns a list
Errors
Raise an exceptions if the number of paramets is not even.
Examples
Expression
Value
Description
list(1,2,3)
[1, 2, 3]
list( 1.3.6.1.2.1.1.1.0@, "ciao")
[ 'Linux debian ....', 'ciao' ]
list( 1.3.6.1.2.1.1.1.0@, "ciao")[0]
'Linux debian ....'
list( 1.3.6.1.2.1.1.1.0@, "ciao")[1]
'ciao'
4.2.1.2. List and arrays¶
4.2.1.2.1. len()¶
Syntax
len ( arg )
Description
Return the number of sub elements of the given arg.
If arg is a unicode string, the number of unicode characters is returned.
If arg is a byte array, the number of bytes is returned.
If arg is a list, the length of the list is returned.
If arg is a dictionary, the number of keys is returned.
If arg is SNMP value (a lazy value), a WALK is performed and the number of returned OIDs is returned.
Input
args: any value.
Output
Returns a number.
Errors
Raise an exceptions if the argument is not compatibile with a list, an array, dict or SNMP value.
Examples
Expression
Value
Description
len("città")
5
len(encode("città"))
3 (byte array = b'Citt\xc3\xa0'
len(1.3.6.1.2.1.1.1.0@)
ERROR
WALK not allowed on 1.3.6.1.2.1.1.1.0
len(1.3.6.1.2.1.1.1@)
1
WALK on 1.3.6.1.2.1.1.1 has only .0 sub-OID
len(str(1.3.6.1.2.1.1.1.0@))
86
Bytes for 'Linux sanet3unstable-deb9 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+deb9u5 (2017-09-19) x86_64'
len(list(1,2,3))
3
Length of [1, 2, 3]
4.2.1.2.2. 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.3. Dictionaries¶
4.2.1.3.1. dict() / args2dict()¶
Syntax
dict ( key1 , value1 [ , key2 , value2 ... ] )
args2dict **( key1 , value1 [ , key2 , value2 ... ] )
dict ( list ) (special case)
dict ( name = value [ , ... ] ) (special case)
Description
Takes a sequence of parameters rappresenting key/value pairs, and created a dictionary object in memory.
The function args2dict() is an alias for the second version of dict()
If the number of arguments is one, it's treat like a list of (key, value) tuples.
Note
These expression are equivalent:
dict('a', 1, 'b', 2, 'c', 'foo') loadjson('{ "a": 1, "b": 2, "c": "foo" }')Input
args: a sequence of paired key / value options or a single list of tuples
Output
Returns a dictionary
Errors
Raise an exceptions if the number of paramets is not even.
Examples
Expression
Value
Description
dict("key1", 666)
{ "key1: 666 }
dict(key1=666, key2="foo")
{ "key1: 666, "key2"="foo" }
dict("key1", 666)["key1"]
666
dict("key1", 666, "foo", "bar")
{ "foo": "bar", "key1":666 }
dict( list(list("key1", 666), list("foo", "bar")) )
{ "foo": "bar", "key1":666 }
dict( 1.3.6.1.2.1.1.1@ )
{'.1.3.6.1.2.1.1.1.0': b'Linux.....' }
WALKs 1.3.6.1.2.1.1.1, and treats the tables as sequence of oid/value pair
dict( 1.3.6.1.2.1.1.1@ )[".1.3.6.1.2.1.1.1.0"]
b'Linux.....'
4.2.1.3.2. haskey¶
Syntax
haskey ( dict , key )
Description
Return true if key is contained in dict, false otherwise.
Input
dict: a dictionary object.
key: any value.
Output
Returns a boolean true or false.
Errors
Raise an exception when a conversion error is detected.
Examples
Expression
Value
Description
getkey( loadjson('{ "key1": "a" }'), 'key1' )
True
getkey( loadjson('{ "key1": "a" }'), 'xxx' )
False
4.2.1.3.3. getkey¶
Syntax
getkey ( dict , key [ , default ] )
Description
Return the value of key inside dict. If key is not inside dict, and optional parameter default is specified, the value default is returned. Otherwise None is returned.
Input
dict: a dictionary object
key: any value
default: (optional) any value
Output
Returns any value.
Errors
Raise an exception when a conversion error is detected.
Examples
Expression
Value
Description
getkey( loadjson('{ "key1": "a" }'), 'key1' )
"a"
getkey( loadjson('{ "key1": "a" }'), 'key2' )
exception
getkey( loadjson('{ "key1": "a" }'), 'key2', 666 )
666
4.2.1.4. Sets¶
4.2.1.4.1. set() / list2set()¶
Syntax
set ( arg1 [ , arg2 ... ] )
list2set **( list )
Description
Takes a sequence of arguments arg1, arg2, ecc. and return a set object created with the given arguments.
The function
list2set()
is likeset()
but takes a single parameter as a list of values.Input
A sequence of arguments or a single list of values
Output
Returns a set
Errors
Raise an exceptions if the number of paramets is not even.
Examples
Expression
Value
Description
set(1,2,3)
{ 1, 2, 3, }
set( list(1,2,3) )
{ 1, 2, 3, }
set( 1.3.6.1.2.1.1.3.0, 'a', 'b' )
{ 'a', 'b', 142291587 }
4.2.1.5. Symbols functions¶
4.2.1.5.1. ENVIRONMENT()¶
Syntax
ENVIRONMENT ( name )
Description
Return the string value of the given environement variable.
Input
name : unicode string.
Output
A unicode string
Examples
Expression
Return value
Description
isDefined("$ifindex")
true
Tells if $ifindex can be calculated and used inside the espression.
4.2.1.5.2. isDefined()¶
Syntax
isDefined ( varname [ , catch_timeouts ] )
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. If catch_timeouts is true the function do not intercept TimeoutException errors.
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
Return value
Description
isDefined("$ifindex")
true
Tells if $ifindex can be calculated and used inside the espression.
isDefined("$ifindex", catch_timeouts=1)
EXCEPTION
When the $ifindex can not be calculated because SNMP agent is not responding
4.2.1.5.3. ifDefined()¶
Syntax
isDefined ( varname , default_value [ , catch_timeouts ] )
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.
If catch_timeouts is true the function do not intercept TimeoutException errors.
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 : (string) symbol name.
default_value: (any type) any value.
Output
Return a valid expression value.
Examples
Expression
Return value
Description
ifDefined("$ifindex", -1)
12
Returns the value of the simbol $ifindex
ifDefined("$ifindex", -1)
-1 ($ifindex is not defined
Returns the value of the simbol $ifindex
ifDefined("$ifindex", -1, catch_exceptions=1)
EXCEPTIONS
When the $ifindex can not be calculated because SNMP agent is not responding.
4.2.2. Encoding¶
4.2.2.1. Encoding / Decoding¶
4.2.2.1.1. encode¶
Syntax
encode ( string [ , encoding ] )
Description
Tries to convert the unicode string to a byte buffer using the given encoding.
This is the inverse of decode.
Input
string : (unicode string) a string. encoding: (unicode string) encoding name (utf8, iso-8859-1, ascii, ecc.)
Output
Returns a bytes buffer.
Errors
If the input parameter can not be converted to a valid bytes buffer the expression evaluation fails.
Examples
Expression
Return string value
Description
encode('citta')
b'citta'
5 bytes
encode('citta', 'ascii')
b'citta'
5 bytes
encode('citta', 'utf8')
b'citta'
5 bytes
encode('citta', 'iso-8859-1')
b'citta'
5 bytes
encode('Paläozoikum')
b'Pal\xc3\xa4ozoikum'
12 bytes
encode('Paläozoikum', 'ascii')
ERROR
Raised exception
encode('Paläozoikum')
b'Pal\xc3\xa4ozoikum'
12 bytes
encode('Paläozoikum', 'iso-8859-1')
b'Pal\xe4ozoikum'
11 bytes
4.2.2.1.2. decode¶
Syntax
decode ( bytes [ , encoding ] )
Description
Tries to convert input bytes to Unicode string using the given encoding. Default is: 'utf8'.
This is the inverse of encode.
Input
bytes : (bytes) a buffer of bytes. encoding: (unicode string) encoding name (utf8, iso-8859-1, ascii, ecc.)
Output
Returns a Unicode string.
Errors
If the input parameter can not be converted to a valid Unicode string the expression evaluation fails.
Examples
Expression
Return string value
Description
decode(encode('citta'))
'citta'
(Ascii-compatible) Returned Unicode string (5 characters)
decode(encode('citta', 'ascii'))
'citta'
idem
decode(encode('citta', 'ascii'), 'utf8')
'citta'
idem
decode(encode('citta'), 'utf8')
'citta'
idem
decode(encode("città", "iso-8859-1"), "iso-8859-1")
'città'
decode(encode("città", "iso-8859-1"), "utf8")
ERROR
The encoded bytes ( b'citt\xe0' ) is not compatibile with utf8
decode(1.3.6.1.2.1.2.2.1.2.3@, "ascii")
'lxcbr0'
Warning: don't cross the streams, don't mix different encodings:
Expression
Return string value
Description
decode(encode("città", "utf8") , "iso-8859-1" )
'cittÃ\xa0'
The encoded bytes ( b'citt\xc3\xa0' ) are decoded with strange results.
Other infos:
OIDs return strings as bytes:
1.3.6.1.2.1.2.2.1.2.3@ --> b'lxcbr0'If you want OIDs strings as unicode strings you have to decode them:
decode(1.3.6.1.2.1.2.2.1.2.3@, "ascii") --> 'lxcbr0'Note
More infos about bytes strings and unicode strings: Unicode String and Byte strings (arrays)
4.2.3. String Handling¶
4.2.3.1. String functions¶
These functions are intended for manipulating unicode strings or bytes.
Some of these functions works also with other types (such as integer, float or list) for backwards compatibility, but that usage is deprecated and a warning message will be issued if used.
For example (see strpos for the function used in this example):
* strpos( 1234567890, "4" ) --> 3.
This works (with a warning) because it implicitly converts the number into a unicode string and finds where the string "4" is in the string.
For managing this case correctly you should convert explicitly the number into a string: strpos( str(1234567890), "4" )
* strpos( list(1,2,3,4), 4 ) --> 10.
This works (with a warning) because it implicitly converts the list into the unicode string "[1, 2, 3, 4]" and finds where the string "4" is in the string.
This usage can lead to an unexpected result and should be avoided.
4.2.3.1.1. strlen¶
Syntax
strlen ( data )
Description
Return the lenght of the given unicode string or bytes.
Input
data: a unicode string or bytes
Output
Returns an integer value.
Errors
Examples
Expression
Return value
Description
strlen("foo")
3
3 is the length of the unicode string passed
strlen( 1.3.6.1.2.1.2.2.1.2.2@ )
53
53 is the length of the bytes returned by the oid
4.2.3.1.2. strrep¶
Syntax
strrep ( str_orig, str_pattern , str_rep )
Description
Replaces the string or bytes str_pattern with str_rep inside str_orig, and returns the result string or bytes.
If at least one of the input parameters is bytes, all other input parameters (which are not bytes) must be ascii unicode string. Returns a unicode string when all input parameters are unicode string and returns bytes when at least one of the input parameters is bytes.
Input
str_orig : unicode string or bytes
str_pattern: unicode string or bytes
str_rep : unicode string or bytes
Output
Returns a string or bytes. (See description)
Errors
Examples
Expression
Return value
Description
strrep("123", "2", "B")
'1B3'
returns a unicode string
strrep(1.3.6.1.2.1.2.2.1.2.3@, "0", "666")
b'lxcbr666'
returns 8 bytes
strrep(1.3.6.1.2.1.2.2.1.2.3@, "0", "à")
ERROR
strrep not allowed between bytes and non-ascii unicode string ('à')
strrep(1.3.6.1.2.1.2.2.1.2.3@, "0", encode("à"))
b'lxcbr\xc3\xa0'
4.2.3.1.3. strpos¶
Syntax
strpos ( str1 , str2 ** ] )**
Description
Returns the position of str2 inside str1. The first valid position is 0. If at least one of the input parameters is bytes, all other input parameters (which are not bytes) must be ascii unicode string.
Input
str1: unicode string or bytes
str2: unicode string or bytes
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
strpos(1.3.6.1.2.1.2.2.1.2.3@, "xc")
1
strpos(1.3.6.1.2.1.2.2.1.2.3@, "tà")
ERROR
strpos not allowed between bytes and non-ascii unicode string ('tà')
strpos(1.3.6.1.2.1.2.2.1.2.2@, encode("tà"))
1
4.2.3.1.4. strsub¶
Syntax
strsub ( str1 [ , startpos ] [ , endpos )
Description
Returns a slice of the given unicode string or bytes which starts at startpos and ends at endpos
Input
str : unicode string or bytes
startpos : integer
endpos : integer
Output
Returns a unicode string or bytes.
Errors
Examples
Expression
Return value
Description
strsub("lxcbr0", 1, 4)
'xcb'
returns a unicode string
strsub(1.3.6.1.2.1.2.2.1.2.3@, 1, 4)
b'xcb'
returns 3 bytes
4.2.3.1.5. strsplit¶
Syntax
strsplit ( str1 [, splitchar ] [, count ])**
Description
Splits str1 in tokens. The split unicode string or bytes used is spitchar (default is whitespace " "). The max number of splits is given by count.
Input
str1 : unicode string or bytes
splitchar : unicode string or bytes
count : integer
Output
Returns a vector of unicode strings or a vector of bytes.
Errors
Examples
Expression
Return value
Description
strsplit("a b c")
["a", "b", "c"]
strsplit("a b c", count=1)
["a", "bc"]
strsplit(1.3.6.1.2.1.2.2.1.2.3@, "x")
[b'l', b'cbr0']
strsplit(1.3.6.1.2.1.2.2.1.2.2@, "à")
ERROR
strsplit not allowed between bytes and non-ascii unicode string ('à')
strsplit(1.3.6.1.2.1.2.2.1.2.2@, encode("à")) | [b'ex', b'ample']
4.2.3.1.6. strstrip¶
Syntax
strstrip ( data )
Description
Remove whitespaces (newline, whitespace, tabs, ecc...) from the head and the tail of the given unicode string or bytes.
Input
data: unicode string or bytes
Output
Returns an unicode string or bytes
Errors
Examples
Expression
Return value
Description
strstrip(" hello ")
'hello'
unicode string returned
strstrip(encode(" hello "))
b'hello'
bytes returned
4.2.3.1.7. strjoin¶
Syntax
strjoin ( data [, join_char ] )
Description
Returns a unicode string or bytes 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 or bytes values)
Output
Returns an unicode string or bytes
Errors
An error is raised if data is not suitable to join.
Examples
Expression | Return value
Description
strjoin( array(1,2,3) ) | "1 2 3"
Returns a unicode string
strjoin( array(1,2,3) , "#") | "1#2#3"
Returns a unicode string
strjoin( array(1.3.6.1.2.1.2.2.1.2.3@,1.3.6.1.2.1.2.2.1.2.2@), "#" ) | b'lxcbr0#example'
Returns bytes
4.2.3.1.8. head¶
Syntax
head ( data , num )
Description
Return a vector containing the first num lines of the given multi-line data unicode string or bytes.
Input
data: multi-line unicode string or bytes.
num: integer.
Output
Returns a unicode string or bytes with the first num lines.
Errors
TODO
Examples
Expression
Return value
Description
head("line1nline2nline3nline4", 2)
"line1nline2"
head("line1nline2nline3nline4", 1)
"line1"
head(encode("line1nline2nline3nline4"), 2)
b'line1nline2'
_
4.2.3.1.9. tail¶
Syntax
tail ( data , num )
Description
Return a vector containing the last num lines of the given multi-line data unicode string or bytes.
Input
data: multi-line unicode string or bytes
num: integer
Output
Returns a unicode string or byte with the first num + 1 lines.
Errors
An exception is raised when an error on input parameters is detected.
Examples
Expression
Return value
Description
tail("line1nline2nline3nline4, 1)
"line3nline4"
tail("line1nline2nline3nline4, 0)
"line4"
tail(encode("line1nline2nline3nline4), 1)
b'line3nline4'
4.2.3.1.10. lower¶
Syntax
lower ( s )
Description
Converts all uppercase characters in a unicode string or bytes into lowercase characters and returns it.
Input
s: unicode string or bytes
Output
Returns an unicode string or bytes
Errors
An error is raised if s is not suitable to the conversion.
Examples
Expression
Return value
Description
lower( "HELLO" )
"hello"
lower( encode("HELLO") )
b'hello'
lower( 1.3.6.1.2.1.2.2.1.2.5 )
b'example'
4.2.3.1.11. upper¶
Syntax
upper ( s )
Description
Converts all uppercase characters in a string into uppercase characters and returns it.
Input
s: string of characters
Output
Returns an string
Errors
An error is raised if s is not suitable to the conversion.
Examples
Expression
Return value
Description
upper( "hello" )
"HELLO"
upper( encode("HELLO") )
b'HELLO'
upper( 1.3.6.1.2.1.2.2.1.2.5 )
b'EXAMPLE'
4.2.3.2. Hexadeciaml / Binary utilities¶
4.2.3.2.1. hex()¶
Syntax
hex ( byte string ) bin2hexstr ( byte string )
Description
Converts the input parameter bytes into it's UPPERCASE hexadecimal string rappresentation.
Input
bytes: a sequence of bytes.
Output
Returns a unicode string.
Errors
If the input parameter can not be converted to a valid string the expression evaluation fails.
Examples
Expression
Return value
Description
hex(1.3.6.1.2.1.2.2.1.6.2@"mason")
'01279AF7A4D'
Converts into a string the MAC address of the interface with ifindex 2
hex("Città")
ERROR
Input unicode string is not a sequence of bytes.
hex(encode("Città"))
'43697474C3A0'
hex(encode("Città", 'iso-8859-1'))
'43697474E0'
4.2.3.2.2. 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
Return value
Description
hexstr2bin('68656c6c6f')
b'hello'
bytes for hello
hexstr2bin( hex( encode("Città") ) )
b'Citt\xc3\xa0'
bytes for Città with uf8 encoding
decode( hexstr2bin( hex( encode("Città") ) )
'Città'
Unicode string
4.2.3.3. Number conversions¶
4.2.3.3.1. str2number()¶
Syntax
str2number ( string )
Description
Converts the string of characters in the corresponding number rappresentation.
Input
string: a string of ascii characters.
Output
Returns a number.
Errors
Raise an exception when a conversion error is detected.
Examples
Expression
Value
Description
str2number('10.5k')
10500.0
4.2.3.3.2. str2numbers()¶
TODO
4.2.4. Time functions¶
4.2.4.1. Time functions¶
4.2.4.1.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 value
Description
time()
1291971078.92
Executed at 17:35 (local time)
4.2.4.1.2. ts2str()¶
Syntax
ts2str ( ts , format , [ tz ] )
Description
Return the LOCAL date string version of the Unix Timestamp ts, according to the tz timezone parameter. If tz is not specified the server local time zone is used.
The format string format uses the wildcard of the python function datetime.strftime().
Default is: '%Y-%m-%d %H:%M:%S %z'.
Output
Returns a string.
Examples
Expression
Return string value
Description
ts2str( time() , "%Y-%m")
2020-06
Executed at 17:35 (local time)
ts2str( time() , "%Y-%m-%d %H:%M:%S")
2020-06-04 17:35:08
Executed at 17:35 (local time)
ts2str( time() , "%Y-%m-%d %H:%M:%S %Z")
2020-06-04 17:35:08 +02
Executed at 17:35 (local time)
ts2str( 1588284000 )
"2020-05-01 00:00:00+02:00"
2020-04-30T22:00+00:00
ts2str( 1588284000 , tz="UTC")
"2020-04-30 22:00:00+0000"
2020-04-30T22:00+00:00
ts2str( 1588284000 , "%Y-%m")
"2020-05"
2020-04-30T22:00+00:00
ts2str( 1588284000 , "%Y-%m", tz="UTC")
"2020-04"
2020-04-30T22:00+00:00
ts2str( 1588284000, tz="Europe/Dublin" )
"2020-04-30 23:00:00+0100"
ts2str( 1588284000, "%Y-%m-%d", tz="UTC" )
"2020-04-30"
2020-04-30T22:00+00:00
4.2.4.1.3. str2ts()¶
Syntax
str2ts ( str [ , format_s ] [ , tz ] )
Description
Return the Unix Timestamp corresponding to the given date str.
If str do not contains timezone informations, you can specify the timezone with the parameter tz.
When no timezone is specified, the system timezone is used for the conversion.
** Format **
The format string format_s uses the wildcard of the Pytho strftime() https://docs.python.org/3.9/library/datetime.html#strftime-and-strptime-format-codes.
If a format string is not specified, these formats are tries before raise an exception
%Y-%m-%d %H:%M:%S 2019-10-11 00:10:00 <-- no timezone %Y-%m-%d %H:%M:%S%z 2022-01-01 23:42:00+01:00 <-- with timezoneOutput
Returns an integer value
Examples
Expression
Return string value
UTC time ISO
Note
str2ts( "2020-05-01 00:00:00")
1588284000
2020-04-30T23:00+00:00
Note: system timezone is CET and Daylight Saving Time (DST) is ACTIVE
str2ts( "2020-05-01 00:00:00", tz="CET")
1588284000
2020-04-30T23:00+00:00
Note: with CET the Daylight Saving Time (DST) is ACTIVE
str2ts( "2020-05-01 00:00:00+01:00")
1588287600
2020-04-30T23:00+00:00
str2ts( "2020-12-01 00:00:00")
1606777200
2020-11-30T23:00+00:00
Note: system timezone is CET and Daylight Saving Time (DST) is ACTIVE
str2ts( "2020-12-01 00:00:00", tz="CET")
1606777200
2020-11-30T23:00+00:00
Note: with CET the Daylight Saving Time (DST) is ACTIVE
str2ts( "2020-12-01 00:00:00+01:00")
1606777200
2020-11-30T23:00+00:00
str2ts( "2020-05-01 00:00:00", tz="Etc/GMT-1")
1588287600
2020-04-30T23:00+00:00
For Etc/GMT-1 there is no Daylight Saving Time (DST)
str2ts( "2020-12-01 00:00:00", tz="Etc/GMT-1")
1606777200
2020-11-30T23:00+00:00
For Etc/GMT-1 there is no Daylight Saving Time (DST)
str2ts( "2020-05-01T00:00:00+01:00", "%Y-%m-%dT%H:%M:%S%z")
1588287600
2020-04-30T23:00+00:00
For Etc/GMT-1 there is no Daylight Saving Time (DST)
str2ts( "2020-05-01T00:00:00+01:00", "%Y-%m-%dT%H:%M:%S%z")
1606777200
2020-12-01T00:00+01:00
For Etc/GMT-1 there is no Daylight Saving Time (DST)
4.2.4.1.4. UTCOffset()¶
Syntax
UTCOffset ( [ timezone_name ] )
Description
Returns the offset in seconds of the given timezone_name (string or ASCII).
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 seconds
Errors
Raise an exception if the input timezone is not valid.
Examples
Expression
Value
Description
UTCOffset() / 3600
1
Offset of local timezone (Europe/Rome) when Daylight Saving Time (DST) is NOT active. (+01:00)
UTCOffset() / 3600
2
Offset of local timezone (Europe/Rome) when Daylight Saving Time (DST) IS active. (+02:00)
UTCOffset('America/Chicago') / 3600
-6
Offset when Daylight Saving Time (DST) is NOT active. (es: 6 Nov )
UTCOffset('America/Chicago') / 3600
-5
Offset when Daylight Saving Time (DST) is ACTIVE. (es: 1 Oct )
4.2.4.1.5. create_dateandtime()¶
Syntax
create_dateandtime ( year , month , day , hour , minutes , seconds , deci_seconds [ , utc_dir , utc_hours , utc_minutes ] )
Description
Create a dateandtime byte array 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.4.1.6. 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.4.1.7. 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 not
Examples
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.4.1.8. createTimerange()¶
Syntax
createTimerange ( ts_start , ts_end [ , day_range )
Description
Return a "time range" string "HH:SS-HH:SS/1-7". The "hour" interval is set in order to match the given ts_start and ts_end timestamps.
If ts_end is not specified, the current time is used.
If ts_start is not specified, ts_start is set to ts_end minus one minute.
If ts_start is a negative number, ts_start is calculated by subtracting the corresponding number of seconds from ts_end.
- The parameter day_range is optional and specifies the days of the week to consider. The format can be:
<day start>-<day-end>. Example: "1-7" (from monday to sunday), "6-6" (only saturday)
"today": the current day of the week (at the moment of the execution ).
Output
Returns a "time range" unicode string.
Examples
Expression
Return string value
Note
createTimerange()
17:39-17:40/1-7
NOW is 17:40
createTimerange(ts_start=-3600)
16:40-17:40/1-7
NOW is 17:40
createTimerange(ts_start=-60, ts_end=time()-180)
17:43-17:44/1-7
NOW is 17:47
createTimerange(ts_start=-60, ts_end=time()-180, day_range="today")
17:43-17:44/1-1
NOW is 17:47 (of all Mondays)
4.2.5. Math and logic¶
4.2.5.1. Math functions¶
4.2.5.1.1. abs¶
Syntax
abs ( arg )
Description
Returns the absolute value of the given argument.
Input
args: number
Output
Returns a number
Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.
Examples
Expression
Value
Description
abs(1)
1
abs(-1)
1
4.2.5.1.2. min¶
Syntax
min ( arg )
Description
Returns the minimum value.
Input
args: a single list of numeric values or a sequence of numeric values.
Output
Returns a number
Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.
Examples
Expression
Value
Description
min(1,2,3)
1
min(-1,0)
-1
min([1,2,3])
1
4.2.5.1.3. max¶
Syntax
max ( arg )
Description
Returns the maximum value.
Input
args: a single list of numeric values or a sequence of numeric values.
Output
Returns a number
Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.
Examples
Expression
Value
Description
max(1,2,3)
3
max([1,2,3])
3
max(-1,0)
0
4.2.5.1.4. sum¶
Syntax
sum ( arg )
Description
Sums all the input arguments.
Input
args: a single list of numeric values or a sequence of numeric values.
Output
Returns a number
Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.
Examples
Expression
Value
Description
sum(1,2,3)
6
sum([1,2,3])
6
4.2.5.1.5. avg¶
Syntax
avg ( arg )
Description
Calculates average for the give arguments.
Input
args: a single list of numeric values or a sequence of numeric values.
Output
Returns a number
Errors
If the input parameter can not be converted to a valid number the expression evaluation fails.
Examples
Expression
Value
Description
sum(1,2,3)
2
sum([1,2,3])
2
4.2.5.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
Description
ceil(0.1)
1.0
ceil(1.9)
2.0
ceil(-1.1)
-1.0
4.2.5.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
Description
floor(0.1)
0.0
floor(1.9)
1.0
floor(-1.1)
-2.0
4.2.6. Search/Find utilities¶
4.2.6.1. Regexpr utils¶
4.2.6.1.1. re_escape¶
Syntax
re_escape ( str )
Description
Returns an unicode string or bytes 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 : unicode string or bytes
Output
Returns an unicode string or bytes.
Examples
Expression
Value
Description
re_escape("hello")
hello
Nothing to escape
re_escape("192.168.0.1")
192.168.0.1
dots escaped
re_escape(encode("192.168.0.1"))
b'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.6.1.2. 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 vector with the matched groups. If regexp do not use groups, the matching string is returned.
Input
string : a unicode string or bytes
regexp : a regular expression unicode string or bytes
Output
A dictionary or a vector of values.
Examples
Expression
Return value
Description
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", encode(r"(w+) (w+)" ))
[ b'hello', b'world' ]
re_search( "hello world", r"(w+) (w+)" )[0]
'hello'
re_search( "hello world", encode(r"(w+) (w+)" )[0])
b'hello'
re_search( "John Doe", r"(?P<name>w+) (?P<surname>w+)" )
{'surname': 'Doe', 'name': 'John'}
re_search( "John Doe", encode(r"(?P<name>w+) (?P<surname>w+)" ))
{'name': b'John', 'surname': b'Doe'}
re_search( "John Doe", r"(?P<name>w+) (?P<surname>w+)" )['surname']
'Doe'
re_search( "John Doe", encode(r"(?P<name>w+) (?P<surname>w+)") )['surname']
b'Doe'
4.2.6.2. Array utils¶
4.2.6.2.1. 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) unicode string or byte string
substring: string or bytes
Output
A string or bytes.
Examples
Expression
Return value
Description
greplines("a1na2na3", '2')
'a2'
greplines(readFile(), 'xxx')
b'line with xxx'
4.2.7. Network Protocols¶
4.2.7.1. ICMP Functions¶
4.2.7.1.1. Ping & RTT¶
4.2.7.1.1.1. getICMPStat¶
Syntax
getICMPStat ( info_type , host [, probesize] [, shorttries] [, timeout ] [, do_frag] [, bind_address] [, ipversion ] [, interval])
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 : (unicode string or bytes) rttavg, rttmin, rttmax, loss.
host : (unicode string or bytes) 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 : (unicode string or bytes) IP source address. Default: not set.
ipversion : (number) IP version: 4 for IPv4, 6 for IPv6. Default: 4.
interval : (number) Seconds between each PING. Default: none.
Warning
probesize default values is always 1472, even if ipversion is 6.
Output
Returns an floating point value
Errors
An exception is raised when an error occurs.
Examples
Expression
Description
Return string value
getICMPStat ('rttmin', "mason")
getICMPStat ('rttmin', $node, 1472)
4.2.7.1.1.2. getRttInfo¶
Alias for getICMPStat.
4.2.7.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.7.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.7.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.7.5. TCP¶
4.2.7.5.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 address or a hostname. If a hostname is given, it is resolved and the test tries the first IP returned.
The functions returns false if the address resolution fails or 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 boolean
Errors
TODO
Examples
Expression
Return value
Description
isTcpOpen("www.google.com", 80)
true
isTcpOpen("thisisnotavalidhostname", 80)
false
4.2.7.5.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 bytes.
Errors
TODO
Examples
Expression
Return value
Description
tcpReceive("www.google.com", 80)
b'<html>....'
4.2.7.6. UDP¶
4.2.7.6.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 boolean
Errors
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.7.7. NTP¶
4.2.7.7.1. isNtpOk¶
Syntax
isNtpOk ( hostname )
Description
Checks if the host hostname (unicode string or bytes) 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: unicode string or ASCII bytes 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.7.7.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 timestamps
Output
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.7.8. HTTP¶
4.2.7.8.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.7.8.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:
Option
Default
Description
include_data
false
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
false
(default False) Disable all special Sanet3 fixes for SSL3 and TLS.
ignore_errors
true
Specify how to handle errors. See Ignore errors.
follow_redirects
yes
Follow HTTP redirects (302). 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:
Option
Default
Description
basic_user
username
basic_password
password
basic_ntlm
false
true/false. Switch to NTML authentication.
basic_challenge
true
true/false. Send authentication info challenge.
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
Default
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:
Option
Default
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 CLIENT keys/certificates
In order to use client-size key/certificate use these parameters
Option
Optional
Description
keyfile
Local PEM file for the client KEY.
certfile
Local PEM file for the client CERTIFICATE.
keypass
yes
Password (passphrase) for the KEY file
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() / args2dict().
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" | "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,-HTTP ignore all errors, BUT raise HTTP/S errors ALL,-HTTP,NONE NONE wins. DO NOT IGNORE ANY ERROR ALL,+HTTP Equivalent to ALL NONE,-HTTP Equivalent to NONEOutput
Returns a boolean
Errors
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)
Specify request options/headers:
Expression
Return Value
Description
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
SSL options:
Expression
Return Value
Description
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)
Error handling:
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 HTTP/S error (because "+" is the defautl behaviour)
urlContentMatches("https://www.google.com/login", "/google/i", ignore_errors="+TIMEOUT,+HTTP")
False
with a HTTP/S error (because "+" is the defautl behaviour)
urlContentMatches("https://www.google.com/login", "/google/i", ignore_errors="+TIMEOUT,-HTTP")
exception
with a HTTP 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
User Client-side certificates:
Expression
Return Value
Description
urlContentMatches("https://myserver/site", "Login", keyfile="/tmp/key.pem", certfile="/tmp/cert.pem")
True
without any error
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.7.8.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.d
Errors
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.7.8.4. httpRequestRaw¶
Syntax
httpRequestRaw ( url [, optional params ] )
Description
Sends an HTTP request (GET or POST) and returns a dictionary containing the HTTP code and the response data.
{ "code": 200, "data": ".....", "time": 0.00032 }By default, the function performs GET request. If optional parameter postdata is specified, the function will perform a POST request.
The "code" and "data" keys can be NULL when a low-level error occurs (not HTTP error) and neither HTTP Code or HTTP Response can be calculated.
The "time" key can be NULL when a low-level error occurs (not HTTP error) and now HTTP response was received.
See the function urlContentMatches for more details aboud options params.
Output
Returns a dictionary containing "code" and "data" keys.
Errors
An exception is raised when error is detected. If an error occurrs and it is ignored, the function will return a dictionary with "data" and "code" set properly.
Examples
Expression
Return Value
Description
httpRequestRaw("http://www.google.com")["code"]
200
Performs a GET.
httpRequestRaw("http://www.google.com")["data"]
string
Response data
httpRequestRaw("http://www.google.com")["time"]
0.13
Total time
httpRequestRaw("http://www.google.com/foo")["code"]
404
Performs a GET on wrong url
httpRequestRaw("http://www.google.com/foo")["data"]
string
Error message
httpRequestRaw("http://www.google.com/foo")["time"]
0.01
Total time
httpRequestRaw("http://www.foo.com")["code"]
404
Performs a GET on wrong url
httpRequestRaw("http://www.google.com/foo")["data"]
string
Error message
Expression
Return Value
Description
httpRequestRaw("http://foo.bar", timeout=1, ignore_errors="ALL")
{'code': None, 'data': None, 'time': 0.023 }
httpRequestRaw("http://foo.bar", timeout=1, ignore_errors="NONE")
EXCEPTION
Expression
Return Value
Description
httpRequestRaw("http://www.google.com/foo", timeout=1, ignore_erros="NONE")
{'code': 404, 'data': '...', 'time': 0.003 }
HTTP errors never raise an exception.
httpRequestRaw("http://www.google.com/foo", timeout=1, ignore_errors="ALL")
{'code': 404, 'data': '...', 'time': 0.003 }
HTTP errors never raise an exception.
Expression
Return Value
Description
httpRequestRaw("http://unreachable", timeout=1, ignore_errors="NONE")
EXCEPTION
httpRequestRaw("http://unreachable", timeout=1, ignore_errors="ALL")
{'code': None, 'data': None}
Unreachable but exception ignored.
4.2.7.9. Cluster management¶
4.2.7.9.1. isAssociated¶
Syntax
isAssociated ( )
Description
Returns true if the current node (Access point) is associated to the cluster which it belongs to.
Input
NONE
Output
True or False
Errors
An exception is raised if the cluster association can not be calculated.
Examples
Expression
Return value
Description
isAssociated()
true
4.2.7.9.2. clusterNode¶
Syntax
clusterNode ( )
Description
Returns the name of the master node the current node is associated to.
Input
None
Output
A string with the give node.
Errors
An exception is raised if the cluster association can not be calculated.
Examples
Expression
Return value
Description
clusterNode()
wlc1
4.2.7.9.3. clusterCommunity¶
Syntax
clusterCommunity ( )
Description
Returns the SNMP community configured for the master node the current node is associated to.
Input
None
Output
A string with the give community.
Errors
An exception is raised if the cluster association can not be calculated.
Examples
Expression
Return value
Description
clusterCommunity()
public123
4.2.7.9.4. clusterSnmpPort¶
Syntax
clusterSnmpPort ( )
Description
Returns the SNMP port configured for the master node the current node is associated to.
Input
None
Output
A number with the give SNMP port.
Errors
An exception is raised if the cluster association can not be calculated.
Examples
Expression
Return value
Description
clusterSnmpPort()
161
4.2.7.9.5. clusterInstance¶
Syntax
clusterInstance ( )
Description
Returns the SNMP instance for the current node (AP) inside the MIB of the controller (master node).
Input
None
Output
A string with the give instance.
Errors
An exception is raised if the cluster association can not be calculated.
Examples
Expression
Return value
Description
clusterInstance()
144.23.51.8
4.2.7.10. Network utils¶
4.2.7.10.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 string
Errors
An exception is raised if an error occurs.
Examples
Expression
Return value
Description
resolve("www.google.com")
173.194.113.230
4.2.7.10.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.7.10.3. buff2IP¶
Syntax
buff2IP ( buffer )
Description
Convert the buffer of bytes buffer storing a IPv4 or IPv6 address to it's dotted-string rappresentation (es: 192.168.0.24).
Input
buffer : a 4 byte or 16 byte buffer string
Output
A string
Errors
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.
buff2IP( hexstr2bin("0101F0FF") )
"1.1.240.255"
buff2IP( hexstr2bin("F0000000000000000000000000000001"))
"f000::1"
4.2.8. Local utilities¶
4.2.8.1. External Programs execution¶
4.2.8.1.1. exec()¶
Syntax
exec ( current , command , [ param, ...] [ , basedir ] [ , execute_timeout ] [ , exec_on_remote_agent ] [, env ] )
Description
The function executes the external command command with the given param(s) param and returns the content of the standard output (in bytes!) produced by the command when it terminates with return code 0.
Important
parameters can be unicode
When the current parameter is true, the command is executed with the given parameters.
If current is false, the function returns the standard output (in bytes) produced by the command at the previous check for the same datagroup.
The env parameter specifies additional environment variables for the command. It must be a dictionary key-value object created with the function "dict()".
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.
env: Additional environement. Es: dict("VAR1","12345" , "VAR2","foo" , "VAR3","bar")
Output
Returns a string.
Errors
If the command terminates with return code different from zero (0), and exception is raised.
An an exception is raised when a timeout occurs or when there is comunication error with the remote agent (exec_on_remote_agent).
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
exec(0, "break.sh" )
exception
Program not returned code <> 0
exec(0, "psql", "-U", "user1", env=dict("PGPASSWORD", "12345" ), basedir="")
4.2.8.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 string
Errors
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.8.2. Filesystem functions¶
4.2.8.2.1. mtime¶
Syntax
mtime ( path )
Description
Performs a stat() system call on the given path path and returns the time of most recent content modification.
If an error occurrs the function returns 0.
Input
path: (string or bytes) containing the file absolute path
Output
Returns a floating point value.
Examples
Expression
Return value
Description
mtime("/etc/passwd")
1291971078.92
1291971078.92
mtime("/etc2/foo")
0
0
4.2.8.2.2. fileExists¶
Syntax
fileExists ( path )
Description
Return True if the given path exists
If an error occurrs the function returns 0.
Input
path: (string or bytes) containing the file absolute path
Output
Returns a floating point value.
Examples
Expression
Return value
Description
mtime("/etc/passwd")
1291971078.92
1291971078.92
mtime("/etc2/foo")
0
0
4.2.8.2.3. readFile¶
Syntax
readFile ( path )
Description
The function returns the content of the given file in bytes.
Input
path: (string or bytes) containing the file absolute path
Output
Returns bytes.
Errors
Raises an exceptions if an error occurs while opening/reading the file
Examples
Expression
Return value
Description
readFile("/etc/hosts")
b'127.0.0.1 localhost .....'
readFile("/tmp/nonexistent")
EXCEPTION
4.2.9. SNMP¶
4.2.9.1. SNMP Utils¶
4.2.9.1.1. str2oid¶
Syntax
str2oid( string )
Description
Convert a unicode string or byte strings to the corrisponding dot-separated OID string.
Input
string: unicode or byte 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'
str2oid(encode("foo bar"))
b'102.111.111.32.98.97.114'
Input was bytes, returns bytes
4.2.9.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 value
Errors
None
Examples
Expression
Return value
Description
tryget( 1.3.6.1.2.1.1.1.0@, "foo" )
a value * or foo
4.2.9.1.3. testget¶
Syntax
testget ( snmpexpr )
Description
Tries to calculate the value for the given SNMP expression.
Input
snmpexpr: a SNMP expression.
Outpu
TODO
Errors
TODO
Examples
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.9.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 hostname
Output
Returns a number
Errors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.
Examples
Expression
value
Description
sumall("1.3.6.1.2.1.1.3.0", "public", "foo","bar")
1531782725
4.2.9.1.5. walk2set¶
Syntax
walk2set ( oid expr [ , encoding ] )
Description
Perform a walk on the given oid expr and returns a SET with all the oids' values.
if encoding is specified, string values are decoded using the given encoding.
Input
oid expr: a Snmp Expression.
encoding: string
Outpu
Returns a SET of values.
Errors
Raises and exception if an error occurs
Examples
Expression
Return value
Description
walk2set(1.3.6.1.2.1.4.20.1.1@)
{ b"127.0.0.1", b"192.168.0.1" }
walk2set(1.3.6.1.2.1.4.20.1.1@, encoding='ascii')
{ "127.0.0.1", "192.168.0.1" }
4.2.9.1.6. walk2list¶
Syntax
walk2set ( oid expr [ , encoding ] )
Description
Perform a walk on the given oid expr and returns a LIST with all the oids' values.
if encoding is specified, string values are decoded using the given encoding.
Input
oid expr: a Snmp Expression.
encoding: string
Outpu
Returns a LIST
Errors
Raises and exception if an error occurs
Examples
Expression
Return value
Description
walk2set(1.3.6.1.2.1.4.20.1.1@)
[ b"127.0.0.1", b"192.168.0.1" ]
list of byte arrays
walk2set(1.3.6.1.2.1.4.20.1.1@, encoding='ascii')
[ "127.0.0.1", "192.168.0.1" ]
list of unicode strings
4.2.9.2. SNMP Walk utils¶
4.2.9.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 integer
Errors
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.9.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 integer
Errors
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.9.2.3. walkCountMatch¶
Syntax
walkCountMatch ( snmpexpr , str_regexpr_oid , str_regexpr_val [ , add_infos ] )
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.
If str_regexpr_prefix and str_regexpr_val are passed as unicode string they will be encoded as utf-8. If another encoding is needed they must be converted explicitly. (For ex. encode("<str_regexpr_val>", "iso-8859-1"))
If add_infos is true, additional informations about the SNMP walk are added to the verbose status. Default: false.
Warning
Enabling add_infos will cause extra data to be processed (or saved on logs). Do not enable this flags on huge SNMP walks.
Input
snmpexpr : SNMP Expression identifying the MIB to scan.
str_regexpr_prefix : Regular expression unicode string or bytes matching the sub-OIDs in the MIB
str_regexpr_val : Regular expression unicode string or bytes matching the OIDs' value
add_infos : (optional) If true, the walk result is added to verb status informations
Output
Returns the number of matching entries
Errors
The function raises an exception if the SNMP MIB identified by snmp expr can not be found.
Examples
Expression
Return Value
Description
walkCountMatch( 1.2.3.4.5@ , "^6.7.8", "^5$")
44.0
walkCountMatch( 1.2.3.4.5@ , "^6.7.8", "^à$")
1
"^à$" will be encoded as utf-8 resulting in b'(.*)xc3xa0(.*)' and will be matched with the oid value bytes
walkCountMatch( 1.2.3.4.5@ , "^6.7.8", encode("^à$", "iso-8859-1"))
1
"^à$" will be encoded as iso-8859-1 resulting in b'(.*)xe0(.*)' and will be matched with the oid value bytes
4.2.9.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 integer
Errors
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.9.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 integer
Errors
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.9.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 integer
Errors
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.9.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 integer
Errors
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.9.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 integer
Errors
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.9.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 boolean
Errors
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.9.2.10. walkDiffIface¶
Syntax
walkDiffIface ( snmparg [, threshold=None] [ , verbose_info ] [ , time_delta ] [ , policy ] [ , ifstatus_filter ] )
Description
TODO
Input
TODO
Output
TODO
Errors
TODO
Examples
TODO
4.2.9.2.11. 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:
comparison / value
The comp type must be: b (binary) or s (string).
Expression
Description
b
The binary value of the oid is compated with regular expression value
s
The string value of the oid is compated with regular expression value
>
The numeric value of the oid must be greater than the value value
<
The numeric value of the oid must be lower than the value value
Input
snmp expr : Base oid
selected suboid : oid string
suboid n : suboid string
val n : unicode string or bytes
Output
Returns a vector of values
Errors
The function raises an exception when an error occours.
Examples
Expression
Return Value
Description
walkFilter(1.3.6.1.2.1.2@, "2.1.4", "2.1.7", "s/1"))
[1,2]
List of ifindexs of interface with status active (1)
walkFilter(1.3.6.1.2.1.2@, "2.1.1", "2.1.4", ">/1499")
[1,2]
List of ifindexs of interfaces with MTU >= 1500 |
sum(walkFilter(1.3.6.1.2.1.2@, "2.1.4", "2.1.7", "s/1"))
31436
Sums all MTU (...2.1.4) of active interfaces (...2.1.7)
4.2.9.2.12. sumWalks¶
Syntax
sumWalks ( snmp expr1 [ , snmp expr2 ... ] )
Description
Perform SNMP walks for all snmp expressions and create a virtual SNMP table with summed values for all instances.
Esample: Give the following expression:
sumWalks( 1.3.6.1.2.1.2.2.1.17@, 1.3.6.1.2.1.2.2.1.16@ )
- These are the values for the
1.3.6.1.2.1.2.2.1.17.1 = 10 1.3.6.1.2.1.2.2.1.17.2 = 22 1.3.6.1.2.1.2.2.1.16.1 = 32 1.3.6.1.2.1.2.2.1.16.2 = 7 ^^^^^^^^^^^^^^^^^ ^^ ^ | | `-- instance | `----- oid `----------------- common prefixThe result is:
1.3.6.1.2.1.2.2.1.1 = 42 1.3.6.1.2.1.2.2.1.2 = 29 ^^^^^^^^^^^^^^^^^ `-- common prefixInput
snmp exprN: a list of SNMP expr values
Output
A SNMP value rappresenting the result of an SNMP WALK
Errors
The function raises an exception when an error occours.
Examples
Expression
Return Value
Description
sumWalks( 1.3.6.1.2.1.2.2.1.17@, 1.3.6.1.2.1.2.2.1.16@ )
snmp value
Virtual SNMP walk
4.2.9.3. RegExpr¶
4.2.9.3.1. byBinaryValue¶
Syntax
byBinaryValue ( snmpexpr , str hex [, match_pattern ] [, instance_filter ], )
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.
By default the binary value is compared with the entire string. The default match pattern is '^%s$'.
The parameter instance_filter is a regular expression: all OIDs with a non matching instance (sub-OID) will be ignored/skipped.
Input
snmpexpr : A SNMP expression indentifing a valid MIB.
str hex : A string containing a valid hexadecimal string.
match_pattern : a regular expression template for matching str_hex.
instance_filter : a regular expression for instance/sub-oid matching.
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".
byBinaryValue(1.3.6.1.2.1.2.2.1.6@, "fefd", match_pattern="^%s")
2
It returns the ifPhysAddress sub-oid of the interface with MAC address starting with "fefd".
byBinaryValue(1.3.6.1.2.1.2@, "fefd", instance_filter="^.*6$")
2
It returns the ifPhysAddress sub-oid of the interface with MAC address starting with "fefd".
byBinaryValue(1.3.6.1.2.1.2.2.1.6@, "6A09C3B34C1B", instance_filter=".5$")
2
It returns the ifPhysAddress sub-oid but only if ends with a dot and 5 (".5")
4.2.9.3.2. byBinaryIP¶
Warning
NON USARE!!! Funzione bacata, in fase di review
Syntax
byBinaryIP ( snmpexpr , str_ip [, instance_filter ], )
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.
instance_filter: a regular expression for instance/sub-oid matching.
Output
Returns a string OID.
Errors
Examples
Expression
Description
byBinaryIP( 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.9.3.3. byRegexpUnique¶
Syntax
byRegexpUnique ( snmpexpr , str_regexpr [, instance_filter ], )
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.
The parameter instance_filter is a regular expression: all OIDs with a non matching instance (sub-OID) will be ignored/skipped.
Input
snmpexpr : A SNMP expression indentifing a valid MIB.
snmpexpr : A string containing a valid regular expression.
instance_filter: a regular expression for instance/sub-oid matching.
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.9.3.4. existsRegexp¶
Syntax
existsRegexp ( snmpexpr , str_regexpr [, instance_filter ], )
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.
instance_filter: a regular expression for instance/sub-oid matching.
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.9.3.5. existsRegexpUnique¶
Syntax
existsRegexpUnique ( snmpexpr , str_regexpr [, instance_filter ], )
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.
instance_filter: a regular expression for instance/sub-oid matching.
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.9.3.6. byMultiRegexpUnique¶
Syntax
byMultiRegexpUnique ( snmparg , [ suboid1 , matchexpr1 ] , [ suboid2 , matchexpr2 ] , ... )
Description
Scans the MIB identified by the SNMP expression snmparg and verifies all the sub-oids <suboid1>, <suboid2>, ect. match with the corresponding matching expressions <matchexpr1>, <matchexpr2>, 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 these forms:
regular expressions
<type>/<regular expression>The <type> must be b (binary) or s (string).
Math comparisons:
<comparison>/<value>The <comparison> can be "<", ">",
Input
snmpexpr : A SNMP expression indentifing a valid MIB.
sequence of suboid, matchexpr : A string containing a valid matching 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'.
byMultiRegexpUnique(1.3.6.1.2.1.25.4.2.1@ , "2" , "s/^" + re_escape("firefox-esr") + "$", "7", "</3")
12313
Searches for a process 'firefox-esr' with status less than 3 ( running (1) or runnable(2) )
4.2.9.3.7. 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. with the same logic of the function byMultiRegexpUnique().
Input
snmpexpr : A SNMP expression indentifing a valid MIB.
sequence of suboid, matchexpr : A string containing a valid matching 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.9.4. Storage utils¶
4.2.9.4.1. hrStorageNoFull()¶
Syntax
hrStorageNoFull ( default_percent_threshold , [ storage_re , percent_threshold [, ... ] ] , [ ignore_monitored ] )
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_threshold
specify 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.
When parameter ignore_monitored is set to true, the function ignores filesystems alread monitored with a Sanet Storage configured on the target node.
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%.
hrStorageNoFull(99, "^/run/log$", 80, ignore_monitored=1)
Check every partition with 99%, /run/log with 80% ( /home is already monitored with a storage)
4.2.9.5. Interface utils¶
4.2.9.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 boolean
Errors
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.9.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 number
Errors
The function raises an exception if an error occurs.
Examples
Expression
Return value
Description
getHCInOctets($node)
123131
4.2.9.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 boolean
Errors
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.9.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.9.6. OIDs Utilities¶
4.2.9.6.1. oidFirst()¶
Syntax
oidFirst ( oid )
Description
The function take in input a dot-separted OID string (unicode or ascii) and returns the first node of the sequence.
If oid value starts with a dot character ('.'), the first dot is ignored.
Input
oid: a dot-separated string (unicode or ascii bytes)
Output
Returns a unicode string or bytes.
Errors
Raise an exception if input values is not an unicode string or a byte array.
Examples
Expression
Return value
Description
oidFirst(".1.3.6.1.4.1.8072.3.2.10")
'1'
unicode string
oidFirst("1.3.6.1.4.1.8072.3.2.10")
'1'
unicode string
oidFirst(encode("1.3.6.1.4.1.8072.3.2.10"))
b'1'
byte string
oidFirst( 1.3.6.1.2.1.1.2.0@ )
b'1'
Extracts the first node from the node's SysOID
oidFirst( 10.34 )
ERROR
oidFirst( 10 )
ERROR
oidFirst( "iso.3.6.1.2.1.1.1.0" )
'iso'
4.2.9.6.2. oidLast()¶
Syntax
oidLast ( oid )
Description
The function takes in input a dot-separted OID string (unicode or ascii) and returns the last node of the sequence.
Input
oid: a dot-separated string.(unicode or ascii bytes)
Output
Returns a unicode string or bytes.
Errors
Raise an exception if input values is not an unicode string or a byte array.
Examples
Expression
Return value
Description
oidLast(".1.3.6.1.4.1.8072.3.2.10")
'10'
unicode string
oidLast("1.3.6.1.4.1.8072.3.2.10")
'10'
unicode string
oidLast(encode("1.3.6.1.4.1.8072.3.2.10"))
b'10'
byte string
oidLast( 1.3.6.1.2.1.1.2.0@ )
b'10'
Last part of bytes b'.1.3.6.1.4.1.8072.3.2.10'
oidLast( 10.34 )
ERROR
oidLast( 10 )
ERROR
oidLast( "iso.3.6.1.2.1.1.1.0" )
'0'
4.2.9.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-compatibile unicode string or ASCII-compatibile byte array.
Output
Returns an OID string. The value a unicode string if input was unicode, bytes otherwise.
Errors
Raise an exception if an error occours.
Examples
Expression
Return value
Description
oidIp("2a01:4f8:110:3383::1")
'42.1.4.248.1.16.51.131.0.0.0.0.0.0.0.1'
unicode string
oidIp(encode("2a01:4f8:110:3383::1"))
b'42.1.4.248.1.16.51.131.0.0.0.0.0.0.0.1'
input is bytes, return value is bytes
oidIp("192.168.1.255")
'192.168.1.255'
unicode string
oidIp(encode("192.168.1.255"))
b'192.168.1.255'
input is bytes, return value is bytes
oidIp(127)
ERROR
oidIp('1.3.a.4')
ERROR
4.2.9.6.4. oidString()¶
Syntax
oidString ( string )
Description
The function takes in input a unicode string or byte string and returns an OID made with the length of the string as the first item, and the bytes value as subsequent items.
Important
If string is a unicode string, it will converted to utf8 before computation.
Input
string: an string (unicode or bytes).
Output
Returns an dot-seprated OID string (unicode or bytes, depending of the input)
Errors
Raise an exception if an error occours.
Examples
Expression
Return value
Description
oidString("abc")
'3.97.98.99'
unicode string
oidString(encode("abc"))
b'3.97.98.99'
bytes. (input value are ASCII complatible bytes)
oidString("Città")
'6.67.105.116.116.195.160'
unicode string (input encoded in utf8 to b'Cittxc3xa0'
oidString(encode("Città","utf8"))
b'5.67.105.116.116.224'
bytes. (input is b'Cittxc3xa0')
oidString(encode("Città","iso-8859-1"))
b'5.67.105.116.116.224'
bytes. (input is b'Cittxe0')
oidString(1.3.6.1.2.1.2.2.1.6.2@)
b'6.8.0.39.159.186.171'
Oid for bytes of MAC "08:00:27:9F:BA:AB"
4.2.10. SNMP Advanced¶
4.2.10.1. SNMP Advanced¶
4.2.10.1.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
Return value
Description
adjacent()
adjacent("stp")
adjacent("stp", "cdp")
4.2.11. Redis DB Utilities¶
4.2.11.1. Redis Utils¶
4.2.11.1.1. redis_get¶
Syntax
redis ( key [ , default ] [ , db ] [ , host ] [ , port ] [, username ] [, password ] [, ssl ] )
Description
Tries to get the value for the key key from a Redis DB. A unicode string is always returned.
An exception is raised when the key is not found and default is not specified.
If Redis is used as local cache manager, the other Redis parameters take their defaults from local cache manager settings.
These are the defaults:
parameter
default
Description
db
0
host
127.0.0.1
port
6379
username
password
ssl
false
Use SSL for TCP connection
** Output **
A unicode string value.
** Errors **
Raise exceptions if the key does not exists or other exceptions.
Examples
Expression
Return value
Description
redis("a.key.in.the.db")
'foo'
Stored value was a string or uft8 byte array.
redis("b.key.in.the.db")
'3.14'
Stored value was a float.
redis("xxx")
ERROR
Key xxx does not exist.
redis("xxx", default=10)
10
Key xxx does not exists. Integer 10 is returned.
redis("xxx2", default=10)
'666'
Key xxx exists with value '666'.
4.2.11.1.3. redis_set¶
Syntax
redis_set ( key , val [ , db ] [ , host ] [ , port ] [, username ] [, password ] [, ssl ] )
Description
Store the key/value inside a redis server.
An exception is raised on error.
Other options are the same of redis_get.
** Output **
Returns always true.
** Errors **
Raise exceptions on any error.
Examples
Expression
Return value
Description
redis_set("a.key.in.the.db", 1)
true
Unicode string "1" is saved.
redis_set("a.key.in.the.db", 3.14)
true
Unicode string "3.14" is saved.
redis_set("a.key.in.the.db", "foo")
true
redis_set("a.key.in.the.db", "Città")
true
Unicode string "Città" is saved
redis_set("a.key.in.the.db", encode("Città") )
true
Unicode string "Città" is saved
redis_set("a.key.in.the.db", encode("Città") )
true
Unicode string "b'Cittxc3xa0'" is saved
redis_set("a.key.in.the.db", encode("Città", "iso-8859-1") )
true
Unicode string "b'Cittxe0'" is saved
4.2.12. Database functions¶
4.2.12.1. Postgres functions¶
4.2.12.1.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.
Warning
input byte values will be converted to unicode strings using UTF8.
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.13. Services¶
4.2.13.1. SANET Service utils¶
4.2.13.1.1. isServiceRunning()¶
Syntax
isServiceRunning ( )
Description
Returns true if the value of swRunIndex for the current service can be calculated.
Input
None
Output
Returns a boolean.
Errors
An exception is raised when if swRunIndex can not be calculated*.
Examples
Expression
Return value
Description
isServiceRunning()
true
4.2.14. Sanet internal Monitoring¶
4.2.14.1. Monitoraggio condition¶
4.2.14.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.14.1.2. getConditionStatus()¶
Syntax
getConditionStatus ( identity string )
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 the current condition status CODE ('UP', 'DN', ecc.)
If the condition's status can not be calculated, the functions raises and exception.
Input
path: the full path or classification of the condition
Outpu
Returns a string.
Errors
Raise an exceptions and become uncheckable when the given condition is not found or when an other error occurs.
Examples
Expression
Return value
getConditionStatus("localhost;;dg;condition_up")
"UP"
getConditionStatus("localhost;;dg;condition_down")
"DN"
getConditionStatus("localhost;;dg;condition_failing")
"FA"
getConditionStatus("localhost;;dg;condition_uncheckable_up")
"UU"
getConditionStatus("localhost;;dg;condition_uncheckable_down")
"UD"
getConditionStatus("localhost;;dg;condition_suspended")
"IN"
4.2.14.1.3. 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.14.2. Monitoraggio dei Tag¶
4.2.14.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.14.2.2. tagNodesDownCount¶
Syntax
tagNodesDownCount ( tagpath [ , percentage ] )
Description
Return the number of nodes with primary condition with a "down state" (DN, DD, DU).
If percentage is TRUE the percentage values is returned. Default is FALSE.
Input
tagpath: the fullpath of the given tag (es: "geo:/Global vision/tag1/tag2")
Outpu
Returns a number (absolute o percentage value)
Errors
The expression goes uncheckable if the tag is not found.
Examples
Expression
Description
tagNodesDownCount("geo:/Global vision/tag1/tag2")
3 (of 10)
tagNodesDownCount("geo:/Global vision/tag1/tag2", percentage=1)
0.33
4.2.14.3. Monitoraggio Datasource¶
4.2.14.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 value
Errors
The expression goes down if the datasourse does not exits.
Examples
Expression
Description
measureAvgInInterval("localhost;;icmp-reachability:lossperc", 600)
4.2.14.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 value
Errors
It goes uncheckable if the function can not find useful data to fetch.
Examples
Expression
Description
pktLossAvgInInterval(600)
0.004
4.2.14.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.14.3.4. getConditionStatusTotalTime¶
Syntax
getConditionStatusTotalTime ( [ path ] [, time_range] [, down_states] [, perc] [, classification ] )
Description
Returns the total down time of a particular condition with the given path
If path is specified, the condition with the given path is selected. If classification is specified, the condition of the current node matching the given classification is selected. If path and classification are not specified.
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.
classification : (optional) the classification string.
Output
Numeric value
Errors
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
getConditionStatusTotalTime(classification="system.interface.status")
43
4.2.14.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 value
Errors
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.14.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.14.3.7. DataSourcesAvgAndVar¶
Syntax
DataSourceAvgAndVar ( [ datasources, ] [ , classification ] [ , interval ] [ , timespec ] [ , discard_high_threshold ] [ , discard_high_max_number ] [ , null_max_number ] )
Description
Calculate average and variance of the datasources selected by the given datasources names/paths or classification.
The parameter datasources can be a comma-separated list of paths, or a list of path strings created with the funtion list() / array().
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.
Values are selected in the given interval (seconds). With timespec you can specify particula time-ranges inside the given interval (es: 8:00-12:00/1-7).
When timespec is not specified, 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
datasources: (optional) list of path or names.
classification: (optional) a string with the desired classification.
interval: (optional) number of seconds in the past.
timespec: (optional) validi time-ranges inside the given interval.
discard_high_threshold: (optional) values above this values will be ignored.
discard_high_max_number: (optional) maximum number of discarded values by discard_high_threshold.
null_max_number: (optional) maximum number of null values.
Output
The function returns a tuple <average, variance>.
Errors
An exception is raised if the agent can not load datasources' values from Sanet.
Examples
Expression
Return
Description
DataSourcesAvgAndVar(datasources="localhost;;icmp-reachability;rttmin")
(5.24653328, 4.6422)
tuple
DataSourcesAvgAndVar(datasources="localhost;;icmp-reachability;rttmin,rttmax")
(5.24653328, 4.6422)
tuple
DataSourcesAvgAndVar(datasources=list("localhost;;icmp-reachability;rttmin","rttmax"))
(5.24653328, 4.6422)
tuple
DataSourcesAvgAndVar(datasources=list("localhost;;icmp-reachability;rttmin","rttmax"), interval=3600)
(5.24653328, 4.6422)
tuple
4.2.14.3.8. DataSourcesAvg¶
Syntax
DataSourceAvgAndVar ( [ datasources, ] [ , classification ] [ , interval ] [ , timespec ] [ , discard_high_threshold ] [ , discard_high_max_number ] [ , null_max_number ] )
Description
Same behavior of DataSourcesAvgAndVar, but returns only the average value.
Examples
Expression
Return
Description
DataSourceAvgAndVar(datasources="localhost;;icmp-reachability;rttmin")
5.24653328
4.2.14.3.9. DataSourceLastValue¶
Syntax
getDataSourceLastValue ( [ path, ] [ , samples_tollerance ] )
Description
Return the last not null value for datasource with the given path.
If last samples_tollerance values are all null, the system raises an exception. Default: 3.
Input
path: the path of the datasource.
samples_tollerance: (optional) integer.
Output
The function returns a float value.
Errors
An exception is raised if the agent can not load datasources' last value from Sanet.
Examples
Expression
Return
Description
getDataSourceLastValue(path="localhost;;icmp-reachability;rttmin")
5.24653328
A value
getDataSourceLastValue(path="localhost;;datagroup-test;val", samples_tollerance=1)
Exception
A value
4.2.14.4. Monitoraggio condition¶
4.2.14.4.1. addDSInfos¶
Syntax
addDSInfos ( names )
Description
The poller will add verbstatus of the datasources with name in names to the verbstatus of the current condition.
The parameter name can be:
An asterisk ("*") : all datasource if the datagroup are selected.
A sequence of "names" separated by comma.
If there is not a datasource with the given name, the name is ignored.
The function always returns true.
Input
names: unicode string
Output
Returns true.
Errors
Raise an exceptions if
Examples
Expression
Return value
addDSInfos("*")
true
addDSInfos("loss,rttmin")
true
4.2.14.5. Statistics¶
4.2.14.5.1. getMonitoringStats¶
Syntax
getMonitoringStats ( [ tag_path ] [ , timeout ] )
Description
Asks the main server for statistics about monitored elements, datasources and conditions for the current tenant.
If tag_path is specified, statistics are related to the specified tag.
The timeout parameter is optional, and specifies the time the agent will wait for a response from the main server.
{ 'elements' : { 'node': 1, 'interface': 0, 'storage': 0, 'service': 0, 'device': 0 }, 'datasources': { 'OK': 0, 'SV': 0, 'CA': 0, 'DO': 0, 'UN': 0, 'ER': 0 }, 'conditions' : { 'NONE': 0, 'DN': 1, 'FA': 0, 'UD': 0, 'UU': 0, 'DD': 0, 'DU': 0, 'TD': 0, 'TU': 0, 'IN': 0, 'UP': 0 }, }Input
tag_path: (option) String. A tag path.
timouet: (optiona) Number. A timeout in seconds.
Output
Returns a "dictionary".
Errors
Raise an exceptions if
Examples
Expression
Return value
TODO
true
4.2.15. Execution utilities¶
4.2.15.1. Execution values¶
4.2.15.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
None
Examples
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.15.1.2. getlastval¶
Syntax
getlastval ( name , [ default ] )
Description
Returns the value of name saved at the last execution time by the function saveval() (See: :ref':saveval.)
if name is missing and default is specified, default is returned.
Input
name: string
Outpu
Any value
Errors
Raise exception in there is no value for the given variable name or default is defined.
Examples
Expression
Return value
Description
getlastval("x")
a value
The the last value of "x".
getlastval("foo")
EXCEPTION
"foo" is missing.
getlastval("foo", 10)
10
"foo" is missing. returns the default value 10.
saveval("x", ....) - getlastval("x") < $delta
true or false
Compare the current value of "x" with the last.
4.2.15.2. Test functions¶
4.2.15.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 value
Errors
None
Examples
Expression
Return value
Description
iftrue(1, "yes", "no")
"yes"
iftrue(0, "yes", "no")
"no"
4.2.15.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.15.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 false
Errors
None
Examples
Expression
Return value
Description
test_symbol("$ifindex")
true
test_symbol("$_xyz_ ")
false
4.2.15.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
None
Examples
Expression
Return value
Description
test_state("UP")
true
test_state("FA")
false
test_state("UN")
exception
4.2.15.2.5. valueinrange()¶
Syntax
valueinrage ( value , minvalue , maxvalue )
Description
Returns value if value is between minvalue and maxvalue (included).
Raises an exception otherwise.
Input
value Number
minvalue Number
maxvalue Number
Output
number if in range, error otherwise
Examples
Expression
Return value
Description
valueinrange(2,1,3)
2
valueinrange(5,1,3)
ERROR
4.2.16. Encoding functions¶
4.2.16.1. JSON Functions¶
4.2.16.1.1. loadjson()¶
Syntax
loadjson ( string )
Description
Parse the JSON unicode string string or UTF8 byte array 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
Return value
Description
loadjson("10")
10
Read JSON from string and return INTEGER
loadjson( encode("10") )
10
Read JSON from UTF8 byte string and return INTEGER
loadjson( encode("10", "iso-8859-1") )
10
Read JSON from ISO byte string and return INTEGER
loadjson("Città")
'Città'
Read JSON from literal string and return INTEGER
loadjson( encode("Città") )
'Città'
Read JSON from UTF8 byte string and return INTEGER
loadjson( encode("Città", "iso-8859-1") )
ERROR
ISO byte string is not decodable (JSON standard wants UTF8 bytes)
loadjson('{ "hello": "world" }')['hello']
"world"
Convert the JSON string '{ "hello": "world" }'
loadjson( readFile("/tmp/data.json")['hello']
"world"
Read JSON data from file ( '{ "hello": "world" }' )
4.2.17. Data Manipulation¶
4.2.17.1. External tools¶
4.2.17.1.1. jq¶
Syntax
jq ( jq_string, data )
Description
Executes a valid JQ command jq_string on data and return the result.
Input
jq_string: a JQ string command.
data: structured data (loaded from a JSON string).
Output
Returns a value or a datastructure.
Errors
Raise an exception and when error occurs.
Examples
Expression
Result
Description
jq ( ".[0]", loadjson( httpRequest("http://127.0.0.1/data.json"))
a value
Load JSON data from localhost and return the first element
Dependences
apt-get install autoconf automake build-essential libtool python-dev pip install jq==1.4.0
4.2.18. Sending data¶
4.2.18.1. SYSLOG¶
4.2.18.1.1. sendValueToSysLog¶
Syntax
sendValueToSysLog ( value [ , options ] )
Description
Send a Syslog message containing the given value (and other informations) and returns the same value.
Input
value :
ds_name : (optional) name of the value (default: datasource or condition name)
server : (optional) Syslog server hostname/ip.
port : (optional) Syslog port
facility : (optional) Syslog facility (default 'USER' [8])
severity : (optional) Syslog serverity (default INFO [6])
hostname : (optional) Value for the HOST field in syslog header.
proc : (optional) value for the PROC field in syslog header.
Output
Returns the given input value value.
Errors
The function returns an uncheckable value when any unmanaged network error occurs.
Examples
Expression
Return value
SYSLOG message
sendValueToSysLog(10)
'hello world'
Mar 14 10:04:49 debian11.internal.labs.it sanet: {"node": "localhost", "element": "localhost", "effective_ip": "127.0.0.1", "value": 10 }
sendValueToSysLog('hello world')
'hello world'
Mar 14 10:04:49 debian11.internal.labs.it sanet: {"node": "localhost", "element": "localhost", "effective_ip": "127.0.0.1", "value": "hello world"}
sendValueToSysLog(decode(1.3.6.1.2.1.1.1.0@))
sysdescr of localhost
Mar 14 10:06:31 debian11.internal.labs.it sanet: {"node": "localhost", "element": "localhost", "effective_ip": "127.0.0.1", "value": "Linux debian11 5.10.0-8-amd64 #1 SMP Debian 5.10.46-4 (2021-08-03) x86_64"}
4.2.19. Debug¶
4.2.19.1. pollerror¶
Syntax
pollerror **( [ info ] )
Description
Always raises an execution exception and the current expression goes uncheckable.
The raise error contains the optional info text.
Input
None
Outpu
Returns 0.
Errors
Raise and
Examples
Expression
Return value
Description
pollerror()
exception
4.2.19.2. unknownerror¶
Syntax
unknownerror()
Description
Always raises an unspecified exception.
NOTE: used only for debug purpose.
Input
None
Outpu
Returns 0.
Errors
Raise and
Examples
Expression
Return value
Description
pollerror()
exception
4.2.19.3. test()¶
Syntax
test()
Description
It always returns 0.
Input
None
Outpu
Returns 0.
Errors
None
Examples
Expression
Return value
Description
test()
0
4.2.19.4. sleep()¶
Syntax
sleep ( [ seconds ] )
Description
Stop execution of the current thread for seconds.
Input
seconds: number of seconds (default=1)
Output
Returns seconds.
Errors
None
Examples
Expression
Return value
Description
sleep()
1
Stops for 1 second
sleep(10)
10
Stops for 10 seconds
sleep(0.5)
0.5
Stops for 1/2 second
4.2.19.5. randint()¶
Syntax
randint ( min , max* )
Description
Return a random integer between min and max.
Input
min: integer value
max: integer value
Output
Returns an integer value
Errors
None
Examples
Expression
Return value
Description
randint(0, 100)
35
Random value 35
4.2.19.6. log_snmpval¶
Syntax
log_snmpval **( snmp val )
Description
Logs informations about snmp val and returns it.
Input
snmp val: an SNMP value type.
Outpu
Returns the input value as is.
Errors
Raise an exception if input values is not an SNMP value.
Examples
Expression
Return value
Description
log_snmpval( 1.3.6.1.2.1.1.1.0@ )
any
Logs and returns