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