summaryrefslogtreecommitdiff
path: root/src/persistence_client_library_data_access.c
blob: 8cb38c5c2328da48aad69548d5823e28f0e18304 (plain)
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
/******************************************************************************
 * Project         Persistency
 * (c) copyright   2012
 * Company         XS Embedded GmbH
 *****************************************************************************/
/******************************************************************************
 * This Source Code Form is subject to the terms of the
 * Mozilla Public License, v. 2.0. If a  copy of the MPL was not distributed
 * with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
******************************************************************************/
 /**
 * @file           persistence_client_library_data_access.c
 * @ingroup        Persistence client library
 * @author         Ingo Huerner
 * @brief          Implementation of persistence data access
 *                 Library provides an API to access persistent data
 * @see            
 */

#include "../include_protected/persistence_client_library_data_access.h"
#include "persistence_client_library_custom_loader.h"
#include "persistence_client_library_access_helper.h"
#include "persistence_client_library_itzam_errors.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


/// definition of a key-value pair stored in the database
typedef struct _KeyValuePair_s
{
    char m_key[DbKeySize];       /// the key
    char m_data[DbValueSize];    /// the data
    unsigned int m_data_size;   /// the size of the data
}
KeyValuePair_s;


// definition of a cursor entry
typedef struct _CursorEntry_s
{
   itzam_btree_cursor m_cursor;
   PersistenceStorage_e storage;
   PersistencePolicy_e policy;
   int m_empty;
}
CursorEntry_s;

// cursor array handle
CursorEntry_s gCursorArray[MaxPersHandle];

/// handle index
static int gHandleIdx = 1;

/// free handle array
int gFreeCursorHandleArray[MaxPersHandle];
// free head index
int gFreeCursorHandleIdxHead = 0;

// mutex to controll access to the cursor array
pthread_mutex_t gMtx = PTHREAD_MUTEX_INITIALIZER;


/// btree array
static itzam_btree gBtree[DbTableSize][PersistencePolicy_LastEntry];
static int gBtreeCreated[DbTableSize][PersistencePolicy_LastEntry] = { {0} };



itzam_btree* database_get(PersistenceInfo_s* info, const char* dbPath)
{
   int arrayIdx = 0;
   itzam_btree* btree = NULL;

   // create array index: index is a combination of resource config table type and group
   arrayIdx = info->configKey.storage + info->context.ldbid ;

   if(arrayIdx <= DbTableSize)
   {
      if(gBtreeCreated[arrayIdx][info->configKey.policy] == 0)
      {
         itzam_state  state = ITZAM_FAILED;
         state = itzam_btree_open(&gBtree[arrayIdx][info->configKey.policy], dbPath,
                                  itzam_comparator_string, error_handler, 0/*recover*/, 0/*read_only*/);
         if (state != ITZAM_OKAY)
         {
            fprintf(stderr, "database_get ==> Open Itzam problem: %s\n", STATE_MESSAGES[state]);
         }
         gBtreeCreated[arrayIdx][info->configKey.policy] = 1;
      }
      // assign database
      btree = &gBtree[arrayIdx][info->configKey.policy];
   }
   else
   {
      printf("btree_get ==> invalid storage type\n");
   }
   return btree;
}


void database_close(PersistenceInfo_s* info)
{
   int arrayIdx = info->configKey.storage + info->context.ldbid;

   if(info->configKey.storage <= PersistenceStorage_shared )
   {
      itzam_state  state = ITZAM_FAILED;
      state = itzam_btree_close(&gBtree[arrayIdx][info->configKey.policy]);
      if (state != ITZAM_OKAY)
      {
         fprintf(stderr, "database_close ==> Close Itzam problem: %s\n", STATE_MESSAGES[state]);
      }
      gBtreeCreated[arrayIdx][info->configKey.policy] = 0;
   }
   else
   {
      printf("database_close ==> invalid storage type\n");
   }
}

void database_close_all()
{
   int i = 0;

   for(i=0; i<DbTableSize; i++)
   {
      // close write cached database
      if(gBtreeCreated[i][PersistencePolicy_wc] == 1)
      {
         itzam_state  state = ITZAM_FAILED;
         state = itzam_btree_close(&gBtree[i][PersistencePolicy_wc]);
         if (state != ITZAM_OKAY)
         {
            fprintf(stderr, "database_close ==> Close WC: Itzam problem: %s\n", STATE_MESSAGES[state]);
         }
         gBtreeCreated[i][PersistencePolicy_wc] = 0;
      }

      // close write through database
      if(gBtreeCreated[i][PersistencePolicy_wt] == 1)
      {
         itzam_state  state = ITZAM_FAILED;
         state = itzam_btree_close(&gBtree[i][PersistencePolicy_wt]);
         if (state != ITZAM_OKAY)
         {
            fprintf(stderr, "database_close ==> Close WT: Itzam problem: %s\n", STATE_MESSAGES[state]);
         }
         gBtreeCreated[i][PersistencePolicy_wt] = 0;
      }
   }
}



int persistence_get_data(char* dbPath, char* key, PersistenceInfo_s* info, unsigned char* buffer, unsigned int buffer_size)
{
   int read_size = -1;

   if(   PersistenceStorage_shared == info->configKey.storage
      || PersistenceStorage_local == info->configKey.storage)
   {
      itzam_btree* btree = NULL;
      itzam_state  state = ITZAM_FAILED;
      KeyValuePair_s search;

      btree = database_get(info, dbPath);
      if(btree != NULL)
      {
         if(itzam_true == itzam_btree_find(btree, key, &search))
         {
            read_size = search.m_data_size;
            if(read_size > buffer_size)
            {
               read_size = buffer_size;   // truncate data size to buffer size
            }
            memcpy(buffer, search.m_data, read_size);
         }
         else
         {
            read_size = EPERS_NOKEY;
         }

         //
         // workaround till lifecycle is working correctly
         //
         database_close(info);
      }
      else
      {
         read_size = EPERS_NOPRCTABLE;
         fprintf(stderr, "\npersistence_get_data ==> Open Itzam problem: %s\n", STATE_MESSAGES[state]);
      }
   }
   else if(PersistenceStorage_custom == info->configKey.storage)   // custom storage implementation via custom library
   {
      int idx =  custom_client_name_to_id(dbPath, 1);
      char workaroundPath[128];  // workaround, because /sys/ can not be accessed on host!!!!
      snprintf(workaroundPath, 128, "%s%s", "/Data", dbPath  );

      if( (idx < PersCustomLib_LastEntry) && (gPersCustomFuncs[idx].custom_plugin_handle_get_data != NULL) )
      {
         gPersCustomFuncs[idx].custom_plugin_get_data(key, (char*)buffer, buffer_size);
      }
      else
      {
         read_size = EPERS_NOPLUGINFUNCT;
      }
   }
   return read_size;
}



int persistence_set_data(char* dbPath, char* key, PersistenceInfo_s* info, unsigned char* buffer, unsigned int buffer_size)
{
   int write_size = -1;

   if(   PersistenceStorage_shared == info->configKey.storage
      || PersistenceStorage_local == info->configKey.storage)
   {
      write_size = buffer_size;
      itzam_btree* btree = NULL;
      itzam_state  state = ITZAM_FAILED;
      KeyValuePair_s insert;

      btree = database_get(info, dbPath);
      if(btree != NULL)
      {
         int keySize = 0;
         keySize = (int)strlen((const char*)key);
         if(keySize < DbKeySize)
         {
            int dataSize = 0;
            dataSize = (int)strlen( (const char*)buffer);
            if(dataSize < DbValueSize)
            {
               // key
               memset(insert.m_key, 0, DbKeySize);
               memcpy(insert.m_key, key, keySize);
               if(itzam_true == itzam_btree_find(btree, key, &insert))
               {
                  // key already available, so delete "old" key
                  state = itzam_btree_remove(btree, (const void *)&insert);
               }

               // data
               memset(insert.m_data, 0, DbValueSize);
               memcpy(insert.m_data, buffer, dataSize);

               // data size
               insert.m_data_size = buffer_size;

               state = itzam_btree_insert(btree,(const void *)&insert);
               if (state != ITZAM_OKAY)
               {
                  fprintf(stderr, "\npersistence_set_data ==> Insert Itzam problem: %s\n", STATE_MESSAGES[state]);
                  write_size = EPERS_DB_ERROR_INTERNAL;
               }
            }
            else
            {
               fprintf(stderr, "\npersistence_set_data ==> set_value_to_table_itzam => data to long » size %d | maxSize: %d\n", dataSize, DbKeySize);
               write_size = EPERS_DB_VALUE_SIZE;
            }

            //
            // workaround till lifecycle is working correctly
            //
            database_close(info);
         }
         else
         {
            fprintf(stderr, "\nset_value_to_table_itzam => key to long » size: %d | maxSize: %d\n", keySize, DbKeySize);
            write_size = EPERS_DB_KEY_SIZE;
         }
      }
      else
      {
         write_size = EPERS_NOPRCTABLE;
         fprintf(stderr, "\npersistence_set_data ==> Open Itzam problem: %s\n", STATE_MESSAGES[state]);
      }
   }
   else if(PersistenceStorage_custom == info->configKey.storage)   // custom storage implementation via custom library
   {
      int idx = custom_client_name_to_id(dbPath, 1);
      if((idx < PersCustomLib_LastEntry) && (gPersCustomFuncs[idx].custom_plugin_handle_set_data) )
      {
         gPersCustomFuncs[idx].custom_plugin_set_data(key, (char*)buffer, buffer_size);
      }
      else
      {
         write_size = EPERS_NOPLUGINFUNCT;
      }
   }
   return write_size;
}



int persistence_get_data_size(char* dbPath, char* key, PersistenceInfo_s* info)
{
   int read_size = -1;

   if(   PersistenceStorage_shared == info->configKey.storage
      || PersistenceStorage_local == info->configKey.storage)
   {
      int keySize = 0;
      itzam_btree*  btree = NULL;
      itzam_state  state = ITZAM_FAILED;
      KeyValuePair_s search;

      btree = database_get(info, dbPath);
      if(btree != NULL)
      {
         keySize = (int)strlen((const char*)key);
         if(keySize < DbKeySize)
         {
            memset(search.m_key,0, DbKeySize);
            memcpy(search.m_key, key, keySize);
            if(itzam_true == itzam_btree_find(btree, key, &search))
            {
               read_size = strlen(search.m_data);
            }
            else
            {
               read_size = EPERS_NOKEY;
            }
         }
         else
         {
            fprintf(stderr, "persistence_get_data_size => key to long » size: %d | maxSize: %d\n", keySize, DbKeySize);
            read_size = EPERS_DB_KEY_SIZE;
         }
         //
         // workaround till lifecycle is working correctly
         //
         database_close(info);
      }
      else
      {
         read_size = EPERS_NOPRCTABLE;
         fprintf(stderr, "\npersistence_get_data_size ==> Open Itzam problem: %s\n", STATE_MESSAGES[state]);
      }
   }
   else if(PersistenceStorage_custom == info->configKey.storage)   // custom storage implementation via custom library
   {
      int idx = custom_client_name_to_id(dbPath, 1);
      if((idx < PersCustomLib_LastEntry) && (gPersCustomFuncs[idx].custom_plugin_handle_set_data) )
      {
         gPersCustomFuncs[idx].custom_plugin_get_size(key);
      }
      else
      {
         read_size = EPERS_NOPLUGINFUNCT;
      }
   }
   return read_size;
}



int persistence_delete_data(char* dbPath, char* dbKey, PersistenceInfo_s* info)
{
   int ret = 0;
   if(PersistenceStorage_custom != info->configKey.storage)
   {
      itzam_btree*  btree = NULL;
      KeyValuePair_s delete;

      //printf("delete_key_from_table_itzam => Path: \"%s\" | key: \"%s\" \n", dbPath, key);
      btree = database_get(info, dbPath);
      if(btree != NULL)
      {
         int keySize = 0;
         keySize = (int)strlen((const char*)dbKey);
         if(keySize < DbKeySize)
         {
            itzam_state  state;

            memset(delete.m_key,0, DbKeySize);
            memcpy(delete.m_key, dbKey, keySize);
            state = itzam_btree_remove(btree, (const void *)&delete);
            if (state != ITZAM_OKAY)
            {
               fprintf(stderr, "persistence_delete_data ==> Remove Itzam problem: %s\n", STATE_MESSAGES[state]);
               ret = EPERS_DB_ERROR_INTERNAL;
            }
         }
         else
         {
            fprintf(stderr, "persistence_delete_data => key to long » size: %d | maxSize: %d\n", keySize, DbKeySize);
            ret = EPERS_DB_KEY_SIZE;
         }
         //
         // workaround till lifecycle is working correctly
         //
         database_close(info);
      }
      else
      {
         fprintf(stderr, "persistence_delete_data => no prct table\n");
         ret = EPERS_NOPRCTABLE;
      }
   }
   else   // custom storage implementation via custom library
   {
      int idx = custom_client_name_to_id(dbPath, 1);
      if((idx < PersCustomLib_LastEntry) && (gPersCustomFuncs[idx].custom_plugin_handle_set_data) )
      {
         gPersCustomFuncs[idx].custom_plugin_delete_data(dbKey);
      }
      else
      {
         ret = EPERS_NOPLUGINFUNCT;
      }
   }
   return ret;
}


int persistence_reg_notify_on_change(char* dbPath, char* key)
{
   int rval = -1;

   return rval;
}


//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------

int get_cursor_handle()
{
   int handle = 0;

   if(pthread_mutex_lock(&gMtx) == 0)
   {
      if(gFreeCursorHandleIdxHead > 0)   // check if we have a free spot in the array before the current max
      {
         handle = gFreeCursorHandleArray[--gFreeCursorHandleIdxHead];
      }
      else
      {
         if(gHandleIdx < MaxPersHandle-1)
         {
            handle = gHandleIdx++;  // no free spot before current max, increment handle index
         }
         else
         {
            handle = -1;
            printf("get_persistence_handle_idx => Reached maximum of open handles: %d \n", MaxPersHandle);
         }
      }
      pthread_mutex_unlock(&gMtx);
   }
   return handle;
}


void close_cursor_handle(int handlerDB)
{
   if(pthread_mutex_lock(&gMtx) == 0)
   {
      if(gFreeCursorHandleIdxHead < MaxPersHandle)
      {
         gFreeCursorHandleArray[gFreeCursorHandleIdxHead++] = handlerDB;
      }
      pthread_mutex_unlock(&gMtx);
   }
}



int persistence_db_cursor_create(char* dbPath, PersistenceStorage_e storage, PersistencePolicy_e policy)
{
   int handle = -1;
   itzam_btree*  btree = NULL;

   PersistenceInfo_s info;
   info.configKey.storage = storage;
   info.configKey.policy  = policy;

   //printf("CREATE-Cursor: %d | path: %s \n", (int)storage, dbPath);
   btree = database_get(&info, dbPath);
   if(btree != NULL)
   {
      itzam_state  state;
      handle = get_cursor_handle();
      if(handle < MaxPersHandle && handle >= 0)
      {
         state = itzam_btree_cursor_create(&gCursorArray[handle].m_cursor, btree);
         if(state == ITZAM_OKAY)
         {
            gCursorArray[handle].m_empty = 0;
            gCursorArray[handle].storage = storage;
            gCursorArray[handle].policy  = policy;
         }
         else
         {
            gCursorArray[handle].m_empty = 1;
            gCursorArray[handle].storage = PersistenceStoragePolicy_LastEntry;
            gCursorArray[handle].policy = PersistencePolicy_LastEntry;
         }
      }
   }
   return handle;
}



int persistence_db_cursor_next(unsigned int handlerDB)
{
   int rval = -1;
   if(handlerDB < MaxPersHandle && handlerDB >= 0)
   {
      if(gCursorArray[handlerDB].m_empty != 1)
      {
         itzam_bool success;
         success = itzam_btree_cursor_next(&gCursorArray[handlerDB].m_cursor);

         if(success == itzam_true)
         {
            rval = 0;
         }
         else
         {
            rval = EPERS_LAST_ENTRY_IN_DB;
         }
      }
      else
      {
         printf("persistence_db_cursor_get_key ==> invalid handle: %u \n", handlerDB);
      }
   }
   else
   {
      printf("persistence_db_cursor_get_key ==> handle bigger than max » handleDB: %u | max: : %d \n", handlerDB, MaxPersHandle);
   }
   return rval;
}



int persistence_db_cursor_get_key(unsigned int handlerDB, char * bufKeyName_out, int bufSize)
{
   int rval = -1;
   KeyValuePair_s search;

   if(handlerDB < MaxPersHandle)
   {
      if(gCursorArray[handlerDB].m_empty != 1)
      {
         int length = 0;
         itzam_btree_cursor_read(&gCursorArray[handlerDB].m_cursor ,(void *)&search);
         length = strlen(search.m_key);
         if(length < bufSize)
         {
            memcpy(bufKeyName_out, search.m_key, length);
            rval = 0;
         }
         else
         {
            printf("persistence_db_cursor_get_key ==> buffer to small » keySize: %d | bufSize: %d \n", length, bufSize);
         }
      }
      else
      {
         printf("persistence_db_cursor_get_key ==> invalid handle: %u \n", handlerDB);
      }
   }
   else
   {
      printf("persistence_db_cursor_get_key ==> handle bigger than max » handleDB: %u | max: : %d \n", handlerDB, MaxPersHandle);
   }
   return rval;
}



int persistence_db_cursor_get_data(unsigned int handlerDB, char * bufData_out, int bufSize)
{
   int rval = -1;
   KeyValuePair_s search;

   if(handlerDB < MaxPersHandle)
   {
      if(gCursorArray[handlerDB].m_empty != 1)
      {
         int length = 0;
         itzam_btree_cursor_read(&gCursorArray[handlerDB].m_cursor ,(void *)&search);

         length = strlen(search.m_data);
         if(length < bufSize)
         {
            memcpy(bufData_out, search.m_data, length);
            rval = 0;
         }
         else
         {
            printf("persistence_db_cursor_get_data ==> buffer to small » keySize: %d | bufSize: %d \n", length, bufSize);
         }
      }
      else
      {
         printf("persistence_db_cursor_get_data ==> invalid handle: %u \n", handlerDB);
      }
   }
   else
   {
      printf("persistence_db_cursor_get_data ==> handle bigger than max » handleDB: %u | max: : %d \n", handlerDB, MaxPersHandle);
   }
   return rval;
}



int persistence_db_cursor_get_data_size(unsigned int handlerDB)
{
   int size = -1;
   KeyValuePair_s search;

   if(handlerDB < MaxPersHandle)
   {
      if(gCursorArray[handlerDB].m_empty != 1)
      {
         itzam_btree_cursor_read(&gCursorArray[handlerDB].m_cursor ,(void *)&search);
         size = strlen(search.m_data);
      }
      else
      {
         printf("persistence_db_cursor_get_data ==> invalid handle: %u \n", handlerDB);
      }
   }
   else
   {
      printf("persistence_db_cursor_get_data ==> handle bigger than max » handleDB: %u | max: : %d \n", handlerDB, MaxPersHandle);
   }
   return size;
}



int persistence_db_cursor_destroy(unsigned int handlerDB)
{
   int rval = -1;
   itzam_state  state;

   if(handlerDB < MaxPersHandle)
   {
      state = itzam_btree_cursor_free(&gCursorArray[handlerDB].m_cursor);
      if (state == ITZAM_OKAY)
      {
         rval = 0;
         /*
         PersistenceInfo_s info;
         info.configKey.storage = gCursorArray[handlerDB].storage;
         info.configKey.policy  = gCursorArray[handlerDB].policy;

         database_close(&info);   // to do correct cursor handling
         */

         gCursorArray[handlerDB].m_empty = 1;
         gCursorArray[handlerDB].storage = PersistenceStoragePolicy_LastEntry;
         gCursorArray[handlerDB].policy = PersistencePolicy_LastEntry;

         close_cursor_handle(handlerDB);
      }
   }
   return rval;
}




//-----------------------------------------------------------------------------
// code to print database content (for debugging)
//-----------------------------------------------------------------------------
// walk the database
/*
KeyValuePair_s  rec;
itzam_btree_cursor cursor;
state = itzam_btree_cursor_create(&cursor, &btree);
if(state == ITZAM_OKAY)
{
  printf("==> Database content ==> db size: %d\n", (int)itzam_btree_count(&btree));
  do
  {
     // get the key pointed to by the cursor
     state = itzam_btree_cursor_read(&cursor,(void *)&rec);
     if (state == ITZAM_OKAY)
     {
       printf("   Key: %s \n     ==> data: %s\n", rec.m_key, rec.m_data);
     }
     else
        fprintf(stderr, "\nItzam problem: %s\n", STATE_MESSAGES[state]);
  }
  while (itzam_btree_cursor_next(&cursor));

  state = itzam_btree_cursor_free(&cursor);
}
*/
//-----------------------------------------------------------------------------