]> git.sesse.net Git - plocate/blob - plocate.cpp
Full scans (not trigram-based) would always print counts, even without -c. Fix.
[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 void do_search_file(const vector<string> &needles, const char *filename)
313 {
314         int fd = open(filename, O_RDONLY);
315         if (fd == -1) {
316                 perror(filename);
317                 exit(1);
318         }
319
320         // Drop privileges.
321         if (setgid(getgid()) != 0) {
322                 perror("setgid");
323                 exit(EXIT_FAILURE);
324         }
325
326         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
327         if (access("/", R_OK | X_OK)) {
328                 // We can't find anything, no need to bother...
329                 return;
330         }
331
332         IOUringEngine engine(/*slop_bytes=*/16);  // 16 slop bytes as described in turbopfor.h.
333         Corpus corpus(fd, &engine);
334         dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
335
336         vector<pair<Trigram, size_t>> trigrams;
337         uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
338         for (const string &needle : needles) {
339                 if (needle.size() < 3)
340                         continue;
341                 for (size_t i = 0; i < needle.size() - 2; ++i) {
342                         uint32_t trgm = read_trigram(needle, i);
343                         corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
344                                 if (trgmptr == nullptr) {
345                                         dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
346                                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
347                                         if (only_count) {
348                                                 printf("0\n");
349                                         }
350                                         exit(0);
351                                 }
352                                 if (trgmptr->num_docids > shortest_so_far * 100) {
353                                         dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
354                                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
355                                                 trgmptr->num_docids);
356                                 } else {
357                                         trigrams.emplace_back(*trgmptr, len);
358                                         shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
359                                 }
360                         });
361                 }
362         }
363         engine.finish();
364         dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
365
366         if (trigrams.empty()) {
367                 // Too short for trigram matching. Apply brute force.
368                 // (We could have searched through all trigrams that matched
369                 // the pattern and done a union of them, but that's a lot of
370                 // work for fairly unclear gain.)
371                 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
372                 if (only_count) {
373                         printf("%zu\n", matched);
374                 }
375                 return;
376         }
377         sort(trigrams.begin(), trigrams.end());
378         {
379                 auto last = unique(trigrams.begin(), trigrams.end());
380                 trigrams.erase(last, trigrams.end());
381         }
382         sort(trigrams.begin(), trigrams.end(),
383              [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
384                      return a.first.num_docids < b.first.num_docids;
385              });
386
387         vector<uint32_t> in1, in2, out;
388         bool done = false;
389         for (auto [trgmptr, len] : trigrams) {
390                 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
391                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
392                         dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
393                                 "weed out false positives later)\n",
394                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
395                                 len, trgmptr.num_docids);
396                         break;
397                 }
398
399                 // Only stay a certain amount ahead, so that we don't spend I/O
400                 // on reading the latter, large posting lists. We are unlikely
401                 // to need them anyway, even if they should come in first.
402                 if (engine.get_waiting_reads() >= 5) {
403                         engine.finish();
404                         if (done)
405                                 break;
406                 }
407                 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &in1, &in2, &out](string_view s) {
408                         if (done)
409                                 return;
410                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
411                         size_t num = trgmptr.num_docids;
412                         const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
413                         if (in1.empty()) {
414                                 in1.resize(num + 128);
415                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in1[0]);
416                                 in1.resize(num);
417                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
418                                         (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
419                         } else {
420                                 if (in2.size() < num + 128) {
421                                         in2.resize(num + 128);
422                                 }
423                                 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in2[0]);
424
425                                 out.clear();
426                                 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
427                                                  back_inserter(out));
428                                 swap(in1, out);
429                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
430                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
431                                         len, num, in1.size());
432                                 if (in1.empty()) {
433                                         dprintf("no matches (intersection list is empty)\n");
434                                         done = true;
435                                 }
436                         }
437                 });
438         }
439         engine.finish();
440         if (done) {
441                 return;
442         }
443         dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
444                 1e3 * duration<float>(steady_clock::now() - start).count());
445
446         uint64_t matched = scan_docids(needles, in1, corpus, &engine);
447         dprintf("Done in %.1f ms, found %zu matches.\n",
448                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
449
450         if (only_count) {
451                 printf("%zu\n", matched);
452         }
453 }
454
455 void usage()
456 {
457         // The help text comes from mlocate.
458         printf("Usage: plocate [OPTION]... PATTERN...\n");
459         printf("\n");
460         printf("  -c, --count            only print number of found entries\n");
461         printf("  -d, --database DBPATH  use DBPATH instead of default database (which is\n");
462         printf("                         %s)\n", dbpath);
463         printf("  -h, --help             print this help\n");
464         printf("  -l, --limit, -n LIMIT  limit output (or counting) to LIMIT entries\n");
465         printf("  -0, --null             separate entries with NUL on output\n");
466 }
467
468 int main(int argc, char **argv)
469 {
470         static const struct option long_options[] = {
471                 { "help", no_argument, 0, 'h' },
472                 { "count", no_argument, 0, 'c' },
473                 { "database", required_argument, 0, 'd' },
474                 { "limit", required_argument, 0, 'l' },
475                 { nullptr, required_argument, 0, 'n' },
476                 { "null", no_argument, 0, '0' },
477                 { 0, 0, 0, 0 }
478         };
479
480         for (;;) {
481                 int option_index = 0;
482                 int c = getopt_long(argc, argv, "cd:hl:n:0", long_options, &option_index);
483                 if (c == -1) {
484                         break;
485                 }
486                 switch (c) {
487                 case 'c':
488                         only_count = true;
489                         break;
490                 case 'd':
491                         dbpath = strdup(optarg);
492                         break;
493                 case 'h':
494                         usage();
495                         exit(0);
496                 case 'l':
497                 case 'n':
498                         limit_matches = atoll(optarg);
499                         break;
500                 case '0':
501                         print_nul = true;
502                         break;
503                 default:
504                         exit(1);
505                 }
506         }
507
508         vector<string> needles;
509         for (int i = optind; i < argc; ++i) {
510                 needles.push_back(argv[i]);
511         }
512         if (needles.empty()) {
513                 fprintf(stderr, "plocate: no pattern to search for specified\n");
514                 exit(0);
515         }
516         do_search_file(needles, dbpath);
517 }