#include #include #include #include #include #include #include static void controller_load_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_controller_e key_controller, MDB_val *value) { int err; MDB_val key; key.mv_size = sizeof(db_key_controller_e); key.mv_data = &key_controller; if((err = mdb_get(mdb_txn, mdb_dbi, &key, value)) != 0) { LOG_ERROR("mdb_get error %s", mdb_strerror(err)); exit(1); } } controller_t* controller_load(MDB_env *mdb_env) { int err; MDB_txn *mdb_txn; MDB_dbi mdb_dbi; controller_t *new_controller; if((err = mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn)) != 0) { LOG_ERROR("mdb_txn_begin error %s", mdb_strerror(err)); return NULL; } if((err = mdb_dbi_open(mdb_txn, "controller", 0, &mdb_dbi)) != 0) { switch(err) { case MDB_NOTFOUND: LOG_INFO("no controller found in db. creating new one"); mdb_txn_abort(mdb_txn); new_controller = controller_create(); controller_save(new_controller, mdb_env); return new_controller; default: LOG_ERROR("mdb_txn_begin error %s", mdb_strerror(err)); return NULL; } } new_controller = malloc(sizeof(controller_t)); MDB_val value; controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_ID, &value); memmove(new_controller->id, (uuid_t*)value.mv_data, sizeof(uuid_t)); controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_NAME, &value); strncpy(new_controller->name, (char*)value.mv_data, MAX_NAME_LENGTH); new_controller->name[MAX_NAME_LENGTH] = '\0'; controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_COMMAND_PORT, &value); new_controller->command_port = ((uint16_t*)value.mv_data)[0]; controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_DISCOVERY_PORT, &value); new_controller->discovery_port = ((uint16_t*)value.mv_data)[0]; new_controller->relay_count = global_config.relay_count; mdb_txn_abort(mdb_txn); // transaction is read only new_controller->relays = malloc(sizeof(relay_t*) * new_controller->relay_count); for(uint8_t i = 0; i < new_controller->relay_count; i++) { LOG_TRACE("loading relay %d", i); new_controller->relays[i] = relay_load(mdb_env, i); } return new_controller; }