Add USDT sample (#1229)
[platform/upstream/bcc.git] / examples / usdt_sample / usdt_sample_lib1 / src / lib1.cpp
1 #include "usdt_sample_lib1/lib1.h"
2
3 // std
4 #include <atomic>
5 #include <chrono>
6 #include <iostream>
7 #include <thread>
8
9 // usdt_sample_lib1
10 #include "folly/tracing/StaticTracepoint.h"
11
12 // When using systemtap-sdt-devel, the following file should be included:
13 // #include "usdt_sample_lib1/lib1_sdt.h"
14
15 OperationRequest::OperationRequest(const std::string& input_)
16     : _input(input_)
17 {
18 }
19
20 OperationResponse::OperationResponse(const std::string& output_)
21     : _output(output_)
22 {
23 }
24
25 OperationProvider::OperationProvider(std::uint32_t minLatencyMs_, std::uint32_t maxLatencyMs_)
26     : _gen(std::random_device()())
27     , _dis(minLatencyMs_, maxLatencyMs_)
28 {
29 }
30
31 std::shared_future<OperationResponse> OperationProvider::executeAsync(const OperationRequest& request)
32 {
33     static std::atomic<std::uint64_t> operationIdCounter(0);
34     std::uint64_t operationId = operationIdCounter++;
35
36     FOLLY_SDT(usdt_sample_lib1, operation_start, operationId, request.input().c_str());
37
38 /* Below an example of how to use this sample with systemtap-sdt-devel:
39     if (USDT_SAMPLE_LIB1_OPERATION_START_ENABLED()) {
40         //std::cout << "operation_start probe enabled." << std::endl;
41         USDT_SAMPLE_LIB1_OPERATION_START(operationId, &inputBuf);
42     }
43 */
44
45     auto latencyMs = _dis(_gen);
46
47     return std::async(std::launch::async, [latencyMs, operationId, request]() {
48         std::this_thread::sleep_for(std::chrono::milliseconds(latencyMs));
49
50         auto output = std::string("resp_") + request.input();
51         OperationResponse response(output);
52
53         FOLLY_SDT(usdt_sample_lib1, operation_end, operationId, response.output().c_str());
54
55 /* Below an example of how to use this sample with systemtap-sdt-devel:
56         if (USDT_SAMPLE_LIB1_OPERATION_END_ENABLED()) {
57             //std::cout << "operation_end probe enabled." << std::endl;
58             USDT_SAMPLE_LIB1_OPERATION_END(operationId, &outputBuf);
59         }
60 */
61
62         return response;
63     });
64 }