feat(monitor): add api server

This commit is contained in:
eeff
2022-10-09 18:37:02 +08:00
parent b22120eb07
commit 0fb7786cef
+70
View File
@@ -22,22 +22,90 @@
#include <string.h>
#include <nng/nng.h>
#include <nng/supplemental/http/http.h>
#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);