Python Sample Identification ETL

From truxwiki.com
Jump to navigation Jump to search

This sample shows the steps needed to implement a byte identifier ETL in Python.

Sample File Format

This sample will identify a fake file format we call Acme. Acme Corporation is a known supplier of nefarious devices and explosives. Their file format begins with a five byte magic value followed by eleven bytes in a data structure.

0000h: 88 77 66 55 00 11 22 33 44 55 66 77 88 99 AA BB
0010h: CC

Source Code

import truxton

# For our sample File Identifier ETL
# An Acme File begins with 0x88 0x77 0x66 0x55 0x00 and is at least 16 bytes long

def main():

  etl = truxton.etl()
  etl.name = "Acme Identifier"
  etl.description = "This ETL identifies files using the Acme method"
  etl.queue = "acme"

  # Pick an early stage 
  etl.stage = 2

  # We are an identifier, the Loader attempts to identify files first, if it can't it
  # will give them a type of Type_Unknown
  # We will grab those files and run them through Acme algorithms
  etl.addtype(truxton.Type_Unknown)

  message = etl.getmessage()

  while message is not None:
    if message.depotlength >= 16 and message.signature == 0x88776655:
      file_in_truxton = message.file()

      file_in_truxton.seek(4)

      next_byte = file_in_truxton.read(1)
      if next_byte[0] == 0:
        file_in_truxton.changetype(11000)
        message.filetype = 11000
        message.route()

    message = etl.getmessage()

if __name__ == "__main__":
    main()

Code Walkthrough

Lines 5-10 setup the ETL. The message queue name will be "acme", we are an early stage and want to receive Type_Unknown files.

Line 12 starts the ETL logic and waits until a message arrives on the "acme" queue.

Line 15 looks at the data in the message to see if it is even possible for the file we have received to be an Acme file. The signature member contains the first four bytes of the file. Acme's format has a five byte signature which means we will have to read bytes from the file in order to perform a valid check. Opening a file is rather expensive and we want identification to be as fast as possible. By using signature to check the first four bytes, we can avoid unnecessarily incurring a performance hit by reading from a file we know can't possibly be Acme.

Line 16 gives you a Python file object so you can read from it.

Lines 20-21 read the fifth byte in the file and checks it for validity.

Line 22 changes the file type to our identifier for Acme. We talked about file type identifiers in a previous article.

Line 23-24 begins the process of sending this newly identified file to any ETL process that has registered for it. The first step is to overwrite the filetype, which should contain Type_Unknown with the identifier for our file type. The last step is to call route() which tells Truxton to send this message to any ETLs that want it.