<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wenceslas des Déserts on Medium]]></title>
        <description><![CDATA[Stories by Wenceslas des Déserts on Medium]]></description>
        <link>https://medium.com/@wenceslas.desdeserts?source=rss-7d2885a7c777------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Wenceslas des Déserts on Medium</title>
            <link>https://medium.com/@wenceslas.desdeserts?source=rss-7d2885a7c777------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:12:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wenceslas.desdeserts/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Recovering corrupted RabbitMQ data by reversing its storage protocol (part 2)]]></title>
            <link>https://medium.com/cybelangel-product-engineering/recovering-corrupted-rabbitmq-data-by-reversing-its-storage-protocol-part-2-858b2074b9f5?source=rss-7d2885a7c777------2</link>
            <guid isPermaLink="false">https://medium.com/p/858b2074b9f5</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[cybelangel]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[outage]]></category>
            <dc:creator><![CDATA[Wenceslas des Déserts]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 10:27:07 GMT</pubDate>
            <atom:updated>2022-01-28T10:37:45.179Z</atom:updated>
            <content:encoded><![CDATA[<p>· <a href="#8e1b">Introduction</a><br>· <a href="#b50d">Queue index</a><br>· <a href="#97d5">Reinjection</a><br>· <a href="#3f82">Introducing RabbitMQ-storage-recoverer</a><br>· <a href="#5784">Conclusion</a></p><h3>Introduction</h3><p>In the first part of this post, we saw how our RabbitMQ cluster failed, filling its data partition entirely and corrupting its data. With some help from Erlang doc and RabbitMQ code, we were able to write a Python parser that extracts all messages stored in a .rdq file, along with their metadata. Today, we will give a closer look at the queue index and share the CLI tool we wrote, in case you need it (hopefully you won’t)!</p><h3>Queue index</h3><p>Quick reminder: each queue has a queue index. The queue index contains the rank and the status of each message. If the message body is short, it is stored directly in the index. If it is bigger than 4096 bytes, it is stored in the message store.</p><p>If we want to recover every message that was in RabbitMQ at the time of the outage, we have to extract all messages from the message store (done in part one) and all messages stored in the indexes!</p><p>As with .rdq files, we are going to use hexdump to get a better grasp of how .idx files are structured. The first lines of a random .idx file look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4db31b32082531b69d09627ac0b65450/href">https://medium.com/media/4db31b32082531b69d09627ac0b65450/href</a></iframe><p>That… looks a lot like a .rdq file, right? Indeed, the format is very similar: a bunch of non-ETF metadata, followed by ETF terms, and then the message body.</p><p>The code responsible for writing .idx files is arguably much more difficult to read than the code for .rdq. It lives in rabbit_queue_index.erl</p><p>This function exposes the structure of an index record:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcbce7f6d1d8e4993f483bbf469c1153/href">https://medium.com/media/bcbce7f6d1d8e4993f483bbf469c1153/href</a></iframe><p>So there are three types of records:</p><ul><li>Delivered (Del)</li><li>Acknowledged (Ack)</li><li>Published (Pub)</li></ul><p>Delivered and acknowledged records are straightforward: a prefix and the sequence id RelSeq of the message (RabbitMQ actually has a notion of absolute and relative sequence ids, but we don&#39;t need to go into details).</p><p>Publish records are more complex, but we can track down Bin and MessageBin structures through functions like <a href="https://github.com/rabbitmq/rabbitmq-server/blob/v3.8.7/src/rabbit_queue_index.erl#L761">parse_pub_record_body</a>. As before, we replace the size hints and constants by their actual value (defined at the top of the file), and we get the full structure:</p><ul><li>Delivered and acknowledged records:<br>– Prefix 0b01 : 2 bits<br>– Sequence id: 14 bits</li><li>Publish records:<br>– Prefix 0b11: 2 bits<br>– Sequence id: 14 bits<br>– Message id: 16 bytes<br>– Expiry time: 8 bytes<br>– Message body size: 4 bytes<br>– Serialized message record size (aka len): 4 bytes<br>– Message record (ETF): len bytes</li></ul><p>If the serialized message record size is equal to 0, it means the message has been saved in the store!</p><p>There is no difference between a delivered record and an acknowledged record, so we assumed a single occurrence means the message has been delivered, while two occurrences mean the message has been acknowledged.</p><p>We can now parse the beginning of the .idx file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9848a7e718154f3a1199c0dc04c3f3d/href">https://medium.com/media/d9848a7e718154f3a1199c0dc04c3f3d/href</a></iframe><ul><li>The first two bytes contain the prefix and the sequence id. 0xfc65 is equal to 0b1111110001100101 <br>– 0b11is the Publish prefix<br>– 0b11110001100101 is the sequence id</li><li>The next sixteen bytes encode the message id</li><li>The next eight bytes encode the message expiry date (all zeroes)</li><li>The next four bytes encode the message body size</li><li>The next four bytes encode the serialized message size: 0x00000447 aka 1095 bytes</li><li>And then we find our now familiar 0x83 prefix signaling the start of ETF serialized data!</li></ul><p>The parser we wrote for .rdq files can easily be extended for .idx files.</p><h3>Reinjection</h3><p>Our parser extract all messages from .rdq and .idx files and stores them in a tree-like structure:</p><pre>. <br>├── job.annotated_micro_mirrors <br>│   ├── e5fd7458-28c0-4295-8a41-e66c4fa889ea.metadata-adder <br>│   │   ├── 225599029630722498134902122607327092200 <br>│   │   ├── 229794879411040445244508789418059379920 <br>│   │   ├── 236036947466602537838237371623984582930 <br>│   │   ├── 24197186105763127597443970767539278509 <br>│   │   ├── 35068473120265785601150337424496069334 <br>├── job.alerts <br>│   │   ├── 174960407332388722689908875227005199431</pre><p>Each top level directory is mapped to an exchange. Sub-directories, if any, are mapped to routing keys. Messages are then stored as files either directly in the exchange directory or in one of the routing keys directories.</p><p>This is probably not optimal, but it provides an easy interface to handle the messages (sorting, filtering, and eventually re-injection).</p><p>It is technically doable to get all acknowledged records in all queue indexes and use them to remove messages in the message store that have already been acknowledged. We didn’t do it because our workers are idempotent, so re-injecting a bunch of duplicates was not a big deal.</p><h3>Introducing RabbitMQ-storage-recoverer</h3><p>We are glad to share the tool we wrote during this investigation. <a href="https://github.com/CybelAngel/rabbitmq-storage-recoverer">It is available on Github</a>. RabbitMQ Storage Recoverer is a simple Python CLI providing four commands:</p><ul><li>recover-idx-file &lt;filepath&gt; &lt;output_dir&gt; : extract all messages from the .idx file at &lt;filepath&gt; and dumps the messages bodies in &lt;output_dir&gt; in the directory structure detailed above</li><li>recover-rdq-file &lt;filepath&gt; &lt;output_dir&gt; : idem, but for a .rdq file</li><li>recover-indexes &lt;indexes_path&gt; &lt;output_dir&gt;: Looks for .idx files in &lt;indexes_path&gt; and its sub-directories. Each .idx file found is then parsed like in recover-idx-file.</li><li>recover-persistent-store &lt;store_path&gt; &lt;output_dir&gt; : Looks for .rdq files in &lt;store_path&gt;. Each .rdq file found is then parsed like in recover-rdq-file.</li></ul><p>It does everything described in this post and should allow you to rescue most of your data, if you ever find yourselves in the same situation. It can also automatically detect corrupted records and skip them.</p><p>For example, if you have a directory store containing some .rdq files and you want to extract the messages in a directory named output, you could run:</p><pre>python3 main.py recover-persistent-store store output</pre><h3>Conclusion</h3><p>We are reaching the end of this blog post. The actual investigation only took us two or three days, but we learned a lot about RabbitMQ and Erlang, and we are very happy to share it this way! We hope you enjoyed the post and learned a thing or two. If you ever find yourself in the same situation, <a href="https://github.com/CybelAngel/rabbitmq-storage-recoverer">feel free to use and improve our tool!</a> And if you want to work on interesting engineering problems like this, <a href="https://cybelangel.com/careers/">we are hiring!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=858b2074b9f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybelangel-product-engineering/recovering-corrupted-rabbitmq-data-by-reversing-its-storage-protocol-part-2-858b2074b9f5">Recovering corrupted RabbitMQ data by reversing its storage protocol (part 2)</a> was originally published in <a href="https://medium.com/cybelangel-product-engineering">CybelAngel Product &amp; Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recovering corrupted RabbitMQ data by reversing its storage protocol (part 1)]]></title>
            <link>https://medium.com/cybelangel-product-engineering/recovering-corrupted-rabbitmq-data-by-reversing-its-storage-protocol-part-1-bed2501d0fa9?source=rss-7d2885a7c777------2</link>
            <guid isPermaLink="false">https://medium.com/p/bed2501d0fa9</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[outage]]></category>
            <category><![CDATA[cybelangel]]></category>
            <dc:creator><![CDATA[Wenceslas des Déserts]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 10:26:44 GMT</pubDate>
            <atom:updated>2022-01-28T10:45:45.646Z</atom:updated>
            <content:encoded><![CDATA[<p>· <a href="#8e1b">Introduction</a><br>· <a href="#580f">What happened</a><br>· <a href="#8648">RabbitMQ Storage overview</a><br>· <a href="#4040">The message store</a><br> ∘ <a href="#6282">Testing community tools</a><br> ∘ <a href="#6fcb">Erlang External Term Format</a><br> ∘ <a href="#930d">Digging into RabbitMQ code</a><br> ∘ <a href="#a8fb">Wrapping up everything we learned</a><br>· <a href="#13b2">Conclusion</a></p><h3>Introduction</h3><p>CybelAngel is an external risk protection solution. As such we continuously scan various services, bringing data into our monitoring pipeline.</p><p>From a technical standpoint, our product consists of hundreds of microservices talking to each other through a message broker. Our most recent microservices have been migrated to GCP PubSub, while some of our older services still use RabbitMQ until the migration is complete.</p><p>A few weeks ago, our RabbitMQ cluster experienced a critical outage and one of the nodes’ data ended up corrupted. We had to backup the data and reset the node entirely to get the cluster back to a functional state. This blog post details how we “reversed” RabbitMQ disk storage protocol and managed to recover the corrupted data and re-inject it into our pipeline, mitigating the impact of the outage. We will also share the code we wrote for those interested!</p><h3>What happened</h3><p>The crash happened a few weeks ago, early on a Sunday morning. Our alerting system woke up the on-call engineer. He rapidly identified the root cause: a microservice failure triggered a rapid accumulation of messages in RabbitMQ.</p><p>We scan hundreds of thousands of documents per minute, and as such, any delay in processing can result in a very large amount of messages piling up in our message broker. We have safety systems and circuit breakers in place to avoid cascading failure, but unfortunately this time the failing microservice was on the critical path. Our last line of defense against this kind of outages is RabbitMQ high disk usage watermark: when the disk usage reaches a configured threshold, RabbitMQ blocks all incoming messages until enough disk space has been freed, acting as a naive back-pressure system.</p><p>This day, RabbitMQ continued writing data long after the watermark had been reached. It filled the data partition entirely and crashed. We suspect RabbitMQ flushed a lot of data at once, reaching the watermark and filling the disk in one operation. (We later reconfigured the watermark to have a bigger safety margin and prevent the issue from happening again.) The damage was done: some changes were only partially persisted, and RabbitMQ wouldn’t restart.</p><p>Our on-call engineer increased the VM disk size and tried restarting RabbitMQ, but the service kept complaining about corrupted log files:</p><pre>** FATAL ** Possibly truncated decision_tab file: {corrupt_log_file,&quot;/var/lib/rabbitmq/mnesia/rabbit@&lt;ip&gt;/DECISION_TAB.LOG&quot;}</pre><p>Deleting DECISION_TAB.log didn’t help. The only option left was to reset the node entirely. This would bring it back online, but destroy all the data stored in RabbitMQ internal database.</p><p>RabbitMQ has a replication feature that, when enabled, automatically replicates queues on multiple nodes. When enabled, the loss of a node is not a big deal because all the messages exist elsewhere. Sadly, we had no replication in this cluster because we observed a huge amount of Rabbit inter-nodes communication issues after enabling the feature. (We suspect those have to do with how Erlang transmits data between nodes internally and the sheer amount of inter-nodes traffic generated by the management plugin we use to gather metrics.)</p><p>At this point, our on-call engineer was joined by the manager of the SRE team. Data in the impacted queues were not critical, so they decided it was more important to get the node back to a live state as fast as possible. Before resetting the node, they did a backup of the whole data partition, so that we could try to recover the messages later.</p><p>During the post-mortem meeting on the following day we decided it was worth spending some engineer time on recovering the data:</p><ul><li>to mitigate the impact of the outage</li><li>to be prepared if something similar were to happen (although we are confident the specific issue described here won’t occur again, since we reconfigured the watermark)</li><li>to get a better grasp of RabbitMQ internals: migrating away from RabbitMQ is a slow process, and while it is no longer a key piece of our infrastructure, it is still an interesting technology that we want to understand better!</li></ul><h3>RabbitMQ Storage overview</h3><p>RabbitMQ documentation on disk storage is scarce, and we didn’t find much in mailing lists or blog posts. The best official source we found is the <a href="https://www.rabbitmq.com/persistence-conf.html">doc on persistence</a>:</p><ul><li>Messages can be stored on disk in two different places: the <strong>queue index</strong> or the <strong>message store</strong></li><li>Each queue has an index (which can be stored in multiple files if it’s big)</li><li>For each message in a queue, the index stores:<br>– The rank of the message in the queue<br>– The status of the message (published, delivered, acknowledged)<br>– The message itself if it’s shorter than 4096 bytes (default configuration)</li><li>The message store (which, again, can be stored in multiple files) contains all messages longer than 4096 bytes, regardless of their source and destination.</li></ul><p>RabbitMQ data directory contains a lot of stuff, but we were only interested in the msg_stores directory that lives at /var/lib/rabbitmq/mnesia/rabbit@&lt;node_private_ip&gt;/msg_stores. On our systems the whole /var/lib/rabbitmq is on a dedicated partition that our engineers had backed up before resetting the node. The store directory was included in our disk backup.</p><p>It has the following structure:</p><pre>rabbit@&lt;node_private_ip&gt;/msg_stores/vhosts/&lt;vhost_id&gt;: <br>. <br>├── msg_store_persistent<br>│   ├── 1011223.rdq <br>│   ├── 1011669.rdq <br>│   ├── 1012396.rdq <br>│   ├── &lt;other .rdq files&gt; <br>├── queues <br>│   ├── 115HPE6OZTZ9QG7OOPLLVSAT <br>│   │   └── journal.jif <br>│   ├── 120ZI4D1WKBFGVQ1V8GT3BPWZ <br>│   │   ├── 5.idx <br>│   │   └── journal.jif <br>│   ├── 1F530S78TDLFD4ZUYWVN25L43 <br>│   │   ├── 10588.idx <br>│   │   ├── 10589.idx <br>│   │   └── journal.jif <br>│   ├── &lt;other directories with ids&gt;</pre><p>The message store lives in the msg_store_persistent directory and consists of multiple .rdq files. Indexes are stored in sub-directories of queues (one subdir per queue) in .idx files. Not all queues have a .idx, we are not sure why‽ Maybe those are old or dead queues. If you know, please reach out!</p><p>Most messages were stored in .rdq files. We had ten thousand of those!</p><p><em>Note: there is also a </em><em>msg_store_transient store for transient messages. If you use transient queues, your setup might be slightly different. We didn’t dig into it, but the transient message store has the same structure as the persistent message store, so everything below stands true.</em></p><h3>The message store</h3><p>We began our investigation with .rdq files since most messages were stored there. All .rdq files have the same structure, so we picked a random one and ran hexdump on it (e.g. hexdump -C 1011223.rdq ). Looking at the first bytes of the file already gives us a lot of intel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0809af23e723920750a29d7bd42958e9/href">https://medium.com/media/0809af23e723920750a29d7bd42958e9/href</a></iframe><p>The -C flag gives us hexadecimal and ASCII display side by side so that we can see at a glance what part of the file is valid ASCII.</p><p>The good news is that our messages are there, stored in (almost) plain text. We mostly transmit JSON through RabbitMQ, and the {“document&quot;: {&quot;$storable... part is a valid document start in our messaging model.</p><p>Everything before the JSON start is a bit cryptic, but we can break it down:</p><ul><li>basic_message is the type of the resource stored</li><li>exchange [...] job.annotated_micromirrors matches with an existing AMQP exchange in our cluster</li><li>rabbit_framing_amqp_0_9_1 is the version of AMQP RabbitMQ uses</li></ul><p>This is a good start, but if we want to reinject our lost messages we need to extract them with their destination exchanges and their routing keys.</p><h4>Testing community tools</h4><p>Several projects out there do exactly that, for example <a href="https://github.com/jeffbryner/rdqdump">RDQ dump</a>. When we ran this tool on our files though, it immediately appeared that it only extracted <em>some</em> of the messages but missed a lot of them!</p><p>All the RDQ parsers we could find work on the same principle: they look for all occurrences of a (seemingly arbitrary) token in the file, and read what comes after. That token is 395f316c000000016d0000 and has probably been copy-pasted from one script to another!</p><p>Since this didn’t work for us, we had to understand how exactly messages were encoded and what all the data surrounding our messages meant.</p><h4>Erlang External Term Format</h4><p>Erlang has its own serialization protocol called <a href="http://erlang.org/doc/apps/erts/erl_ext_dist.html">Erlang External Term Format</a>. Some of the data we had definitely looked like ETF.</p><p>All Erlang serialized items have the same binary structure:</p><ul><li>A one-byte long header specifying the type of the serialized variable (for example, 104 means small tuple)</li><li>One or more metadata fields describing the type (for example, the tuple length)</li><li>One or more fields of variable lengths containing the actual data (for example, tuple items)</li></ul><p>Please note that Erlang’s documentation describes prefixes in decimal format while this post shows bytes directly in hexadecimal format. In the rest of this post, we will use the following prefixes to avoid confusion:</p><ul><li>0x for hexadecimal</li><li>0d for decimal</li><li>0b for binary</li></ul><p>Since a group of 4 bits can take 2⁴ = 16 values, one byte (8 bits, or 2 groups of 4 bits) can be represented as two hexadecimal characters so that the following notations are equivalent:</p><ul><li>0x64 in hexadecimal</li><li>0d100 in decimal</li><li>0b01100100 in binary</li></ul><p>If we look at a portion of our hexadecimal dump:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab92d824dc3438f0204462c8fbb965a5/href">https://medium.com/media/ab92d824dc3438f0204462c8fbb965a5/href</a></iframe><p>The 64 00 19 part (first line) is particularly interesting. Indeed, 0x64 (or 0d100 in decimal) is the prefix for an ATOM_EXT aka en Erlang constant string.</p><p><a href="http://erlang.org/doc/apps/erts/erl_ext_dist.html#atom_ext--deprecated-">Erlang’s doc</a> specify that ATOM_EXT have the following structure:</p><ul><li>A prefix which value is 0x64 (one byte)</li><li>The length len of the atom (two bytes)</li><li>The atom itself (len bytes)</li></ul><p>So if 64 is the ATOM_EXT prefix, it follow that 00 19 must be the length. That’s 25 in base 10 ( 0d25 ), so we take the following 25 bytes: 72 61 62 62 69 74 5f 66 72 61 6d 69 6e 67 5f 61 6d 71 70 5f 30 5f 39 5f 31</p><p>All those bytes are valid in ASCII and translate to rabbit_framing_amqp_0_9_1 .</p><p>Great! We now have a better understanding of how messages are encoded. But if we look at the beginning of the .rdq file, we have bytes that are NOT valid ETF.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3d3d3bb500ceffa26bef0faea5c4d2/href">https://medium.com/media/ac3d3d3bb500ceffa26bef0faea5c4d2/href</a></iframe><p>Erlang documentation specifies that ETF data always begin with 0x83 ( 0d100). This marker is clearly visible here (second line, start of second group), but all bytes before can’t be ETF: 00 00 00 00 00 01 c2 fb 02 e9 eb e0 0f 39 2b 51 fd cd 34 ba d7 fc 29 92</p><p>We had no choice but to look for the RabbitMQ portion of code which wrote those bytes.</p><h4>Digging into RabbitMQ code</h4><p>Navigating Erlang code is not easy when you don’t know the language. Fortunately, RabbitMQ files are well-named and <a href="https://github.com/rabbitmq/rabbitmq-server/blob/v3.8.7/src/rabbit_msg_store.erl">rabbit_msg_store.erl</a> had the function we were looking for, along with a bunch of comments explaining how the store works. The actual message-to-rdq-file code, though, lives in the append function of <a href="https://www.notion.so/Part-1-1c0aef8ca7654b4581b955047ad20b93#629bc0f5bf484d27b72248e6e9f95d54">rabbit_msg_file.erl</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4575ba061e402dc41795c4e275e205/href">https://medium.com/media/dd4575ba061e402dc41795c4e275e205/href</a></iframe><p>This is very interesting! term_to_binary is a standard Erlang function that serializes a data structure into ETF. We can see that RabbitMQ appends a bunch of information around the serialized message. The final structure looks like this:</p><ul><li>The size of (message id + serialized message), aka record size</li><li>The message id</li><li>The serialized message itself, in ETF</li><li>A “write ok marker”</li></ul><p>If we replace the size hints and constants by their values (declared above in the file), we get the full specification of the storage protocol:</p><ul><li>Record size (message id size + serialized message size): 8 bytes</li><li>Message id: 16 bytes</li><li>Serialized message in ETF: Record size minus 16 bytes</li><li>Write ok marker: 1 bytes</li></ul><p>If we look again at the beginning of our RDQ file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac3d3d3bb500ceffa26bef0faea5c4d2/href">https://medium.com/media/ac3d3d3bb500ceffa26bef0faea5c4d2/href</a></iframe><p>We can now identify the 24 bytes before 0x83 that where puzzling us before:</p><ul><li>00 00 00 00 00 01 c2 fb: record size on 8 bytes</li><li>02 e9 eb e0 0f 39 2b 51 fd cd 34 ba d7 fc 29 92: message id on 16 bytes</li></ul><p>The following bytes, starting with 0x83, contain the serialized message. Just after the end of the serialized message (not shown in the extracts above), we would find the write ok marker, whose value is always 0xff.</p><h4>Wrapping up everything we learned</h4><p>Now that we have a good understanding of the RDQ format, we can write a Python parser that loads all the messages stored in a .rdq file. We discovered some quirks while doing so:</p><p><strong>Encoding<br></strong>We have non-ASCII characters in our messages (accented characters and such). Erlang stores strings in UTF-8, so decoding them was straightforward.</p><p><strong>Chunking<br></strong>If we look at the following block of hexadecimal data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/707d5e0715d38a3c9c065260e466dc14/href">https://medium.com/media/707d5e0715d38a3c9c065260e466dc14/href</a></iframe><p>We see that after the rabbit_framing_amqp_0_9_1 atom, there is the beginning of an <a href="http://erlang.org/doc/apps/erts/erl_ext_dist.html#list_ext">ETF list</a> (marked by the byte 0x6c = 0d108). The following four bytes 00 00 00 01 specify that the list has a length of one: the only element of the list is the body of the message.</p><p>When a message body is long, RabbitMQ chunks it into multiple pieces and the list will contain more than one element. Fun fact: these elements need to be joined <em>in reverse-order</em> to get back the full message body!</p><p>This also explains why the community tools we tried didn’t work! If we align the “magic token” they use to find messages with the actual bytes structure, we get this: 39 5f 31 6c 00 00 00 01 6d 00 00</p><p>Or, in plain text:</p><ul><li>39 5f 31 is 9_1 in ASCII, aka the end of the rabbit_framing_amqp_0_9_1 atom</li><li>6c begins an ETF list</li><li>00 00 00 01 means the list has a size of 1</li><li>6d 00 00 is the beginning of the body</li></ul><p>All these tools consistently missed all messages whose body had been chunked, because they expected the list to always have a size of exactly one!</p><h3>Conclusion</h3><p>This wraps up the first part of this investigation! We have seen how a microservice failure caused an accumulation of messages in RabbitMQ, filling the disk and corrupting data. We had to dig pretty deep in the data format and the code, but we were eventually able to understand most of the storage protocol and write a parser able to extract all messages stored in the message store.</p><p><a href="https://medium.com/cybelangel-product-engineering/recovering-corrupted-rabbitmq-data-by-reversing-its-storage-protocol-part-2-858b2074b9f5">In the second (and last) part</a>, we will apply the same techniques to the index store and share the CLI tool we wrote to recover messages!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bed2501d0fa9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cybelangel-product-engineering/recovering-corrupted-rabbitmq-data-by-reversing-its-storage-protocol-part-1-bed2501d0fa9">Recovering corrupted RabbitMQ data by reversing its storage protocol (part 1)</a> was originally published in <a href="https://medium.com/cybelangel-product-engineering">CybelAngel Product &amp; Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>