-
Notifications
You must be signed in to change notification settings - Fork 0
/
logdb.h
2259 lines (1774 loc) · 65.6 KB
/
logdb.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
logdb -- A simple log-structured database.
<https://github.com/torrentg/logdb>
Copyright (c) 2024 Gerard Torrent <gerard@generacio.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef LOGDB_H
#define LOGDB_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
/**
* Logdb is a simple database with the following characteristics:
* - Variable length record type
* - Records uniquely identified by a sequential number (seqnum)
* - Records are indexed by timestamp (monotonic non-decreasing field)
* - There are no other indexes other than seqnum and timestamp.
* - Records can be appended, read, and searched
* - Records can not be updated nor deleted
* - Allows to revert last entries (rollback)
* - Allows to remove obsolete entries (purge)
* - Read-write concurrency supported (multi-thread)
* - Automatic data recovery on catastrofic event
* - Minimal memory footprint
*
* Use cases:
* - Storage engine in a raft library (fault-tolerant distributed applications)
* - Storage engine for journal-based apps
*
* Basically, logdb is an append-only data file (\*.dat) with
* an index file (\*.idx) used to speed up lookups. No complex
* data structures, no sofisticated algorithms, only basic file
* access. We rely on the filesystem cache (managed by the operating
* system) to ensure read performance.
*
* dat file format
* ---------------
*
* Contains the database data.
*
* @see struct ldb_header_dat_t
* @see struct ldb_record_dat_t
*
* header record1 data1 record2 data2
* ┌──────┴──────┐┌─────┴─────┐┌────────┴────────┐┌─────┴─────┐┌─────┴─────┐...
* magic number seqnum1 raw bytes 1 seqnum2 raw bytes 2
* format timestamp1 timestamp2
* etc checksum1 checksum2
* length1 length2
*
* idx file format
* ---------------
*
* Used to search database entries.
* If idx file does not exist, it is rebuilt from the data.
*
* @see struct ldb_header_idx_t
* @see struct ldb_record_idx_t
*
* header record1 record2
* ┌──────┴──────┐┌─────┴─────┐┌─────┴─────┐...
* magic number seqnum1 seqnum1
* format timestamp1 timestamp2
* etc pos1 pos2
*
* We can access directly any record by seqnum because:
* - we know the first seqnum in the db
* - we know the last seqnum in the db
* - idx header has fixed size
* - all idx records have same size
*
* We use the binary search method over the index records to search data by timestamp.
* In all cases we rely on the system file caches to store data in memory.
*
* Concurrency
* ---------------
*
* Main goal: append() function not blocked.
* File write ops are done with [dat|idx]_fp.
* File read ops are done with [dat|idx]_fd.
*
* We use 2 mutex:
* - data mutex: grants data integrity ([first|last]_[seqnum|timestamp])
* reduced scope (variables update)
* - file mutex: grants that no reads are done during destructive writes
* extended scope (function execution)
*
* File Data
* Thread Function Mutex Mutex Notes
* -------------------------------------------------------------------
* ┌ open() - - Init mutexes, create FILE's used to write and fd's used to read
* ├ append() - W dat and idx files flushed at the end. State updated after flush.
* thread-write: ┼ rollback() W W
* ├ purge() W W
* └ close() - - Destroy mutexes, close files
* ┌ stats() R R
* thread-read: ┼ read() R R
* └ search() R R
*/
#define LDB_VERSION_MAJOR 1
#define LDB_VERSION_MINOR 1
#define LDB_VERSION_PATCH 0
#define LDB_OK 0
#define LDB_ERR -1
#define LDB_ERR_ARG -2
#define LDB_ERR_MEM -3
#define LDB_ERR_PATH -4
#define LDB_ERR_NAME -5
#define LDB_ERR_OPEN_DAT -6
#define LDB_ERR_READ_DAT -7
#define LDB_ERR_WRITE_DAT -8
#define LDB_ERR_OPEN_IDX -9
#define LDB_ERR_READ_IDX -10
#define LDB_ERR_WRITE_IDX -11
#define LDB_ERR_FMT_DAT -12
#define LDB_ERR_FMT_IDX -13
#define LDB_ERR_ENTRY_SEQNUM -14
#define LDB_ERR_ENTRY_TIMESTAMP -15
#define LDB_ERR_ENTRY_METADATA -16
#define LDB_ERR_ENTRY_DATA -17
#define LDB_ERR_NOT_FOUND -18
#define LDB_ERR_TMP_FILE -19
#define LDB_ERR_CHECKSUM -20
#ifdef __cplusplus
extern "C" {
#endif
struct ldb_impl_t;
typedef struct ldb_impl_t ldb_db_t;
typedef enum ldb_search_e {
LDB_SEARCH_LOWER, // Search first entry having timestamp not less than value.
LDB_SEARCH_UPPER // Search first entry having timestamp greater than value.
} ldb_search_e;
typedef struct ldb_state_t {
uint64_t seqnum1; // Initial seqnum (0 means no entries)
uint64_t timestamp1; // Timestamp of the first entry
uint64_t seqnum2; // Ending seqnum (0 means no entries)
uint64_t timestamp2; // Timestamp of the last entry
} ldb_state_t;
typedef struct ldb_entry_t {
uint64_t seqnum;
uint64_t timestamp;
uint32_t metadata_len;
uint32_t data_len;
void *metadata;
void *data;
} ldb_entry_t;
typedef struct ldb_stats_t {
uint64_t min_seqnum;
uint64_t max_seqnum;
uint64_t min_timestamp;
uint64_t max_timestamp;
size_t num_entries;
size_t data_size;
size_t index_size;
} ldb_stats_t;
/**
* Returns ldb library version.
* @return Library version (semantic version, ex. 1.0.4).
*/
const char * ldb_version(void);
/**
* Returns the textual description of the ldb error code.
*
* @param[in] errnum Code error.
* @return Textual description.
*/
const char * ldb_strerror(int errnum);
/**
* Deallocates the memory pointed by the entry.
* It do not dealloc the entry itself.
*
* Use this function to deallocate entries returned by ldb_read().
* Updates entry pointers to NULL and lengths to 0.
*
* @param[in,out] entry Entry to dealloc data (if NULL does nothing).
*/
void ldb_free_entry(ldb_entry_t *entry);
/**
* Deallocates the memory of an array of entries.
*
* This is an utility function that calls ldb_free_entry() for
* each array item.
*
* @param[in] entries Array of entries (if NULL does nothing).
* @param[in] len Number of entries.
*/
void ldb_free_entries(ldb_entry_t *entries, size_t len);
/**
* Allocate a new ldb_db_t (opaque) object.
*
* @return Allocated object or NULL if no memory.
*/
ldb_db_t * ldb_alloc(void);
/**
* Deallocates a ldb_db_t object.
*
* @param obj Object to deallocate.
*/
void ldb_free(ldb_db_t *obj);
/**
* Open a database.
*
* Creates database files (dat+idx) if they not exists.
* Update index file if incomplete (not flushed + crash).
* Rebuild index file when corrupted or not found.
*
* @param[in,out] obj Uninitialized database object.
* @param[in] path Directory where database files are located.
* @param[in] name Database name (chars allowed: [a-ZA-Z0-9_], max length = 32).
* @param[in] check Check database files (true|false).
* @return Error code (0 = OK). On error db is closed properly (ldb_close not required).
* You can check errno value to get additional error details.
*/
int ldb_open(ldb_db_t *obj, const char *path, const char *name, bool check);
/**
* Close a database.
*
* Close open files and release allocated memory.
*
* @param[in,out] obj Database to close.
* @return Return code (0 = OK).
*/
int ldb_close(ldb_db_t *obj);
/**
* Append entries to the database.
*
* Entries are identified by its seqnum.
* First entry can have any seqnum distinct than 0.
* The rest of entries must have correlative values (no gaps).
*
* Each entry has an associated timestamp (distinct than 0).
* If no timestamp value is provided (0 value), logdb populates this
* field with milliseconds from epoch time. Otherwise, the meaning and
* units of this field are user-defined. Logdb verifies that the timestamp
* is equal to or greater than the timestamp of the preceding entry.
* It is legit for multiple records to have an identical timestamp
* because they were logged within the timestamp granularity.
*
* This function is not 'atomic'. Entries are appended sequentially.
* On error (ex. disk full) writed entries are flushed and remaining entries
* are reported as not writed (see num return argument).
*
* Seqnum values:
* - equals to 0 -> system assigns the sequential value.
* - distinct than 0 -> system check that it is the next value.
*
* Timestamp values:
* - equals to 0: system assigns the current UTC epoch time (in millis).
* - distinct than 0 -> system check that is bigger or equal to previous timestamp.
*
* File operations:
* - Data file is updated and flushed.
* - Index file is updated but not flushed.
*
* Memory pointed by entries is not modified and can be deallocated after function call.
*
* @param[in] obj Database to modify.
* @param[in,out] entries Entries to append to the database. Memory pointed
* by each entry is not modified. Seqnum and timestamp
* are updated if they have value 0.
* User must reset pointers before reuse.
* @param[in] len Number of entries to append.
* @param[out] num Number of entries appended (can be NULL).
* @return Error code (0 = OK).
*/
int ldb_append(ldb_db_t *obj, ldb_entry_t *entries, size_t len, size_t *num);
/**
* Read num entries starting from seqnum (included).
*
* @param[in] obj Database to use.
* @param[in] seqnum Initial sequence number.
* @param[out] entries Array of entries (min length = len).
* These entries are uninitialized (with NULL pointers) or entries
* previously initialized by ldb_read() function. In this case, the
* allocated memory is reused and will be reallocated if not enough.
* Use ldb_free_entry() to dealloc returned entries.
* @param[in] len Number of entries to read.
* @param[out] num Number of entries read (can be NULL). If num less than 'len' means
* that last record was reached. Unused entries are signaled with
* seqnum = 0.
* @return Error code (0 = OK).
*/
int ldb_read(ldb_db_t *obj, uint64_t seqnum, ldb_entry_t *entries, size_t len, size_t *num);
/**
* Return statistics between seqnum1 and seqnum2 (both included).
*
* @param[in] obj Database to use.
* @param[in] seqnum1 First sequence number.
* @param[in] seqnum2 Second sequence number (greater or equal than seqnum1).
* @param[out] stats Uninitialized statistics.
* @return Error code (0 = OK).
*/
int ldb_stats(ldb_db_t *obj, uint64_t seqnum1, uint64_t seqnum2, ldb_stats_t *stats);
/**
* Search the seqnum corresponding to the given timestamp.
*
* Use the binary search algorithm over the index file.
*
* @param[in] obj Database to use.
* @param[in] ts Timestamp to search.
* @param[in] mode Search mode.
* @param[out] seqnum Resulting seqnum (distinct than NULL, 0 = NOT_FOUND).
* @return Error code (0 = OK).
*/
int ldb_search(ldb_db_t *obj, uint64_t ts, ldb_search_e mode, uint64_t *seqnum);
/**
* Remove all entries greater than seqnum.
*
* File operations:
* - Index file is updated (zero'ed top-to-bottom) and flushed.
* - Data file is updated (zero'ed bottom-to-top) and flushed.
*
* @param[in] obj Database to update.
* @param[in] seqnum Sequence number from which records are removed (seqnum=0 removes all content).
* @return Number of removed entries, or error if negative.
*/
long ldb_rollback(ldb_db_t *obj, uint64_t seqnum);
/**
* Remove all entries less than seqnum.
*
* This function is expensive because recreates the dat and idx files.
*
* To prevent data loss in case of outage we do:
* - A tmp data file is created.
* - Preserved records are copied from dat file to tmp file.
* - Tmp, dat and idx are closed
* - Idx file is removed
* - Tmp file is renamed to dat
* - Dat file is opened
* - Idx file is rebuilt
*
* @param[in] obj Database to update.
* @param[in] seqnum Sequence number up to which records are removed.
* @return Number of removed entries, or error if negative.
*/
long ldb_purge(ldb_db_t *obj, uint64_t seqnum);
#ifdef __cplusplus
}
#endif
#endif /* LOGDB_H */
/* ------------------------------------------------------------------------- */
#ifdef LDB_IMPL
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <pthread.h>
#include <sys/stat.h>
#define LDB_EXT_DAT ".dat"
#define LDB_EXT_IDX ".idx"
#define LDB_EXT_TMP ".tmp"
#define LDB_PATH_SEPARATOR "/"
#define LDB_NAME_MAX_LENGTH 32
#define LDB_TEXT_LEN 128 /* value multiple of 8 to preserve alignment */
#define LDB_TEXT_DAT "\nThis is a ldb database dat file.\nDon't edit it.\n"
#define LDB_TEXT_IDX "\nThis is a ldb database idx file.\nDon't edit it.\n"
#define LDB_MAGIC_NUMBER 0x211ABF1A62646C00
#define LDB_FORMAT_1 1
typedef struct ldb_impl_t
{
// Fixed info (unchanged)
char *name; // Database name
char *path; // Directory where files are located
char *dat_path; // Data filepath (path + filename)
char *idx_path; // Index filepath (path + filename)
uint32_t format; // File format
// Thread-write variables
FILE *dat_fp; // Data file pointer (used to write)
FILE *idx_fp; // Index file pointer (used to write)
size_t dat_end; // Last position on data file
bool force_fsync; // Force fsync after flush
char padding[64]; // Padding to avoid destructive interference between threads
// Thread-read variables
int dat_fd; // Data file descriptor (used to read)
int idx_fd; // Index file descriptor (used to read)
// Shared data (accessed by both threads)
ldb_state_t state; // First and last seqnums and timestamps
// Guards
pthread_mutex_t mutex_data; // Prevents race condition on state values
pthread_mutex_t mutex_files; // Preserve coherence between shared variable and file contents
} ldb_impl_t;
typedef struct ldb_header_dat_t {
uint64_t magic_number;
uint32_t format;
char text[LDB_TEXT_LEN];
} ldb_header_dat_t;
typedef struct ldb_header_idx_t {
uint64_t magic_number;
uint32_t format;
char text[LDB_TEXT_LEN];
} ldb_header_idx_t;
typedef struct ldb_record_dat_t {
uint64_t seqnum;
uint64_t timestamp;
uint32_t metadata_len;
uint32_t data_len;
uint32_t checksum;
} ldb_record_dat_t;
typedef struct ldb_record_idx_t {
uint64_t seqnum;
uint64_t timestamp;
uint64_t pos;
} ldb_record_idx_t;
#if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_LLVM_COMPILER)
#define LDB_INLINE __attribute__((const)) __attribute__((always_inline)) inline
#else
#define LDB_INLINE /**/
#endif
#if defined __has_attribute
#if __has_attribute(__fallthrough__)
# define fallthrough __attribute__((__fallthrough__))
#endif
#endif
#ifndef fallthrough
# define fallthrough do {} while (0) /* fallthrough */
#endif
/* generated using the AUTODIN II polynomial
* x^32 + x^26 + x^23 + x^22 + x^16 +
* x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x^1 + 1
*/
static const uint32_t ldb_crctab[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
#define LDB_CRC(crc, ch) (crc = (crc >> 8) ^ ldb_crctab[(crc ^ (ch)) & 0xff])
/**
* Computes the crc32 checksum.
*
* @see https://opensource.apple.com/source/file_cmds/file_cmds-188/cksum/crc32.c
*
* @param bytes Bytes to digest.
* @param len Bytes length.
* @param checksum Previous checksum value (0 on startup).
* @return Checksum value updated.
*/
uint32_t ldb_crc32(const char *bytes, size_t len, uint32_t checksum)
{
if (bytes == NULL || len == 0)
return checksum;
checksum = ~checksum;
for (size_t i = 0; i < len; i++)
LDB_CRC(checksum, (unsigned char) bytes[i]);
return ~checksum;
}
const char * ldb_strerror(int errnum)
{
if (errnum > 0)
return "Success";
switch(errnum)
{
case LDB_OK: return "Success";
case LDB_ERR: return "Generic error";
case LDB_ERR_ARG: return "Invalid argument";
case LDB_ERR_MEM: return "Out of memory";
case LDB_ERR_NAME: return "Invalid db name";
case LDB_ERR_PATH: return "Invalid directory";
case LDB_ERR_OPEN_DAT: return "Cannot open dat file";
case LDB_ERR_READ_DAT: return "Error reading dat file";
case LDB_ERR_WRITE_DAT: return "Error writing to dat file";
case LDB_ERR_OPEN_IDX: return "Cannot open idx file";
case LDB_ERR_READ_IDX: return "Error reading idx file";
case LDB_ERR_WRITE_IDX: return "Error writing to idx file";
case LDB_ERR_FMT_DAT: return "Invalid dat file";
case LDB_ERR_FMT_IDX: return "Invalid idx file";
case LDB_ERR_ENTRY_SEQNUM: return "Broken sequence";
case LDB_ERR_ENTRY_TIMESTAMP: return "Invalid timestamp";
case LDB_ERR_ENTRY_METADATA: return "Metadata not found";
case LDB_ERR_ENTRY_DATA: return "Data not found";
case LDB_ERR_NOT_FOUND: return "No results";
case LDB_ERR_TMP_FILE: return "Error creating temp file";
case LDB_ERR_CHECKSUM: return "Checksum mismatch";
default: return "Unknown error";
}
}
static uint64_t ldb_get_millis(void)
{
struct timespec ts = {0};
if (clock_gettime(CLOCK_REALTIME, &ts) != 0)
return 0;
return (uint64_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}
LDB_INLINE
static size_t ldb_min(size_t a, size_t b) {
return (a < b ? a : b);
}
LDB_INLINE
static uint64_t ldb_max(uint64_t a, uint64_t b) {
return (a > b ? a : b);
}
LDB_INLINE
static uint64_t ldb_clamp(uint64_t val, uint64_t lo, uint64_t hi) {
return (val < lo ? lo : (hi < val ? hi : val));
}
LDB_INLINE
static bool ldb_is_valid_db(ldb_impl_t *obj) {
return (obj &&
obj->dat_fp && !feof(obj->dat_fp) && !ferror(obj->dat_fp) &&
obj->idx_fp && !feof(obj->idx_fp) && !ferror(obj->idx_fp) &&
obj->dat_fd > STDERR_FILENO &&
obj->idx_fd > STDERR_FILENO);
}
static void ldb_reset_state(ldb_state_t *state) {
if (state) {
state->seqnum1 = 0;
state->timestamp1 = 0;
state->seqnum2 = 0;
state->timestamp2 = 0;
}
}
static int ldb_close_files(ldb_impl_t *obj)
{
if (!obj)
return LDB_OK;
int ret = LDB_OK;
if (obj->idx_fp != NULL && fclose(obj->idx_fp) != 0)
ret = LDB_ERR_WRITE_IDX;
if (obj->idx_fd > STDERR_FILENO && close(obj->idx_fd) == -1)
ret = LDB_ERR_WRITE_IDX;
if (obj->dat_fp != NULL && fclose(obj->dat_fp) != 0)
ret = LDB_ERR_WRITE_DAT;
if (obj->dat_fd > STDERR_FILENO && close(obj->dat_fd) == -1)
ret = LDB_ERR_WRITE_DAT;
obj->dat_fp = NULL;
obj->idx_fp = NULL;
obj->dat_fd = -1;
obj->idx_fd = -1;
obj->dat_end = 0;
return ret;
}
#define LDB_FREE(ptr) do { free(ptr); ptr = NULL; } while(0)
int ldb_close(ldb_impl_t *obj)
{
if (obj == NULL)
return LDB_OK;
int ret = ldb_close_files(obj);
ldb_reset_state(&obj->state);
if (obj->name) {
pthread_mutex_destroy(&obj->mutex_data);
pthread_mutex_destroy(&obj->mutex_files);
}
LDB_FREE(obj->name);
LDB_FREE(obj->path);
LDB_FREE(obj->dat_path);
LDB_FREE(obj->idx_path);
return ret;
}
#undef LDB_FREE
// only deallocs memory, does not modify seqnum nor timestamp
void ldb_free_entry(ldb_entry_t *entry)
{
if (entry == NULL)
return;
// ldb_alloc_entry() does only 1 mem allocation
free(entry->metadata);
entry->metadata = NULL;
entry->data = NULL;
entry->metadata_len = 0;
entry->data_len = 0;
}
void ldb_free_entries(ldb_entry_t *entries, size_t len)
{
if (entries == NULL || len == 0)
return;
for (size_t i = 0; i < len; i++)
ldb_free_entry(entries + i);
}
// returns size adjusted to a multiple of sizeof(intptr_t)
LDB_INLINE
static size_t ldb_allocated_size(size_t size) {
size_t rem = size % sizeof(intptr_t);
return size + (rem == 0 ? 0 : sizeof(intptr_t) - rem);
}
// try to reuse previous allocated memory
// otherwise, free existent memory and does only 1 memory allocation
// both returned pointer are aligned to generic type intptr_t
// returns false on error (allocation error)
static bool ldb_alloc_entry(ldb_entry_t *entry, uint32_t metadata_len, uint32_t data_len)
{
if (entry == NULL)
return false;
if ((entry->metadata_len > 0 && entry->metadata == NULL) ||
(entry->data_len > 0 && entry->data == NULL) ||
(entry->metadata == NULL && entry->data != NULL))
return false;
size_t len1 = ldb_allocated_size(metadata_len);
size_t len2 = ldb_allocated_size(data_len);
assert((len1 + len2) % sizeof(intptr_t) == 0);
char *ptr = NULL;
if (len1 + len2 <= ldb_allocated_size(entry->metadata_len) + ldb_allocated_size(entry->data_len)) {
ptr = entry->metadata ? entry->metadata : (entry->data ? entry->data : NULL);
}
else {
ldb_free_entry(entry);
ptr = (char *) calloc((len1 + len2)/sizeof(intptr_t), sizeof(intptr_t));
if (ptr == NULL)
return false;
}
entry->metadata = ptr;
entry->metadata_len = metadata_len;
entry->data = ptr + (data_len == 0 ? 0 : len1);
entry->data_len = data_len;
return true;
}
static bool ldb_is_valid_path(const char *path)
{
struct stat statbuf = {0};
if (path == NULL)
return false;
if (*path == 0) // case cwd (current working directory)
return true;
if (stat(path, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
return false;
return true;
}
static bool ldb_is_valid_name(const char *name)
{
if (!name || *name == 0)
return false;
const char *ptr = name;
while (*ptr != 0 && (isalnum(*ptr) || *ptr == '_'))
ptr++;
return (*ptr == 0 && ptr - name < LDB_NAME_MAX_LENGTH);
}
static char * ldb_create_filename(const char *path, const char *name, const char *ext)
{
if (path == NULL || name == NULL || ext == NULL || *name == 0)
return NULL;
size_t len = strlen(path);
bool path_sep_required = (len > 0 && path[len -1] != LDB_PATH_SEPARATOR[0]);
len = len + 1 + strlen(name) + strlen(ext) + 1;
char *filepath = (char *) calloc(len, 1);
if (filepath == NULL)
return NULL;
snprintf(filepath, len, "%s%s%s%s",
path,
(path_sep_required ? LDB_PATH_SEPARATOR : ""),
name,
ext);
return filepath;
}
static bool ldb_create_file_dat(const char *path)
{
assert(path);
if (access(path, F_OK) == 0)
return false;
bool ret = true;
FILE *fp = fopen(path, "wx");
if (fp == NULL)
return false;
ldb_header_dat_t header = {
.magic_number = LDB_MAGIC_NUMBER,
.format = LDB_FORMAT_1,
.text = {0}
};
strncpy(header.text, LDB_TEXT_DAT, sizeof(header.text));
if (fwrite(&header, sizeof(ldb_header_dat_t), 1, fp) != 1)
ret = false;
if (fclose(fp) != 0)
ret = false;
return ret;
}
static bool ldb_create_file_idx(const char *path)
{
assert(path);
if (access(path, F_OK) == 0)
return false;
bool ret = true;
FILE *fp = fopen(path, "wx");
if (fp == NULL)
return false;
ldb_header_idx_t header = {
.magic_number = LDB_MAGIC_NUMBER,
.format = LDB_FORMAT_1,
.text = {0}
};
strncpy(header.text, LDB_TEXT_IDX, sizeof(header.text));
if (fwrite(&header, sizeof(ldb_header_idx_t), 1, fp) != 1)
ret = false;
if (fclose(fp) != 0)
ret = false;
return ret;
}
// Returns file size preserving current file position
// Returns 0 on error
static size_t ldb_get_file_size(FILE *fp)
{
if (fp == NULL)
return 0;
long pos = ftell(fp);
if (pos < 0)
return 0;
if (fseek(fp, 0, SEEK_END) != 0)
return 0;
long len = ftell(fp);
if (fseek(fp, pos, SEEK_SET) != 0)
return 0;
return (size_t)(len < 0 ? 0 : len);
}
// Set zero's from pos until the end of the file.
// Does not update file if already zeroized.
// Preserve current file position.
// On error return false, otherwise returns true.
static bool ldb_zeroize(FILE *fp, size_t pos)
{
assert(fp);
assert(!feof(fp));
assert(!ferror(fp));
char c = 0;
bool ret = false;
size_t cur_pos = pos;
size_t max_pos = ldb_get_file_size(fp);
const char buf[BUFSIZ] = {0};
if (max_pos < pos)
goto LDB_ZEROIZE_END;
if (fseek(fp, (long) pos, SEEK_SET) != 0)
goto LDB_ZEROIZE_END;
for (cur_pos = pos; cur_pos < max_pos; cur_pos++)
{
if (fread(&c, 1, 1, fp) != 1)
goto LDB_ZEROIZE_END;
if (c == 0)
continue;
if (fseek(fp, -1, SEEK_CUR) != 0)
goto LDB_ZEROIZE_END;
break;
}
// case already zeroized
if (c == 0) {
ret = true;
goto LDB_ZEROIZE_END;
}
for (; cur_pos < max_pos; cur_pos += sizeof(buf))
if (fwrite(buf, ldb_min(max_pos - cur_pos, sizeof(buf)), 1, fp) != 1)
goto LDB_ZEROIZE_END;
fflush(fp);
ret = true;
LDB_ZEROIZE_END:
fseek(fp, (long) pos, SEEK_SET);
assert(!feof(fp) && !ferror(fp));
return ret;
}
// Copy file1 content in range [pos0,pos1] to file2 at pos2.
// Preserve current file positions.
// Flush destination file.
// On error return false, otherwise returns true.
static bool ldb_copy_file(FILE *fp1, size_t pos0, size_t pos1, FILE *fp2, size_t pos2)
{
assert(fp1);
assert(!feof(fp1));
assert(!ferror(fp1));
assert(fp2);
assert(!feof(fp2));
assert(!ferror(fp2));
assert(pos0 <= pos1);
bool ret = false;
char buf[BUFSIZ] = {0};
long orig1 = ftell(fp1);
long orig2 = ftell(fp2);
size_t len1 = ldb_get_file_size(fp1);
size_t len2 = ldb_get_file_size(fp2);
if (orig1 < 0 || orig2 < 0)
return false;
if (pos0 > pos1 || pos1 > len1 || pos2 > len2)
return false;
if (pos0 == pos1)
return true;
if (fseek(fp1, (long) pos0, SEEK_SET) != 0)
goto LDB_COPY_FILE_END;
if (fseek(fp2, (long) pos2, SEEK_SET) != 0)
goto LDB_COPY_FILE_END;
for (size_t pos = pos0; pos < pos1; pos += sizeof(buf))
{
size_t num_bytes = ldb_min(pos1 - pos, sizeof(buf));
if (fread(buf, 1, num_bytes, fp1) != num_bytes)
goto LDB_COPY_FILE_END;
if (fwrite(buf, num_bytes, 1, fp2) != 1)
goto LDB_COPY_FILE_END;
}
ret = true;
LDB_COPY_FILE_END:
fseek(fp1, orig1, SEEK_SET);
fseek(fp2, orig2, SEEK_SET);
assert(!feof(fp1) && !ferror(fp1));
assert(!feof(fp2) && !ferror(fp2));
return ret;
}
// returns the position in the idx for a given seqnum
static size_t ldb_get_pos_idx(ldb_state_t *state, uint64_t seqnum)
{
assert(state);
assert(state->seqnum1 <= seqnum);