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