forked from ElektraInitiative/libelektra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkdb.c
1927 lines (1705 loc) · 56.2 KB
/
kdb.c
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
/**
* @file
*
* @brief Low level functions for access the Key Database.
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#ifdef HAVE_KDBCONFIG_H
#include "kdbconfig.h"
#endif
#if DEBUG && defined(HAVE_STDIO_H)
#include <stdio.h>
#endif
#include <kdbassert.h>
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STDARG_H
#include <stdarg.h>
#endif
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include <kdbinternal.h>
/**
* @defgroup kdb KDB
* @brief General methods to access the Key database.
*
* To use them:
* @code
* #include <kdb.h>
* @endcode
*
* The kdb*() methods are used to access the storage, to get and set
* @link keyset KeySets@endlink.
*
* Parameters common for all these functions are:
*
* - *handle*, as returned by kdbOpen(), need to be passed to every call
* - *parentKey* is used for every call to add warnings and set an
* error. For kdbGet() / kdbSet() it is used to give an hint which keys
* should be retrieved/stored.
*
* @note The parentKey is an obligation for you, but only an hint for KDB.
* KDB does not remember anything
* about the configuration. You need to pass the same configuration
* back to kdbSet(), otherwise parts of the configuration get
* lost. Only keys below the parentKey are subject for change, the rest
* must be left untouched.
*
* KDB uses different backend implementations that know the details
* about how to access the storage.
* One backend consists of multiple plugins.
* See @link plugin writing a new plugin @endlink for information
* about how to write a plugin.
* Backends are state-less regarding the configuration (because of that
* you must pass back the whole configuration for every backend), but
* have a state for:
*
* - a two phase-commit
* - a conflict detection (error C02000) and
* - optimizations that avoid redoing already done operations.
*
* @image html state.png "State"
* @image latex state.png "State"
*
* As we see in the figure, kdbOpen() can be called arbitrarily often in any
* number of threads.
*
* For every handle you got from kdbOpen(), for every parentKey with a
* different name, *only* the shown state transitions
* are valid. From a freshly opened KDB, only kdbGet() and kdbClose()
* are allowed, because otherwise conflicts (error C02000) would not be detected.
*
* Once kdbGet() was called (for a specific handle+parentKey),
* any number of kdbGet() and kdbSet() can be
* used with this handle respective parentKey, unless kdbSet() had
* a conflict (error C02000) with another application.
* Every affair with KDB needs to be finished with kdbClose().
*
* The name of the parentKey in kdbOpen() and kdbClose() does not matter.
*
* In the usual case we just have one parentKey and one handle. In
* these cases we just have to remember to use kdbGet() before
* kdbSet():
*
* @include kdbintro.c
*
* To output warnings, you can use following code:
*
* @snippet tests.c warnings
*
* To output the error, you can use following code:
*
* @snippet tests.c error
*
* @{
*/
/**
* @internal
* Helper which iterates over MetaKeys from key
* and removes all MetaKeys starting with
* searchfor.
*/
void elektraRemoveMetaData (Key * key, const char * searchfor)
{
const Key * iter_key;
keyRewindMeta (key);
while ((iter_key = keyNextMeta (key)) != 0)
{
/*startsWith*/
if (strncmp (searchfor, keyName (iter_key), strlen (searchfor)) == 0)
{
keySetMeta (key, keyName (iter_key), 0);
}
}
}
/**
* @brief Takes the first key and cuts off this common part
* for all other keys, instead name will be prepended
*
* @return a new allocated keyset with keys in user namespace.
*
* The first key is removed in the resulting keyset.
*/
KeySet * ksRenameKeys (KeySet * config, const char * name)
{
Key * root;
Key * cur;
ssize_t rootSize = 0;
ksRewind (config);
root = ksNext (config);
rootSize = keyGetNameSize (root);
keyDel (ksLookup (config, root, KDB_O_POP));
KeySet * newConfig = ksNew (ksGetSize (config), KS_END);
if (rootSize == -1) return newConfig;
while ((cur = ksPop (config)) != 0)
{
Key * dupKey = keyDup (cur, KEY_CP_ALL);
keySetName (dupKey, name);
keyAddName (dupKey, keyName (cur) + rootSize - 1);
ksAppendKey (newConfig, dupKey);
keyDel (cur);
}
return newConfig;
}
/**
* @brief Bootstrap, first phase with fallback
* @internal
*
* @param handle already allocated, but without defaultBackend
* @param [out] keys for bootstrapping
* @param errorKey key to add errors too
*
* @retval -1 failure: cannot initialize defaultBackend
* @retval 0 warning: could not get initial config
* @retval 1 success
* @retval 2 success in fallback mode
*/
int elektraOpenBootstrap (KDB * handle, KeySet * keys, Key * errorKey)
{
handle->defaultBackend = backendOpenDefault (handle->modules, handle->global, KDB_DB_INIT, errorKey);
if (!handle->defaultBackend) return -1;
handle->split = splitNew ();
splitAppend (handle->split, handle->defaultBackend, keyNew (KDB_SYSTEM_ELEKTRA, KEY_END), 2);
keySetName (errorKey, KDB_SYSTEM_ELEKTRA);
keySetString (errorKey, "kdbOpen(): get");
int funret = kdbGet (handle, keys, errorKey) != -1;
elektraRemoveMetaData (errorKey, "error"); // fix errors from kdbGet()
return funret;
}
/**
* Checks whether the same instance of the list plugin is mounted in the global (maxonce) positions:
*
* pregetstorage, procgetstorage, postgetstorage, postgetcleanup,
* presetstorage, presetcleanup, precommit, postcommit,
* prerollback and postrollback
*
* @param handle the KDB handle to check
* @param errorKey used for error reporting
*
* @retval 1 if list is mounted everywhere
* @retval 0 otherwise
*/
static int ensureListPluginMountedEverywhere (KDB * handle, Key * errorKey)
{
GlobalpluginPositions expectedPositions[] = { PREGETSTORAGE,
PROCGETSTORAGE,
POSTGETSTORAGE,
POSTGETCLEANUP,
PRESETSTORAGE,
PRESETCLEANUP,
PRECOMMIT,
POSTCOMMIT,
PREROLLBACK,
POSTROLLBACK,
-1 };
Plugin * list = handle->globalPlugins[expectedPositions[0]][MAXONCE];
if (list == NULL || elektraStrCmp (list->name, "list") != 0)
{
ELEKTRA_SET_INSTALLATION_ERRORF (errorKey, "list plugin not mounted at position %s/maxonce",
GlobalpluginPositionsStr[expectedPositions[0]]);
return 0;
}
for (int i = 1; expectedPositions[i] > 0; ++i)
{
Plugin * plugin = handle->globalPlugins[expectedPositions[i]][MAXONCE];
if (plugin != list)
{
// must always be the same instance
ELEKTRA_SET_INSTALLATION_ERRORF (errorKey, "list plugin not mounted at position %s/maxonce",
GlobalpluginPositionsStr[expectedPositions[i]]);
return 0;
}
}
return 1;
}
/**
* Handles the system:/elektra/contract/globalkeyset part of kdbOpen() contracts
*
* NOTE: @p contract will be modified
*
* @see kdbOpen()
*/
static void ensureContractGlobalKs (KDB * handle, KeySet * contract)
{
Key * globalKsContractRoot = keyNew ("system:/elektra/contract/globalkeyset", KEY_END);
Key * globalKsRoot = keyNew ("system:/elektra", KEY_END);
KeySet * globalKs = ksCut (contract, globalKsContractRoot);
ksRename (globalKs, globalKsContractRoot, globalKsRoot);
ksAppend (handle->global, globalKs);
ksDel (globalKs);
keyDel (globalKsContractRoot);
keyDel (globalKsRoot);
}
/**
* Handles the system:/elektra/contract/mountglobal part of kdbOpen() contracts
*
* NOTE: @p contract will be modified
*
* @see kdbOpen()
*/
static int ensureContractMountGlobal (KDB * handle, KeySet * contract, Key * parentKey)
{
if (!ensureListPluginMountedEverywhere (handle, parentKey))
{
return -1;
}
Plugin * listPlugin = handle->globalPlugins[PREGETSTORAGE][MAXONCE];
typedef int (*mountPluginFun) (Plugin *, const char *, KeySet *, Key *);
mountPluginFun listAddPlugin = (mountPluginFun) elektraPluginGetFunction (listPlugin, "mountplugin");
typedef int (*unmountPluginFun) (Plugin *, const char *, Key *);
unmountPluginFun listRemovePlugin = (unmountPluginFun) elektraPluginGetFunction (listPlugin, "unmountplugin");
Key * mountContractRoot = keyNew ("system:/elektra/contract/mountglobal", KEY_END);
Key * pluginConfigRoot = keyNew ("user:/", KEY_END);
for (elektraCursor it = ksFindHierarchy (contract, mountContractRoot, NULL); it < ksGetSize (contract); it++)
{
Key * cur = ksAtCursor (contract, it);
if (keyIsDirectlyBelow (mountContractRoot, cur) == 1)
{
const char * pluginName = keyBaseName (cur);
KeySet * pluginConfig = ksCut (contract, cur);
// increment ref count, because cur is part of pluginConfig and
// we hold a reference to cur that is still needed (via pluginName)
keyIncRef (cur);
ksRename (pluginConfig, cur, pluginConfigRoot);
int ret = listRemovePlugin (listPlugin, pluginName, parentKey);
if (ret != ELEKTRA_PLUGIN_STATUS_ERROR)
{
ret = listAddPlugin (listPlugin, pluginName, pluginConfig, parentKey);
}
// we ned to delete cur separately, because it was ksCut() from contract
// we also need to decrement the ref count, because it was incremented above
keyDecRef (cur);
keyDel (cur);
if (ret == ELEKTRA_PLUGIN_STATUS_ERROR)
{
ELEKTRA_SET_INSTALLATION_ERRORF (
parentKey, "The plugin '%s' couldn't be mounted globally (via the 'list' plugin).", pluginName);
return -1;
}
// adjust cursor, because we removed the current key
--it;
}
}
keyDel (mountContractRoot);
keyDel (pluginConfigRoot);
return 0;
}
/**
* Handles the @p contract argument of kdbOpen().
*
* @see kdbOpen()
*/
static int ensureContract (KDB * handle, const KeySet * contract, Key * parentKey)
{
// TODO: tests
// deep dup, so modifications to the keys in contract after kdbOpen() cannot modify the contract
KeySet * dup = ksDeepDup (contract);
ensureContractGlobalKs (handle, dup);
int ret = ensureContractMountGlobal (handle, dup, parentKey);
ksDel (dup);
return ret;
}
/**
* @brief Opens the session with the Key database.
*
* @pre errorKey must be a valid key, e.g. created with keyNew()
*
* The method will bootstrap itself the following way.
* The first step is to open the default backend. With it
* system:/elektra/mountpoints will be loaded and all needed
* libraries and mountpoints will be determined.
* Then the global plugins and global keyset data from the @p contract
* is processed.
* Finally, the libraries for backends will be loaded and with it the
* @p KDB data structure will be initialized.
*
* You must always call this method before retrieving or committing any
* keys to the database. In the end of the program,
* after using the key database, you must not forget to kdbClose().
*
* The pointer to the @p KDB structure returned will be initialized
* like described above, and it must be passed along on any kdb*()
* method your application calls.
*
* Get a @p KDB handle for every thread using elektra. Don't share the
* handle across threads, and also not the pointer accessing it:
*
* @snippet kdbopen.c open
*
* You don't need kdbOpen() if you only want to
* manipulate plain in-memory Key or KeySet objects.
*
* @pre errorKey must be a valid key, e.g. created with keyNew()
*
* @param contract the contract that should be ensured before opening the KDB
* all data is copied and the KeySet can safely be used for
* e.g. kdbGet() later
* @param errorKey the key which holds errors and warnings which were issued
* @see kdbGet(), kdbClose() to end all affairs to the key database.
* @retval handle on success
* @retval NULL on failure
* @ingroup kdb
*/
KDB * kdbOpen (const KeySet * contract, Key * errorKey)
{
if (!errorKey)
{
ELEKTRA_LOG ("no parent key passed");
return 0;
}
ELEKTRA_LOG ("called with %s", keyName (errorKey));
int errnosave = errno;
KDB * handle = elektraCalloc (sizeof (struct _KDB));
Key * initialParent = keyDup (errorKey, KEY_CP_ALL);
handle->global = ksNew (0, KS_END);
ksAppendKey (handle->global, keyNew ("system:/elektra/kdb", KEY_BINARY, KEY_SIZE, sizeof (handle), KEY_VALUE, &handle, KEY_END));
handle->modules = ksNew (0, KS_END);
if (elektraModulesInit (handle->modules, errorKey) == -1)
{
ksDel (handle->global);
ksDel (handle->modules);
elektraFree (handle);
ELEKTRA_SET_INSTALLATION_ERROR (
errorKey, "Method 'elektraModulesInit' returned with -1. See other warning or error messages for concrete details");
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
return 0;
}
KeySet * keys = ksNew (0, KS_END);
int inFallback = 0;
switch (elektraOpenBootstrap (handle, keys, errorKey))
{
case -1:
ksDel (handle->global);
ksDel (handle->modules);
elektraFree (handle);
ELEKTRA_SET_INSTALLATION_ERROR (errorKey,
"Could not open default backend. See other warning or error messages for concrete details");
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
ksDel (keys);
return 0;
case 0:
ELEKTRA_ADD_INSTALLATION_WARNING (errorKey, "Initial 'kdbGet()' failed, you should either fix " KDB_DB_INIT
" or the fallback " KDB_DB_FILE);
break;
case 2:
ELEKTRA_LOG ("entered fallback code for bootstrapping");
inFallback = 1;
break;
}
keySetString (errorKey, "kdbOpen(): mountGlobals");
if (mountGlobals (handle, ksDup (keys), handle->modules, errorKey) == -1)
{
// mountGlobals also sets a warning containing the name of the plugin that failed to load
ELEKTRA_ADD_INSTALLATION_WARNING (errorKey, "Mounting global plugins failed. Please see warning of concrete plugin");
}
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, "kdbOpen(): backendClose");
backendClose (handle->defaultBackend, errorKey);
splitDel (handle->split);
handle->defaultBackend = 0;
handle->trie = 0;
#ifdef HAVE_LOGGER
if (inFallback) ELEKTRA_LOG_WARNING ("fallback for bootstrapping: you might want to run `kdb upgrade-bootstrap`");
Key * key;
ksRewind (keys);
for (key = ksNext (keys); key; key = ksNext (keys))
{
ELEKTRA_LOG_DEBUG ("config for createTrie name: %s value: %s", keyName (key), keyString (key));
}
#endif
if (contract != NULL)
{
keySetString (errorKey, "kdbOpen(): ensureContract");
if (ensureContract (handle, contract, errorKey) != 0)
{
// error is set by ensureContract
keySetString (errorKey, "kdbOpen(): close");
kdbClose (handle, errorKey);
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
return 0;
}
}
handle->split = splitNew ();
keySetString (errorKey, "kdbOpen(): mountOpen");
// Open the trie, keys will be deleted within mountOpen
if (mountOpen (handle, keys, handle->modules, errorKey) == -1)
{
ELEKTRA_ADD_INSTALLATION_WARNING (errorKey, "Initial loading of trie did not work");
}
keySetString (errorKey, "kdbOpen(): mountDefault");
if (mountDefault (handle, handle->modules, inFallback, errorKey) == -1)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not reopen and mount default backend");
keySetString (errorKey, "kdbOpen(): close");
kdbClose (handle, errorKey);
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
return 0;
}
keySetString (errorKey, "kdbOpen(): mountVersion");
mountVersion (handle, errorKey);
keySetString (errorKey, "kdbOpen(): mountModules");
if (mountModules (handle, handle->modules, errorKey) == -1)
{
ELEKTRA_ADD_INTERNAL_WARNING (errorKey, "Mounting modules did not work");
}
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
return handle;
}
/**
* Closes the session with the Key database.
*
* @pre The handle must be a valid handle as returned from kdbOpen()
*
* @pre errorKey must be a valid key, e.g. created with keyNew()
*
* This is the counterpart of kdbOpen().
*
* You must call this method when you finished your affairs with the key
* database. You can manipulate Key and KeySet objects also after
* kdbClose(), but you must not use any kdb*() call afterwards.
*
* The @p handle parameter will be finalized and all resources associated to it
* will be freed. After a kdbClose(), the @p handle cannot be used anymore.
*
* @param handle contains internal information of
* @link kdbOpen() opened @endlink key database
* @param errorKey the key which holds error/warning information
* @retval 0 on success
* @retval -1 on NULL pointer
* @ingroup kdb
*/
int kdbClose (KDB * handle, Key * errorKey)
{
if (!handle)
{
return -1;
}
Key * initialParent = keyDup (errorKey, KEY_CP_ALL);
int errnosave = errno;
splitDel (handle->split);
trieClose (handle->trie, errorKey);
backendClose (handle->defaultBackend, errorKey);
handle->defaultBackend = 0;
// not set in fallback mode, so lets check:
if (handle->initBackend)
{
backendClose (handle->initBackend, errorKey);
handle->initBackend = 0;
}
for (int i = 0; i < NR_GLOBAL_POSITIONS; ++i)
{
for (int j = 0; j < NR_GLOBAL_SUBPOSITIONS; ++j)
{
elektraPluginClose (handle->globalPlugins[i][j], errorKey);
}
}
if (handle->modules)
{
elektraModulesClose (handle->modules, errorKey);
ksDel (handle->modules);
}
else
{
ELEKTRA_ADD_RESOURCE_WARNING (errorKey, "Could not close modules: modules were not open");
}
if (handle->global) ksDel (handle->global);
elektraFree (handle);
keySetName (errorKey, keyName (initialParent));
keySetString (errorKey, keyString (initialParent));
keyDel (initialParent);
errno = errnosave;
return 0;
}
/**
* @internal
*
* @brief Check if an update is needed at all
*
* @retval -2 cache hit
* @retval -1 an error occurred
* @retval 0 no update needed
* @retval number of plugins which need update
*/
static int elektraGetCheckUpdateNeeded (Split * split, Key * parentKey)
{
int updateNeededOccurred = 0;
size_t cacheHits = 0;
for (size_t i = 0; i < split->size; i++)
{
int ret = -1;
Backend * backend = split->handles[i];
clear_bit (split->syncbits[i], (splitflag_t) SPLIT_FLAG_SYNC);
Plugin * resolver = backend->getplugins[RESOLVER_PLUGIN];
if (resolver && resolver->kdbGet)
{
ksRewind (split->keysets[i]);
keySetName (parentKey, keyName (split->parents[i]));
keySetString (parentKey, "");
ret = resolver->kdbGet (resolver, split->keysets[i], parentKey);
// store resolved filename
keySetString (split->parents[i], keyString (parentKey));
// no keys in that backend
ELEKTRA_LOG_DEBUG ("backend: %s,%s ;; ret: %d", keyName (split->parents[i]), keyString (split->parents[i]), ret);
backendUpdateSize (backend, split->parents[i], 0);
}
// TODO: set error in else case!
switch (ret)
{
case ELEKTRA_PLUGIN_STATUS_CACHE_HIT:
// Keys in cache are up-to-date
++cacheHits;
// Set sync flag, needed in case of cache miss
// FALLTHROUGH
case ELEKTRA_PLUGIN_STATUS_SUCCESS:
// Seems like we need to sync that
set_bit (split->syncbits[i], SPLIT_FLAG_SYNC);
++updateNeededOccurred;
break;
case ELEKTRA_PLUGIN_STATUS_NO_UPDATE:
// Nothing to do here
break;
default:
ELEKTRA_ASSERT (0, "resolver did not return 1 0 -1, but %d", ret);
case ELEKTRA_PLUGIN_STATUS_ERROR:
// Ohh, an error occurred, lets stop the
// process.
return -1;
}
}
if (cacheHits == split->size)
{
ELEKTRA_LOG_DEBUG ("all backends report cache is up-to-date");
return -2;
}
return updateNeededOccurred;
}
typedef enum
{
FIRST,
LAST
} UpdatePass;
/**
* @internal
* @brief Do the real update.
*
* @retval -1 on error
* @retval 0 on success
*/
static int elektraGetDoUpdate (Split * split, Key * parentKey)
{
const int bypassedSplits = 1;
for (size_t i = 0; i < split->size - bypassedSplits; i++)
{
if (!test_bit (split->syncbits[i], SPLIT_FLAG_SYNC))
{
// skip it, update is not needed
continue;
}
Backend * backend = split->handles[i];
ksRewind (split->keysets[i]);
keySetName (parentKey, keyName (split->parents[i]));
keySetString (parentKey, keyString (split->parents[i]));
for (size_t p = 1; p < NR_OF_PLUGINS; ++p)
{
int ret = 0;
if (backend->getplugins[p] && backend->getplugins[p]->kdbGet)
{
ret = backend->getplugins[p]->kdbGet (backend->getplugins[p], split->keysets[i], parentKey);
}
if (ret == -1)
{
// Ohh, an error occurred,
// lets stop the process.
return -1;
}
}
}
return 0;
}
static KeySet * prepareGlobalKS (KeySet * ks, Key * parentKey)
{
ksRewind (ks);
Key * cutKey = keyNew ("/", KEY_END);
keyAddName (cutKey, strchr (keyName (parentKey), '/'));
KeySet * cutKS = ksCut (ks, cutKey);
Key * specCutKey = keyNew ("spec:/", KEY_END);
KeySet * specCut = ksCut (cutKS, specCutKey);
ksRewind (specCut);
Key * cur;
while ((cur = ksNext (specCut)) != NULL)
{
if (keyGetNamespace (cur) == KEY_NS_CASCADING)
{
ksAppendKey (cutKS, cur);
keyDel (ksLookup (specCut, cur, KDB_O_POP));
}
}
ksAppend (ks, specCut);
ksDel (specCut);
keyDel (specCutKey);
keyDel (cutKey);
ksRewind (cutKS);
return cutKS;
}
static int elektraGetDoUpdateWithGlobalHooks (KDB * handle, Split * split, KeySet * ks, Key * parentKey, Key * initialParent,
UpdatePass run)
{
const int bypassedSplits = 1;
switch (run)
{
case FIRST:
keySetName (parentKey, keyName (initialParent));
elektraGlobalGet (handle, ks, parentKey, GETSTORAGE, INIT);
elektraGlobalGet (handle, ks, parentKey, GETSTORAGE, MAXONCE);
break;
case LAST:
keySetName (parentKey, keyName (initialParent));
elektraGlobalGet (handle, ks, parentKey, PROCGETSTORAGE, INIT);
elektraGlobalGet (handle, ks, parentKey, PROCGETSTORAGE, MAXONCE);
elektraGlobalError (handle, ks, parentKey, PROCGETSTORAGE, DEINIT);
break;
default:
break;
}
// elektraGlobalGet (handle, ks, parentKey, POSTGETSTORAGE, INIT);
for (size_t i = 0; i < split->size - bypassedSplits; i++)
{
Backend * backend = split->handles[i];
ksRewind (split->keysets[i]);
keySetName (parentKey, keyName (split->parents[i]));
keySetString (parentKey, keyString (split->parents[i]));
int start, end;
if (run == FIRST)
{
start = 1;
end = STORAGE_PLUGIN + 1;
}
else
{
start = STORAGE_PLUGIN + 1;
end = NR_OF_PLUGINS;
}
for (int p = start; p < end; ++p)
{
int ret = 0;
if (p == (STORAGE_PLUGIN + 1) && handle->globalPlugins[PROCGETSTORAGE][FOREACH])
{
keySetName (parentKey, keyName (initialParent));
ksRewind (ks);
handle->globalPlugins[PROCGETSTORAGE][FOREACH]->kdbGet (handle->globalPlugins[PROCGETSTORAGE][FOREACH], ks,
parentKey);
keySetName (parentKey, keyName (split->parents[i]));
}
if (p == (STORAGE_PLUGIN + 2) && handle->globalPlugins[POSTGETSTORAGE][FOREACH])
{
keySetName (parentKey, keyName (initialParent));
ksRewind (ks);
handle->globalPlugins[POSTGETSTORAGE][FOREACH]->kdbGet (handle->globalPlugins[POSTGETSTORAGE][FOREACH], ks,
parentKey);
keySetName (parentKey, keyName (split->parents[i]));
}
else if (p == (NR_OF_PLUGINS - 1) && handle->globalPlugins[POSTGETCLEANUP][FOREACH])
{
keySetName (parentKey, keyName (initialParent));
ksRewind (ks);
handle->globalPlugins[POSTGETCLEANUP][FOREACH]->kdbGet (handle->globalPlugins[POSTGETCLEANUP][FOREACH], ks,
parentKey);
keySetName (parentKey, keyName (split->parents[i]));
}
if (backend->getplugins[p] && backend->getplugins[p]->kdbGet)
{
if (p <= STORAGE_PLUGIN)
{
if (!test_bit (split->syncbits[i], SPLIT_FLAG_SYNC))
{
// skip it, update is not needed
continue;
}
ret = backend->getplugins[p]->kdbGet (backend->getplugins[p], split->keysets[i], parentKey);
}
else
{
KeySet * cutKS = prepareGlobalKS (ks, parentKey);
ret = backend->getplugins[p]->kdbGet (backend->getplugins[p], cutKS, parentKey);
ksAppend (ks, cutKS);
ksDel (cutKS);
}
}
if (ret == -1)
{
keySetName (parentKey, keyName (initialParent));
// Ohh, an error occurred,
// lets stop the process.
elektraGlobalError (handle, ks, parentKey, GETSTORAGE, DEINIT);
// elektraGlobalError (handle, ks, parentKey, POSTGETSTORAGE, DEINIT);
return -1;
}
}
}
if (run == FIRST)
{
keySetName (parentKey, keyName (initialParent));
elektraGlobalGet (handle, ks, parentKey, GETSTORAGE, DEINIT);
// elektraGlobalGet (handle, ks, parentKey, POSTGETSTORAGE, DEINIT);
}
return 0;
}
static int copyError (Key * dest, Key * src)
{
keyRewindMeta (src);
const Key * metaKey = keyGetMeta (src, "error");
if (!metaKey) return 0;
keySetMeta (dest, keyName (metaKey), keyString (metaKey));
while ((metaKey = keyNextMeta (src)) != NULL)
{
if (strncmp (keyName (metaKey), "error/", 6)) break;
keySetMeta (dest, keyName (metaKey), keyString (metaKey));
}
return 1;
}
static void clearError (Key * key)
{
keySetMeta (key, "error", 0);
keySetMeta (key, "error/number", 0);
keySetMeta (key, "error/description", 0);
keySetMeta (key, "error/reason", 0);
keySetMeta (key, "error/module", 0);
keySetMeta (key, "error/file", 0);
keySetMeta (key, "error/line", 0);
keySetMeta (key, "error/configfile", 0);
keySetMeta (key, "error/mountpoint", 0);
}
static int elektraCacheCheckParent (KeySet * global, Key * cacheParent, Key * initialParent)
{
const char * cacheName = keyGetNamespace (cacheParent) == KEY_NS_DEFAULT ? "" : keyName (cacheParent);
// first check if parentkey matches
Key * lastParentName = ksLookupByName (global, KDB_CACHE_PREFIX "/lastParentName", KDB_O_NONE);
ELEKTRA_LOG_DEBUG ("LAST PARENT name: %s", keyString (lastParentName));
ELEKTRA_LOG_DEBUG ("KDBG PARENT name: %s", cacheName);
if (!lastParentName || elektraStrCmp (keyString (lastParentName), cacheName)) return -1;
const char * cacheValue = keyGetNamespace (cacheParent) == KEY_NS_DEFAULT ? "default" : keyString (cacheParent);
Key * lastParentValue = ksLookupByName (global, KDB_CACHE_PREFIX "/lastParentValue", KDB_O_NONE);
ELEKTRA_LOG_DEBUG ("LAST PARENT value: %s", keyString (lastParentValue));
ELEKTRA_LOG_DEBUG ("KDBG PARENT value: %s", cacheValue);
if (!lastParentValue || elektraStrCmp (keyString (lastParentValue), cacheValue)) return -1;
Key * lastInitalParentName = ksLookupByName (global, KDB_CACHE_PREFIX "/lastInitialParentName", KDB_O_NONE);
Key * lastInitialParent = keyNew (keyString (lastInitalParentName), KEY_END);
ELEKTRA_LOG_DEBUG ("LAST initial PARENT name: %s", keyName (lastInitialParent));
ELEKTRA_LOG_DEBUG ("CURR initial PARENT name: %s", keyName (initialParent));
if (!keyIsBelowOrSame (lastInitialParent, initialParent))
{
ELEKTRA_LOG_DEBUG ("CACHE initial PARENT: key is not below or same");
keyDel (lastInitialParent);
return -1;
}
keyDel (lastInitialParent);
return 0;
}
static void elektraCacheCutMeta (KDB * handle)
{
Key * parentKey = keyNew (KDB_CACHE_PREFIX, KEY_END);
ksDel (ksCut (handle->global, parentKey));
keyDel (parentKey);
}
KeySet * elektraCutProc (KeySet * ks)
{
Key * parentKey = keyNew ("proc:/", KEY_END);
KeySet * ret = ksCut (ks, parentKey);
keyDel (parentKey);
return ret;
}
static void elektraRestoreProc (KeySet * ks, KeySet * proc)
{
ksAppend (ks, proc);
ksDel (proc);
}
static void elektraCacheLoad (KDB * handle, KeySet * cache, Key * parentKey, Key * initialParent ELEKTRA_UNUSED, Key * cacheParent)
{
// prune old cache info
elektraCacheCutMeta (handle);
if (elektraGlobalGet (handle, cache, cacheParent, PREGETCACHE, MAXONCE) != ELEKTRA_PLUGIN_STATUS_SUCCESS)
{
ELEKTRA_LOG_DEBUG ("CACHE MISS: could not fetch cache");
elektraCacheCutMeta (handle);
return;
}
ELEKTRA_ASSERT (elektraStrCmp (keyName (initialParent), keyName (parentKey)) == 0, "parentKey name differs from initial");
if (elektraCacheCheckParent (handle->global, cacheParent, parentKey) != 0)
{
// parentKey in cache does not match, needs rebuild
ELEKTRA_LOG_DEBUG ("CACHE WRONG PARENTKEY");
elektraCacheCutMeta (handle);
return;
}
}
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
/**
* @brief Deletes the OPMPHM.
*
* Clears and frees all memory in Opmphm.
*
* @param opmphm the OPMPHM
*/
static void cacheOpmphmDel (Opmphm * opmphm)
{
ELEKTRA_NOT_NULL (opmphm);