From 1dda721343e9a30e2934a57dc9181917c4ac7113 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 15:29:24 +0100 Subject: [PATCH 01/10] feat(fpga)!: Remove public dma C api Signed-off-by: Philipp Jungkamp --- fpga/include/villas/fpga/dma.h | 41 -------- fpga/lib/CMakeLists.txt | 1 - fpga/lib/dma.cpp | 173 --------------------------------- fpga/tests/unit/CMakeLists.txt | 10 -- fpga/tests/unit/dma.c | 100 ------------------- 5 files changed, 325 deletions(-) delete mode 100644 fpga/include/villas/fpga/dma.h delete mode 100644 fpga/lib/dma.cpp delete mode 100644 fpga/tests/unit/dma.c diff --git a/fpga/include/villas/fpga/dma.h b/fpga/include/villas/fpga/dma.h deleted file mode 100644 index ebd7ffcc0..000000000 --- a/fpga/include/villas/fpga/dma.h +++ /dev/null @@ -1,41 +0,0 @@ -/* C bindings for VILLASfpga - * - * Author: Niklas Eiling - * SPDX-FileCopyrightText: 2023 Niklas Eiling - * SPDX-License-Identifier: Apache-2.0 - */ - -#ifndef _VILLASFPGA_DMA_H -#define _VILLASFPGA_DMA_H -#ifdef __cplusplus -extern "C" { -#endif - -#include - -typedef struct villasfpga_handle_t *villasfpga_handle; -typedef struct villasfpga_memory_t *villasfpga_memory; - -villasfpga_handle villasfpga_init(const char *configFile); - -void villasfpga_destroy(villasfpga_handle handle); - -int villasfpga_alloc(villasfpga_handle handle, villasfpga_memory *mem, - size_t size); -int villasfpga_register(villasfpga_handle handle, villasfpga_memory *mem); -int villasfpga_free(villasfpga_memory mem); -void *villasfpga_get_ptr(villasfpga_memory mem); - -int villasfpga_read(villasfpga_handle handle, villasfpga_memory mem, - size_t size); -int villasfpga_read_complete(villasfpga_handle handle, size_t *size); - -int villasfpga_write(villasfpga_handle handle, villasfpga_memory mem, - size_t size); -int villasfpga_write_complete(villasfpga_handle handle, size_t *size); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _VILLASFPGA_DMA_H diff --git a/fpga/lib/CMakeLists.txt b/fpga/lib/CMakeLists.txt index 4628dd18a..b554195a4 100644 --- a/fpga/lib/CMakeLists.txt +++ b/fpga/lib/CMakeLists.txt @@ -13,7 +13,6 @@ set(SOURCES core.cpp node.cpp utils.cpp - dma.cpp ips/aurora_xilinx.cpp ips/aurora.cpp diff --git a/fpga/lib/dma.cpp b/fpga/lib/dma.cpp deleted file mode 100644 index 6ea1e0318..000000000 --- a/fpga/lib/dma.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* API for interacting with the FPGA DMA Controller. - * - * Author: Niklas Eiling - * SPDX-FileCopyrightText: 2023 Niklas Eiling - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace villas; - -static std::shared_ptr pciDevices; -static auto logger = villas::Log::get("villasfpga_dma"); - -struct villasfpga_handle_t { - std::shared_ptr card; - std::shared_ptr dma; -}; -struct villasfpga_memory_t { - std::shared_ptr block; -}; - -villasfpga_handle villasfpga_init(const char *configFile) { - std::string fpgaName = "vc707"; - std::string connectStr = "3<->pipe"; - std::string outputFormat = "short"; - bool dumpGraph = false; - bool dumpAuroraChannels = true; - try { - // Logging setup - Log::getInstance().setLevel(spdlog::level::debug); - fpga::setupColorHandling(); - - if (configFile == nullptr || configFile[0] == '\0') { - logger->error( - "No configuration file provided/ Please use -c/--config argument"); - return nullptr; - } - - auto handle = new villasfpga_handle_t; - handle->card = fpga::setupFpgaCard(configFile, fpgaName); - - if (dumpGraph) { - auto &mm = MemoryManager::get(); - mm.getGraph().dump("graph.dot"); - } - - if (dumpAuroraChannels) { - auto aurora_channels = getAuroraChannels(handle->card); - for (auto aurora : *aurora_channels) - aurora->dump(); - } - - // Configure Crossbar switch - const fpga::ConnectString parsedConnectString(connectStr); - if (!parsedConnectString.configCrossBar(handle->card)) { - logger->error("Failed to configure crossbar"); - return nullptr; - } - - return handle; - } catch (const RuntimeError &e) { - logger->error("Error: {}", e.what()); - return nullptr; - } catch (const std::exception &e) { - logger->error("Error: {}", e.what()); - return nullptr; - } catch (...) { - logger->error("Unknown error"); - return nullptr; - } -} - -void villasfpga_destroy(villasfpga_handle handle) { delete handle; } - -int villasfpga_alloc(villasfpga_handle handle, villasfpga_memory *mem, - size_t size) { - try { - auto &alloc = villas::HostRam::getAllocator(); - *mem = new villasfpga_memory_t; - (*mem)->block = alloc.allocateBlock(size); - return villasfpga_register(handle, mem); - } catch (const RuntimeError &e) { - logger->error("Failed to allocate memory: {}", e.what()); - return -1; - } -} -int villasfpga_register(villasfpga_handle handle, villasfpga_memory *mem) { - try { - handle->dma->makeAccesibleFromVA((*mem)->block); - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to register memory: {}", e.what()); - return -1; - } -} -int villasfpga_free(villasfpga_memory mem) { - try { - delete mem; - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to free memory: {}", e.what()); - return -1; - } -} - -int villasfpga_read(villasfpga_handle handle, villasfpga_memory mem, - size_t size) { - try { - if (!handle->dma->read(*mem->block, size)) { - logger->error("Failed to read from device"); - return -1; - } - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to read memory: {}", e.what()); - return -1; - } -} - -int villasfpga_read_complete(villasfpga_handle handle, size_t *size) { - try { - auto readComp = handle->dma->readComplete(); - logger->debug("Read {} bytes", readComp.bytes); - *size = readComp.bytes; - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to read memory: {}", e.what()); - return -1; - } -} - -int villasfpga_write(villasfpga_handle handle, villasfpga_memory mem, - size_t size) { - try { - if (!handle->dma->write(*mem->block, size)) { - logger->error("Failed to write to device"); - return -1; - } - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to write memory: {}", e.what()); - return -1; - } -} - -int villasfpga_write_complete(villasfpga_handle handle, size_t *size) { - try { - auto writeComp = handle->dma->writeComplete(); - logger->debug("Wrote {} bytes", writeComp.bytes); - *size = writeComp.bytes; - return 0; - } catch (const RuntimeError &e) { - logger->error("Failed to write memory: {}", e.what()); - return -1; - } -} - -void *villasfpga_get_ptr(villasfpga_memory mem) { - return (void *)MemoryManager::get() - .getTranslationFromProcess(mem->block->getAddrSpaceId()) - .getLocalAddr(0); -} diff --git a/fpga/tests/unit/CMakeLists.txt b/fpga/tests/unit/CMakeLists.txt index 67b3bfced..d2a3884bf 100644 --- a/fpga/tests/unit/CMakeLists.txt +++ b/fpga/tests/unit/CMakeLists.txt @@ -29,13 +29,3 @@ target_link_libraries(unit-tests-fpga PUBLIC villas-fpga ${CRITERION_LIBRARIES} ) - -add_executable(villasfpga-dma dma.c) - -target_include_directories(villasfpga-dma PUBLIC - ../include -) - -target_link_libraries(villasfpga-dma PUBLIC - villas-fpga -) diff --git a/fpga/tests/unit/dma.c b/fpga/tests/unit/dma.c deleted file mode 100644 index 466a1ea2c..000000000 --- a/fpga/tests/unit/dma.c +++ /dev/null @@ -1,100 +0,0 @@ -/* Testing the C bindings for the VILLASfpga DMA interface. - * - * Author: Niklas Eiling - * SPDX-FileCopyrightText: 2023 Niklas Eiling - * SPDX-License-Identifier: Apache-2.0 - */ - -#include -#include -#include - -#include - -int main(int argc, char *argv[]) { - int ret; - villasfpga_handle vh; - villasfpga_memory mem1, mem2; - void *mem1ptr, *mem2ptr; - size_t size; - - if (argv == NULL) { - return 1; - } - if (argc != 2 || argv[1] == NULL) { - fprintf(stderr, "Usage: %s \n", argv[0]); - } - - if ((vh = villasfpga_init(argv[1])) == NULL) { - fprintf(stderr, "Failed to initialize FPGA\n"); - ret = 1; - goto out; - } - - if (villasfpga_alloc(vh, &mem1, 0x200 * sizeof(uint32_t)) != 0) { - fprintf(stderr, "Failed to allocate DMA memory 1\n"); - ret = 1; - goto out; - } - - if (villasfpga_alloc(vh, &mem2, 0x200 * sizeof(uint32_t)) != 0) { - fprintf(stderr, "Failed to allocate DMA memory 2\n"); - ret = 1; - goto out; - } - - if ((mem1ptr = villasfpga_get_ptr(mem1)) == NULL) { - fprintf(stderr, "Failed to get pointer to DMA memory 1\n"); - ret = 1; - goto out; - } - - if ((mem2ptr = villasfpga_get_ptr(mem2)) == NULL) { - fprintf(stderr, "Failed to get pointer to DMA memory 2\n"); - ret = 1; - goto out; - } - - printf("DMA memory 1: %p, DMA memory 2: %p\n", mem1ptr, mem2ptr); - - while (1) { - // Setup read transfer - if ((ret = villasfpga_read(vh, mem1, 0x200 * sizeof(uint32_t))) != 0) { - fprintf(stderr, "Failed to initiate read transfer\n"); - ret = 1; - goto out; - } - - printf("Enter a float:\n"); - if ((ret = scanf("%f", (float *)mem2ptr)) != 1) { - fprintf(stderr, "Failed to parse input: sscanf returned %d\n", ret); - ret = 1; - goto out; - } - printf("sending %f (%zu bytes)\n", ((float *)mem2ptr)[0], sizeof(float)); - // Initiate write transfer - if ((ret = villasfpga_write(vh, mem2, sizeof(float))) != 0) { - fprintf(stderr, "Failed to initiate write transfer\n"); - ret = 1; - goto out; - } - - if ((ret = villasfpga_write_complete(vh, &size)) != 0) { - fprintf(stderr, "Failed to write complete\n"); - ret = 1; - goto out; - } - - if ((ret = villasfpga_read_complete(vh, &size)) != 0) { - fprintf(stderr, "Failed to write complete\n"); - ret = 1; - goto out; - } - - printf("Read %f (%zu bytes)\n", ((float *)mem1ptr)[0], size); - } - - ret = 0; -out: - return ret; -} From 10d122f1aa86316e8ffe3d44258fa9ca959d7e7a Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 15:43:41 +0100 Subject: [PATCH 02/10] fix(common): Remove dead test Signed-off-by: Philipp Jungkamp --- common/tests/unit/tsc.cpp | 62 --------------------------------------- 1 file changed, 62 deletions(-) delete mode 100644 common/tests/unit/tsc.cpp diff --git a/common/tests/unit/tsc.cpp b/common/tests/unit/tsc.cpp deleted file mode 100644 index 6e73dc04a..000000000 --- a/common/tests/unit/tsc.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* Unit tests for rdtsc. - * - * Author: Steffen Vogel - * SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -#include -#include -#include - -#define CNT (1 << 18) - -// cppcheck-suppress unknownMacro -TestSuite(tsc, .description = "Timestamp counters"); - -Test(tsc, increasing) { - int ret; - struct Tsc tsc; - uint64_t *cntrs; - - ret = tsc_init(&tsc); - cr_assert_eq(ret, 0); - - cntrs = new uint64_t[CNT]; - cr_assert_not_null(cntrs); - - for (unsigned i = 0; i < CNT; i++) - cntrs[i] = tsc_now(&tsc); - - for (unsigned i = 1; i < CNT; i++) - cr_assert_lt(cntrs[i - 1], cntrs[i]); - - delete cntrs; -} - -Test(tsc, sleep) { - int ret; - double delta, duration = 1; - struct timespec start, stop; - struct Tsc tsc; - uint64_t start_cycles, end_cycles; - - ret = tsc_init(&tsc); - cr_assert_eq(ret, 0); - - clock_gettime(CLOCK_MONOTONIC, &start); - - start_cycles = tsc_now(&tsc); - end_cycles = start_cycles + duration * tsc.frequency; - - while (tsc_now(&tsc) < end_cycles) - ; - - clock_gettime(CLOCK_MONOTONIC, &stop); - delta = time_delta(&start, &stop); - - cr_assert_float_eq(delta, duration, 1e-4, "Error: %f, Delta: %lf, Freq: %llu", - delta - duration, delta, tsc.frequency); -} From 2a7c46cbfcc726f24443d0ef7eabcf85cb75fe2b Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 15:45:28 +0100 Subject: [PATCH 03/10] fix(node): Remove unused header Signed-off-by: Philipp Jungkamp --- src/villas-node.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/villas-node.cpp b/src/villas-node.cpp index 379e7519c..4e4dd6827 100644 --- a/src/villas-node.cpp +++ b/src/villas-node.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include From 4e4d448f852e0ce828bb0ae0ff1be7b57e66d7aa Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 15:46:56 +0100 Subject: [PATCH 04/10] feat(lib)!: Merge libvillas-common and libvillas-fpga into libvillas Signed-off-by: Philipp Jungkamp --- .github/workflows/test.yaml | 2 +- CMakeLists.txt | 8 +- CODEOWNERS | 4 +- common/CMakeLists.txt | 15 --- common/lib/CMakeLists.txt | 108 ------------------ common/tests/CMakeLists.txt | 10 -- common/tests/unit/CMakeLists.txt | 39 ------- .../include/villas/graph/directed.hpp | 0 .../include/villas/graph/edge.hpp | 0 .../include/villas/graph/vertex.hpp | 0 .../include/villas/kernel/devices/device.hpp | 0 .../kernel/devices/device_connection.hpp | 0 .../include/villas/kernel/devices/driver.hpp | 0 .../villas/kernel/devices/ip_device.hpp | 0 .../villas/kernel/devices/linux_driver.hpp | 0 .../villas/kernel/devices/pci_device.hpp | 0 .../villas/kernel/devices/platform_device.hpp | 0 .../include/villas/kernel/vfio_container.hpp | 0 .../include/villas/kernel/vfio_device.hpp | 0 .../include/villas/kernel/vfio_group.hpp | 0 {common => fpga}/include/villas/memory.hpp | 0 .../include/villas/memory_manager.hpp | 0 fpga/lib/CMakeLists.txt | 42 ++++--- .../lib/kernel/devices/device_connection.cpp | 0 .../lib/kernel/devices/ip_device.cpp | 0 .../lib/kernel/devices/linux_driver.cpp | 0 .../lib/kernel/devices/pci_device.cpp | 0 .../lib/kernel/devices/platform_device.cpp | 0 .../lib/kernel/vfio_container.cpp | 0 {common => fpga}/lib/kernel/vfio_device.cpp | 0 {common => fpga}/lib/kernel/vfio_group.cpp | 0 {common => fpga}/lib/memory.cpp | 0 {common => fpga}/lib/memory_manager.cpp | 0 fpga/src/CMakeLists.txt | 4 +- fpga/tests/unit/CMakeLists.txt | 3 +- {common => fpga}/tests/unit/graph.cpp | 0 {common/include => include}/villas/boxes.hpp | 0 {common/include => include}/villas/buffer.hpp | 0 {common/include => include}/villas/colors.hpp | 0 {common/include => include}/villas/common.hpp | 0 {common/include => include}/villas/compat.hpp | 0 .../include => include}/villas/config.hpp.in | 0 {common/include => include}/villas/cpuset.hpp | 0 .../villas/dsp/exponential_window.hpp | 0 .../villas/dsp/moving_average_window.hpp | 0 .../include => include}/villas/dsp/pid.hpp | 0 .../include => include}/villas/dsp/window.hpp | 0 .../villas/dsp/window_cosine.hpp | 0 .../include => include}/villas/exceptions.hpp | 0 {common/include => include}/villas/fs.hpp | 0 {common/include => include}/villas/hist.hpp | 0 .../include => include}/villas/jansson.hpp | 0 {common/include => include}/villas/json.hpp | 0 .../villas/kernel/kernel.hpp | 0 .../include => include}/villas/kernel/rt.hpp | 0 {common/include => include}/villas/list.hpp | 0 {common/include => include}/villas/log.hpp | 0 {common/include => include}/villas/plugin.hpp | 0 {common/include => include}/villas/popen.hpp | 0 {common/include => include}/villas/table.hpp | 0 {common/include => include}/villas/task.hpp | 0 .../include => include}/villas/terminal.hpp | 0 {common/include => include}/villas/timing.hpp | 0 {common/include => include}/villas/tool.hpp | 0 {common/include => include}/villas/tsc.hpp | 0 {common/include => include}/villas/utils.hpp | 0 {common/include => include}/villas/uuid.hpp | 0 .../include => include}/villas/version.hpp | 0 lib/CMakeLists.txt | 40 ++++++- {common/lib => lib}/base64.cpp | 0 {common/lib => lib}/buffer.cpp | 0 {common/lib => lib}/common.cpp | 0 {common/lib => lib}/compat.cpp | 0 {common/lib => lib}/cpuset.cpp | 0 {common/lib => lib}/dsp/pid.cpp | 0 {common/lib => lib}/hist.cpp | 0 {common/lib => lib}/json.cpp | 0 {common/lib => lib}/kernel/kernel.cpp | 0 {common/lib => lib}/kernel/rt.cpp | 0 {common/lib => lib}/list.cpp | 0 {common/lib => lib}/log.cpp | 0 {common/lib => lib}/plugin.cpp | 0 {common/lib => lib}/popen.cpp | 0 {common/lib => lib}/table.cpp | 0 {common/lib => lib}/task.cpp | 0 {common/lib => lib}/terminal.cpp | 0 {common/lib => lib}/timing.cpp | 0 {common/lib => lib}/tool.cpp | 0 {common/lib => lib}/tsc.cpp | 0 {common/lib => lib}/utils.cpp | 0 {common/lib => lib}/uuid.cpp | 0 {common/lib => lib}/version.cpp | 0 src/CMakeLists.txt | 2 +- tests/unit/CMakeLists.txt | 9 ++ {common/tests => tests}/unit/base64.cpp | 0 {common/tests => tests}/unit/buffer.cpp | 0 {common/tests => tests}/unit/hist.cpp | 0 {common/tests => tests}/unit/kernel.cpp | 0 {common/tests => tests}/unit/list.cpp | 0 {common/tests => tests}/unit/popen.cpp | 0 {common/tests => tests}/unit/task.cpp | 0 {common/tests => tests}/unit/timing.cpp | 0 {common/tests => tests}/unit/utils.cpp | 0 103 files changed, 88 insertions(+), 198 deletions(-) delete mode 100644 common/CMakeLists.txt delete mode 100644 common/lib/CMakeLists.txt delete mode 100644 common/tests/CMakeLists.txt delete mode 100644 common/tests/unit/CMakeLists.txt rename {common => fpga}/include/villas/graph/directed.hpp (100%) rename {common => fpga}/include/villas/graph/edge.hpp (100%) rename {common => fpga}/include/villas/graph/vertex.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/device.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/device_connection.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/driver.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/ip_device.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/linux_driver.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/pci_device.hpp (100%) rename {common => fpga}/include/villas/kernel/devices/platform_device.hpp (100%) rename {common => fpga}/include/villas/kernel/vfio_container.hpp (100%) rename {common => fpga}/include/villas/kernel/vfio_device.hpp (100%) rename {common => fpga}/include/villas/kernel/vfio_group.hpp (100%) rename {common => fpga}/include/villas/memory.hpp (100%) rename {common => fpga}/include/villas/memory_manager.hpp (100%) rename {common => fpga}/lib/kernel/devices/device_connection.cpp (100%) rename {common => fpga}/lib/kernel/devices/ip_device.cpp (100%) rename {common => fpga}/lib/kernel/devices/linux_driver.cpp (100%) rename {common => fpga}/lib/kernel/devices/pci_device.cpp (100%) rename {common => fpga}/lib/kernel/devices/platform_device.cpp (100%) rename {common => fpga}/lib/kernel/vfio_container.cpp (100%) rename {common => fpga}/lib/kernel/vfio_device.cpp (100%) rename {common => fpga}/lib/kernel/vfio_group.cpp (100%) rename {common => fpga}/lib/memory.cpp (100%) rename {common => fpga}/lib/memory_manager.cpp (100%) rename {common => fpga}/tests/unit/graph.cpp (100%) rename {common/include => include}/villas/boxes.hpp (100%) rename {common/include => include}/villas/buffer.hpp (100%) rename {common/include => include}/villas/colors.hpp (100%) rename {common/include => include}/villas/common.hpp (100%) rename {common/include => include}/villas/compat.hpp (100%) rename {common/include => include}/villas/config.hpp.in (100%) rename {common/include => include}/villas/cpuset.hpp (100%) rename {common/include => include}/villas/dsp/exponential_window.hpp (100%) rename {common/include => include}/villas/dsp/moving_average_window.hpp (100%) rename {common/include => include}/villas/dsp/pid.hpp (100%) rename {common/include => include}/villas/dsp/window.hpp (100%) rename {common/include => include}/villas/dsp/window_cosine.hpp (100%) rename {common/include => include}/villas/exceptions.hpp (100%) rename {common/include => include}/villas/fs.hpp (100%) rename {common/include => include}/villas/hist.hpp (100%) rename {common/include => include}/villas/jansson.hpp (100%) rename {common/include => include}/villas/json.hpp (100%) rename {common/include => include}/villas/kernel/kernel.hpp (100%) rename {common/include => include}/villas/kernel/rt.hpp (100%) rename {common/include => include}/villas/list.hpp (100%) rename {common/include => include}/villas/log.hpp (100%) rename {common/include => include}/villas/plugin.hpp (100%) rename {common/include => include}/villas/popen.hpp (100%) rename {common/include => include}/villas/table.hpp (100%) rename {common/include => include}/villas/task.hpp (100%) rename {common/include => include}/villas/terminal.hpp (100%) rename {common/include => include}/villas/timing.hpp (100%) rename {common/include => include}/villas/tool.hpp (100%) rename {common/include => include}/villas/tsc.hpp (100%) rename {common/include => include}/villas/utils.hpp (100%) rename {common/include => include}/villas/uuid.hpp (100%) rename {common/include => include}/villas/version.hpp (100%) rename {common/lib => lib}/base64.cpp (100%) rename {common/lib => lib}/buffer.cpp (100%) rename {common/lib => lib}/common.cpp (100%) rename {common/lib => lib}/compat.cpp (100%) rename {common/lib => lib}/cpuset.cpp (100%) rename {common/lib => lib}/dsp/pid.cpp (100%) rename {common/lib => lib}/hist.cpp (100%) rename {common/lib => lib}/json.cpp (100%) rename {common/lib => lib}/kernel/kernel.cpp (100%) rename {common/lib => lib}/kernel/rt.cpp (100%) rename {common/lib => lib}/list.cpp (100%) rename {common/lib => lib}/log.cpp (100%) rename {common/lib => lib}/plugin.cpp (100%) rename {common/lib => lib}/popen.cpp (100%) rename {common/lib => lib}/table.cpp (100%) rename {common/lib => lib}/task.cpp (100%) rename {common/lib => lib}/terminal.cpp (100%) rename {common/lib => lib}/timing.cpp (100%) rename {common/lib => lib}/tool.cpp (100%) rename {common/lib => lib}/tsc.cpp (100%) rename {common/lib => lib}/utils.cpp (100%) rename {common/lib => lib}/uuid.cpp (100%) rename {common/lib => lib}/version.cpp (100%) rename {common/tests => tests}/unit/base64.cpp (100%) rename {common/tests => tests}/unit/buffer.cpp (100%) rename {common/tests => tests}/unit/hist.cpp (100%) rename {common/tests => tests}/unit/kernel.cpp (100%) rename {common/tests => tests}/unit/list.cpp (100%) rename {common/tests => tests}/unit/popen.cpp (100%) rename {common/tests => tests}/unit/task.cpp (100%) rename {common/tests => tests}/unit/timing.cpp (100%) rename {common/tests => tests}/unit/utils.cpp (100%) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index dc3e2b57b..f547cd7cf 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -117,7 +117,7 @@ jobs: run: cmake -S . -B build ${{ env.CCACHE }} - name: Build and run unit tests - run: LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH cmake --build build ${{ env.CMAKE_BUILD_OPTS }} --target run-unit-tests run-unit-tests-common + run: LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH cmake --build build ${{ env.CMAKE_BUILD_OPTS }} --target run-unit-tests integration: name: Integration Tests diff --git a/CMakeLists.txt b/CMakeLists.txt index 1cbf80ea1..061c95e7b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ set(PROJECT_COPYRIGHT "2014-2025 The VILLASframework Authors") set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_STANDARD 20) set(CMAKE_THREAD_PREFER_PTHREAD ON) -set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake;${PROJECT_SOURCE_DIR}/common/cmake") +set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) @@ -261,7 +261,6 @@ if(WITH_FPGA) add_subdirectory(fpga) endif() -add_subdirectory(common) add_subdirectory(etc) add_subdirectory(lib) add_subdirectory(packaging) @@ -287,6 +286,11 @@ if(WITH_TESTS) add_subdirectory(tests) endif() +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/include/villas/config.hpp.in + ${CMAKE_CURRENT_BINARY_DIR}/include/villas/config.hpp +) + configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/include/villas/node/config.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/include/villas/node/config.hpp diff --git a/CODEOWNERS b/CODEOWNERS index 22bd8481e..f8473294a 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -40,5 +40,5 @@ fpga @n-eiling /include/villas/dumper.hpp @windrad6 # VFIO related files -/common/lib/kernel @n-eiling -/common/include/villas/kernel @n-eiling +/fpga/lib/kernel @n-eiling +/fpga/include/villas/kernel @n-eiling diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt deleted file mode 100644 index 5f1b17d73..000000000 --- a/common/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -## CMakeLists.txt -# -# Author: Steffen Vogel -# SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University -# SPDX-License-Identifier: Apache-2.0 - -add_subdirectory(lib) -if(WITH_TESTS) - add_subdirectory(tests) -endif() - -configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/include/villas/config.hpp.in - ${CMAKE_CURRENT_BINARY_DIR}/include/villas/config.hpp -) diff --git a/common/lib/CMakeLists.txt b/common/lib/CMakeLists.txt deleted file mode 100644 index 816df3a42..000000000 --- a/common/lib/CMakeLists.txt +++ /dev/null @@ -1,108 +0,0 @@ -## CMakeLists.txt -# -# Author: Daniel Krebs -# SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University -# SPDX-License-Identifier: Apache-2.0 -# -# VILLAScommon - - -add_library(villas-common SHARED - base64.cpp - buffer.cpp - common.cpp - compat.cpp - cpuset.cpp - dsp/pid.cpp - hist.cpp - json.cpp - kernel/kernel.cpp - kernel/rt.cpp - list.cpp - log.cpp - memory_manager.cpp - memory.cpp - plugin.cpp - popen.cpp - table.cpp - task.cpp - terminal.cpp - timing.cpp - tool.cpp - utils.cpp - uuid.cpp - version.cpp -) - -if(CMAKE_SYSTEM_NAME STREQUAL Linux) - target_sources(villas-common PRIVATE - kernel/devices/device_connection.cpp - kernel/devices/ip_device.cpp - kernel/devices/linux_driver.cpp - kernel/devices/pci_device.cpp - kernel/devices/platform_device.cpp - kernel/vfio_device.cpp - kernel/vfio_group.cpp - kernel/vfio_container.cpp - tsc.cpp - ) -endif() - -target_include_directories(villas-common PUBLIC - ${OPENSSL_INCLUDE_DIR} - ${CURL_INCLUDE_DIRS} - ${PROJECT_BINARY_DIR}/common/include - ${PROJECT_SOURCE_DIR}/common/include -) - -target_link_libraries(villas-common PUBLIC - nlohmann_json::nlohmann_json - PkgConfig::JANSSON - PkgConfig::UUID - ${OPENSSL_LIBRARIES} - ${CURL_LIBRARIES} - ${CMAKE_DL_LIBS} - spdlog::spdlog - fmt::fmt - stdc++ -) - -if(WITH_CONFIG) - target_link_libraries(villas-common PUBLIC - PkgConfig::LIBCONFIG - ) -endif() - -target_compile_definitions(villas-common PUBLIC - -D__STDC_FORMAT_MACROS -D_GNU_SOURCE -) - -set_target_properties(villas-common PROPERTIES - VERSION ${CMAKE_PROJECT_VERSION} - SOVERSION 1 -) - -install( - TARGETS villas-common - EXPORT VILLASCommonConfig - COMPONENT lib - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} -) - -install( - DIRECTORY ${CMAKE_SOURCE_DIR}/common/include/villas/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/villas - COMPONENT devel - FILES_MATCHING - PATTERN "*.h" - PATTERN "*.hpp" -) - -install( - DIRECTORY ${PROJECT_BINARY_DIR}/common/include/villas/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/villas - COMPONENT devel - FILES_MATCHING - PATTERN "*.h" - PATTERN "*.hpp" -) diff --git a/common/tests/CMakeLists.txt b/common/tests/CMakeLists.txt deleted file mode 100644 index fb6d280a5..000000000 --- a/common/tests/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -# CMakeLists.txt. -# -# Author: Steffen Vogel -# SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University -# SPDX-License-Identifier: Apache-2.0 - -# We only have unit tests for now -if(CRITERION_FOUND) - add_subdirectory(unit) -endif() diff --git a/common/tests/unit/CMakeLists.txt b/common/tests/unit/CMakeLists.txt deleted file mode 100644 index 0da325f7f..000000000 --- a/common/tests/unit/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -## CMakeLists.txt -# -# Author: Daniel Krebs -# SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University -# SPDX-License-Identifier: Apache-2.0 -# -# VILLAScommon - -add_executable(unit-tests-common - buffer.cpp - graph.cpp - hist.cpp - kernel.cpp - list.cpp - task.cpp - timing.cpp - utils.cpp - base64.cpp - popen.cpp -) - -if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") - list(APPEND TEST_SRC tsc.cpp) -endif() - -target_include_directories(unit-tests-common PUBLIC - ${PROJECT_SOURCE_DIR}/common/include - ${CRITERION_INCLUDE_DIRS} -) - -target_link_libraries(unit-tests-common PUBLIC - villas-common - ${CRITERION_LIBRARIES} -) - -add_custom_target(run-unit-tests-common - COMMAND $ ${CRITERION_OPTS} - USES_TERMINAL -) diff --git a/common/include/villas/graph/directed.hpp b/fpga/include/villas/graph/directed.hpp similarity index 100% rename from common/include/villas/graph/directed.hpp rename to fpga/include/villas/graph/directed.hpp diff --git a/common/include/villas/graph/edge.hpp b/fpga/include/villas/graph/edge.hpp similarity index 100% rename from common/include/villas/graph/edge.hpp rename to fpga/include/villas/graph/edge.hpp diff --git a/common/include/villas/graph/vertex.hpp b/fpga/include/villas/graph/vertex.hpp similarity index 100% rename from common/include/villas/graph/vertex.hpp rename to fpga/include/villas/graph/vertex.hpp diff --git a/common/include/villas/kernel/devices/device.hpp b/fpga/include/villas/kernel/devices/device.hpp similarity index 100% rename from common/include/villas/kernel/devices/device.hpp rename to fpga/include/villas/kernel/devices/device.hpp diff --git a/common/include/villas/kernel/devices/device_connection.hpp b/fpga/include/villas/kernel/devices/device_connection.hpp similarity index 100% rename from common/include/villas/kernel/devices/device_connection.hpp rename to fpga/include/villas/kernel/devices/device_connection.hpp diff --git a/common/include/villas/kernel/devices/driver.hpp b/fpga/include/villas/kernel/devices/driver.hpp similarity index 100% rename from common/include/villas/kernel/devices/driver.hpp rename to fpga/include/villas/kernel/devices/driver.hpp diff --git a/common/include/villas/kernel/devices/ip_device.hpp b/fpga/include/villas/kernel/devices/ip_device.hpp similarity index 100% rename from common/include/villas/kernel/devices/ip_device.hpp rename to fpga/include/villas/kernel/devices/ip_device.hpp diff --git a/common/include/villas/kernel/devices/linux_driver.hpp b/fpga/include/villas/kernel/devices/linux_driver.hpp similarity index 100% rename from common/include/villas/kernel/devices/linux_driver.hpp rename to fpga/include/villas/kernel/devices/linux_driver.hpp diff --git a/common/include/villas/kernel/devices/pci_device.hpp b/fpga/include/villas/kernel/devices/pci_device.hpp similarity index 100% rename from common/include/villas/kernel/devices/pci_device.hpp rename to fpga/include/villas/kernel/devices/pci_device.hpp diff --git a/common/include/villas/kernel/devices/platform_device.hpp b/fpga/include/villas/kernel/devices/platform_device.hpp similarity index 100% rename from common/include/villas/kernel/devices/platform_device.hpp rename to fpga/include/villas/kernel/devices/platform_device.hpp diff --git a/common/include/villas/kernel/vfio_container.hpp b/fpga/include/villas/kernel/vfio_container.hpp similarity index 100% rename from common/include/villas/kernel/vfio_container.hpp rename to fpga/include/villas/kernel/vfio_container.hpp diff --git a/common/include/villas/kernel/vfio_device.hpp b/fpga/include/villas/kernel/vfio_device.hpp similarity index 100% rename from common/include/villas/kernel/vfio_device.hpp rename to fpga/include/villas/kernel/vfio_device.hpp diff --git a/common/include/villas/kernel/vfio_group.hpp b/fpga/include/villas/kernel/vfio_group.hpp similarity index 100% rename from common/include/villas/kernel/vfio_group.hpp rename to fpga/include/villas/kernel/vfio_group.hpp diff --git a/common/include/villas/memory.hpp b/fpga/include/villas/memory.hpp similarity index 100% rename from common/include/villas/memory.hpp rename to fpga/include/villas/memory.hpp diff --git a/common/include/villas/memory_manager.hpp b/fpga/include/villas/memory_manager.hpp similarity index 100% rename from common/include/villas/memory_manager.hpp rename to fpga/include/villas/memory_manager.hpp diff --git a/fpga/lib/CMakeLists.txt b/fpga/lib/CMakeLists.txt index b554195a4..7d068abcd 100644 --- a/fpga/lib/CMakeLists.txt +++ b/fpga/lib/CMakeLists.txt @@ -13,6 +13,17 @@ set(SOURCES core.cpp node.cpp utils.cpp + memory.cpp + memory_manager.cpp + + kernel/vfio_container.cpp + kernel/vfio_device.cpp + kernel/vfio_group.cpp + kernel/devices/device_connection.cpp + kernel/devices/ip_device.cpp + kernel/devices/linux_driver.cpp + kernel/devices/pci_device.cpp + kernel/devices/platform_device.cpp ips/aurora_xilinx.cpp ips/aurora.cpp @@ -41,20 +52,27 @@ set(SOURCES set_source_files_properties(ips/rtds2gpu/xrtds2gpu.c PROPERTIES COMPILE_FLAGS -Wno-int-to-pointer-cast) -add_library(villas-fpga SHARED ${SOURCES}) +# Linked into libvillas with --whole-archive (see lib/CMakeLists.txt) +add_library(villas-fpga STATIC ${SOURCES}) -target_link_libraries(villas-fpga PUBLIC villas-common) +set_target_properties(villas-fpga PROPERTIES + POSITION_INDEPENDENT_CODE ON +) -target_compile_definitions(villas-fpga PRIVATE - BUILDID=\"abc\" - _GNU_SOURCE +target_compile_definitions(villas-fpga + PUBLIC + __STDC_FORMAT_MACROS + _GNU_SOURCE + PRIVATE + BUILDID=\"abc\" ) target_include_directories(villas-fpga PUBLIC ${PROJECT_BINARY_DIR}/include + ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/fpga/include - ${JANSSON_INCLUDE_DIRS} + ${OPENSSL_INCLUDE_DIR} ) target_link_libraries(villas-fpga PUBLIC @@ -62,16 +80,10 @@ target_link_libraries(villas-fpga PUBLIC ${CMAKE_DL_LIBS} m xil - villas-common + PkgConfig::JANSSON + spdlog::spdlog + fmt::fmt "$<$,$,9.0>>:stdc++fs>" ) -include(GNUInstallDirs) - -install(TARGETS villas-fpga - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}/static -) - install(DIRECTORY ../include/villas DESTINATION include) diff --git a/common/lib/kernel/devices/device_connection.cpp b/fpga/lib/kernel/devices/device_connection.cpp similarity index 100% rename from common/lib/kernel/devices/device_connection.cpp rename to fpga/lib/kernel/devices/device_connection.cpp diff --git a/common/lib/kernel/devices/ip_device.cpp b/fpga/lib/kernel/devices/ip_device.cpp similarity index 100% rename from common/lib/kernel/devices/ip_device.cpp rename to fpga/lib/kernel/devices/ip_device.cpp diff --git a/common/lib/kernel/devices/linux_driver.cpp b/fpga/lib/kernel/devices/linux_driver.cpp similarity index 100% rename from common/lib/kernel/devices/linux_driver.cpp rename to fpga/lib/kernel/devices/linux_driver.cpp diff --git a/common/lib/kernel/devices/pci_device.cpp b/fpga/lib/kernel/devices/pci_device.cpp similarity index 100% rename from common/lib/kernel/devices/pci_device.cpp rename to fpga/lib/kernel/devices/pci_device.cpp diff --git a/common/lib/kernel/devices/platform_device.cpp b/fpga/lib/kernel/devices/platform_device.cpp similarity index 100% rename from common/lib/kernel/devices/platform_device.cpp rename to fpga/lib/kernel/devices/platform_device.cpp diff --git a/common/lib/kernel/vfio_container.cpp b/fpga/lib/kernel/vfio_container.cpp similarity index 100% rename from common/lib/kernel/vfio_container.cpp rename to fpga/lib/kernel/vfio_container.cpp diff --git a/common/lib/kernel/vfio_device.cpp b/fpga/lib/kernel/vfio_device.cpp similarity index 100% rename from common/lib/kernel/vfio_device.cpp rename to fpga/lib/kernel/vfio_device.cpp diff --git a/common/lib/kernel/vfio_group.cpp b/fpga/lib/kernel/vfio_group.cpp similarity index 100% rename from common/lib/kernel/vfio_group.cpp rename to fpga/lib/kernel/vfio_group.cpp diff --git a/common/lib/memory.cpp b/fpga/lib/memory.cpp similarity index 100% rename from common/lib/memory.cpp rename to fpga/lib/memory.cpp diff --git a/common/lib/memory_manager.cpp b/fpga/lib/memory_manager.cpp similarity index 100% rename from common/lib/memory_manager.cpp rename to fpga/lib/memory_manager.cpp diff --git a/fpga/src/CMakeLists.txt b/fpga/src/CMakeLists.txt index 50c44cd1b..b5b2ef8d8 100644 --- a/fpga/src/CMakeLists.txt +++ b/fpga/src/CMakeLists.txt @@ -7,11 +7,11 @@ add_executable(villas-fpga-ctrl villas-fpga-ctrl.cpp) target_link_libraries(villas-fpga-ctrl PUBLIC - villas-fpga + villas ) add_executable(villas-fpga-pipe villas-fpga-pipe.cpp) target_link_libraries(villas-fpga-pipe PUBLIC - villas-fpga + villas ) diff --git a/fpga/tests/unit/CMakeLists.txt b/fpga/tests/unit/CMakeLists.txt index d2a3884bf..e6953e434 100644 --- a/fpga/tests/unit/CMakeLists.txt +++ b/fpga/tests/unit/CMakeLists.txt @@ -8,6 +8,7 @@ set(SOURCES dma.cpp fifo.cpp fpga.cpp + graph.cpp logging.cpp main.cpp rtds.cpp @@ -26,6 +27,6 @@ target_include_directories(unit-tests-fpga PUBLIC ) target_link_libraries(unit-tests-fpga PUBLIC - villas-fpga + villas ${CRITERION_LIBRARIES} ) diff --git a/common/tests/unit/graph.cpp b/fpga/tests/unit/graph.cpp similarity index 100% rename from common/tests/unit/graph.cpp rename to fpga/tests/unit/graph.cpp diff --git a/common/include/villas/boxes.hpp b/include/villas/boxes.hpp similarity index 100% rename from common/include/villas/boxes.hpp rename to include/villas/boxes.hpp diff --git a/common/include/villas/buffer.hpp b/include/villas/buffer.hpp similarity index 100% rename from common/include/villas/buffer.hpp rename to include/villas/buffer.hpp diff --git a/common/include/villas/colors.hpp b/include/villas/colors.hpp similarity index 100% rename from common/include/villas/colors.hpp rename to include/villas/colors.hpp diff --git a/common/include/villas/common.hpp b/include/villas/common.hpp similarity index 100% rename from common/include/villas/common.hpp rename to include/villas/common.hpp diff --git a/common/include/villas/compat.hpp b/include/villas/compat.hpp similarity index 100% rename from common/include/villas/compat.hpp rename to include/villas/compat.hpp diff --git a/common/include/villas/config.hpp.in b/include/villas/config.hpp.in similarity index 100% rename from common/include/villas/config.hpp.in rename to include/villas/config.hpp.in diff --git a/common/include/villas/cpuset.hpp b/include/villas/cpuset.hpp similarity index 100% rename from common/include/villas/cpuset.hpp rename to include/villas/cpuset.hpp diff --git a/common/include/villas/dsp/exponential_window.hpp b/include/villas/dsp/exponential_window.hpp similarity index 100% rename from common/include/villas/dsp/exponential_window.hpp rename to include/villas/dsp/exponential_window.hpp diff --git a/common/include/villas/dsp/moving_average_window.hpp b/include/villas/dsp/moving_average_window.hpp similarity index 100% rename from common/include/villas/dsp/moving_average_window.hpp rename to include/villas/dsp/moving_average_window.hpp diff --git a/common/include/villas/dsp/pid.hpp b/include/villas/dsp/pid.hpp similarity index 100% rename from common/include/villas/dsp/pid.hpp rename to include/villas/dsp/pid.hpp diff --git a/common/include/villas/dsp/window.hpp b/include/villas/dsp/window.hpp similarity index 100% rename from common/include/villas/dsp/window.hpp rename to include/villas/dsp/window.hpp diff --git a/common/include/villas/dsp/window_cosine.hpp b/include/villas/dsp/window_cosine.hpp similarity index 100% rename from common/include/villas/dsp/window_cosine.hpp rename to include/villas/dsp/window_cosine.hpp diff --git a/common/include/villas/exceptions.hpp b/include/villas/exceptions.hpp similarity index 100% rename from common/include/villas/exceptions.hpp rename to include/villas/exceptions.hpp diff --git a/common/include/villas/fs.hpp b/include/villas/fs.hpp similarity index 100% rename from common/include/villas/fs.hpp rename to include/villas/fs.hpp diff --git a/common/include/villas/hist.hpp b/include/villas/hist.hpp similarity index 100% rename from common/include/villas/hist.hpp rename to include/villas/hist.hpp diff --git a/common/include/villas/jansson.hpp b/include/villas/jansson.hpp similarity index 100% rename from common/include/villas/jansson.hpp rename to include/villas/jansson.hpp diff --git a/common/include/villas/json.hpp b/include/villas/json.hpp similarity index 100% rename from common/include/villas/json.hpp rename to include/villas/json.hpp diff --git a/common/include/villas/kernel/kernel.hpp b/include/villas/kernel/kernel.hpp similarity index 100% rename from common/include/villas/kernel/kernel.hpp rename to include/villas/kernel/kernel.hpp diff --git a/common/include/villas/kernel/rt.hpp b/include/villas/kernel/rt.hpp similarity index 100% rename from common/include/villas/kernel/rt.hpp rename to include/villas/kernel/rt.hpp diff --git a/common/include/villas/list.hpp b/include/villas/list.hpp similarity index 100% rename from common/include/villas/list.hpp rename to include/villas/list.hpp diff --git a/common/include/villas/log.hpp b/include/villas/log.hpp similarity index 100% rename from common/include/villas/log.hpp rename to include/villas/log.hpp diff --git a/common/include/villas/plugin.hpp b/include/villas/plugin.hpp similarity index 100% rename from common/include/villas/plugin.hpp rename to include/villas/plugin.hpp diff --git a/common/include/villas/popen.hpp b/include/villas/popen.hpp similarity index 100% rename from common/include/villas/popen.hpp rename to include/villas/popen.hpp diff --git a/common/include/villas/table.hpp b/include/villas/table.hpp similarity index 100% rename from common/include/villas/table.hpp rename to include/villas/table.hpp diff --git a/common/include/villas/task.hpp b/include/villas/task.hpp similarity index 100% rename from common/include/villas/task.hpp rename to include/villas/task.hpp diff --git a/common/include/villas/terminal.hpp b/include/villas/terminal.hpp similarity index 100% rename from common/include/villas/terminal.hpp rename to include/villas/terminal.hpp diff --git a/common/include/villas/timing.hpp b/include/villas/timing.hpp similarity index 100% rename from common/include/villas/timing.hpp rename to include/villas/timing.hpp diff --git a/common/include/villas/tool.hpp b/include/villas/tool.hpp similarity index 100% rename from common/include/villas/tool.hpp rename to include/villas/tool.hpp diff --git a/common/include/villas/tsc.hpp b/include/villas/tsc.hpp similarity index 100% rename from common/include/villas/tsc.hpp rename to include/villas/tsc.hpp diff --git a/common/include/villas/utils.hpp b/include/villas/utils.hpp similarity index 100% rename from common/include/villas/utils.hpp rename to include/villas/utils.hpp diff --git a/common/include/villas/uuid.hpp b/include/villas/uuid.hpp similarity index 100% rename from common/include/villas/uuid.hpp rename to include/villas/uuid.hpp diff --git a/common/include/villas/version.hpp b/include/villas/version.hpp similarity index 100% rename from common/include/villas/version.hpp rename to include/villas/version.hpp diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 197be4bc4..4d8f5270c 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -5,16 +5,24 @@ # SPDX-License-Identifier: Apache-2.0 add_compile_options(-fPIC) +add_compile_definitions(__STDC_FORMAT_MACROS _GNU_SOURCE) list(APPEND INCLUDE_DIRS ${PROJECT_BINARY_DIR}/include ${PROJECT_SOURCE_DIR}/include + ${OPENSSL_INCLUDE_DIR} + ${CURL_INCLUDE_DIRS} ) set(LIBRARIES - villas-common + nlohmann_json::nlohmann_json PkgConfig::JANSSON PkgConfig::UUID + ${OPENSSL_LIBRARIES} + ${CURL_LIBRARIES} + ${CMAKE_DL_LIBS} + spdlog::spdlog + fmt::fmt m stdc++ rt @@ -22,10 +30,22 @@ set(LIBRARIES ) set(LIB_SRC + base64.cpp + buffer.cpp capabilities.cpp + common.cpp + compat.cpp config_helper.cpp + cpuset.cpp + dsp/pid.cpp dumper.cpp format.cpp + hist.cpp + json.cpp + kernel/kernel.cpp + kernel/rt.cpp + list.cpp + log.cpp mapping.cpp mapping_list.cpp memory.cpp @@ -42,7 +62,9 @@ set(LIB_SRC path_source.cpp path.cpp path_list.cpp + plugin.cpp pool.cpp + popen.cpp queue_signalled.cpp queue.cpp sample.cpp @@ -54,8 +76,20 @@ set(LIB_SRC socket_addr.cpp stats.cpp super_node.cpp + table.cpp + task.cpp + terminal.cpp + timing.cpp + tool.cpp + utils.cpp + uuid.cpp + version.cpp ) +if(CMAKE_SYSTEM_NAME STREQUAL Linux) + list(APPEND LIB_SRC tsc.cpp) +endif() + if(WITH_WEB) list(APPEND LIB_SRC web.cpp @@ -126,12 +160,14 @@ if(LIBUSB_FOUND) endif() if(WITH_FPGA) - list(APPEND LIBRARIES villas-fpga) + list(APPEND WHOLE_ARCHIVES villas-fpga) + list(APPEND INCLUDE_DIRS $) endif() add_library(villas SHARED ${LIB_SRC}) target_include_directories(villas PUBLIC ${INCLUDE_DIRS}) target_link_libraries(villas PUBLIC ${LIBRARIES}) +target_compile_definitions(villas PUBLIC __STDC_FORMAT_MACROS _GNU_SOURCE) target_link_libraries(villas PRIVATE -Wl,--whole-archive ${WHOLE_ARCHIVES} -Wl,--no-whole-archive) set_target_properties(villas PROPERTIES diff --git a/common/lib/base64.cpp b/lib/base64.cpp similarity index 100% rename from common/lib/base64.cpp rename to lib/base64.cpp diff --git a/common/lib/buffer.cpp b/lib/buffer.cpp similarity index 100% rename from common/lib/buffer.cpp rename to lib/buffer.cpp diff --git a/common/lib/common.cpp b/lib/common.cpp similarity index 100% rename from common/lib/common.cpp rename to lib/common.cpp diff --git a/common/lib/compat.cpp b/lib/compat.cpp similarity index 100% rename from common/lib/compat.cpp rename to lib/compat.cpp diff --git a/common/lib/cpuset.cpp b/lib/cpuset.cpp similarity index 100% rename from common/lib/cpuset.cpp rename to lib/cpuset.cpp diff --git a/common/lib/dsp/pid.cpp b/lib/dsp/pid.cpp similarity index 100% rename from common/lib/dsp/pid.cpp rename to lib/dsp/pid.cpp diff --git a/common/lib/hist.cpp b/lib/hist.cpp similarity index 100% rename from common/lib/hist.cpp rename to lib/hist.cpp diff --git a/common/lib/json.cpp b/lib/json.cpp similarity index 100% rename from common/lib/json.cpp rename to lib/json.cpp diff --git a/common/lib/kernel/kernel.cpp b/lib/kernel/kernel.cpp similarity index 100% rename from common/lib/kernel/kernel.cpp rename to lib/kernel/kernel.cpp diff --git a/common/lib/kernel/rt.cpp b/lib/kernel/rt.cpp similarity index 100% rename from common/lib/kernel/rt.cpp rename to lib/kernel/rt.cpp diff --git a/common/lib/list.cpp b/lib/list.cpp similarity index 100% rename from common/lib/list.cpp rename to lib/list.cpp diff --git a/common/lib/log.cpp b/lib/log.cpp similarity index 100% rename from common/lib/log.cpp rename to lib/log.cpp diff --git a/common/lib/plugin.cpp b/lib/plugin.cpp similarity index 100% rename from common/lib/plugin.cpp rename to lib/plugin.cpp diff --git a/common/lib/popen.cpp b/lib/popen.cpp similarity index 100% rename from common/lib/popen.cpp rename to lib/popen.cpp diff --git a/common/lib/table.cpp b/lib/table.cpp similarity index 100% rename from common/lib/table.cpp rename to lib/table.cpp diff --git a/common/lib/task.cpp b/lib/task.cpp similarity index 100% rename from common/lib/task.cpp rename to lib/task.cpp diff --git a/common/lib/terminal.cpp b/lib/terminal.cpp similarity index 100% rename from common/lib/terminal.cpp rename to lib/terminal.cpp diff --git a/common/lib/timing.cpp b/lib/timing.cpp similarity index 100% rename from common/lib/timing.cpp rename to lib/timing.cpp diff --git a/common/lib/tool.cpp b/lib/tool.cpp similarity index 100% rename from common/lib/tool.cpp rename to lib/tool.cpp diff --git a/common/lib/tsc.cpp b/lib/tsc.cpp similarity index 100% rename from common/lib/tsc.cpp rename to lib/tsc.cpp diff --git a/common/lib/utils.cpp b/lib/utils.cpp similarity index 100% rename from common/lib/utils.cpp rename to lib/utils.cpp diff --git a/common/lib/uuid.cpp b/lib/uuid.cpp similarity index 100% rename from common/lib/uuid.cpp rename to lib/uuid.cpp diff --git a/common/lib/version.cpp b/lib/version.cpp similarity index 100% rename from common/lib/version.cpp rename to lib/version.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8212b9b4a..16a6fca29 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -48,7 +48,7 @@ endif() if(LIBZMQ_FOUND) add_executable(villas-zmq-keygen villas-zmq-keygen.cpp) - target_link_libraries(villas-zmq-keygen PUBLIC villas-common PkgConfig::LIBZMQ) + target_link_libraries(villas-zmq-keygen PUBLIC villas PkgConfig::LIBZMQ) list(APPEND SRCS villas-zmq-keygen) endif() diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index c6d79c217..16e9b035e 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -5,18 +5,27 @@ # SPDX-License-Identifier: Apache-2.0 set(TEST_SRC + base64.cpp + buffer.cpp config_json.cpp config.cpp format.cpp helpers.cpp + hist.cpp json.cpp + kernel.cpp + list.cpp main.cpp mapping.cpp memory.cpp pool.cpp + popen.cpp queue_signalled.cpp queue.cpp signal.cpp + task.cpp + timing.cpp + utils.cpp ) if(WITH_NODE_C37_118) diff --git a/common/tests/unit/base64.cpp b/tests/unit/base64.cpp similarity index 100% rename from common/tests/unit/base64.cpp rename to tests/unit/base64.cpp diff --git a/common/tests/unit/buffer.cpp b/tests/unit/buffer.cpp similarity index 100% rename from common/tests/unit/buffer.cpp rename to tests/unit/buffer.cpp diff --git a/common/tests/unit/hist.cpp b/tests/unit/hist.cpp similarity index 100% rename from common/tests/unit/hist.cpp rename to tests/unit/hist.cpp diff --git a/common/tests/unit/kernel.cpp b/tests/unit/kernel.cpp similarity index 100% rename from common/tests/unit/kernel.cpp rename to tests/unit/kernel.cpp diff --git a/common/tests/unit/list.cpp b/tests/unit/list.cpp similarity index 100% rename from common/tests/unit/list.cpp rename to tests/unit/list.cpp diff --git a/common/tests/unit/popen.cpp b/tests/unit/popen.cpp similarity index 100% rename from common/tests/unit/popen.cpp rename to tests/unit/popen.cpp diff --git a/common/tests/unit/task.cpp b/tests/unit/task.cpp similarity index 100% rename from common/tests/unit/task.cpp rename to tests/unit/task.cpp diff --git a/common/tests/unit/timing.cpp b/tests/unit/timing.cpp similarity index 100% rename from common/tests/unit/timing.cpp rename to tests/unit/timing.cpp diff --git a/common/tests/unit/utils.cpp b/tests/unit/utils.cpp similarity index 100% rename from common/tests/unit/utils.cpp rename to tests/unit/utils.cpp From 6d929e978bffaaaac7770aba614a64bbac0c0e76 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 17:18:54 +0100 Subject: [PATCH 05/10] fix(fpga): Cleanup paths and namespaces Signed-off-by: Philipp Jungkamp --- CODEOWNERS | 6 ++- fpga/include/villas/fpga/card.hpp | 4 +- fpga/include/villas/fpga/core.hpp | 2 +- fpga/include/villas/fpga/core_connection.hpp | 13 +++---- .../{kernel => fpga}/devices/device.hpp | 6 +-- .../villas/fpga/devices/device_connection.hpp | 38 ++++++++++++++++++ .../{kernel => fpga}/devices/driver.hpp | 4 +- .../{kernel => fpga}/devices/ip_device.hpp | 8 ++-- .../{kernel => fpga}/devices/linux_driver.hpp | 6 +-- .../{kernel => fpga}/devices/pci_device.hpp | 4 +- .../devices/platform_device.hpp | 8 ++-- .../directed.hpp => fpga/directed_graph.hpp} | 8 ++-- fpga/include/villas/{graph => fpga}/edge.hpp | 8 ++-- fpga/include/villas/fpga/ips/bram.hpp | 2 +- fpga/include/villas/fpga/ips/dma.hpp | 2 +- fpga/include/villas/fpga/ips/gpu2rtds.hpp | 2 +- fpga/include/villas/fpga/ips/hls.hpp | 2 +- fpga/include/villas/fpga/ips/i2c.hpp | 2 +- fpga/include/villas/fpga/ips/intc.hpp | 6 +-- .../include/villas/fpga/ips/platform_intc.hpp | 2 +- fpga/include/villas/fpga/ips/rtds2gpu.hpp | 2 +- fpga/include/villas/{ => fpga}/memory.hpp | 4 +- .../villas/{ => fpga}/memory_manager.hpp | 16 ++++---- fpga/include/villas/fpga/node.hpp | 10 ++--- fpga/include/villas/fpga/pcie_card.hpp | 16 ++++---- fpga/include/villas/fpga/platform_card.hpp | 9 +++-- fpga/include/villas/fpga/utils.hpp | 16 ++++---- .../include/villas/{graph => fpga}/vertex.hpp | 6 +-- .../vfio/container.hpp} | 6 +-- .../vfio_device.hpp => fpga/vfio/device.hpp} | 8 ++-- .../vfio_group.hpp => fpga/vfio/group.hpp} | 8 ++-- .../kernel/devices/device_connection.hpp | 39 ------------------- fpga/lib/CMakeLists.txt | 16 ++++---- fpga/lib/core.cpp | 2 +- fpga/lib/core_connection.cpp | 12 +++--- .../devices/device_connection.cpp | 21 +++++----- fpga/lib/{kernel => }/devices/ip_device.cpp | 10 ++--- .../lib/{kernel => }/devices/linux_driver.cpp | 6 +-- fpga/lib/{kernel => }/devices/pci_device.cpp | 4 +- .../{kernel => }/devices/platform_device.cpp | 8 ++-- fpga/lib/ips/dma.cpp | 4 +- fpga/lib/ips/intc.cpp | 2 +- fpga/lib/ips/pcie.cpp | 2 +- fpga/lib/ips/rtds2gpu/gpu2rtds.cpp | 2 +- fpga/lib/ips/rtds2gpu/rtds2gpu.cpp | 2 +- fpga/lib/ips/zynq.cpp | 2 +- fpga/lib/memory.cpp | 4 +- fpga/lib/memory_manager.cpp | 4 +- fpga/lib/pcie_card.cpp | 21 +++++----- fpga/lib/platform_card.cpp | 9 ++--- fpga/lib/utils.cpp | 8 ++-- .../vfio_container.cpp => vfio/container.cpp} | 4 +- .../vfio_device.cpp => vfio/device.cpp} | 6 +-- .../{kernel/vfio_group.cpp => vfio/group.cpp} | 6 +-- fpga/src/villas-fpga-ctrl.cpp | 16 ++++---- fpga/src/villas-fpga-pipe.cpp | 10 ++--- fpga/tests/unit/dma.cpp | 18 ++++----- fpga/tests/unit/fpga.cpp | 6 +-- fpga/tests/unit/graph.cpp | 28 ++++++------- fpga/tests/unit/rtds.cpp | 4 +- include/villas/nodes/fpga.hpp | 12 +++--- lib/nodes/fpga.cpp | 8 ++-- 62 files changed, 267 insertions(+), 263 deletions(-) rename fpga/include/villas/{kernel => fpga}/devices/device.hpp (89%) create mode 100644 fpga/include/villas/fpga/devices/device_connection.hpp rename fpga/include/villas/{kernel => fpga}/devices/driver.hpp (94%) rename fpga/include/villas/{kernel => fpga}/devices/ip_device.hpp (84%) rename fpga/include/villas/{kernel => fpga}/devices/linux_driver.hpp (93%) rename fpga/include/villas/{kernel => fpga}/devices/pci_device.hpp (98%) rename fpga/include/villas/{kernel => fpga}/devices/platform_device.hpp (90%) rename fpga/include/villas/{graph/directed.hpp => fpga/directed_graph.hpp} (98%) rename fpga/include/villas/{graph => fpga}/edge.hpp (86%) rename fpga/include/villas/{ => fpga}/memory.hpp (99%) rename fpga/include/villas/{ => fpga}/memory_manager.hpp (95%) rename fpga/include/villas/{graph => fpga}/vertex.hpp (89%) rename fpga/include/villas/{kernel/vfio_container.hpp => fpga/vfio/container.hpp} (96%) rename fpga/include/villas/{kernel/vfio_device.hpp => fpga/vfio/device.hpp} (94%) rename fpga/include/villas/{kernel/vfio_group.hpp => fpga/vfio/group.hpp} (91%) delete mode 100644 fpga/include/villas/kernel/devices/device_connection.hpp rename fpga/lib/{kernel => }/devices/device_connection.cpp (79%) rename fpga/lib/{kernel => }/devices/ip_device.cpp (84%) rename fpga/lib/{kernel => }/devices/linux_driver.cpp (85%) rename fpga/lib/{kernel => }/devices/pci_device.cpp (99%) rename fpga/lib/{kernel => }/devices/platform_device.cpp (85%) rename fpga/lib/{kernel/vfio_container.cpp => vfio/container.cpp} (99%) rename fpga/lib/{kernel/vfio_device.cpp => vfio/device.cpp} (98%) rename fpga/lib/{kernel/vfio_group.cpp => vfio/group.cpp} (95%) diff --git a/CODEOWNERS b/CODEOWNERS index f8473294a..75127707d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -40,5 +40,7 @@ fpga @n-eiling /include/villas/dumper.hpp @windrad6 # VFIO related files -/fpga/lib/kernel @n-eiling -/fpga/include/villas/kernel @n-eiling +/fpga/lib/vfio @n-eiling +/fpga/lib/devices @n-eiling +/fpga/include/villas/fpga/vfio @n-eiling +/fpga/include/villas/fpga/devices @n-eiling diff --git a/fpga/include/villas/fpga/card.hpp b/fpga/include/villas/fpga/card.hpp index e62f7c47c..f789f94f6 100644 --- a/fpga/include/villas/fpga/card.hpp +++ b/fpga/include/villas/fpga/card.hpp @@ -13,8 +13,8 @@ #include #include +#include #include -#include namespace villas { namespace fpga { @@ -24,7 +24,7 @@ class Card { bool polling = 0; bool doReset = 0; // Reset VILLASfpga during startup? std::string name; // The name of the FPGA card - std::shared_ptr vfioContainer; + std::shared_ptr vfioContainer; // Slave address space ID to access the PCIe address space from the // FPGA diff --git a/fpga/include/villas/fpga/core.hpp b/fpga/include/villas/fpga/core.hpp index 8fb0847f8..6d4df16a8 100644 --- a/fpga/include/villas/fpga/core.hpp +++ b/fpga/include/villas/fpga/core.hpp @@ -19,9 +19,9 @@ #include #include +#include #include #include -#include #include namespace villas { diff --git a/fpga/include/villas/fpga/core_connection.hpp b/fpga/include/villas/fpga/core_connection.hpp index 8f8101191..3de04ddb6 100644 --- a/fpga/include/villas/fpga/core_connection.hpp +++ b/fpga/include/villas/fpga/core_connection.hpp @@ -17,8 +17,8 @@ #include #include -#include -#include +#include +#include namespace villas { namespace fpga { @@ -27,16 +27,15 @@ class CoreConnection { public: const Logger logger; const std::shared_ptr ip; - const villas::kernel::devices::DeviceConnection device_connection; + const villas::fpga::devices::DeviceConnection device_connection; private: CoreConnection(std::shared_ptr ip, - villas::kernel::devices::DeviceConnection device_connection); + villas::fpga::devices::DeviceConnection device_connection); public: - static CoreConnection - from(std::shared_ptr ip, - std::shared_ptr vfio_container); + static CoreConnection from(std::shared_ptr ip, + std::shared_ptr vfio_container); void add_to_memorygraph(); }; diff --git a/fpga/include/villas/kernel/devices/device.hpp b/fpga/include/villas/fpga/devices/device.hpp similarity index 89% rename from fpga/include/villas/kernel/devices/device.hpp rename to fpga/include/villas/fpga/devices/device.hpp index d6602da10..c5a09653e 100644 --- a/fpga/include/villas/kernel/devices/device.hpp +++ b/fpga/include/villas/fpga/devices/device.hpp @@ -10,11 +10,11 @@ #include +#include #include -#include namespace villas { -namespace kernel { +namespace fpga { namespace devices { class Device { @@ -30,5 +30,5 @@ class Device { }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/fpga/devices/device_connection.hpp b/fpga/include/villas/fpga/devices/device_connection.hpp new file mode 100644 index 000000000..dd9dd4d59 --- /dev/null +++ b/fpga/include/villas/fpga/devices/device_connection.hpp @@ -0,0 +1,38 @@ +/* Vfio connection to a device. + * + * Author: Pascal Bauer + * + * SPDX-FileCopyrightText: 2024-25 Pascal Bauer + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include +#include +#include + +namespace villas { +namespace fpga { +namespace devices { + +class DeviceConnection { +public: + Logger logger; + const std::shared_ptr vfio_device; + +private: + DeviceConnection(std::shared_ptr vfio_device); + +public: + static DeviceConnection from(const villas::fpga::devices::Device &device, + std::shared_ptr vfio_container); + + void addToMemorygraph() const; +}; + +} // namespace devices +} // namespace fpga +} // namespace villas diff --git a/fpga/include/villas/kernel/devices/driver.hpp b/fpga/include/villas/fpga/devices/driver.hpp similarity index 94% rename from fpga/include/villas/kernel/devices/driver.hpp rename to fpga/include/villas/fpga/devices/driver.hpp index 8e1f13685..ff4a65041 100644 --- a/fpga/include/villas/kernel/devices/driver.hpp +++ b/fpga/include/villas/fpga/devices/driver.hpp @@ -12,7 +12,7 @@ #include namespace villas { -namespace kernel { +namespace fpga { namespace devices { class Device; @@ -28,5 +28,5 @@ class Driver { }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/devices/ip_device.hpp b/fpga/include/villas/fpga/devices/ip_device.hpp similarity index 84% rename from fpga/include/villas/kernel/devices/ip_device.hpp rename to fpga/include/villas/fpga/devices/ip_device.hpp index 4ec192f08..f05ec3de1 100644 --- a/fpga/include/villas/kernel/devices/ip_device.hpp +++ b/fpga/include/villas/fpga/devices/ip_device.hpp @@ -10,11 +10,11 @@ #include +#include #include -#include namespace villas { -namespace kernel { +namespace fpga { namespace devices { class IpDevice : public PlatformDevice { @@ -31,10 +31,10 @@ class IpDevice : public PlatformDevice { size_t addr() const; std::string ip_name() const; - static std::vector + static std::vector from_directory(fs::path devices_directory); }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/devices/linux_driver.hpp b/fpga/include/villas/fpga/devices/linux_driver.hpp similarity index 93% rename from fpga/include/villas/kernel/devices/linux_driver.hpp rename to fpga/include/villas/fpga/devices/linux_driver.hpp index b1c01cb14..acb5a7888 100644 --- a/fpga/include/villas/kernel/devices/linux_driver.hpp +++ b/fpga/include/villas/fpga/devices/linux_driver.hpp @@ -11,11 +11,11 @@ #include #include +#include #include -#include namespace villas { -namespace kernel { +namespace fpga { namespace devices { class LinuxDriver : public Driver { @@ -48,5 +48,5 @@ class LinuxDriver : public Driver { }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/devices/pci_device.hpp b/fpga/include/villas/fpga/devices/pci_device.hpp similarity index 98% rename from fpga/include/villas/kernel/devices/pci_device.hpp rename to fpga/include/villas/fpga/devices/pci_device.hpp index ea95b7346..751b666ab 100644 --- a/fpga/include/villas/kernel/devices/pci_device.hpp +++ b/fpga/include/villas/fpga/devices/pci_device.hpp @@ -15,7 +15,7 @@ #include namespace villas { -namespace kernel { +namespace fpga { namespace devices { #define PCI_SLOT(devfn) (((devfn) >> 3) & 0x1f) @@ -125,5 +125,5 @@ class PciDeviceList : public std::list> { }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/devices/platform_device.hpp b/fpga/include/villas/fpga/devices/platform_device.hpp similarity index 90% rename from fpga/include/villas/kernel/devices/platform_device.hpp rename to fpga/include/villas/fpga/devices/platform_device.hpp index 1071a5a84..29fb3f2d8 100644 --- a/fpga/include/villas/kernel/devices/platform_device.hpp +++ b/fpga/include/villas/fpga/devices/platform_device.hpp @@ -8,12 +8,12 @@ #pragma once +#include +#include #include -#include -#include namespace villas { -namespace kernel { +namespace fpga { namespace devices { class PlatformDevice : public Device { @@ -46,5 +46,5 @@ class PlatformDevice : public Device { }; } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/graph/directed.hpp b/fpga/include/villas/fpga/directed_graph.hpp similarity index 98% rename from fpga/include/villas/graph/directed.hpp rename to fpga/include/villas/fpga/directed_graph.hpp index e74c3a9d5..c71f7254b 100644 --- a/fpga/include/villas/graph/directed.hpp +++ b/fpga/include/villas/fpga/directed_graph.hpp @@ -16,12 +16,12 @@ #include #include -#include -#include +#include +#include #include namespace villas { -namespace graph { +namespace fpga { template class DirectedGraph { @@ -251,5 +251,5 @@ class DirectedGraph { Logger logger; }; -} // namespace graph +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/graph/edge.hpp b/fpga/include/villas/fpga/edge.hpp similarity index 86% rename from fpga/include/villas/graph/edge.hpp rename to fpga/include/villas/fpga/edge.hpp index 0c4efe3d1..4b775e117 100644 --- a/fpga/include/villas/graph/edge.hpp +++ b/fpga/include/villas/fpga/edge.hpp @@ -10,10 +10,10 @@ #include #include -#include +#include namespace villas { -namespace graph { +namespace fpga { class Edge { template friend class DirectedGraph; @@ -43,10 +43,10 @@ class Edge { Vertex::Identifier to; }; -} // namespace graph +} // namespace fpga } // namespace villas #ifndef FMT_LEGACY_OSTREAM_FORMATTER template <> -class fmt::formatter : public fmt::ostream_formatter {}; +class fmt::formatter : public fmt::ostream_formatter {}; #endif diff --git a/fpga/include/villas/fpga/ips/bram.hpp b/fpga/include/villas/fpga/ips/bram.hpp index b36f336a1..e16fd9c66 100644 --- a/fpga/include/villas/fpga/ips/bram.hpp +++ b/fpga/include/villas/fpga/ips/bram.hpp @@ -8,7 +8,7 @@ #pragma once #include -#include +#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/dma.hpp b/fpga/include/villas/fpga/ips/dma.hpp index abf9a092d..d444a6ae5 100644 --- a/fpga/include/villas/fpga/ips/dma.hpp +++ b/fpga/include/villas/fpga/ips/dma.hpp @@ -14,8 +14,8 @@ #include #include +#include #include -#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/gpu2rtds.hpp b/fpga/include/villas/fpga/ips/gpu2rtds.hpp index 754929df2..d858e8689 100644 --- a/fpga/include/villas/fpga/ips/gpu2rtds.hpp +++ b/fpga/include/villas/fpga/ips/gpu2rtds.hpp @@ -10,8 +10,8 @@ #include #include #include +#include #include -#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/hls.hpp b/fpga/include/villas/fpga/ips/hls.hpp index 979d01b28..228d44b30 100644 --- a/fpga/include/villas/fpga/ips/hls.hpp +++ b/fpga/include/villas/fpga/ips/hls.hpp @@ -7,8 +7,8 @@ #pragma once +#include #include -#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/i2c.hpp b/fpga/include/villas/fpga/ips/i2c.hpp index 91f53d2e8..f6c5868a7 100644 --- a/fpga/include/villas/fpga/ips/i2c.hpp +++ b/fpga/include/villas/fpga/ips/i2c.hpp @@ -12,8 +12,8 @@ #include #include +#include #include -#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/intc.hpp b/fpga/include/villas/fpga/ips/intc.hpp index cb459d989..565a46544 100644 --- a/fpga/include/villas/fpga/ips/intc.hpp +++ b/fpga/include/villas/fpga/ips/intc.hpp @@ -11,7 +11,7 @@ #include #include -#include +#include namespace villas { namespace fpga { @@ -45,7 +45,7 @@ class InterruptController : public Core { protected: static constexpr char registerMemory[] = "reg0"; - std::shared_ptr vfioDevice = nullptr; + std::shared_ptr vfioDevice = nullptr; std::list getMemoryBlocks() const override { return {registerMemory}; @@ -57,7 +57,7 @@ class InterruptController : public Core { bool polling; // Polled or not }; - std::vector irq_vectors; + std::vector irq_vectors; int nos[maxIrqs] = {-1}; bool polling[maxIrqs] = {false}; }; diff --git a/fpga/include/villas/fpga/ips/platform_intc.hpp b/fpga/include/villas/fpga/ips/platform_intc.hpp index e90989ddb..0bfa82ee6 100644 --- a/fpga/include/villas/fpga/ips/platform_intc.hpp +++ b/fpga/include/villas/fpga/ips/platform_intc.hpp @@ -12,7 +12,7 @@ #include #include -#include +#include namespace villas { namespace fpga { diff --git a/fpga/include/villas/fpga/ips/rtds2gpu.hpp b/fpga/include/villas/fpga/ips/rtds2gpu.hpp index 01af005df..d50294bcf 100644 --- a/fpga/include/villas/fpga/ips/rtds2gpu.hpp +++ b/fpga/include/villas/fpga/ips/rtds2gpu.hpp @@ -8,8 +8,8 @@ #pragma once #include +#include #include -#include #include "rtds2gpu/register_types.hpp" #include "rtds2gpu/xrtds2gpu.h" diff --git a/fpga/include/villas/memory.hpp b/fpga/include/villas/fpga/memory.hpp similarity index 99% rename from fpga/include/villas/memory.hpp rename to fpga/include/villas/fpga/memory.hpp index 52b1cc7f3..dcaf3aa99 100644 --- a/fpga/include/villas/memory.hpp +++ b/fpga/include/villas/fpga/memory.hpp @@ -11,10 +11,11 @@ #include +#include #include -#include namespace villas { +namespace fpga { // Basic memory block backed by an address space in the memory graph // @@ -288,4 +289,5 @@ class HostDmaRam { static uintptr_t getUdmaBufPhysAddr(int num); }; +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/memory_manager.hpp b/fpga/include/villas/fpga/memory_manager.hpp similarity index 95% rename from fpga/include/villas/memory_manager.hpp rename to fpga/include/villas/fpga/memory_manager.hpp index fee4fdf14..60590e2bc 100644 --- a/fpga/include/villas/memory_manager.hpp +++ b/fpga/include/villas/fpga/memory_manager.hpp @@ -16,10 +16,11 @@ #include #include -#include +#include #include namespace villas { +namespace fpga { // Translation between a local (master) to a foreign (slave) address space // @@ -92,7 +93,7 @@ class MemoryManager { // The application allocates a block 1kB at address 0x843001000 in its // address space. The mapping would then have a #dest address of 0x843001000 // and a #size of 1024. - class Mapping : public graph::Edge { + class Mapping : public Edge { public: std::string name; // Human-readable name uintptr_t src; // Base address in "from" address space @@ -119,7 +120,7 @@ class MemoryManager { // Since most information in the memory graph is stored in the edges (memory // mappings), this is just a small extension to the default vertex. It only // associates an additional string #name for human-readability. - class AddressSpace : public graph::Vertex { + class AddressSpace : public Vertex { public: std::string name; // Human-readable name @@ -131,7 +132,7 @@ class MemoryManager { }; // Memory graph with custom edges and vertices for address resolution - using MemoryGraph = graph::DirectedGraph; + using MemoryGraph = DirectedGraph; public: using AddressSpaceId = MemoryGraph::VertexIdentifier; @@ -225,16 +226,17 @@ class MemoryManager { static MemoryManager *instance; }; +} // namespace fpga } // namespace villas #ifndef FMT_LEGACY_OSTREAM_FORMATTER template <> -class fmt::formatter +class fmt::formatter : public fmt::ostream_formatter {}; template <> -class fmt::formatter +class fmt::formatter : public fmt::ostream_formatter {}; template <> -class fmt::formatter +class fmt::formatter : public fmt::ostream_formatter {}; #endif diff --git a/fpga/include/villas/fpga/node.hpp b/fpga/include/villas/fpga/node.hpp index 3ce7f5251..6a5c2fb9c 100644 --- a/fpga/include/villas/fpga/node.hpp +++ b/fpga/include/villas/fpga/node.hpp @@ -18,16 +18,16 @@ #include #include -#include +#include namespace villas { namespace fpga { namespace ip { -class StreamVertex : public graph::Vertex { +class StreamVertex : public Vertex { public: StreamVertex(const std::string &node, const std::string &port, bool isMaster) - : graph::Vertex(), nodeName(node), portName(port), isMaster(isMaster) {} + : Vertex(), nodeName(node), portName(port), isMaster(isMaster) {} std::string getName() const { return nodeName + "/" + portName + "(" + (isMaster ? "M" : "S") + ")"; @@ -44,9 +44,9 @@ class StreamVertex : public graph::Vertex { bool isMaster; }; -class StreamGraph : public graph::DirectedGraph { +class StreamGraph : public DirectedGraph { public: - StreamGraph() : graph::DirectedGraph("stream:graph") {} + StreamGraph() : DirectedGraph("stream:graph") {} std::shared_ptr getOrCreateStreamVertex(const std::string &node, const std::string &port, diff --git a/fpga/include/villas/fpga/pcie_card.hpp b/fpga/include/villas/fpga/pcie_card.hpp index 95b045567..5f6fca63d 100644 --- a/fpga/include/villas/fpga/pcie_card.hpp +++ b/fpga/include/villas/fpga/pcie_card.hpp @@ -19,10 +19,10 @@ #include #include #include +#include +#include +#include #include -#include -#include -#include #include namespace villas { @@ -53,8 +53,8 @@ class PCIeCard : public Card { public: // TODO: make this private int affinity; // Affinity for MSI interrupts - std::shared_ptr pdev; // PCI device handle - std::shared_ptr vfioDevice; + std::shared_ptr pdev; // PCI device handle + std::shared_ptr vfioDevice; protected: Logger getLogger() const { return villas::Log::get(name); } @@ -62,9 +62,9 @@ class PCIeCard : public Card { class PCIeCardFactory : public plugin::Plugin { public: - static std::shared_ptr - make(json_t *json, std::string card_name, - std::shared_ptr vc, const fs::path &searchPath); + static std::shared_ptr make(json_t *json, std::string card_name, + std::shared_ptr vc, + const fs::path &searchPath); static PCIeCard *make() { return new PCIeCard(); } diff --git a/fpga/include/villas/fpga/platform_card.hpp b/fpga/include/villas/fpga/platform_card.hpp index 39df00441..9d18f7141 100644 --- a/fpga/include/villas/fpga/platform_card.hpp +++ b/fpga/include/villas/fpga/platform_card.hpp @@ -23,7 +23,7 @@ namespace fpga { class PlatformCard : public Card { public: - PlatformCard(std::shared_ptr vfioContainer); + PlatformCard(std::shared_ptr vfioContainer); ~PlatformCard() override{}; @@ -36,9 +36,10 @@ class PlatformCard : public Card { class PlatformCardFactory { public: - static std::shared_ptr - make(json_t *json_card, std::string card_name, - std::shared_ptr vc, const fs::path &searchPath); + static std::shared_ptr make(json_t *json_card, + std::string card_name, + std::shared_ptr vc, + const fs::path &searchPath); }; } /* namespace fpga */ diff --git a/fpga/include/villas/fpga/utils.hpp b/fpga/include/villas/fpga/utils.hpp index 8b45306c9..c75ec8e4b 100644 --- a/fpga/include/villas/fpga/utils.hpp +++ b/fpga/include/villas/fpga/utils.hpp @@ -20,17 +20,15 @@ std::shared_ptr setupFpgaCard(const std::string &configFile, std::shared_ptr createCard(json_t *config, const fs::path &searchPath, - std::shared_ptr vfioContainer, + std::shared_ptr vfioContainer, std::string card_name = "anonymous Card"); -int createCards( - json_t *config, std::list> &cards, - const fs::path &searchPath, - std::shared_ptr vfioContainer = nullptr); -int createCards( - json_t *config, std::list> &cards, - const std::string &searchPath, - std::shared_ptr vfioContainer = nullptr); +int createCards(json_t *config, std::list> &cards, + const fs::path &searchPath, + std::shared_ptr vfioContainer = nullptr); +int createCards(json_t *config, std::list> &cards, + const std::string &searchPath, + std::shared_ptr vfioContainer = nullptr); std::shared_ptr>> getAuroraChannels(std::shared_ptr card); diff --git a/fpga/include/villas/graph/vertex.hpp b/fpga/include/villas/fpga/vertex.hpp similarity index 89% rename from fpga/include/villas/graph/vertex.hpp rename to fpga/include/villas/fpga/vertex.hpp index 4dcf73ad1..162c03b1c 100644 --- a/fpga/include/villas/graph/vertex.hpp +++ b/fpga/include/villas/fpga/vertex.hpp @@ -15,7 +15,7 @@ #include namespace villas { -namespace graph { +namespace fpga { class Vertex { template friend class DirectedGraph; @@ -45,10 +45,10 @@ class Vertex { std::list edges; }; -} // namespace graph +} // namespace fpga } // namespace villas #ifndef FMT_LEGACY_OSTREAM_FORMATTER template <> -class fmt::formatter : public fmt::ostream_formatter {}; +class fmt::formatter : public fmt::ostream_formatter {}; #endif diff --git a/fpga/include/villas/kernel/vfio_container.hpp b/fpga/include/villas/fpga/vfio/container.hpp similarity index 96% rename from fpga/include/villas/kernel/vfio_container.hpp rename to fpga/include/villas/fpga/vfio/container.hpp index e9ef36b7d..eb5d18c29 100644 --- a/fpga/include/villas/kernel/vfio_container.hpp +++ b/fpga/include/villas/fpga/vfio/container.hpp @@ -18,10 +18,10 @@ #include #include -#include +#include namespace villas { -namespace kernel { +namespace fpga { namespace vfio { // Backwards compatibility with older kernels @@ -79,5 +79,5 @@ class Container { }; } // namespace vfio -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/vfio_device.hpp b/fpga/include/villas/fpga/vfio/device.hpp similarity index 94% rename from fpga/include/villas/kernel/vfio_device.hpp rename to fpga/include/villas/fpga/vfio/device.hpp index d1af0951d..ddde27c0a 100644 --- a/fpga/include/villas/kernel/vfio_device.hpp +++ b/fpga/include/villas/fpga/vfio/device.hpp @@ -19,11 +19,11 @@ #include #include -#include +#include #include namespace villas { -namespace kernel { +namespace fpga { namespace vfio { class Device { @@ -35,7 +35,7 @@ class Device { }; Device(const std::string &name, int groupFileDescriptor, - const kernel::devices::PciDevice *pci_device = nullptr); + const devices::PciDevice *pci_device = nullptr); ~Device(); // No copying allowed because we manage the vfio state in constructor and destructors @@ -102,5 +102,5 @@ class Device { }; } // namespace vfio -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/vfio_group.hpp b/fpga/include/villas/fpga/vfio/group.hpp similarity index 91% rename from fpga/include/villas/kernel/vfio_group.hpp rename to fpga/include/villas/fpga/vfio/group.hpp index 5f990c46c..952815973 100644 --- a/fpga/include/villas/kernel/vfio_group.hpp +++ b/fpga/include/villas/fpga/vfio/group.hpp @@ -18,11 +18,11 @@ #include #include -#include +#include #include namespace villas { -namespace kernel { +namespace fpga { namespace vfio { #define VFIO_PATH "/dev/vfio/" @@ -48,7 +48,7 @@ class Group { std::shared_ptr attachDevice(std::shared_ptr device); std::shared_ptr attachDevice(const std::string &name, - const kernel::devices::PciDevice *pci_device = nullptr); + const devices::PciDevice *pci_device = nullptr); bool checkStatus(); void dump(); @@ -72,5 +72,5 @@ class Group { }; } // namespace vfio -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/include/villas/kernel/devices/device_connection.hpp b/fpga/include/villas/kernel/devices/device_connection.hpp deleted file mode 100644 index 122ea1c07..000000000 --- a/fpga/include/villas/kernel/devices/device_connection.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/* Vfio connection to a device. - * - * Author: Pascal Bauer - * - * SPDX-FileCopyrightText: 2024-25 Pascal Bauer - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include - -#include -#include -#include - -namespace villas { -namespace kernel { -namespace devices { - -class DeviceConnection { -public: - Logger logger; - const std::shared_ptr vfio_device; - -private: - DeviceConnection(std::shared_ptr vfio_device); - -public: - static DeviceConnection - from(const villas::kernel::devices::Device &device, - std::shared_ptr vfio_container); - - void addToMemorygraph() const; -}; - -} // namespace devices -} // namespace kernel -} // namespace villas diff --git a/fpga/lib/CMakeLists.txt b/fpga/lib/CMakeLists.txt index 7d068abcd..8e176ed65 100644 --- a/fpga/lib/CMakeLists.txt +++ b/fpga/lib/CMakeLists.txt @@ -16,14 +16,14 @@ set(SOURCES memory.cpp memory_manager.cpp - kernel/vfio_container.cpp - kernel/vfio_device.cpp - kernel/vfio_group.cpp - kernel/devices/device_connection.cpp - kernel/devices/ip_device.cpp - kernel/devices/linux_driver.cpp - kernel/devices/pci_device.cpp - kernel/devices/platform_device.cpp + vfio/container.cpp + vfio/device.cpp + vfio/group.cpp + devices/device_connection.cpp + devices/ip_device.cpp + devices/linux_driver.cpp + devices/pci_device.cpp + devices/platform_device.cpp ips/aurora_xilinx.cpp ips/aurora.cpp diff --git a/fpga/lib/core.cpp b/fpga/lib/core.cpp index 40678c260..5186883e9 100644 --- a/fpga/lib/core.cpp +++ b/fpga/lib/core.cpp @@ -16,11 +16,11 @@ #include #include #include +#include #include #include #include #include -#include #include using namespace villas::fpga; diff --git a/fpga/lib/core_connection.cpp b/fpga/lib/core_connection.cpp index 242009a34..90fc2988f 100644 --- a/fpga/lib/core_connection.cpp +++ b/fpga/lib/core_connection.cpp @@ -18,21 +18,21 @@ namespace fpga { CoreConnection::CoreConnection( std::shared_ptr ip, - villas::kernel::devices::DeviceConnection device_connection) + villas::fpga::devices::DeviceConnection device_connection) : logger(villas::Log::get("CoreConnection")), ip(ip), device_connection(device_connection){}; CoreConnection CoreConnection::from(std::shared_ptr ip, - std::shared_ptr vfio_container) { + std::shared_ptr vfio_container) { // Find matching OS device for ip const fs::path PLATFORM_DEVICES_DIRECTORY("/sys/bus/platform/devices"); - std::vector devices = - villas::kernel::devices::IpDevice::from_directory( + std::vector devices = + villas::fpga::devices::IpDevice::from_directory( PLATFORM_DEVICES_DIRECTORY); auto it_device = std::find_if(devices.begin(), devices.end(), - [ip](villas::kernel::devices::IpDevice device) { + [ip](villas::fpga::devices::IpDevice device) { return ip->getBaseaddr() == device.addr(); }); @@ -41,7 +41,7 @@ CoreConnection::from(std::shared_ptr ip, "No device found with address matching ip baseadress.")); } - return CoreConnection(ip, villas::kernel::devices::DeviceConnection::from( + return CoreConnection(ip, villas::fpga::devices::DeviceConnection::from( *it_device, vfio_container)); } diff --git a/fpga/lib/kernel/devices/device_connection.cpp b/fpga/lib/devices/device_connection.cpp similarity index 79% rename from fpga/lib/kernel/devices/device_connection.cpp rename to fpga/lib/devices/device_connection.cpp index b32872f02..9b19f9624 100644 --- a/fpga/lib/kernel/devices/device_connection.cpp +++ b/fpga/lib/devices/device_connection.cpp @@ -8,21 +8,20 @@ #include -#include -#include -#include +#include +#include +#include namespace villas { -namespace kernel { +namespace fpga { namespace devices { -DeviceConnection::DeviceConnection( - std::shared_ptr vfio_device) +DeviceConnection::DeviceConnection(std::shared_ptr vfio_device) : logger(villas::Log::get("DeviceConnection")), vfio_device(vfio_device){}; -DeviceConnection DeviceConnection::from( - const villas::kernel::devices::Device &device, - std::shared_ptr vfio_container) { +DeviceConnection +DeviceConnection::from(const villas::fpga::devices::Device &device, + std::shared_ptr vfio_container) { auto logger = villas::Log::get("Builder: DeviceConnection"); // Bind the devicetree device to vfio driver @@ -35,7 +34,7 @@ DeviceConnection DeviceConnection::from( logger->debug("Device: {}, Iommu: {}", device.name(), iommu_group); // Open Vfio Device - auto vfio_device = std::make_shared( + auto vfio_device = std::make_shared( device.name(), vfio_group->getFileDescriptor()); // Attach device to group @@ -64,5 +63,5 @@ void DeviceConnection::addToMemorygraph() const { } } // namespace devices -} // namespace kernel +} // namespace fpga } // namespace villas diff --git a/fpga/lib/kernel/devices/ip_device.cpp b/fpga/lib/devices/ip_device.cpp similarity index 84% rename from fpga/lib/kernel/devices/ip_device.cpp rename to fpga/lib/devices/ip_device.cpp index 6a8c00009..f3aacf294 100644 --- a/fpga/lib/kernel/devices/ip_device.cpp +++ b/fpga/lib/devices/ip_device.cpp @@ -10,11 +10,11 @@ #include #include +#include #include -#include #include -using villas::kernel::devices::IpDevice; +using villas::fpga::devices::IpDevice; IpDevice IpDevice::from(const fs::path unsafe_path) { if (!is_path_valid(unsafe_path)) @@ -54,13 +54,13 @@ bool IpDevice::is_path_valid(const fs::path unsafe_path) { return true; } -std::vector +std::vector IpDevice::from_directory(fs::path devices_directory) { - std::vector devices; + std::vector devices; for (auto devicetree : fs::directory_iterator{devices_directory}) { try { - auto device = villas::kernel::devices::IpDevice::from(devicetree.path()); + auto device = villas::fpga::devices::IpDevice::from(devicetree.path()); devices.push_back(device); } catch (std::runtime_error &e) { } diff --git a/fpga/lib/kernel/devices/linux_driver.cpp b/fpga/lib/devices/linux_driver.cpp similarity index 85% rename from fpga/lib/kernel/devices/linux_driver.cpp rename to fpga/lib/devices/linux_driver.cpp index d6cfcda48..70eb75315 100644 --- a/fpga/lib/kernel/devices/linux_driver.cpp +++ b/fpga/lib/devices/linux_driver.cpp @@ -6,11 +6,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include -#include +#include +#include #include -using villas::kernel::devices::Device, villas::kernel::devices::LinuxDriver; +using villas::fpga::devices::Device, villas::fpga::devices::LinuxDriver; using villas::utils::write_to_file; void LinuxDriver::attach(const Device &device) const { diff --git a/fpga/lib/kernel/devices/pci_device.cpp b/fpga/lib/devices/pci_device.cpp similarity index 99% rename from fpga/lib/kernel/devices/pci_device.cpp rename to fpga/lib/devices/pci_device.cpp index 377c7d697..9a85795df 100644 --- a/fpga/lib/kernel/devices/pci_device.cpp +++ b/fpga/lib/devices/pci_device.cpp @@ -19,10 +19,10 @@ #include #include -#include +#include #include -using namespace villas::kernel::devices; +using namespace villas::fpga::devices; #define PCI_BASE_ADDRESS_N(n) (PCI_BASE_ADDRESS_0 + sizeof(uint32_t) * (n)) diff --git a/fpga/lib/kernel/devices/platform_device.cpp b/fpga/lib/devices/platform_device.cpp similarity index 85% rename from fpga/lib/kernel/devices/platform_device.cpp rename to fpga/lib/devices/platform_device.cpp index 48a98ea70..8427bc7df 100644 --- a/fpga/lib/kernel/devices/platform_device.cpp +++ b/fpga/lib/devices/platform_device.cpp @@ -6,12 +6,12 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include -#include +#include +#include #include -using villas::kernel::devices::Driver, villas::kernel::devices::LinuxDriver; -using villas::kernel::devices::PlatformDevice; +using villas::fpga::devices::Driver, villas::fpga::devices::LinuxDriver; +using villas::fpga::devices::PlatformDevice; using villas::utils::write_to_file; std::optional> PlatformDevice::driver() const { diff --git a/fpga/lib/ips/dma.cpp b/fpga/lib/ips/dma.cpp index 11134c306..f5eb7d3db 100644 --- a/fpga/lib/ips/dma.cpp +++ b/fpga/lib/ips/dma.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include // Max. size of a DMA transfer in simple mode #define FPGA_DMA_BOUNDARY 0x1000 @@ -71,7 +71,7 @@ bool Dma::init() { void Dma::setupScatterGather() { // Allocate and map space for BD ring in host RAM - auto &alloc = villas::HostRam::getAllocator(); + auto &alloc = villas::fpga::HostRam::getAllocator(); sgRing = alloc.allocateBlock(2 * requestedRingBdSizeMemory); if (not card->mapMemoryBlock(sgRing)) diff --git a/fpga/lib/ips/intc.cpp b/fpga/lib/ips/intc.cpp index f4ec9fa17..6b930b56f 100644 --- a/fpga/lib/ips/intc.cpp +++ b/fpga/lib/ips/intc.cpp @@ -29,7 +29,7 @@ bool InterruptController::init() { this->vfioDevice = pciecard->vfioDevice; const uintptr_t base = getBaseAddr(registerMemory); - kernel::vfio::Device::IrqVectorInfo irq_vector = {.eventFds = {0}}; + vfio::Device::IrqVectorInfo irq_vector = {.eventFds = {0}}; irq_vector.numFds = this->vfioDevice->pciMsiInit(irq_vector.eventFds); irq_vector.automask = true; irq_vectors.push_back(irq_vector); diff --git a/fpga/lib/ips/pcie.cpp b/fpga/lib/ips/pcie.cpp index c3e6b3067..f50ae5c3d 100644 --- a/fpga/lib/ips/pcie.cpp +++ b/fpga/lib/ips/pcie.cpp @@ -12,8 +12,8 @@ #include #include #include +#include #include -#include using namespace villas::fpga::ip; diff --git a/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp b/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp index 172953536..cac0cdb8f 100644 --- a/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp +++ b/fpga/lib/ips/rtds2gpu/gpu2rtds.cpp @@ -10,8 +10,8 @@ #include #include +#include #include -#include using namespace villas::fpga::ip; diff --git a/fpga/lib/ips/rtds2gpu/rtds2gpu.cpp b/fpga/lib/ips/rtds2gpu/rtds2gpu.cpp index 7e06b5df7..b51a6f8e4 100644 --- a/fpga/lib/ips/rtds2gpu/rtds2gpu.cpp +++ b/fpga/lib/ips/rtds2gpu/rtds2gpu.cpp @@ -10,8 +10,8 @@ #include #include +#include #include -#include using namespace villas::fpga::ip; diff --git a/fpga/lib/ips/zynq.cpp b/fpga/lib/ips/zynq.cpp index 72114dc19..db49d4428 100644 --- a/fpga/lib/ips/zynq.cpp +++ b/fpga/lib/ips/zynq.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include using namespace villas::fpga::ip; diff --git a/fpga/lib/memory.cpp b/fpga/lib/memory.cpp index a9f60d96b..10fe951a4 100644 --- a/fpga/lib/memory.cpp +++ b/fpga/lib/memory.cpp @@ -12,9 +12,10 @@ #include #include -#include +#include namespace villas { +namespace fpga { std::unique_ptr HostRam::HostRamAllocator::allocateBlock(size_t size) { @@ -262,4 +263,5 @@ HostDmaRam::HostDmaRamAllocator &HostDmaRam::getAllocator(int num) { return *allocator; } +} // namespace fpga } // namespace villas diff --git a/fpga/lib/memory_manager.cpp b/fpga/lib/memory_manager.cpp index 1ea8d6d25..f386cd2da 100644 --- a/fpga/lib/memory_manager.cpp +++ b/fpga/lib/memory_manager.cpp @@ -10,13 +10,14 @@ #include #include -#include +#include #include using namespace villas; using namespace villas::utils; namespace villas { +namespace fpga { MemoryManager *MemoryManager::instance = nullptr; @@ -247,4 +248,5 @@ void MemoryManager::printGraph() { } } +} // namespace fpga } // namespace villas diff --git a/fpga/lib/pcie_card.cpp b/fpga/lib/pcie_card.cpp index 8da4a6eaf..9caddba55 100644 --- a/fpga/lib/pcie_card.cpp +++ b/fpga/lib/pcie_card.cpp @@ -13,11 +13,11 @@ #include #include +#include +#include #include -#include +#include #include -#include -#include using namespace villas; using namespace villas::fpga; @@ -25,12 +25,12 @@ using namespace villas::fpga; // Instantiate factory to register static PCIeCardFactory PCIeCardFactoryInstance; -static const kernel::devices::PciDevice defaultFilter( - (kernel::devices::Id(FPGA_PCI_VID_XILINX, FPGA_PCI_PID_VFPGA))); +static const fpga::devices::PciDevice + defaultFilter((fpga::devices::Id(FPGA_PCI_VID_XILINX, FPGA_PCI_PID_VFPGA))); std::shared_ptr PCIeCardFactory::make(json_t *json_card, std::string card_name, - std::shared_ptr vc, + std::shared_ptr vc, const fs::path &searchPath) { auto logger = getStaticLogger(); @@ -74,16 +74,15 @@ PCIeCardFactory::make(json_t *json_card, std::string card_name, card->ignored_ip_names.push_back(json_string_value(value)); } - kernel::devices::PciDevice filter = defaultFilter; + devices::PciDevice filter = defaultFilter; if (pci_id) - filter.id = kernel::devices::Id(pci_id); + filter.id = devices::Id(pci_id); if (pci_slot) - filter.slot = kernel::devices::Slot(pci_slot); + filter.slot = devices::Slot(pci_slot); // Search for FPGA card - card->pdev = - kernel::devices::PciDeviceList::getInstance()->lookupDevice(filter); + card->pdev = devices::PciDeviceList::getInstance()->lookupDevice(filter); if (!card->pdev) { logger->warn("Failed to find PCI device"); return nullptr; diff --git a/fpga/lib/platform_card.cpp b/fpga/lib/platform_card.cpp index 7244c2abe..863fdd190 100644 --- a/fpga/lib/platform_card.cpp +++ b/fpga/lib/platform_card.cpp @@ -15,17 +15,16 @@ #include #include +#include #include #include -#include using namespace villas; using namespace villas::fpga; using namespace villas::kernel; -using namespace villas::kernel::devices; +using namespace villas::fpga::devices; -PlatformCard::PlatformCard( - std::shared_ptr vfioContainer) { +PlatformCard::PlatformCard(std::shared_ptr vfioContainer) { this->vfioContainer = vfioContainer; this->logger = villas::Log::get("PlatformCard"); } @@ -87,7 +86,7 @@ bool PlatformCard::mapMemoryBlock(const std::shared_ptr block) { std::shared_ptr PlatformCardFactory::make(json_t *json_card, std::string card_name, - std::shared_ptr vc, + std::shared_ptr vc, const fs::path &searchPath) { auto logger = villas::Log::get("PlatformCardFactory"); diff --git a/fpga/lib/utils.cpp b/fpga/lib/utils.cpp index 619f2e632..ae05b3f4d 100644 --- a/fpga/lib/utils.cpp +++ b/fpga/lib/utils.cpp @@ -233,7 +233,7 @@ void fpga::setupColorHandling() { std::shared_ptr fpga::createCard(json_t *config, const fs::path &searchPath, - std::shared_ptr vfioContainer, + std::shared_ptr vfioContainer, std::string card_name) { auto configDir = fs::path().parent_path(); @@ -264,10 +264,10 @@ fpga::createCard(json_t *config, const fs::path &searchPath, int fpga::createCards(json_t *config, std::list> &cards, const fs::path &searchPath, - std::shared_ptr vfioContainer) { + std::shared_ptr vfioContainer) { int numFpgas = 0; if (vfioContainer == nullptr) { - vfioContainer = std::make_shared(); + vfioContainer = std::make_shared(); } auto configDir = fs::path().parent_path(); @@ -293,7 +293,7 @@ int fpga::createCards(json_t *config, int fpga::createCards(json_t *config, std::list> &cards, const std::string &searchPath, - std::shared_ptr vfioContainer) { + std::shared_ptr vfioContainer) { const auto fsPath = fs::path(searchPath); return createCards(config, cards, fsPath, vfioContainer); } diff --git a/fpga/lib/kernel/vfio_container.cpp b/fpga/lib/vfio/container.cpp similarity index 99% rename from fpga/lib/kernel/vfio_container.cpp rename to fpga/lib/vfio/container.cpp index 989759dd9..968cc5c18 100644 --- a/fpga/lib/kernel/vfio_container.cpp +++ b/fpga/lib/vfio/container.cpp @@ -32,11 +32,11 @@ #include #include +#include #include -#include #include -using namespace villas::kernel::vfio; +using namespace villas::fpga::vfio; #ifndef VFIO_NOIOMMU_IOMMU #define VFIO_NOIOMMU_IOMMU 8 diff --git a/fpga/lib/kernel/vfio_device.cpp b/fpga/lib/vfio/device.cpp similarity index 98% rename from fpga/lib/kernel/vfio_device.cpp rename to fpga/lib/vfio/device.cpp index cc1680704..0aa4862dc 100644 --- a/fpga/lib/kernel/vfio_device.cpp +++ b/fpga/lib/vfio/device.cpp @@ -28,9 +28,9 @@ #include #include -#include +#include -using namespace villas::kernel::vfio; +using namespace villas::fpga::vfio; static const char *vfio_pci_region_names[] = { "PCI_BAR0", // VFIO_PCI_BAR0_REGION_INDEX @@ -53,7 +53,7 @@ static const char *vfio_pci_irq_names[] = { }; Device::Device(const std::string &name, int groupFileDescriptor, - const kernel::devices::PciDevice *pci_device) + const devices::PciDevice *pci_device) : name(name), fd(-1), attachedToGroup(false), groupFd(groupFileDescriptor), info(), info_irq_vectors(), regions(), mappings(), log(Log::get("kernel:vfio:device")) { diff --git a/fpga/lib/kernel/vfio_group.cpp b/fpga/lib/vfio/group.cpp similarity index 95% rename from fpga/lib/kernel/vfio_group.cpp rename to fpga/lib/vfio/group.cpp index e17ee4c67..8cb15404f 100644 --- a/fpga/lib/kernel/vfio_group.cpp +++ b/fpga/lib/vfio/group.cpp @@ -31,9 +31,9 @@ #include #include -#include +#include -using namespace villas::kernel::vfio; +using namespace villas::fpga::vfio; Group::Group(int index, bool iommuEnabled) : fd(-1), index(index), attachedToContainer(false), status(), devices(), @@ -67,7 +67,7 @@ std::shared_ptr Group::attachDevice(std::shared_ptr device) { std::shared_ptr Group::attachDevice(const std::string &name, - const kernel::devices::PciDevice *pci_device) { + const devices::PciDevice *pci_device) { auto device = std::make_shared(name, fd, pci_device); return attachDevice(device); } diff --git a/fpga/src/villas-fpga-ctrl.cpp b/fpga/src/villas-fpga-ctrl.cpp index 836cfe017..5af0b361b 100644 --- a/fpga/src/villas-fpga-ctrl.cpp +++ b/fpga/src/villas-fpga-ctrl.cpp @@ -33,14 +33,14 @@ using namespace villas; -static std::shared_ptr pciDevices; +static std::shared_ptr pciDevices; static auto logger = villas::Log::get("ctrl"); void writeToDmaFromStdIn(std::shared_ptr dma) { - auto &alloc = villas::HostRam::getAllocator(); - const std::shared_ptr block = + auto &alloc = villas::fpga::HostRam::getAllocator(); + const std::shared_ptr block = alloc.allocateBlock(0x200 * sizeof(float)); - villas::MemoryAccessor mem = *block; + villas::fpga::MemoryAccessor mem = *block; dma->makeAccesibleFromVA(block); logger->info("Please enter values to write to the device, separated by ';'"); @@ -74,12 +74,12 @@ void readFromDmaToStdOut( std::shared_ptr dma, std::unique_ptr formatter) { - auto &alloc = villas::HostRam::getAllocator(); + auto &alloc = villas::fpga::HostRam::getAllocator(); - const std::shared_ptr block[] = { + const std::shared_ptr block[] = { alloc.allocateBlock(0x200 * sizeof(uint32_t)), alloc.allocateBlock(0x200 * sizeof(uint32_t))}; - villas::MemoryAccessor mem[] = {*block[0], *block[1]}; + villas::fpga::MemoryAccessor mem[] = {*block[0], *block[1]}; for (auto b : block) { dma->makeAccesibleFromVA(b); @@ -167,7 +167,7 @@ int main(int argc, char *argv[]) { auto card = fpga::setupFpgaCard(configFile, fpgaName); if (dumpGraph) { - auto &mm = MemoryManager::get(); + auto &mm = fpga::MemoryManager::get(); mm.getGraph().dump("graph.dot"); } diff --git a/fpga/src/villas-fpga-pipe.cpp b/fpga/src/villas-fpga-pipe.cpp index 3aba1657a..6f0dc7bad 100644 --- a/fpga/src/villas-fpga-pipe.cpp +++ b/fpga/src/villas-fpga-pipe.cpp @@ -26,7 +26,7 @@ using namespace villas; -static std::shared_ptr pciDevices; +static std::shared_ptr pciDevices; static auto logger = villas::Log::get("streamer"); int main(int argc, char *argv[]) { @@ -87,16 +87,16 @@ int main(int argc, char *argv[]) { #else dma->connectLoopback(); #endif - auto &alloc = villas::HostRam::getAllocator(); - const std::shared_ptr block[] = { + auto &alloc = villas::fpga::HostRam::getAllocator(); + const std::shared_ptr block[] = { alloc.allocateBlock(0x200 * sizeof(uint32_t)), alloc.allocateBlock(0x200 * sizeof(uint32_t))}; - villas::MemoryAccessor mem[] = {*block[0], *block[1]}; + villas::fpga::MemoryAccessor mem[] = {*block[0], *block[1]}; for (auto b : block) { dma->makeAccesibleFromVA(b); } - auto &mm = MemoryManager::get(); + auto &mm = fpga::MemoryManager::get(); mm.getGraph().dump("graph.dot"); while (true) { diff --git a/fpga/tests/unit/dma.cpp b/fpga/tests/unit/dma.cpp index 6700266dd..f66ec077c 100644 --- a/fpga/tests/unit/dma.cpp +++ b/fpga/tests/unit/dma.cpp @@ -10,8 +10,8 @@ #include #include #include +#include #include -#include #include #include "global.hpp" @@ -48,8 +48,8 @@ Test(fpga, dma, .description = "DMA") { #if 0 // Allocate memory to use with DMA - auto src = HostDmaRam::getAllocator().allocate(len); - auto dst = HostDmaRam::getAllocator().allocate(len); + auto src = fpga::HostDmaRam::getAllocator().allocate(len); + auto dst = fpga::HostDmaRam::getAllocator().allocate(len); #elif 0 // ... only works with IOMMU enabled currently @@ -63,13 +63,13 @@ Test(fpga, dma, .description = "DMA") { auto dst = bram->getAllocator().allocate(len); #else // ... only works with IOMMU enabled currently - auto &alloc = villas::HostRam::getAllocator(); - const std::shared_ptr srcBlock = + auto &alloc = villas::fpga::HostRam::getAllocator(); + const std::shared_ptr srcBlock = alloc.allocateBlock(len); - const std::shared_ptr dstBlock = + const std::shared_ptr dstBlock = alloc.allocateBlock(len); - villas::MemoryAccessor src(*srcBlock); - villas::MemoryAccessor dst(*dstBlock); + villas::fpga::MemoryAccessor src(*srcBlock); + villas::fpga::MemoryAccessor dst(*dstBlock); #endif // Make sure memory is accessible for DMA dma->makeAccesibleFromVA(srcBlock); @@ -93,6 +93,6 @@ Test(fpga, dma, .description = "DMA") { cr_assert(count > 0, "No DMA found"); - MemoryManager::get().getGraph().dump(); + fpga::MemoryManager::get().getGraph().dump(); fpga::ip::Node::getGraph().dump(); } diff --git a/fpga/tests/unit/fpga.cpp b/fpga/tests/unit/fpga.cpp index d0a09445d..608c3b5be 100644 --- a/fpga/tests/unit/fpga.cpp +++ b/fpga/tests/unit/fpga.cpp @@ -26,7 +26,7 @@ using namespace villas; -static kernel::devices::PciDeviceList *pciDevices; +static fpga::devices::PciDeviceList *pciDevices; FpgaState state; @@ -39,9 +39,9 @@ static void init() { plugin::registry->dump(); - pciDevices = kernel::devices::PciDeviceList::getInstance(); + pciDevices = fpga::devices::PciDeviceList::getInstance(); - auto vfioContainer = std::make_shared(); + auto vfioContainer = std::make_shared(); // Parse FPGA configuration char *fn = getenv("TEST_CONFIG"); diff --git a/fpga/tests/unit/graph.cpp b/fpga/tests/unit/graph.cpp index 55d9c7551..a51ae76cd 100644 --- a/fpga/tests/unit/graph.cpp +++ b/fpga/tests/unit/graph.cpp @@ -9,9 +9,9 @@ #include -#include +#include +#include #include -#include using namespace villas; @@ -20,13 +20,13 @@ TestSuite(graph, .description = "Graph library"); Test(graph, basic, .description = "DirectedGraph") { Logger logger = Log::get("test:graph:basic"); - villas::graph::DirectedGraph<> g("test:graph:basic"); + villas::fpga::DirectedGraph<> g("test:graph:basic"); logger->info("Testing basic graph construction and modification"); - std::shared_ptr v1(new villas::graph::Vertex); - std::shared_ptr v2(new villas::graph::Vertex); - std::shared_ptr v3(new villas::graph::Vertex); + std::shared_ptr v1(new villas::fpga::Vertex); + std::shared_ptr v2(new villas::fpga::Vertex); + std::shared_ptr v3(new villas::fpga::Vertex); auto v1id = g.addVertex(v1); auto v2id = g.addVertex(v2); @@ -52,15 +52,15 @@ Test(graph, path, .description = "Find path") { Logger logger = Log::get("test:graph:path"); logger->info("Testing path finding algorithm"); - using Graph = villas::graph::DirectedGraph<>; + using Graph = villas::fpga::DirectedGraph<>; Graph g("test:graph:path"); - std::shared_ptr v1(new villas::graph::Vertex); - std::shared_ptr v2(new villas::graph::Vertex); - std::shared_ptr v3(new villas::graph::Vertex); - std::shared_ptr v4(new villas::graph::Vertex); - std::shared_ptr v5(new villas::graph::Vertex); - std::shared_ptr v6(new villas::graph::Vertex); + std::shared_ptr v1(new villas::fpga::Vertex); + std::shared_ptr v2(new villas::fpga::Vertex); + std::shared_ptr v3(new villas::fpga::Vertex); + std::shared_ptr v4(new villas::fpga::Vertex); + std::shared_ptr v5(new villas::fpga::Vertex); + std::shared_ptr v6(new villas::fpga::Vertex); auto v1id = g.addVertex(v1); auto v2id = g.addVertex(v2); @@ -111,7 +111,7 @@ Test(graph, path, .description = "Find path") { Test(graph, memory_manager, .description = "Global Memory Manager") { Logger logger = Log::get("test:graph:mm"); - auto &mm = villas::MemoryManager::get(); + auto &mm = villas::fpga::MemoryManager::get(); logger->info("Create address spaces"); auto dmaRegs = mm.getOrCreateAddressSpace("DMA Registers"); diff --git a/fpga/tests/unit/rtds.cpp b/fpga/tests/unit/rtds.cpp index c30c9401d..7d6bef10b 100644 --- a/fpga/tests/unit/rtds.cpp +++ b/fpga/tests/unit/rtds.cpp @@ -16,8 +16,8 @@ #include #include #include +#include #include -#include #include #include "global.hpp" @@ -66,7 +66,7 @@ Test(fpga, rtds, .description = "RTDS") { // rtds->connect(rtdsMaster, dmaSlave); // dma->connect(dmaMaster, rtdsSlave); - auto mem = villas::HostRam::getAllocator().allocate( + auto mem = villas::fpga::HostRam::getAllocator().allocate( 0x100 / sizeof(int32_t)); // auto start = std::chrono::high_resolution_clock::now(); diff --git a/include/villas/nodes/fpga.hpp b/include/villas/nodes/fpga.hpp index a17988b86..ccfd50f3d 100644 --- a/include/villas/nodes/fpga.hpp +++ b/include/villas/nodes/fpga.hpp @@ -62,12 +62,12 @@ class FpgaNode : public Node { // State std::shared_ptr card; std::shared_ptr dma; - std::shared_ptr blockRx; - std::shared_ptr> accessorRxInt; - std::shared_ptr> accessorRxFloat; - std::shared_ptr blockTx; - std::shared_ptr> accessorTxInt; - std::shared_ptr> accessorTxFloat; + std::shared_ptr blockRx; + std::shared_ptr> accessorRxInt; + std::shared_ptr> accessorRxFloat; + std::shared_ptr blockTx; + std::shared_ptr> accessorTxInt; + std::shared_ptr> accessorTxFloat; // Non-public methods int fastRead(Sample *smps[], unsigned cnt); diff --git a/lib/nodes/fpga.cpp b/lib/nodes/fpga.cpp index f9019a0e5..4d4a1a8f6 100644 --- a/lib/nodes/fpga.cpp +++ b/lib/nodes/fpga.cpp @@ -16,11 +16,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -34,7 +34,7 @@ using namespace villas::utils; // Global state static std::list> cards; -static std::shared_ptr vfioContainer; +static std::shared_ptr vfioContainer; FpgaNode::FpgaNode(const uuid_t &id, const std::string &name) : Node(id, name), cardName(""), connectStrings(), lowLatencyMode(false), @@ -124,7 +124,7 @@ int FpgaNode::parse(json_t *json) { json_t *jsonConnectStrings = nullptr; if (vfioContainer == nullptr) { - vfioContainer = std::make_shared(); + vfioContainer = std::make_shared(); } ret = json_unpack_ex(json, &err, 0, "{ s: o, s?: o, s?: b, s?: F}", "card", @@ -378,7 +378,7 @@ std::vector FpgaNode::getPollFDs() { int FpgaNodeFactory::start(SuperNode *sn) { if (vfioContainer == nullptr) { - vfioContainer = std::make_shared(); + vfioContainer = std::make_shared(); } if (cards.empty()) { From 726f668c779ef59a0dbf4b16d9c8e67a4ac4940b Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 20:20:05 +0100 Subject: [PATCH 06/10] fix(exceptions): Remove outdated exceptions header Signed-off-by: Philipp Jungkamp --- clients/shmem/villas-shmem.cpp | 2 +- include/villas/node/exceptions.hpp | 41 ------------------------------ lib/api/requests/restart.cpp | 2 +- lib/hook.cpp | 2 +- lib/hooks/average.cpp | 2 +- lib/hooks/limit_value.cpp | 2 +- lib/hooks/stats.cpp | 2 +- lib/nodes/exec.cpp | 2 +- lib/super_node.cpp | 1 - lib/web.cpp | 2 +- src/villas-hook.cpp | 21 ++++++++------- 11 files changed, 20 insertions(+), 59 deletions(-) delete mode 100644 include/villas/node/exceptions.hpp diff --git a/clients/shmem/villas-shmem.cpp b/clients/shmem/villas-shmem.cpp index f76ca4c3d..cf93571e6 100644 --- a/clients/shmem/villas-shmem.cpp +++ b/clients/shmem/villas-shmem.cpp @@ -12,10 +12,10 @@ #include #include +#include #include #include #include -#include #include #include #include diff --git a/include/villas/node/exceptions.hpp b/include/villas/node/exceptions.hpp deleted file mode 100644 index 5990fa55c..000000000 --- a/include/villas/node/exceptions.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/* VILLASnode exceptions. - * - * Author: Steffen Vogel - * SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include -#include - -namespace villas { -namespace node { - -class ParseError : public RuntimeError { - -protected: - std::string text; - std::string file; - int line; - int column; - -public: - ParseError(const std::string &t, const std::string &f, int l, int c = 0) - : RuntimeError("Failed to parse configuration: {} in {}:{}", t, f, l), - text(t), file(f), line(l), column(c) {} -}; - -class JanssonParseError : public ParseError { - -protected: - json_error_t error; - -public: - JanssonParseError(json_error_t e) - : ParseError(e.text, e.source, e.line, e.column), error(e) {} -}; - -} // namespace node -} // namespace villas diff --git a/lib/api/requests/restart.cpp b/lib/api/requests/restart.cpp index ccb923287..c249107ac 100644 --- a/lib/api/requests/restart.cpp +++ b/lib/api/requests/restart.cpp @@ -8,8 +8,8 @@ #include #include #include +#include #include -#include #include #include diff --git a/lib/hook.cpp b/lib/hook.cpp index 9ad51a84b..ad693ee1c 100644 --- a/lib/hook.cpp +++ b/lib/hook.cpp @@ -7,10 +7,10 @@ #include +#include #include #include #include -#include #include #include #include diff --git a/lib/hooks/average.cpp b/lib/hooks/average.cpp index 6b1777dbd..4894e0513 100644 --- a/lib/hooks/average.cpp +++ b/lib/hooks/average.cpp @@ -5,8 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include #include -#include #include #include diff --git a/lib/hooks/limit_value.cpp b/lib/hooks/limit_value.cpp index 1491abb42..d3f47ced2 100644 --- a/lib/hooks/limit_value.cpp +++ b/lib/hooks/limit_value.cpp @@ -5,8 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include #include -#include #include #include diff --git a/lib/hooks/stats.cpp b/lib/hooks/stats.cpp index 9e33de2ba..69ecc70ae 100644 --- a/lib/hooks/stats.cpp +++ b/lib/hooks/stats.cpp @@ -8,9 +8,9 @@ #include #include +#include #include #include -#include #include #include diff --git a/lib/nodes/exec.cpp b/lib/nodes/exec.cpp index 908d10c96..f82e090df 100644 --- a/lib/nodes/exec.cpp +++ b/lib/nodes/exec.cpp @@ -9,9 +9,9 @@ #include +#include #include #include -#include #include #include diff --git a/lib/super_node.cpp b/lib/super_node.cpp index b8a6cb181..56f3b70ed 100644 --- a/lib/super_node.cpp +++ b/lib/super_node.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include diff --git a/lib/web.cpp b/lib/web.cpp index 97c2df2dc..a66d401cf 100644 --- a/lib/web.cpp +++ b/lib/web.cpp @@ -10,8 +10,8 @@ #include #include #include +#include #include -#include #include #include #include diff --git a/src/villas-hook.cpp b/src/villas-hook.cpp index 79e743036..787edf86a 100644 --- a/src/villas-hook.cpp +++ b/src/villas-hook.cpp @@ -15,10 +15,11 @@ #include #include #include +#include +#include #include #include #include -#include #include #include #include @@ -79,8 +80,8 @@ class Hook : public Tool { << std::endl << " OPTIONS is one or more of the following options:" << std::endl - << " -c CONFIG a JSON file containing just the hook " - "configuration" + << " -c CONFIG a JSON or libconfig file containing just " + "the hook configuration" << std::endl << " -f FMT the input data format" << std::endl << " -F FMT the output data format (defaults to " @@ -174,12 +175,14 @@ class Hook : public Tool { output_format = input_format; if (!file.empty()) { - json_error_t err; - json_t *j = json_load_file(file.c_str(), 0, &err); - if (!j) - throw JanssonParseError(err); - - json_object_update_missing(config, j); + JanssonPtr j = load_config_file(file, { + .allow_libconfig = true, + .allow_environment = true, + .allow_include = true, + .allow_comments = true, + }); + + json_object_update_missing_new(config, j.release()); } if (argc < optind + 1) { From 814f4e32066c2a6810e5278b23e89f1284bacf6f Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Tue, 24 Nov 2026 21:04:49 +0100 Subject: [PATCH 07/10] fix(tests): Use /usr/bin/env instead of /bin/bash Signed-off-by: Philipp Jungkamp --- tests/integration/CMakeLists.txt | 2 +- tests/unit/CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/integration/CMakeLists.txt b/tests/integration/CMakeLists.txt index e7be67e0b..17c88666b 100644 --- a/tests/integration/CMakeLists.txt +++ b/tests/integration/CMakeLists.txt @@ -6,7 +6,7 @@ add_custom_target(run-integration-tests COMMAND - /bin/bash -o pipefail -c \" + /usr/bin/env bash -o pipefail -c \" SRCDIR=${PROJECT_SOURCE_DIR} BUILDDIR=${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR}/tools/integration-tests.sh 2>&1 | c++filt\" diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 16e9b035e..c0ea8fa62 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -42,7 +42,7 @@ target_link_libraries(unit-tests PUBLIC add_custom_target(run-unit-tests COMMAND - /bin/bash -o pipefail -c \" + /usr/bin/env bash -o pipefail -c \" $ 2>&1 | c++filt\" DEPENDS unit-tests From ac229768cd4ec19da96ed5654d16f9f9450e742d Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 25 Nov 2026 02:07:52 +0100 Subject: [PATCH 08/10] fix(tests): Fix queue unit tests - Running for `1 << 16` iterations takes about 40s on my machine which exceeds the default timeout of 20s imposed by criterion. - Criterion can't reliably pass pointers as parameters to parameterized tests because these are passed through shared memory to a new process. A PIE executable can not use pointers from the test parameters because of ASLR. Signed-off-by: Philipp Jungkamp --- tests/unit/pool.cpp | 29 ++++++++++++++++++++++------- tests/unit/queue.cpp | 41 ++++++++++++++++++++++++++--------------- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/tests/unit/pool.cpp b/tests/unit/pool.cpp index 1f5835d7d..a04f0e088 100644 --- a/tests/unit/pool.cpp +++ b/tests/unit/pool.cpp @@ -25,17 +25,32 @@ struct param { int thread_count; int pool_size; size_t block_size; - struct memory::Type *mt; + // Criterion builds the parameters and runs the test in different processes. + // In a PIE binary, addresses of static objects like memory::heap differ. + enum class MemoryType { HEAP, MMAP, MMAP_HUGETLB } mt; }; +static struct memory::Type *memory_type(param::MemoryType mt) { + switch (mt) { + case param::MemoryType::HEAP: + return &memory::heap; + case param::MemoryType::MMAP: + return &memory::mmap; + case param::MemoryType::MMAP_HUGETLB: + return &memory::mmap_hugetlb; + } + + return nullptr; +} + ParameterizedTestParameters(pool, basic) { static std::vector params; params.clear(); - params.push_back({1, 4096, 150, &memory::heap}); - params.push_back({1, 128, 8, &memory::mmap}); - params.push_back({1, 4, 8192, &memory::mmap_hugetlb}); - params.push_back({1, 1 << 13, 4, &memory::mmap_hugetlb}); + params.push_back({1, 4096, 150, param::MemoryType::HEAP}); + params.push_back({1, 128, 8, param::MemoryType::MMAP}); + params.push_back({1, 4, 8192, param::MemoryType::MMAP_HUGETLB}); + params.push_back({1, 1 << 13, 4, param::MemoryType::MMAP_HUGETLB}); return cr_make_param_array(struct param, params.data(), params.size()); } @@ -48,11 +63,11 @@ ParameterizedTest(struct param *p, pool, basic, .init = init_memory) { Log::getInstance().setLevel("trace"); - if (!utils::isPrivileged() && p->mt == &memory::mmap_hugetlb) + if (!utils::isPrivileged() && p->mt == param::MemoryType::MMAP_HUGETLB) cr_skip_test("Skipping memory_mmap_hugetlb tests allocatpr because we are " "running in an unprivileged environment."); - ret = pool_init(&pool, p->pool_size, p->block_size, p->mt); + ret = pool_init(&pool, p->pool_size, p->block_size, memory_type(p->mt)); cr_assert_eq(ret, 0, "Failed to create pool"); ptr = pool_get(&pool); diff --git a/tests/unit/queue.cpp b/tests/unit/queue.cpp index daca7a464..6bf9ae438 100644 --- a/tests/unit/queue.cpp +++ b/tests/unit/queue.cpp @@ -26,10 +26,6 @@ using namespace villas::node; extern void init_memory(); -#define SIZE (1 << 10) - -static struct CQueue q; - #if defined(_POSIX_BARRIERS) && _POSIX_BARRIERS > 0 static pthread_barrier_t barrier; #endif @@ -40,11 +36,26 @@ struct param { int thread_count; bool many; int batch_size; - struct memory::Type *mt; + // Criterion builds the parameters and runs the test in different processes. + // In a PIE binary, addresses of static objects like memory::heap differ. + enum class MemoryType { HEAP, MMAP, MMAP_HUGETLB } mt; volatile int start; struct CQueue queue; }; +static struct memory::Type *memory_type(param::MemoryType mt) { + switch (mt) { + case param::MemoryType::HEAP: + return &memory::heap; + case param::MemoryType::MMAP: + return &memory::mmap; + case param::MemoryType::MMAP_HUGETLB: + return &memory::mmap_hugetlb; + } + + return nullptr; +} + /* Get thread id as integer * In contrast to pthread_t which is an opaque type */ #ifdef __linux__ @@ -220,7 +231,7 @@ Test(queue, single_threaded, .init = init_memory) { producer(&p); consumer(&p); - cr_assert_eq(queue_available(&q), 0); + cr_assert_eq(queue_available(&p.queue), 0); ret = queue_destroy(&p.queue); cr_assert_eq(ret, 0, "Failed to create queue"); @@ -234,31 +245,31 @@ ParameterizedTestParameters(queue, multi_threaded) { .thread_count = 32, .many = true, .batch_size = 10, - .mt = &memory::heap}, + .mt = param::MemoryType::HEAP}, {.iter_count = 1 << 8, .queue_size = 1 << 9, .thread_count = 4, .many = true, .batch_size = 100, - .mt = &memory::heap}, - {.iter_count = 1 << 16, + .mt = param::MemoryType::HEAP}, + {.iter_count = 1 << 12, .queue_size = 1 << 14, .thread_count = 16, .many = true, .batch_size = 100, - .mt = &memory::heap}, + .mt = param::MemoryType::HEAP}, {.iter_count = 1 << 8, .queue_size = 1 << 9, .thread_count = 4, .many = true, .batch_size = 10, - .mt = &memory::heap}, + .mt = param::MemoryType::HEAP}, {.iter_count = 1 << 16, .queue_size = 1 << 9, .thread_count = 16, .many = false, .batch_size = 10, - .mt = &memory::mmap_hugetlb}}; + .mt = param::MemoryType::MMAP_HUGETLB}}; return cr_make_param_array(struct param, params, std::size(params)); } @@ -271,7 +282,7 @@ ParameterizedTest(struct param *p, queue, multi_threaded, .timeout = 20, Logger logger = Log::get("test:queue:multi_threaded"); - if (!utils::isPrivileged() && p->mt == &memory::mmap_hugetlb) + if (!utils::isPrivileged() && p->mt == param::MemoryType::MMAP_HUGETLB) cr_skip_test("Skipping memory_mmap_hugetlb tests allocatpr because we are " "running in an unprivileged environment."); @@ -279,7 +290,7 @@ ParameterizedTest(struct param *p, queue, multi_threaded, .timeout = 20, p->start = 0; - ret = queue_init(&p->queue, p->queue_size, p->mt); + ret = queue_init(&p->queue, p->queue_size, memory_type(p->mt)); cr_assert_eq(ret, 0, "Failed to create queue"); uint64_t start_tsc_time, end_tsc_time; @@ -311,7 +322,7 @@ ParameterizedTest(struct param *p, queue, multi_threaded, .timeout = 20, "Cycles/op are very high ({}). Are you running on a hypervisor?", cycpop); - ret = queue_available(&q); + ret = queue_available(&p->queue); cr_assert_eq(ret, 0); ret = queue_destroy(&p->queue); From 8ceef3182c0fd868158f6f6962b3269911bb3495 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 25 Nov 2026 02:08:35 +0100 Subject: [PATCH 09/10] fix(tests): Use /usr/bin/env for popen tests for NixOS Signed-off-by: Philipp Jungkamp --- tests/unit/popen.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/popen.cpp b/tests/unit/popen.cpp index 08488a5a7..7e2fd3044 100644 --- a/tests/unit/popen.cpp +++ b/tests/unit/popen.cpp @@ -17,7 +17,7 @@ using namespace villas::utils; TestSuite(popen, .description = "Bi-directional popen"); Test(popen, no_shell) { - PopenStream proc("/usr/bin/tee", {"tee", "test"}); + PopenStream proc("/usr/bin/env", {"env", "tee", "test"}); proc.cout() << "Hello World" << std::endl; proc.cout().flush(); @@ -50,13 +50,13 @@ Test(popen, shell) { } Test(popen, wd) { - PopenStream proc("/usr/bin/pwd", {"pwd"}, {}, "/usr/lib"); + PopenStream proc("/usr/bin/env", {"env", "pwd"}, {}, "/usr/bin"); std::string wd; proc.cin() >> wd; - cr_assert_eq(wd, "/usr/lib"); + cr_assert_eq(wd, "/usr/bin"); proc.kill(); proc.close(); From 0f65aad549bdd40acdc455435a90e74ccba11d0e Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Wed, 25 Nov 2026 02:10:31 +0100 Subject: [PATCH 10/10] fix(node): Replace ConfigError with JsonError Signed-off-by: Philipp Jungkamp --- fpga/include/villas/fpga/card_parser.hpp | 4 +- fpga/lib/card.cpp | 37 ++++++------ fpga/lib/core.cpp | 15 +++-- fpga/lib/ips/bram.cpp | 3 +- fpga/lib/ips/dino.cpp | 6 +- fpga/lib/ips/dma.cpp | 4 +- fpga/lib/ips/i2c.cpp | 6 +- fpga/lib/ips/pcie.cpp | 13 +++-- fpga/lib/ips/switch.cpp | 4 +- fpga/lib/node.cpp | 16 ++++-- fpga/lib/pcie_card.cpp | 10 +++- fpga/lib/platform_card.cpp | 9 ++- fpga/lib/utils.cpp | 6 +- include/villas/config_helper.hpp | 9 +-- include/villas/exceptions.hpp | 67 ---------------------- include/villas/jansson.hpp | 3 +- include/villas/json.hpp | 73 ++++++++++++++++++++++++ include/villas/node/json_schema.hpp | 61 -------------------- lib/format.cpp | 13 +++-- lib/formats/column.cpp | 9 +-- lib/formats/json.cpp | 9 +-- lib/formats/json_kafka.cpp | 9 +-- lib/formats/line.cpp | 13 +++-- lib/formats/opal_asyncip.cpp | 5 +- lib/formats/raw.cpp | 12 ++-- lib/formats/villas_binary.cpp | 5 +- lib/hook.cpp | 26 ++++----- lib/hook_list.cpp | 22 +++---- lib/hooks/average.cpp | 3 +- lib/hooks/cast.cpp | 3 +- lib/hooks/decimate.cpp | 3 +- lib/hooks/digest.cpp | 3 +- lib/hooks/dp.cpp | 20 +++---- lib/hooks/ebm.cpp | 8 ++- lib/hooks/frame.cpp | 15 +++-- lib/hooks/gate.cpp | 3 +- lib/hooks/limit_rate.cpp | 7 ++- lib/hooks/limit_value.cpp | 3 +- lib/hooks/lua.cpp | 19 +++--- lib/hooks/ma.cpp | 3 +- lib/hooks/pmu.cpp | 37 ++++++------ lib/hooks/pmu_dft.cpp | 19 +++--- lib/hooks/pmu_ipdft.cpp | 7 ++- lib/hooks/power.cpp | 21 +++---- lib/hooks/pps_ts.cpp | 3 +- lib/hooks/print.cpp | 17 +++--- lib/hooks/reorder_ts.cpp | 3 +- lib/hooks/rms.cpp | 9 +-- lib/hooks/round.cpp | 3 +- lib/hooks/scale.cpp | 3 +- lib/hooks/shift_seq.cpp | 3 +- lib/hooks/shift_ts.cpp | 6 +- lib/hooks/skip_first.cpp | 3 +- lib/hooks/stats.cpp | 7 ++- lib/kernel/tc_netem.cpp | 46 ++++++++------- lib/log.cpp | 5 +- lib/node.cpp | 23 +++++--- lib/node_direction.cpp | 9 ++- lib/nodes/amqp.cpp | 20 ++++--- lib/nodes/can.cpp | 37 ++++++------ lib/nodes/comedi.cpp | 22 ++++--- lib/nodes/ethercat.cpp | 5 +- lib/nodes/example.cpp | 3 +- lib/nodes/exec.cpp | 33 ++++++----- lib/nodes/file.cpp | 13 +++-- lib/nodes/fpga.cpp | 24 ++++---- lib/nodes/iec60870.cpp | 13 +++-- lib/nodes/iec61850_goose.cpp | 49 ++++++++++------ lib/nodes/iec61850_sv.cpp | 30 +++++----- lib/nodes/infiniband.cpp | 10 ++-- lib/nodes/influxdb.cpp | 3 +- lib/nodes/kafka.cpp | 33 ++++++----- lib/nodes/loopback.cpp | 6 +- lib/nodes/modbus.cpp | 24 +++++--- lib/nodes/mqtt.cpp | 33 ++++++----- lib/nodes/nanomsg.cpp | 13 +++-- lib/nodes/ngsi.cpp | 41 +++++++------ lib/nodes/opal_async.cpp | 3 +- lib/nodes/opal_orchestra.cpp | 39 ++++++++----- lib/nodes/opal_orchestra/ddf.cpp | 26 +++++---- lib/nodes/opendss.cpp | 23 ++++---- lib/nodes/redis.cpp | 26 +++++---- lib/nodes/rtp.cpp | 15 +++-- lib/nodes/shmem.cpp | 3 +- lib/nodes/signal.cpp | 13 +++-- lib/nodes/signal_v1.cpp | 26 ++++----- lib/nodes/socket.cpp | 18 +++--- lib/nodes/stats.cpp | 25 ++++---- lib/nodes/temper.cpp | 3 +- lib/nodes/test_rtt.cpp | 60 +++++++++++-------- lib/nodes/uldaq.cpp | 35 ++++++------ lib/nodes/webrtc.cpp | 19 +++--- lib/nodes/websocket.cpp | 24 ++++---- lib/nodes/zeromq.cpp | 53 +++++++++-------- lib/path.cpp | 44 +++++++------- lib/super_node.cpp | 42 ++++++++------ lib/tool.cpp | 6 ++ lib/web.cpp | 3 +- 98 files changed, 933 insertions(+), 768 deletions(-) diff --git a/fpga/include/villas/fpga/card_parser.hpp b/fpga/include/villas/fpga/card_parser.hpp index cef55c744..9a7d7da85 100644 --- a/fpga/include/villas/fpga/card_parser.hpp +++ b/fpga/include/villas/fpga/card_parser.hpp @@ -15,6 +15,7 @@ #include #include +#include #include class CardParser { @@ -49,6 +50,7 @@ class CardParser { } if (ret != 0) - throw villas::ConfigError(json_card, err, "", "Failed to parse card"); + throw villas::JsonError(""_json_pointer, "Failed to parse card: {}", + err.text); } }; diff --git a/fpga/lib/card.cpp b/fpga/lib/card.cpp index 91d6e9c4d..4ab0b9ac5 100644 --- a/fpga/lib/card.cpp +++ b/fpga/lib/card.cpp @@ -11,6 +11,7 @@ #include #include #include +#include using namespace villas; using namespace villas::fpga; @@ -135,8 +136,8 @@ void CardFactory::loadIps(std::shared_ptr card, json_t *json_ips, // Load IPs from a separate json file if (!json_is_string(json_ips)) { logger->debug("FPGA IP cores config item is not a string."); - throw ConfigError(json_ips, "node-config-fpga-ips", - "FPGA IP cores config item is not a string."); + throw JsonError(""_json_pointer, + "FPGA IP cores config item is not a string."); } if (!searchPath.empty()) { @@ -153,20 +154,18 @@ void CardFactory::loadIps(std::shared_ptr card, json_t *json_ips, logger->debug("searching for FPGA IP cors config at {}", json_string_value(json_ips)); if (json_ips == nullptr) { - throw ConfigError(json_ips, "node-config-fpga-ips", - "Failed to find FPGA IP cores config"); + throw JsonError(""_json_pointer, "Failed to find FPGA IP cores config"); } } if (not json_is_object(json_ips)) - throw ConfigError(json_ips, "node-config-fpga-ips", - "FPGA IP core list must be an object!"); + throw JsonError(""_json_pointer, "FPGA IP core list must be an object!"); ip::CoreFactory::make(card.get(), json_ips); if (card->ips.empty()) - throw ConfigError(json_ips, "node-config-fpga-ips", - "Cannot initialize IPs of FPGA card {}", card->name); + throw JsonError(""_json_pointer, "Cannot initialize IPs of FPGA card {}", + card->name); }; void CardFactory::loadSwitch(std::shared_ptr card, json_t *json_paths) { @@ -174,8 +173,8 @@ void CardFactory::loadSwitch(std::shared_ptr card, json_t *json_paths) { json_error_t err; if (json_paths != nullptr) { if (not json_is_array(json_paths)) - throw ConfigError(json_paths, err, "", - "Switch path configuration must be an array"); + throw JsonError(""_json_pointer, + "Switch path configuration must be an array"); size_t i; json_t *json_path; @@ -186,28 +185,30 @@ void CardFactory::loadSwitch(std::shared_ptr card, json_t *json_paths) { int ret = json_unpack_ex(json_path, &err, 0, "{ s: s, s: s, s?: b }", "from", &from, "to", &to, "reverse", &reverse); if (ret != 0) - throw ConfigError(json_path, err, "", - "Cannot parse switch path config"); + throw JsonError(""_json_pointer / i, + "Cannot parse switch path config: {}", err.text); auto masterIpCore = card->lookupIp(from); if (!masterIpCore) - throw ConfigError(json_path, "", "Unknown IP {}", from); + throw JsonError(""_json_pointer / i, "Unknown IP {}", from); auto slaveIpCore = card->lookupIp(to); if (!slaveIpCore) - throw ConfigError(json_path, "", "Unknown IP {}", to); + throw JsonError(""_json_pointer / i, "Unknown IP {}", to); auto masterIpNode = std::dynamic_pointer_cast(masterIpCore); if (!masterIpNode) - throw ConfigError(json_path, "", "IP {} is not a streaming node", from); + throw JsonError(""_json_pointer / i, "IP {} is not a streaming node", + from); auto slaveIpNode = std::dynamic_pointer_cast(slaveIpCore); if (!slaveIpNode) - throw ConfigError(json_path, "", "IP {} is not a streaming node", to); + throw JsonError(""_json_pointer / i, "IP {} is not a streaming node", + to); if (not masterIpNode->connect(*slaveIpNode, reverse != 0)) - throw ConfigError(json_path, "", "Failed to connect node {} to {}", - from, to); + throw JsonError(""_json_pointer / i, "Failed to connect node {} to {}", + from, to); } } } diff --git a/fpga/lib/core.cpp b/fpga/lib/core.cpp index 5186883e9..3c18dd1d1 100644 --- a/fpga/lib/core.cpp +++ b/fpga/lib/core.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -50,7 +51,8 @@ std::list CoreFactory::parseIpIdentifier(json_t *json_ips) { json_error_t err; int ret = json_unpack_ex(json_ip, &err, 0, "{ s: s }", "vlnv", &vlnv); if (ret != 0) - throw ConfigError(json_ip, err, "", "IP {} has no VLNV", ipName); + throw JsonError(""_json_pointer / ipName, "IP {} has no VLNV: {}", ipName, + err.text); allIps.push_back({vlnv, ipName}); } @@ -251,9 +253,11 @@ CoreFactory::configureIps(std::list orderedIps, json_t *json_ips, "{ s: I, s: I, s: I }", "baseaddr", &base, "highaddr", &high, "size", &size); if (ret != 0) - throw ConfigError( - json_block, err, "", "Cannot parse address block {}/{}/{}/{}", - ip->getInstanceName(), bus_name, instance_name, block_name); + throw JsonError(""_json_pointer / id.getName() / "memory-view" / + bus_name / instance_name / block_name, + "Cannot parse address block {}/{}/{}/{}: {}", + ip->getInstanceName(), bus_name, instance_name, + block_name, err.text); // Get or create the slave address space const std::string slaveAddrSpace = @@ -272,7 +276,8 @@ CoreFactory::configureIps(std::list orderedIps, json_t *json_ips, } // IP-specific setup via JSON config - f->parse(*ip, json_ip); + JsonError::context(""_json_pointer / id.getName(), + [&] { return f->parse(*ip, json_ip); }); // Set polling mode f->configurePollingMode( diff --git a/fpga/lib/ips/bram.cpp b/fpga/lib/ips/bram.cpp index 4f2032542..03587708c 100644 --- a/fpga/lib/ips/bram.cpp +++ b/fpga/lib/ips/bram.cpp @@ -7,6 +7,7 @@ #include #include +#include using namespace villas; using namespace villas::fpga::ip; @@ -19,7 +20,7 @@ void BramFactory::parse(Core &ip, json_t *cfg) { json_error_t err; int ret = json_unpack_ex(cfg, &err, 0, "{ s: i }", "size", &bram.size); if (ret != 0) - throw ConfigError(cfg, err, "", "Cannot parse BRAM config"); + throw JsonError(""_json_pointer, "Cannot parse BRAM config: {}", err.text); } bool Bram::init() { diff --git a/fpga/lib/ips/dino.cpp b/fpga/lib/ips/dino.cpp index a3df87124..520ffa5fd 100644 --- a/fpga/lib/ips/dino.cpp +++ b/fpga/lib/ips/dino.cpp @@ -9,6 +9,7 @@ #include #include +#include #include using namespace villas::fpga::ip; @@ -271,10 +272,11 @@ void DinoFactory::parse(Core &ip, json_t *cfg) { int ret = json_unpack_ex(cfg, &err, 0, "{ s: i }", "i2c_channel", &i2c_channel); if (ret != 0) { - throw ConfigError(cfg, err, "", "Failed to parse Dino configuration"); + throw JsonError(""_json_pointer, "Failed to parse Dino configuration: {}", + err.text); } if (i2c_channel < 0 || i2c_channel >= 8) { - throw ConfigError(cfg, err, "", "Invalid I2C channel"); + throw JsonError("/i2c_channel"_json_pointer, "Invalid I2C channel"); } dino.i2c_channel = static_cast(i2c_channel); diff --git a/fpga/lib/ips/dma.cpp b/fpga/lib/ips/dma.cpp index f5eb7d3db..c378eb298 100644 --- a/fpga/lib/ips/dma.cpp +++ b/fpga/lib/ips/dma.cpp @@ -18,6 +18,7 @@ #include #include #include +#include // Max. size of a DMA transfer in simple mode #define FPGA_DMA_BOUNDARY 0x1000 @@ -937,7 +938,8 @@ void DmaFactory::parse(Core &ip, json_t *cfg) { &dma.xConfig.MicroDmaMode, "c_addr_width", &dma.xConfig.AddrWidth, "c_sg_length_width", &dma.xConfig.SgLengthWidth); if (ret != 0) - throw ConfigError(cfg, err, "", "Failed to parse DMA configuration"); + throw JsonError(""_json_pointer, "Failed to parse DMA configuration: {}", + err.text); dma.configDone = true; } diff --git a/fpga/lib/ips/i2c.cpp b/fpga/lib/ips/i2c.cpp index 75ec4dbe3..7eef7bfb6 100644 --- a/fpga/lib/ips/i2c.cpp +++ b/fpga/lib/ips/i2c.cpp @@ -12,6 +12,7 @@ #include #include +#include #include using namespace villas::fpga::ip; @@ -323,8 +324,9 @@ void I2cFactory::parse(Core &ip, json_t *cfg) { "c_gpo_width", &i2c.xConfig.GpOutWidth, "component_name", &component_name); if (ret != 0) { - throw ConfigError(cfg, err, "", "Failed to parse DMA configuration for {}", - ip.getInstanceName()); + throw JsonError(""_json_pointer, + "Failed to parse DMA configuration for {}: {}", + ip.getInstanceName(), err.text); } if (component_name != nullptr) { char last_letter = component_name[strlen(component_name) - 1]; diff --git a/fpga/lib/ips/pcie.cpp b/fpga/lib/ips/pcie.cpp index f50ae5c3d..eaf7eb08e 100644 --- a/fpga/lib/ips/pcie.cpp +++ b/fpga/lib/ips/pcie.cpp @@ -14,6 +14,7 @@ #include #include #include +#include using namespace villas::fpga::ip; @@ -107,7 +108,8 @@ void AxiPciExpressBridgeFactory::parse(Core &ip, json_t *cfg) { for (auto barType : std::list{"axi_bars", "pcie_bars"}) { json_t *json_bars = json_object_get(cfg, barType.c_str()); if (not json_is_object(json_bars)) - throw ConfigError(cfg, "", "Missing BAR config: {}", barType); + throw JsonError(""_json_pointer / barType, "Missing BAR config: {}", + barType); json_t *json_bar; const char *bar_name; @@ -118,8 +120,8 @@ void AxiPciExpressBridgeFactory::parse(Core &ip, json_t *cfg) { int ret = json_unpack_ex(json_bar, &err, 0, "{ s: i }", "translation", &translation); if (ret != 0) - throw ConfigError(json_bar, err, "", "Cannot parse {}/{}", barType, - bar_name); + throw JsonError(""_json_pointer / barType / bar_name, + "Cannot parse {}/{}: {}", barType, bar_name, err.text); if (barType == "axi_bars") { json_int_t base, high, size; @@ -127,8 +129,9 @@ void AxiPciExpressBridgeFactory::parse(Core &ip, json_t *cfg) { json_unpack_ex(json_bar, &err, 0, "{ s: I, s: I, s: I }", "baseaddr", &base, "highaddr", &high, "size", &size); if (ret != 0) - throw ConfigError(json_bar, err, "", "Cannot parse {}/{}", barType, - bar_name); + throw JsonError(""_json_pointer / barType / bar_name, + "Cannot parse {}/{}: {}", barType, bar_name, + err.text); pcie.axiToPcieTranslations[bar_name] = { .base = static_cast(base), diff --git a/fpga/lib/ips/switch.cpp b/fpga/lib/ips/switch.cpp index 6f8e232ab..5539f20d7 100644 --- a/fpga/lib/ips/switch.cpp +++ b/fpga/lib/ips/switch.cpp @@ -13,6 +13,7 @@ #include #include +#include namespace villas { namespace fpga { @@ -146,7 +147,8 @@ void AxiStreamSwitchFactory::parse(Core &ip, json_t *cfg) { auto ret = json_unpack_ex(cfg, &err, 0, "{ s: { s: i, s: i } }", "parameters", "num_si", &num_si, "num_mi", &num_mi); if (ret != 0) - throw ConfigError(cfg, err, "", "Cannot parse switch config"); + throw JsonError(""_json_pointer, "Cannot parse switch config: {}", + err.text); axiSwitch.xConfig.MaxNumMI = num_mi; axiSwitch.xConfig.MaxNumSI = num_si; diff --git a/fpga/lib/node.cpp b/fpga/lib/node.cpp index 2ee211249..3a6428927 100644 --- a/fpga/lib/node.cpp +++ b/fpga/lib/node.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include using namespace villas::fpga::ip; @@ -32,7 +33,8 @@ void NodeFactory::parse(Core &ip, json_t *cfg) { json_t *json_port; json_array_foreach (json_ports, index, json_port) { if (not json_is_object(json_port)) - throw ConfigError(json_port, "", "Port {} is not an object", index); + throw JsonError("/ports"_json_pointer / index, + "Port {} is not an object", index); const char *role_raw, *target_raw, *name_raw; @@ -41,12 +43,13 @@ void NodeFactory::parse(Core &ip, json_t *cfg) { json_unpack_ex(json_port, &err, 0, "{ s: s, s: s, s: s }", "role", &role_raw, "target", &target_raw, "name", &name_raw); if (ret != 0) - throw ConfigError(json_port, err, "", "Cannot parse port {}", index); + throw JsonError("/ports"_json_pointer / index, + "Cannot parse port {}: {}", index, err.text); const auto tokens = utils::tokenize(target_raw, ":"); if (tokens.size() != 2) - throw ConfigError(json_port, err, "", - "Cannot parse 'target' of port {}", index); + throw JsonError("/ports"_json_pointer / index / "target", + "Cannot parse 'target' of port {}", index); const std::string role(role_raw); const bool isMaster = (role == "master" or role == "initiator"); @@ -65,8 +68,9 @@ void NodeFactory::parse(Core &ip, json_t *cfg) { Node.portsSlave[name_raw] = thisVertex; } } else if (json_ports) { - throw ConfigError(json_ports, "", "IP port list of {} must be an array", - ip.getInstanceName()); + throw JsonError("/ports"_json_pointer, + "IP port list of {} must be an array", + ip.getInstanceName()); } } diff --git a/fpga/lib/pcie_card.cpp b/fpga/lib/pcie_card.cpp index 9caddba55..3f6e9bce3 100644 --- a/fpga/lib/pcie_card.cpp +++ b/fpga/lib/pcie_card.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include using namespace villas; @@ -56,7 +57,7 @@ PCIeCardFactory::make(json_t *json_card, std::string card_name, "ignore_ips", &ignored_ips_array); if (ret != 0) - throw ConfigError(json_card, err, "", "Failed to parse card"); + throw JsonError(""_json_pointer, "Failed to parse card: {}", err.text); auto card = std::shared_ptr(make()); @@ -93,12 +94,15 @@ PCIeCardFactory::make(json_t *json_card, std::string card_name, return nullptr; } - CardFactory::loadIps(card, json_ips, searchPath); + JsonError::context("/ips"_json_pointer, [&] { + return CardFactory::loadIps(card, json_ips, searchPath); + }); if (not card->check()) throw RuntimeError("Checking of FPGA card {} failed", card_name); - CardFactory::loadSwitch(card, json_paths); + JsonError::context("/paths"_json_pointer, + [&] { return CardFactory::loadSwitch(card, json_paths); }); // Deallocate JSON config json_decref(json_ips); diff --git a/fpga/lib/platform_card.cpp b/fpga/lib/platform_card.cpp index 863fdd190..8981a4086 100644 --- a/fpga/lib/platform_card.cpp +++ b/fpga/lib/platform_card.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include using namespace villas; @@ -101,8 +102,12 @@ PlatformCardFactory::make(json_t *json_card, std::string card_name, card->polling = parser.polling != 0; card->ignored_ip_names = parser.ignored_ip_names; - CardFactory::loadIps(card, parser.json_ips, searchPath); - CardFactory::loadSwitch(card, parser.json_paths); + JsonError::context("/ips"_json_pointer, [&] { + return CardFactory::loadIps(card, parser.json_ips, searchPath); + }); + JsonError::context("/paths"_json_pointer, [&] { + return CardFactory::loadSwitch(card, parser.json_paths); + }); // Deallocate JSON config json_decref(parser.json_ips); diff --git a/fpga/lib/utils.cpp b/fpga/lib/utils.cpp index ae05b3f4d..e2890ea57 100644 --- a/fpga/lib/utils.cpp +++ b/fpga/lib/utils.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -243,8 +244,9 @@ fpga::createCard(json_t *config, const fs::path &searchPath, int ret = json_unpack_ex(config, &err, 0, "{s: s}", "interface", &interfaceName); if (ret) { - throw ConfigError(config, err, "interface", - "Failed to parse interface name for card {}", card_name); + throw JsonError("/interface"_json_pointer, + "Failed to parse interface name for card {}: {}", card_name, + err.text); } std::string interfaceNameStr(interfaceName); std::shared_ptr card = nullptr; diff --git a/include/villas/config_helper.hpp b/include/villas/config_helper.hpp index 61d7f2269..2feb68c76 100644 --- a/include/villas/config_helper.hpp +++ b/include/villas/config_helper.hpp @@ -13,6 +13,7 @@ #include +#include #include #include @@ -117,7 +118,7 @@ Duration parse_duration(json_t *json) { case JSON_INTEGER: { int64_t value = json_integer_value(json); if (value < 0) { - throw ConfigError(json, "duration-negative", "Negative duration value"); + throw JsonError(""_json_pointer, "Negative duration value"); } return Duration(value); @@ -128,13 +129,13 @@ Duration parse_duration(json_t *json) { return parse_duration( std::string_view(json_string_value(json), json_string_length(json))); } catch (const RuntimeError &e) { - throw ConfigError(json, "duration", "{}", e.what()); + throw JsonError(""_json_pointer, "{}", e.what()); } } default: - throw ConfigError(json, "duration", - "Expected a string or integer for duration"); + throw JsonError(""_json_pointer, + "Expected a string or integer for duration"); } } diff --git a/include/villas/exceptions.hpp b/include/villas/exceptions.hpp index d73b2d872..eb8181e59 100644 --- a/include/villas/exceptions.hpp +++ b/include/villas/exceptions.hpp @@ -43,71 +43,4 @@ class MemoryAllocationError : public RuntimeError { MemoryAllocationError() : RuntimeError("Failed to allocate memory") {} }; -class ConfigError : public std::runtime_error { - -protected: - // A setting-id referencing the setting. - std::string id; - json_t *setting; - json_error_t error; - - char *msg; - - std::string getMessage() const { - std::stringstream ss; - - ss << std::runtime_error::what() << std::endl; - - if (error.position >= 0) { - ss << std::endl; - ss << " " << error.text << " in " << error.source << ":" << error.line - << ":" << error.column << std::endl; - } - - ss << std::endl - << " Please consult the user documentation for details: " << std::endl; - ss << " " << docUri(); - - ss << std::endl; - - return ss.str(); - } - -public: - ~ConfigError() override { - if (msg) - free(msg); - } - - template - ConfigError( - json_t *s, const std::string &i, - fmt::format_string what = "Failed to parse configuration", - Args &&...args) - : std::runtime_error(fmt::format(what, std::forward(args)...)), - id(i), setting(s) { - error.position = -1; - - msg = strdup(getMessage().c_str()); - } - - template - ConfigError( - json_t *s, const json_error_t &e, const std::string &i, - fmt::format_string what = "Failed to parse configuration", - Args &&...args) - : std::runtime_error(fmt::format(what, std::forward(args)...)), - id(i), setting(s), error(e) { - msg = strdup(getMessage().c_str()); - } - - std::string docUri() const { - std::string baseUri = "https://villas.fein-aachen.org/doc/jump?"; - - return baseUri + id; - } - - const char *what() const noexcept override { return msg; } -}; - } // namespace villas diff --git a/include/villas/jansson.hpp b/include/villas/jansson.hpp index 026db68cb..45391721e 100644 --- a/include/villas/jansson.hpp +++ b/include/villas/jansson.hpp @@ -14,6 +14,7 @@ #include #include +#include namespace villas { @@ -298,7 +299,7 @@ void janssonUnpack(::json_t *json, ::json_error_t err; if (auto ret = ::json_unpack_ex(json, &err, 0, fmt.c_str(), args...); ret == -1) - throw RuntimeError("Could not unpack json value: {}", err.text); + throw JsonError(""_json_pointer, "{}", err.text); } // Compile time validator for json_pack-style format strings. diff --git a/include/villas/json.hpp b/include/villas/json.hpp index d7bb94858..ba7c3f500 100644 --- a/include/villas/json.hpp +++ b/include/villas/json.hpp @@ -6,6 +6,14 @@ */ #pragma once +#include +#include +#include +#include +#include +#include + +#include #include #include @@ -18,6 +26,71 @@ namespace villas { using Json = nlohmann::json; using JsonPointer = Json::json_pointer; +struct JsonDiagnostic { + JsonPointer pointer; + std::string message; +}; + +class JsonError final : public std::exception { + std::vector diagnostics_; + +public: + using value_type = decltype(diagnostics_)::value_type; + + explicit JsonError(std::vector diagnostics) + : diagnostics_(std::move(diagnostics)) { + assert(not diagnostics_.empty()); + } + + explicit JsonError(JsonDiagnostic diagnostic) + : JsonError(std::vector{std::move(diagnostic)}) {} + + template + JsonError(JsonPointer pointer, fmt::format_string message, + Args &&...args) + : JsonError(JsonDiagnostic{ + .pointer = std::move(pointer), + .message = fmt::format(message, std::forward(args)...), + }) {} + + void push_back(JsonDiagnostic diagnostic) { + diagnostics_.push_back(std::move(diagnostic)); + } + + auto what() const noexcept -> char const * override { + return diagnostics_.front().message.c_str(); + } + + auto begin() const noexcept -> decltype(diagnostics_)::const_iterator { + return diagnostics_.begin(); + } + + auto end() const noexcept -> decltype(diagnostics_)::const_iterator { + return diagnostics_.end(); + } + + static auto with_parent(JsonPointer parent, JsonError error) -> JsonError { + auto &diagnostics = error.diagnostics_; + + for (auto &diagnostic : diagnostics) { + diagnostic.pointer = parent / std::move(diagnostic.pointer); + } + + return JsonError(std::move(diagnostics)); + } + + template + requires std::invocable + static auto context(JsonPointer pointer, Fn &&fn, Args &&...args) + -> std::invoke_result_t { + try { + return std::invoke(std::forward(fn), std::forward(args)...); + } catch (JsonError &error) { + throw JsonError::with_parent(std::move(pointer), std::move(error)); + } + } +}; + // forward declaration for villas/jansson.hpp compatibility header class JanssonPtr; void to_json(Json &json, JanssonPtr const &jansson); diff --git a/include/villas/node/json_schema.hpp b/include/villas/node/json_schema.hpp index 42c736d21..d7d3e6878 100644 --- a/include/villas/node/json_schema.hpp +++ b/include/villas/node/json_schema.hpp @@ -3,10 +3,6 @@ // Generated file — do not edit #pragma once -#include -#include -#include -#include #include #include @@ -17,63 +13,6 @@ namespace villas::node { using JsonUri = nlohmann::json_uri; -struct JsonDiagnostic { - JsonPointer pointer; - std::string message; -}; - -class JsonError final : public std::exception { - std::vector diagnostics_; - -public: - using value_type = decltype(diagnostics_)::value_type; - - explicit JsonError(std::vector diagnostics) - : diagnostics_(std::move(diagnostics)) { - assert(not diagnostics_.empty()); - } - - explicit JsonError(JsonDiagnostic diagnostic) - : JsonError(std::vector{std::move(diagnostic)}) {} - - void push_back(JsonDiagnostic diagnostic) { - diagnostics_.push_back(std::move(diagnostic)); - } - - auto what() const noexcept -> char const * override { - return diagnostics_.front().message.c_str(); - } - - auto begin() const noexcept -> decltype(diagnostics_)::const_iterator { - return diagnostics_.begin(); - } - - auto end() const noexcept -> decltype(diagnostics_)::const_iterator { - return diagnostics_.end(); - } - - static auto with_parent(JsonPointer parent, JsonError error) -> JsonError { - auto &diagnostics = error.diagnostics_; - - for (auto &diagnostic : diagnostics) { - diagnostic.pointer = parent / std::move(diagnostic.pointer); - } - - return JsonError(std::move(diagnostics)); - } - - template - requires std::invocable - static auto context(JsonPointer pointer, Fn &&fn, Args &&...args) - -> std::invoke_result_t { - try { - return std::invoke(std::forward(fn), std::forward(args)...); - } catch (JsonError &error) { - throw JsonError::with_parent(std::move(pointer), std::move(error)); - } - } -}; - Json const &bundled_schemas(); class JsonSchema { diff --git a/lib/format.cpp b/lib/format.cpp index e87f379d1..37da07203 100644 --- a/lib/format.cpp +++ b/lib/format.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -42,7 +43,7 @@ Format *FormatFactory::make(json_t *json) { return f; } else - throw ConfigError(json, "node-config-format", "Invalid format config"); + throw JsonError(""_json_pointer, "Invalid format config"); } Format *FormatFactory::make(const std::string &format) { @@ -123,13 +124,13 @@ void Format::parse(json_t *json) { "sequence", &sequence, "data", &data, "offset", &offset, "real_precision", &real_precision); if (ret) - throw ConfigError(json, err, "node-config-format", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (real_precision < 0 || real_precision > 31) - throw ConfigError(json, err, "node-config-format-precision", - "The valid range for the real_precision setting is " - "between 0 and 31 (inclusive)"); + throw JsonError("/real_precision"_json_pointer, + "The valid range for the real_precision setting is " + "between 0 and 31 (inclusive)"); if (ts_origin == 0) flags &= ~(int)SampleFlags::HAS_TS_ORIGIN; diff --git a/lib/formats/column.cpp b/lib/formats/column.cpp index 4bf854645..9684318d4 100644 --- a/lib/formats/column.cpp +++ b/lib/formats/column.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -179,13 +180,13 @@ void ColumnLineFormat::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: s }", "separator", &sep); if (ret) - throw ConfigError(json, err, "node-config-format-column", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (sep) { if (strlen(sep) != 1) - throw ConfigError(json, "node-config-format-column-separator", - "Column separator must be a single character!"); + throw JsonError("/separator"_json_pointer, + "Column separator must be a single character!"); separator = sep[0]; } diff --git a/lib/formats/json.cpp b/lib/formats/json.cpp index ff3c13577..f68b00273 100644 --- a/lib/formats/json.cpp +++ b/lib/formats/json.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -396,12 +397,12 @@ void JsonFormat::parse(json_t *json) { ); if (ret) - throw ConfigError(json, err, "node-config-format-json", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (indent > JSON_MAX_INDENT) - throw ConfigError(json, "node-config-format-json-indent", - "The maximum indentation level is {}", JSON_MAX_INDENT); + throw JsonError("/indent"_json_pointer, + "The maximum indentation level is {}", JSON_MAX_INDENT); dump_flags = 0; diff --git a/lib/formats/json_kafka.cpp b/lib/formats/json_kafka.cpp index b627f3c00..6d03f0054 100644 --- a/lib/formats/json_kafka.cpp +++ b/lib/formats/json_kafka.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -138,13 +139,13 @@ void JsonKafkaFormat::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: o }", "schema", &json_schema_tmp); if (ret) - throw ConfigError(json, err, "node-config-format-json-kafka", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (json_schema_tmp) { if (!json_is_object(json_schema_tmp)) - throw ConfigError(json, "node-config-format-json-kafka-schema", - "Kafka schema must be configured as a dictionary"); + throw JsonError("/schema"_json_pointer, + "Kafka schema must be configured as a dictionary"); if (json_schema) json_decref(json_schema); diff --git a/lib/formats/line.cpp b/lib/formats/line.cpp index b4af854d2..0e8211f6f 100644 --- a/lib/formats/line.cpp +++ b/lib/formats/line.cpp @@ -7,6 +7,7 @@ #include #include +#include using namespace villas; using namespace villas::node; @@ -136,21 +137,21 @@ void LineFormat::parse(json_t *json) { "delimiter", &delim, "header", &header, "skip_first_line", &skip, "comment_prefix", &com); if (ret) - throw ConfigError(json, err, "node-config-format-line", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (delim) { if (strlen(delim) != 1) - throw ConfigError(json, "node-config-format-line-delimiter", - "Line delimiter must be a single character!"); + throw JsonError("/delimiter"_json_pointer, + "Line delimiter must be a single character!"); delimiter = delim[0]; } if (com) { if (strlen(com) != 1) - throw ConfigError(json, "node-config-format-line-comment_prefix", - "Comment prefix must be a single character!"); + throw JsonError("/comment_prefix"_json_pointer, + "Comment prefix must be a single character!"); comment = com[0]; } diff --git a/lib/formats/opal_asyncip.cpp b/lib/formats/opal_asyncip.cpp index 7e42d612b..6b7888b15 100644 --- a/lib/formats/opal_asyncip.cpp +++ b/lib/formats/opal_asyncip.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -104,8 +105,8 @@ void OpalAsyncIPFormat::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: i }", "dev_id", &did); if (ret) - throw ConfigError(json, err, "node-config-format-opal-asyncip", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (did >= 0) dev_id = did; diff --git a/lib/formats/raw.cpp b/lib/formats/raw.cpp index 2fcf72532..973eabcec 100644 --- a/lib/formats/raw.cpp +++ b/lib/formats/raw.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -496,12 +497,11 @@ void RawFormat::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: s, s?: b, s?: i }", "endianess", &end, "fake", &fake_tmp, "bits", &bits); if (ret) - throw ConfigError(json, err, "node-config-format-raw", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (bits % 8 != 0 || bits > 128 || bits <= 0) - throw ConfigError(json, "node-config-format-raw-bits", - "Failed to parse format configuration"); + throw JsonError("/bits"_json_pointer, "Invalid number of bits: {}", bits); if (end) { if (!strcmp(end, "little")) @@ -509,8 +509,8 @@ void RawFormat::parse(json_t *json) { else if (!strcmp(end, "big")) endianess = Endianess::BIG; else - throw ConfigError(json, "node-config-format-raw-endianess", - "Endianess must be either 'big' or 'little'"); + throw JsonError("/endianess"_json_pointer, + "Endianess must be either 'big' or 'little'"); } fake = fake_tmp; diff --git a/lib/formats/villas_binary.cpp b/lib/formats/villas_binary.cpp index 7e6a7f6f6..9b34a6942 100644 --- a/lib/formats/villas_binary.cpp +++ b/lib/formats/villas_binary.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -114,8 +115,8 @@ void VillasBinaryFormat::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: i, s?: b }", "source_index", &sid, "validate_source_index", &vsi); if (ret) - throw ConfigError(json, err, "node-config-format-villas-binary", - "Failed to parse format configuration"); + throw JsonError(""_json_pointer, "Failed to parse format configuration: {}", + err.text); if (vsi >= 0) validate_source_index = vsi != 0; diff --git a/lib/hook.cpp b/lib/hook.cpp index ad693ee1c..d546f4365 100644 --- a/lib/hook.cpp +++ b/lib/hook.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -49,7 +50,7 @@ void Hook::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: i }", "priority", &prio); if (ret) - throw ConfigError(json, err, "node-config-hook"); + throw JsonError(""_json_pointer, "{}", err.text); if (prio >= 0) priority = prio; @@ -69,11 +70,11 @@ void SingleSignalHook::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: o }", "signal", &json_signal); if (ret) - throw ConfigError(json, err, "node-config-hook"); + throw JsonError(""_json_pointer, "{}", err.text); if (!json_is_string(json_signal)) - throw ConfigError(json_signal, "node-config-hook-signals", - "Invalid value for setting 'signal'"); + throw JsonError("/signal"_json_pointer, + "Invalid value for setting 'signal'"); signalName = json_string_value(json_signal); } @@ -104,17 +105,17 @@ void MultiSignalHook::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: o, s?: o }", "signals", &json_signals, "signal", &json_signal); if (ret) - throw ConfigError(json, err, "node-config-hook"); + throw JsonError(""_json_pointer, "{}", err.text); if (json_signals) { if (!json_is_array(json_signals)) - throw ConfigError(json_signals, "node-config-hook-signals", - "Setting 'signals' must be a list of signal names"); + throw JsonError("/signals"_json_pointer, + "Setting 'signals' must be a list of signal names"); json_array_foreach (json_signals, i, json_signal) { if (!json_is_string(json_signal)) - throw ConfigError(json_signal, "node-config-hook-signals", - "Invalid value for setting 'signals'"); + throw JsonError("/signals"_json_pointer / i, + "Invalid value for setting 'signals'"); const char *name = json_string_value(json_signal); @@ -122,15 +123,14 @@ void MultiSignalHook::parse(json_t *json) { } } else if (json_signal) { if (!json_is_string(json_signal)) - throw ConfigError(json_signal, "node-config-hook-signals", - "Invalid value for setting 'signals'"); + throw JsonError("/signal"_json_pointer, + "Invalid value for setting 'signal'"); const char *name = json_string_value(json_signal); signalNames.push_back(name); } else - throw ConfigError(json, "node-config-hook-signals", - "Missing 'signals' setting"); + throw JsonError(""_json_pointer, "Missing 'signals' setting"); } void MultiSignalHook::prepare() { diff --git a/lib/hook_list.cpp b/lib/hook_list.cpp index c1ed94720..3284f8362 100644 --- a/lib/hook_list.cpp +++ b/lib/hook_list.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -17,8 +18,8 @@ using namespace villas::node; void HookList::parse(json_t *json, int mask, Path *o, Node *n) { if (!json_is_array(json)) - throw ConfigError(json, "node-config-hook", - "Hooks must be configured as a list of hook objects"); + throw JsonError(""_json_pointer, + "Hooks must be configured as a list of hook objects"); size_t i; json_t *json_hook; @@ -38,27 +39,26 @@ void HookList::parse(json_t *json, int mask, Path *o, Node *n) { case JSON_OBJECT: ret = json_unpack_ex(json_hook, &err, 0, "{ s: s }", "type", &type); if (ret) - throw ConfigError(json_hook, err, "node-config-hook", - "Failed to parse hook"); + throw JsonError(""_json_pointer / i, "Failed to parse hook: {}", + err.text); json_config = json_hook; break; default: - throw ConfigError(json_hook, "node-config-hook", - "Hook must be configured by simple string or object"); + throw JsonError(""_json_pointer / i, + "Hook must be configured by simple string or object"); } auto hf = plugin::registry->lookup(type); if (!hf) - throw ConfigError(json_hook, "node-config-hook", "Unknown hook type '{}'", - type); + throw JsonError(""_json_pointer / i, "Unknown hook type '{}'", type); if (!(hf->getFlags() & mask)) - throw ConfigError(json_hook, "node-config-hook", - "Hook '{}' not allowed here", type); + throw JsonError(""_json_pointer / i, "Hook '{}' not allowed here", type); h = hf->make(o, n); - h->parse(json_config); + JsonError::context(""_json_pointer / i, + [&] { return h->parse(json_config); }); push_back(h); } diff --git a/lib/hooks/average.cpp b/lib/hooks/average.cpp index 4894e0513..179c47cf4 100644 --- a/lib/hooks/average.cpp +++ b/lib/hooks/average.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -47,7 +48,7 @@ class AverageHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s: i }", "offset", &offset); if (ret) - throw ConfigError(json, err, "node-config-hook-average"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/cast.cpp b/lib/hooks/cast.cpp index 9a1c87ace..27c3d9076 100644 --- a/lib/hooks/cast.cpp +++ b/lib/hooks/cast.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -56,7 +57,7 @@ class CastHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s?: s, s?: s, s?: s }", "new_type", &type, "new_name", &name, "new_unit", &unit); if (ret) - throw ConfigError(json, err, "node-config-hook-cast"); + throw JsonError(""_json_pointer, "{}", err.text); if (type) { new_type = signalTypeFromString(type); diff --git a/lib/hooks/decimate.cpp b/lib/hooks/decimate.cpp index d30b7ac52..0646864ee 100644 --- a/lib/hooks/decimate.cpp +++ b/lib/hooks/decimate.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -30,7 +31,7 @@ void DecimateHook::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: i, s?: b }", "ratio", &ratio, "renumber", &renumber); if (ret) - throw ConfigError(json, err, "node-config-hook-decimate"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/digest.cpp b/lib/hooks/digest.cpp index e6d8fbf06..46df6f8c2 100644 --- a/lib/hooks/digest.cpp +++ b/lib/hooks/digest.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -201,7 +202,7 @@ class DigestHook : public Hook { json_unpack_ex(json, &err, 0, "{ s: s, s?: s, s?: s }", "uri", &uri_str, "mode", &mode_str, "algorithm", &algorithm_str); if (ret) - throw ConfigError(json, err, "node-config-hook-digest"); + throw JsonError(""_json_pointer, "{}", err.text); uri = std::string(uri_str); diff --git a/lib/hooks/dp.cpp b/lib/hooks/dp.cpp index 3e4ea919c..66f0ccf74 100644 --- a/lib/hooks/dp.cpp +++ b/lib/hooks/dp.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -143,20 +144,19 @@ class DPHook : public Hook { &json_signal, "f0", &f0, "dt", &dt, "rate", &rate, "harmonics", &json_harmonics, "inverse", &inverse); if (ret) - throw ConfigError(json, err, "node-config-hook-dp"); + throw JsonError(""_json_pointer, "{}", err.text); if (rate > 0) timestep = 1. / rate; else if (dt > 0) timestep = dt; else - throw ConfigError( - json, "node-config-hook-dp", - "Either on of the settings 'dt' or 'rate' must be given"); + throw JsonError(""_json_pointer, + "Either on of the settings 'dt' or 'rate' must be given"); if (!json_is_array(json_harmonics)) - throw ConfigError(json_harmonics, "node-config-hook-dp-harmonics", - "Setting 'harmonics' must be a list of integers"); + throw JsonError("/harmonics"_json_pointer, + "Setting 'harmonics' must be a list of integers"); switch (json_typeof(json_signal)) { case JSON_STRING: @@ -169,8 +169,8 @@ class DPHook : public Hook { break; default: - throw ConfigError(json_signal, "node-config-hook-dp-signal", - "Invalid value for setting 'signal'"); + throw JsonError("/signal"_json_pointer, + "Invalid value for setting 'signal'"); } fharmonics_len = json_array_size(json_harmonics); @@ -181,8 +181,8 @@ class DPHook : public Hook { json_array_foreach (json_harmonics, i, json_harmonic) { if (!json_is_integer(json_harmonic)) - throw ConfigError(json_harmonic, "node-config-hook-dp-harmonics", - "Setting 'harmonics' must be a list of integers"); + throw JsonError("/harmonics"_json_pointer / i, + "Setting 'harmonics' must be a list of integers"); fharmonics[i] = json_integer_value(json_harmonic); } diff --git a/lib/hooks/ebm.cpp b/lib/hooks/ebm.cpp index 049f92b1e..48ab112da 100644 --- a/lib/hooks/ebm.cpp +++ b/lib/hooks/ebm.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -37,17 +38,18 @@ class EBMHook : public Hook { ret = json_unpack_ex(json, &err, 0, "{ s: o }", "phases", &json_phases); if (ret) - throw ConfigError(json, err, "node-config-hook-ebm"); + throw JsonError(""_json_pointer, "{}", err.text); if (!json_is_array(json_phases)) - throw ConfigError(json_phases, "node-config-hook-ebm-phases"); + throw JsonError("/phases"_json_pointer, + "The 'phases' setting must be an array"); json_array_foreach (json_phases, i, json_phase) { int voltage, current; ret = json_unpack_ex(json_phase, &err, 0, "[ i, i ]", &voltage, ¤t); if (ret) - throw ConfigError(json, err, "node-config-hook-ebm-phases"); + throw JsonError("/phases"_json_pointer / i, "{}", err.text); phases.emplace_back(voltage, current); } diff --git a/lib/hooks/frame.cpp b/lib/hooks/frame.cpp index e42db9e47..af20f1db7 100644 --- a/lib/hooks/frame.cpp +++ b/lib/hooks/frame.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include "villas/timing.hpp" @@ -77,18 +78,20 @@ class FrameHook : public Hook { auto ret = json_unpack_ex(json, &err, 0, "{ s?: s, s: o }", "trigger", &trigger_str, "interval", &json_interval); if (ret) - throw ConfigError(json, err, "node-config-hook-frame"); + throw JsonError(""_json_pointer, "{}", err.text); if (trigger_str == nullptr || !strcmp(trigger_str, "timestamp")) { - interval = parse_duration(json_interval); + interval = JsonError::context("/interval"_json_pointer, [&] { + return parse_duration(json_interval); + }); if (std::get(interval) == TimeInterval::zero()) - throw ConfigError(json, "node-config-hook-frame-interval", - "Interval must be greater than zero"); + throw JsonError("/interval"_json_pointer, + "Interval must be greater than zero"); } else if (!strcmp(trigger_str, "sequence")) { if (!json_is_integer(json_interval)) - throw ConfigError(json_interval, "node-config-hook-frame-interval", - "Interval must be an integer"); + throw JsonError("/interval"_json_pointer, + "Interval must be an integer"); interval = SequenceInterval(json_integer_value(json_interval)); } diff --git a/lib/hooks/gate.cpp b/lib/hooks/gate.cpp index 4e380d566..ff441da64 100644 --- a/lib/hooks/gate.cpp +++ b/lib/hooks/gate.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -53,7 +54,7 @@ class GateHook : public SingleSignalHook { "threshold", &threshold, "duration", &duration, "samples", &samples, "mode", &mode_str); if (ret) - throw ConfigError(json, err, "node-config-hook-gate"); + throw JsonError(""_json_pointer, "{}", err.text); if (mode_str) { if (!strcmp(mode_str, "above")) diff --git a/lib/hooks/limit_rate.cpp b/lib/hooks/limit_rate.cpp index 65075e06b..fd763fcdc 100644 --- a/lib/hooks/limit_rate.cpp +++ b/lib/hooks/limit_rate.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -28,7 +29,7 @@ void LimitRateHook::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: F, s?: s }", "rate", &rate, "mode", &m); if (ret) - throw ConfigError(json, err, "node-config-hook-limit_rate"); + throw JsonError(""_json_pointer, "{}", err.text); if (m) { if (!strcmp(m, "origin")) @@ -38,8 +39,8 @@ void LimitRateHook::parse(json_t *json) { else if (!strcmp(m, "local")) mode = LIMIT_RATE_LOCAL; else - throw ConfigError(json, "node-config-hook-limit_rate-mode", - "Invalid value '{}' for setting 'mode'", m); + throw JsonError("/mode"_json_pointer, + "Invalid value '{}' for setting 'mode'", m); } deadtime = 1.0 / rate; diff --git a/lib/hooks/limit_value.cpp b/lib/hooks/limit_value.cpp index d3f47ced2..087ef43f8 100644 --- a/lib/hooks/limit_value.cpp +++ b/lib/hooks/limit_value.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -36,7 +37,7 @@ class LimitValueHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s: F, s: F }", "min", &min, "max", &max); if (ret) - throw ConfigError(json, err, "node-config-hook-average"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/lua.cpp b/lib/hooks/lua.cpp index deafcdef8..b634844ee 100644 --- a/lib/hooks/lua.cpp +++ b/lib/hooks/lua.cpp @@ -17,6 +17,7 @@ extern "C" { #include #include +#include #include #include #include @@ -298,7 +299,7 @@ LuaSignalExpression::LuaSignalExpression(lua_State *l, json_t *json_sig) // Parse expression ret = json_unpack_ex(json_sig, &err, 0, "{ s: s }", "expression", &expr); if (ret) - throw ConfigError(json_sig, err, "node-config-hook-lua-signals"); + throw JsonError(""_json_pointer, "{}", err.text); cfg = json_sig; @@ -316,8 +317,8 @@ void LuaSignalExpression::parseExpression(const std::string &expr) { int err = luaL_loadstring(L, fexpr.c_str()); if (err) - throw ConfigError(cfg, "node-config-hook-lua-signals", - "Failed to load Lua expression: {}", lua_tostring(L, -1)); + throw JsonError(""_json_pointer, "Failed to load Lua expression: {}", + lua_tostring(L, -1)); cookie = luaL_ref(L, LUA_REGISTRYINDEX); } @@ -354,12 +355,13 @@ void LuaHook::parseExpressions(json_t *json_sigs) { signalsExpressions->clear(); ret = signalsExpressions->parse(json_sigs); if (ret) - throw ConfigError(json_sigs, "node-config-hook-lua-signals", - "Setting 'signals' must be a list of dicts"); + throw JsonError(""_json_pointer, + "Setting 'signals' must be a list of dicts"); // cppcheck-suppress unknownMacro json_array_foreach (json_sigs, i, json_sig) - expressions.emplace_back(L, json_sig); + JsonError::context(""_json_pointer / i, + [&] { return expressions.emplace_back(L, json_sig); }); hasExpressions = true; } @@ -379,7 +381,7 @@ void LuaHook::parse(json_t *json) { &script_str, "signals", &json_signals, "use_names", &names); if (ret) - throw ConfigError(json, err, "node-config-hook-lua"); + throw JsonError(""_json_pointer, "{}", err.text); useNames = names; @@ -387,7 +389,8 @@ void LuaHook::parse(json_t *json) { script = script_str; if (json_signals) - parseExpressions(json_signals); + JsonError::context("/signals"_json_pointer, + [&] { return parseExpressions(json_signals); }); state = State::PARSED; } diff --git a/lib/hooks/ma.cpp b/lib/hooks/ma.cpp index 4700920f5..44edbe5fb 100644 --- a/lib/hooks/ma.cpp +++ b/lib/hooks/ma.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -57,7 +58,7 @@ class MovingAverageHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s?: i }", "window_size", &windowSize); if (ret) - throw ConfigError(json, err, "node-config-hook-ma"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/pmu.cpp b/lib/hooks/pmu.cpp index b8e42e65a..4c574464e 100644 --- a/lib/hooks/pmu.cpp +++ b/lib/hooks/pmu.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -102,26 +103,26 @@ void PmuHook::parse(json_t *json) { &frequencyOffset, "rocof_offset", &rocofOffset); if (ret) - throw ConfigError(json, err, "node-config-hook-pmu"); + throw JsonError(""_json_pointer, "{}", err.text); if (sampleRate <= 0) - throw ConfigError(json, "node-config-hook-pmu-sample_rate", - "Sample rate cannot be less than 0 tried to set {}", - sampleRate); + throw JsonError("/sample_rate"_json_pointer, + "Sample rate cannot be less than 0 tried to set {}", + sampleRate); if (phasorRate <= 0) - throw ConfigError(json, "node-config-hook-pmu-phasor_rate", - "Phasor rate cannot be less than 0 tried to set {}", - phasorRate); + throw JsonError("/dft_rate"_json_pointer, + "Phasor rate cannot be less than 0 tried to set {}", + phasorRate); if (nominalFreq <= 0) - throw ConfigError(json, "node-config-hook-pmu-nominal_freq", - "Nominal frequency cannot be less than 0 tried to set {}", - nominalFreq); + throw JsonError("/nominal_freq"_json_pointer, + "Nominal frequency cannot be less than 0 tried to set {}", + nominalFreq); if (numberPlc <= 0) - throw ConfigError( - json, "node-config-hook-pmu-number_plc", + throw JsonError( + "/number_plc"_json_pointer, "Number of power line cycles cannot be less than 0 tried to set {}", numberPlc); @@ -140,8 +141,8 @@ void PmuHook::parse(json_t *json) { else if (strcmp(windowTypeC, "blackman") == 0) windowType = WindowType::BLACKMAN; else - throw ConfigError(json, "node-config-hook-pmu-window-type", - "Invalid window type: {}", windowTypeC); + throw JsonError("/window_type"_json_pointer, "Invalid window type: {}", + windowTypeC); if (!angleUnitC) logger->info("No angle type given, assume rad"); @@ -150,8 +151,8 @@ void PmuHook::parse(json_t *json) { else if (strcmp(angleUnitC, "degree") == 0) angleUnitFactor = 180 / M_PI; else - throw ConfigError(json, "node-config-hook-pmu-angle-unit", - "Angle unit {} not recognized", angleUnitC); + throw JsonError("/angle_unit"_json_pointer, "Angle unit {} not recognized", + angleUnitC); if (!timeAlignC) logger->info("No timestamp alignment defined. Assume alignment center"); @@ -162,8 +163,8 @@ void PmuHook::parse(json_t *json) { else if (strcmp(timeAlignC, "right") == 0) timeAlignType = TimeAlign::RIGHT; else - throw ConfigError(json, "node-config-hook-dft-timestamp-alignment", - "Timestamp alignment {} not recognized", timeAlignC); + throw JsonError("/timestamp_align"_json_pointer, + "Timestamp alignment {} not recognized", timeAlignC); } Hook::Reason PmuHook::process(struct Sample *smp) { diff --git a/lib/hooks/pmu_dft.cpp b/lib/hooks/pmu_dft.cpp index e9b59d164..502253549 100644 --- a/lib/hooks/pmu_dft.cpp +++ b/lib/hooks/pmu_dft.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -263,7 +264,7 @@ class PmuDftHook : public MultiSignalHook { "amplitude_offset", &litudeOffset, "frequency_offset", &frequencyOffset, "rocof_offset", &rocofOffset); if (ret) - throw ConfigError(json, err, "node-config-hook-dft"); + throw JsonError(""_json_pointer, "{}", err.text); // Backward-compatibility: accept the previously misspelled keys. json_t *json_start = json_object_get(json, "start_freqency"); @@ -289,8 +290,8 @@ class PmuDftHook : public MultiSignalHook { else if (strcmp(windowTypeC, "hann") == 0) windowType = WindowType::HANN; else - throw ConfigError(json, "node-config-hook-dft-window-type", - "Invalid window type: {}", windowTypeC); + throw JsonError("/window_type"_json_pointer, "Invalid window type: {}", + windowTypeC); if (!timeAlignC) logger->info("No timestamp alignment defined. Assume alignment center"); @@ -301,8 +302,8 @@ class PmuDftHook : public MultiSignalHook { else if (strcmp(timeAlignC, "right") == 0) timeAlignType = TimeAlign::RIGHT; else - throw ConfigError(json, "node-config-hook-dft-timestamp-alignment", - "Timestamp alignment {} not recognized", timeAlignC); + throw JsonError("/timestamp_align"_json_pointer, + "Timestamp alignment {} not recognized", timeAlignC); if (!angleUnitC) logger->info("No angle type given, assume rad"); @@ -311,8 +312,8 @@ class PmuDftHook : public MultiSignalHook { else if (strcmp(angleUnitC, "degree") == 0) angleUnitFactor = 180 / M_PI; else - throw ConfigError(json, "node-config-hook-dft-angle-unit", - "Angle unit {} not recognized", angleUnitC); + throw JsonError("/angle_unit"_json_pointer, + "Angle unit {} not recognized", angleUnitC); if (!paddingTypeC) logger->info("No Padding type given, assume no zeropadding"); @@ -321,8 +322,8 @@ class PmuDftHook : public MultiSignalHook { else if (strcmp(paddingTypeC, "signal_repeat") == 0) paddingType = PaddingType::SIG_REPEAT; else - throw ConfigError(json, "node-config-hook-dft-padding-type", - "Padding type {} not recognized", paddingTypeC); + throw JsonError("/padding_type"_json_pointer, + "Padding type {} not recognized", paddingTypeC); if (!estimateTypeC) { logger->info("No Frequency estimation type given, assume no none"); diff --git a/lib/hooks/pmu_ipdft.cpp b/lib/hooks/pmu_ipdft.cpp index c4455fed2..38eab6de6 100644 --- a/lib/hooks/pmu_ipdft.cpp +++ b/lib/hooks/pmu_ipdft.cpp @@ -6,6 +6,7 @@ */ #include +#include namespace villas { namespace node { @@ -67,11 +68,11 @@ class IpDftPmuHook : public PmuHook { &estimationRange); if (ret) - throw ConfigError(json, err, "node-config-hook-ip-dft-pmu"); + throw JsonError(""_json_pointer, "{}", err.text); if (estimationRange <= 0) - throw ConfigError( - json, "node-config-hook-ip-dft-pmu-estimation_range", + throw JsonError( + "/estimation_range"_json_pointer, "Estimation range cannot be less or equal than 0 tried to set {}", estimationRange); } diff --git a/lib/hooks/power.cpp b/lib/hooks/power.cpp index ff8093386..76358005b 100644 --- a/lib/hooks/power.cpp +++ b/lib/hooks/power.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -187,12 +188,12 @@ class PowerHook : public MultiSignalHook { "timestamp_align", &timeAlignC, "angle_unit", &angleUnitC); if (result) - throw ConfigError(json, json_error, "node-config-hook-power"); + throw JsonError(""_json_pointer, "{}", json_error.text); if (windowSizeIn < 1) - throw ConfigError(json, "node-config-hook-power", - "Window size must be greater 0 but is set to {}", - windowSizeIn); + throw JsonError("/window_size"_json_pointer, + "Window size must be greater 0 but is set to {}", + windowSizeIn); windowSize = (unsigned)windowSizeIn; @@ -205,8 +206,8 @@ class PowerHook : public MultiSignalHook { else if (strcmp(timeAlignC, "right") == 0) timeAlignType = TimeAlign::RIGHT; else - throw ConfigError(json, "node-config-hook-dft-timestamp-alignment", - "Timestamp alignment {} not recognized", timeAlignC); + throw JsonError("/timestamp_align"_json_pointer, + "Timestamp alignment {} not recognized", timeAlignC); if (!angleUnitC) logger->info("No angle type given, assume rad"); @@ -215,13 +216,13 @@ class PowerHook : public MultiSignalHook { else if (strcmp(angleUnitC, "degree") == 0) angleUnitFactor = 180 / M_PI; else - throw ConfigError(json, "node-config-hook-dft-angle-unit", - "Angle unit {} not recognized", angleUnitC); + throw JsonError("/angle_unit"_json_pointer, + "Angle unit {} not recognized", angleUnitC); // Pairings if (!json_is_array(json_pairings)) - throw ConfigError(json_pairings, "node-config-hook-power", - "Pairings are expected as json array"); + throw JsonError("/pairings"_json_pointer, + "Pairings are expected as json array"); size_t i = 0; json_t *json_pairings_value; diff --git a/lib/hooks/pps_ts.cpp b/lib/hooks/pps_ts.cpp index 197e44b8c..9c061a7c3 100644 --- a/lib/hooks/pps_ts.cpp +++ b/lib/hooks/pps_ts.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -53,7 +54,7 @@ class PpsTsHook : public SingleSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s?: s, s?: F }", "time_source", &timeSourceC, "threshold", &threshold); if (ret) - throw ConfigError(json, err, "node-config-hook-pps_ts"); + throw JsonError(""_json_pointer, "{}", err.text); if (timeSourceC) { if (!strcmp(timeSourceC, "sample")) diff --git a/lib/hooks/print.cpp b/lib/hooks/print.cpp index 2bb189125..ebf7d2d39 100644 --- a/lib/hooks/print.cpp +++ b/lib/hooks/print.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -67,11 +68,11 @@ class PrintHook : public Hook { ret = json_unpack_ex(json, &err, 0, "{ s?: s, s?: o, s?: s }", "prefix", &p, "format", &json_format, "output", &o); if (ret) - throw ConfigError(json, err, "node-config-hook-print"); + throw JsonError(""_json_pointer, "{}", err.text); if (p && o) { - throw ConfigError(json, "node-config-hook-print", - "Prefix and output settings are exclusive."); + throw JsonError(""_json_pointer, + "Prefix and output settings are exclusive."); } if (p) @@ -81,13 +82,15 @@ class PrintHook : public Hook { output_path = o; // Format - auto *fmt = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.human"); + auto *fmt = json_format + ? JsonError::context( + "/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.human"); formatter = Format::Ptr(fmt); if (!formatter) - throw ConfigError(json_format, "node-config-hook-print-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); state = State::PARSED; } diff --git a/lib/hooks/reorder_ts.cpp b/lib/hooks/reorder_ts.cpp index 35689c659..5e9408450 100644 --- a/lib/hooks/reorder_ts.cpp +++ b/lib/hooks/reorder_ts.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -54,7 +55,7 @@ class ReorderTsHook : public Hook { int ret = json_unpack_ex(json, &err, 0, "{ s?: i }", "window_size", &window_size); if (ret) - throw ConfigError(json, err, "node-config-hook-reorder-ts"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/rms.cpp b/lib/hooks/rms.cpp index 5f167a1b5..79967d42a 100644 --- a/lib/hooks/rms.cpp +++ b/lib/hooks/rms.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -60,12 +61,12 @@ class RMSHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s: i }", "window_size", &windowSizeIn); if (ret) - throw ConfigError(json, err, "node-config-hook-rms"); + throw JsonError(""_json_pointer, "{}", err.text); if (windowSizeIn < 1) - throw ConfigError(json, "node-config-hook-rms", - "Window size must be greater 0 but is set to {}", - windowSizeIn); + throw JsonError("/window_size"_json_pointer, + "Window size must be greater 0 but is set to {}", + windowSizeIn); windowSize = (unsigned)windowSizeIn; diff --git a/lib/hooks/round.cpp b/lib/hooks/round.cpp index 5cd742995..4363497d5 100644 --- a/lib/hooks/round.cpp +++ b/lib/hooks/round.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -30,7 +31,7 @@ class RoundHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s?: i}", "precision", &precision); if (ret) - throw ConfigError(json, err, "node-config-hook-round"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/scale.cpp b/lib/hooks/scale.cpp index c579cc037..a17a8ff09 100644 --- a/lib/hooks/scale.cpp +++ b/lib/hooks/scale.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -32,7 +33,7 @@ class ScaleHook : public MultiSignalHook { ret = json_unpack_ex(json, &err, 0, "{ s?: F, s?: F }", "scale", &scale, "offset", &offset); if (ret) - throw ConfigError(json, err, "node-config-hook-scale"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/shift_seq.cpp b/lib/hooks/shift_seq.cpp index 426b3db2a..03de86d1b 100644 --- a/lib/hooks/shift_seq.cpp +++ b/lib/hooks/shift_seq.cpp @@ -6,6 +6,7 @@ */ #include +#include #include namespace villas { @@ -29,7 +30,7 @@ class ShiftSequenceHook : public Hook { ret = json_unpack_ex(json, &err, 0, "{ s: i }", "offset", &offset); if (ret) - throw ConfigError(json, err, "node-config-hook-shift_seq"); + throw JsonError(""_json_pointer, "{}", err.text); state = State::PARSED; } diff --git a/lib/hooks/shift_ts.cpp b/lib/hooks/shift_ts.cpp index fb9fe0b1c..53914acf1 100644 --- a/lib/hooks/shift_ts.cpp +++ b/lib/hooks/shift_ts.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -37,7 +38,7 @@ class ShiftTimestampHook : public Hook { ret = json_unpack_ex(json, &err, 0, "{ s?: s, s: F }", "mode", &m, "offset", &o); if (ret) - throw ConfigError(json, err, "node-config-hook-shift_ts"); + throw JsonError(""_json_pointer, "{}", err.text); if (m) { if (!strcmp(m, "origin")) @@ -45,8 +46,7 @@ class ShiftTimestampHook : public Hook { else if (!strcmp(m, "received")) mode = SHIFT_RECEIVED; else - throw ConfigError(json, "node-config-hook-shift_ts-mode", - "Invalid mode parameter '{}'", m); + throw JsonError("/mode"_json_pointer, "Invalid mode parameter '{}'", m); } offset = time_from_double(o); diff --git a/lib/hooks/skip_first.cpp b/lib/hooks/skip_first.cpp index 7a5e06df3..16a3c059f 100644 --- a/lib/hooks/skip_first.cpp +++ b/lib/hooks/skip_first.cpp @@ -6,6 +6,7 @@ */ #include +#include #include #include @@ -65,7 +66,7 @@ class SkipFirstHook : public Hook { return; } - throw ConfigError(json, err, "node-config-hook-skip_first"); + throw JsonError(""_json_pointer, "{}", err.text); } void start() override { diff --git a/lib/hooks/stats.cpp b/lib/hooks/stats.cpp index 69ecc70ae..088ffd8db 100644 --- a/lib/hooks/stats.cpp +++ b/lib/hooks/stats.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -165,14 +166,14 @@ class StatsHook : public Hook { "format", &f, "verbose", &verbose, "warmup", &warmup, "buckets", &buckets, "output", &u); if (ret) - throw ConfigError(json, err, "node-config-hook-stats"); + throw JsonError(""_json_pointer, "{}", err.text); if (f) { try { format = Stats::lookupFormat(f); } catch (const std::invalid_argument &e) { - throw ConfigError(json, "node-config-hook-stats", - "Invalid statistic output format: {}", f); + throw JsonError("/format"_json_pointer, + "Invalid statistic output format: {}", f); } } diff --git a/lib/kernel/tc_netem.cpp b/lib/kernel/tc_netem.cpp index 00134ce21..c08fd3cf9 100644 --- a/lib/kernel/tc_netem.cpp +++ b/lib/kernel/tc_netem.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -73,8 +74,9 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { "jitter", &json_jitter, "loss", &json_loss, "duplicate", &json_duplicate, "corruption", &json_corruption); if (ret) - throw ConfigError(json, err, "node-config-netem", - "Failed to parse setting network emulation settings"); + throw JsonError(""_json_pointer, + "Failed to parse setting network emulation settings: {}", + err.text); struct rtnl_qdisc *ne = rtnl_qdisc_alloc(); if (!ne) @@ -84,18 +86,17 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { if (json_delay_distribution) { if (set_delay_distribution(ne, json_delay_distribution)) - throw ConfigError(json_delay_distribution, - "node-config-netem-distrobution", - "Invalid delay distribution in netem config"); + throw JsonError("/distribution"_json_pointer, + "Invalid delay distribution in netem config"); } if (json_delay_correlation) { double dval = json_number_value(json_delay_correlation); if (!json_is_number(json_delay_correlation) || dval < 0 || dval > 100) - throw ConfigError(json_delay_correlation, - "Setting 'correlation' must be a positive integer " - "within the range [ 0, 100 ]"); + throw JsonError("/correlation"_json_pointer, + "Setting 'correlation' must be a positive integer " + "within the range [ 0, 100 ]"); unsigned *pval = (unsigned *)&val; *pval = (unsigned)rint((dval / 100.) * max_percent_value); @@ -108,8 +109,8 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { val = json_integer_value(json_limit); if (!json_is_integer(json_limit) || val <= 0) - throw ConfigError(json_limit, - "Setting 'limit' must be a positive integer"); + throw JsonError("/limit"_json_pointer, + "Setting 'limit' must be a positive integer"); rtnl_netem_set_limit(ne, val); } else @@ -119,8 +120,8 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { val = json_integer_value(json_delay); if (!json_is_integer(json_delay) || val <= 0) - throw ConfigError(json_delay, - "Setting 'delay' must be a positive integer"); + throw JsonError("/delay"_json_pointer, + "Setting 'delay' must be a positive integer"); rtnl_netem_set_delay(ne, val); } @@ -129,8 +130,8 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { val = json_integer_value(json_jitter); if (!json_is_integer(json_jitter) || val <= 0) - throw ConfigError(json_jitter, - "Setting 'jitter' must be a positive integer"); + throw JsonError("/jitter"_json_pointer, + "Setting 'jitter' must be a positive integer"); rtnl_netem_set_jitter(ne, val); } @@ -139,8 +140,9 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { double dval = json_number_value(json_loss); if (!json_is_number(json_loss) || dval < 0 || dval > 100) - throw ConfigError(json_loss, "Setting 'loss' must be a positive integer " - "within the range [ 0, 100 ]"); + throw JsonError("/loss"_json_pointer, + "Setting 'loss' must be a positive integer " + "within the range [ 0, 100 ]"); unsigned *pval = (unsigned *)&val; *pval = (unsigned)rint((dval / 100.) * max_percent_value); @@ -152,9 +154,9 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { double dval = json_number_value(json_duplicate); if (!json_is_number(json_duplicate) || dval < 0 || dval > 100) - throw ConfigError(json_duplicate, - "Setting 'duplicate' must be a positive integer within " - "the range [ 0, 100 ]"); + throw JsonError("/duplicate"_json_pointer, + "Setting 'duplicate' must be a positive integer within " + "the range [ 0, 100 ]"); unsigned *pval = (unsigned *)&val; *pval = (unsigned)rint((dval / 100.) * max_percent_value); @@ -166,9 +168,9 @@ int villas::kernel::tc::netem_parse(struct rtnl_qdisc **netem, json_t *json) { double dval = json_number_value(json_corruption); if (!json_is_number(json_corruption) || dval < 0 || dval > 100) - throw ConfigError(json_corruption, - "Setting 'corruption' must be a positive integer " - "within the range [ 0, 100 ]"); + throw JsonError("/corruption"_json_pointer, + "Setting 'corruption' must be a positive integer " + "within the range [ 0, 100 ]"); unsigned *pval = (unsigned *)&val; *pval = (unsigned)rint((dval / 100.) * max_percent_value); diff --git a/lib/log.cpp b/lib/log.cpp index cddc7b589..ca5bfb0c7 100644 --- a/lib/log.cpp +++ b/lib/log.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -132,8 +133,8 @@ void Log::parse(json_t *json) { if (json_expressions) { if (!json_is_array(json_expressions)) - throw ConfigError(json_expressions, "node-config-logging-expressions", - "The 'expressions' setting must be a list of objects."); + throw JsonError("/expressions"_json_pointer, + "The 'expressions' setting must be a list of objects."); size_t i; json_t *json_expression; diff --git a/lib/node.cpp b/lib/node.cpp index e3d7eeafc..5b3670ef0 100644 --- a/lib/node.cpp +++ b/lib/node.cpp @@ -21,6 +21,7 @@ extern "C" { #include #include #include +#include #include #include #include @@ -126,16 +127,22 @@ int Node::parse(json_t *json) { return ret; if (enabled) - kernel::tc::netem_parse(&tc_qdisc, json_netem); + JsonError::context("/out/netem"_json_pointer, [&] { + return kernel::tc::netem_parse(&tc_qdisc, json_netem); + }); else tc_qdisc = nullptr; #endif // WITH_NETEM } - if (auto ret = in.parse(json_object_get(json, "in"))) + if (auto ret = JsonError::context("/in"_json_pointer, [&] { + return in.parse(json_object_get(json, "in")); + })) return ret; - if (auto ret = out.parse(json_object_get(json, "out"))) + if (auto ret = JsonError::context("/out"_json_pointer, [&] { + return out.parse(json_object_get(json, "out")); + })) return ret; config = json; @@ -411,8 +418,7 @@ Node *NodeFactory::make(json_t *json, const uuid_t &id, Node *n; if (json_is_object(json)) - throw ConfigError(json, "node-config-node", - "Node configuration must be an object"); + throw JsonError(""_json_pointer, "Node configuration must be an object"); json_t *json_type = json_object_get(json, "type"); @@ -543,7 +549,8 @@ Json NodeFactory::migrate(Json const &json) const { if (dir != json.end() and (!dir->is_object() or dir->contains(setting))) continue; - auto path = JsonPointer{} / std::string(direction) / std::string(setting); + auto path = + ""_json_pointer / std::string(direction) / std::string(setting); patch.push_back(Json::object({ {"op", "add"}, {"path", path.to_string()}, @@ -553,7 +560,7 @@ Json NodeFactory::migrate(Json const &json) const { create = true; } - auto path = JsonPointer{} / std::string(setting); + auto path = ""_json_pointer / std::string(setting); patch.push_back(Json::object({ {"op", "remove"}, {"path", path.to_string()}, @@ -575,7 +582,7 @@ Json NodeFactory::migrate(Json const &json) const { for (auto const &direction : {"in"sv, "out"sv}) { auto dir = json.find(direction); - auto path = JsonPointer{} / std::string(direction) / "signals"; + auto path = ""_json_pointer / std::string(direction) / "signals"; if (dir != json.end() and dir->contains("signals")) { if (auto new_signals = migrate_signal_list(dir->at("signals"))) diff --git a/lib/node_direction.cpp b/lib/node_direction.cpp index 65ccc9178..01f50597d 100644 --- a/lib/node_direction.cpp +++ b/lib/node_direction.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -43,8 +44,8 @@ int NodeDirection::parse(json_t *json) { signals = std::make_shared(); ret = signals->parse(json_signals); if (ret) - throw ConfigError(json_signals, "node-config-node-signals", - "Failed to parse signal definition"); + throw JsonError("/signals"_json_pointer, + "Failed to parse signal definition"); } else { signals = std::make_shared(DEFAULT_SAMPLE_LENGTH, SignalType::FLOAT); @@ -56,7 +57,9 @@ int NodeDirection::parse(json_t *json) { ? (int)Hook::Flags::NODE_WRITE : (int)Hook::Flags::NODE_READ; - hooks.parse(json_hooks, m, nullptr, node); + JsonError::context("/hooks"_json_pointer, [&] { + return hooks.parse(json_hooks, m, nullptr, node); + }); } #endif // WITH_HOOKS diff --git a/lib/nodes/amqp.cpp b/lib/nodes/amqp.cpp index 4eb7df2d1..0fab29f46 100644 --- a/lib/nodes/amqp.cpp +++ b/lib/nodes/amqp.cpp @@ -7,6 +7,7 @@ #include +#include #include #ifdef RABBITMQ_C_NEW_INCLUDE_DIR @@ -162,7 +163,7 @@ int villas::node::amqp_parse(NodeCompat *n, json_t *json) { "password", &password, "port", &port, "exchange", &exchange, "routing_key", &routing_key, "format", &json_format, "ssl", &json_ssl); if (ret) - throw ConfigError(json, err, "node-config-node-amqp"); + throw JsonError(""_json_pointer, "{}", err.text); a->exchange = amqp_bytes_strdup(exchange); a->routing_key = amqp_bytes_strdup(routing_key); @@ -175,8 +176,7 @@ int villas::node::amqp_parse(NodeCompat *n, json_t *json) { ret = amqp_parse_url(a->uri, &a->connection_info); if (ret != AMQP_STATUS_OK) - throw ConfigError(json, "node-config-node-uri", "Failed to parse URI '{}'", - uri); + throw JsonError("/uri"_json_pointer, "Failed to parse URI '{}'", uri); if (json_ssl) { const char *ca_cert = nullptr; @@ -189,8 +189,8 @@ int villas::node::amqp_parse(NodeCompat *n, json_t *json) { &a->ssl_info.verify_hostname, "ca_cert", &ca_cert, "client_key", &client_key, "client_cert", &client_cert); if (ret) - throw ConfigError(json_ssl, err, "node-config-node-amqp-ssl", - "Failed to parse SSL configuration"); + throw JsonError("/ssl"_json_pointer, + "Failed to parse SSL configuration: {}", err.text); if (ca_cert) a->ssl_info.ca_cert = strdup(ca_cert); @@ -205,11 +205,13 @@ int villas::node::amqp_parse(NodeCompat *n, json_t *json) { // Format if (a->formatter) delete a->formatter; - a->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("json"); + a->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("json"); if (!a->formatter) - throw ConfigError(json_format, "node-config-node-amqp-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); return 0; } diff --git a/lib/nodes/can.cpp b/lib/nodes/can.cpp index 2f44857f7..e0ccc7a8b 100644 --- a/lib/nodes/can.cpp +++ b/lib/nodes/can.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -76,19 +77,19 @@ static int can_parse_signal(json_t *json, SignalList::Ptr node_signals, &name, "can_id", &can_id, "can_size", &can_size, "can_offset", &can_offset); if (ret) - throw ConfigError(json, err, "node-config-node-can-signals"); + throw JsonError(""_json_pointer, "{}", err.text); if (can_size > 8 || can_size <= 0) - throw ConfigError(json, "node-config-node-can-can-size", - "can_size of {} for signal '{}' is invalid. You must " - "satisfy 0 < can_size <= 8.", - can_size, name); + throw JsonError("/can_size"_json_pointer, + "can_size of {} for signal '{}' is invalid. You must " + "satisfy 0 < can_size <= 8.", + can_size, name); if (can_offset > 8 || can_offset < 0) - throw ConfigError(json, "node-config-node-can-can-offset", - "can_offset of {} for signal '{}' is invalid. You must " - "satisfy 0 <= can_offset <= 8.", - can_offset, name); + throw JsonError("/can_offset"_json_pointer, + "can_offset of {} for signal '{}' is invalid. You must " + "satisfy 0 <= can_offset <= 8.", + can_offset, name); auto sig = node_signals->getByIndex(signal_index); if ((!name && sig->name.empty()) || (name && sig->name == name)) { @@ -98,10 +99,10 @@ static int can_parse_signal(json_t *json, SignalList::Ptr node_signals, ret = 0; goto out; } else - throw ConfigError(json, "node-config-node-can-signa;s", - "Signal configuration inconsistency detected: Signal " - "with index {} '{}' does not match can_signal '{}'", - signal_index, sig->name, name); + throw JsonError(""_json_pointer, + "Signal configuration inconsistency detected: Signal " + "with index {} '{}' does not match can_signal '{}'", + signal_index, sig->name, name); out: return ret; @@ -123,7 +124,7 @@ int villas::node::can_parse(NodeCompat *n, json_t *json) { "interface_name", &c->interface_name, "in", "signals", &json_in_signals, "out", "signals", &json_out_signals); if (ret) - throw ConfigError(json, err, "node-config-node-can"); + throw JsonError(""_json_pointer, "{}", err.text); c->in = (struct can_signal *)calloc(json_array_size(json_in_signals), sizeof(struct can_signal)); @@ -136,13 +137,17 @@ int villas::node::can_parse(NodeCompat *n, json_t *json) { throw MemoryAllocationError(); json_array_foreach (json_in_signals, i, json_signal) { - ret = can_parse_signal(json_signal, n->in.signals, c->in, i); + ret = JsonError::context("/in/signals"_json_pointer / i, [&] { + return can_parse_signal(json_signal, n->in.signals, c->in, i); + }); if (ret) throw RuntimeError("at signal {}.", i); } json_array_foreach (json_out_signals, i, json_signal) { - ret = can_parse_signal(json_signal, n->out.signals, c->out, i); + ret = JsonError::context("/out/signals"_json_pointer / i, [&] { + return can_parse_signal(json_signal, n->out.signals, c->out, i); + }); if (ret) throw RuntimeError("at signal {}.", i); } diff --git a/lib/nodes/comedi.cpp b/lib/nodes/comedi.cpp index f8c017b38..43e7d0d3c 100644 --- a/lib/nodes/comedi.cpp +++ b/lib/nodes/comedi.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -41,7 +42,7 @@ static int comedi_parse_direction(struct comedi *c, struct comedi_direction *d, "subdevice", &d->subdevice, "bufsize", &d->buffer_size, "signals", &json_chans, "rate", &d->sample_rate_hz); if (ret) - throw ConfigError(json, err, "node-config-node-comedi"); + throw JsonError(""_json_pointer, "{}", err.text); if (!json_is_array(json_chans)) return -1; @@ -54,8 +55,7 @@ static int comedi_parse_direction(struct comedi *c, struct comedi_direction *d, d->chanlist_len = json_array_size(json_chans); if (d->chanlist_len == 0) - throw ConfigError(json_chans, "node-config-node-channels", - "No channels configured"); + throw JsonError("/signals"_json_pointer, "No channels configured"); d->chanlist = new unsigned int[d->chanlist_len]; if (!d->chanlist) @@ -70,11 +70,11 @@ static int comedi_parse_direction(struct comedi *c, struct comedi_direction *d, ret = json_unpack_ex(json_chan, &err, 0, "{ s: i, s: i, s: i }", "channel", &num, "range", &range, "aref", &aref); if (ret) - throw ConfigError(json_chan, err, "node-config-node-comedi"); + throw JsonError("/signals"_json_pointer / i, "{}", err.text); if (aref < AREF_GROUND || aref > AREF_OTHER) - throw ConfigError(json_chan, "node-config-node-comedi-aref", - "Invalid value for analog reference: aref={}", aref); + throw JsonError("/signals"_json_pointer / i / "aref", + "Invalid value for analog reference: aref={}", aref); d->chanlist[i] = CR_PACK(num, range, aref); } @@ -393,7 +393,7 @@ int villas::node::comedi_parse(NodeCompat *n, json_t *json) { &device, "in", &json_in, "out", &json_out); if (ret) - throw ConfigError(json, err, "node-config-node-comedi"); + throw JsonError(""_json_pointer, "{}", err.text); c->in.present = json_in != nullptr; c->in.enabled = false; @@ -404,13 +404,17 @@ int villas::node::comedi_parse(NodeCompat *n, json_t *json) { c->out.running = false; if (c->in.present) { - ret = comedi_parse_direction(c, &c->in, json_in); + ret = JsonError::context("/in"_json_pointer, [&] { + return comedi_parse_direction(c, &c->in, json_in); + }); if (ret) return ret; } if (c->out.present) { - ret = comedi_parse_direction(c, &c->out, json_out); + ret = JsonError::context("/out"_json_pointer, [&] { + return comedi_parse_direction(c, &c->out, json_out); + }); if (ret) return ret; } diff --git a/lib/nodes/ethercat.cpp b/lib/nodes/ethercat.cpp index 2a34ee3bd..40282846e 100644 --- a/lib/nodes/ethercat.cpp +++ b/lib/nodes/ethercat.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -110,7 +111,7 @@ int villas::node::ethercat_type_start(villas::node::SuperNode *sn) { "coupler", "position", &coupler.position, "product_code", &coupler.product_code, "vendor_id", &coupler.vendor_id); if (ret) - throw ConfigError(json.get(), err, "node-config-node-ethercat"); + throw JsonError(""_json_pointer, "{}", err.text); } master = ecrt_request_master(master_id); @@ -153,7 +154,7 @@ int villas::node::ethercat_parse(NodeCompat *n, json_t *json) { &w->in.position, "product_code", &w->in.product_code, "vendor_id", &w->in.vendor_id); if (ret) - throw ConfigError(json, err, "node-config-node-ethercat"); + throw JsonError(""_json_pointer, "{}", err.text); return 0; } diff --git a/lib/nodes/example.cpp b/lib/nodes/example.cpp index 670c3b10d..0e7546b2f 100644 --- a/lib/nodes/example.cpp +++ b/lib/nodes/example.cpp @@ -9,6 +9,7 @@ */ #include +#include #include #include #include @@ -92,7 +93,7 @@ class ExampleNode : public Node { int ret = json_unpack_ex(json, &err, 0, "{ s?: i, s?: s }", "setting1", &setting1, "setting2", &setting2_str); if (ret) - throw ConfigError(json, err, "node-config-node-example"); + throw JsonError(""_json_pointer, "{}", err.text); if (setting2_str) setting2 = setting2_str; diff --git a/lib/nodes/exec.cpp b/lib/nodes/exec.cpp index f82e090df..153d43e8f 100644 --- a/lib/nodes/exec.cpp +++ b/lib/nodes/exec.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -46,7 +47,7 @@ int ExecNode::parse(json_t *json) { &json_exec, "format", &json_format, "flush", &f, "environment", &json_env, "shell", &s, "working_directory", &wd); if (ret) - throw ConfigError(json, err, "node-config-node-exec"); + throw JsonError(""_json_pointer, "{}", err.text); flush = f != 0; shell = s < 0 ? json_is_string(json_exec) : s != 0; @@ -56,27 +57,27 @@ int ExecNode::parse(json_t *json) { if (json_is_string(json_exec)) { if (!shell) - throw ConfigError( - json_exec, "node-config-node-exec-shell", + throw JsonError( + "/exec"_json_pointer, "The exec setting must be an array if shell mode is disabled."); command = json_string_value(json_exec); } else if (json_is_array(json_exec)) { if (shell) - throw ConfigError( - json_exec, "node-config-node-exec-shell", + throw JsonError( + "/exec"_json_pointer, "The exec setting must be a string if shell mode is enabled."); if (json_array_size(json_exec) < 1) - throw ConfigError(json_exec, "node-config-node-exec-exec", - "At least one argument must be given"); + throw JsonError("/exec"_json_pointer, + "At least one argument must be given"); size_t i; json_t *json_arg; json_array_foreach (json_exec, i, json_arg) { if (!json_is_string(json_arg)) - throw ConfigError(json_arg, "node-config-node-exec-exec", - "All arguments must be of string type"); + throw JsonError("/exec"_json_pointer / i, + "All arguments must be of string type"); if (i == 0) command = json_string_value(json_arg); @@ -92,21 +93,23 @@ int ExecNode::parse(json_t *json) { json_object_foreach (json_env, key, json_value) { if (!json_is_string(json_value)) - throw ConfigError(json_value, "node-config-node-exec-environment", - "Environment variables must be of string type"); + throw JsonError("/environment"_json_pointer / key, + "Environment variables must be of string type"); environment[key] = json_string_value(json_value); } } // Format - auto *fmt = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.human"); + auto *fmt = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.human"); formatter = Format::Ptr(fmt); if (!formatter) - throw ConfigError(json_format, "node-config-node-exec-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); state = State::PARSED; diff --git a/lib/nodes/file.cpp b/lib/nodes/file.cpp index 391cea1d1..ce2ffbb70 100644 --- a/lib/nodes/file.cpp +++ b/lib/nodes/file.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -87,7 +88,7 @@ int villas::node::file_parse(NodeCompat *n, json_t *json) { &f->skip_lines, "out", "flush", &f->flush, "buffer_size", &f->buffer_size_out); if (ret) - throw ConfigError(json, err, "node-config-node-file"); + throw JsonError(""_json_pointer, "{}", err.text); f->epoch = time_from_double(epoch_flt); f->uri_tmpl = uri_tmpl ? strdup(uri_tmpl) : nullptr; @@ -95,11 +96,13 @@ int villas::node::file_parse(NodeCompat *n, json_t *json) { // Format if (f->formatter) delete f->formatter; - f->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.human"); + f->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.human"); if (!f->formatter) - throw ConfigError(json_format, "node-config-node-file-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); if (eof) { if (!strcmp(eof, "exit") || !strcmp(eof, "stop")) diff --git a/lib/nodes/fpga.cpp b/lib/nodes/fpga.cpp index 4d4a1a8f6..8c6314468 100644 --- a/lib/nodes/fpga.cpp +++ b/lib/nodes/fpga.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -53,8 +54,8 @@ int FpgaNode::prepare() { } } if (card == nullptr) { - throw ConfigError(config, "node-config-fpga", - "There is no FPGA card with the name: {}", cardName); + throw JsonError("/nodes"_json_pointer / getName() / "card", + "There is no FPGA card with the name: {}", cardName); } } @@ -132,9 +133,9 @@ int FpgaNode::parse(json_t *json) { "low_latency_mode", &lowLatencyMode, "timestep", ×tep); if (ret) { - throw ConfigError(json, err, "node-config-fpga", - "Failed to parse configuration of node {}", - this->getName()); + throw JsonError(""_json_pointer, + "Failed to parse configuration of node {}: {}", + this->getName(), err.text); } if (json_is_string(jsonCard)) { cardName = std::string(json_string_value(jsonCard)); @@ -146,23 +147,24 @@ int FpgaNode::parse(json_t *json) { cardName = "anonymous Card"; } auto searchPath = configPath.substr(0, configPath.rfind("/")); - card = createCard(jsonCard, searchPath, vfioContainer, cardName); + card = JsonError::context("/card"_json_pointer, [&] { + return createCard(jsonCard, searchPath, vfioContainer, cardName); + }); if (card == nullptr) { - throw ConfigError(jsonCard, "node-config-fpga", "Failed to create card"); + throw JsonError("/card"_json_pointer, "Failed to create card"); } else { cards.push_back(card); } } else { - throw ConfigError(jsonCard, "node-config-fpga", - "Failed to parse card name"); + throw JsonError("/card"_json_pointer, "Failed to parse card name"); } if (jsonConnectStrings != nullptr && json_is_array(jsonConnectStrings)) { for (size_t i = 0; i < json_array_size(jsonConnectStrings); i++) { json_t *jsonConnectString = json_array_get(jsonConnectStrings, i); if (jsonConnectString == nullptr || !json_is_string(jsonConnectString)) { - throw ConfigError(jsonConnectString, "node-config-fpga", - "Failed to parse connect string"); + throw JsonError("/connect"_json_pointer / i, + "Failed to parse connect string"); } connectStrings.push_back( std::string(json_string_value(jsonConnectString))); diff --git a/lib/nodes/iec60870.cpp b/lib/nodes/iec60870.cpp index fa8850c63..889b3d277 100644 --- a/lib/nodes/iec60870.cpp +++ b/lib/nodes/iec60870.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -47,7 +48,7 @@ ASDUData ASDUData::parse(json_t *json_signal, std::optional last_data, "asdu_type", &asdu_type_name, "with_timestamp", &with_timestamp, "asdu_type_id", &asdu_type_id, "ioa", &ioa)) - throw ConfigError(json_signal, err, "node-config-node-iec60870-5-104"); + throw JsonError(""_json_pointer, "{}", err.text); // Increase the ioa if it is found twice to make it a sequence if (duplicate_ioa_is_sequence && last_data && @@ -707,7 +708,7 @@ int SlaveNode::parse(json_t *json) { "apci_t1", &apci_t1, "apci_t2", &apci_t2, "apci_t3", &apci_t3, "apci_k", &apci_k, "apci_w", &apci_w); if (ret) - throw ConfigError(json, err, "node-config-node-iec60870-5-104"); + throw JsonError(""_json_pointer, "{}", err.text); if (apci_t0 != -1) server.apci_t0 = apci_t0; @@ -740,7 +741,7 @@ int SlaveNode::parse(json_t *json) { &json_signals, "duplicate_ioa_is_sequence", &duplicate_ioa_is_sequence); if (ret) - throw ConfigError(json_out, err, "node-config-node-iec60870-5-104"); + throw JsonError("/out"_json_pointer, "{}", err.text); } if (json_signals) { @@ -750,8 +751,10 @@ int SlaveNode::parse(json_t *json) { json_array_foreach (json_signals, i, json_signal) { auto signal = signals ? signals->getByIndex(i) : Signal::Ptr{}; - auto asdu_data = - ASDUData::parse(json_signal, last_data, duplicate_ioa_is_sequence); + auto asdu_data = JsonError::context("/out/signals"_json_pointer / i, [&] { + return ASDUData::parse(json_signal, last_data, + duplicate_ioa_is_sequence); + }); last_data = asdu_data; SignalData initial_value; diff --git a/lib/nodes/iec61850_goose.cpp b/lib/nodes/iec61850_goose.cpp index b7b486598..f5af85d24 100644 --- a/lib/nodes/iec61850_goose.cpp +++ b/lib/nodes/iec61850_goose.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -644,7 +645,7 @@ int GooseNode::parse(json_t *json) { "in", &json_in, // "out", &json_out); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); if (json_keys) { size_t index; @@ -653,15 +654,17 @@ int GooseNode::parse(json_t *json) { keys.reserve(json_array_size(json_keys)); json_array_foreach (json_keys, index, json_key) { assert(json_is_object(json_key)); - parseSessionKey(json_key); + JsonError::context("/keys"_json_pointer / index, + [&] { return parseSessionKey(json_key); }); } } if (json_in) - parseInput(json_in); + JsonError::context("/in"_json_pointer, [&] { return parseInput(json_in); }); if (json_out) - parseOutput(json_out); + JsonError::context("/out"_json_pointer, + [&] { return parseOutput(json_out); }); return 0; } @@ -689,7 +692,7 @@ void GooseNode::parseInput(json_t *json) { "interface", &interface_id, // "with_timestamp", &with_timestamp); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); if (routed) { input.local_address = local_address; @@ -713,8 +716,12 @@ void GooseNode::parseInput(json_t *json) { input.interface_id = interface_id; } - parseSubscribers(json_subscribers, input.contexts); - parseInputSignals(json_signals, input.mappings); + JsonError::context("/subscribers"_json_pointer, [&] { + return parseSubscribers(json_subscribers, input.contexts); + }); + JsonError::context("/signals"_json_pointer, [&] { + return parseInputSignals(json_signals, input.mappings); + }); input.with_timestamp = with_timestamp; } @@ -738,7 +745,7 @@ void GooseNode::parseSessionKey(json_t *json) { "string", &data_str, &data_str_len, // "base64", &data_base64, &data_base64_len); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); RSecurityAlgorithm security; if (security_str == "aes_128_gcm"sv) @@ -808,7 +815,7 @@ void GooseNode::parseSubscriber(json_t *json, GooseNode::SubscriberConfig &sc) { "dst_address", &dst_address_str, // "app_id", &app_id); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); sc.go_cb_ref = std::string{go_cb_ref}; @@ -841,7 +848,8 @@ void GooseNode::parseSubscribers( json_object_foreach (json, key, json_subscriber) { SubscriberConfig sc; - parseSubscriber(json_subscriber, sc); + JsonError::context(""_json_pointer / key, + [&] { return parseSubscriber(json_subscriber, sc); }); ctx[key] = InputEventContext{sc}; } @@ -866,7 +874,7 @@ void GooseNode::parseInputSignals( "index", &mapping_index, // "mms_type", &mapping_type_name); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer / index, "{}", err.text); auto mapping_type = GooseSignal::lookupMmsTypeName(mapping_type_name).value(); @@ -911,7 +919,7 @@ void GooseNode::parseOutput(json_t *json) { "interface", &interface_id, // "resend_interval", &output.resend_interval); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); if (!routed) { output.interface_id = interface_id; @@ -936,7 +944,9 @@ void GooseNode::parseOutput(json_t *json) { output.key_id = key_id; } - parsePublishers(json_publishers, output.contexts); + JsonError::context("/publishers"_json_pointer, [&] { + return parsePublishers(json_publishers, output.contexts); + }); } void GooseNode::parsePublisherData(json_t *json, @@ -961,7 +971,7 @@ void GooseNode::parsePublisherData(json_t *json, "value", &json_value, // "mms_bitstring_size", &bitstring_size); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer / index, "{}", err.text); auto goose_type = GooseSignal::lookupMmsTypeName(mms_type).value(); std::optional meta = std::nullopt; @@ -974,7 +984,8 @@ void GooseNode::parsePublisherData(json_t *json, if (json_value) { ret = signal_data.parseJson(goose_type->signal_type, json_value); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer / index / "value", + "Invalid value for MMS type {}", mms_type); } auto signal = std::optional{}; @@ -1021,7 +1032,7 @@ void GooseNode::parsePublisher(json_t *json, PublisherConfig &pc) { "burst", &burst, // "data", &json_data); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-8-1"); + throw JsonError(""_json_pointer, "{}", err.text); if (!output.interface_id.empty()) { std::optional dst_address = stringToMac(dst_address_str); @@ -1041,7 +1052,8 @@ void GooseNode::parsePublisher(json_t *json, PublisherConfig &pc) { pc.time_allowed_to_live = time_allowed_to_live; pc.burst = burst; - parsePublisherData(json_data, pc.data); + JsonError::context("/data"_json_pointer, + [&] { return parsePublisherData(json_data, pc.data); }); } void GooseNode::parsePublishers(json_t *json, std::vector &ctx) { @@ -1051,7 +1063,8 @@ void GooseNode::parsePublishers(json_t *json, std::vector &ctx) { json_array_foreach (json, index, json_publisher) { PublisherConfig pc; - parsePublisher(json_publisher, pc); + JsonError::context(""_json_pointer / index, + [&] { return parsePublisher(json_publisher, pc); }); ctx.push_back(OutputContext{pc}); } diff --git a/lib/nodes/iec61850_sv.cpp b/lib/nodes/iec61850_sv.cpp index b5096956f..89aee05c9 100644 --- a/lib/nodes/iec61850_sv.cpp +++ b/lib/nodes/iec61850_sv.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -181,7 +182,7 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { "out", &json_out, "in", &json_in, "interface", &interface, "app_id", &i->app_id, "dst_address", &dst_address); if (ret) - throw ConfigError(json, err, "node-config-node-iec61850-sv"); + throw JsonError(""_json_pointer, "{}", err.text); if (interface) i->interface = strdup(interface); @@ -189,8 +190,8 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { if (dst_address) { struct ether_addr *addr = ether_aton_r(dst_address, &i->dst_address); if (addr == nullptr) - throw ConfigError(json, "node-config-node-iec61850-sv-dst-address", - "Invalid setting 'dst_address': {}", dst_address); + throw JsonError("/dst_address"_json_pointer, + "Invalid setting 'dst_address': {}", dst_address); } if (json_out) { @@ -202,7 +203,7 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { "smp_mod", &smp_mod, "smp_rate", &i->out.smp_rate, "smp_synch", &smp_synch, "vlan", &json_vlan); if (ret) - throw ConfigError(json_out, err, "node-config-node-iec61850-sv-out"); + throw JsonError("/out"_json_pointer, "{}", err.text); if (json_vlan != nullptr) { int enabled = -1; @@ -223,8 +224,8 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { else if (!strcmp(smp_mod, "seconds_per_sample")) i->out.smp_mod = IEC61850_SV_SMPMOD_SECONDS_PER_SAMPLE; else - throw ConfigError(json_out, "node-config-node-iec61850-sv-out-smp-mod", - "Invalid value '{}' for setting 'smp_mod'", smp_mod); + throw JsonError("/out/smp_mod"_json_pointer, + "Invalid value '{}' for setting 'smp_mod'", smp_mod); } if (smp_synch) { @@ -235,9 +236,9 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { else if (!strcmp(smp_synch, "global_clock")) i->out.smp_synch = IEC61850_SV_SMPSYNC_SYNCED_GLOBAL_CLOCK; else - throw ConfigError( - json_out, "node-config-node-iec61850-sv-out-smp-synch", - "Invalid value '{}' for setting 'smp_synch'", smp_synch); + throw JsonError("/out/smp_synch"_json_pointer, + "Invalid value '{}' for setting 'smp_synch'", + smp_synch); } i->out.sv_id = sv_id ? strdup(sv_id) : nullptr; @@ -245,9 +246,8 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { ret = iec61850_parse_signals(json_signals, &i->out.signals, n->getOutputSignals()); if (ret <= 0) - throw ConfigError(json_signals, - "node-config-node-iec61850-sv-out-signals", - "Failed to parse setting 'signals'"); + throw JsonError("/out/signals"_json_pointer, + "Failed to parse setting 'signals'"); } if (json_in) { @@ -258,7 +258,7 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { json_unpack_ex(json_in, &err, 0, "{ s: o, s?: b }", "signals", &json_signals, "check_dst_address", &check_dst_address); if (ret) - throw ConfigError(json_in, err, "node-config-node-iec61850-in"); + throw JsonError("/in"_json_pointer, "{}", err.text); if (check_dst_address > 0) i->in.check_dst_address = check_dst_address > 0; @@ -266,8 +266,8 @@ int villas::node::iec61850_sv_parse(NodeCompat *n, json_t *json) { ret = iec61850_parse_signals(json_signals, &i->in.signals, n->getInputSignals(false)); if (ret <= 0) - throw ConfigError(json_signals, "node-config-node-iec61850-sv-in-signals", - "Failed to parse setting 'signals'"); + throw JsonError("/in/signals"_json_pointer, + "Failed to parse setting 'signals'"); i->in.total_size = ret; } diff --git a/lib/nodes/infiniband.cpp b/lib/nodes/infiniband.cpp index ab56d3af9..f9b618f83 100644 --- a/lib/nodes/infiniband.cpp +++ b/lib/nodes/infiniband.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -161,7 +162,8 @@ int villas::node::ib_reverse(NodeCompat *n) { int villas::node::ib_parse(NodeCompat *n, json_t *json) { auto *ib = n->getData(); - throw ConfigError(json, "The infiniband node-type is currently broken!"); + throw JsonError(""_json_pointer, + "The infiniband node-type is currently broken!"); int ret; char *local = nullptr, *remote = nullptr, *lasts; @@ -187,7 +189,7 @@ int villas::node::ib_parse(NodeCompat *n, json_t *json) { json_unpack_ex(json, &err, 0, "{ s?: o, s?: o, s?: s }", "in", &json_in, "out", &json_out, "rdma_transport_mode", &transport_mode); if (ret) - throw ConfigError(json, err, "node-config-node-ib"); + throw JsonError(""_json_pointer, "{}", err.text); if (json_in) { ret = json_unpack_ex( @@ -195,7 +197,7 @@ int villas::node::ib_parse(NodeCompat *n, json_t *json) { &local, "cq_size", &recv_cq_size, "max_wrs", &max_recv_wr, "vectorize", &vectorize_in, "buffer_subtraction", &buffer_subtraction); if (ret) - throw ConfigError(json_in, err, "node-config-node-ib-in"); + throw JsonError("/in"_json_pointer, "{}", err.text); } if (json_out) { @@ -208,7 +210,7 @@ int villas::node::ib_parse(NodeCompat *n, json_t *json) { &vectorize_out, "use_fallback", &use_fallback, "periodic_signaling", &ib->periodic_signaling); if (ret) - throw ConfigError(json_out, err, "node-config-node-ib-out"); + throw JsonError("/out"_json_pointer, "{}", err.text); if (remote) { ib->is_source = 1; diff --git a/lib/nodes/influxdb.cpp b/lib/nodes/influxdb.cpp index 9845fdd17..29a272514 100644 --- a/lib/nodes/influxdb.cpp +++ b/lib/nodes/influxdb.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -37,7 +38,7 @@ int villas::node::influxdb_parse(NodeCompat *n, json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: s, s: s }", "server", &server, "key", &key); if (ret) - throw ConfigError(json, err, "node-config-node-influx"); + throw JsonError(""_json_pointer, "{}", err.text); tmp = strdup(server); diff --git a/lib/nodes/kafka.cpp b/lib/nodes/kafka.cpp index 035fd6e74..a952d3aac 100644 --- a/lib/nodes/kafka.cpp +++ b/lib/nodes/kafka.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -174,7 +175,7 @@ int villas::node::kafka_parse(NodeCompat *n, json_t *json) { "client_id", &client_id, "ssl", &json_ssl, "sasl", &json_sasl); if (ret) - throw ConfigError(json, err, "node-config-node-kafka"); + throw JsonError(""_json_pointer, "{}", err.text); k->server = strdup(server); k->produce = produce ? strdup(produce) : nullptr; @@ -185,22 +186,22 @@ int villas::node::kafka_parse(NodeCompat *n, json_t *json) { if (strcmp(protocol, "SSL") && strcmp(protocol, "PLAINTEXT") && strcmp(protocol, "SASL_SSL") && strcmp(protocol, "SASL_PLAINTEXT")) - throw ConfigError(json, "node-config-node-kafka-protocol", - "Invalid security protocol: {}", protocol); + throw JsonError("/protocol"_json_pointer, "Invalid security protocol: {}", + protocol); if (!k->produce && !k->consume) - throw ConfigError(json, "node-config-node-kafka", - "At least one topic has to be specified for node {}", - n->getName()); + throw JsonError(""_json_pointer, + "At least one topic has to be specified for node {}", + n->getName()); if (json_ssl) { const char *ca; ret = json_unpack_ex(json_ssl, &err, 0, "{ s: s }", "ca", &ca); if (ret) - throw ConfigError(json_ssl, err, "node-config-node-kafka-ssl", - "Failed to parse SSL configuration of node {}", - n->getName()); + throw JsonError("/ssl"_json_pointer, + "Failed to parse SSL configuration of node {}: {}", + n->getName(), err.text); k->ssl.ca = strdup(ca); } @@ -214,8 +215,8 @@ int villas::node::kafka_parse(NodeCompat *n, json_t *json) { "mechanisms", &mechanisms, "username", &username, "password", &password); if (ret) - throw ConfigError(json_sasl, err, "node-config-node-kafka-sasl", - "Failed to parse SASL configuration"); + throw JsonError("/sasl"_json_pointer, + "Failed to parse SASL configuration: {}", err.text); k->sasl.mechanisms = strdup(mechanisms); k->sasl.username = strdup(username); @@ -225,11 +226,13 @@ int villas::node::kafka_parse(NodeCompat *n, json_t *json) { // Format if (k->formatter) delete k->formatter; - k->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.binary"); + k->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.binary"); if (!k->formatter) - throw ConfigError(json_format, "node-config-node-kafka-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); return 0; } diff --git a/lib/nodes/loopback.cpp b/lib/nodes/loopback.cpp index a0f844099..4cf045f9b 100644 --- a/lib/nodes/loopback.cpp +++ b/lib/nodes/loopback.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -102,7 +103,7 @@ int LoopbackNode::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: i, s?: s }", "queuelen", &queuelen, "mode", &mode_str); if (ret) - throw ConfigError(json, err, "node-config-node-loopback"); + throw JsonError(""_json_pointer, "{}", err.text); if (mode_str) { if (!strcmp(mode_str, "auto")) @@ -116,8 +117,7 @@ int LoopbackNode::parse(json_t *json) { else if (!strcmp(mode_str, "polling")) mode = QueueSignalledMode::POLLING; else - throw ConfigError(json, "node-config-node-loopback-mode", - "Unknown mode '{}'", mode_str); + throw JsonError("/mode"_json_pointer, "Unknown mode '{}'", mode_str); } return Node::parse(json); diff --git a/lib/nodes/modbus.cpp b/lib/nodes/modbus.cpp index a31ca27c5..01cfff02d 100644 --- a/lib/nodes/modbus.cpp +++ b/lib/nodes/modbus.cpp @@ -41,6 +41,7 @@ #include #include +#include #include #include #include @@ -693,7 +694,7 @@ Rtu Rtu::parse(json_t *json) { &baudrate, "data_bits", &data_bits, "stop_bits", &stop_bits); if (ret) - throw ConfigError(json, err, "node-config-node-modbus-rtu"); + throw JsonError(""_json_pointer, "{}", err.text); Parity parity = parseParity(parity_str); @@ -709,7 +710,7 @@ Tcp Tcp::parse(json_t *json) { int ret = json_unpack_ex(json, &err, 0, "{ s: s, s?: i, s?: i }", "remote", &remote, "port", &port, "unit", &unit_int); if (ret) - throw ConfigError(json, err, "node-config-node-modbus-tcp"); + throw JsonError(""_json_pointer, "{}", err.text); std::optional unit = unit_int >= 0 ? std::optional(unit_int) : std::nullopt; @@ -738,7 +739,7 @@ RegisterMappingSingle RegisterMappingSingle::parse(unsigned int index, "word_endianess", &word_endianess_str, "byte_endianess", &byte_endianess_str, "offset", &offset, "scale", &scale); if (ret) - throw ConfigError(json, err, "node-config-node-modbus-signal"); + throw JsonError(""_json_pointer, "{}", err.text); if (integer_registers != -1 && (integer_registers <= 0 || (size_t)integer_registers > MAX_REGISTERS)) @@ -811,7 +812,9 @@ unsigned int ModbusNode::parseMappings(std::vector &mappings, json_array_foreach (json, i, signal_json) { auto signal = signals->getByIndex(i); - mappings.push_back(RegisterMappingSingle::parse(i, signal, signal_json)); + mappings.push_back(JsonError::context(""_json_pointer / i, [&] { + return RegisterMappingSingle::parse(i, signal, signal_json); + })); } return json_array_size(json); @@ -833,7 +836,7 @@ int ModbusNode::parse(json_t *json) { "reconnect_interval", &reconnect_interval, "min_block_usage", &min_block_usage, "max_block_size", &max_block_size, "rate", &rate, "in", &in_json, "out", &out_json)) - throw ConfigError(json, err, "node-config-node-modbus"); + throw JsonError(""_json_pointer, "{}", err.text); if (in.enabled && rate < 0) throw RuntimeError{"missing polling rate for Modbus reads"}; @@ -843,15 +846,20 @@ int ModbusNode::parse(json_t *json) { else if (!strcmp(transport, "tcp")) connection_settings = Tcp::parse(json); else - throw ConfigError(json, err, "node-config-node-modbus-transport"); + throw JsonError("/transport"_json_pointer, "Invalid transport '{}'", + transport); json_t *signals_json; if (in_json && (signals_json = json_object_get(in_json, "signals"))) - num_in_signals = parseMappings(in_mappings, signals_json); + num_in_signals = JsonError::context("/in/signals"_json_pointer, [&] { + return parseMappings(in_mappings, signals_json); + }); if (out_json && (signals_json = json_object_get(out_json, "signals"))) - num_out_signals = parseMappings(out_mappings, signals_json); + num_out_signals = JsonError::context("/out/signals"_json_pointer, [&] { + return parseMappings(out_mappings, signals_json); + }); return 0; } diff --git a/lib/nodes/mqtt.cpp b/lib/nodes/mqtt.cpp index 3fba0a7b3..a5697cb73 100644 --- a/lib/nodes/mqtt.cpp +++ b/lib/nodes/mqtt.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -181,7 +182,7 @@ int villas::node::mqtt_parse(NodeCompat *n, json_t *json) { &m->keepalive, "retain", &m->retain, "username", &username, "password", &password, "ssl", &json_ssl); if (ret) - throw ConfigError(json, err, "node-config-node-mqtt"); + throw JsonError(""_json_pointer, "{}", err.text); m->host = strdup(host); m->publish = publish ? strdup(publish) : nullptr; @@ -190,9 +191,9 @@ int villas::node::mqtt_parse(NodeCompat *n, json_t *json) { m->password = password ? strdup(password) : nullptr; if (!m->publish && !m->subscribe) - throw ConfigError(json, "node-config-node-mqtt", - "At least one topic has to be specified for node {}", - n->getName()); + throw JsonError(""_json_pointer, + "At least one topic has to be specified for node {}", + n->getName()); if (json_ssl) { m->ssl.enabled = 1; @@ -212,15 +213,15 @@ int villas::node::mqtt_parse(NodeCompat *n, json_t *json) { "cipher", &ciphers, "verify", &m->ssl.cert_reqs, "tls_version", &tls_version); if (ret) - throw ConfigError(json_ssl, err, "node-config-node-mqtt-ssl", - "Failed to parse SSL configuration of node {}", - n->getName()); + throw JsonError("/ssl"_json_pointer, + "Failed to parse SSL configuration of node {}: {}", + n->getName(), err.text); if (m->ssl.enabled && !cafile && !capath) - throw ConfigError(json_ssl, "node-config-node-mqtt-ssl", - "Either 'ssl.cafile' or 'ssl.capath' settings must be " - "set for node {}.", - n->getName()); + throw JsonError("/ssl"_json_pointer, + "Either 'ssl.cafile' or 'ssl.capath' settings must be " + "set for node {}.", + n->getName()); m->ssl.cafile = cafile ? strdup(cafile) : nullptr; m->ssl.capath = capath ? strdup(capath) : nullptr; @@ -232,11 +233,13 @@ int villas::node::mqtt_parse(NodeCompat *n, json_t *json) { // Format if (m->formatter) delete m->formatter; - m->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("json"); + m->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("json"); if (!m->formatter) - throw ConfigError(json_format, "node-config-node-mqtt-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); return 0; } diff --git a/lib/nodes/nanomsg.cpp b/lib/nodes/nanomsg.cpp index 95e4dacab..7da177977 100644 --- a/lib/nodes/nanomsg.cpp +++ b/lib/nodes/nanomsg.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -103,7 +104,7 @@ int villas::node::nanomsg_parse(NodeCompat *n, json_t *json) { &json_out_endpoints, "in", "endpoints", &json_in_endpoints); if (ret) - throw ConfigError(json, err, "node-config-node-nanomsg"); + throw JsonError(""_json_pointer, "{}", err.text); if (json_out_endpoints) { ret = nanomsg_parse_endpoints(&m->out.endpoints, json_out_endpoints); @@ -120,11 +121,13 @@ int villas::node::nanomsg_parse(NodeCompat *n, json_t *json) { // Format if (m->formatter) delete m->formatter; - m->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("json"); + m->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("json"); if (!m->formatter) - throw ConfigError(json_format, "node-config-node-nanomsg-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); return 0; } diff --git a/lib/nodes/ngsi.cpp b/lib/nodes/ngsi.cpp index ba2a0b4a3..89ba51281 100644 --- a/lib/nodes/ngsi.cpp +++ b/lib/nodes/ngsi.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -90,8 +91,7 @@ class NgsiMetadata { ret = json_unpack_ex(json, &err, 0, "{ s: s, s: s, s: s }", "name", &nam, "type", &typ, "value", &val); if (ret) - throw ConfigError(json, "node-config-node-ngsi-metadata", - "Failed to parse NGSI metadata"); + throw JsonError(""_json_pointer, "Failed to parse NGSI metadata"); name = nam; type = typ; @@ -127,8 +127,8 @@ class NgsiAttribute { "ngsi_attribute_name", &nam, "ngsi_attribute_type", &typ, "ngsi_metadatas", &json_metadatas); if (ret) - throw ConfigError(json, err, "node-config-node-ngsi", - "Failed to parse NGSI attribute"); + throw JsonError(""_json_pointer, "Failed to parse NGSI attribute: {}", + err.text); // Copy values from node signal, if 'ngsi_attribute' settings not provided if (s && !nam) @@ -143,14 +143,16 @@ class NgsiAttribute { if (json_metadatas) { if (!json_is_array(json_metadatas)) - throw ConfigError(json_metadatas, "node-config-node-ngsi-metadata", - "ngsi_metadata must be a list of objects"); + throw JsonError("/ngsi_metadatas"_json_pointer, + "ngsi_metadata must be a list of objects"); json_t *json_metadata; // cppcheck-suppress unknownMacro json_array_foreach (json_metadatas, j, json_metadata) - metadata.emplace_back(json_metadata); + JsonError::context("/ngsi_metadatas"_json_pointer / j, [&] { + return metadata.emplace_back(json_metadata); + }); } // Metadata: index(integer)=j @@ -381,7 +383,9 @@ static int ngsi_parse_signals(json_t *json_signals, struct List *ngsi_signals, json_array_foreach (json_signals, j, json_signal) { auto s = node_signals->getByIndex(j); - auto *a = new NgsiAttribute(json_signal, j, s); + auto *a = JsonError::context(""_json_pointer / j, [&] { + return new NgsiAttribute(json_signal, j, s); + }); if (!a) throw MemoryAllocationError(); @@ -597,25 +601,28 @@ int villas::node::ngsi_parse(NodeCompat *n, json_t *json) { "delete", &remove, "in", "signals", &json_signals_in, "out", "signals", &json_signals_out); if (ret) - throw ConfigError(json, err, "node-config-node-ngsi"); + throw JsonError(""_json_pointer, "{}", err.text); i->create = create; i->remove = remove; if (json_signals_in) { - ret = ngsi_parse_signals(json_signals_in, &i->in.signals, n->in.signals); + ret = JsonError::context("/in/signals"_json_pointer, [&] { + return ngsi_parse_signals(json_signals_in, &i->in.signals, n->in.signals); + }); if (ret) - throw ConfigError(json_signals_in, "node-config-node-ngsi-in-signals", - "Invalid setting 'in.signals' of node {}", - n->getName()); + throw JsonError("/in/signals"_json_pointer, + "Invalid setting 'in.signals' of node {}", n->getName()); } if (json_signals_out) { - ret = ngsi_parse_signals(json_signals_out, &i->out.signals, n->out.signals); + ret = JsonError::context("/out/signals"_json_pointer, [&] { + return ngsi_parse_signals(json_signals_out, &i->out.signals, + n->out.signals); + }); if (ret) - throw ConfigError(json_signals_out, "node-config-node-ngsi-out-signals", - "Invalid setting 'out.signals' of node {}", - n->getName()); + throw JsonError("/out/signals"_json_pointer, + "Invalid setting 'out.signals' of node {}", n->getName()); } return 0; diff --git a/lib/nodes/opal_async.cpp b/lib/nodes/opal_async.cpp index e25d0f07e..00ca2f285 100644 --- a/lib/nodes/opal_async.cpp +++ b/lib/nodes/opal_async.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -149,7 +150,7 @@ int OpalAsyncNode::parse(json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: i, s?: { s?: b } }", "id", &id, "in", "reply", &rply); if (ret) - throw ConfigError(json, err, "node-config-node-opal-async"); + throw JsonError(""_json_pointer, "{}", err.text); if (id >= 0) { in.id = id; diff --git a/lib/nodes/opal_orchestra.cpp b/lib/nodes/opal_orchestra.cpp index 5d86388de..28132373b 100644 --- a/lib/nodes/opal_orchestra.cpp +++ b/lib/nodes/opal_orchestra.cpp @@ -27,6 +27,7 @@ __attribute__((weak)) void op_license_feature_register() {} #include #include #include +#include #include #include #include @@ -355,8 +356,7 @@ class OpalOrchestraNode : public Node { std::unordered_map, OpalOrchestraMapping> &mappings) { if (!json_is_array(json)) { - throw ConfigError(json, "node-config-node-opal-orchestra-signals", - "Signals must be an array"); + throw JsonError(""_json_pointer, "Signals must be an array"); } size_t i; @@ -374,8 +374,7 @@ class OpalOrchestraNode : public Node { "orchestra_name", &nme, "orchestra_type", &typ, "orchestra_index", &oi); if (ret) { - throw ConfigError(json_signal, err, - "node-config-node-opal-orchestra-signals"); + throw JsonError(""_json_pointer / i, "{}", err.text); } std::optional orchestraIdx; @@ -439,7 +438,7 @@ class OpalOrchestraNode : public Node { "ddf_overwrite_only", &owo, "rate", &rate, "in", "signals", &json_in_signals, "out", "signals", &json_out_signals); if (ret) { - throw ConfigError(json, err, "node-config-node-opal-orchestra"); + throw JsonError(""_json_pointer, "{}", err.text); } domain.name = dn; @@ -469,31 +468,41 @@ class OpalOrchestraNode : public Node { } if (json_connect_timeout) { - connectTimeout = - parse_duration(json_connect_timeout); + connectTimeout = JsonError::context("/connect_timeout"_json_pointer, [&] { + return parse_duration(json_connect_timeout); + }); } if (json_flag_delay) { - *flagDelay = parse_duration(json_flag_delay); + *flagDelay = JsonError::context("/flag_delay"_json_pointer, [&] { + return parse_duration(json_flag_delay); + }); } if (json_flag_delay_tool) { - *flagDelayTool = - parse_duration(json_flag_delay_tool); + *flagDelayTool = JsonError::context("/flag_delay_tool"_json_pointer, [&] { + return parse_duration(json_flag_delay_tool); + }); } if (json_connection) { - domain.connection = Connection::fromJson(json_connection); + domain.connection = JsonError::context("/connection"_json_pointer, [&] { + return Connection::fromJson(json_connection); + }); } if (json_in_signals) { - parseSignals(json_in_signals, in.getSignals(false), domain.publish, - publishMappings); + JsonError::context("/in/signals"_json_pointer, [&] { + return parseSignals(json_in_signals, in.getSignals(false), + domain.publish, publishMappings); + }); } if (json_out_signals) { - parseSignals(json_out_signals, out.getSignals(false), domain.subscribe, - subscribeMappings); + JsonError::context("/out/signals"_json_pointer, [&] { + return parseSignals(json_out_signals, out.getSignals(false), + domain.subscribe, subscribeMappings); + }); } return 0; diff --git a/lib/nodes/opal_orchestra/ddf.cpp b/lib/nodes/opal_orchestra/ddf.cpp index ac0309b7e..47d48e731 100644 --- a/lib/nodes/opal_orchestra/ddf.cpp +++ b/lib/nodes/opal_orchestra/ddf.cpp @@ -12,6 +12,7 @@ extern "C" { } #include +#include #include #include #include @@ -220,8 +221,9 @@ void ConnectionLocal::parse(json_t *json) { "nic_framework", &nf, "nic_client", &nc, "core_framework", &cf, "core_client", &cc); if (ret) { - throw ConfigError(json, err, "node-config-node-opal-orchestra-connection", - "Failed to parse configuration of local connection"); + throw JsonError(""_json_pointer, + "Failed to parse configuration of local connection: {}", + err.text); } if (ec) { @@ -270,9 +272,10 @@ void ConnectionRemote::parse(json_t *json) { int ret = json_unpack_ex(json, &err, 0, "{ s: s, s: i }", "card", &nme, "pci_index", &pciIndex); if (ret) { - throw ConfigError( - json, err, "node-config-node-opal-orchestra-rfm", - "Failed to parse configuration of Reflective Memory Card (RFM)"); + throw JsonError( + ""_json_pointer, + "Failed to parse configuration of Reflective Memory Card (RFM): {}", + err.text); } name = nme; @@ -301,8 +304,9 @@ void ConnectionDolphin::parse(json_t *json) { json_unpack_ex(json, &err, 0, "{ s: i, s: i }", "node_id_framework", &nodeIdFramework, "segment_id", &segmentId); if (ret) { - throw ConfigError(json, err, "node-config-node-opal-orchestra-connection", - "Failed to parse configuration of dolphin connection"); + throw JsonError(""_json_pointer, + "Failed to parse configuration of dolphin connection: {}", + err.text); } } @@ -312,8 +316,8 @@ std::shared_ptr Connection::fromJson(json_t *json) { int ret = json_unpack_ex(json, &err, 0, "{ s: s, }", "type", &type); if (ret) { - throw ConfigError(json, err, "node-config-node-opal-orchestra-connection", - "Failed to parse connection type"); + throw JsonError(""_json_pointer, "Failed to parse connection type: {}", + err.text); } std::shared_ptr c; @@ -328,8 +332,8 @@ std::shared_ptr Connection::fromJson(json_t *json) { c = std::make_shared(); c->parse(json); } else { - throw ConfigError(json, err, "node-config-node-opal-orchestra-connection", - "Unknown type of connection '{}'", type); + throw JsonError("/type"_json_pointer, "Unknown type of connection '{}'", + type); } return c; diff --git a/lib/nodes/opendss.cpp b/lib/nodes/opendss.cpp index 4dcffe5f9..9057aae59 100644 --- a/lib/nodes/opendss.cpp +++ b/lib/nodes/opendss.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -62,11 +63,11 @@ void OpenDSS::parseData(json_t *json, bool in) { int ret = json_unpack_ex(json_data, &err, 0, "{ s: s, s: s, s: o }", "name", &name, "type", &type, "data", &a_mode); if (ret) - throw ConfigError(json, err, "node-config-node-opendss"); + throw JsonError(""_json_pointer / i, "{}", err.text); if (!json_is_array(a_mode) && a_mode) - throw ConfigError( - a_mode, "node-config-opendssIn", + throw JsonError( + ""_json_pointer / i / "data", "datatype must be configured as a list of name objects"); ele.name = name; @@ -147,18 +148,20 @@ int OpenDSS::parse(json_t *json) { "list", &json_dataOut); if (ret) - throw ConfigError(json, err, "node-config-node-opendss"); + throw JsonError(""_json_pointer, "{}", err.text); if (!json_is_array(json_dataIn) && json_dataIn) - throw ConfigError(json_dataIn, "node-config-opendssIn", - "DataIn must be configured as a list of name objects"); + throw JsonError("/in/list"_json_pointer, + "DataIn must be configured as a list of name objects"); if (!json_is_array(json_dataOut) && json_dataOut) - throw ConfigError(json_dataIn, "node-config-opendssIn", - "DataOut must be configured as a list of name objects"); + throw JsonError("/out/list"_json_pointer, + "DataOut must be configured as a list of name objects"); - parseData(json_dataIn, true); - parseData(json_dataOut, false); + JsonError::context("/in/list"_json_pointer, + [&] { return parseData(json_dataIn, true); }); + JsonError::context("/out/list"_json_pointer, + [&] { return parseData(json_dataOut, false); }); return 0; } diff --git a/lib/nodes/redis.cpp b/lib/nodes/redis.cpp index 939decf97..fc07fb6ba 100644 --- a/lib/nodes/redis.cpp +++ b/lib/nodes/redis.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -325,8 +326,8 @@ int villas::node::redis_parse(NodeCompat *n, json_t *json) { &socket_timeout, "ssl", &json_ssl, "keepalive", &keepalive, "mode", &mode, "key", &key, "channel", &channel, "notify", ¬ify, "rate", &r->rate); if (ret) - throw ConfigError(json, err, "node-config-node-redis", - "Failed to parse node configuration"); + throw JsonError(""_json_pointer, "Failed to parse node configuration: {}", + err.text); if (json_ssl) { #ifdef REDISPP_WITH_TLS @@ -342,8 +343,8 @@ int villas::node::redis_parse(NodeCompat *n, json_t *json) { &enabled, "cacert", &cacert, "cacertdir", &cacertdir, "cert", &cert, "key", &key); if (ret) - throw ConfigError(json, err, "node-config-node-redis-ssl", - "Failed to parse Redis SSL configuration"); + throw JsonError(""_json_pointer, + "Failed to parse Redis SSL configuration: {}", err.text); r->options.tls.enabled = enabled != 0; @@ -355,8 +356,8 @@ int villas::node::redis_parse(NodeCompat *n, json_t *json) { if (host) r->options.tls.sni = host; #else - throw ConfigError(json_ssl, "node-config-node-redis-ssl", - "This built of the redis++ library does not support SSL"); + throw JsonError("/ssl"_json_pointer, + "This built of the redis++ library does not support SSL"); #endif // REDISPP_WITH_TLS } @@ -369,18 +370,19 @@ int villas::node::redis_parse(NodeCompat *n, json_t *json) { else if (!strcmp(mode, "channel") || !strcmp(mode, "pub-sub")) r->mode = RedisMode::CHANNEL; else - throw ConfigError(json, "node-config-node-redis-mode", - "Invalid Redis mode: {}", mode); + throw JsonError("/mode"_json_pointer, "Invalid Redis mode: {}", mode); } // Format if (r->formatter) delete r->formatter; - r->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("json"); + r->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("json"); if (!r->formatter) - throw ConfigError(json_format, "node-config-node-redis-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); if (key && r->mode == RedisMode::KEY) r->key = key; diff --git a/lib/nodes/rtp.cpp b/lib/nodes/rtp.cpp index 8ee172895..063f8608c 100644 --- a/lib/nodes/rtp.cpp +++ b/lib/nodes/rtp.cpp @@ -12,6 +12,7 @@ #include #include +#include #include extern "C" { @@ -128,7 +129,7 @@ int villas::node::rtp_parse(NodeCompat *n, json_t *json) { "format", &json_format, "rtcp", &r->rtcp.enabled, "aimd", &json_aimd, "out", "address", &remote, "in", "address", &local); if (ret) - throw ConfigError(json, err, "node-config-node-rtp"); + throw JsonError(""_json_pointer, "{}", err.text); // AIMD if (json_aimd) { @@ -141,7 +142,7 @@ int villas::node::rtp_parse(NodeCompat *n, json_t *json) { "rate_init", &r->aimd.rate, "log", &log, "hook_type", &hook_type); if (ret) - throw ConfigError(json_aimd, err, "node-config-node-rtp-aimd"); + throw JsonError("/aimd"_json_pointer, "{}", err.text); // AIMD Hook type if (!r->rtcp.enabled) @@ -164,11 +165,13 @@ int villas::node::rtp_parse(NodeCompat *n, json_t *json) { // Format if (r->formatter) delete r->formatter; - r->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.binary"); + r->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.binary"); if (!r->formatter) - throw ConfigError(json_format, "node-config-node-rtp-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); // Remote address ret = sa_decode(&r->out.saddr_rtp, remote, strlen(remote)); diff --git a/lib/nodes/shmem.cpp b/lib/nodes/shmem.cpp index 601fec8ee..095bacf0e 100644 --- a/lib/nodes/shmem.cpp +++ b/lib/nodes/shmem.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -51,7 +52,7 @@ int villas::node::shmem_parse(NodeCompat *n, json_t *json) { "name", &shm->out_name, "in", "name", &shm->in_name, "queuelen", &shm->conf.queuelen, "exec", &json_exec, "mode", &mode_str); if (ret) - throw ConfigError(json, err, "node-config-node-shmem"); + throw JsonError(""_json_pointer, "{}", err.text); if (mode_str) { if (!strcmp(mode_str, "polling")) diff --git a/lib/nodes/signal.cpp b/lib/nodes/signal.cpp index 6dcabbc3a..883890e42 100644 --- a/lib/nodes/signal.cpp +++ b/lib/nodes/signal.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -149,13 +150,13 @@ int SignalNodeSignal::parse(json_t *json) { "stddev", &stddev, "offset", &offset, "pulse_width", &pulse_width, "pulse_low", &pulse_low, "pulse_high", &pulse_high, "phase", &phase); if (ret) - throw ConfigError(json, err, "node-config-node-signal"); + throw JsonError(""_json_pointer, "{}", err.text); try { type = lookupType(type_str); } catch (std::invalid_argument &e) { - throw ConfigError(json, "node-config-node-signal-type", - "Unknown signal type: {}", type_str); + throw JsonError("/signal"_json_pointer, "Unknown signal type: {}", + type_str); } return 0; @@ -209,7 +210,7 @@ int SignalNode::parse(json_t *json) { "realtime", &r, "limit", &limit, "rate", &rate, "monitor_missed", &m, "in", "signals", &json_signals); if (ret) - throw ConfigError(json, err, "node-config-node-signal"); + throw JsonError(""_json_pointer, "{}", err.text); if (r >= 0) rt = r != 0; @@ -220,7 +221,9 @@ int SignalNode::parse(json_t *json) { signals.clear(); unsigned j = 0; json_array_foreach (json_signals, i, json_signal) { - auto sig = SignalNodeSignal(json_signal); + auto sig = JsonError::context("/in/signals"_json_pointer / i, [&] { + return SignalNodeSignal(json_signal); + }); if (sig.type == SignalNodeSignal::Type::MIXED) sig.type = diff --git a/lib/nodes/signal_v1.cpp b/lib/nodes/signal_v1.cpp index 2cf016ff2..15ffe53c4 100644 --- a/lib/nodes/signal_v1.cpp +++ b/lib/nodes/signal_v1.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -176,7 +177,7 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { "pulse_high", &json_pulse_high, "phase", &json_phase, "monitor_missed", &s->monitor_missed); if (ret) - throw ConfigError(json, err, "node-config-node-signal"); + throw JsonError(""_json_pointer, "{}", err.text); struct desc { json_t *json; @@ -205,14 +206,13 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { switch (json_typeof(json_type)) { case JSON_ARRAY: if (json_array_size(json_type) != s->values) - throw ConfigError(json_type, "node-config-node-signal", - "Length of values must match"); + throw JsonError("/signal"_json_pointer, "Length of values must match"); json_array_foreach (json_type, i, json_value) { type_str = json_string_value(json_value); if (!type_str) - throw ConfigError(json_value, "node-config-node-signal", - "Signal type must be a string"); + throw JsonError("/signal"_json_pointer / i, + "Signal type must be a string"); s->type[i] = signal_node_lookup_type(type_str); } @@ -230,8 +230,8 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { break; default: - throw ConfigError(json_type, "node-config-node-signal", - "Invalid setting 'signal' for node {}", n->getName()); + throw JsonError("/signal"_json_pointer, + "Invalid setting 'signal' for node {}", n->getName()); } for (auto &a : arrays) { @@ -244,15 +244,15 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { switch (json_typeof(a.json)) { case JSON_ARRAY: if (json_array_size(a.json) != s->values) - throw ConfigError(a.json, "node-config-node-signal", - "Length of values must match"); + throw JsonError(""_json_pointer / a.name, + "Length of values must match"); size_t i; json_t *json_value; json_array_foreach (a.json, i, json_value) { if (!json_is_number(json_value)) - throw ConfigError( - json_value, "node-config-node-signal", + throw JsonError( + ""_json_pointer / a.name / i, "Values must gives as array of integer or float values!"); (*a.array)[i] = json_number_value(json_value); @@ -268,8 +268,8 @@ int villas::node::signal_node_parse(NodeCompat *n, json_t *json) { break; default: - throw ConfigError( - a.json, "node-config-node-signal", + throw JsonError( + ""_json_pointer / a.name, "Values must given as array or scalar integer or float value!"); } } else { diff --git a/lib/nodes/socket.cpp b/lib/nodes/socket.cpp index bcf49fd69..1cd61648b 100644 --- a/lib/nodes/socket.cpp +++ b/lib/nodes/socket.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -589,16 +590,18 @@ int villas::node::socket_parse(NodeCompat *n, json_t *json) { "address", &local, "verify_source", &s->verify_source, "multicast", &json_multicast); if (ret) - throw ConfigError(json, err, "node-config-node-socket"); + throw JsonError(""_json_pointer, "{}", err.text); // Format if (s->formatter) delete s->formatter; - s->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.binary"); + s->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.binary"); if (!s->formatter) - throw ConfigError(json_format, "node-config-node-socket-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); // IP layer if (layer) { @@ -646,9 +649,8 @@ int villas::node::socket_parse(NodeCompat *n, json_t *json) { "enabled", &s->multicast.enabled, "group", &group, "interface", &interface, "loop", &s->multicast.loop, "ttl", &s->multicast.ttl); if (ret) - throw ConfigError(json_multicast, err, - "node-config-node-socket-multicast", - "Failed to parse multicast settings"); + throw JsonError("/in/multicast"_json_pointer, + "Failed to parse multicast settings: {}", err.text); ret = inet_aton(group, &s->multicast.mreq.imr_multiaddr); if (!ret) diff --git a/lib/nodes/stats.cpp b/lib/nodes/stats.cpp index 74d2facd2..e3e84c86d 100644 --- a/lib/nodes/stats.cpp +++ b/lib/nodes/stats.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -38,7 +39,7 @@ int villas::node::stats_node_signal_parse(struct stats_node_signal *s, ret = json_unpack_ex(json, &err, 0, "{ s: s }", "stats", &stats); if (ret) - throw ConfigError(json, err, "node-config-node-stats"); + throw JsonError(""_json_pointer, "{}", err.text); cpy = strdup(stats); @@ -112,8 +113,9 @@ int villas::node::stats_node_start(NodeCompat *n) { stats_sig->node = nodes.lookup(stats_sig->node_str); if (!stats_sig->node) - throw ConfigError(n->getConfig(), "node-config-node-stats-node", - "Invalid reference node {}", stats_sig->node_str); + throw JsonError("/nodes"_json_pointer / n->getName() / "in" / "signals" / + i / "stats", + "Invalid reference node {}", stats_sig->node_str); } return 0; @@ -170,25 +172,26 @@ int villas::node::stats_node_parse(NodeCompat *n, json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s: F, s: { s: o } }", "rate", &s->rate, "in", "signals", &json_signals); if (ret) - throw ConfigError(json, err, "node-config-node-stats"); + throw JsonError(""_json_pointer, "{}", err.text); if (s->rate <= 0) - throw ConfigError(json, "node-config-node-stats-rate", - "Setting 'rate' must be positive"); + throw JsonError("/rate"_json_pointer, "Setting 'rate' must be positive"); if (!json_is_array(json_signals)) - throw ConfigError(json, "node-config-node-stats-in-signals", - "Setting 'in.signals' must be an array"); + throw JsonError("/in/signals"_json_pointer, + "Setting 'in.signals' must be an array"); json_array_foreach (json_signals, i, json_signal) { auto *stats_sig = new struct stats_node_signal; if (!stats_sig) throw MemoryAllocationError(); - ret = stats_node_signal_parse(stats_sig, json_signal); + ret = JsonError::context("/in/signals"_json_pointer / i, [&] { + return stats_node_signal_parse(stats_sig, json_signal); + }); if (ret) - throw ConfigError(json_signal, "node-config-node-stats-signals", - "Failed to parse statistics signal definition"); + throw JsonError("/in/signals"_json_pointer / i, + "Failed to parse statistics signal definition"); list_push(&s->signals, stats_sig); } diff --git a/lib/nodes/temper.cpp b/lib/nodes/temper.cpp index 662f2f8ce..a5f5364bf 100644 --- a/lib/nodes/temper.cpp +++ b/lib/nodes/temper.cpp @@ -17,6 +17,7 @@ */ #include +#include #include #include #include @@ -297,7 +298,7 @@ int villas::node::temper_parse(NodeCompat *n, json_t *json) { "bus", &t->filter.bus, "port", &t->filter.port); if (ret) - throw ConfigError(json, err, "node-config-node-temper"); + throw JsonError(""_json_pointer, "{}", err.text); return 0; } diff --git a/lib/nodes/test_rtt.cpp b/lib/nodes/test_rtt.cpp index 2959ca6c1..4f361fbd9 100644 --- a/lib/nodes/test_rtt.cpp +++ b/lib/nodes/test_rtt.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -161,7 +162,7 @@ int TestRTT::parse(json_t *json) { &shutdown_, "mode", &mode_str, "count", &count_default, "duration", &duration_default); if (ret) - throw ConfigError(json, err, "node-config-node-test-rtt"); + throw JsonError(""_json_pointer, "{}", err.text); output = output_str; prefix = prefix_str ? prefix_str : getNameShort(); @@ -172,35 +173,37 @@ int TestRTT::parse(json_t *json) { if (mode_str) { mode_default = parseMode(mode_str); if (mode_default == Mode::UNKNOWN) - throw ConfigError(json, "node-config-node-test-rtt-mode", - "Invalid mode: {}. Must be 'min' or 'max'", mode_str); + throw JsonError("/mode"_json_pointer, + "Invalid mode: {}. Must be 'min' or 'max'", mode_str); } // Formatter - auto *fmt = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.human"); + auto *fmt = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.human"); formatter = Format::Ptr(fmt); if (!formatter) - throw ConfigError(json_format, "node-config-node-test-rtt-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); if (json_rates_default && !json_is_array(json_rates_default) && !json_is_number(json_rates_default)) - throw ConfigError( - json_rates_default, "node-config-node-test-rtt-rates", + throw JsonError( + "/rates"_json_pointer, "The 'rates' setting must be a real or an array of real numbers"); if (json_values_default && !json_is_array(json_values_default) && !json_is_integer(json_values_default)) - throw ConfigError( - json_values_default, "node-config-node-test-rtt-values", + throw JsonError( + "/values"_json_pointer, "The 'values' setting must be an integer or an array of integers"); // Construct List of test cases if (!json_is_array(json_cases)) - throw ConfigError(json_cases, "node-config-node-test-rtt-format", - "The 'cases' setting must be an array."); + throw JsonError("/cases"_json_pointer, + "The 'cases' setting must be an array."); int id = 0; json_array_foreach (json_cases, i, json_case) { @@ -224,28 +227,35 @@ int TestRTT::parse(json_t *json) { &duration, "warmup", &warmup, "cooldown", &cooldown, "mode", &mode_str); if (!json_is_array(json_rates) && !json_is_number(json_rates)) - throw ConfigError( - json_case, "node-config-node-test-rtt-rates", + throw JsonError( + (json_rates == json_rates_default + ? "/rates"_json_pointer + : "/cases"_json_pointer / i / "rates"), "The 'rates' setting must be a real or an array of real numbers"); if (!json_is_array(json_values) && !json_is_integer(json_values)) - throw ConfigError( - json_case, "node-config-node-test-rtt-values", + throw JsonError( + (json_values == json_values_default + ? "/values"_json_pointer + : "/cases"_json_pointer / i / "values"), "The 'values' setting must be an integer or an array of integers"); if (mode_str) { mode = parseMode(mode_str); if (mode == Mode::UNKNOWN) - throw ConfigError(json, "node-config-node-test-rtt-mode", - "Invalid mode: {}. Must be 'min' or 'max'", mode_str); + throw JsonError("/cases"_json_pointer / i / "mode", + "Invalid mode: {}. Must be 'min' or 'max'", mode_str); } if (json_is_array(json_rates)) { size_t j; json_array_foreach (json_rates, j, json_val) { if (!json_is_number(json_val)) - throw ConfigError( - json_val, "node-config-node-test-rtt-rates", + throw JsonError( + (json_rates == json_rates_default + ? "/rates"_json_pointer + : "/cases"_json_pointer / i / "rates") / + j, "The 'rates' setting must be an array of real numbers"); rates.push_back(json_integer_value(json_val)); @@ -257,9 +267,11 @@ int TestRTT::parse(json_t *json) { size_t j; json_array_foreach (json_values, j, json_val) { if (!json_is_integer(json_val)) - throw ConfigError( - json_val, "node-config-node-test-rtt-values", - "The 'values' setting must be an array of integers"); + throw JsonError((json_values == json_values_default + ? "/values"_json_pointer + : "/cases"_json_pointer / i / "values") / + j, + "The 'values' setting must be an array of integers"); values.push_back(json_integer_value(json_val)); } diff --git a/lib/nodes/uldaq.cpp b/lib/nodes/uldaq.cpp index 9964fb953..883041847 100644 --- a/lib/nodes/uldaq.cpp +++ b/lib/nodes/uldaq.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -283,13 +284,13 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { &default_range_str, "input_mode", &default_input_mode_str, "sample_clock_source", &sample_clock_source); if (ret) - throw ConfigError(json, err, "node-config-node-uldaq"); + throw JsonError(""_json_pointer, "{}", err.text); if (interface_type) { int iftype = uldaq_parse_interface_type(interface_type); if (iftype < 0) - throw ConfigError(json, "node-config-node-uldaq-interface-type", - "Invalid interface type: {}", interface_type); + throw JsonError("/interface_type"_json_pointer, + "Invalid interface type: {}", interface_type); u->device_interface_type = (DaqDeviceInterface)iftype; } @@ -297,8 +298,8 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { if (sample_clock_source) { int clksrc = uldaq_parse_clock_source(sample_clock_source); if (clksrc < 0) { - throw ConfigError(json, "node-config-node-uldaq-clock_source", - "Invalid clock source type: {}", sample_clock_source); + throw JsonError("/sample_clock_source"_json_pointer, + "Invalid clock source type: {}", sample_clock_source); } u->in.scan_options = (ScanOption)(u->in.scan_options | clksrc); } @@ -319,8 +320,8 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { "range", &range_str, "input_mode", &input_mode_str, "channel", &channel); if (ret) - throw ConfigError(json_signal, err, "node-config-node-uldaq-signal", - "Failed to parse signal configuration"); + throw JsonError("/in/signals"_json_pointer / i, + "Failed to parse signal configuration: {}", err.text); if (!range_str) range_str = default_range_str; @@ -332,22 +333,22 @@ int villas::node::uldaq_parse(NodeCompat *n, json_t *json) { channel = i; if (!range_str) - throw ConfigError(json_signal, err, "node-config-node-uldaq-signal", - "No input range specified for signal {}.", i); + throw JsonError("/in/signals"_json_pointer / i / "range", + "No input range specified for signal {}.", i); if (!input_mode_str) - throw ConfigError(json_signal, err, "node-config-node-uldaq-signal", - "No input mode specified for signal {}.", i); + throw JsonError("/in/signals"_json_pointer / i / "input_mode", + "No input mode specified for signal {}.", i); range = uldaq_parse_range(range_str); if (range < 0) - throw ConfigError(json_signal, err, "node-config-node-uldaq-signal", - "Invalid input range specified for signal {}.", i); + throw JsonError("/in/signals"_json_pointer / i / "range", + "Invalid input range specified for signal {}.", i); input_mode = uldaq_parse_input_mode(input_mode_str); if (input_mode < 0) - throw ConfigError(json_signal, err, "node-config-node-uldaq-signal", - "Invalid input mode specified for signal {}.", i); + throw JsonError("/in/signals"_json_pointer / i / "input_mode", + "Invalid input mode specified for signal {}.", i); u->in.queues[i].range = (Range)range; u->in.queues[i].inputMode = (AiInputMode)input_mode; @@ -390,8 +391,8 @@ int villas::node::uldaq_check(NodeCompat *n) { UlError err; if (n->in.vectorize < 100) - throw ConfigError(n->getConfig(), "node-config-node-vectorize", - "Setting 'vectorize' must be larger than 100"); + throw JsonError("/nodes"_json_pointer / n->getName() / "in" / "vectorize", + "Setting 'vectorize' must be larger than 100"); ret = uldaq_connect(n); if (ret) diff --git a/lib/nodes/webrtc.cpp b/lib/nodes/webrtc.cpp index ef30b380e..78d537c41 100644 --- a/lib/nodes/webrtc.cpp +++ b/lib/nodes/webrtc.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -91,16 +92,16 @@ int WebRTCNode::parse(json_t *json) { rtcConf.iceServers.clear(); if (!json_is_array(json_servers)) - throw ConfigError( - json_servers, "node-config-node-webrtc-ice-servers", + throw JsonError( + "/ice/servers"_json_pointer, "ICE Servers must be a an array of server configurations."); size_t i; json_t *json_server; json_array_foreach (json_servers, i, json_server) { if (!json_is_string(json_server)) - throw ConfigError(json_server, "node-config-node-webrtc-ice-server", - "ICE servers must be provided as STUN/TURN url."); + throw JsonError("/ice/servers"_json_pointer / i, + "ICE servers must be provided as STUN/TURN url."); std::string uri = json_string_value(json_server); @@ -111,12 +112,14 @@ int WebRTCNode::parse(json_t *json) { rtcConf.enableIceTcp = tcp > 0; } - auto *fmt = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.binary"); + auto *fmt = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.binary"); formatter = Format::Ptr(fmt); if (!formatter) - throw ConfigError(json_format, "node-config-node-webrtc-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); return 0; } diff --git a/lib/nodes/websocket.cpp b/lib/nodes/websocket.cpp index bf6b78bb5..1d03a1f4d 100644 --- a/lib/nodes/websocket.cpp +++ b/lib/nodes/websocket.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -560,7 +561,7 @@ int villas::node::websocket_parse(NodeCompat *n, json_t *json) { ret = json_unpack_ex(json, &err, 0, "{ s?: o, s?: b }", "destinations", &json_dests, "wait_connected", &wc); if (ret) - throw ConfigError(json, err, "node-config-node-websocket"); + throw JsonError(""_json_pointer, "{}", err.text); if (wc >= 0) w->wait = wc != 0; @@ -568,18 +569,16 @@ int villas::node::websocket_parse(NodeCompat *n, json_t *json) { list_clear(&w->destinations); if (json_dests) { if (!json_is_array(json_dests)) - throw ConfigError(json_dests, err, - "node-config-node-websocket-destinations", - "The 'destinations' setting must be an array of URLs"); + throw JsonError("/destinations"_json_pointer, + "The 'destinations' setting must be an array of URLs"); json_array_foreach (json_dests, i, json_dest) { const char *uri, *prot, *ads, *path; uri = json_string_value(json_dest); if (!uri) - throw ConfigError( - json_dest, err, "node-config-node-websocket-destinations", - "The 'destinations' setting must be an array of URLs"); + throw JsonError("/destinations"_json_pointer / i, + "The 'destinations' setting must be an array of URLs"); auto *d = new struct websocket_destination; if (!d) @@ -591,14 +590,13 @@ int villas::node::websocket_parse(NodeCompat *n, json_t *json) { ret = lws_parse_uri(d->uri, &prot, &ads, &d->info.port, &path); if (ret) - throw ConfigError(json_dest, err, - "node-config-node-websocket-destinations", - "Failed to parse WebSocket URI: '{}'", uri); + throw JsonError("/destinations"_json_pointer / i, + "Failed to parse WebSocket URI: '{}'", uri); if (strlen(path) == 0) { - throw ConfigError(json_dest, "node-config-node-websocket-destinations", - "Missing node name / path in destination URI: '{}'", - d->uri); + throw JsonError("/destinations"_json_pointer / i, + "Missing node name / path in destination URI: '{}'", + d->uri); } d->info.ssl_connection = !strcmp(prot, "https"); diff --git a/lib/nodes/zeromq.cpp b/lib/nodes/zeromq.cpp index d0009cb45..d195b508a 100644 --- a/lib/nodes/zeromq.cpp +++ b/lib/nodes/zeromq.cpp @@ -14,6 +14,7 @@ #endif #include +#include #include #include #include @@ -113,8 +114,8 @@ static int zeromq_parse_endpoints(json_t *json_ep, struct List *epl) { json_array_foreach (json_ep, i, json_val) { ep = json_string_value(json_val); if (!ep) - throw ConfigError(json_val, "node-config-node-publish", - "All 'publish' settings must be strings"); + throw JsonError(""_json_pointer / i, + "All 'publish' settings must be strings"); list_push(epl, strdup(ep)); } @@ -155,7 +156,7 @@ int villas::node::zeromq_parse(NodeCompat *n, json_t *json) { &json_curve, "pattern", &type, "ipv6", &z->ipv6, "format", &json_format); if (ret) - throw ConfigError(json, err, "node-config-node-zeromq"); + throw JsonError(""_json_pointer, "{}", err.text); z->in.filter = in_filter ? strdup(in_filter) : nullptr; z->out.filter = out_filter ? strdup(out_filter) : nullptr; @@ -163,24 +164,30 @@ int villas::node::zeromq_parse(NodeCompat *n, json_t *json) { // Format if (z->formatter) delete z->formatter; - z->formatter = json_format ? FormatFactory::make(json_format) - : FormatFactory::make("villas.binary"); + z->formatter = + json_format + ? JsonError::context("/format"_json_pointer, + [&] { return FormatFactory::make(json_format); }) + : FormatFactory::make("villas.binary"); if (!z->formatter) - throw ConfigError(json_format, "node-config-node-zeromq-format", - "Invalid format configuration"); + throw JsonError("/format"_json_pointer, "Invalid format configuration"); if (json_out_ep) { - ret = zeromq_parse_endpoints(json_out_ep, &z->out.endpoints); + ret = JsonError::context("/out/publish"_json_pointer, [&] { + return zeromq_parse_endpoints(json_out_ep, &z->out.endpoints); + }); if (ret) - throw ConfigError(json_out_ep, "node-config-node-zeromq-publish", - "Failed to parse list of publish endpoints"); + throw JsonError("/out/publish"_json_pointer, + "Failed to parse list of publish endpoints"); } if (json_in_ep) { - ret = zeromq_parse_endpoints(json_in_ep, &z->in.endpoints); + ret = JsonError::context("/in/subscribe"_json_pointer, [&] { + return zeromq_parse_endpoints(json_in_ep, &z->in.endpoints); + }); if (ret) - throw ConfigError(json_out_ep, "node-config-node-zeromq-subscribe", - "Failed to parse list of subscribe endpoints"); + throw JsonError("/in/subscribe"_json_pointer, + "Failed to parse list of subscribe endpoints"); } if (json_curve) { @@ -192,17 +199,17 @@ int villas::node::zeromq_parse(NodeCompat *n, json_t *json) { "public_key", &public_key, "secret_key", &secret_key, "enabled", &z->curve.enabled); if (ret) - throw ConfigError(json_curve, err, "node-config-node-zeromq-curve", - "Failed to parse setting 'curve'"); + throw JsonError("/curve"_json_pointer, + "Failed to parse setting 'curve': {}", err.text); if (strlen(secret_key) != 40) - throw ConfigError( - json_curve, err, "node-config-node-zeromq-curve", + throw JsonError( + "/curve/secret_key"_json_pointer, "Setting 'curve.secret_key' must be a Z85 encoded CurveZMQ key"); if (strlen(public_key) != 40) - throw ConfigError( - json_curve, err, "node-config-node-zeromq-curve", + throw JsonError( + "/curve/public_key"_json_pointer, "Setting 'curve.public_key' must be a Z85 encoded CurveZMQ key"); memcpy(z->curve.server.public_key, public_key, 41); @@ -211,8 +218,8 @@ int villas::node::zeromq_parse(NodeCompat *n, json_t *json) { // TODO: We should fix this. Its mostly done. if (z->curve.enabled) - throw ConfigError(json_curve, "node-config-zeromq-curve", - "CurveZMQ support is currently broken"); + throw JsonError("/curve"_json_pointer, + "CurveZMQ support is currently broken"); if (type) { if (!strcmp(type, "pubsub")) @@ -222,8 +229,8 @@ int villas::node::zeromq_parse(NodeCompat *n, json_t *json) { z->pattern = zeromq::Pattern::RADIODISH; #endif else - throw ConfigError(json, "node-config-node-zeromq-type", - "Invalid type for ZeroMQ node: {}", n->getNameShort()); + throw JsonError("/pattern"_json_pointer, + "Invalid type for ZeroMQ node: {}", n->getNameShort()); } return 0; diff --git a/lib/path.cpp b/lib/path.cpp index e2f00242a..758156144 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -336,8 +337,8 @@ void Path::parse(json_t *json, NodeList &nodes, const uuid_t sn_uuid) { "original_sequence_no", &original_sequence_no, "uuid", &uuid_str, "affinity", &affinity); if (ret) - throw ConfigError(json, err, "node-config-path", - "Failed to parse path configuration"); + throw JsonError(""_json_pointer, "Failed to parse path configuration: {}", + err.text); if (en >= 0) enabled = en != 0; @@ -352,16 +353,15 @@ void Path::parse(json_t *json, NodeList &nodes, const uuid_t sn_uuid) { else if (!strcmp(mode_str, "all")) mode = Mode::ALL; else - throw ConfigError(json, "node-config-path", "Invalid path mode '{}'", - mode_str); + throw JsonError("/mode"_json_pointer, "Invalid path mode '{}'", mode_str); } // UUID if (uuid_str) { ret = uuid_parse(uuid_str, uuid); if (ret) - throw ConfigError(json, "node-config-path-uuid", - "Failed to parse UUID: {}", uuid_str); + throw JsonError("/uuid"_json_pointer, "Failed to parse UUID: {}", + uuid_str); } else // Generate UUID from hashed config uuid::generateFromJson(uuid, json, sn_uuid); @@ -369,23 +369,22 @@ void Path::parse(json_t *json, NodeList &nodes, const uuid_t sn_uuid) { // Input node(s) ret = mappings.parse(json_in); if (ret) - throw ConfigError(json_in, "node-config-path-in", - "Failed to parse input mapping of path {}", - this->toString()); + throw JsonError("/in"_json_pointer, + "Failed to parse input mapping of path {}", + this->toString()); // Output node(s) NodeList dests; if (json_out) { ret = dests.parse(json_out, nodes); if (ret) - throw ConfigError(json_out, "node-config-path-out", - "Failed to parse output nodes"); + throw JsonError("/out"_json_pointer, "Failed to parse output nodes"); } for (auto *n : dests) { if (n->out.path) - throw ConfigError( - json, "node-config-path", + throw JsonError( + "/out"_json_pointer, "Every node must only be used by a single path as destination"); n->out.path = this; @@ -400,11 +399,14 @@ void Path::parse(json_t *json, NodeList &nodes, const uuid_t sn_uuid) { #ifdef WITH_HOOKS if (json_hooks) - hooks.parse(json_hooks, (int)Hook::Flags::PATH, this, nullptr); + JsonError::context("/hooks"_json_pointer, [&] { + return hooks.parse(json_hooks, (int)Hook::Flags::PATH, this, nullptr); + }); #endif // WITH_HOOKS if (json_mask) - parseMask(json_mask, nodes); + JsonError::context("/mask"_json_pointer, + [&] { return parseMask(json_mask, nodes); }); config = json; state = State::PARSED; @@ -415,8 +417,8 @@ void Path::parseMask(json_t *json_mask, NodeList &nodes) { size_t i; if (!json_is_array(json_mask)) - throw ConfigError(json_mask, "node-config-path-mask", - "The 'mask' setting must be a list of node names"); + throw JsonError(""_json_pointer, + "The 'mask' setting must be a list of node names"); json_array_foreach (json_mask, i, json_entry) { const char *name; @@ -424,13 +426,13 @@ void Path::parseMask(json_t *json_mask, NodeList &nodes) { name = json_string_value(json_entry); if (!name) - throw ConfigError(json_mask, "node-config-path-mask", - "The 'mask' setting must be a list of node names"); + throw JsonError(""_json_pointer / i, + "The 'mask' setting must be a list of node names"); node = nodes.lookup(name); if (!node) - throw ConfigError(json_mask, "node-config-path-mask", - "The 'mask' entry '{}' is not a valid node name", name); + throw JsonError(""_json_pointer / i, + "The 'mask' entry '{}' is not a valid node name", name); masked.push_back(node); } diff --git a/lib/super_node.cpp b/lib/super_node.cpp index 56f3b70ed..63297dd1a 100644 --- a/lib/super_node.cpp +++ b/lib/super_node.cpp @@ -71,6 +71,9 @@ SuperNode::SuperNode(Json config, fs::path search_path) .apply_migrations = true, .apply_defaults = true, }); + + JanssonPtr jansson = this->config; + parse(jansson.get()); } catch (JsonError const &error) { for (auto const &[ptr, msg] : error) { if (not ptr.empty()) @@ -82,8 +85,6 @@ SuperNode::SuperNode(Json config, fs::path search_path) throw RuntimeError("Failed to parse configuration"); } - JanssonPtr jansson = this->config; - parse(jansson.get()); check(); } @@ -302,7 +303,7 @@ void SuperNode::validate(Json &json, const SuperNodeValidateOptions &opts) { if (opts.apply_defaults) json.patch_inplace(default_values); - validate_walk_schema(json, JsonPointer{}, schema.json(), opts); + validate_walk_schema(json, ""_json_pointer, schema.json(), opts); } void SuperNode::parse(json_t *root) { @@ -331,8 +332,8 @@ void SuperNode::parse(json_t *root) { &affinity, "priority", &priority, "idle_stop", &stop, "uuid", &uuid_str, "seed", &seed); if (ret) - throw ConfigError(root, err, "node-config", - "Unpacking top-level config failed"); + throw JsonError(""_json_pointer, "Unpacking top-level config failed: {}", + err.text); if (stop >= 0) { idleStop = stop > 0; @@ -341,23 +342,25 @@ void SuperNode::parse(json_t *root) { if (uuid_str) { ret = uuid_parse(uuid_str, uuid); if (ret) - throw ConfigError(root, "node-config-uuid", "Failed to parse UUID: {}", - uuid_str); + throw JsonError("/uuid"_json_pointer, "Failed to parse UUID: {}", + uuid_str); } #ifdef WITH_WEB if (json_http) - web.parse(json_http); + JsonError::context("/http"_json_pointer, + [&] { return web.parse(json_http); }); #endif // WITH_WEB if (json_logging) - Log::getInstance().parse(json_logging); + JsonError::context("/logging"_json_pointer, + [&] { return Log::getInstance().parse(json_logging); }); // Parse nodes if (json_nodes) { if (!json_is_object(json_nodes)) - throw ConfigError( - json_nodes, "node-config-nodes", + throw JsonError( + "/nodes"_json_pointer, "Setting 'nodes' must be a group with node name => group mappings."); const char *node_name; @@ -372,8 +375,9 @@ void SuperNode::parse(json_t *root) { ret = json_unpack_ex(json_node, &err, 0, "{ s: s }", "type", &node_type); if (ret) - throw ConfigError(root, err, "node-config-node-type", - "Failed to parse type of node '{}'", node_name); + throw JsonError("/nodes"_json_pointer / node_name, + "Failed to parse type of node '{}': {}", node_name, + err.text); // Generate UUID from node name and super-node UUID uuid::generateFromString(node_uuid, node_name, uuid::toString(uuid)); @@ -384,12 +388,13 @@ void SuperNode::parse(json_t *root) { n->configPath = getSearchPath(); - ret = n->parse(json_node); + ret = JsonError::context("/nodes"_json_pointer / node_name, + [&] { return n->parse(json_node); }); if (ret) { auto config_id = fmt::format("node-config-node-{}", node_type); - throw ConfigError(json_node, config_id, - "Failed to parse configuration of node '{}'", - node_name); + throw JsonError("/nodes"_json_pointer / node_name, + "Failed to parse configuration of node '{}'", + node_name); } nodes.push_back(n); @@ -408,7 +413,8 @@ void SuperNode::parse(json_t *root) { if (!p) throw MemoryAllocationError(); - p->parse(json_path, nodes, uuid); + JsonError::context("/paths"_json_pointer / i, + [&] { return p->parse(json_path, nodes, uuid); }); paths.push_back(p); } diff --git a/lib/tool.cpp b/lib/tool.cpp index ba94c76d1..783d8bc28 100644 --- a/lib/tool.cpp +++ b/lib/tool.cpp @@ -7,6 +7,7 @@ #include +#include #include using namespace villas; @@ -60,6 +61,11 @@ int Tool::run() { logger->info(CLR_GRN("Goodbye!")); return ret; + } catch (const JsonError &error) { + for (auto const &[ptr, msg] : error) + logger->error("config[{}]: {}", ptr.empty() ? "/" : ptr.to_string(), msg); + + return -1; } catch (const std::exception &e) { logger->error("{}", e.what()); diff --git a/lib/web.cpp b/lib/web.cpp index a66d401cf..0d720533d 100644 --- a/lib/web.cpp +++ b/lib/web.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -183,7 +184,7 @@ int Web::parse(json_t *json) { json, &err, JSON_STRICT, "{ s?: s, s?: s, s?: i, s?: b }", "ssl_cert", &cert, "ssl_private_key", &pkey, "port", &port, "enabled", &enabled); if (ret) - throw ConfigError(json, err, "node-config-http"); + throw JsonError(""_json_pointer, "{}", err.text); if (cert) ssl_cert = cert;