1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef GRPC_CORE_LIB_DEBUG_STATS_H
20 #define GRPC_CORE_LIB_DEBUG_STATS_H
21 
22 #include <grpc/support/port_platform.h>
23 
24 #include <string>
25 
26 #include <grpc/support/atm.h>
27 
28 #include "src/core/lib/debug/stats_data.h"
29 #include "src/core/lib/iomgr/exec_ctx.h"
30 
31 typedef struct grpc_stats_data {
32   gpr_atm counters[GRPC_STATS_COUNTER_COUNT];
33   gpr_atm histograms[GRPC_STATS_HISTOGRAM_BUCKETS];
34 } grpc_stats_data;
35 
36 extern grpc_stats_data* grpc_stats_per_cpu_storage;
37 
38 #define GRPC_THREAD_STATS_DATA() \
39   (&grpc_stats_per_cpu_storage[grpc_core::ExecCtx::Get()->starting_cpu()])
40 
41 /* Only collect stats if GRPC_COLLECT_STATS is defined or it is a debug build.
42  */
43 #if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)
44 #define GRPC_STATS_INC_COUNTER(ctr) \
45   (gpr_atm_no_barrier_fetch_add(&GRPC_THREAD_STATS_DATA()->counters[(ctr)], 1))
46 
47 #define GRPC_STATS_INC_HISTOGRAM(histogram, index)                             \
48   (gpr_atm_no_barrier_fetch_add(                                               \
49       &GRPC_THREAD_STATS_DATA()->histograms[histogram##_FIRST_SLOT + (index)], \
50       1))
51 #else /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
52 #define GRPC_STATS_INC_COUNTER(ctr)
53 #define GRPC_STATS_INC_HISTOGRAM(histogram, index)
54 #endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
55 
56 void grpc_stats_init(void);
57 void grpc_stats_shutdown(void);
58 void grpc_stats_collect(grpc_stats_data* output);
59 // c = b-a
60 void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a,
61                      grpc_stats_data* c);
62 std::string grpc_stats_data_as_json(const grpc_stats_data* data);
63 int grpc_stats_histo_find_bucket_slow(int value, const int* table,
64                                       int table_size);
65 double grpc_stats_histo_percentile(const grpc_stats_data* stats,
66                                    grpc_stats_histograms histogram,
67                                    double percentile);
68 size_t grpc_stats_histo_count(const grpc_stats_data* stats,
69                               grpc_stats_histograms histogram);
70 
71 #endif  // GRPC_CORE_LIB_DEBUG_STATS_H
72