From 0fb7786ceff4eaaa82ec46b0a5ecce788ca02ac6 Mon Sep 17 00:00:00 2001 From: eeff <33566201+eeff@users.noreply.github.com> Date: Sun, 9 Oct 2022 18:37:02 +0800 Subject: [PATCH] feat(monitor): add api server --- plugins/monitor/monitor.c | 70 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/plugins/monitor/monitor.c b/plugins/monitor/monitor.c index 3a5421ea..d40c49e9 100644 --- a/plugins/monitor/monitor.c +++ b/plugins/monitor/monitor.c @@ -22,22 +22,90 @@ #include #include +#include #include "monitor.h" +#include "restful/handle.h" #include "utils/log.h" #define neu_plugin_module default_monitor_plugin_module struct neu_plugin { neu_plugin_common_t common; + nng_http_server * api_server; }; +static nng_http_server *server_init() +{ + nng_url * url = NULL; + nng_http_server *server = NULL; + const char * host_port = "http://0.0.0.0:7001"; + + nlog_info("monitor bind url: %s", host_port); + + int ret = nng_url_parse(&url, host_port); + if (0 != ret) { + return NULL; + } + + ret = nng_http_server_hold(&server, url); + if (0 != ret) { + nlog_error("monitor server bind error: %d", ret); + } + + nng_url_free(url); + return server; +} + +static struct neu_rest_handler api_handlers[] = {}; + +static int add_handlers(nng_http_server *server) +{ + struct neu_rest_handler cors = { + .method = NEU_REST_METHOD_OPTIONS, + .type = NEU_REST_HANDLER_FUNCTION, + .value.handler = neu_rest_handle_cors, + }; + + for (size_t i = 0; i < sizeof(api_handlers) / sizeof(api_handlers[0]); + ++i) { + if (0 != neu_rest_add_handler(server, &api_handlers[0])) { + return -1; + } + + cors.url = api_handlers[i].url; + if (0 != neu_rest_add_handler(server, &cors)) { + return -1; + } + } + + return 0; +} + static neu_plugin_t *monitor_plugin_open(void) { neu_plugin_t *plugin = calloc(1, sizeof(neu_plugin_t)); + if (NULL == plugin) { + return NULL; + } neu_plugin_common_init(&plugin->common); + plugin->api_server = server_init(); + if (NULL == plugin->api_server) { + nlog_error("fail to create monitor server"); + free(plugin); + return NULL; + } + + if (0 != add_handlers(plugin->api_server) || + 0 != nng_http_server_start(plugin->api_server)) { + nlog_error("fail to start monitor server"); + nng_http_server_release(plugin->api_server); + free(plugin); + return NULL; + } + return plugin; } @@ -45,6 +113,8 @@ static int monitor_plugin_close(neu_plugin_t *plugin) { int rv = 0; + nng_http_server_stop(plugin->api_server); + nng_http_server_release(plugin->api_server); free(plugin); nlog_info("Success to free plugin: %s", neu_plugin_module.module_name);