]> git.sesse.net Git - plocate/blob - plocate-build.cpp
Reuse zstd compression contexts, for a tiny speed boost.
[plocate] / plocate-build.cpp
1 #include "db.h"
2 #include "turbopfor-encode.h"
3
4 #include <algorithm>
5 #include <assert.h>
6 #include <chrono>
7 #include <getopt.h>
8 #include <iosfwd>
9 #include <math.h>
10 #include <memory>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <string>
16 #include <string_view>
17 #include <sys/stat.h>
18 #include <utility>
19 #include <vector>
20 #include <zstd.h>
21
22 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
23 #define dprintf(...)
24 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
25
26 #define NUM_TRIGRAMS 16777216
27
28 using namespace std;
29 using namespace std::chrono;
30
31 string zstd_compress(const string &src, string *tempbuf);
32
33 constexpr unsigned num_overflow_slots = 16;
34
35 static inline uint32_t read_unigram(const string_view s, size_t idx)
36 {
37         if (idx < s.size()) {
38                 return (unsigned char)s[idx];
39         } else {
40                 return 0;
41         }
42 }
43
44 static inline uint32_t read_trigram(const string_view s, size_t start)
45 {
46         return read_unigram(s, start) |
47                 (read_unigram(s, start + 1) << 8) |
48                 (read_unigram(s, start + 2) << 16);
49 }
50
51 enum {
52         DBE_NORMAL = 0, /* A non-directory file */
53         DBE_DIRECTORY = 1, /* A directory */
54         DBE_END = 2 /* End of directory contents; contains no name */
55 };
56
57 // From mlocate.
58 struct db_header {
59         uint8_t magic[8];
60         uint32_t conf_size;
61         uint8_t version;
62         uint8_t check_visibility;
63         uint8_t pad[2];
64 };
65
66 // From mlocate.
67 struct db_directory {
68         uint64_t time_sec;
69         uint32_t time_nsec;
70         uint8_t pad[4];
71 };
72
73 class PostingListBuilder {
74 public:
75         inline void add_docid(uint32_t docid);
76         void finish();
77
78         string encoded;
79         size_t num_docids = 0;
80
81 private:
82         void write_header(uint32_t docid);
83         void append_block();
84
85         vector<uint32_t> pending_deltas;
86
87         uint32_t last_block_end, last_docid = -1;
88 };
89
90 void PostingListBuilder::add_docid(uint32_t docid)
91 {
92         // Deduplicate against the last inserted value, if any.
93         if (docid == last_docid) {
94                 return;
95         }
96
97         if (num_docids == 0) {
98                 // Very first docid.
99                 write_header(docid);
100                 ++num_docids;
101                 last_block_end = last_docid = docid;
102                 return;
103         }
104
105         pending_deltas.push_back(docid - last_docid - 1);
106         last_docid = docid;
107         if (pending_deltas.size() == 128) {
108                 append_block();
109                 pending_deltas.clear();
110                 last_block_end = docid;
111         }
112         ++num_docids;
113 }
114
115 void PostingListBuilder::finish()
116 {
117         if (pending_deltas.empty()) {
118                 return;
119         }
120
121         assert(!encoded.empty());  // write_header() should already have run.
122
123         // No interleaving for partial blocks.
124         unsigned char buf[P4NENC_BOUND(128)];
125         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), pending_deltas.size(), /*interleaved=*/false, buf);
126         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
127 }
128
129 void PostingListBuilder::append_block()
130 {
131         unsigned char buf[P4NENC_BOUND(128)];
132         assert(pending_deltas.size() == 128);
133         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), 128, /*interleaved=*/true, buf);
134         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
135 }
136
137 void PostingListBuilder::write_header(uint32_t docid)
138 {
139         unsigned char buf[P4NENC_BOUND(1)];
140         unsigned char *end = write_baseval(docid, buf);
141         encoded.append(reinterpret_cast<char *>(buf), end - buf);
142 }
143
144 class Corpus {
145 public:
146         Corpus(FILE *outfp, size_t block_size)
147                 : invindex(new PostingListBuilder *[NUM_TRIGRAMS]), outfp(outfp), block_size(block_size)
148         {
149                 fill(invindex.get(), invindex.get() + NUM_TRIGRAMS, nullptr);
150         }
151         ~Corpus()
152         {
153                 for (unsigned i = 0; i < NUM_TRIGRAMS; ++i) {
154                         delete invindex[i];
155                 }
156         }
157
158         void add_file(string filename);
159         void flush_block();
160
161         vector<uint64_t> filename_blocks;
162         size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
163         bool seen_trigram(uint32_t trgm)
164         {
165                 return invindex[trgm] != nullptr;
166         }
167         PostingListBuilder &get_pl_builder(uint32_t trgm)
168         {
169                 if (invindex[trgm] == nullptr) {
170                         invindex[trgm] = new PostingListBuilder;
171                 }
172                 return *invindex[trgm];
173         }
174
175 private:
176         unique_ptr<PostingListBuilder *[]> invindex;
177         FILE *outfp;
178         string current_block;
179         string tempbuf;
180         const size_t block_size;
181 };
182
183 void Corpus::add_file(string filename)
184 {
185         ++num_files;
186         if (!current_block.empty()) {
187                 current_block.push_back('\0');
188         }
189         current_block += filename;
190         if (++num_files_in_block == block_size) {
191                 flush_block();
192         }
193 }
194
195 void Corpus::flush_block()
196 {
197         if (current_block.empty()) {
198                 return;
199         }
200
201         uint32_t docid = num_blocks;
202
203         // Create trigrams.
204         const char *ptr = current_block.c_str();
205         while (ptr < current_block.c_str() + current_block.size()) {
206                 string_view s(ptr);
207                 if (s.size() >= 3) {
208                         for (size_t j = 0; j < s.size() - 2; ++j) {
209                                 uint32_t trgm = read_trigram(s, j);
210                                 get_pl_builder(trgm).add_docid(docid);
211                         }
212                 }
213                 ptr += s.size() + 1;
214         }
215
216         // Compress and add the filename block.
217         filename_blocks.push_back(ftell(outfp));
218         string compressed = zstd_compress(current_block, &tempbuf);
219         if (fwrite(compressed.data(), compressed.size(), 1, outfp) != 1) {
220                 perror("fwrite()");
221                 exit(1);
222         }
223
224         current_block.clear();
225         num_files_in_block = 0;
226         ++num_blocks;
227 }
228
229 string read_cstr(FILE *fp)
230 {
231         string ret;
232         for (;;) {
233                 int ch = getc(fp);
234                 if (ch == -1) {
235                         perror("getc");
236                         exit(1);
237                 }
238                 if (ch == 0) {
239                         return ret;
240                 }
241                 ret.push_back(ch);
242         }
243 }
244
245 void handle_directory(FILE *fp, Corpus *corpus)
246 {
247         db_directory dummy;
248         if (fread(&dummy, sizeof(dummy), 1, fp) != 1) {
249                 if (feof(fp)) {
250                         return;
251                 } else {
252                         perror("fread");
253                 }
254         }
255
256         string dir_path = read_cstr(fp);
257         if (dir_path == "/") {
258                 dir_path = "";
259         }
260
261         for (;;) {
262                 int type = getc(fp);
263                 if (type == DBE_NORMAL) {
264                         string filename = read_cstr(fp);
265                         corpus->add_file(dir_path + "/" + filename);
266                 } else if (type == DBE_DIRECTORY) {
267                         string dirname = read_cstr(fp);
268                         corpus->add_file(dir_path + "/" + dirname);
269                 } else {
270                         return;  // Probably end.
271                 }
272         }
273 }
274
275 void read_mlocate(const char *filename, Corpus *corpus)
276 {
277         FILE *fp = fopen(filename, "rb");
278         if (fp == nullptr) {
279                 perror(filename);
280                 exit(1);
281         }
282
283         db_header hdr;
284         if (fread(&hdr, sizeof(hdr), 1, fp) != 1) {
285                 perror("short read");
286                 exit(1);
287         }
288
289         // TODO: Care about the base path.
290         string path = read_cstr(fp);
291         while (!feof(fp)) {
292                 handle_directory(fp, corpus);
293         }
294         fclose(fp);
295 }
296
297 string zstd_compress(const string &src, string *tempbuf)
298 {
299         size_t max_size = ZSTD_compressBound(src.size());
300         if (tempbuf->size() < max_size) {
301                 tempbuf->resize(max_size);
302         }
303         static ZSTD_CCtx *ctx = ZSTD_createCCtx();  // Reused across calls.
304         size_t size = ZSTD_compressCCtx(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
305         return string(tempbuf->data(), size);
306 }
307
308 bool is_prime(uint32_t x)
309 {
310         if ((x % 2) == 0 || (x % 3) == 0) {
311                 return false;
312         }
313         uint32_t limit = ceil(sqrt(x));
314         for (uint32_t factor = 5; factor <= limit; ++factor) {
315                 if ((x % factor) == 0) {
316                         return false;
317                 }
318         }
319         return true;
320 }
321
322 uint32_t next_prime(uint32_t x)
323 {
324         if ((x % 2) == 0) {
325                 ++x;
326         }
327         while (!is_prime(x)) {
328                 x += 2;
329         }
330         return x;
331 }
332
333 unique_ptr<Trigram[]> create_hashtable(Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
334 {
335         unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]);  // 1 for the sentinel element at the end.
336         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
337                 ht[i].trgm = uint32_t(-1);
338                 ht[i].num_docids = 0;
339                 ht[i].offset = 0;
340         }
341         for (uint32_t trgm : all_trigrams) {
342                 // We don't know offset yet, so set it to zero.
343                 Trigram to_insert{ trgm, uint32_t(corpus.get_pl_builder(trgm).num_docids), 0 };
344
345                 uint32_t bucket = hash_trigram(trgm, ht_size);
346                 unsigned distance = 0;
347                 while (ht[bucket].num_docids != 0) {
348                         // Robin Hood hashing; reduces the longest distance by a lot.
349                         unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
350                         if (distance > other_distance) {
351                                 swap(to_insert, ht[bucket]);
352                                 distance = other_distance;
353                         }
354
355                         ++bucket, ++distance;
356                         if (distance > num_overflow_slots) {
357                                 return nullptr;
358                         }
359                 }
360                 ht[bucket] = to_insert;
361         }
362         return ht;
363 }
364
365 void do_build(const char *infile, const char *outfile, int block_size)
366 {
367         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
368
369         umask(0027);
370         FILE *outfp = fopen(outfile, "wb");
371
372         // Write the header.
373         Header hdr;
374         memcpy(hdr.magic, "\0plocate", 8);
375         hdr.version = -1;  // Mark as broken.
376         hdr.hashtable_size = 0;  // Not known yet.
377         hdr.extra_ht_slots = num_overflow_slots;
378         hdr.num_docids = 0;
379         hdr.hash_table_offset_bytes = -1;  // We don't know these offsets yet.
380         hdr.filename_index_offset_bytes = -1;
381         fwrite(&hdr, sizeof(hdr), 1, outfp);
382
383         Corpus corpus(outfp, block_size);
384
385         read_mlocate(infile, &corpus);
386         if (false) {  // To read a plain text file.
387                 FILE *fp = fopen(infile, "r");
388                 while (!feof(fp)) {
389                         char buf[1024];
390                         if (fgets(buf, 1024, fp) == nullptr || feof(fp)) {
391                                 break;
392                         }
393                         string s(buf);
394                         if (s.back() == '\n')
395                                 s.pop_back();
396                         corpus.add_file(move(s));
397                 }
398                 fclose(fp);
399         }
400         corpus.flush_block();
401         dprintf("Read %zu files from %s\n", corpus.num_files, infile);
402         hdr.num_docids = corpus.filename_blocks.size();
403
404         // Stick an empty block at the end as sentinel.
405         corpus.filename_blocks.push_back(ftell(outfp));
406         const size_t bytes_for_filenames = corpus.filename_blocks.back() - corpus.filename_blocks.front();
407
408         // Write the offsets to the filenames.
409         hdr.filename_index_offset_bytes = ftell(outfp);
410         const size_t bytes_for_filename_index = corpus.filename_blocks.size() * sizeof(uint64_t);
411         fwrite(corpus.filename_blocks.data(), corpus.filename_blocks.size(), sizeof(uint64_t), outfp);
412         corpus.filename_blocks.clear();
413         corpus.filename_blocks.shrink_to_fit();
414
415         // Finish up encoding the posting lists.
416         size_t trigrams = 0, longest_posting_list = 0;
417         size_t bytes_for_posting_lists = 0;
418         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
419                 if (!corpus.seen_trigram(trgm))
420                         continue;
421                 PostingListBuilder &pl_builder = corpus.get_pl_builder(trgm);
422                 pl_builder.finish();
423                 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
424                 trigrams += pl_builder.num_docids;
425                 bytes_for_posting_lists += pl_builder.encoded.size();
426         }
427         dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
428                 corpus.num_files, corpus.invindex.size(), trigrams, double(trigrams) / corpus.invindex.size(), longest_posting_list);
429         dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_for_posting_lists, 8 * bytes_for_posting_lists / double(trigrams));
430
431         dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - start).count());
432
433         // Find the used trigrams.
434         vector<uint32_t> all_trigrams;
435         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
436                 if (corpus.seen_trigram(trgm)) {
437                         all_trigrams.push_back(trgm);
438                 }
439         }
440
441         // Create the hash table.
442         unique_ptr<Trigram[]> hashtable;
443         uint32_t ht_size = next_prime(all_trigrams.size());
444         for (;;) {
445                 hashtable = create_hashtable(corpus, all_trigrams, ht_size, num_overflow_slots);
446                 if (hashtable == nullptr) {
447                         dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
448                         ht_size = next_prime(ht_size * 1.05);
449                 } else {
450                         dprintf("Created hash table of size %u.\n\n", ht_size);
451                         break;
452                 }
453         }
454
455         // Find the offsets for each posting list.
456         size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
457         uint64_t offset = ftell(outfp) + bytes_for_hashtable;
458         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
459                 hashtable[i].offset = offset;  // Needs to be there even for empty slots.
460                 if (hashtable[i].num_docids == 0) {
461                         continue;
462                 }
463
464                 const string &encoded = corpus.get_pl_builder(hashtable[i].trgm).encoded;
465                 offset += encoded.size();
466         }
467
468         // Write the hash table.
469         hdr.hash_table_offset_bytes = ftell(outfp);
470         hdr.hashtable_size = ht_size;
471         fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
472
473         // Write the actual posting lists.
474         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
475                 if (hashtable[i].num_docids == 0) {
476                         continue;
477                 }
478                 const string &encoded = corpus.get_pl_builder(hashtable[i].trgm).encoded;
479                 fwrite(encoded.data(), encoded.size(), 1, outfp);
480         }
481
482         // Rewind, and write the updated header.
483         hdr.version = 0;
484         fseek(outfp, 0, SEEK_SET);
485         fwrite(&hdr, sizeof(hdr), 1, outfp);
486         fclose(outfp);
487
488         size_t total_bytes __attribute__((unused)) = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
489
490         dprintf("Block size:     %7d files\n", block_size);
491         dprintf("Hash table:     %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
492         dprintf("Posting lists:  %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
493         dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
494         dprintf("Filenames:      %'7.1f MB\n", bytes_for_filenames / 1048576.0);
495         dprintf("Total:          %'7.1f MB\n", total_bytes / 1048576.0);
496         dprintf("\n");
497 }
498
499 void usage()
500 {
501         printf(
502                 "Usage: plocate-build MLOCATE_DB PLOCATE_DB\n"
503                 "\n"
504                 "Generate plocate index from mlocate.db, typically /var/lib/mlocate/mlocate.db.\n"
505                 "Normally, the destination should be /var/lib/mlocate/plocate.db.\n"
506                 "\n"
507                 "  -b, --block-size SIZE  number of filenames to store in each block (default 32)\n"
508                 "      --help             print this help\n"
509                 "      --version          print version information\n");
510 }
511
512 void version()
513 {
514         printf("plocate-build %s\n", PLOCATE_VERSION);
515         printf("Copyright 2020 Steinar H. Gunderson\n");
516         printf("License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html>.\n");
517         printf("This is free software: you are free to change and redistribute it.\n");
518         printf("There is NO WARRANTY, to the extent permitted by law.\n");
519 }
520
521 int main(int argc, char **argv)
522 {
523         static const struct option long_options[] = {
524                 { "block-size", required_argument, 0, 'b' },
525                 { "help", no_argument, 0, 'h' },
526                 { "version", no_argument, 0, 'V' },
527                 { 0, 0, 0, 0 }
528         };
529
530         int block_size = 32;
531
532         setlocale(LC_ALL, "");
533         for (;;) {
534                 int option_index = 0;
535                 int c = getopt_long(argc, argv, "b:hV", long_options, &option_index);
536                 if (c == -1) {
537                         break;
538                 }
539                 switch (c) {
540                 case 'b':
541                         block_size = atoi(optarg);
542                         break;
543                 case 'h':
544                         usage();
545                         exit(0);
546                 case 'v':
547                         version();
548                         exit(0);
549                 default:
550                         exit(1);
551                 }
552         }
553
554         if (argc - optind != 2) {
555                 usage();
556                 exit(1);
557         }
558
559         do_build(argv[optind], argv[optind + 1], block_size);
560         exit(EXIT_SUCCESS);
561 }