tutorial-16-server_with_metrics.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright (c) 2022 sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include <signal.h>
  14. #include "echo_pb.srpc.h"
  15. #include "workflow/WFFacilities.h"
  16. #include "srpc/rpc_types.h"
  17. #include "srpc/rpc_metrics_filter.h"
  18. using namespace srpc;
  19. static WFFacilities::WaitGroup wait_group(1);
  20. class ExampleServiceImpl : public Example::Service
  21. {
  22. public:
  23. void Echo(EchoRequest *req, EchoResponse *resp, RPCContext *ctx) override
  24. {
  25. resp->set_message("Hi back");
  26. printf("Server Echo()\nget_req:\n%s\nset_resp:\n%s\n",
  27. req->DebugString().c_str(), resp->DebugString().c_str());
  28. this->filter->histogram("echo_request_size")->observe(req->ByteSizeLong());
  29. for (size_t i = 1; i <= 10; i++)
  30. this->filter->summary("echo_test_quantiles")->observe(0.01 * i);
  31. }
  32. void set_filter(RPCMetricsPull *filter) { this->filter = filter; }
  33. private:
  34. RPCMetricsPull *filter;
  35. };
  36. static void sig_handler(int signo)
  37. {
  38. wait_group.done();
  39. }
  40. int main()
  41. {
  42. GOOGLE_PROTOBUF_VERIFY_VERSION;
  43. signal(SIGINT, sig_handler);
  44. signal(SIGTERM, sig_handler);
  45. SRPCServer server;
  46. ExampleServiceImpl impl;
  47. RPCMetricsPull filter;
  48. filter.init(8080); /* export port for prometheus */
  49. filter.create_histogram("echo_request_size", "Echo request size",
  50. {1, 10, 100});
  51. filter.create_summary("echo_test_quantiles", "Test quantile",
  52. {{0.5, 0.05}, {0.9, 0.01}});
  53. impl.set_filter(&filter);
  54. server.add_filter(&filter);
  55. server.add_service(&impl);
  56. if (server.start(1412) == 0)
  57. {
  58. printf("Server with metrics for Promethes(port:8080) is running on 1412\n"
  59. "Try ./srpc_pb_client to send requests.\n"
  60. "Try ' curl http://localhost:8080/metrics ' to get prometheus data.\n");
  61. wait_group.wait();
  62. server.stop();
  63. }
  64. else
  65. perror("server start");
  66. filter.deinit();
  67. google::protobuf::ShutdownProtobufLibrary();
  68. return 0;
  69. }