]> git.sesse.net Git - plocate/blob - plocate.cpp
Test for errors from zstd.
[plocate] / plocate.cpp
1 #include "vp4.h"
2 #include "io_uring_engine.h"
3
4 #include <algorithm>
5 #include <arpa/inet.h>
6 #include <chrono>
7 #include <endian.h>
8 #include <fcntl.h>
9 #include <functional>
10 #include <memory>
11 #include <stdio.h>
12 #include <string.h>
13 #include <string>
14 #include <unistd.h>
15 #include <unordered_map>
16 #include <vector>
17 #include <zstd.h>
18
19 using namespace std;
20 using namespace std::chrono;
21
22 #define dprintf(...)
23 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
24
25 class Serializer {
26 public:
27         void do_or_wait(int seq, function<void()> cb);
28
29 private:
30         int next_seq = 0;
31         struct Element {
32                 int seq;
33                 function<void()> cb;
34
35                 bool operator<(const Element &other) const
36                 {
37                         return seq > other.seq;
38                 }
39         };
40         priority_queue<Element> pending;
41 };
42
43 void Serializer::do_or_wait(int seq, function<void()> cb)
44 {
45         if (seq != next_seq) {
46                 pending.emplace(Element{ seq, move(cb) });
47                 return;
48         }
49
50         cb();
51         ++next_seq;
52
53         while (!pending.empty() && pending.top().seq == next_seq) {
54                 pending.top().cb();
55                 pending.pop();
56                 ++next_seq;
57         }
58 }
59
60 static inline uint32_t read_unigram(const string &s, size_t idx)
61 {
62         if (idx < s.size()) {
63                 return (unsigned char)s[idx];
64         } else {
65                 return 0;
66         }
67 }
68
69 static inline uint32_t read_trigram(const string &s, size_t start)
70 {
71         return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
72                 (read_unigram(s, start + 2) << 16);
73 }
74
75 bool has_access(const char *filename,
76                 unordered_map<string, bool> *access_rx_cache)
77 {
78         const char *end = strchr(filename + 1, '/');
79         while (end != nullptr) {
80                 string parent_path(filename, end);
81                 auto it = access_rx_cache->find(parent_path);
82                 bool ok;
83                 if (it == access_rx_cache->end()) {
84                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
85                         access_rx_cache->emplace(move(parent_path), ok);
86                 } else {
87                         ok = it->second;
88                 }
89                 if (!ok) {
90                         return false;
91                 }
92                 end = strchr(end + 1, '/');
93         }
94
95         return true;
96 }
97
98 struct Trigram {
99         uint32_t trgm;
100         uint32_t num_docids;
101         uint64_t offset;
102
103         bool operator==(const Trigram &other) const
104         {
105                 return trgm == other.trgm;
106         }
107         bool operator<(const Trigram &other) const
108         {
109                 return trgm < other.trgm;
110         }
111 };
112
113 class Corpus {
114 public:
115         Corpus(int fd, IOUringEngine *engine);
116         ~Corpus();
117         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
118         void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
119         size_t get_num_filename_blocks() const;
120         off_t offset_for_block(uint32_t docid) const {
121                 return filename_index_offset + docid * sizeof(uint64_t);
122         }
123
124 public:
125         const int fd;
126         IOUringEngine *const engine;
127
128         off_t len;
129         uint64_t filename_index_offset;
130
131         uint64_t num_trigrams;
132         const off_t trigram_offset = sizeof(uint64_t) * 2;
133
134         void binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb);
135 };
136
137 Corpus::Corpus(int fd, IOUringEngine *engine)
138         : fd(fd), engine(engine)
139 {
140         len = lseek(fd, 0, SEEK_END);
141         if (len == -1) {
142                 perror("lseek");
143                 exit(1);
144         }
145
146         // Uncomment to test cold-cache behavior (except for access()).
147         // posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
148
149         uint64_t vals[2];
150         complete_pread(fd, vals, sizeof(vals), /*offset=*/0);
151
152         num_trigrams = vals[0];
153         filename_index_offset = vals[1];
154 }
155
156 Corpus::~Corpus()
157 {
158         close(fd);
159 }
160
161 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
162 {
163         binary_search_trigram(trgm, 0, num_trigrams - 1, move(cb));
164 }
165
166 void Corpus::binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb)
167 {
168         if (left > right) {
169                 cb(nullptr, 0);
170                 return;
171         }
172         uint32_t mid = (left + right) / 2;
173         engine->submit_read(fd, sizeof(Trigram) * 2, trigram_offset + sizeof(Trigram) * mid, [this, trgm, left, mid, right, cb{ move(cb) }](string s) {
174                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
175                 const Trigram *next_trgmptr = trgmptr + 1;
176                 if (trgmptr->trgm < trgm) {
177                         binary_search_trigram(trgm, mid + 1, right, move(cb));
178                 } else if (trgmptr->trgm > trgm) {
179                         binary_search_trigram(trgm, left, mid - 1, move(cb));
180                 } else {
181                         cb(trgmptr, next_trgmptr->offset - trgmptr->offset);
182                 }
183         });
184 }
185
186 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
187 {
188         // Read the file offset from this docid and the next one.
189         // This is always allowed, since we have a sentinel block at the end.
190         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
191                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
192                 off_t offset = ptr[0];
193                 size_t len = ptr[1] - ptr[0];
194                 engine->submit_read(fd, len, offset, cb);
195         });
196 }
197
198 size_t Corpus::get_num_filename_blocks() const
199 {
200         // The beginning of the filename blocks is the end of the filename index blocks.
201         uint64_t end;
202         complete_pread(fd, &end, sizeof(end), filename_index_offset);
203
204         // Subtract the sentinel block.
205         return (end - filename_index_offset) / sizeof(uint64_t) - 1;
206 }
207
208 size_t scan_file_block(const string &needle, string_view compressed,
209                        unordered_map<string, bool> *access_rx_cache)
210 {
211         size_t matched = 0;
212
213         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
214         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
215                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
216                 exit(1);
217         }
218
219         string block;
220         block.resize(uncompressed_len + 1);
221
222         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
223                         compressed.size());
224         if (ZSTD_isError(err)) {
225                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
226                 exit(1);
227         }
228         block[block.size() - 1] = '\0';
229
230         for (const char *filename = block.data();
231              filename != block.data() + block.size();
232              filename += strlen(filename) + 1) {
233                 if (strstr(filename, needle.c_str()) == nullptr) {
234                         continue;
235                 }
236                 if (has_access(filename, access_rx_cache)) {
237                         ++matched;
238                         printf("%s\n", filename);
239                 }
240         }
241         return matched;
242 }
243
244 size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
245 {
246         Serializer docids_in_order;
247         unordered_map<string, bool> access_rx_cache;
248         size_t matched = 0;
249         for (size_t i = 0; i < docids.size(); ++i) {
250                 uint32_t docid = docids[i];
251                 corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
252                         docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
253                                 matched += scan_file_block(needle, compressed, &access_rx_cache);
254                         });
255                 });
256         }
257         engine->finish();
258         return matched;
259 }
260
261 // We do this sequentially, as it's faster than scattering
262 // a lot of I/O through io_uring and hoping the kernel will
263 // coalesce it plus readahead for us.
264 void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
265 {
266         unordered_map<string, bool> access_rx_cache;
267         uint32_t num_blocks = corpus.get_num_filename_blocks();
268         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
269         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
270         string compressed;
271         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
272                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
273                 size_t io_len = offsets[last_docid] - offsets[io_docid];
274                 if (compressed.size() < io_len) {
275                         compressed.resize(io_len);
276                 }
277                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
278
279                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
280                         size_t relative_offset = offsets[docid] - offsets[io_docid];
281                         size_t len = offsets[docid + 1] - offsets[docid];
282                         scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
283                 }
284         }
285 }
286
287 void do_search_file(const string &needle, const char *filename)
288 {
289         int fd = open(filename, O_RDONLY);
290         if (fd == -1) {
291                 perror(filename);
292                 exit(1);
293         }
294
295         // Drop privileges.
296         if (setgid(getgid()) != 0) {
297                 perror("setgid");
298                 exit(EXIT_FAILURE);
299         }
300
301         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
302         if (access("/", R_OK | X_OK)) {
303                 // We can't find anything, no need to bother...
304                 return;
305         }
306
307         IOUringEngine engine;
308         Corpus corpus(fd, &engine);
309         dprintf("Corpus init took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
310
311         if (needle.size() < 3) {
312                 // Too short for trigram matching. Apply brute force.
313                 // (We could have searched through all trigrams that matched
314                 // the pattern and done a union of them, but that's a lot of
315                 // work for fairly unclear gain.)
316                 scan_all_docids(needle, fd, corpus, &engine);
317                 return;
318         }
319
320         vector<pair<Trigram, size_t>> trigrams;
321         for (size_t i = 0; i < needle.size() - 2; ++i) {
322                 uint32_t trgm = read_trigram(needle, i);
323                 pair<uint32_t, uint32_t> range{ 0, corpus.num_trigrams - 1 };
324                 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
325                         if (trgmptr == nullptr) {
326                                 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
327                                 return;
328                         }
329                         trigrams.emplace_back(*trgmptr, len);
330                 });
331         }
332         engine.finish();
333         dprintf("Binary search took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
334
335         sort(trigrams.begin(), trigrams.end());
336         {
337                 auto last = unique(trigrams.begin(), trigrams.end());
338                 trigrams.erase(last, trigrams.end());
339         }
340         sort(trigrams.begin(), trigrams.end(),
341              [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
342                      return a.first.num_docids < b.first.num_docids;
343              });
344
345         vector<uint32_t> in1, in2, out;
346         bool done = false;
347         for (auto [trgmptr, len] : trigrams) {
348                 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
349                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
350                         dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
351                                 "weed out false positives later)\n",
352                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
353                                 len, trgmptr.num_docids);
354                         break;
355                 }
356
357                 // Only stay a certain amount ahead, so that we don't spend I/O
358                 // on reading the latter, large posting lists. We are unlikely
359                 // to need them anyway, even if they should come in first.
360                 if (engine.get_waiting_reads() >= 5) {
361                         engine.finish();
362                         if (done)
363                                 break;
364                 }
365                 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
366                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
367                         size_t num = trgmptr.num_docids;
368                         unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
369                         if (in1.empty()) {
370                                 in1.resize(num + 128);
371                                 p4nd1dec128v32(pldata, num, &in1[0]);
372                                 in1.resize(num);
373                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
374                                         (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
375                         } else {
376                                 if (in2.size() < num + 128) {
377                                         in2.resize(num + 128);
378                                 }
379                                 p4nd1dec128v32(pldata, num, &in2[0]);
380
381                                 out.clear();
382                                 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
383                                                  back_inserter(out));
384                                 swap(in1, out);
385                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
386                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
387                                         len, num, in1.size());
388                                 if (in1.empty()) {
389                                         dprintf("no matches (intersection list is empty)\n");
390                                         done = true;
391                                 }
392                         }
393                 });
394         }
395         engine.finish();
396         dprintf("Intersection took %.1f ms. Doing final verification and printing:\n",
397                 1e3 * duration<float>(steady_clock::now() - start).count());
398
399         size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
400         dprintf("Done in %.1f ms, found %zu matches.\n",
401                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
402 }
403
404 int main(int argc, char **argv)
405 {
406         do_search_file(argv[1], "/var/lib/mlocate/plocate.db");
407 }