]> git.sesse.net Git - plocate/blob - plocate.cpp
Move TurboPFor compilation to its own compilation unit.
[plocate] / plocate.cpp
1 #include "db.h"
2 #include "io_uring_engine.h"
3
4 #include <algorithm>
5 #include <arpa/inet.h>
6 #include <assert.h>
7 #include <chrono>
8 #include <endian.h>
9 #include <fcntl.h>
10 #include <functional>
11 #include <getopt.h>
12 #include <limits.h>
13 #include <memory>
14 #include <stdio.h>
15 #include <string.h>
16 #include <string>
17 #include <unistd.h>
18 #include <unordered_map>
19 #include <vector>
20 #include <zstd.h>
21
22 using namespace std;
23 using namespace std::chrono;
24
25 #define dprintf(...)
26 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
27
28 #include "turbopfor.h"
29
30 const char *dbpath = "/var/lib/mlocate/plocate.db";
31 bool only_count = false;
32 bool print_nul = false;
33 int64_t limit_matches = numeric_limits<int64_t>::max();
34
35 class Serializer {
36 public:
37         bool ready_to_print(int seq) { return next_seq == seq; }
38         void print_delayed(int seq, const vector<string> msg);
39         void release_current();
40
41 private:
42         int next_seq = 0;
43         struct Element {
44                 int seq;
45                 vector<string> msg;
46
47                 bool operator<(const Element &other) const
48                 {
49                         return seq > other.seq;
50                 }
51         };
52         priority_queue<Element> pending;
53 };
54
55 void Serializer::print_delayed(int seq, const vector<string> msg)
56 {
57         pending.push(Element{ seq, move(msg) });
58 }
59
60 void Serializer::release_current()
61 {
62         ++next_seq;
63
64         // See if any delayed prints can now be dealt with.
65         while (!pending.empty() && pending.top().seq == next_seq) {
66                 if (limit_matches-- <= 0)
67                         return;
68                 for (const string &msg : pending.top().msg) {
69                         if (print_nul) {
70                                 printf("%s%c", msg.c_str(), 0);
71                         } else {
72                                 printf("%s\n", msg.c_str());
73                         }
74                 }
75                 pending.pop();
76                 ++next_seq;
77         }
78 }
79
80 static inline uint32_t read_unigram(const string &s, size_t idx)
81 {
82         if (idx < s.size()) {
83                 return (unsigned char)s[idx];
84         } else {
85                 return 0;
86         }
87 }
88
89 static inline uint32_t read_trigram(const string &s, size_t start)
90 {
91         return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
92                 (read_unigram(s, start + 2) << 16);
93 }
94
95 bool has_access(const char *filename,
96                 unordered_map<string, bool> *access_rx_cache)
97 {
98         const char *end = strchr(filename + 1, '/');
99         while (end != nullptr) {
100                 string parent_path(filename, end);
101                 auto it = access_rx_cache->find(parent_path);
102                 bool ok;
103                 if (it == access_rx_cache->end()) {
104                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
105                         access_rx_cache->emplace(move(parent_path), ok);
106                 } else {
107                         ok = it->second;
108                 }
109                 if (!ok) {
110                         return false;
111                 }
112                 end = strchr(end + 1, '/');
113         }
114
115         return true;
116 }
117
118 class Corpus {
119 public:
120         Corpus(int fd, IOUringEngine *engine);
121         ~Corpus();
122         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
123         void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
124         size_t get_num_filename_blocks() const;
125         off_t offset_for_block(uint32_t docid) const
126         {
127                 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
128         }
129
130 public:
131         const int fd;
132         IOUringEngine *const engine;
133
134         Header hdr;
135 };
136
137 Corpus::Corpus(int fd, IOUringEngine *engine)
138         : fd(fd), engine(engine)
139 {
140         // Enable to test cold-cache behavior (except for access()).
141         if (false) {
142                 off_t len = lseek(fd, 0, SEEK_END);
143                 if (len == -1) {
144                         perror("lseek");
145                         exit(1);
146                 }
147                 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
148         }
149
150         complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
151         if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
152                 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
153                 exit(1);
154         }
155         if (hdr.version != 0) {
156                 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
157                 exit(1);
158         }
159 }
160
161 Corpus::~Corpus()
162 {
163         close(fd);
164 }
165
166 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
167 {
168         uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
169         engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, cb{ move(cb) }](string_view s) {
170                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
171                 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
172                         if (trgmptr[i].trgm == trgm) {
173                                 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
174                                 return;
175                         }
176                 }
177
178                 // Not found.
179                 cb(nullptr, 0);
180         });
181 }
182
183 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
184 {
185         // Read the file offset from this docid and the next one.
186         // This is always allowed, since we have a sentinel block at the end.
187         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
188                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
189                 off_t offset = ptr[0];
190                 size_t len = ptr[1] - ptr[0];
191                 engine->submit_read(fd, len, offset, cb);
192         });
193 }
194
195 size_t Corpus::get_num_filename_blocks() const
196 {
197         return hdr.num_docids;
198 }
199
200 uint64_t scan_file_block(const vector<string> &needles, string_view compressed,
201                          unordered_map<string, bool> *access_rx_cache, int seq,
202                          Serializer *serializer)
203 {
204         uint64_t matched = 0;
205
206         unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
207         if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
208                 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
209                 exit(1);
210         }
211
212         string block;
213         block.resize(uncompressed_len + 1);
214
215         size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
216                                      compressed.size());
217         if (ZSTD_isError(err)) {
218                 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
219                 exit(1);
220         }
221         block[block.size() - 1] = '\0';
222
223         bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
224         vector<string> delayed;
225
226         for (const char *filename = block.data();
227              filename != block.data() + block.size();
228              filename += strlen(filename) + 1) {
229                 bool found = true;
230                 for (const string &needle : needles) {
231                         if (strstr(filename, needle.c_str()) == nullptr) {
232                                 found = false;
233                                 break;
234                         }
235                 }
236                 if (found && has_access(filename, access_rx_cache)) {
237                         if (limit_matches-- <= 0)
238                                 break;
239                         ++matched;
240                         if (only_count)
241                                 continue;
242                         if (immediate_print) {
243                                 if (print_nul) {
244                                         printf("%s%c", filename, 0);
245                                 } else {
246                                         printf("%s\n", filename);
247                                 }
248                         } else {
249                                 delayed.push_back(filename);
250                         }
251                 }
252         }
253         if (serializer != nullptr && !only_count) {
254                 if (immediate_print) {
255                         serializer->release_current();
256                 } else {
257                         serializer->print_delayed(seq, move(delayed));
258                 }
259         }
260         return matched;
261 }
262
263 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
264 {
265         Serializer docids_in_order;
266         unordered_map<string, bool> access_rx_cache;
267         uint64_t matched = 0;
268         for (size_t i = 0; i < docids.size(); ++i) {
269                 uint32_t docid = docids[i];
270                 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
271                         matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
272                 });
273         }
274         engine->finish();
275         return matched;
276 }
277
278 // We do this sequentially, as it's faster than scattering
279 // a lot of I/O through io_uring and hoping the kernel will
280 // coalesce it plus readahead for us.
281 uint64_t scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
282 {
283         unordered_map<string, bool> access_rx_cache;
284         uint32_t num_blocks = corpus.get_num_filename_blocks();
285         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
286         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
287         string compressed;
288         uint64_t matched = 0;
289         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
290                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
291                 size_t io_len = offsets[last_docid] - offsets[io_docid];
292                 if (compressed.size() < io_len) {
293                         compressed.resize(io_len);
294                 }
295                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
296
297                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
298                         size_t relative_offset = offsets[docid] - offsets[io_docid];
299                         size_t len = offsets[docid + 1] - offsets[docid];
300                         matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
301                         if (limit_matches <= 0)
302                                 return matched;
303                 }
304         }
305         return matched;
306 }
307
308 void do_search_file(const vector<string> &needles, const char *filename)
309 {
310         int fd = open(filename, O_RDONLY);
311         if (fd == -1) {
312                 perror(filename);
313                 exit(1);
314         }
315
316         // Drop privileges.
317         if (setgid(getgid()) != 0) {
318                 perror("setgid");
319                 exit(EXIT_FAILURE);
320         }
321
322         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
323         if (access("/", R_OK | X_OK)) {
324                 // We can't find anything, no need to bother...
325                 return;
326         }
327
328         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
329         Corpus corpus(fd, &engine);
330         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
331
332         vector<pair<Trigram, size_t>> trigrams;
333         uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
334         for (const string &needle : needles) {
335                 if (needle.size() < 3)
336                         continue;
337                 for (size_t i = 0; i < needle.size() - 2; ++i) {
338                         uint32_t trgm = read_trigram(needle, i);
339                         corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
340                                 if (trgmptr == nullptr) {
341                                         dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
342                                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
343                                         if (only_count) {
344                                                 printf("0\n");
345                                         }
346                                         exit(0);
347                                 }
348                                 if (trgmptr->num_docids > shortest_so_far * 100) {
349                                         dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
350                                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
351                                                 trgmptr->num_docids);
352                                 } else {
353                                         trigrams.emplace_back(*trgmptr, len);
354                                         shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
355                                 }
356                         });
357                 }
358         }
359         engine.finish();
360         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
361
362         if (trigrams.empty()) {
363                 // Too short for trigram matching. Apply brute force.
364                 // (We could have searched through all trigrams that matched
365                 // the pattern and done a union of them, but that's a lot of
366                 // work for fairly unclear gain.)
367                 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
368                 printf("%zu\n", matched);
369                 return;
370         }
371         sort(trigrams.begin(), trigrams.end());
372         {
373                 auto last = unique(trigrams.begin(), trigrams.end());
374                 trigrams.erase(last, trigrams.end());
375         }
376         sort(trigrams.begin(), trigrams.end(),
377              [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
378                      return a.first.num_docids < b.first.num_docids;
379              });
380
381         vector<uint32_t> in1, in2, out;
382         bool done = false;
383         for (auto [trgmptr, len] : trigrams) {
384                 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
385                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
386                         dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
387                                 "weed out false positives later)\n",
388                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
389                                 len, trgmptr.num_docids);
390                         break;
391                 }
392
393                 // Only stay a certain amount ahead, so that we don't spend I/O
394                 // on reading the latter, large posting lists. We are unlikely
395                 // to need them anyway, even if they should come in first.
396                 if (engine.get_waiting_reads() >= 5) {
397                         engine.finish();
398                         if (done)
399                                 break;
400                 }
401                 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &in1, &in2, &out](string_view s) {
402                         if (done)
403                                 return;
404                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
405                         size_t num = trgmptr.num_docids;
406                         const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
407                         if (in1.empty()) {
408                                 in1.resize(num + 128);
409                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in1[0]);
410                                 in1.resize(num);
411                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
412                                         (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
413                         } else {
414                                 if (in2.size() < num + 128) {
415                                         in2.resize(num + 128);
416                                 }
417                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in2[0]);
418
419                                 out.clear();
420                                 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
421                                                  back_inserter(out));
422                                 swap(in1, out);
423                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
424                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
425                                         len, num, in1.size());
426                                 if (in1.empty()) {
427                                         dprintf("no matches (intersection list is empty)\n");
428                                         done = true;
429                                 }
430                         }
431                 });
432         }
433         engine.finish();
434         if (done) {
435                 return;
436         }
437         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
438                 1e3 * duration<float>(steady_clock::now() - start).count());
439
440         uint64_t matched = scan_docids(needles, in1, corpus, &engine);
441         dprintf("Done in %.1f ms, found %zu matches.\n",
442                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
443
444         if (only_count) {
445                 printf("%zu\n", matched);
446         }
447 }
448
449 void usage()
450 {
451         // The help text comes from mlocate.
452         printf("Usage: plocate [OPTION]... PATTERN...\n");
453         printf("\n");
454         printf("  -c, --count            only print number of found entries\n");
455         printf("  -d, --database DBPATH  use DBPATH instead of default database (which is\n");
456         printf("                         %s)\n", dbpath);
457         printf("  -h, --help             print this help\n");
458         printf("  -l, --limit, -n LIMIT  limit output (or counting) to LIMIT entries\n");
459         printf("  -0, --null             separate entries with NUL on output\n");
460 }
461
462 int main(int argc, char **argv)
463 {
464         static const struct option long_options[] = {
465                 { "help", no_argument, 0, 'h' },
466                 { "count", no_argument, 0, 'c' },
467                 { "database", required_argument, 0, 'd' },
468                 { "limit", required_argument, 0, 'l' },
469                 { nullptr, required_argument, 0, 'n' },
470                 { "null", no_argument, 0, '0' },
471                 { 0, 0, 0, 0 }
472         };
473
474         for (;;) {
475                 int option_index = 0;
476                 int c = getopt_long(argc, argv, "cd:hl:n:0", long_options, &option_index);
477                 if (c == -1) {
478                         break;
479                 }
480                 switch (c) {
481                 case 'c':
482                         only_count = true;
483                         break;
484                 case 'd':
485                         dbpath = strdup(optarg);
486                         break;
487                 case 'h':
488                         usage();
489                         exit(0);
490                 case 'l':
491                 case 'n':
492                         limit_matches = atoll(optarg);
493                         break;
494                 case '0':
495                         print_nul = true;
496                         break;
497                 default:
498                         exit(1);
499                 }
500         }
501
502         vector<string> needles;
503         for (int i = optind; i < argc; ++i) {
504                 needles.push_back(argv[i]);
505         }
506         if (needles.empty()) {
507                 fprintf(stderr, "plocate: no pattern to search for specified\n");
508                 exit(0);
509         }
510         do_search_file(needles, dbpath);
511 }