controller-legacy/models/controller_load.c

81 lines
2.3 KiB
C
Raw Normal View History

2020-02-08 14:09:34 +00:00
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <uuid/uuid.h>
#include <models/controller.h>
#include <macros.h>
static void
controller_load_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, controller_db_key key_meta, MDB_val *value)
{
int err;
MDB_val key;
key.mv_size = sizeof(controller_db_key);
key.mv_data = &key_meta;
if((err = mdb_get(mdb_txn, mdb_dbi, &key, value)) != 0)
{
fprintf(stderr, "mdb_get error %s\n", mdb_strerror(err));
exit(1);
}
}
controller*
controller_load(MDB_env *mdb_env)
{
int err;
MDB_txn *mdb_txn;
MDB_dbi mdb_dbi;
controller *new_controller;
if((err = mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn)) != 0)
{
fprintf(stderr, "mdb_txn_begin error %s\n", mdb_strerror(err));
2020-02-09 23:58:17 +00:00
return NULL;
2020-02-08 14:09:34 +00:00
}
if((err = mdb_dbi_open(mdb_txn, "meta", 0, &mdb_dbi)) != 0)
{
switch(err)
{
case MDB_NOTFOUND:
mdb_txn_abort(mdb_txn);
new_controller = controller_create();
controller_save(new_controller, mdb_env);
return new_controller;
default:
fprintf(stderr, "mdb_txn_begin error %s\n", mdb_strerror(err));
2020-02-09 23:58:17 +00:00
return NULL;
2020-02-08 14:09:34 +00:00
}
}
new_controller = malloc(sizeof(*new_controller));
MDB_val value;
controller_load_single(mdb_txn, mdb_dbi, KEY_META_ID, &value);
memmove(new_controller->id, (uuid_t*)value.mv_data, sizeof(uuid_t));
2020-02-08 14:09:34 +00:00
controller_load_single(mdb_txn, mdb_dbi, KEY_META_NAME, &value);
strncpy(new_controller->name, (char*)value.mv_data, CONTROLLER_NAME_LENGTH);
new_controller->name[CONTROLLER_NAME_LENGTH] = '\0';
2020-02-09 23:58:17 +00:00
controller_load_single(mdb_txn, mdb_dbi, KEY_META_COMMAND_PORT, &value);
new_controller->command_port = ((uint16_t*)value.mv_data)[0];
controller_load_single(mdb_txn, mdb_dbi, KEY_META_DISCOVERY_PORT, &value);
new_controller->discovery_port = ((uint16_t*)value.mv_data)[0];
2020-02-08 14:09:34 +00:00
controller_load_single(mdb_txn, mdb_dbi, KEY_META_RELAY_COUNT, &value);
new_controller->relay_count = ((uint8_t*)value.mv_data)[0];
controller_debug(new_controller);
mdb_txn_abort(mdb_txn); // transaction is read only
return new_controller;
}