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