diff --git a/examples/README.md b/examples/README.md index 371fd5be..06e06e02 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,19 +2,20 @@ The following examples can help you understand how to use Drogon: -1. [helloworld](https://github.com/an-tao/drogon/tree/master/examples/helloworld) - The multiple ways of "Hello, World!" -2. [client_example](https://github.com/an-tao/drogon/tree/master/examples/client_example/main.cc) - A client example. -3. [websocket_client](https://github.com/an-tao/drogon/tree/master/examples/websocket_client/WebSocketClient.cc) - An example on how to use the WebSocket client -4. [login_session](https://github.com/an-tao/drogon/tree/master/examples/login_session) - How to use the built-in session system to handle login and out -5. [file_upload](https://github.com/an-tao/drogon/tree/master/examples/file_upload) - How to handle file uploads in Drogon -6. [simple_reverse_proxy](https://github.com/an-tao/drogon/tree/master/examples/simple_reverse_proxy) - A Example showing how to use drogon as a http reverse +1. [helloworld](https://github.com/drogonframework/drogon/tree/master/examples/helloworld) - The multiple ways of "Hello, World!" +2. [client_example](https://github.com/drogonframework/drogon/tree/master/examples/client_example/main.cc) - A client example. +3. [websocket_client](https://github.com/drogonframework/drogon/tree/master/examples/websocket_client/WebSocketClient.cc) - An example on how to use the WebSocket client +4. [login_session](https://github.com/drogonframework/drogon/tree/master/examples/login_session) - How to use the built-in session system to handle login and out +5. [file_upload](https://github.com/drogonframework/drogon/tree/master/examples/file_upload) - How to handle file uploads in Drogon +6. [simple_reverse_proxy](https://github.com/drogonframework/drogon/tree/master/examples/simple_reverse_proxy) - A Example showing how to use drogon as a http reverse proxy with a simple round robin. -7. [benchmark](https://github.com/an-tao/drogon/tree/master/examples/benchmark) - Basic benchmark example. see [wiki benchmarks](https://github.com/an-tao/drogon/wiki/13-Benchmarks) -8. [jsonstore](https://github.com/an-tao/drogon/tree/master/examples/jsonstore) - Implementation of a [jsonstore](https://github.com/bluzi/jsonstore)-like storage service that is concurrent and stores in memory. Serving as a showcase on how to build a minimally useful RESTful APIs in Drogon. -9. [redis](https://github.com/an-tao/drogon/tree/master/examples/redis) - A simple example of Redis +7. [benchmark](https://github.com/drogonframework/drogon/tree/master/examples/benchmark) - Basic benchmark example. see [wiki benchmarks](https://github.com/drogonframework/drogon/wiki/13-Benchmarks) +8. [jsonstore](https://github.com/drogonframework/drogon/tree/master/examples/jsonstore) - Implementation of a [jsonstore](https://github.com/bluzi/jsonstore)-like storage service that is concurrent and stores in memory. Serving as a showcase on how to build a minimally useful RESTful APIs in Drogon. +9. [redis](https://github.com/drogonframework/drogon/tree/master/examples/redis) - A simple example of Redis 10. [websocket_server](https://github.com/drogonframework/drogon/tree/master/examples/websocket_server) - Example WebSocker chat room server -11. [redis_cache](https://github.com/an-tao/drogon/tree/master/examples/redis_cache) - An example for using coroutines of redis clients -12. [redis_chat](https://github.com/an-tao/drogon/tree/master/examples/redis_chat) - A chatroom server built with websocket and redis pub/sub service. +11. [redis_cache](https://github.com/drogonframework/drogon/tree/master/examples/redis_cache) - An example for using coroutines of redis clients +12. [redis_chat](https://github.com/drogonframework/drogon/tree/master/examples/redis_chat) - A chatroom server built with websocket and redis pub/sub service. +13. [prometheus_example](https://github.com/drogonframework/drogon/tree/master/examples/prometheus_example) - An example of how to use the Prometheus exporter in Drogon. ### [TechEmpower Framework Benchmarks](https://github.com/TechEmpower/FrameworkBenchmarks) test suite diff --git a/examples/prometheus_example/.gitignore b/examples/prometheus_example/.gitignore new file mode 100644 index 00000000..a44a1475 --- /dev/null +++ b/examples/prometheus_example/.gitignore @@ -0,0 +1,561 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,visualstudio,visualstudiocode,cmake,c,c++ +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,visualstudio,visualstudiocode,cmake,c,c++ + +### C ### +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### C++ ### +# Prerequisites + +# Compiled Object files +*.slo + +# Precompiled Headers + +# Linker files + +# Debugger Files + +# Compiled Dynamic libraries + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai + +# Executables + +### CMake ### +CMakeLists.txt.user +CMakeCache.txt +CMakeFiles +CMakeScripts +Testing +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake +_deps +CMakeUserPresets.json + +### CMake Patch ### +# External projects +*-prefix/ + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignores the whole .idea folder and all .iml files +# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 + +.idea/ + +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +# Sonarlint plugin +.idea/sonarlint + +### VisualStudioCode ### +.vscode/* +!.vscode/tasks.json +!.vscode/launch.json +*.code-workspace + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.meta +*.iobj +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +### VisualStudio Patch ### +# Additional files built by Visual Studio +*.tlog + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,visualstudio,visualstudiocode,cmake,c,c++ diff --git a/examples/prometheus_example/CMakeLists.txt b/examples/prometheus_example/CMakeLists.txt new file mode 100644 index 00000000..addf7e06 --- /dev/null +++ b/examples/prometheus_example/CMakeLists.txt @@ -0,0 +1,75 @@ +cmake_minimum_required(VERSION 3.5) +project(prometheus_example CXX) + +include(CheckIncludeFileCXX) + +check_include_file_cxx(any HAS_ANY) +check_include_file_cxx(string_view HAS_STRING_VIEW) +check_include_file_cxx(coroutine HAS_COROUTINE) +if (NOT "${CMAKE_CXX_STANDARD}" STREQUAL "") + # Do nothing +elseif (HAS_ANY AND HAS_STRING_VIEW AND HAS_COROUTINE) + set(CMAKE_CXX_STANDARD 20) +elseif (HAS_ANY AND HAS_STRING_VIEW) + set(CMAKE_CXX_STANDARD 17) +else () + set(CMAKE_CXX_STANDARD 14) +endif () + +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +add_executable(${PROJECT_NAME} main.cc) + +# ############################################################################## +# If you include the drogon source code locally in your project, use this method +# to add drogon +# add_subdirectory(drogon) +# target_link_libraries(${PROJECT_NAME} PRIVATE drogon) +# +# and comment out the following lines +find_package(Drogon CONFIG REQUIRED) +target_link_libraries(${PROJECT_NAME} PRIVATE Drogon::Drogon) + +# ############################################################################## + +if (CMAKE_CXX_STANDARD LESS 17) + message(FATAL_ERROR "c++17 or higher is required") +elseif (CMAKE_CXX_STANDARD LESS 20) + message(STATUS "use c++17") +else () + message(STATUS "use c++20") +endif () + +aux_source_directory(controllers CTL_SRC) +aux_source_directory(filters FILTER_SRC) +aux_source_directory(plugins PLUGIN_SRC) +aux_source_directory(models MODEL_SRC) + +drogon_create_views(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/views + ${CMAKE_CURRENT_BINARY_DIR}) +# use the following line to create views with namespaces. +# drogon_create_views(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/views +# ${CMAKE_CURRENT_BINARY_DIR} TRUE) +# use the following line to create views with namespace CHANGE_ME prefixed +# and path namespaces. +# drogon_create_views(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/views +# ${CMAKE_CURRENT_BINARY_DIR} TRUE CHANGE_ME) + +target_include_directories(${PROJECT_NAME} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/models) +target_sources(${PROJECT_NAME} + PRIVATE + ${SRC_DIR} + ${CTL_SRC} + ${FILTER_SRC} + ${PLUGIN_SRC} + ${MODEL_SRC}) +# ############################################################################## +# uncomment the following line for dynamically loading views +# set_property(TARGET ${PROJECT_NAME} PROPERTY ENABLE_EXPORTS ON) + +# ############################################################################## + +add_subdirectory(test) diff --git a/examples/prometheus_example/config.json b/examples/prometheus_example/config.json new file mode 100644 index 00000000..efaafb22 --- /dev/null +++ b/examples/prometheus_example/config.json @@ -0,0 +1,33 @@ +{ + + "listeners": [ + { + "address": "0.0.0.0", + "port": 5555, + "https": false + } + ], + "plugins": [ + { + "name": "drogon::plugin::PromExporter", + "dependencies": [], + "config": { + "path": "/metrics", + "collectors":[ + { + "name": "http_requests_total", + "help": "The total number of http requests", + "type": "counter", + "labels": ["method", "path"] + }, + { + "name": "http_request_duration_seconds", + "help": "The processing time of http requests, in seconds", + "type": "histogram", + "labels": ["method", "path"] + } + ] + } + } + ] +} diff --git a/examples/prometheus_example/controllers/PromTestCtrl.cc b/examples/prometheus_example/controllers/PromTestCtrl.cc new file mode 100644 index 00000000..f67930fd --- /dev/null +++ b/examples/prometheus_example/controllers/PromTestCtrl.cc @@ -0,0 +1,27 @@ +#include "PromTestCtrl.h" + +using namespace drogon; + +void PromTestCtrl::fast(const HttpRequestPtr &req, + std::function &&callback) +{ + auto resp = HttpResponse::newHttpResponse(); + resp->setBody("Hello, world!"); + callback(resp); +} + +drogon::AsyncTask PromTestCtrl::slow( + const HttpRequestPtr req, + std::function callback) +{ + // sleep for a random time between 1 and 3 seconds + static std::once_flag flag; + std::call_once(flag, []() { srand(time(nullptr)); }); + auto duration = 1 + (rand() % 3); + auto loop = trantor::EventLoop::getEventLoopOfCurrentThread(); + co_await drogon::sleepCoro(loop, std::chrono::seconds(duration)); + auto resp = HttpResponse::newHttpResponse(); + resp->setBody("Hello, world!"); + callback(resp); + co_return; +} diff --git a/examples/prometheus_example/controllers/PromTestCtrl.h b/examples/prometheus_example/controllers/PromTestCtrl.h new file mode 100644 index 00000000..9712d6b2 --- /dev/null +++ b/examples/prometheus_example/controllers/PromTestCtrl.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +using namespace drogon; + +class PromTestCtrl : public drogon::HttpController +{ + public: + METHOD_LIST_BEGIN + ADD_METHOD_TO(PromTestCtrl::fast, "/fast", "PromStat"); + ADD_METHOD_TO(PromTestCtrl::slow, "/slow", "PromStat"); + METHOD_LIST_END + + void fast(const HttpRequestPtr &req, + std::function &&callback); + drogon::AsyncTask slow( + const HttpRequestPtr req, + std::function callback); +}; diff --git a/examples/prometheus_example/filters/PromStat.cc b/examples/prometheus_example/filters/PromStat.cc new file mode 100644 index 00000000..2a6480f0 --- /dev/null +++ b/examples/prometheus_example/filters/PromStat.cc @@ -0,0 +1,52 @@ +/** + * + * PromStat.cc + * + */ + +#include "PromStat.h" +#include +#include +#include +#include +#include + +using namespace std::literals::chrono_literals; +using namespace drogon; + +Task PromStat::invoke(const HttpRequestPtr &req, + MiddlewareNextAwaiter &&next) +{ + std::string path{req->matchedPathPattern()}; + auto method = req->methodString(); + auto promExporter = app().getPlugin(); + if (promExporter) + { + auto collector = + promExporter->getCollector( + "http_requests_total"); + if (collector) + { + collector->metric({method, path})->increment(); + } + } + auto start = trantor::Date::date(); + auto resp = co_await next; + if (promExporter) + { + auto collector = + promExporter->getCollector( + "http_request_duration_seconds"); + if (collector) + { + static const std::vector boundaries{ + 0.0001, 0.001, 0.01, 0.1, 0.5, 1, 2, 3}; + auto end = trantor::Date::date(); + auto duration = + end.microSecondsSinceEpoch() - start.microSecondsSinceEpoch(); + collector->metric({method, path}, boundaries, 1h, 6) + ->observe((double)duration / 1000000); + } + } + co_return resp; +} diff --git a/examples/prometheus_example/filters/PromStat.h b/examples/prometheus_example/filters/PromStat.h new file mode 100644 index 00000000..b60b6ab5 --- /dev/null +++ b/examples/prometheus_example/filters/PromStat.h @@ -0,0 +1,27 @@ +/** + * + * PromStat.h + * + */ + +#pragma once + +#include + +using namespace drogon; + +class PromStat : public HttpCoroMiddleware +{ + public: + PromStat() + { + void(0); + } + + virtual ~PromStat() + { + } + + Task invoke(const HttpRequestPtr &req, + MiddlewareNextAwaiter &&next) override; +}; diff --git a/examples/prometheus_example/main.cc b/examples/prometheus_example/main.cc new file mode 100644 index 00000000..217a84aa --- /dev/null +++ b/examples/prometheus_example/main.cc @@ -0,0 +1,7 @@ +#include + +int main() +{ + drogon::app().loadConfigFile("../config.json").run(); + return 0; +} diff --git a/examples/prometheus_example/test/CMakeLists.txt b/examples/prometheus_example/test/CMakeLists.txt new file mode 100644 index 00000000..346af7ce --- /dev/null +++ b/examples/prometheus_example/test/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.5) +project(prometheus_example_test CXX) + +add_executable(${PROJECT_NAME} test_main.cc) + +# ############################################################################## +# If you include the drogon source code locally in your project, use this method +# to add drogon +# target_link_libraries(${PROJECT_NAME} PRIVATE drogon) +# +# and comment out the following lines +target_link_libraries(${PROJECT_NAME} PRIVATE Drogon::Drogon) + +ParseAndAddDrogonTests(${PROJECT_NAME}) diff --git a/examples/prometheus_example/test/test_main.cc b/examples/prometheus_example/test/test_main.cc new file mode 100644 index 00000000..a86bb053 --- /dev/null +++ b/examples/prometheus_example/test/test_main.cc @@ -0,0 +1,32 @@ +#define DROGON_TEST_MAIN +#include +#include + +DROGON_TEST(BasicTest) +{ + // Add your tests here +} + +int main(int argc, char **argv) +{ + using namespace drogon; + + std::promise p1; + std::future f1 = p1.get_future(); + + // Start the main loop on another thread + std::thread thr([&]() { + // Queues the promise to be fulfilled after starting the loop + app().getLoop()->queueInLoop([&p1]() { p1.set_value(); }); + app().run(); + }); + + // The future is only satisfied after the event loop started + f1.get(); + int status = test::run(argc, argv); + + // Ask the event loop to shutdown and wait + app().getLoop()->queueInLoop([]() { app().quit(); }); + thr.join(); + return status; +} diff --git a/lib/inc/drogon/utils/monitoring/Collector.h b/lib/inc/drogon/utils/monitoring/Collector.h index b46bcefd..4c362694 100644 --- a/lib/inc/drogon/utils/monitoring/Collector.h +++ b/lib/inc/drogon/utils/monitoring/Collector.h @@ -60,8 +60,10 @@ class Collector : public CollectorBase { } + template const std::shared_ptr &metric( - const std::vector &labelValues) noexcept(false) + const std::vector &labelValues, + Arguments... args) noexcept(false) { if (labelValues.size() != labelsNames_.size()) { @@ -75,7 +77,8 @@ class Collector : public CollectorBase { return iter->second; } - auto metric = std::make_shared(name_, labelsNames_, labelValues); + auto metric = + std::make_shared(name_, labelsNames_, labelValues, args...); metrics_[labelValues] = metric; return metrics_[labelValues]; } diff --git a/lib/inc/drogon/utils/monitoring/Histogram.h b/lib/inc/drogon/utils/monitoring/Histogram.h index cea92d89..f46b5c8d 100644 --- a/lib/inc/drogon/utils/monitoring/Histogram.h +++ b/lib/inc/drogon/utils/monitoring/Histogram.h @@ -68,6 +68,7 @@ class DROGON_EXPORT Histogram : public Metric } } timeBuckets_.emplace_back(); + timeBuckets_.back().buckets.resize(bucketBoundaries.size() + 1); // check the bucket boundaries are sorted for (size_t i = 1; i < bucketBoundaries.size(); i++) { diff --git a/lib/src/PromExporter.cc b/lib/src/PromExporter.cc index 990e95f3..65941411 100644 --- a/lib/src/PromExporter.cc +++ b/lib/src/PromExporter.cc @@ -12,7 +12,7 @@ using namespace drogon::plugin; void PromExporter::initAndStart(const Json::Value &config) { path_ = config.get("path", path_).asString(); - LOG_ERROR << path_; + LOG_TRACE << path_; auto &app = drogon::app(); std::weak_ptr weakPtr = shared_from_this(); app.registerHandler( @@ -130,7 +130,7 @@ static std::string exportCollector( auto const &samples = sampleGroup.samples; for (auto &sample : samples) { - res.append(metricPtr->name()); + res.append(sample.name); if (!sample.exLabels.empty() || !metricPtr->labels().empty()) { res.append("{");