pyfixbuf — Class Descriptions¶
Class Overview
The data for single flow is represented in pyfixbuf by the
Record class. A Record contains one or more
Field objects, where each Field describes some
aspect of the flow.
The format of a flow record is flexible and is described by a Template,
represented in pyfixbuf by the Template class. A template
contains references to one or more Information Elements
(InfoElement), where each element describes some aspect of
the flow, such as sourceIPv4Address. The elements referenced by a
template correspond to the fields in the Record. The
InfoElementSpec class is used to specify the Information
Elements used by a Template.
libfixbuf and Pyfixbuf support RFC 6313 which defines object types to hold
structured data. A basicList (BL) may contain multiple
instances of a single Information Element. A subTemplateList
(STL) contains zero or more Record
instances that use that a single Template. Finally, the
subTemplateMultiList (STML) type holds
Record instances that may use different
Template descriptions. In an STML, a
group of Records that use the same Template are
represented by the STMLEntry class.
An exporting process is created with the Exporter class,
and a collecting process is created with the Collector
class if it is file-based or the Listener class if it is
socket-based. Internally, the Listener creates a new
Collector object when a new connection is made to the
socket.
The interface between a Collector or an
Exporter and the Record and
Template objects is managed by two classes:
The message buffer,
Buffer, is used to read data from a Collector and write data to a Exporter.The
Sessionmanages Templates and other state, such as message sequence numbers.
The universe of information elements (InfoElement) is
maintained by an Information Model (InfoModel). An
InfoModel instance contains the information elements defined by IANA. The
InfoModel may be expanded by defining enterprise-specific elements, such as
those defined by CERT (see also the pyfixbuf.cert module). The CERT
elements are required when reading data produced by YAF or super_mediator.
The DataType, Units, and
Semantic classes are enumerations that describe properties
of an InfoElement.
Record¶
A Record is one of the “core” interfaces to the IPFIX data through
libfixbuf. This is the main object for manipulating the data prior
to export and following import.
- class pyfixbuf.Record(model: InfoModel[, template: Template = None[, record: Record = None]])¶
Creates an empty Record given an
InfoModel, model, and optionally a template or a record.The
Recordis returned from a collectionBufferor is added to an exportingBuffer.When adding elements to a
Record, theRecordshould match aTemplate. If the process is collecting, theRecordshould match the Internal Template. For an Exporting process, theRecordshould match the External Template, and there should be oneRecordfor each External Template. ARecordcan not contain more Information Elements than it’s associated template. Information Elements should be added to theRecordin the same order as theTemplate.If a template is given to the constructor, all Information Elements that exist in the template are added to the
Recordin the same order as they exist in the Template. The record argument is ignored.If a record is given, all Information Elements that exist in the record are added to the
Recordin the same order as they exist in the record.One element must exist in the
Recordbefore exporting any data.A
Recordmaintains internal dictionaries for the elements that it contains. For this reason, if a template contains more than 1 of the same Information Element, elements must be added using theadd_elementmethod in order to give alternate key names to elements that are the same.A
Recordmay also be accessed similar to a list.- add_element(key_name: str[, type: DataType = DataType.OCTET_ARRAY[, element_name: str = None[, length: int = 0]]])¶
Appends a field named key_name to this
Record, where key_name will be used to get or set the value of an Information Element.The
InfoElementmay be specified in three ways: The key_name may match the name of anInfoElementin theInfoModel, the element_name may name theInfoElement, or the type may be specified asBASICLIST,SUBTEMPLATELIST,SUBTEMPLATEMULTILIST, orVARLENfor octetArray.When the
Recordcontains duplicate Information Elements, the key_name should be unique to ease reference to the elements and theInfoElementshould be specified using the element_name or type parameters.The length parameter specifies the reduced-length encoding length for the Information Element, similar to the
lengthattribute ofInfoElementSpec. This may only be applied to certain data types and must be smaller than the default length. When 0, the default length specified by theInfoModelis used.When type is
BASICLIST, the element_name parameter is used as the content type for the elements in the basicList. Seeinit_basic_listand theBLconstructor.Elements must be added in the same order as they exist in the template.
Examples:
>>> my_rec = pyfixbuf.Record(model) >>> my_rec.add_element("sourceTransportPort") >>> my_rec.add_element("sourceTransportPort2", 0, "sourceTransportPort") >>> my_rec.add_element("basicList") >>> my_rec.add_element("basicList2", BASICLIST) >>> my_rec.add_element("octetTotalCount", length=4)
In the above example, an empty
Recordwas created. The corresponding template to the aboveRecordwould look something like:>>> tmpl = Template(model) >>> tmpl.add_spec_list([ ... pyfixbuf.InfoElementSpec("sourceTransportPort"), ... pyfixbuf.InfoElementSpec("sourceTransportPort"), ... pyfixbuf.InfoElementSpec("basicList"), ... pyfixbuf.InfoElementSpec("basicList"), ... pyfixbuf.InfoElementSpec("octetTotalCount", 4)])
As you can see, we have two sourceTransportPort elements and two basicList elements. A basicList is a list of one or more of the same Information Element. The Information Element in the basicList does not have to be initialized until data is added to the
Record.Since we have two sourceTransportPort fields, we must give a key_name to one of the elements, in this case, sourceTransport2. Since sourceTransportPort2 is not a defined Information Element in the Information Model, the element_name must be given to the method.
Similarly, in order to access the dictionary of elements in the
Record, we had to give the second basicList a key_name, basicList2. Since basicList2 is not a defined Information Element, it needs to be given the type,BASICLIST. Since type is not 0, it does not need an element_name.
- add_element_list(name_list: Iterable[str])¶
Treats each string in name_list as the name of an
InfoElementand appends that information element to theRecord. See the above methodadd_element.
- clear_all_lists()¶
Clears all the lists in the top level of the
Record.Any nested lists must be accessed and cleared manually.
- clear()¶
Clears any memory allocated for the
Record.
- init_basic_list(basic_list_key: str[, count: int = 0[, element_name: str = None]])¶
Initializes a basicList for export with the given basic_list_key name to a list of count elements. If a name is not given to the element_name keyword, it assumes the basic_list_key is a valid Information Element Name.
Examples:
>>> my_rec.add_element("bL", BASICLIST, "octetTotalCount") >>> my_rec.add_element("basicList") >>> my_rec.add_element("basicList2", BASICLIST) >>> my_rec.init_basic_list("bL", 4) >>> my_rec.init_basic_list("basicList", 3, "destinationTransportPort") >>> my_rec.init_basic_list("basicList2", 2, "souceIPv4Address")
In the above example, we have initialized three basicLists. The first initializes a basicList of octetTotalCounts by adding the element as as basicList to the record. Later we initialize the basicList to 4 items. The second does the initialization of the type, destintationTransportPort, when calling
init_basic_listas opposed to the first, which is done when the basicList is added to the record. The third, basicList2, is initialized to two sourceIPv4Addresses.It is perfectly acceptable to initialize a list to 0 elements. All basicLists in the
Recordmust be initialized before appending theRecordto theBuffer.A basicList may be initialized via this method, or by using the
BLand setting the basicList element in theRecordto theBL.
- clear_basic_list(basic_list_key: str)¶
Clears the basicList on this
Recordidentified by basic_list_key, freeing any memory allocated for the list. This should be called after theRecordhas been appended to theBuffer. Does nothing if the type of the field identified by basic_list_key is notDataType.BASIC_LIST, but does raisesKeyErrorif basic_list_key is not known on thisRecord.
- __getitem__(key: Union[str, int]) Any¶
Implements the evaluation of
record[key]forRecordinstances: Returns the value of the element with the given key.If key is a string, it may the name of an
InfoElementor the key_name specified to theadd_elementmethod. key may also be an integer corresponding to the positional index in theRecord.Raises an
Exceptionwhen key is not in theRecord. Usegetfor a similar function that does not raise an Exception. See alsoget_field.The return type depends on the Information Element type which was defined when initializing the
InfoElement.Element Type
Return Type
UINT*, INT*
long
FLOAT*
float
MILLISECONDS, MICROSECONDS
long
NANOSECONDS, SECONDS
long
OCTET_ARRAY
bytearray
BASICLIST
STRING
string
IP (v4 or v6)
ipaddress object
MAC_ADDR
MAC Address String xx:xx:xx:xx:xx:xx
SUBTEMPLATELIST
SUBTEMPLATEMULTILIST
Default (Undefined Type)
bytearray
Example:
>>> rec <pyfixbuf.Record object at 0x10d0f49f0> >>> rec['protocolIdentifier'] 6 >>> rec[1] 80 >>> rec.template[1].name 'sourceTransportPort'
- __setitem__(key: Union[str, int], value: Any)¶
Implements assignment to
record[key]forRecordinstances: Sets the value of the element having the given key to value.If key is a string, it may the name of an
InfoElementor the key_name specified to theadd_elementmethod. key may also be an integer corresponding to the positional index in theRecord.
- is_list(key: str) bool¶
Returns
TrueorFalsedepending on the type of the given key. RaisesKeyErrorwhen key is not on thisRecord.
- get(key: str, default: Any = None) Any¶
Returns
record[key]if key exists on thisRecord; otherwise returns default.
- get_field(key: str) Record.Field¶
Returns a
Record.Fieldobject for key on thisRecord. RaisesKeyErrorwhen key is not present.
- get_stl_list_entry(key: str) STL¶
Gets the subTemplateList from this
Recordwith the given key and returns a newly allocatedSTL. ReturnsNoneif the type of key is notDataType.SUB_TMPL_LIST. RaisesKeyErrorif key is not a known key on thisRecord.A
STLmay also be accessed by using__getitem__.
- get_stml_list_entry(key: str) STML¶
Gets the subTemplateMultiList from this
Recordwith the given key and returns a newly allocatedSTML. ReturnsNoneif the type of key is notDataType.SUB_TMPL_MULTI_LIST. RaisesKeyErrorif key is not a known key on thisRecord.A
STMLmay also be retrieved by using__getitem__.
- as_dict() Dict[Union[str, Tuple(str, int)], Any]¶
Returns a
dictthat represents theRecord.The keys of the dictionary are normally strings, but if the
Record’sTemplatecontains duplicate aInfoElement, the key for the second such element is a couple containing the name and theint1, the third would be the name and theint2, et cetera.
- __len__() int¶
Implements the built-in len() method for
Recordinstances: Returns the number of elements in theRecord.
- __contains__(item: str) bool¶
Implements the
inoperator forRecordinstances: Tests whetheradd_elementwas called with a key_name that is equal to element. If theRecordwas initialized with aTemplate, tests whether theTemplateincluded anInfoElementhaving the name element.Example:
>>> rec <pyfixbuf.Record object at 0x10d0f49f0> >>> 'protocolIdentifier' in rec True
- set_template(template: Template)¶
If this
Recordwas not initialized with aTemplate, this method may be used to set theRecord’sTemplate. ARecordmust have aTemplateassociated with it when assigning aRecordto a subTemplateList element.Examples:
>>> tmpl = pyfixbuf.Template(model) >>> tmpl.add_spec_list([ ... pyfixbuf.InfoElementSpec("sourceTransportPort"), ... pyfixbuf.InfoElementSpec("destinationTransportPort")] >>> my_rec = pyfixbuf.Record(model) >>> my_rec.add_element("sourceTransportPort", "destinationTransportPort") >>> my_rec["sourceTransportPort"] = 13 >>> my_rec["destinationTransportPort"] = 15 >>> my_rec.set_template(tmpl) >>> other_rec["subTemplateList"] = [my_rec]
- __iter__() Iterator[Any]¶
Implements the method to return an Iterator over the values in the
Record. See alsoiterfields.Example:
>>> for value in record: ... print(value)
- iterfields() Iterator[Record.Field]¶
Returns an Iterator over the
Record’s values where each iteration returns aRecord.Fieldobject. To get aRecord.Fieldfor a single field, useget_field.Example:
>>> for field in record.iterfields(): ... print(field.ie.name, DataType.get_name(field.ie.type), field.value) ...
- matches_template(template: Template, exact: bool = False) bool¶
Returns
Trueif thisRecordmatchesTemplateusing the checks specified bycheck_template. ReturnsFalseotherwise.
- count(element_name: str) int¶
Counts the occurrences of the element_name in the
Record.Examples:
>>> rec.add_element_list(["basicList", "basicList", "basicList"]) >>> rec.count("basicList") 3 >>> rec.count("sourceTransportPort") 0
- template : Template
Returns the
Templateused by thisRecord.
Record.Field¶
- class Record.Field(name: str, instance: int, ie: InfoElement, length: int, value: Any)¶
Represents a complete value field in a
Record, and is implemented as a subclass ofcollection.namedtuple. This is the type of object returned by theRecord.iterfieldsmethod. ARecord.Fieldobject includes the following attributes:- name : str
The field name provided as the key parameter to
Record.add_element. For aRecordbuilt from aTemplate, this is the name is theInfoElement.
- instance : int
An integer that is non-zero when
nameis not unique. The value represents the number of timesnameoccurs in theRecordbefore this one.
- ie : InfoElement
The canonical
InfoElementthat describes this value.
- length : int
The length of this field specified to
Record.add_elementor in theInfoElementSpecassociated with theRecord‘sTemplate. May be different than the length specified in theInfoElementdue to reduced length encoding.
- value : Any
The value of this field.
Template¶
The Template type implements an IPFIX Template or an IPFIX Options
Template. IPFIX templates contain one or more Information Elements
(InfoElement).
If a certain sequence of elements is desired, each Information Element
(InfoElementSpec) must be added to the template in the desired
order. Templates are stored by Template ID and type (internal, external)
per domain in a Session. The valid range of Template IDs is
256 to 65535. Templates are given a template ID when they are added to
a Session. The only difference between Data Templates and Options
Templates is that Options Templates have a scope associated with them,
which gives the context of reported Information Elements in the Data
Records.
An Internal Template is how fixbuf decides what the data should look
like when it is transcoded. For this reason, an internal template should
match the corresponding Record, in terms of the order of Information
Elements. An External Template is sent before
the exported data so that the Collecting Process is able to process
IPFIX messages without necessarily knowing the interpretation of all data
records.
- class pyfixbuf.Template(model: InfoModel[, type: bool = False])¶
Creates a new Template using the given model, an
InfoModel. An IPFIX Template is an ordered list of the Information Elements that are to be collected or exported. For export, the order of Information Elements in the Templates determines how the data will be exported.If type is given, an Information Element Type Information Options Template will be created. The appropriate elements will automatically be added to the template and the scope will be sent. See RFC 5610 for more information.
Once a Template has been added to a
Session, it cannot be altered.A
Templatecan be accessed like a dictionary or a list to retrieve a specificInfoElementSpec.An Information Model (
InfoModel) is needed to allocate and initialize a new Template.- add_spec(spec: InfoElementSpec)¶
Appends a given
InfoElementSpecspec to the Template.Once the Template has been added to a
Session, it cannot be altered.
- add_spec_list(specs: Iterable[InfoElementSpec])¶
Appends each of the
InfoElementSpecitems in specs to theTemplate.Once the
Templatehas been added to theSession, it can not be altered.
- add_element(name: str)¶
Appends an Information Element with the given name to this
Template. This function may be used as an alternative toadd_spec.This function creates an
InfoElementSpecwith the given element name and default length and adds it to the Template.Once the Template has been added to the
Session, it can not be altered.
- get_indexed_ie(index: int) InfoElement¶
Returns the
InfoElementat the given positional index in theTemplate. Unlike the__getitem__method which returns theInfoElementSpec, this method returns theInfoElementat a particular index.
- get_context() Any¶
Returns the
Template’s context object as set by the callables registered with theSession.add_template_callbackfunction.
- __contains__(element: Union[InfoElement, InfoElementSpec, str, int]) bool¶
Implements the
inoperator forTemplateinstances: Tests whether element is in theTemplate.If element is an
int, returnTrueif it is non-negative and less than the length of theTemplate.If element is a
str, returnTrueif an Information Element with the name element is included in theTemplate.If element is an
InfoElementorInfoElementSpec, returnTrueif the element exists in theTemplate,Falseotherwise.Examples:
>>> t = Template(InfoModel()) >>> t.add_element("protocolIdentifier") >>> "protocolIdentifier" in t True >>> InfoElementSpec("protocolIdentifier") in t True
- __getitem__(key: Union[str, int]) InfoElementSpec¶
Implements the evaluation of
template[key]forTemplateinstances: Returns theInfoElementSpecrepresented by key.If key is an
int, it is treated as a positional index and anIndexErrorexception is raised when it is out of range.If key is a
str, it is treated as the name of theInfoElementSpecto find andKeyErrorException is raised when key is not the name of anInfoElementSpecon theTemplate. If anInfoElementSpecis repeated in theTemplate, querying by name always returns the first element.Any other type for key raises a
TypeError.Examples:
>>> t = Template(InfoModel()) >>> t.add_element("protocolIdentifier") >>> t[0] <pyfixbuf.InfoElementSpec object at 0x107a0fc00> >>> t["protocolIdentifier"] <pyfixbuf.InfoElementSpec object at 0x107a0fc00>
- __len__() int¶
Implements the built-in len() method for
Templateinstances: Returns the number ofInfoElementSpecobjects in theTemplate.Examples:
>>> t = Template(InfoModel()) >>> t.add_element("protocolIdentifier") >>> len(t) 1
- __iter__() Iterator[InfoElementSpec]¶
Implements the method to return an Iterator over the
InfoElementSpecobjects in thisTemplate. See alsoie_iter.
- ie_iter() Iterator[InfoElement]¶
Returns an Iterator over the
InfoElementobjects in thisTemplate. See also__iter__.Example:
>>> for ie in template: ... print(ie.name, DataType.get_name(ie.type)) ...
- scope : int
Returns the scope associated with the
Template. Setting scope to zero sets the scope to encompass the entire template. Setting the scope toNoneremoves the scope.
- template_id : int
Returns the template ID associated with the
Template. Template ID can only be changed by adding the template to aSession.
- type : bool
Returns
Trueif template is an Information Element Type Information Template. ReturnsFalseotherwise. This attribute may not be changed.
- infomodel : InfoModel
Returns the
InfoModelassociated with the Template. This attribute may not be changed.
- read_only : bool
Returns
Trueif this template has been added to aSession. This attribute may not be set.
Examples:
>>> tmpl = pyfixbuf.Template(model)
>>> spec = pyfixbuf.InfoElementSpec("sourceTransportPort")
>>> spec2 = pyfixbuf.InfoElementSpec("destinationTransportPort")
>>> tmpl.add_spec(spec)
>>> tmpl.add_spec(spec2)
>>> tmpl2 = pyfixbuf.Template(model)
>>> tmpl2.add_spec_list([pyfixbuf.InfoElementSpec("fooname"),
pyfixbuf.InfoElementSpec("barname")])
>>> tmpl2.scope = 2
>>> if "sourceTransportPort" in tmpl:
>>> print "yes"
yes
BL¶
A basicList is a list of zero or more instances of an Information Element. Examples include a list of port numbers, or a list of host names. The BL object acts similar to a Python list with additional attributes.
- class pyfixbuf.BL(model: InfoModel, element: Union[InfoElement, InfoElementSpec, str][, count: int = 0[, semantic: int = 0]])¶
A
BLrepresents a basicList.A basicList is a list of zero or more instances of an Information Element.
A basicList can be initialized through a
Recordviainit_basic_listor by creating aBLobject.The constructor requires an
InfoModelmodel, and aInfoElementSpec,InfoElement, or string element. Additionally, it takes an optional integer count which represents the number of elements in the list, and an optional integer semantic to express the relationship among the list items.All basicLists in a
Recordmust be initialized (even to 0) before appending aRecordto aBuffer.Examples:
>>> rec.add_element("basicList", BASICLIST) >>> rec.add_element("basicList2", BASICLIST) >>> bl = BL(model, "sourceTransportPort", 2) >>> bl[0] = 80 >>> bl[1] = 23 >>> rec["basicList"] = bl >>> rec.init_basic_list("basicList2", 4, "octetTotalCount") >>> rec["basicList2"] = [99, 101, 104, 23]
- __len__() int¶
Implements the built-in len() method for
BLinstances: Returns the number of entries in the basicList.Example:
>>> bl = BL(model, "sourceTransportPort", 5) >>> len(bl) 5
- __iter__() Iterator[Any]¶
Implements the method to return an Iterator over the items in the
BL.Example:
>>> bl = record['basicList'] >>> bl.element.name 'httpContentType' >>> for v in bl: ... print(v) ... 'text/xml' 'text/plain'
- __getitem__(index: int) Any¶
Implements the evaluation of
bl[index]forBLinstances: Returns the value at position index in the basicList.Example:
>>> bl = record['basicList'] >>> bl.element.name 'httpContentType' >>> print(bl[0]) 'text/xml'
- __setitem__(key: int, value: Any)¶
Implements assignment to
bl[index]forBLinstances: Sets the value at position index in the basicList to value.
- copy(other: Iterable[Any])¶
Copies the items in the list other to this
BL, stopping when other is exhausted or the length of theBLis reached.Raises
TypeErrorwhen other does not support iteration.
- __contains__(item: Any) bool¶
Implements the
inoperator forBLinstances: Tests whether thisBLcontains an element whose value is item.Example:
>>> bl = record['basicList'] >>> bl.element.name 'httpContentType' >>> 'text/plain' in bl True
- __str__() str¶
Return str(self).
- __eq__(other: list) bool¶
Determines whether other is equal to this
BL.Returns
Truewhen other and this basicList contain the same elements in the same order. ReturnsFalseotherwise. RaisesTypeErrorwhen other does not support iteration.Example:
>>> bl = record['basicList'] >>> bl.element.name 'httpContentType' >>> bl == ['text/xml', 'text/plain'] True
- clear()¶
Clears and frees the basicList data.
- semantic : int
The structured data semantic value for this
BL.
- element : InfoElement
The
InfoElementassociated with thisBLthat was set when the class:!BL was created. This attribute may not be changed.
Decoding Examples:
>>> bl = rec["basicList"]
>>> for items in bl:
... print str(items) + '\n'
... bl.clear()
Encoding Examples:
>>> bl = BL(model, "httpUserAgent", 2)
>>> bl[0] = "Mozilla/Firefox"
>>> bl[1] = "Safari5.0"
>>> rec["basicList"] = bl
>>> if "Safari5.0" in bl:
... print "Apple"
Apple
>>> print bl
["Mozilla/Firefox", "Safari5.0"]
STL¶
A subTemplateList is a list of zero or more instances of a
structured data type where each entry corresponds to a
single template. Since a single template is associated
with an STL, a Record must also be associated with the
STL. Access each entry (a Record) in the list by
iterating through the STL.
- class pyfixbuf.STL([record: Record = None, key_name: str = None])¶
A
STLrepresents a subTemplateList.If record, a
Recordobject, and key_name, a string, are provided, the subTemplateList for key_name in the given record is initialized, otherwise a genericSTLis initialized. Eventually aTemplatemust be associated with theSTLfor encoding.For decoding, a
Recordmust be associated with theSTL.- __contains__(name: str) bool¶
Implements the
inoperator forSTLinstances: Tests whether theTemplateassociated with thisSTLcontains anInfoElementhaving the name name.
- entry_init(record: Record, template: Template[, count: int = 0])¶
Initializes the
STLto count entries of the givenRecordandTemplate.This method should only be used to export a
STL.Each
STLshould be initialized before appending theRecordto theBuffereven if it is initialized to 0.Raises an
Exceptionwhen template has a template_id of 0. You should add the template to aSessionbefore using it for theSTL.The record that contains the
STLshould not be modified after calling entry_init().
- __iter__() Iterator[Record]¶
Implements the method to return an Iterator over the
Recordobjects in theSTL.Example:
>>> for record in stl: ... print(record.as_dict())
- iter_records(tmpl_id: int = 0) Iterator[Records]¶
Returns an Iterator over the
STL‘s records, including records in any nestedSTMLorSTL. If a template ID is passed, returns an iterator over all theRecordobjects with a template ID matching the passed value.Example:
>>> for record in stl.iter_records(): ... print(record.template.template_id) ...
- clear()¶
Clears all entries in the list. Nested elements should be accessed and freed before calling this method. Frees any memory previously allocated for the list.
- __getitem__(item: Union[int, str]) Any¶
Implements the evaluation of
stl[item]forSTLinstances:If item is an
int, returns theRecordat that positional index.If item is a
str, finds theInfoElementwith the name item in theSTL’sTemplateand returns the value for that element in the most recently accessedRecordin theSTL.Returns
Noneif item has an unexpected type.
- __setitem__(key: int, value: Record)¶
Implements assignment to
stl[index]forSTLinstances: Sets theRecordat position index in thisSTLto value.If this
STLwas not previously initialized viaentry_init, it is initialized with the givenRecord’sTemplateand a count of 1.
- __len__() int¶
Implements the built-in len() method for
STLinstances: Returns the number ofRecordobjects in theSTL.
- template_id : int
The template ID of the
Templateused for thisSTL.
- semantic : int
The structured data semantic value for this
STL.
Decoding Examples:
>>> stl = rec["dnsList"]
>>> stl.set_record(dnsRecord)
>>> for dnsRecord in stl:
... dnsRecord = dnsRecord.as_dict()
... for key,value in dnsRecord.items():
... print key + ": " + str(value) + '\n'
... stl.clear()
Encoding Examples:
>>> stl = STL()
>>> stl.entry_init(dnsRecord, dnsTemplate, 2)
>>> dnsRecord["dnsName"] = "google.com"
>>> dnsRecord["rrType"] = 1
>>> stl[0] = dnsRecord
>>> dnsRecord["dnsName"] = "ns.google.com"
>>> dnsRecord["rrType"] = 2
>>> stl[1] = dnsRecord
>>> rec["subTemplateList"] = stl
STML¶
A subTemplateMultiList is a list of zero or more instances of
a structured data record, where the data records do not necessarily
have to reference the same template. A subTemplateMultiList is made
up of one or more STMLEntry objects. Each STMLEntry in the
STML typically has a different template associated with it, but that
is not a requirement. The data in the STML is accessed by iterating
through each STMLEntry in the list and setting a Record on
the STMLEntry.
- class pyfixbuf.STML([record: Record = None[, key_name:str = None[, type_count: int = -1]]])¶
A
STMLobject represents a subTemplateMultiList.If a
Recordobject, record, and key_name, a string, are provided, theSTMLobject with key_name will be initialized in the givenRecord. It is only necessary to initialize and give a type_count if the subTemplateMultiList will be exported. All subTemplateMultiLists in an exportedRecordmust be initialized. It is acceptable to initialize an STML to 0 list entries.A
STMLmust be initialized with record and key_name OR a type_count. This object can be used to set a subTemplateMultiList element in aRecord.The subTemplateMultiList is initialized to
Noneunless it is given a type_count, in which case it will intialize the list and allocate memory in the given record.type_count is the number of different templates that the
STMLwill contain. For example, if you plan to have an STML with entries of type Template ID 999 and 888, type_count would be 2. type_count would also be 2 even if both instances will use Template ID 999.Examples:
>>> stml = my_rec["subTemplateMultiList"] # sufficient for collection >>> stml = pyfixbuf.STML(rec, "subTemplateMultiList", 3) # STML with 3 entries for export >>> stml = pyfixbuf.STML(type_count=2) >>> stml = [record1, record2] >>> stml2 = pyfixbuf.STML(type_count=3) >>> stml2[0] = [record1, record2] >>> stml2[1][0] = record3 >>> stml2[2].entry_init(record3, tmpl3, 0) #all entries must be init'd - even to 0. >>> rec["subTemplateMultiList"] = stml
- clear()¶
Clears the entries in the subTemplateMultiList and frees any memory allocated.
- __iter__() Iterator[STMLEntry]¶
Implements the method to return an Iterator over the
STMLEntryobjects in theSTML.Example:
>>> for entry in stml: ... for record in entry: ... print(record.as_dict())
- iter_records(tmpl_id: int = 0) Iterator[Records]¶
Returns an Iterator over the
STML’s records, including records in any nestedSTMLorSTL. If a template ID is passed, returns an iterator over all theRecordobjects with a template ID matching the passed value.Example:
>>> for record in stml.iter_records(): ... print(record.template.template_id) ...
- __len__() int¶
Implements the built-in len() method for
STMLinstances: Returns the number ofSTMLEntryobjects in theSTML.
- __contains__(name: str) bool¶
Implements the
inoperator forSTMLinstances: Tests whether theTemplateused by the firstSTMLEntryin thisSTMLcontains anInfoElementhaving the name name.
- __getitem__(index: int) STMLEntry¶
Implements the evaluation of
stml[index]forSTMLinstances: Returns theSTMLEntryat position index.Examples:
>>> entry = stml[0] >>> stml[0].entry_init[record, template, 3]
- __setitem__(key: int, value: Iterable[Record])¶
Implements assignment to
stml[index]forSTMLinstances: Sets theSTMLEntryat position index in theSTMLto the list ofRecordobjects in value. value must be a list. AllRecordsin the list should have the same :class:Template.Examples:
>>> stml[0] = [rec1, rec2, rec3, rec4]
- semantic : int
The structured data semantic value for this
STML.
Decode Examples:
>>> stml = my_rec["subTemplateMultiList"]
>>> for entry in stml:
... if "tcpSequenceNumber" in entry:
... entry.set_record(tcprec)
... for tcp_record in entry:
... tcp_record = tcp_record.as_dict()
... for key,value in tcp_record.items()
... print key + ": " + str(value) + '\n'
Encode Examples:
>>> stml = STML(type_count=3)
>>> stml.entry_init(rec, template, 2) #init first entry to 2 with template
>>> rec["sourceTransportPort"] = 3
>>> rec["destinationTransportPort"] = 5
>>> stml[0][0] = rec
>>> rec["sourceTransportPort"] = 6
>>> rec["destinationTransportPort"] = 7
>>> stml[0][1] = rec
>>> stml[1][0] = rec2 #init second entry to 1 item using rec2
>>> stml[2].entry_init(rec3, template3, 0) #init third entry to 0
STMLEntry¶
Each STML consists of one or more STMLEntry objects. Each
STMLEntry is associated with a Template, and therefore
should have a corresponding Record. An STMLEntry can
contain zero or more instances of the associated Record.
- class pyfixbuf.STMLEntry(stml: STML)¶
Creates an empty
STMLEntryand associates it to the givenSTML, stml. There should be oneSTMLEntryfor each differentTemplatein theSTML.Each
STMLEntryshould be initialized usingentry_initto associate aRecordandTemplatewith the entry.- entry_init(record: Record, template: Template[, count: int = 0])¶
Initializes the
STMLEntryto the givenRecord, record,Template, template, and count instances of the record it will contain.This should only be used for exporting a subTemplateMultiList. Entries in the
STMLmust all be initialized, even if it is initialized to 0. This method is not necessary if aRecordhas a template associated with it. The application can simply set theSTMLEntryto a list ofRecordobjects and theSTMLEntrywill automatically be initialized.Raises an
Exceptionwhen template has a template_id of 0. You should add the template to aSessionbefore using it for theSTMLEntry.Examples:
>>> stml = pyfixbuf.STML(my_rec, "subTemplateMultiList", 1) >>> stml[0].entry_init(my_rec, template, 2) >>> my_rec["sourceTransportPort"] = 3 >>> stml[0][0] = my_rec >>> my_rec["sourceTransportPort"] = 5 >>> stml[0][1] = my_rec
- set_record(record: Record)¶
Sets the
Recordon theSTMLEntryto record in order to access its elements.
- __contains__(name: str) bool¶
Implements the
inoperator forSTMLEntryinstances: Tests whether theTemplateassociated with thisSTMLEntrycontains anInfoElementhaving the name name.Alternatively, you can access the
TemplateID associated with thisSTMLEntryto determine the type ofRecordthat should be used to access the elements.
- set_template(template: Template)¶
Assigns a
Templateto theSTMLEntry. TheTemplatemust be valid.This method may be used as an alternative to
entry_init. This is only required if theRecordthat will be assigned to theSTMLEntrywas not created with aTemplate. Using this method instead ofentry_initresults in only allocating one item for theSTMLEntry.Raises an
Exceptionwhen template has a template_id of 0. You should add the template to aSessionbefore using it for theSTMLEntry.
- __iter__() Iterator[Record]¶
Implements the method to return an Iterator over the
Recordobjects in theSTMLEntry.Example:
>>> for entry in stml: ... for record in entry: ... print(record.as_dict())
- __getitem__(item: Union[int, str]) Any¶
Implements the evaluation of
stmlEntry[item]forSTMLEntryinstances:If item is an
int, returns theRecordat that positional index.If item is a
str, finds theInfoElementwith the name item in theSTMLEntry’sTemplateand returns the value for that element in the firstRecordin theSTMLEntry.Returns
Noneif item has an unexpected type.
- __setitem__(key: int, value: Record)¶
Implements assignment to
stmlentry[index]forSTMLEntryinstances: Sets theRecordat position index in thisSTMLEntryto value.If this
STMLEntryhas not been previously initialized, it is initialized with theRecord’sTemplateand a length of 1.
Examples:
>>> stml = my_rec["subTemplateMultiList"]
>>> for entry in stml:
... if "tcpSequenceNumber" in entry:
... entry.set_record(tcp_rec)
... for tcp_record in entry:
... tcp_record = tcp_record.as_dict()
... for key,value in tcp_record.items():
... print key + ": " + str(value) + '\n'
... elif entry.template_id == 0xCE00:
... entry.set_record(dns_rec)
...
>>> stml.clear()
Buffer¶
The Buffer implements a transcoding IPFIX Message buffer for both
export and collection. The Buffer is one of the “core” interfaces
to the fixbuf library. Each Buffer must be initialized to do either
collecting or exporting.
- class pyfixbuf.Buffer([record: Record = None[, auto: bool = False]])¶
Creates an uninitialized
Buffer.The
Buffermust be initialized for collection or export usinginit_collectionorinit_exportprior to use.If auto is
Trueand theBufferis initialized for collection, aTemplateis automatically generated from the external template that is read from theCollector, the internal template on theBufferis set to that template, and a matchingRecordis created to match thatTemplate.Example:
>>> collector = Collector() >>> collector.init_file(sys.argv[1]) >>> session = Session(infomodel) >>> buffer = Buffer(auto=True) >>> buffer.init_collection(session, collector) >>> for record in buffer: >>> print(record.as_dict())
If record is specified, it is set as the
Buffer‘s cachedRecordfor use during collection. Theset_recordmethod may also be used to set the cachedRecord.There is no requirement to set a cached
Recordon theBuffersince theBuffercreates one as needed. The cachedRecordis used during collection when itsTemplatematches theBuffer‘s current internalTemplate. Callingset_internal_templatemay clear the cachedRecord.For export, the user may use
set_internal_templateandset_export_templateto specify the format of the record, and callappendto append aRecordto theBuffer.- init_collection(session: Session, collector: Collector)¶
Initializes the
Bufferfor collection given theSession, session, andCollector, collector.
- init_export(session: Session, exporter: Exporter)¶
Initializes the
Bufferfor Export given theSession, session, andExporter, exporter.
- set_internal_template(template_id: int)¶
Sets the internal
Templateto the one whose ID is template_id. TheBuffermust have an internal template set on it before collecting or exporting. Causes theBufferto discard the cachedRecordspecified in the call toset_recordor to the constructor if itsTemplatedoes not match that specified by template_id.
- set_export_template(template_id: int)¶
Sets the external
Templateto the one whose ID is template_id. TheBuffermust have an export template set before appending (append) aRecordto theBuffer. The exportTemplatedescribes how fixbuf will write the givenRecordto the output stream.
- next_record(record: Record) Record¶
Gets the next record on this
Bufferin the form of the givenRecord, record. ReturnsNoneif theBufferis empty. Raises an exception if an internal template is not set on theBufferor if record does not match the internal template.
- next([record: Record = None]) Record¶
Returns the next
Recordfrom thisBufferinitialized for collection. Raises aStopIterationException when there are no moreRecordobjects. RaisesExceptionif an internal template has not been set on theBuffer.
- __iter__() Iterator[Record]¶
Implements the method to return an Iterator over the
Recordobjects in thisBufferinitialized for collection.Example:
>>> for record in buffer: ... print(record.as_dict())
- set_record(record: Record)¶
Sets the cached
Recordon thisBufferto record. If record is associated with aTemplate(and thisBufferis initialized for collection or export), callsset_internal_templatewith the template_id of thatTemplate.
- next_template() Template¶
Retrieves the external
Templatethat will be used to read the nextRecordfrom thisBufferinitialized for collection. If no nextRecordis available, raisesStopIteration.If
ignore_optionsis True, skips options records and returns theTemplatefor the next non-optionsRecord.See also
get_template.
- get_template() Template¶
Retrieves the external
Templatethat was used to read the currentRecordfrom thisBufferinitialized for collection. If noRecordhas been read, returnsNone.See also
next_template.
- append(rec: Record[, length: int])¶
Appends the first argument, a
Record, to thisBufferinitialized for export. If a second argument, anintrepresenting a length, is given, appends only the first length number of bytes to theBuffer.An internal and external
Templatemust be set on theBufferprior to appending aRecord.
- write_ie_options_record(name: str, template: Template)¶
Appends an Information Element Type Information Record (RFC 5610) to this
Bufferinitialized for export. An Options Record is appended with information about the Information Element with the given name. template is the Information Element Type Options Template that was created by givingtype=Trueto theTemplateconstructor.
- auto_insert()¶
Tells this
Bufferintialized for collection to watch the stream for Information Element Option Records (RFC 5610) and automatically create and insert anInfoElementto theInfoModelfor each one seen. Information elements that have an enterprise number of 0 are ignored.
- ignore_options(ignore: bool)¶
Tells this
Bufferinitialized for collection how to handle Options Records.If ignore is set to
True, theBufferignores Options Templates and Records. By default, ignore isFalse, and theBufferreturns Options Records that the application must handle.The application may use
next_templateto retrieve theTemplateand determine if it is an Options Template.
- free()¶
Frees the
Buffer. This method may be invoked when using aBufferfor export to flush and close the stream.
Examples:
>>> buf = pyfixbuf.Buffer(my_rec)
>>> buf.init_collection(session, collector)
>>> buf.set_internal_template(999)
>>> for data in buf:
... data = data.as_dict()
... for key,value in data.items()
... print key + ":" + str(value) + '\n'
Examples:
>>> buf = pyfixbuf.Buffer(my_rec)
>>> buf.init_export(session, exporter)
>>> buf.set_internal_template(999)
>>> buf.set_external_template(999)
>>> session.export_templates()
>>> while count < 10:
... my_rec['sourceIPv4Address'] = "192.168.3.2"
... my_rec['destinationIPv4Address'] = "192.168.4.5"
... buf.append(my_rec)
>>> buf.emit()
Examples:
>> buf = pyfixbuf.Buffer(auto=True)
>> buf.init_collection(session, collector)
>> for data in buf:
... data = data.as_dict()
... for key,value in data.items()
... print key + ":" + str(value) + '\n'
Session¶
The state of an IPFIX Transport Session is maintained in the Session
object. This includes all IPFIX Message Sequence Number tracking, and
internal and external template management. A Session is associated
with an InfoModel. Template instances must be added before
collecting (via a Collector or Listener) or exporting (see
Exporter) any data.
- class pyfixbuf.Session(model: InfoModel)¶
Creates an empty
Sessiongiven anInfoModel.- add_template(template: Template[, template_id: int = 0]) int¶
Adds the given
Templatetemplate to theSessionwith the optional template_id. This template may be used as both an internal and an external template. Useadd_internal_templateoradd_external_templateto be more selective on template usage.If a template_id is not given or 0, libfixbuf automatically chooses an unused template ID. template_id is used for representing both the internal and external template. The valid range for template_id is 256 to 65535 (0x100 to 0xffff).
When template_id is specified and it is already in use by the
Session, template replaces thoseTemplate(s).Returns the template ID of the added template.
- add_internal_template(template: Template[, template_id: int = 0]) int¶
Adds the given template as an internal template to the session with the optionally given template_id. An internal template determines how the data is presented when transcoded. See also
add_template.If template_id is not set or 0, libfixbuf will automatically choose an unused value.
Returns the template ID of the added
Template.
- add_external_template(template: Template[, template_id: int = 0]) int¶
Adds the given template as an external template to the session with the optionally given template_id. An external template is used when exporting IPFIX data. (libfixbuf automatically creates external templates when collecting IPFIX.) See also
add_template.If template_id is not set or 0, libfixbuf will automatically choose an unused value.
Returns the template ID of the added
Template.
- decode_only(id_list: Iterable[int])¶
When decoding, causes this
Sessionto ignore a record in a subTemplateList (STL) or subTemplateMultiList (STML) unless the record has a template ID in the given id_list ofints. The method is only used when theSessionis bound to aCollectororListener.This method has no effect on records that are not in a subTemplateList or subTemplateMultiList. See also
ignore_templates.
- ignore_templates(id_list: Iterable[int])¶
When decoding, causes this
Sessionto ignore a record in a subTemplateList (STL) or subTemplateMultiList (STML) when the record has a template ID in the given id_list ofints. The method is only used when theSessionis bound to aCollectororListener.This method has no effect on records that are not in a subTemplateList or subTemplateMultiList. See also
decode_only.
- add_template_pair(external_template_id: int, internal_template_id: int)¶
Specifies how to transcode data within structured data (a list).
That is, tells a
CollectororListenerthat data in aSTMLorSTLwhoseTemplateis external_template_id is to be transcoded into theTemplategiven by internal_template_id.By default, libfixbuf transcodes each entry in the
STMLorSTLwith the external template it received, requiring the collector to free or clear any memory allocated for the list elements. The collector can change this behavior by adding a “template pair.” For each entry in the STL or STML, if the entry has the given external_template_id, it will use the given internal_template_id to transcode the record. The internal_template_id must reference an internal template that was previously added to theSession. If internal_template_id is 0, the entry will not be transcoded and will be ignored by libfixbuf.Once a template pair has been added - the default is to ONLY decode entries that have an external_template_id in this template pair table. Therefore, any entries in a STML or STL that reference a template id not in this table will be dropped.
- export_templates()¶
Exports the templates associated with this
Session. This is necessary for an exporting session (seeExporter) and must be called before any records are appended to theBuffer.Buffermust already have aSessionassociated with it usingBuffer.init_export.
- get_template(template_id: int[, internal: bool = False]) Template¶
Returns the
Templatewith the given template_id. By default, the external template is returned. Set internal toTrueto retrieve the internal template with the given template_id. The returnedTemplatemay not be modified.Raises an Exception if a
Templatewith the given template_id does not exist on theSession.
- add_template_callback(callback: Callable[[Session, Template, Any], Any])¶
Adds the callable callback to be called whenever a new external template is read from a
CollectororListener.Multiple callbacks may be added to a
Session. The callbacks may specify a context object that is stored with theTemplate.After setting the callback(s), when a new template is read the callbacks will be called in the order they are added, and each may modify the context object. After all callbacks are called, the
Template’s context object will be set to the result. ATemplate’s context may be retrieved viaTemplate.get_context.The callback must be a callable and it will be called with three arguments: session, template, and context. session is the
Sessionfrom which the callback was added. template is the newTemplateand will have its template_id property set to the external template ID.The context argument is the current object that is to be stored as the Template’s context. The callback should either return a new object to use as the context or
None. A return value ofNoneindicates that the context object should not change.To avoid undefined behavior, the callback functions should be added before the
Sessionis bound to aBuffer.
- domain : int
The observation domain on the
Session.
Examples:
>>> session = pyfixbuf.Session(model)
>>> session.add_internal_template(289, tmpl)
>>> auto_id = session.add_external_template(0, tmpl)
>>> session.decode_only([256, 257])
Collector¶
An Collector maintains the necessary information for the connection
to a corresponding Exporting Process. A Collector is used for
reading from an IPFIX file. See Listener for collecting IPFIX over a
network.
- class pyfixbuf.Collector¶
Creates an uninitialized
Collector. An IPFIX Collector manages the file it is reading from. Initialize the collector usinginit_file.
Examples:
>>> collector = pyfixbuf.Collector()
>>> collector.init_file("path/to/in.ipfix")
Exporter¶
An Exporter maintains the information needed for its connection to a
corresponding Collecting Process. An Exporter may be created to
write to IPFIX files or to connect via the network using one of the supported
IPFIX transport protocols.
- class pyfixbuf.Exporter¶
Creates an empty
Exporter. Initialize the exporter usinginit_fileorinit_net.- init_net(hostname: str[, transport: str = "tcp"[, port: int = 4739]])¶
Initializes the
Exporterto write to the given hostname, port over the given transport.Given hostname may be a hostname or IP address.
Acceptable values for transport are
"tcp"and"udp". Default is"tcp".Given port must be greater than 1024. Default is 4739.
Examples:
>>> exporter = pyfixbuf.Exporter()
>>> exporter.init_file("/path/to/out.ipfix")
>>> exporter2 = pyfixbuf.Exporter()
>>> exporter2.init_net("localhost", "udp", 18000)
Listener¶
The Listener manages the passive collection used to listen for
connections from Exporting Processes.
- class pyfixbuf.Listener(session: Session, hostname: str[, transport: str = "tcp"[, port: int = 4739]])¶
Creates a
Listenergiven the session, hostname, transport, and port.session must be a valid instance of
Session.hostname is a string containing the address to bind to, a hostname or an IP Address. If hostname is
None, all addresses are used.transport is the transport protocol; it may contain
"tcp"(the default)"udp", or"sctp". (Using"sctp"raises an exception unless libfixbuf has been compiled with SCTP support.)port is the port number to listen on, and it must not be less than 1024. The default is 4739.
Examples:
>>> listener = Listener(session, hostname="localhost", port=18000)
- wait([record: Record = None]) Buffer¶
Waits for a connection on the set host and port. Once a connection is made, returns a newly allocated
Buffer.If a record is given to
waitthen the returnedBufferwill already be associated with aRecord.If no record is given, you must use
set_recordon theBufferbefore accessing the elements.After receiving the
Bufferyou must set the internal template on the returnedBufferusingset_internal_templatebefore accessing the data.Examples:
>>> buf = listener.wait() >>> buf.set_record(my_rec) >>> buf.set_internal_template(999) >>> for data in buf: >>> ...
InfoModel¶
The InfoModel type implements an IPFIX Information Model
(RFC 7012) which holds the known Information Elements
(InfoElement).
libfixbuf adds, by default, the IANA managed Information Elements to the Information Model. IANA’s Information Elements have a enterprise number of 0; a non-zero enterprise number is called a private enterprise number (PEN).
To process data from YAF or super_mediator, enterprise-specific
information elements must be loaded into the information model. These
information elements use the CERT PEN, 6871. One may load all CERT defined
information elements into an InfoModel, model, by importing the
pyfixbuf.cert package and running
pyfixbuf.cert.add_elements_to_model with model as its argument.
There are two alternate ways to add those elements to an InfoModel:
Download the XML file that defines those elements and invoke the model’s
InfoModel.read_from_xml_filemethod.Invoke
InfoModel.add_element_liston the model and pass it one of thepyfixbuf.yaflistsvariables.
- class pyfixbuf.InfoModel¶
An IPFIX Information Model stores all of the Information Elements (
InfoElement) that can be collected or exported by a Collecting or Exporting Process.The constructor creates a new Information Model and adds the default IANA-managed Information Elements.
- add_element(element: InfoElement)¶
Adds the given
InfoElementto theInfoModel.
- add_element_list(elements: Iterable[InfoElement]))¶
Adds each of the
InfoElementobjects in elements to theInfoModel.
- get_element_length(name: str[, type: int]) length¶
Returns the in-memory size of an
InfoElement.Specifically, searches the
InfoModelfor anInfoElementnamed name and if found, returns the length of a value of thatInfoElementwhen the value is part of an in-memoryRecord. If theInfoElementis of variable length or a list, returns the size of the data structure that holds the value within libfixbuf.However, if type is given and is one of
BASICLIST,SUBTEMPLATELIST, orSUBTEMPLATEMULTILIST, ignores name and returns the length of the list data structure within libfixbuf. Any other integer value for type is ignored.Raises
TypeErrorif name is not astror if type is given and is not anint. RaisesKeyErrorif name is not ignored and not the name of a knownInfoElement.
- get_element([name: str[, id: int[, ent: int]]]) InfoElement¶
Returns the
InfoElementgiven the name or id and ent. RaisesKeyErrorwhen the element is not found.Example:
>>> ie = model.get_element('protocolIdentifier') >>> ie.name 'protocolIdentifier' >>> ie = model.get_element(id = 4) >>> ie.name 'protocolIdentifier' >>> ie = m.get_element(id = 4, ent = CERT_PEN) Traceback ... KeyError: 'No element 6871/4'
- get_element_type(name: str) DataType¶
Returns the type of the Information Element as defined in the
InfoModelgiven theInfoElementname.
- add_options_element(rec: Record)¶
Adds the information element contained in the Options
Record. Use this method for incoming Options Records that contain Information Element Type Information.
- read_from_xml_data(xml_data: Any)¶
Adds to this
InfoModelthe Information Elements found in the XML data stored in xml_data, which is an object that supports the buffer call interface. See alsoread_from_xml_file.
- read_from_xml_file(filename: str)¶
Adds to this
InfoModelthe Information Elements found in the XML file in filename. See alsoread_from_xml_data.
Examples:
>>> model = pyfixbuf.InfoModel()
>>> model.add_element(foo);
>>> model.add_element_list([foo, bar, flo])
>>> model.add_element_list(pyfixbuf.yaflists.YAF_DNS_LIST) # adds all YAF DNS DPI elements
>>> length = model.get_element_length("sourceTransportPort")
>>> print length
2
InfoElement¶
An Information Element describes a single piece of data in a Template
and the Record it describes. An IPFIX Information Model
(InfoModel) holds all Information Elements. Each Information Element
consists of a unique and meaningful name, an enterprise number, a numeric
identifier, a length, and a data type (DataType). The enterprise
number is 0 for information elements defined by IANA. A non-zero enterprise
number is called a private enterprise number (PEN).
Giving an InfoElement an DataType allows Python to return
the appropriate type of object when the value is requested. Otherwise, the
value of the InfoElement is bytearray. If the type is
DataType.STRING or one of the list values, the IE length should be
VARLEN. InfoElements that have type DataType.OCTET_ARRAY may or
may not be variable length.
Units (Units), semantics (Semantic),
minimum value, maximum value, and description are all optional parameters to
further describe an information element. If the process is exporting
Information Element Type Option Records (RFC 5610), this information may
help the collecting process identify the type of information contained in the
value of an Information Element.
- class pyfixbuf.InfoElement(name: str, enterprise_number: int, id: int[, length: int = VARLEN[, reversible: bool = False[, endian: bool = False[, type: DataType = DataType.OCTET_ARRAY[, units: Units = Units.NONE[, min: int = 0[, max: int = 0[, semantic: Semantic = Semantic.DEFAULT[, description: str = None]]]]]]]]])¶
Creates a new Information Element (IE) using the given name, enterprise_number, and id, and optional length, reversible flag, endian flag, datatype, units, min, max, semantic, and description. An Information Element identifies a type of data to be stored and transmitted via IPFIX.
If no length is provided, the IE is defined as having a variable length. All Strings should be variable length.
If endian is
True, the IE is assumed to be an integer and will be converted to and from network byte order upon transcoding.If reversible is
True, a second IE is created for the same information in the reverse direction. (The reversed IE’s name is created by capitalizing the first character of name and prepending the stringreverse.)If type is set, pyfixbuf will know how to print values of this type. Otherwise the type of the element will be DataType.OCTET_ARRAY and it is returned as a Python
bytearray. The type may be aDataTypevalue or an integer.units optionally defines the units of an Information Element. See
Unitsfor the available units.min optionally defines the minimum value of an Information Element.
max optionally defines the maximum value of an Information Element.
semantic optionally defines the semantics of an Information Element. See
Semanticfor the known semantics.description optionally contains a human-readable description of an Information Element.
- name : str
The name, a string, associated with the InfoElement.
- enterprise_number : int
The Enterprise Number associated with the InfoElement. Default Information Elements have a enterprise number of 0.
enterprise_numberis a 32-bit unsigned integer (1–4,294,967,295).
- id : int
The Information Element ID that, with the enterprise number, uniquely identifies the Information Element.
idis an unsigned 15-bit integer (1–32767).
- length : int
The length of this Information Element as defined in the Information Model. The lengths of elements having
typeDataType.STRING, DataType.OCTET_ARRAY, and DataType.LIST are 65535 (VARLEN).
- type : DataType
The data type associated with the Information Element. The values are stored in the
DataTypeenumeration. If type is not defined, the default type is 0, DataType.OCTET_ARRAY. If the Information Element is defined as VARLEN, the default type is 14, DataType.STRING.
- units : Units
The units associated with the Information Element. The values are stored in the
Uintsenumeration. If units are not defined, the default is Units.NONE.
- min : int
If a range is defined with the Information Element, min is the minimum value accepted. Valid values are 0 - 2^64-1.
- max : int
If a range is defined for an Information Element, max is the maximum value accepted. Valid values are 0 - 2^64-1.
- semantic : Semantic
Semantic value for an Information Element. The values are stored in the
Semanticenumeration. The default semantic is 0, Semantic.DEFAULT.
- description : str
Description of an Information Element. This is a string. Default is None.
- reversible : bool
Trueif an Information Element is defined as reversible.
- endian : bool
Trueif an Information Element is defined as numeric value that should potentially be byte-swapped when transcoding to or from network byte order.
- as_dict() dict¶
Returns a dictionary of key value pairs suitable for use as keyword arguments to
InfoElement‘s constructor.
- ent : int
An alias for
enterprise_number.
Examples:
>>> foo = pyfixbuf.InfoElement('fooname', CERT_PEN, 722, units=pyfixbuf.Units.WORDS)
>>> bar = pyfixbuf.InfoElement('barname', 123, 565, 1, reversible=True, endian=True)
>>> foo2 = pyfixbuf.InfoElement('fooname2', 0, 888, 3, type=pyfixbuf.DataType.OCTET_ARRAY)
>>> flo = pyfixbuf.InfoElement('flo_element', 0, 452, 8, endian=True, type=8)
DataType¶
The DataType class holds the values for the IPFIX Information
Element Data Types defined by Section 3.1 of RFC 7012. This class may
not be instantiated, and all methods are static.
- class pyfixbuf.DataType¶
An enumeration containing the DataTypes supported by pyfixbuf.
In the following table, the RLE column indicates whether the type supports reduced length encoding.
Type
Integer Value
Length
RLE
Python Return Type
DataType.OCTET_ARRAY
0
VARLEN
Yes
bytearray
DataType.UINT8
1
1
No
int
DataType.UINT16
2
2
Yes
long
DataType.UINT32
3
4
Yes
long
DataType.UINT64
4
8
Yes
long
DataType.INT8
5
1
No
long
DataType.INT16
6
2
Yes
long
DataType.INT32
7
4
Yes
long
DataType.INT64
8
8
Yes
long
DataType.FLOAT32
9
4
No
float
DataType.FLOAT64
10
8
Yes
float
DataType.BOOL
11
1
No
bool
DataType.MAC_ADDR
12
6
No
string
DataType.STRING
13
VARLEN
No
string
DataType.SECONDS
14
4
No
long
DataType.MILLISECONDS
15
8
No
long
DataType.MICROSECONDS
16
8
No
long
DataType.NANOSECONDS
17
8
No
long
DataType.IP4ADDR
18
4
No
ipaddress.IPv4Address
DataType.IP6ADDR
19
16
No
ipaddress.IPv6Address
DataType.BASIC_LIST
20
VARLEN
No
pyfixbuf.BL
DataType.SUB_TMPL_LIST
21
VARLEN
No
pyfixbuf.STL
DataType.SUB_TMPL_MULTI_LIST
22
VARLEN
No
pyfixbuf.STML
- classmethod get_name(value: int) str¶
Returns the string name associated with value in this enumeration.
Raises
KeyErrorif value is not known to this enumeration. RaisesTypeErrorif value is not an instance of anint.
- classmethod to_string(value: int) str¶
Returns a string that includes the class name and the name associated with value in this enumeration; e.g., DataType(UINT8) or Units(PACKETS).
Returns a string even when value is not known to this enumeration.
- classmethod by_name(name: String) DataType¶
Returns the value associated with the name name in this enumeration.
Raises
KeyErrorif this enumeration does not have a value asociated with name. RaisesTypeErrorif name is not astr.
- static check_type(data_type: int, value: Any) bool¶
Returns
Trueif a field whoseInfoElement’s DataType is dt may be set to value given it the Pythonic type of value.
- static get_length(data_type: int) int¶
Returns the standard length of a DataType
- static refine_type_for_length(data_type: int, len: int) DataType¶
Chooses a DataType given a DataType and a length
- static supports_RLE(data_type: int) bool¶
Returns
Trueif the DataType supports reduced length encoding
Semantic¶
The Semantic class holds the values for the IPFIX Information
Element Semantics defined by Section 3.2 of RFC 7012 and Section 3.10 of
RFC 5610. This class may not be instantiated, and all methods are static.
- class pyfixbuf.Semantic¶
An enumeration containg the available Semantic values for Information Elements (
InfoElement). This is not for the semantics of structured data items.Semantic
Integer Value
Semantic.DEFAULT
0
Semantic.QUANTITY
1
Semantic.TOTALCOUNTER
2
Semantic.DELTACOUNTER
3
Semantic.IDENTIFIER
4
Semantic.FLAGS
5
Semantic.LIST
6
Semantic.SNMPCOUNTER
7
Semantic.SNMPGAUGE
8
- classmethod get_name(value: int) String¶
Returns the string name associated with value in this enumeration.
Raises
KeyErrorif value is not known to this enumeration. RaisesTypeErrorif value is not an instance of anint.
- classmethod to_string(value: int) String¶
Returns a string that includes the class name and the name associated with value in this enumeration; e.g., DataType(UINT8) or Units(PACKETS).
Returns a string even when value is not known to this enumeration.
Units¶
The Units class holds the values for the IPFIX Information Element
Units initially defined by Section 3.7 of RFC 5610. This class may not
be instantiated, and all methods are static.
- class pyfixbuf.Units¶
An enumeration containing the Units supported by pyfixbuf.
Units
Integer Value
Units.NONE
0
Units.BITS
1
Units.OCTETS
2
Units.PACKETS
3
Units.FLOWS
4
Units.SECONDS
5
Units.MILLISECONDS
6
Units.MICROSECONDS
7
Units.NANOSECONDS
8
Units.WORDS
9
Units.MESSAGES
10
Units.HOPS
11
Units.ENTRIES
12
Units.FRAMES
13
Units.PORTS
14
UNITS.INFERRED
15
- classmethod get_name(value: int) String¶
Returns the string name associated with value in this enumeration.
Raises
KeyErrorif value is not known to this enumeration. RaisesTypeErrorif value is not an instance of anint.
- classmethod to_string(value: int) String¶
Returns a string that includes the class name and the name associated with value in this enumeration; e.g., DataType(UINT8) or Units(PACKETS).
Returns a string even when value is not known to this enumeration.
InfoElementSpec¶
An Information Element Specification (InfoElementSpec) is used to
name an Information Element (InfoElement) for inclusion in a
Template. The Information Element must have already been defined and
added to the Information Model (InfoModel). An
InfoElementSpec contains the exact name of the defined Information
Element and an optional length override.
- class pyfixbuf.InfoElementSpec(name: str[, length: int = 0])¶
Creates a new Information Element Specification using the given name, and optional override length. An IPFIX Template is made up of one or more
InfoElementSpecs.The given name must be a defined Information Element (
InfoElement) in the Information Model (InfoModel) before adding theInfoElementSpecto aTemplate.If length is nonzero, it is used instead of the default length of this Information Element for reduced-length encoding. Not all Information Element data types support reduced-length encoding, and length must be smaller than the default length. When 0, the default length provided by the
InfoElementin theInfoModelis used.Note that the values of name and length are only checked when the
InfoElementSpecis added to aTemplate. When anInfoElementSpecwhose length is zero is added to aTemplate, the length of thatInfoElementSpecis modified to reflect the default length of theInfoElement.Examples:
>>> spec1 = pyfixbuf.InfoElementSpec("fooname") >>> spec2 = pyfixbuf.InfoElementSpec("sourceTransportPort") >>> spec3 = pyfixbuf.InfoElementSpec("flo_element", 4)
- name : str
The Information Element Specification name.
- length : int
The length override for the Information Element Specification. A value of 0 indicates the length of the element is the default length specified for that
InfoElementin theInfoModel.
Global Variables¶
pyfixbuf defines the following global constants:
- pyfixbuf.__version__¶
The version of pyfixbuf.
- pyfixbuf.VARLEN¶
The size used to indicate an
InfoElementhas a variable length. (65535)
- pyfixbuf.CERT_PEN¶
The private enterprise number assigned by IANA to the CERT division within the Software Engineering Institute. (6871)
- pyfixbuf.BASICLIST¶
An alias for
DataType.BASIC_LIST. TheRecord.add_elementandInfoModel.get_element_lengthmethods accept this value to help when constructing aRecord.
- pyfixbuf.SUBTEMPLATELIST¶
An alias for
DataType.SUB_TMPL_LIST. TheRecord.add_elementandInfoModel.get_element_lengthmethods accept this value to help when constructing aRecord.
- pyfixbuf.SUBTEMPLATEMULTILIST¶
An alias for
DataType.SUB_TMPL_MULTI_LIST. TheRecord.add_elementandInfoModel.get_element_lengthmethods accept this value to help when constructing aRecord.