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