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