-
Notifications
You must be signed in to change notification settings - Fork 103
/
apm.c
2159 lines (1877 loc) · 53.8 KB
/
apm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Tempesta FW
*
* Copyright (C) 2016-2024 Tempesta Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Prototype for fast percentiles calculation.
*/
#include <linux/atomic.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/stringify.h>
#undef DEBUG
#if DBG_APM > 0
#define DEBUG DBG_APM
#endif
#include "lib/str.h"
#include "apm.h"
#include "cfg.h"
#include "log.h"
#include "pool.h"
#include "http.h"
/*
* The algorithm is constructed to be as efficient as possible. That's
* done by sacrificing the accuracy and giving possibly inexact answers
* to questions asked by users. The main concepts and requirements are:
*
* 1. Small O(1) update time with only few conditions and cache line accesses;
*
* 2. Very fast O(1) calculation of several percentiles in parallel;
*
* 3. Very small overall memory footprint for inexpensive handling of
* performance trends of many servers;
*
* 4. Buckets must be dynamically rearranged since server response times
* are unknown apriori;
*
* 5. The adjustments of buckets must be performed in a lock-less fashion
* in a multi-core environment;
*
* 6. If a user asks for Nth percentile, e.g. 75th, an inaccurate value
* may be returned that is in fact for a different percentile, e.g.
* 81st. That is very possible if there is insufficient data for an
* accurate percentiles calculation.
*/
/*
* Response time statistics data structures.
*
* A time range is split into a number of buckets, such that each bucket
* is efficiently calculated as @begin + (1 << @order).
*
* @order - The order of a range. The ranges grow logarithmically.
* Motivation: time estimation error becomes negligible as
* the time grows, so higher response times may be estimated
* with less accuracy;
* @begin - the start response time value of a range;
* @end - the end response time value of a range;
* @atomic - atomic control handler to update all control fields
* above atomically with a single write operation;
* @tot_cnt - global hits counter for all ranges;
* @tot_val - the sum of all response time values, for AVG calculation;
* @min_val - the minimum response time value;
* @max_val - the maximum response time value;
* @cnt - the number of hits with a specific response time that
* fall to a specific bucket in a range.
*
* Keep the members cache line aligned to minimize false sharing: each range
* is placed on a separate cache line, and control handlers are also on their
* own cache lines.
*/
#define TFW_STATS_RANGES 4
#define TFW_STATS_RLAST (TFW_STATS_RANGES - 1)
#define TFW_STATS_BCKTS_ORDER 4
#define TFW_STATS_BCKTS (1 << TFW_STATS_BCKTS_ORDER)
#define TFW_STATS_RSPAN(order) ((TFW_STATS_BCKTS - 1) << (order))
#define TFW_STATS_RSPAN_UL(order) ((TFW_STATS_BCKTS - 1UL) << (order))
typedef struct {
unsigned int order;
unsigned int begin;
unsigned int end;
} TfwPcntCtl;
typedef struct {
TfwPcntCtl ctl[TFW_STATS_RANGES];
char __reset_from[0];
unsigned long tot_cnt;
unsigned long tot_val;
unsigned long min_val;
unsigned long max_val;
unsigned long cnt[TFW_STATS_RANGES][TFW_STATS_BCKTS];
char __reset_till[0];
} TfwPcntRanges __attribute__((aligned(L1_CACHE_BYTES)));
static inline unsigned long *
__rng(TfwPcntCtl *pc, unsigned long *cnt, unsigned int r_time)
{
if (r_time <= pc->begin)
return &cnt[0];
return &cnt[(r_time - pc->begin + ((1 << pc->order) - 1)) >> pc->order];
}
static void
__range_grow_right(TfwPcntRanges *rng, TfwPcntCtl *pc, int r)
{
int i;
++pc->order;
pc->end = pc->begin + TFW_STATS_RSPAN(pc->order);
T_DBG3(" -- extend right bound of range %d to begin=%u order=%u"
" end=%u\n", r, pc->begin, pc->order, pc->end);
/* Coalesce counters to buckets on the left half of the range. */
for (i = 0; i < TFW_STATS_BCKTS / 2; ++i)
rng->cnt[r][i] = rng->cnt[r][2 * i] + rng->cnt[r][2 * i + 1];
}
static void
__range_shrink_left(TfwPcntRanges *rng, TfwPcntCtl *pc, int r)
{
int i;
unsigned long cnt_full, cnt_half;
--pc->order;
pc->begin = pc->end - TFW_STATS_RSPAN(pc->order);
T_DBG3(" -- shrink left bound of range %d to begin=%u order=%u"
" end=%u\n", r, pc->begin, pc->order, pc->end);
/*
* Write sum of the left half counters to the first bucket and equally
* split counters of the right half among the rest of the buckets.
*/
for (i = 1; i < TFW_STATS_BCKTS / 2; ++i)
rng->cnt[r][0] += rng->cnt[r][i];
cnt_full = rng->cnt[r][TFW_STATS_BCKTS / 2];
cnt_half = cnt_full / 2;
rng->cnt[r][0] += cnt_half;
rng->cnt[r][1] = cnt_full - cnt_half;
for (i = 1; i < TFW_STATS_BCKTS / 2; ++i) {
cnt_full = rng->cnt[r][TFW_STATS_BCKTS / 2 + i];
cnt_half = cnt_full / 2;
rng->cnt[r][i * 2] = cnt_half;
rng->cnt[r][i * 2 + 1] = cnt_full - cnt_half;
}
}
/**
* Extend the last range so that larger response times can be handled.
*/
static void
tfw_stats_extend(TfwPcntRanges *rng, unsigned int r_time)
{
int i, b;
unsigned long end;
TfwPcntCtl *pc = &rng->ctl[TFW_STATS_RLAST];
unsigned int sum, parts, units, shift, order = pc->order;
BUILD_BUG_ON_NOT_POWER_OF_2(TFW_STATS_BCKTS);
do {
++order;
end = pc->begin + TFW_STATS_RSPAN_UL(order);
} while (end < r_time);
/*
* It's conceivable that the value of pc->end was already near
* the upper end of the range that the data type could hold.
* As the value was extended to the next order it's conceivable
* that the new value exceeded the maximum for the data type.
* Considering that TfwPcntCtl{}->end is of type unsigned int,
* it's totally unimaginable that this situation may ever happen.
*/
BUG_ON(end >= (1UL << (sizeof_field(TfwPcntCtl, end) * 8)));
pc->end = end;
shift = min_t(unsigned int, order - pc->order, TFW_STATS_BCKTS_ORDER);
units = 1 << shift;
parts = TFW_STATS_BCKTS >> shift;
pc->order = order;
T_DBG3(" -- extend last range to begin=%u order=%u end=%u\n",
pc->begin, pc->order, pc->end);
/*
* Coalesce counters to buckets on the left side of the range.
* Clear the buckets that represent the new extended range.
*/
for (i = 0; i < parts; ++i) {
switch (units) {
case 2:
rng->cnt[TFW_STATS_RLAST][i] =
rng->cnt[TFW_STATS_RLAST][2 * i]
+ rng->cnt[TFW_STATS_RLAST][2 * i + 1];
break;
case 4:
rng->cnt[TFW_STATS_RLAST][i] =
rng->cnt[TFW_STATS_RLAST][4 * i]
+ rng->cnt[TFW_STATS_RLAST][4 * i + 1]
+ rng->cnt[TFW_STATS_RLAST][4 * i + 2]
+ rng->cnt[TFW_STATS_RLAST][4 * i + 3];
break;
default:
sum = 0;
for (b = i * units; b < (i + 1) * units; ++b)
sum += rng->cnt[TFW_STATS_RLAST][b];
rng->cnt[TFW_STATS_RLAST][i] = sum;
break;
}
}
memset(&rng->cnt[TFW_STATS_RLAST][parts], 0,
sizeof(rng->cnt[0][0]) * (TFW_STATS_BCKTS - parts));
}
/**
* See if range @r contains large outliers. Adjust it if so.
*
* The leftmost bound is fixed to 1ms. The rightmost bound is only growing
* to handle large values. So the adjustment may either increase the gaps
* between ranges by decreasing a range order and moving left range bounds,
* or decrease the gaps by increasing a range order and moving right range
* bounds. I.e. ranges worm to the right and the algorithm converges at the
* largest response time faced.
*/
static void
tfw_stats_adjust(TfwPcntRanges *rng, int r)
{
int i;
TfwPcntCtl *pc, *prepc;
unsigned long prend, cnt = 0, sum = 0, max = 0, i_max = 0;
BUG_ON(r == 0);
for (i = 0; i < TFW_STATS_BCKTS; ++i) {
if (rng->cnt[r][i]) {
sum += rng->cnt[r][i];
++cnt;
}
if (max < rng->cnt[r][i]) {
max = rng->cnt[r][i];
i_max = i;
}
}
BUG_ON(!cnt);
/* outlier means (max < avg * 2) */
if (likely(max <= sum * 2 / cnt))
return;
T_DBG3(" -- range %d has an outlier %lu (avg=%lu total=%lu) at"
" bucket %lu\n", r, max, sum / cnt, sum, i_max);
/*
* If too many hits fall in the gap between r'th and (r - 1)'th
* ranges, and (r - 1)'th range can grow, then grow that range
* and spread these hits evenly in the right half of (r - 1)'th
* range as a rough approximation. Afterwards, move on to reduce
* the range order. The first bucket gets a higher count. Since
* the left bound has been moved, the right bound of (r - 1)'th
* range will be moved next time.
*/
pc = &rng->ctl[r];
prepc = &rng->ctl[r - 1];
prend = prepc->begin + TFW_STATS_RSPAN_UL(prepc->order + 1);
if ((i_max == 0) && (prend < pc->begin)) {
__range_grow_right(rng, prepc, r - 1);
cnt = max / (TFW_STATS_BCKTS / 2 + 1);
rng->cnt[r][0] -= cnt * (TFW_STATS_BCKTS / 2);
for (i = TFW_STATS_BCKTS / 2; i < TFW_STATS_BCKTS; ++i)
rng->cnt[r - 1][i] = cnt;
}
/*
* The range order is too big. Reduce it by moving the left bound.
* If servers are too fast (all responses within 1ms), then there's
* nothing to do here.
*/
if (likely(pc->order))
__range_shrink_left(rng, pc, r);
}
/*
* Set the new maximum value.
* Return true if the new value has been set.
* Return false if the maximum value remained the same.
*/
static inline bool
tfw_stats_adj_max(TfwPcntRanges *rng, unsigned int r_time)
{
if (r_time > rng->max_val) {
rng->max_val = r_time;
return true;
}
return false;
}
/*
* Set the new minimum value.
* Return true if the new value has been set.
* Return false if the minimum value remained the same.
*/
static inline bool
tfw_stats_adj_min(TfwPcntRanges *rng, unsigned int r_time)
{
if (r_time < rng->min_val) {
rng->min_val = r_time;
return true;
}
return false;
}
/**
* Update server response time statistic.
* @r_time is in milliseconds (1/HZ second), use jiffies to get it.
*/
static void
tfw_stats_update(TfwPcntRanges *rng, unsigned int r_time)
{
TfwPcntCtl *pc3, *pc2 = &rng->ctl[2];
/* Binary search of an appropriate range. */
if (r_time <= pc2->end) {
TfwPcntCtl *pc0, *pc1 = &rng->ctl[1];
if (r_time > pc1->end) {
++(*__rng(pc2, rng->cnt[2], r_time));
tfw_stats_adjust(rng, 2);
goto totals;
}
pc0 = &rng->ctl[0];
BUG_ON(pc0->begin != 1); /* left bound is never moved */
if (r_time > pc0->end) {
++(*__rng(pc1, rng->cnt[1], r_time));
tfw_stats_adjust(rng, 1);
goto totals;
}
++(*__rng(pc0, rng->cnt[0], r_time));
goto totals;
}
pc3 = &rng->ctl[3];
if (unlikely(r_time > pc3->end))
tfw_stats_extend(rng, r_time);
++(*__rng(pc3, rng->cnt[3], r_time));
tfw_stats_adjust(rng, 3);
totals:
/* Adjust min/max values. */
if (!tfw_stats_adj_min(rng, r_time))
tfw_stats_adj_max(rng, r_time);
/* Add to @tot_val for AVG calculation. */
rng->tot_val += r_time;
++rng->tot_cnt;
return;
}
/* Time granularity for HTTP codes accounting during health monitoring. */
#define HM_FREQ 10
/*
* Structure for health monitor settings ('health_check').
*
* @list - entry in list of all health monitors;
* @name - health monitor's name;
* @url - url for requests which will be used in health monitoring;
* @urlsz - length of @url string (without terminating zero);
* @req - full test request health monitoring;
* @reqsz - length of @req string (without terminating zero);
* @crc32 - crc32 value for verification of response body checksum;
* @codes - pointer to HTTP response codes bitmap (signals that
* backend server alive);
* @tmt - timeout between health monitoring requests;
* @auto_crc - flag for enabling of crc32 generation from first response;
*/
typedef struct {
struct list_head list;
char *name;
char *req;
unsigned long reqsz;
char *url;
int urlsz;
u32 crc32;
long *codes;
unsigned short tmt;
bool auto_crc:1;
} TfwApmHM;
/*
* Structure for monitoring settings of particular HTTP code
* ('server_failover_http' or 'health_stat_server').
*
* @list - entry in list of all monitored codes;
* @tframe - Time frame in seconds for @code accounting;
* @limit - allowed quantity of responses with @code in a @tframe period;
* @code - HTTP code; also wildcarded code values (of type 4*, 5* etc.)
* are allowed during configuration, so in this field they will
* have form of single-digit number (e.g. 4 or 5 respectively);
*/
typedef struct {
struct list_head list;
unsigned short tframe;
unsigned short limit;
int code;
} TfwApmHMCfg;
/*
* History accounting record.
*
* @ts - part of timeframe in granularity of HM_FREQ;
* @resp - amount responses counted in @ts interval;
*/
typedef struct {
unsigned long ts;
unsigned int resp;
} TfwApmHMHistory;
/*
* Accounting entry for particular HTTP code.
*
* @history - ring buffer of history records;
* @hmcfg - pointer to structure with settings for particular HTTP code;
* @rsum - current amount of responses from @history ring buffer;
* @total - total amount of responses during all the time;
* @lock - spinlock for synchronized work with @history buffer;
*/
typedef struct {
TfwApmHMHistory history[HM_FREQ];
TfwApmHMCfg *hmcfg;
unsigned int rsum;
u64 total;
spinlock_t lock;
} TfwApmHMStats;
/*
* Controller for whole health monitoring of backend server.
*
* @hm - pointer to settings for specific health monitor;
* @hmstats - pointer to array of stat entries for all monitored HTTP codes;
* @rcount - current count of health monitoring requests (in @hm->tmt);
* @jtmstamp - time in jiffies of last @timer call (for procfs);
* @timer - timer for sending health monitoring request;
* @rearm - flag for graceful stopping of @timer;
*/
typedef struct {
TfwApmHM *hm;
TfwApmHMStats *hmstats;
atomic64_t rcount;
unsigned long jtmstamp;
struct timer_list timer;
atomic_t rearm;
TfwServer *srv;
} TfwApmHMCtl;
/* Entry for configuration of separate health monitors. */
static TfwApmHM *tfw_hm_entry;
/*
* Whether an HM config entry with an HTTP code 200 was created. We always want
* to have information about the amount of 200 responses from servers,
* regardless of the configuration.
*/
static bool tfw_hm_cfg_200_created;
/* Entry for configuration of default 'auto' health monitor. */
static TfwApmHM *tfw_hm_default;
/* Total count of monitored HTTP codes. */
static unsigned int tfw_hm_codes_cnt;
static LIST_HEAD(tfw_hm_list);
static LIST_HEAD(tfw_hm_codes_list);
/*
* APM ring buffer.
*
* It consists of the predefined number of entries that are "reused" as
* the buffer gets full. The ring buffer as a whole keeps the APM stats
* for the latest time interval (the time window), and each entry of
* the buffer keeps the APM stats for a piece of that time (an interval).
*/
/*
* A ring buffer entry structure.
*
* @pcntrng - Struct for response time data by the percentiles algorithm.
* @jtmistamp - The start of the time interval for the current entry.
* @reset - The entry can be reset by one thread at a time.
*/
typedef struct {
TfwPcntRanges pcntrng;
unsigned long jtmistamp;
atomic_t reset;
} TfwApmRBEnt;
/*
* The ring buffer structure.
*
* @rbent - Array of ring buffer entries.
* @slock - The lock to adjust the ranges in the current entry.
* @rbufsz - The size of @rbent.
*/
typedef struct {
TfwApmRBEnt *rbent;
spinlock_t slock;
int rbufsz;
} TfwApmRBuf;
/*
* The ring buffer control structure.
*
* This is a supporting structure. It keeps related data that is useful
* in making decisions on the need of recalculation of percentiles.
*
* @jtmwstamp - The start of the time window the percentiles are for.
* @entry_cnt - The number of hits in the current buffer ring entry.
* @total_cnt - The number of hits within the current time window.
*/
typedef struct {
unsigned long jtmwstamp;
unsigned long entry_cnt;
unsigned long total_cnt;
} TfwApmRBCtl;
/*
* The stats entry data structure.
* Keeps the latest values of calculated percentiles.
*
* @pstats - The percentile stats structure.
* @seqlock - Protect updates.
*/
typedef struct {
TfwPrcntlStats pstats;
seqlock_t seqlock;
} TfwApmSEnt;
/*
* The stats data structure.
*
* There's only one updater that runs on timer. It calculates the latest
* percentiles and updates the stored values. There are multiple readers
* of the stored values. The stored values of the latest percentiles are
* a shared resource that needs a lock to access. An array of two entries
* is used to decrease the lock contention. Readers read the stored values
* at @asent[@rdidx % 2]. The writer writes the new percentile values to
* @asent[(@rdidx + 1) % 2], and then increments @rdidx. The reading and
* the writing are protected by a seqlock.
*
* @asent - The stats entries for reading/writing (flip-flop manner).
* @rdidx - The current index in @asent for readers.
*/
typedef struct {
TfwApmSEnt asent[2];
atomic_t rdidx;
} TfwApmStats;
/*
* An update buffer entry that holds RTT data for updates.
*
* The value of @centry depends on @jtstamp that comes as part of data
* for the update. Ideally, @jtstamp and @rtt would be stored instead
* of @centry and @rtt. However, together they occupy more than 64 bits,
* and it's highly desirable to read/write them in a single operation.
*
* @centry - The entry number in the array of ring buffer entries.
* @rtt - The RTT of the message, in milliseconds.
*/
typedef union {
struct {
unsigned int centry;
unsigned int rtt;
} __attribute__((packed));
uint64_t data;
} TfwApmUBEnt;
/*
* The buffer that holds RTT data for updates, per CPU.
*
* The data for an update is stored in an array per CPU. The actual
* updates,and then the percentile recalculation is done periodically
* by a single thread, which removes concurrency between updates and
* the calculation. The data for an update is stored in one array of
* the two, while the processing thread processes the accumulated
* data in the other array. The switch between these two arrays is
* managed by way of @counter by the processing thread.
*
* @ubent - Arrays of ring buffer entries (flip-flop manner).
* @ubufsz - The size of @ubent.
* @counter - The counter that controls which @ubent to use.
*/
typedef struct {
TfwApmUBEnt *ubent[2];
size_t ubufsz;
atomic64_t counter;
} TfwApmUBuf;
#define TFW_APM_DATA_F_REARM (0x0001) /* Re-arm the timer. */
#define TFW_APM_TIMER_INTVL (HZ / 20)
#define TFW_APM_UBUF_SZ TFW_APM_TIMER_INTVL /* a slot per ms. */
#define TFW_APM_MIN_TMWSCALE 1 /* Minimum time window scale. */
#define TFW_APM_MAX_TMWSCALE 50 /* Maximum time window scale. */
#define TFW_APM_MIN_TMWINDOW 60 /* Minimum time window (secs). */
#define TFW_APM_MAX_TMWINDOW 3600 /* Maximum time window (secs). */
#define TFW_APM_MIN_TMINTRVL 5 /* Minimum time interval (secs). */
#define TFW_APM_HM_AUTO "auto"
#define TFW_APM_DFLT_REQ "\"GET / HTTTP/1.0\r\n\r\n\""
#define TFW_APM_DFLT_URL "\"/\""
/*
* APM Data structure.
*
* Note that the organization of the supporting data heavily depends
* on the fact that there's only one party that does the calculation
* of percentiles - the function that runs periodically on timer.
* If there are several different parties that do the calculation,
* then the data may need to be organized differently.
*
* @rbuf - The ring buffer for the specified time window.
* @rbctl - The control data helpful in taking optimizations.
* @stats - The latest percentiles.
* @ubuf - The buffer that holds data for updates, per CPU.
* @timer - The periodic timer handle.
* @flags - The atomic flags (TFW_APM_DATA_F_REARM only for now).
*/
typedef struct {
TfwApmRBuf rbuf;
TfwApmRBCtl rbctl;
TfwApmStats stats;
TfwApmUBuf __percpu *ubuf;
struct timer_list timer;
unsigned long flags;
} TfwApmData;
/*
* The structure containing all the data necessary for the APM module,
* belonging to each server. Used as an opaque pointer.
*
* Order of the members is important for the memory allocation, @data must be
* at the end.
*
* @hmctl - Data necessary for the health monitor operation.
* Additionally, it contains statistics on the total number of
* requests, divided by HTTP codes ('health_stat_server').
* @data - Data required for calculating response statistics for each
* server (min/max/avg/percentiles).
*/
typedef struct {
TfwApmHMCtl hmctl;
TfwApmData data;
} TfwApmRef;
/*
* [1ms, 349ms] should be sufficient for almost any installation,
* including cross atlantic.
*/
static const TfwPcntCtl tfw_rngctl_init[TFW_STATS_RANGES] = {
{0, 1, 16},
{1, 17, 47},
{2, 48, 108},
{4, 109, 349}
};
static int tfw_apm_jtmwindow; /* Time window in jiffies. */
static int tfw_apm_jtmintrvl; /* Time interval in jiffies. */
static int tfw_apm_tmwscale; /* Time window scale. */
/*
* Global statistics for all requests passing through Tempesta (whether cached
* or not). Relies on the 'apm_stats' directive, same as the statistics for
* individual servers.
*/
static TfwApmData *tfw_apm_global_data;
/*
* Get the next bucket in the ring buffer entry that has a non-zero
* hits count. Set the bucket's sequential number, the range number,
* and the bucket number. Set the response time value for the bucket.
*/
/*
* Ring buffer entry state structure.
*
* @v - The response time value.
* @i - The current sequential bucket number across all ranges.
* @r - The current range number.
* @b - The current bucket number.
*/
typedef struct {
u16 v;
u8 i;
u8 r : 4;
u8 b : 4;
} __attribute__((packed)) TfwApmRBEState;
static inline void
__tfw_apm_state_set(TfwApmRBEState *st, u16 v, u8 i, u8 r, u8 b)
{
st->v = v;
st->i = i;
st->r = r;
st->b = b;
}
static inline void
__tfw_apm_state_next(TfwPcntRanges *rng, TfwApmRBEState *st)
{
int i = st->i, r, b;
unsigned int rtt;
for (r = i / TFW_STATS_BCKTS; r < TFW_STATS_RANGES; ++r) {
for (b = i % TFW_STATS_BCKTS; b < TFW_STATS_BCKTS; ++b, ++i) {
if (!rng->cnt[r][b])
continue;
rtt = rng->ctl[r].begin + (b << rng->ctl[r].order);
__tfw_apm_state_set(st, rtt, i, r, b);
return;
}
}
__tfw_apm_state_set(st, USHRT_MAX, TFW_STATS_RANGES * TFW_STATS_BCKTS,
TFW_STATS_RANGES, TFW_STATS_BCKTS);
}
static inline void
tfw_apm_state_next(TfwPcntRanges *rng, TfwApmRBEState *st)
{
BUG_ON(st->i >= TFW_STATS_RANGES * TFW_STATS_BCKTS);
++st->i;
__tfw_apm_state_next(rng, st);
}
/*
* Calculate the latest percentiles from the current stats data.
*/
static void
tfw_apm_prnctl_calc(TfwApmRBuf *rbuf, TfwApmRBCtl *rbctl, TfwPrcntlStats *pstats)
{
#define IDX_MIN TFW_PSTATS_IDX_MIN
#define IDX_MAX TFW_PSTATS_IDX_MAX
#define IDX_AVG TFW_PSTATS_IDX_AVG
#define IDX_ITH TFW_PSTATS_IDX_ITH
int i, p;
unsigned long cnt = 0, val, pval[T_PSZ];
TfwApmRBEState st[TFW_APM_MAX_TMWSCALE];
TfwPcntRanges *pcntrng;
TfwApmRBEnt *rbent = rbuf->rbent;
for (i = 0; i < rbuf->rbufsz; i++) {
pcntrng = &rbent[i].pcntrng;
__tfw_apm_state_set(&st[i], pcntrng->ctl[0].begin, 0, 0, 0);
__tfw_apm_state_next(pcntrng, &st[i]);
}
/* The number of items to collect for each percentile. */
for (i = p = IDX_ITH; i < T_PSZ; ++i) {
pval[i] = rbctl->total_cnt * pstats->ith[i] / 100;
if (!pval[i])
pstats->val[p++] = 0;
}
while (p < T_PSZ) {
int v_min = USHRT_MAX;
for (i = 0; i < rbuf->rbufsz; i++) {
if (st[i].v < v_min)
v_min = st[i].v;
}
BUG_ON(v_min == USHRT_MAX);
for (i = 0; i < rbuf->rbufsz; i++) {
if (st[i].v != v_min)
continue;
pcntrng = &rbent[i].pcntrng;
cnt += pcntrng->cnt[st[i].r][st[i].b];
tfw_apm_state_next(pcntrng, &st[i]);
}
for ( ; p < T_PSZ && pval[p] <= cnt; ++p)
pstats->val[p] = v_min;
}
cnt = val = 0;
pstats->val[IDX_MAX] = 0;
pstats->val[IDX_MIN] = UINT_MAX;
for (i = 0; i < rbuf->rbufsz; i++) {
pcntrng = &rbent[i].pcntrng;
if (pstats->val[IDX_MIN] > pcntrng->min_val)
pstats->val[IDX_MIN] = pcntrng->min_val;
if (pstats->val[IDX_MAX] < pcntrng->max_val)
pstats->val[IDX_MAX] = pcntrng->max_val;
cnt += pcntrng->tot_cnt;
val += pcntrng->tot_val;
}
if (likely(cnt))
pstats->val[IDX_AVG] = val / cnt;
#undef IDX_ITH
#undef IDX_AVG
#undef IDX_MAX
#undef IDX_MIN
}
/*
* Reset a ring buffer entry.
* Note that the ranges are not reset. As Tempesta runs the ranges
* are adjusted to reflect the actual response time values.
*/
static inline void
__tfw_apm_rbent_reset(TfwApmRBEnt *crbent, unsigned long jtmistamp)
{
memset(crbent->pcntrng.__reset_from, 0,
offsetof(TfwPcntRanges, __reset_till)
- offsetof(TfwPcntRanges, __reset_from));
crbent->pcntrng.min_val = UINT_MAX;
crbent->jtmistamp = jtmistamp;
smp_mb__before_atomic();
atomic_set(&crbent->reset, 1);
}
/*
* Reset a ring buffer entry if it needs to be reused. Only one thread
* proceeds to reset the entry. While the entry is being reset a number
* of stats updates may be lost. That's acceptable.
*/
static inline void
tfw_apm_rbent_checkreset(TfwApmRBEnt *crbent, unsigned long jtmistamp)
{
if (crbent->jtmistamp != jtmistamp) {
if (!atomic_dec_and_test(&crbent->reset))
return;
__tfw_apm_rbent_reset(crbent, jtmistamp);
}
}
/*
* Update the control information on the APM ring buffer entries with
* stats for subsequent calculation of percentiles. Use optimizations
* to avoid the recalculation whenever possible. Maintain values of
* @entry_cnt, @total_cnt, @jtmwstamp that are used in optimizations.
*
* Return true if recalculation of percentiles is required.
* Return false if the percentile values don't need the recalculation.
*/
static bool
tfw_apm_rbctl_update(TfwApmData *data)
{
int i, centry;
unsigned long jtmnow = jiffies;
unsigned long jtmwstart, jtmistart;
unsigned long entry_cnt, total_cnt = 0;
TfwApmRBuf *rbuf = &data->rbuf;
TfwApmRBCtl *rbctl = &data->rbctl;
TfwApmRBEnt *rbent = rbuf->rbent;
/* The start of the current time interval. */
jtmistart = jtmnow - (jtmnow % tfw_apm_jtmintrvl);
/* The start of the current time window. */
jtmwstart = jtmistart - tfw_apm_jtmwindow;
/* The index of the current entry. */
centry = (jtmnow / tfw_apm_jtmintrvl) % rbuf->rbufsz;
/*
* If the latest percentiles are for a different time window,
* then a recalculation is in order.
*/
if (unlikely(rbctl->jtmwstamp != jtmwstart)) {
tfw_apm_rbent_checkreset(&rbent[centry], jtmistart);
for (i = 0; i < rbuf->rbufsz; ++i)
total_cnt += rbent[i].pcntrng.tot_cnt;
entry_cnt = rbent[centry].pcntrng.tot_cnt;
rbctl->entry_cnt = entry_cnt;
rbctl->total_cnt = total_cnt;
rbctl->jtmwstamp = jtmwstart;
T_DBG3("%s: New time window: centry [%d] total_cnt [%lu]\n",
__func__, centry, rbctl->total_cnt);
return true;
}
/* The latest percentiles are for the current time window.
* In some cases a recalculation is not required. In some
* other cases the recalculation set up can be simpler.
*/
/* Nothing to do if there were no stats updates. */
entry_cnt = rbent[centry].pcntrng.tot_cnt;
if (unlikely(rbctl->entry_cnt == entry_cnt))
return false;
BUG_ON(rbctl->entry_cnt > entry_cnt);
/* Update the counts incrementally. */
rbctl->total_cnt += entry_cnt - rbctl->entry_cnt;
rbctl->entry_cnt = entry_cnt;
T_DBG3("%s: Old time window: centry [%d] total_cnt [%lu]\n",
__func__, centry, rbctl->total_cnt);
return true;
}
/*
* Calculate the latest percentiles if necessary.
*/
static void
tfw_apm_calc(TfwApmData *data)
{
unsigned int rdidx;
unsigned int val[T_PSZ] = { 0 };
TfwPrcntlStats pstats = {
.ith = tfw_pstats_ith,
.val = val,
};
TfwApmSEnt *asent;
rdidx = atomic_read(&data->stats.rdidx);
asent = &data->stats.asent[(rdidx + 1) % 2];
if (!tfw_apm_rbctl_update(data))
return;
tfw_apm_prnctl_calc(&data->rbuf, &data->rbctl, &pstats);
T_DBG3("%s: Percentile values may have changed.\n", __func__);
write_seqlock(&asent->seqlock);
memcpy_fast(asent->pstats.val, pstats.val,
T_PSZ * sizeof(asent->pstats.val[0]));
atomic_inc(&data->stats.rdidx);
write_sequnlock(&asent->seqlock);
return;
}
/*
* Get the latest calculated percentiles.
*
* Return false if the percentile values didn't need recalculation.
* Return true if potentially new percentile values were calculated.
*/
static bool
__tfw_apm_stats(TfwApmData *data, TfwPrcntlStats *pstats)
{
unsigned int rdidx, s, seq = pstats->seq;
TfwApmSEnt *asent;
smp_mb__before_atomic();
rdidx = atomic_read(&data->stats.rdidx);
asent = &data->stats.asent[rdidx % 2];
do {
s = read_seqbegin(&asent->seqlock);
memcpy(pstats->val, asent->pstats.val,
T_PSZ * sizeof(pstats->val[0]));
} while (read_seqretry(&asent->seqlock, s));
pstats->ith = tfw_pstats_ith;
pstats->seq = rdidx;
return seq != rdidx;
}
int
tfw_apm_stats(void *apmref, TfwPrcntlStats *pstats)
{
TfwApmData *data;
BUG_ON(!apmref);
data = &((TfwApmRef *)apmref)->data;
return __tfw_apm_stats(data, pstats);
}
int
tfw_apm_stats_global(TfwPrcntlStats *pstats)
{
BUG_ON(!tfw_apm_global_data);
return __tfw_apm_stats(tfw_apm_global_data, pstats);
}
/*
* Calculate the latest percentiles if necessary.
* Runs periodically on timer.
*/