Difference between revisions of "Python Sample Identification ETL"
| Line 32: | Line 32: | ||
file_in_truxton.seek(4) | file_in_truxton.seek(4) | ||
| − | + | next_byte = file_in_truxton.read(1) | |
| + | if next_byte[0] == 0: | ||
file_in_truxton.changetype(11000) | file_in_truxton.changetype(11000) | ||
message.filetype = 11000 | message.filetype = 11000 | ||
Revision as of 06:15, 16 June 2020
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
1 import truxton
2
3 def main():
4
5 etl = truxton.etl()
6 etl.name = "Acme Identifier"
7 etl.description = "This ETL identifies files using the Acme method"
8 etl.queue = "acme"
9 etl.stage = 2
10 etl.addtype(truxton.Type_Unknown)
11
12 message = etl.getmessage()
13
14 while message is not None:
15 if message.depotlength >= 16 and message.signature == 0x88776655:
16 file_in_truxton = message.file()
17
18 file_in_truxton.seek(4)
19
20 next_byte = file_in_truxton.read(1)
21 if next_byte[0] == 0:
22 file_in_truxton.changetype(11000)
23 message.filetype = 11000
24 message.route()
25
26 message = etl.getmessage()
27
28 if __name__ == "__main__":
29 main()
Code Walkthrough
Lines 5-11 setup the ETL. The message queue name will be "acme", we are an early stage and want to receive Type_Unknown files.
Line 13 starts the ETL logic and waits until a message arrives on the "acme" queue.
Line 16 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 17 gives you a Python file object so you can read from it.
Line 21 reads 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 TruxtonMessage#route() route() which tells Truxton to send this message to any ETLs that want it.