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