python-ipfix ************ IPFIX implementation for Python 3.3. This module provides a Python interface to IPFIX message streams, and provides tools for building IPFIX Exporting and Collecting Processes. It handles message framing and deframing, encoding and decoding IPFIX data records using templates, and a bridge between IPFIX ADTs and appropriate Python data types. Before using any of the functions of this module, it is necessary to populate the information model with Information Elements. "ipfix.ie.use_iana_default()" populates the default IANA IPFIX Information Element Registry shipped with the module; this is the current registry as of release time. "ipfix.ie.use_5103_default()" populates the reverse counterpart IEs as in **RFC 5103**. The module also supports the definition of enterprise-specific Information Elements via "ipfix.ie.for_spec()" and "ipfix.ie.use_specfile()"; see "ipfix.ie" for more. For reading and writing of records to IPFIX message streams with automatic message boundary management, see the "ipfix.reader" and "ipfix.writer" modules, respectively. For manual reading and writing of messages, see "ipfix.message". In any case, exporters will need to define templates; see "ipfix.template". This module is copyright 2013 Brian Trammell. It is made available under the terms of the GNU Lesser General Public License, or, at your option, any later version. Reference documentation for each module is found in the subsections below. module ipfix.types ================== Implementation of IPFIX abstract data types (ADT) and mappings to Python types. Maps each IPFIX ADT to the corresponding Python type, as below: +-------------------------+---------------+ | IPFIX Type | Python Type | +=========================+===============+ | octetArray | bytes | +-------------------------+---------------+ | unsigned8 | int | +-------------------------+---------------+ | unsigned16 | int | +-------------------------+---------------+ | unsigned32 | int | +-------------------------+---------------+ | unsigned64 | int | +-------------------------+---------------+ | signed8 | int | +-------------------------+---------------+ | signed16 | int | +-------------------------+---------------+ | signed32 | int | +-------------------------+---------------+ | signed64 | int | +-------------------------+---------------+ | float32 | float | +-------------------------+---------------+ | float64 | float | +-------------------------+---------------+ | boolean | bool | +-------------------------+---------------+ | macAddress | bytes | +-------------------------+---------------+ | string | str | +-------------------------+---------------+ | dateTimeSeconds | datetime | +-------------------------+---------------+ | dateTimeMilliseconds | datetime | +-------------------------+---------------+ | dateTimeMicroseconds | datetime | +-------------------------+---------------+ | dateTimeNanoseconds | datetime | +-------------------------+---------------+ | ipv4Address | ipaddress | +-------------------------+---------------+ | ipv6Address | ipaddress | +-------------------------+---------------+ Though client code generally will not use this module directly, it defines how each IPFIX abstract data type will be represented in Python, and the concrete IPFIX representation of each type. Type methods operate on buffers, as used internally by the "ipfix.message.MessageBuffer" class, so we'll create one to illustrate encoding and decoding: >>> import ipfix.types >>> buf = memoryview(bytearray(16)) Each of the encoding methods returns the offset into the buffer of the first byte after the encoded value; since we're always encoding to the beginning of the buffer in this example, this is equivalent to the length. We use this to bound the encoded value on subsequent decode. Integers are represented by the python int type: >>> unsigned32 = ipfix.types.for_name("unsigned32") >>> length = unsigned32.encode_single_value_to(42, buf, 0) >>> buf[0:length].tolist() [0, 0, 0, 42] >>> unsigned32.decode_single_value_from(buf, 0, length) 42 ...floats by the float type, with the usual caveats about precision: >>> float32 = ipfix.types.for_name("float32") >>> length = float32.encode_single_value_to(42.03579, buf, 0) >>> buf[0:length].tolist() [66, 40, 36, 166] >>> float32.decode_single_value_from(buf, 0, length) 42.035789489746094 ...strings by the str type, encoded as UTF-8: >>> string = ipfix.types.for_name("string") >>> length = string.encode_single_value_to("Grüezi", buf, 0) >>> buf[0:length].tolist() [71, 114, 195, 188, 101, 122, 105] >>> string.decode_single_value_from(buf, 0, length) 'Grüezi' ...addresses as the IPv4Address and IPv6Address types in the ipaddress module: >>> from ipaddress import ip_address >>> ipv4Address = ipfix.types.for_name("ipv4Address") >>> length = ipv4Address.encode_single_value_to(ip_address("198.51.100.27"), buf, 0) >>> buf[0:length].tolist() [198, 51, 100, 27] >>> ipv4Address.decode_single_value_from(buf, 0, length) IPv4Address('198.51.100.27') >>> ipv6Address = ipfix.types.for_name("ipv6Address") >>> length = ipv6Address.encode_single_value_to(ip_address("2001:db8::c0:ffee"), buf, 0) >>> buf[0:length].tolist() [32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 255, 238] >>> ipv6Address.decode_single_value_from(buf, 0, length) IPv6Address('2001:db8::c0:ffee') ...and the timestamps of various precision as a python datetime, encoded as per RFC5101bis: >>> from datetime import datetime >>> dtfmt_in = "%Y-%m-%d %H:%M:%S.%f %z" >>> dtfmt_out = "%Y-%m-%d %H:%M:%S.%f" >>> dt = datetime.strptime("2013-06-21 14:00:03.456789 +0000", dtfmt_in) dateTimeSeconds truncates microseconds: >>> dateTimeSeconds = ipfix.types.for_name("dateTimeSeconds") >>> length = dateTimeSeconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [81, 196, 92, 99] >>> dateTimeSeconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.000000' dateTimeMilliseconds truncates microseconds to the nearest millisecond: >>> dateTimeMilliseconds = ipfix.types.for_name("dateTimeMilliseconds") >>> length = dateTimeMilliseconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [0, 0, 1, 63, 103, 8, 228, 128] >>> dateTimeMilliseconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.456000' dateTimeMicroseconds exports microseconds fully in NTP format: >>> dateTimeMicroseconds = ipfix.types.for_name("dateTimeMicroseconds") >>> length = dateTimeMicroseconds.encode_single_value_to(dt, buf, 0) >>> buf[0:length].tolist() [81, 196, 92, 99, 116, 240, 32, 0] >>> dateTimeMicroseconds.decode_single_value_from(buf, 0, length).strftime(dtfmt_out) '2013-06-21 14:00:03.456789' dateTimeNanoseconds is also supported, but is identical to dateTimeMicroseconds, as the datetime class in Python only supports microsecond-level timing. class class ipfix.types.IpfixType(name, num, valenc, valdec) Abstract interface for all IPFIX types. Used internally. exception exception ipfix.types.IpfixTypeError(*args) Raised when attempting to do an unsupported operation on a type class class ipfix.types.OctetArrayType(name, num, valenc=, valdec=) Type encoded by byte array packing. Used internally. class class ipfix.types.StructType(name, num, stel, valenc=, valdec=) Type encoded by struct packing. Used internally. ipfix.types.decode_varlen(buf, offset) Decode a IPFIX varlen encoded length; used internally by template ipfix.types.encode_varlen(buf, offset, length) Encode a IPFIX varlen encoded length; used internally by template ipfix.types.for_name(name) Return an IPFIX type for a given type name Parameters: **name** -- the name of the type to look up Returns: IpfixType -- type instance for that name Raises : IpfixTypeError module ipfix.ie =============== IESpec-based interface to IPFIX information elements, and interface to use the default IPFIX IANA Information Model An IESpec is a string representation of an IPFIX information element, including all the information required to define it, as documented in Section 9 of http://tools.ietf.org/html/draft-ietf-ipfix-ie-doctors. It has the format: name(pen/num)[size] To specify a new Information Element, a complete IESpec must be passed to for_spec(): >>> import ipfix.ie >>> e = ipfix.ie.for_spec("myNewInformationElement(35566/1)") >>> e InformationElement('myNewInformationElement', 35566, 1, ipfix.types.for_name('string'), 65535) The string representation of an InformationElement is its IESpec: >>> str(e) 'myNewInformationElement(35566/1)[65535]' To get an Information Element already specified, an incomplete specification can be passed; a name or number is enough: >>> ipfix.ie.use_iana_default() >>> str(ipfix.ie.for_spec("octetDeltaCount")) 'octetDeltaCount(0/1)[8]' >>> str(ipfix.ie.for_spec("(2)")) 'packetDeltaCount(0/2)[8]' Reduced-length encoding and fixed-length sequence types are supported by the for_length method; this is used internally by templates. >>> str(e.for_length(32)) 'myNewInformationElement(35566/1)[32]' Most client code will only need the "use_iana_default()", "use_5103_default()", and "use_specfile()" functions; client code using tuple interfaces will need "spec_list()" as well. class class ipfix.ie.InformationElement(name, pen, num, ietype, length) An IPFIX Information Element (IE). This is essentially a five-tuple of name, element number (num), a private enterprise number (pen; 0 if it is an IANA registered IE), a type, and a length. InformationElement instances should be obtained using the "for_spec()" or "for_template_entry()" functions. for_length(length) Get an instance of this IE for the specified length. Used to support reduced-length encoding (RLE). Parameters: **length** -- length of the new IE Returns: this IE if length matches, or a new IE for the length Raises : ValueError class class ipfix.ie.InformationElementList(iterable=None) A hashable ordered list of Information Elements. Used internally by templates, and to specify the order of tuples to the tuple append and iterator interfaces. Get an instance by calling "spec_list()" ipfix.ie.clear_infomodel() Reset the cache of known Information Elements. ipfix.ie.for_spec(spec) Get an IE from the cache of known IEs, or create a new IE if not found, given an IESpec. Parameters: **spec** -- IEspec, as in draft-ietf-ipfix-ie-doctors, of the form name(pen/num)[size]; some fields may be omitted unless creating a new IE in the cache. Returns: an IE for the name Raises : ValueError ipfix.ie.for_template_entry(pen, num, length) Get an IE from the cache of known IEs, or create a new IE if not found, given a private enterprise number, element number, and length. Used internally by Templates. Parameters: * **pen** -- private enterprise number, or 0 for an IANA IE * **num** -- IE number (Element ID) * **length** -- length of the IE in bytes Returns: an IE for the given pen, num, and length. If the IE has not been previously added to the cache of known IEs, the IE will be named _ipfix_pen_num, and have octetArray as a type. ipfix.ie.parse_spec(spec) Parse an IESpec into name, pen, number, typename, and length fields ipfix.ie.spec_list(specs) Given a list or iterable of IESpecs, return a hashable list of IEs. Pass this as the ielist argument to the tuple export and iterator functions. Parameters: **specs** -- list of IESpecs Returns: a new Information Element List, suitable for use with the tuple export and iterator functions in "message" Raises : ValueError ipfix.ie.use_5103_default() Load the module internal list of RFC 5103 reverse IEs for IANA registered IEs into the cache of known IEs. Normally, biflow-aware client code should call this just after use_iana_default(). ipfix.ie.use_iana_default() Load the module internal list of IANA registered IEs into the cache of known IEs. Normally, client code should call this before using any other part of this module. ipfix.ie.use_specfile(filename) Load a file listing IESpecs into the cache of known IEs Parameters: **filename** -- name of file containing IESpecs to open Raises : ValueError module ipfix.template ===================== Representation of IPFIX templates. Provides template-based packing and unpacking of data in IPFIX messages. For reading, templates are handled internally. For writing, use "from_ielist()" to create a template. See "ipfix.message" for examples. exception exception ipfix.template.IpfixDecodeError(*args) Raised when decoding a malformed IPFIX message exception exception ipfix.template.IpfixEncodeError(*args) Raised on internal encoding errors, or if message MTU is too small class class ipfix.template.Template(tid=0, iterable=None) An IPFIX Template. A template is an ordered list of IPFIX Information Elements with an ID. append(ie) Append an IE to this Template count() Count IEs in this template decode_from(buf, offset, packplan=None) Decodes a record into a tuple containing values in template order decode_iedict_from(buf, offset, recinf=None) Decodes a record from a buffer into a dict keyed by IE decode_namedict_from(buf, offset, recinf=None) Decodes a record from a buffer into a dict keyed by IE name. decode_tuple_from(buf, offset, recinf=None) Decodes a record from a buffer into a tuple, ordered as the IEs in the InformationElementList given as recinf. encode_iedict_to(buf, offset, rec, recinf=None) Encodes a record from a dict containing values keyed by IE encode_namedict_to(buf, offset, rec, recinf=None) Encodes a record from a dict containing values keyed by IE name encode_template_to(buf, offset, setid) Encodes the template to a buffer. Encodes as a Template if setid is TEMPLATE_SET_ID, as an Options Template if setid is OPTIONS_SET_ID. encode_to(buf, offset, vals, packplan=None) Encodes a record from a tuple containing values in template order encode_tuple_to(buf, offset, rec, recinf=None) Encodes a record from a tuple containing values ordered as the IEs in the InformationElementList given as recinf. If recinf is not given, assumes the tuple contains all IEs in the template in template order. finalize() Compile a default packing plan. Called after append()ing all IEs. fixlen_count() Count of fixed-length IEs in this template before the first variable-length IE; this is the size of the portion of the template which can be encoded/decoded efficiently. packplan_for_ielist(*args, **kwds) Given a list of IEs, devise and cache a packing plan. Used by the tuple interfaces. class class ipfix.template.TemplatePackingPlan(tmpl, indices) Plan to pack/unpack a specific set of indices for a template. Used internally by Templates for efficient encoding and decoding. ipfix.template.decode_template_from(buf, offset, setid) Decodes a template from a buffer. Decodes as a Template if setid is TEMPLATE_SET_ID, as an Options Template if setid is OPTIONS_SET_ID. ipfix.template.from_ielist(tid, ielist) Create a template from a template ID and an information element list (itself available from "ipfix.ie.spec_list()"). Parameters: * **tid** -- Template ID, must be between 256 and 65535. * **ielist** -- List of Information Elements for the Template, see "ipfix.ie.spec_list()". Returns: A new Template, ready to use for writing to a Message module ipfix.message ==================== Provides the MessageBuffer class for encoding and decoding IPFIX Messages. This interface allows direct control over Messages; for reading or writing records automatically from/to streams, see "ipfix.reader" and "ipfix.writer", respectively. To create a message buffer: >>> import ipfix.message >>> msg = ipfix.message.MessageBuffer() >>> msg To prepare the buffer to write records: >>> msg.begin_export(8304) >>> msg Note that the buffer grows to contain the message header. To write records to the buffer, first you'll need a template: >>> import ipfix.ie >>> ipfix.ie.use_iana_default() >>> import ipfix.template >>> tmpl = ipfix.template.from_ielist(256, ... ipfix.ie.spec_list(("flowStartMilliseconds", ... "sourceIPv4Address", ... "destinationIPv4Address", ... "packetDeltaCount"))) >>> tmpl