This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
/
kdb.c
2465 lines (2141 loc) · 76.7 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>
#define KDB_GET_PHASE_POST_STORAGE_SPEC (KDB_GET_PHASE_POST_STORAGE "/spec")
#define KDB_GET_PHASE_POST_STORAGE_NONSPEC (KDB_GET_PHASE_POST_STORAGE "/nonspec")
/**
* @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 specify 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
*
* @{
*/
static bool closeBackends (KeySet * backends, Key * errorKey)
{
for (elektraCursor i = 0; i < ksGetSize (backends); i++)
{
Key * backendKey = ksAtCursor (backends, i);
const BackendData * backendData = keyValue (backendKey);
for (elektraCursor p = 0; p < ksGetSize (backendData->plugins); p++)
{
Plugin * plugin = *(Plugin **) keyValue (ksAtCursor (backendData->plugins, p));
if (elektraPluginClose (plugin, errorKey) == ELEKTRA_PLUGIN_STATUS_ERROR)
{
return false;
}
}
ksDel (backendData->plugins);
ksDel (backendData->keys);
ksDel (backendData->definition);
}
ksDel (backends);
return true;
}
/**
* @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;
}
static void clearErrorAndWarnings (Key * key)
{
Key * cutRoot = keyNew ("meta:/error", KEY_END);
ksDel (ksCut (keyMeta (key), cutRoot));
keySetName (cutRoot, "meta:/warnings");
ksDel (ksCut (keyMeta (key), cutRoot));
keyDel (cutRoot);
}
/**
* 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 bool ensureContract (KDB * handle, const KeySet * contract, Key * parentKey)
{
// TODO (kodebach): 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 == 0;
}
/**
* @internal
*
* Helper for kdbOpen(). Creates empty KDB instance.
*
* @see kdbOpen()
*/
static KDB * kdbNew (Key * errorKey)
{
KDB * handle = elektraCalloc (sizeof (struct _KDB));
handle->modules = ksNew (0, KS_END);
if (elektraModulesInit (handle->modules, errorKey) == -1)
{
// TODO (kodebach) [Q]: shouldn't we let elektraModulesInit set this error?
ELEKTRA_SET_INSTALLATION_ERROR (
errorKey, "Method 'elektraModulesInit' returned with -1. See other warning or error messages for concrete details");
ksDel (handle->modules);
elektraFree (handle);
return NULL;
}
handle->global =
ksNew (1, keyNew ("system:/elektra/kdb", KEY_BINARY, KEY_SIZE, sizeof (handle), KEY_VALUE, &handle, KEY_END), KS_END);
handle->backends = ksNew (0, KS_END);
return handle;
}
static void addMountpoint (KeySet * backends, Key * mountpoint, Plugin * backend, KeySet * plugins, KeySet * definition)
{
BackendData backendData = {
.backend = backend,
.keys = ksNew (0, KS_END),
.plugins = plugins,
.definition = definition,
.getSize = 0,
.initialized = false,
.keyNeedsSync = false,
};
keySetBinary (mountpoint, &backendData, sizeof (backendData));
ksAppendKey (backends, mountpoint);
}
static bool addElektraMountpoint (KeySet * backends, KeySet * modules, KeySet * global, Key * errorKey)
{
// TODO (kodebach): implement user:/elektra and dir:/elektra
// FIXME (kodebach): replace KDB_DEFAULT_STORAGE with separate KDB_BOOTSTRAP_STORAGE
Plugin * storage = elektraPluginOpen (KDB_DEFAULT_STORAGE, modules, ksNew (0, KS_END), errorKey);
if (storage == NULL)
{
ELEKTRA_SET_INSTALLATION_ERRORF (errorKey, "Could not open boostrap storage plugin ('%s'). See warnings for details.",
KDB_DEFAULT_STORAGE);
return false;
}
storage->global = global;
// TODO (kodebach) [Q]: support direct read-write to absolute path in backend plugin to avoid resolver in bootstrap?
Plugin * resolver = elektraPluginOpen (KDB_DEFAULT_RESOLVER, modules, ksNew (0, KS_END), errorKey);
if (resolver == NULL)
{
ELEKTRA_SET_INSTALLATION_ERRORF (errorKey, "Could not open boostrap resolver plugin ('%s'). See warnings for details.",
KDB_DEFAULT_RESOLVER);
elektraPluginClose (resolver, errorKey);
return false;
}
resolver->global = global;
Plugin * backend = elektraPluginOpen ("backend", modules, ksNew (0, KS_END), errorKey);
if (backend == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey,
"Could not open system:/elektra backend during bootstrap. See other warnings for details");
elektraPluginClose (resolver, errorKey);
elektraPluginClose (storage, errorKey);
return false;
}
backend->global = global;
// clang-format off
KeySet * plugins =
ksNew (1,
keyNew ("system:/#0", KEY_BINARY, KEY_SIZE, sizeof (resolver), KEY_VALUE, &resolver, KEY_END),
keyNew ("system:/#1", KEY_BINARY, KEY_SIZE, sizeof (storage), KEY_VALUE, &storage, KEY_END),
KS_END);
KeySet * definition =
ksNew (3,
keyNew ("system:/path", KEY_VALUE, KDB_DB_INIT, KEY_END),
keyNew ("system:/positions/get/resolver", KEY_VALUE, "#0", KEY_END),
keyNew ("system:/positions/get/storage", KEY_VALUE, "#1", KEY_END),
keyNew ("system:/positions/set/resolver", KEY_VALUE, "#0", KEY_END),
keyNew ("system:/positions/set/storage", KEY_VALUE, "#1", KEY_END),
keyNew ("system:/positions/set/commit", KEY_VALUE, "#0", KEY_END),
keyNew ("system:/positions/set/rollback", KEY_VALUE, "#0", KEY_END),
KS_END);
// clang-format on
addMountpoint (backends, keyNew (KDB_SYSTEM_ELEKTRA, KEY_END), backend, plugins, definition);
return true;
}
static KeySet * elektraBoostrap (KDB * handle, Key * errorKey)
{
KeySet * elektraKs = ksNew (0, KS_END);
Key * bootstrapParent = keyNew (KDB_SYSTEM_ELEKTRA, KEY_END);
if (kdbGet (handle, elektraKs, bootstrapParent) == -1)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey,
"Bootstrapping failed, please fix '" KDB_DB_SYSTEM "/" KDB_DB_INIT
"'. If the error persists, please report this bug at https://issues.libelektra.org.");
Key * warningsRoot = keyNew ("meta:/warnings", KEY_END);
ksAppend (keyMeta (errorKey), ksBelow (keyMeta (bootstrapParent), warningsRoot));
keyDel (warningsRoot);
elektraTriggerWarnings (keyString (keyGetMeta (bootstrapParent, "meta:/error/number")), errorKey,
keyString (keyGetMeta (bootstrapParent, "meta:/error/reason")));
ksDel (elektraKs);
keyDel (bootstrapParent);
return NULL;
}
keyDel (bootstrapParent);
return elektraKs;
}
static bool openPlugins (KeySet * plugins, const Key * pluginsRoot, KeySet * modules, KeySet * global, const KeySet * systemConfig,
Key * errorKey)
{
bool success = true;
for (elektraCursor i = 0; i < ksGetSize (plugins); i++)
{
Key * cur = ksAtCursor (plugins, i);
if (keyIsDirectlyBelow (pluginsRoot, cur) == 1)
{
Key * lookupHelper = keyDup (cur, KEY_CP_NAME);
keyAddBaseName (lookupHelper, "name");
Key * nameKey = ksLookup (plugins, lookupHelper, 0);
const char * pluginName = nameKey == NULL ? NULL : keyString (nameKey);
if (nameKey == NULL || strlen (pluginName) == 0)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (errorKey,
"The plugin definition at '%s' doesn't contain a plugin name. Please "
"set '%s/name' to a non-empty string value.",
keyName (cur), keyName (cur));
success = false;
keyDel (lookupHelper);
continue;
}
keySetBaseName (lookupHelper, "config");
KeySet * config = ksBelow (plugins, lookupHelper);
Key * configRoot = keyNew ("user:/", KEY_END);
ksRename (config, lookupHelper, configRoot);
keyDel (configRoot);
ksAppend (config, systemConfig);
keyDel (lookupHelper);
Plugin * plugin = elektraPluginOpen (pluginName, modules, config, errorKey);
if (plugin == NULL)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (
errorKey, "Could not open the plugin '%s' defined at '%s'. See other warnings for details.",
pluginName, keyName (cur));
success = false;
continue;
}
plugin->global = global;
// create Plugin * key ...
Key * pluginKey = keyDup (cur, KEY_CP_NAME);
keySetBinary (pluginKey, &plugin, sizeof (plugin));
// ... remove definition (includes cur) ...
ksDel (ksCut (plugins, cur));
// ... and replace Plugin * key
ksAppendKey (plugins, pluginKey);
}
else
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (
errorKey,
"The key '%s' doesn't belong to a plugin definition. Keys below '%s' must be part of a plugin definition.",
keyName (cur), keyName (pluginsRoot));
success = false;
continue;
}
}
return success;
}
static KeySet * dupPluginSet (KeySet * plugins, Key * errorKey)
{
KeySet * dupPlugins = ksNew (ksGetSize (plugins), KS_END);
bool success = true;
for (elektraCursor i = 0; i < ksGetSize (plugins); i++)
{
Key * cur = ksAtCursor (plugins, i);
const Plugin * plugin = *(const Plugin **) keyValue (cur);
Plugin * dup = elektraPluginOpen (plugin->name, plugin->modules, ksDup (plugin->config), errorKey);
if (dup == NULL)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (
errorKey, "Could not open the plugin '%s' defined at '%s'. See other warnings for details.", plugin->name,
keyName (cur));
success = false;
continue;
}
dup->global = plugin->global;
Key * dupKey = keyDup (cur, KEY_CP_NAME);
keySetBinary (dupKey, &dup, sizeof (dup));
ksAppendKey (dupPlugins, dupKey);
}
if (!success)
{
ksDel (dupPlugins);
return NULL;
}
else
{
return dupPlugins;
}
}
static bool addDupMountpoint (KeySet * mountpoints, Key * mountpoint, Key * backendPluginKey, KeySet * plugins, KeySet * definition,
Key * errorKey)
{
KeySet * dupPlugins = dupPluginSet (plugins, errorKey);
if (dupPlugins == NULL)
{
keyDel (mountpoint);
return false;
}
Plugin * backendPlugin = *(Plugin **) keyValue (backendPluginKey);
addMountpoint (mountpoints, keyDup (mountpoint, KEY_CP_NAME), backendPlugin, dupPlugins, ksDup (definition));
return true;
}
static bool parseAndAddMountpoint (KeySet * mountpoints, KeySet * modules, KeySet * elektraKs, KeySet * global, Key * root, Key * errorKey)
{
// check that the base name is a key name
Key * mountpoint = keyNew (keyBaseName (root), KEY_END);
if (mountpoint == NULL)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (errorKey, "'%s' is not a valid key name, but is used for the mountpoint '%s'",
keyBaseName (root), keyName (root));
return false;
}
// FIXME (kodebach): reserve /elektra/... in every namespace
Key * elektraRoot = keyNew (KDB_SYSTEM_ELEKTRA, KEY_END);
if (keyIsBelowOrSame (elektraRoot, mountpoint) != 0)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (
errorKey,
"The mountpoint '%s' (defined at '%s') is not allowed. Everything below '" KDB_SYSTEM_ELEKTRA
"' is reserved for use by Elektra.",
keyBaseName (root), keyName (root));
return false;
}
// load mountpoint level config
Key * lookupHelper = keyDup (root, KEY_CP_NAME);
keyAddBaseName (lookupHelper, "config");
KeySet * systemConfig = ksBelow (elektraKs, lookupHelper);
Key * configRoot = keyNew ("system:/", KEY_END);
ksRename (systemConfig, lookupHelper, configRoot);
keyDel (configRoot);
// get the plugin list and remove the common prefix
keySetBaseName (lookupHelper, "plugins");
KeySet * plugins = ksBelow (elektraKs, lookupHelper);
// open all plugins (replaces key values with Plugin *)
if (!openPlugins (plugins, lookupHelper, modules, global, systemConfig, errorKey))
{
keyDel (mountpoint);
keyDel (lookupHelper);
ksDel (plugins);
ksDel (systemConfig);
return false;
}
// TODO (kodebach): read and process config/needs from contract
ksDel (systemConfig);
Key * pluginsRoot = keyNew ("system:/", KEY_END);
ksRename (plugins, lookupHelper, pluginsRoot);
keyDel (pluginsRoot);
// find backend plugin
Key * backendPluginKey = ksLookupByName (plugins, "system:/backend", 0);
if (backendPluginKey == NULL)
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (errorKey, "The mountpoint '%s' defined in '%s' does not specify a backend plugin.",
keyName (mountpoint), keyName (root));
keyDel (mountpoint);
keyDel (lookupHelper);
ksDel (plugins);
return false;
}
// get definition section
keySetBaseName (lookupHelper, "definition");
KeySet * definition = ksBelow (elektraKs, lookupHelper);
Key * definitionRoot = keyNew ("system:/", KEY_END);
ksRename (definition, lookupHelper, definitionRoot);
keyDel (definitionRoot);
keyDel (lookupHelper);
// create mountpoint
if (keyGetNamespace (mountpoint) == KEY_NS_CASCADING)
{
keySetNamespace (mountpoint, KEY_NS_SYSTEM);
if (!addDupMountpoint (mountpoints, mountpoint, backendPluginKey, plugins, definition, errorKey))
{
return false;
}
keySetNamespace (mountpoint, KEY_NS_USER);
if (!addDupMountpoint (mountpoints, mountpoint, backendPluginKey, plugins, definition, errorKey))
{
return false;
}
keySetNamespace (mountpoint, KEY_NS_DIR);
if (!addDupMountpoint (mountpoints, mountpoint, backendPluginKey, plugins, definition, errorKey))
{
return false;
}
keySetNamespace (mountpoint, KEY_NS_PROC);
if (!addDupMountpoint (mountpoints, mountpoint, backendPluginKey, plugins, definition, errorKey))
{
return false;
}
keyDel (mountpoint);
}
else
{
Plugin * backendPlugin = *(Plugin **) keyValue (backendPluginKey);
addMountpoint (mountpoints, mountpoint, backendPlugin, plugins, definition);
}
return true;
}
// FIXME (kodebach): write tests
KeySet * elektraMountpointsParse (KeySet * elektraKs, KeySet * modules, KeySet * global, Key * errorKey)
{
KeySet * mountpoints = ksNew (0, KS_END);
Key * mountpointsRoot = keyNew (KDB_SYSTEM_ELEKTRA "/mountpoints", KEY_END);
bool error = false;
for (elektraCursor end, i = ksFindHierarchy (elektraKs, mountpointsRoot, &end); i < end;)
{
Key * cur = ksAtCursor (elektraKs, i);
if (keyIsDirectlyBelow (mountpointsRoot, cur) == 1)
{
if (!parseAndAddMountpoint (mountpoints, modules, elektraKs, global, cur, errorKey))
{
error = true;
}
// skip over the keys we just parsed
Key * lookup = keyDup (cur, KEY_CP_NAME);
ksFindHierarchy (elektraKs, lookup, &i);
keyDel (lookup);
}
else
{
ELEKTRA_ADD_INSTALLATION_WARNINGF (
errorKey,
"The key '%s' is below 'system:/elektra/mountpoints', but doesn't belong to a mountpoint configuration. To "
"define a mountpoint for the parent e.g. 'user:/mymountpoint' the key "
"'system:/elektra/user:\\/mymountpoint' must exist and be set to an arbitrary (possibly empty) value.",
keyName (cur));
++i;
}
}
if (error)
{
closeBackends (mountpoints, errorKey);
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Some mountpoints couldn't be parsed. See warnings for details.");
return NULL;
}
return mountpoints;
}
static bool addRootMountpoint (KeySet * backends, elektraNamespace ns, KeySet * modules, KeySet * global, Key * errorKey)
{
Key * rootKey = keyNew ("/", KEY_END);
keySetNamespace (rootKey, ns);
if (ksLookup (backends, rootKey, 0) != NULL)
{
// already present
keyDel (rootKey);
return true;
}
Plugin * defaultResolver = elektraPluginOpen (KDB_RESOLVER, modules, ksNew (0, KS_END), errorKey);
if (defaultResolver == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not open default resolver plugin. See warnings for details.");
return false;
}
defaultResolver->global = global;
Plugin * defaultStorage = elektraPluginOpen (KDB_STORAGE, modules, ksNew (0, KS_END), errorKey);
if (defaultStorage == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not open default storage plugin. See warnings for details.");
elektraPluginClose (defaultResolver, errorKey);
return false;
}
defaultStorage->global = global;
// clang-format off
KeySet * rootPlugins =
ksNew (2,
keyNew ("system:/resolver", KEY_BINARY, KEY_SIZE, sizeof (defaultResolver), KEY_VALUE, &defaultResolver, KEY_END),
keyNew ("system:/storage", KEY_BINARY, KEY_SIZE, sizeof (defaultStorage), KEY_VALUE, &defaultStorage, KEY_END),
KS_END);
KeySet * rootDefinition =
ksNew (7,
keyNew ("system:/path", KEY_VALUE, KDB_DB_FILE, KEY_END),
keyNew ("system:/positions/get/resolver", KEY_VALUE, "resolver", KEY_END),
keyNew ("system:/positions/get/storage", KEY_VALUE, "storage", KEY_END),
keyNew ("system:/positions/set/resolver", KEY_VALUE, "resolver", KEY_END),
keyNew ("system:/positions/set/storage", KEY_VALUE, "storage", KEY_END),
keyNew ("system:/positions/set/commit", KEY_VALUE, "resolver", KEY_END),
keyNew ("system:/positions/set/rollback", KEY_VALUE, "resolver", KEY_END),
KS_END);
// clang-format on
Plugin * root = elektraPluginOpen ("backend", modules, ksNew (0, KS_END), errorKey);
if (root == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not open default backend. See warnings for details.");
ksDel (rootPlugins);
ksDel (rootDefinition);
elektraPluginClose (defaultResolver, errorKey);
elektraPluginClose (defaultStorage, errorKey);
return false;
}
root->global = global;
addMountpoint (backends, rootKey, root, rootPlugins, rootDefinition);
return true;
}
static bool addModulesMountpoint (KDB * handle, Key * mountpoint, Key * errorKey)
{
Plugin * modules = elektraPluginOpen ("modules", handle->modules, ksNew (0, KS_END), errorKey);
if (modules == NULL)
{
ELEKTRA_SET_INSTALLATION_ERRORF (
errorKey, "Could not open 'modules' plugin for mountpoint 'system:/elektra/modules/%s'. See warnings for details.",
keyBaseName (mountpoint));
return false;
}
Plugin * plugin = elektraPluginOpen (keyBaseName (mountpoint), handle->modules,
ksNew (1, keyNew ("system:/module", KEY_END), KS_END), errorKey);
if (plugin == NULL)
{
ELEKTRA_SET_INSTALLATION_ERRORF (
errorKey, "Could not open '%s' plugin for mountpoint 'system:/elektra/modules/%s'. See warnings for details.",
keyBaseName (mountpoint), keyBaseName (mountpoint));
return false;
}
modules->global = handle->global;
addMountpoint (handle->backends, mountpoint, modules, ksNew (0, KS_END),
ksNew (1, keyNew ("system:/plugin", KEY_BINARY, KEY_SIZE, sizeof (plugin), KEY_VALUE, &plugin, KEY_END), KS_END));
return true;
}
static bool addHardcodedMountpoints (KDB * handle, Key * errorKey)
{
if (!addElektraMountpoint (handle->backends, handle->modules, handle->global, errorKey))
{
return false;
}
if (!addRootMountpoint (handle->backends, KEY_NS_SPEC, handle->modules, handle->global, errorKey))
{
return false;
}
if (!addRootMountpoint (handle->backends, KEY_NS_SYSTEM, handle->modules, handle->global, errorKey))
{
return false;
}
if (!addRootMountpoint (handle->backends, KEY_NS_USER, handle->modules, handle->global, errorKey))
{
return false;
}
if (!addRootMountpoint (handle->backends, KEY_NS_DIR, handle->modules, handle->global, errorKey))
{
return false;
}
if (!addRootMountpoint (handle->backends, KEY_NS_PROC, handle->modules, handle->global, errorKey))
{
return false;
}
Key * modulesRoot = keyNew (KDB_SYSTEM_ELEKTRA "/modules", KEY_END);
Plugin * modules = elektraPluginOpen ("modules", handle->modules, ksNew (0, KS_END), errorKey);
if (modules == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not open system:/elektra/modules backend. See warnings for details.");
return false;
}
modules->global = handle->global;
addMountpoint (handle->backends, modulesRoot, modules, ksNew (0, KS_END), ksNew (0, KS_END));
for (elektraCursor i = 0; i < ksGetSize (handle->modules); i++)
{
Key * cur = ksAtCursor (handle->modules, i);
if (keyIsDirectlyBelow (modulesRoot, cur) != 1)
{
continue;
}
if (!addModulesMountpoint (handle, keyDup (cur, KEY_CP_NAME), errorKey))
{
return false;
}
}
Plugin * version = elektraPluginOpen ("version", handle->modules, ksNew (0, KS_END), errorKey);
if (version == NULL)
{
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Could not open system:/elektra/version backend. See warnings for details.");
return false;
}
version->global = handle->global;
addMountpoint (handle->backends, keyNew (KDB_SYSTEM_ELEKTRA "/version", KEY_END), version, ksNew (0, KS_END), ksNew (0, KS_END));
return true;
}
/**
* Opens the session with the Key database.
*
* @pre errorKey must be a valid key, e.g. created with keyNew()
*
* You must always call this method before retrieving or committing any
* keys to the database. At the end of a program, after using the Key database (KDB),
* you must not forget to call kdbClose() to free resources.
*
* The method will bootstrap itself in 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.
*
* 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
*
* @return handle to the newly created KDB on success
* @retval NULL on failure
*
* @since 1.0.0
* @ingroup kdb
* @see kdbClose() to close the session of a Key database opened by kdbOpen()
*/
KDB * kdbOpen (const KeySet * contract, Key * errorKey)
{
if (!errorKey)
{
ELEKTRA_LOG ("no error key passed");
return 0;
}
ELEKTRA_LOG ("called with %s", keyName (errorKey));
Key * initialParent = keyDup (errorKey, KEY_CP_ALL);
int errnosave = errno; // TODO (kodebach) [Q]: really needed?
// Step 1: create empty KDB instance
KDB * handle = kdbNew (errorKey);
if (handle == NULL)
{
goto error;
}
// Step 2: configure for bootstrap
if (!addElektraMountpoint (handle->backends, handle->modules, handle->global, errorKey))
{
goto error;
}
// Step 3: execute bootstrap
KeySet * elektraKs = elektraBoostrap (handle, errorKey);
if (elektraKs == NULL)
{
goto error;
}
// Step 4: setup default global plugins
// TODO (kodebach): remove/replace step in global plugins rewrite
if (mountGlobals (handle, ksDup (elektraKs), handle->modules, errorKey) == -1)
{
// mountGlobals also sets a warning containing the name of the plugin that failed to load
ELEKTRA_SET_INSTALLATION_ERROR (errorKey, "Mounting global plugins failed. Please see warning of concrete plugin");
ksDel (elektraKs);
goto error;
}