forked from 0xc0dec/ustats
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathngx_http_ustats_module.c
1039 lines (919 loc) · 40.5 KB
/
ngx_http_ustats_module.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
/**
* Copyright (C) 2015-2016 Denis Denisov
* Copyright (C) 2014 Dmitry Saprykin
* Copyright (C) 2010-2012 Aleksey Fedotov (0xc0dec), kontur.ru
*
* @author Aleksey Fedotov (0xc0dec)
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
const char HTML[] =
"<!DOCTYPE html>\n"
"<html>\n"
"<head>\n"
" <style>\n"
" .stats-table { border-collapse: collapse; border-width: 1px; border-style: outset; font-family: 'lucida grande'; font-size: 15px; width: %s; height: %s; }\n"
" .cell-common { border-width: 1px; border-style: solid; border-color: black; padding: 4px; text-align: center; }\n"
" .cell-header { background-color: #12b2c4; }\n"
" .cell-blacklisted { background-color: red; }\n"
" .cell-disabled { border-color: black; color: #a8a8a8; }\n"
" .cell-no-last-fail { color: #eee; }\n"
" .cell-upstream { }\n"
" .cell-upstream-one { background-color: #3ec7d6; }\n"
" .cell-upstream-two { background-color: #12a2b3; }\n"
" .cell-implicit-upstream { color: #fff; }\n"
" .cell-sort-asc { }\n"
" .cell-sort-desc { }\n"
" .cell-sort-trigger { cursor: pointer; }\n"
" button { border: 1px outset; font-family: 'Comic Sans MS', 'sans serif'; cursor: pointer; }\n"
" .down { border: 1px inset; background: buttonhighlight; color: black; }\n"
" .up { border: 1px outset; color: #aaa; }\n"
" </style>\n"
"</head>\n"
"\n"
"<body>\n"
" <table width=\"100%%\" height=\"100%%\">\n"
" <tr>\n"
" <td align=\"center\" valign=\"middle\">\n"
" <a href=\"?reset=1\">Reset</a>\n"
" <div id=\"content\"></div>\n"
" </td>\n"
" </tr>\n"
" </table>\n"
"\n"
"<script>\n"
" var REFRESH_INTERVAL = %d\n"
" var TABLE_COLUMNS_COUNT = 18\n"
" var updating = 0\n"
" var sortInfo = new Array()\n"
" var originalTable = document.createElement('table')\n"
"\n"
" var req = function createRequester () {\n"
" var http_obj = false\n"
" if (window.XMLHttpRequest) { // Mozilla, Safari,...\n"
" http_obj = new XMLHttpRequest()\n"
" } else if (window.ActiveXObject) { // IE\n"
" try {\n"
" http_obj = new ActiveXObject('Msxml2.XMLHTTP')\n"
" } catch (e) {\n"
" try {\n"
" http_obj = new ActiveXObject('Microsoft.XMLHTTP')\n"
" } catch (e) {}\n"
" }\n"
" }\n"
"\n"
" return http_obj\n"
" }\n"
"\n"
" /**\n"
" * Adjusts sort status text for column with index cellIndex\n"
" * in upstream indicated by upstreamCell\n"
" */\n"
" function adjustSortStatusText (startIndex, endIndex) {\n"
" var table = document.getElementById('stats-table')\n"
" var row = table.rows[startIndex]\n"
" var cell = row.cells[0]\n"
"\n"
" var sortStatus\n"
" if (cell.className.indexOf('sortInfo$none') != -1)\n"
" { sortStatus = 'none' }\n"
" else if (cell.className.indexOf('sortInfo$asc') != -1)\n"
" { sortStatus = 'asc' }\n"
" else if (cell.className.indexOf('sortInfo$desc') != -1)\n"
" { sortStatus = 'desc' }\n"
"\n"
" var r = /sortInfo\\$.*\\$(.*)$/.exec(cell.className)\n"
" var ind = parseInt(r[1])\n"
" if (ind == -1) {\n"
" return\n"
" }\n"
"\n"
" do {\n"
" cell = (row.cells.length == TABLE_COLUMNS_COUNT) ? row.cells[ind + 1] : row.cells[ind]\n"
" var lastSpaceInd = cell.innerHTML.lastIndexOf(' ')\n"
" switch (sortStatus)\n"
" {\n"
" case 'none':\n"
" if (lastSpaceInd == -1) {\n"
" break\n"
" }\n"
" cell.innerHTML = cell.innerHTML.substring(0, lastSpaceInd)\n"
" break\n"
"\n"
" case 'asc':\n"
" if (lastSpaceInd != -1 && (lastSpaceInd == cell.innerHTML.length - 2 || lastSpaceInd == cell.innerHTML.length - 3)\n"
" ) // last fail time cells have spaces\n"
" { cell.innerHTML = cell.innerHTML.substring(0, lastSpaceInd) }\n"
" cell.innerHTML += ' ↓'\n"
" break\n"
"\n"
" case 'desc':\n"
" cell.innerHTML += ' ↑'\n"
" break\n"
" }\n"
"\n"
" row = row.nextSibling\n"
" }\n"
" while (row && row.cells.length < TABLE_COLUMNS_COUNT)\n"
" }\n"
"\n"
" /**\n"
" * Adjusts upstream cell meta info to reflect sort status\n"
" */\n"
" function toggleSortStatus (upstreamCell, cellIndex) {\n"
" // extract current sort info from className attribute\n"
" var sortInfo = upstreamCell.className.substring(upstreamCell.className.indexOf('sortInfo$'))\n"
" var newSortInfo = null\n"
" if (sortInfo.indexOf('asc') != -1) {\n"
" newSortInfo = 'sortInfo$none$' + cellIndex\n"
" } else if (sortInfo.indexOf('desc') != -1) {\n"
" newSortInfo = 'sortInfo$asc$' + cellIndex\n"
" } else {\n"
" newSortInfo = 'sortInfo$desc$' + cellIndex\n"
" }\n"
" upstreamCell.className = upstreamCell.className.replace(sortInfo, newSortInfo)\n"
" }\n"
"\n"
" function saveSortInfo () {\n"
" // sortInfo here is empty\n"
" var table = document.getElementById('stats-table')\n"
" if (!table) {\n"
" return\n"
" }\n"
" for (var i = 0; i < table.rows.length; ++i)\n"
" {\n"
" var row = table.rows[i]\n"
" if (row.cells[0].className.indexOf('cell-upstream') != -1) { // upstream name cell\n"
" sortInfo[i] = row.cells[0].className\n"
" }\n"
" }\n"
" }\n"
"\n"
" function restoreSorting () {\n"
" var table = document.getElementById('stats-table')\n"
"\n"
" for (var i in sortInfo)\n"
" {\n"
" table.rows[i].cells[0].className = sortInfo[i]\n"
" var indices = sort(table.rows[i].firstChild)\n"
" if (indices[0] != indices[1]) {\n"
" adjustSortStatusText(parseInt(indices[0]), parseInt(indices[1]))\n"
" }\n"
" }\n"
"\n"
" sortInfo.length = 0\n"
" }\n"
"\n"
" function onSortTriggerClick (cell) {\n"
" // find upstream cell name\n"
" var usRow = cell.parentNode\n"
" while (usRow.cells.length != TABLE_COLUMNS_COUNT) {\n"
" usRow = usRow.previousSibling\n"
" }\n"
"\n"
" // Cell index. For rows with upstream\n"
" // name cell, that cell is not included\n"
" var cellIndex = cell.cellIndex\n"
" if (cell.parentNode.cells.length == TABLE_COLUMNS_COUNT) { // row with upstream name cell\n"
" cellIndex--\n"
" }\n"
"\n"
" // Remove sorting from previously sorted column\n"
" var sortInfo = usRow.cells[0].className.substring(usRow.cells[0].className.indexOf('sortInfo$'))\n"
" var r = /sortInfo\\$.*\\$(.*)/.exec(sortInfo)\n"
" var oldIndex = parseInt(r[1])\n"
" if (oldIndex != -1 && cellIndex != oldIndex) {\n"
" usRow.cells[0].className = usRow.cells[0].className.replace(sortInfo, 'sortInfo$none$-1')\n"
" var indices = sort(usRow.firstChild)\n"
" if (indices[0] != indices[1]) {\n"
" adjustSortStatusText(parseInt(indices[0]), parseInt(indices[1]))\n"
" }\n"
" }\n"
"\n"
" toggleSortStatus(usRow.firstChild, cellIndex)\n"
"\n"
" var indices = sort(usRow.firstChild)\n"
" if (indices[0] != indices[1])\n"
" { adjustSortStatusText(parseInt(indices[0]), parseInt(indices[1])) }\n"
" }\n"
"\n"
" // Sorts backends for the given upstream, using sort info\n"
" // saved in upstream name cell class\n"
" function sort (usCell) {\n"
" var sortInfo = usCell.className.substring(usCell.className.indexOf('sortInfo$'))\n"
"\n"
" // 'sortInfo$<mode>$<column_index>'\n"
" var rx = /sortInfo\\$(.*)\\$(.*)/\n"
" var result = rx.exec(sortInfo)\n"
"\n"
" var mode = result[1]\n"
" var columnIndex = parseInt(result[2])\n"
"\n"
" var startRow = usCell.parentNode\n"
"\n"
" var endRow = startRow\n"
" // iterate till the next upstream starting row\n"
" while (endRow.nextSibling && endRow.nextSibling.cells.length < TABLE_COLUMNS_COUNT) {\n"
" endRow = endRow.nextSibling\n"
" }\n"
"\n"
" var startIndex = startRow.rowIndex\n"
" var endIndex = endRow.rowIndex\n"
"\n"
" if (startIndex == endIndex) { // upstream with one backend\n"
" return [startIndex, endIndex]\n"
" }\n"
"\n"
" if (mode == 'none')\n"
" {\n"
" // nothing to sort, only restore table\n"
" var table = document.getElementById('stats-table')\n"
" for (var i = startIndex; i <= endIndex; ++i) {\n"
" table.rows[i].innerHTML = originalTable.rows[i].innerHTML\n"
" }\n"
" return [startIndex, endIndex]\n"
" }\n"
"\n"
" var table = usCell.parentNode.parentNode\n"
"\n"
" var tmpArr = new Array()\n"
" for (var i = startIndex; i <= endIndex; ++i) {\n"
" tmpArr.push(table.rows[i])\n"
" }\n"
"\n"
" var usStartRow\n"
" var newUsStartRow\n"
"\n"
" tmpArr.sort(function (a, b) {\n"
" if (a.cells.length == TABLE_COLUMNS_COUNT) {\n"
" usStartRow = a\n"
" } else if (b.cells.length == TABLE_COLUMNS_COUNT) {\n"
" usStartRow = b\n"
" }\n"
"\n"
" var aCell = (a.cells.length == TABLE_COLUMNS_COUNT) ? a.cells[columnIndex + 1] : a.cells[columnIndex]\n"
" var bCell = (b.cells.length == TABLE_COLUMNS_COUNT) ? b.cells[columnIndex + 1] : b.cells[columnIndex]\n"
"\n"
" if (columnIndex != TABLE_COLUMNS_COUNT - 3 && columnIndex != TABLE_COLUMNS_COUNT - 4) { // all except last fail\n"
" var result = parseInt(aCell.textContent) - parseInt(bCell.textContent)\n"
" return (mode == 'asc') ? result : (mode == 'desc') ? -result : 0\n"
" } else/* if (columnIndex == TABLE_COLUMNS_COUNT - 3 || columnIndex == TABLE_COLUMNS_COUNT - 4) */ {\n"
" var result = (aCell.textContent > bCell.textContent) ? 1 :\n"
" (aCell.textContent === bCell.textContent) ? 0 : -1\n"
" return (mode == 'asc') ? result : (mode == 'desc') ? -result : 0\n"
" }\n"
" })\n"
"\n"
" // Remove upstream name cell from old upstream header row\n"
" var usCell = usStartRow.cells[0]\n"
" usStartRow.removeChild(usCell)\n"
" tmpArr[0].insertBefore(usCell, tmpArr[0].cells[0])\n"
"\n"
" while (tmpArr.length > 0)\n"
" { table.insertBefore(tmpArr.pop(), table.rows[startIndex]) }\n"
"\n"
" return [startIndex, endIndex]\n"
" }\n"
"\n"
" function requestData (url) {\n"
" req.open('GET', url, false)\n"
" req.send(null)\n"
" return req.responseText\n"
" }\n"
"\n"
" function buildTable (data) {\n"
" data = eval('(' + data + ')')\n"
"\n"
" var headers = ['Upstream', 'Backend', 'Weight', 'Requests', 'RPS', 'Req. time (ms)', 'HTTP 499', 'HTTP 5XX', 'HTTP 500', 'HTTP 503', 'TCP errors', 'HTTP read timeouts',\n"
" 'HTTP write timeouts', 'Fail timeouts, sec.', 'Max fails', 'Start time', 'Last fail', 'Total fails']\n"
"\n"
" var table = document.createElement('table')\n"
"\n"
" var updateRow = document.createElement('tr')\n"
" var updateHeader = document.createElement('th')\n"
" updateHeader.id = 'updateStatus'\n"
" updateHeader.className = 'cell-common cell-header'\n"
" updateHeader.setAttribute('colspan', headers.length)\n"
" updateRow.appendChild(updateHeader)\n"
" table.appendChild(updateRow)\n"
"\n"
" var headerRow = document.createElement('tr')\n"
" for (var h in headers) {\n"
" var headerCell = document.createElement('th')\n"
" headerCell.className = 'cell-common cell-header'\n"
" headerCell.innerHTML = headers[h]\n"
" headerRow.appendChild(headerCell)\n"
" }\n"
" table.appendChild(headerRow)\n"
"\n"
" // Upstreams\n"
" var usn = 0 // for coloring upstreams\n"
" for (var us in data)\n"
" {\n"
" var usNameCell = document.createElement('th')\n"
" usNameCell.textContent = us\n"
" usNameCell.className = 'cell-common cell-header'\n"
" if (data[us][data[us].length - 1] == 1) {\n"
" usNameCell.className += ' cell-implicit-upstream'\n"
" }\n"
"\n"
" if (usn %% 2 == 0) {\n"
" usNameCell.className += ' cell-upstream-one'\n"
" } else {\n"
" usNameCell.className += ' cell-upstream-two'\n"
" }\n"
" usn++\n"
"\n"
" // Upstream cell contents\n"
" usNameCell.setAttribute('rowspan', data[us].length - 1)\n"
"\n"
" var firstUpsteamBackend = null\n"
"\n"
" // Backends\n"
" for (var b in data[us]) {\n"
" if (b == data[us].length - 1) {\n"
" break\n"
" }\n"
"\n"
" var backendRow = document.createElement('tr')\n"
"\n"
" var disabled = data[us][b][1]\n"
" var blacklisted = data[us][b][2]\n"
"\n"
" // Backend parameters\n"
" for (var param in data[us][b]) {\n"
" if (param == 1 || param == 2) { // disabled or blacklisted\n"
" continue\n"
" }\n"
"\n"
" var paramCell = document.createElement('td')\n"
" paramCell.className = 'cell-common'\n"
"\n"
" if (disabled) {\n"
" paramCell.className += ' cell-disabled'\n"
" }\n"
"\n"
" if (blacklisted) {\n"
" paramCell.className += ' cell-blacklisted'\n"
" }\n"
"\n"
" // Current parameter is the last fail time, and next (total fails) equals to 0\n"
" if (((param == data[us][b].length - 2) && (data[us][b][parseInt(param) + 1] == 0)) ||\n"
" ((param == data[us][b].length - 1) && (data[us][b][param] == 0)))\n"
" {\n"
" paramCell.className += ' cell-no-last-fail'\n"
" }\n"
"\n"
" if (param == 0) { // backend name\n"
" var nameParts = /(.*) \\((.*)\\)/.exec(data[us][b][param])\n"
" if (nameParts) {\n"
" paramCell.innerHTML = nameParts[1] + '<br/>(' + nameParts[2] + ')'\n"
" } else {\n"
" paramCell.textContent = data[us][b][param]\n"
" }\n"
" } else {\n"
" paramCell.textContent = data[us][b][param]\n"
" }\n"
"\n"
" backendRow.appendChild(paramCell)\n"
"\n"
" // Detect what column this parameter resides in and allow/disallow sorting\n"
" if (param != 0 && param != 14 && param != 15) // not name, not fail timeout and not max fails\n"
" {\n"
" paramCell.className += ' cell-sort-trigger'\n"
" paramCell.setAttribute('onclick', 'onSortTriggerClick(this)')\n"
" }\n"
" }\n"
"\n"
" if (b == 0) { // first upstream row\n"
" backendRow.insertBefore(usNameCell, backendRow.firstChild)\n"
" usNameCell.className += ' cell-upstream'\n"
" usNameCell.className += ' sortInfo$none$-1'\n"
" }\n"
"\n"
" table.appendChild(backendRow)\n"
" }\n"
" }\n"
"\n"
" var content = document.getElementById('content')\n"
" content.innerHTML = '<table class=\"stats-table\" id=\"stats-table\">' + table.innerHTML + '</table>' // WTF\n"
" originalTable.innerHTML = table.innerHTML\n"
" }\n"
"\n"
" function updateTable (data)\n"
" {\n"
" if (updating == 0)\n"
" {\n"
" updating = 1\n"
" saveSortInfo()\n"
" buildTable(data)\n"
" restoreSorting()\n"
" updating = 0\n"
"\n"
" // Update last update time\n"
" var statusHeader = document.getElementById('updateStatus')\n"
" var now = new Date()\n"
" statusHeader.innerHTML = 'Last update: ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()\n"
" }\n"
" }\n"
"\n"
" function onTimer ()\n"
" {\n"
" var data = requestData('?json=1')\n"
" updateTable(data)\n"
" }\n"
"\n"
" window.onload = function ()\n"
" {\n"
" onTimer()\n"
" setInterval(onTimer, REFRESH_INTERVAL) // TODO request parameters from nginx\n"
" }\n"
"</script>\n"
"</body>\n"
"</html>\n";
/**
* Shared memory used to store statistics
*/
ngx_shm_zone_t *stats_data = NULL;
static size_t stats_data_size = 0;
ngx_str_t shm_name = ngx_string("stats_data");
typedef struct {
/**
* HTML table width and height.
* Less or equal 100 - percent value, greater than 100 - pixel value.
* 70 by default.
*/
ngx_uint_t html_table_width;
ngx_uint_t html_table_height;
/** Page refresh interval, milliseconds. 5000 by default */
ngx_uint_t refresh_interval;
} ngx_http_ustats_loc_conf_t;
#define USTATS_REQ_MEASURE_COUNT 3
static void *ngx_http_ustats_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_ustats_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);
static ngx_int_t ngx_http_ustats_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_ustats_log_handler(ngx_http_request_t *r);
static char *ngx_http_ustats(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
//static char * ngx_http_shm_size(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_ustats_handler(ngx_http_request_t *r);
static ngx_buf_t *ngx_http_ustats_create_response_json(ngx_http_request_t *r);
static ngx_buf_t *ngx_http_ustats_create_response_html(ngx_http_request_t *r);
static ngx_command_t ngx_http_ustats_commands[] = {
{
ngx_string("ustats"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_http_ustats,
0,
0,
NULL
},
{
ngx_string("ustats_html_table_width"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_ustats_loc_conf_t, html_table_width),
NULL
},
{
ngx_string("ustats_html_table_height"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_ustats_loc_conf_t, html_table_height),
NULL
},
{
ngx_string("ustats_refresh_interval"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_http_ustats_loc_conf_t, refresh_interval),
NULL
},
ngx_null_command
};
static ngx_http_module_t ngx_http_ustats_module_ctx = {
NULL, /* preconfiguration */
ngx_http_ustats_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_ustats_create_loc_conf, /* create location configuration */
ngx_http_ustats_merge_loc_conf /* merge location configuration */
};
ngx_module_t ngx_http_ustats_module = {
NGX_MODULE_V1,
&ngx_http_ustats_module_ctx, /* module context */
ngx_http_ustats_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *ngx_http_ustats_create_loc_conf(ngx_conf_t *cf) {
ngx_http_ustats_loc_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_ustats_loc_conf_t));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
conf->html_table_width = NGX_CONF_UNSET_UINT;
conf->html_table_height = NGX_CONF_UNSET_UINT;
conf->refresh_interval = NGX_CONF_UNSET_UINT;
return conf;
}
static char *ngx_http_ustats_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) {
ngx_http_ustats_loc_conf_t *prev = parent;
ngx_http_ustats_loc_conf_t *conf = child;
ngx_conf_merge_uint_value(conf->html_table_width, prev->html_table_width, 70);
ngx_conf_merge_uint_value(conf->html_table_height, prev->html_table_height, 70);
ngx_conf_merge_uint_value(conf->refresh_interval, prev->refresh_interval, 5000);
if (conf->html_table_width < 1) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "html table width must be >= 1");
return NGX_CONF_ERROR;
}
if (conf->html_table_height < 1) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "html table height must be >= 1");
return NGX_CONF_ERROR;
}
if (conf->refresh_interval < 1) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "page refresh interval must be >= 1");
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_ustats_init_shm(ngx_shm_zone_t *shm_zone, void *data) {
if (data) {
shm_zone->data = data;
return NGX_OK;
}
ngx_slab_pool_t *shpool = (ngx_slab_pool_t *)shm_zone->shm.addr;
void *new_block = ngx_slab_alloc(shpool, stats_data_size);
if (new_block == NULL) {
ngx_log_error(NGX_LOG_EMERG, shm_zone->shm.log, 0,
"Cannot init shm of size %ul ", stats_data_size);
return NGX_ERROR;
}
ngx_memzero(new_block, stats_data_size);
shpool->data = new_block;
shm_zone->data = new_block;
return NGX_OK;
}
static char *ngx_http_ustats(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_http_core_loc_conf_t *clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_http_ustats_handler;
if (cf->args->nelts == 1) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "ustats: no shared memory size specified");
return NGX_CONF_ERROR;
}
ssize_t size = 0;
ngx_str_t size_arg = ((ngx_str_t *)cf->args->elts)[1];
if (ngx_strncmp(size_arg.data, "memsize=", 8) == 0) {
ngx_str_t size_str;
size_str.len = size_arg.len - 8;
if (size_str.len == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "ustats: no shared memory size specified");
return NGX_CONF_ERROR;
}
size_str.data = size_arg.data + 8;
size = ngx_parse_size(&size_str);
if (size == NGX_ERROR) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "ustats: unable to parse shared memory size");
return NGX_CONF_ERROR;
}
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "ustats: no shared memory size specified");
return NGX_CONF_ERROR;
}
if (size < (int)ngx_pagesize) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0, "ustats: shared memory size must be at least %udB", ngx_pagesize);
size = ngx_pagesize;
}
if (stats_data_size && stats_data_size != (size_t)size) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0, "ustats: cannot change shared memory area without restart, ignoring changes");
} else {
stats_data_size = size;
}
if (stats_data_size == 0) {
stats_data_size = ngx_pagesize;
}
size_t memory_size = stats_data_size + 100 * ngx_pagesize;
stats_data = ngx_shared_memory_add(cf, &shm_name, memory_size, &ngx_http_ustats_module);
if (stats_data == NULL) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "ustats: ngx_shared_memory_add failed. size - %ui", memory_size);
return NGX_CONF_ERROR;
}
stats_data->init = ngx_http_ustats_init_shm;
stats_data->data = NULL;
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_ustats_handler(ngx_http_request_t *r) {
ngx_int_t rc;
ngx_buf_t *b = NULL;
ngx_chain_t out;
if (r->method != NGX_HTTP_GET && r->method != NGX_HTTP_HEAD) {
return NGX_HTTP_NOT_ALLOWED;
}
rc = ngx_http_discard_request_body(r);
if (rc != NGX_OK) {
return rc;
}
ngx_str_set(&r->headers_out.content_type, "text/plain");
if (r->method == NGX_HTTP_HEAD) {
r->headers_out.status = NGX_HTTP_OK;
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
return rc;
}
}
ngx_str_t value;
// Send HTML or simple JSON
if (ngx_http_arg(r, (u_char *)"json", 4, &value) == NGX_OK) {
ngx_str_set(&r->headers_out.content_type, "text/plain");
b = ngx_http_ustats_create_response_json(r);
} else {
if (stats_data && ngx_http_arg(r, (u_char *)"reset", 5, &value) == NGX_OK) {
ngx_memzero(stats_data->data, stats_data_size);
ngx_http_clear_location(r);
r->headers_out.location = ngx_list_push(&r->headers_out.headers);
if (r->headers_out.location == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
r->headers_out.location->hash = 1;
ngx_str_set(&r->headers_out.location->key, "Location");
ngx_str_set(&r->headers_out.location->value, "?");
return NGX_HTTP_MOVED_TEMPORARILY;
}
ngx_str_set(&r->headers_out.content_type, "text/html");
b = ngx_http_ustats_create_response_html(r);
}
if (b == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
out.buf = b;
out.next = NULL;
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = b->last - b->pos;
b->last_buf = 1;
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
return rc;
}
return ngx_http_output_filter(r, &out);
}
static ngx_buf_t *ngx_http_ustats_create_response_json(ngx_http_request_t *r) {
unsigned i, k;
size_t size = 0;
ngx_buf_t *b = NULL;
time_t now = ngx_time();
ngx_http_upstream_main_conf_t *conf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);
/**
* Calculate size
*/
size += sizeof("{\n");
for (i = 0; i < conf->upstreams.nelts; ++i) {
ngx_http_upstream_srv_conf_t *uscf = ((ngx_http_upstream_srv_conf_t **)conf->upstreams.elts)[i];
ngx_http_upstream_rr_peers_t *peers = uscf->peer.data;
// upstream name
size += sizeof(" \"\":\n");
size += (uscf->host.len + 1) * sizeof(u_char);
// array of backends
size += sizeof(" [\n");
for (k = 0; k < peers->number; ++k) {
// Peer name
size += sizeof(" [\"\", ");
// <peer_name> (server_conf_name || upstream_name) if there is more than one peer per backend
if (!peers->peer[k].peer_server || peers->peer[k].peer_server->naddrs > 1) {
size += (peers->peer[k].name.len + 1) * sizeof(u_char);
size += sizeof(" ()");
size += (!peers->peer[k].peer_server)
? (uscf->host.len + 1) * sizeof(u_char) // for implicit backends
// for the (good of) rest (of us, except the ones who are dead) (c)
: (peers->peer[k].peer_server->name.len + 1) * sizeof(u_char);
}
// one server <-> one peer - write server config name
else {
size += (peers->peer[k].peer_server->name.len + 1) * sizeof(u_char);
}
// disabled and blacklisted
size += (sizeof(ngx_uint_t) + sizeof(", ")) * 2;
// numeric parameters
size += (sizeof(ngx_uint_t) + sizeof(", ")) * 14;
// start time string
size += sizeof(u_char) * 24 + sizeof("\"\"") + sizeof(", ");
// failed access time string
size += sizeof(u_char) * 24 + sizeof("\"\"");
size += sizeof("],\n");
}
// implicit upstream
size += sizeof(" ");
size += sizeof(ngx_uint_t);
size += sizeof(" ],\n");
}
size += sizeof("}");
b = ngx_create_temp_buf(r->pool, size);
b->last = ngx_sprintf(b->last, "{\n");
/**
* Fill data
*/
for (i = 0; i < conf->upstreams.nelts; ++i) {
ngx_http_upstream_srv_conf_t *uscf = ((ngx_http_upstream_srv_conf_t **)conf->upstreams.elts)[i];
ngx_http_upstream_rr_peers_t *peers = uscf->peer.data;
b->last = ngx_sprintf(b->last, " \"%s\":\n [\n", uscf->host.data);
for (k = 0; k < peers->number; ++k) {
b->last = ngx_sprintf(b->last, " [\"");
// peer name
if (!peers->peer[k].peer_server || peers->peer[k].peer_server->naddrs > 1) {
// Dirty workaround. Strange bugs with nginx-created strings when running under Duma
size_t j;
// Peer name (resolved)
for (j = 0; j < peers->peer[k].name.len; ++j) {
b->last = ngx_sprintf(b->last, "%c", peers->peer[k].name.data[j]);
}
// Initial config name (unresolved)
b->last = (!peers->peer[k].peer_server)
? ngx_sprintf(b->last, " (%s)", uscf->host.data)
: ngx_sprintf(b->last, " (%s)", (char *)peers->peer[k].peer_server->name.data);
} else {
b->last = ngx_sprintf(b->last, "%s", (peers->peer[k].peer_server->name.data
? (char *)peers->peer[k].peer_server->name.data
: (char *)uscf->host.data));
}
b->last = ngx_sprintf(b->last, "\", ");
unsigned disabled = (peers->peer[k].down) ? 1 : 0;
unsigned blacklisted = (now - *(time_t *)(USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_LAST_FAIL_TIME_STAT_OFFSET)) < peers->peer[k].fail_timeout);
// disabled and blacklisted
b->last = ngx_sprintf(b->last, "%d, %d, ", disabled, blacklisted);
// weight
b->last = ngx_sprintf(b->last, "%ui, ", peers->peer[k].weight);
// requests
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_REQ_STAT_OFFSET));
// RPS
ngx_uint_t rps = (*(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_REQ_COUNT_1_OFFSET)
+ *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_REQ_COUNT_2_OFFSET)
+ *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_REQ_COUNT_3_OFFSET)) / USTATS_REQ_MEASURE_COUNT;
b->last = ngx_sprintf(b->last, "%d, ", rps);
// SPEED
ngx_uint_t speed = (*(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_REQ_TIMES_1_OFFSET)
+ *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_REQ_TIMES_2_OFFSET)
+ *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_REQ_TIMES_3_OFFSET)) / USTATS_REQ_MEASURE_COUNT;
b->last = ngx_sprintf(b->last, "%d, ", speed);
// 499s
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_HTTP499_STAT_OFFSET));
// 5xx
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_HTTP5XX_STAT_OFFSET));
// 500s
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_HTTP500_STAT_OFFSET));
// 503s
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_HTTP503_STAT_OFFSET));
// tcp errors
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_TCP_ERR_STAT_OFFSET));
// http read timeouts
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_READ_TIMEOUT_STAT_OFFSET));
// http write timeouts
b->last = ngx_sprintf(b->last, "%d, ", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_WRITE_TIMEOUT_STAT_OFFSET));
// fail timeout
b->last = ngx_sprintf(b->last, "%ui, ", peers->peer[k].fail_timeout);
// max fails
b->last = ngx_sprintf(b->last, "%ui, ", peers->peer[k].max_fails);
// start_time
if (*(time_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_START_TIME_STAT_OFFSET) == 0) {
b->last = ngx_sprintf(b->last, "\"0000-00-00 00:00:00\", ");
} else {
char at_b[30];
struct tm *t = localtime((time_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_START_TIME_STAT_OFFSET));
strftime(at_b, sizeof(at_b), "%Y-%m-%d %H:%M:%S", t);
b->last = ngx_sprintf(b->last, "\"%s\", ", at_b);
}
// last fail
if (*(time_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset, USTATS_LAST_FAIL_TIME_STAT_OFFSET) == 0) {
b->last = ngx_sprintf(b->last, "\"0000-00-00 00:00:00\", ");
} else {
char at_b[30];
struct tm *t = localtime((time_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_LAST_FAIL_TIME_STAT_OFFSET));
strftime(at_b, sizeof(at_b), "%Y-%m-%d %H:%M:%S", t);
b->last = ngx_sprintf(b->last, "\"%s\", ", at_b);
}
// total fails
b->last = ngx_sprintf(b->last, "%d", *(ngx_uint_t *)USTATS_CALC_ADDRESS(peers->peer[k].shm_start_offset,
USTATS_FAIL_COUNT_STAT_OFFSET));
// close brackets, insert comma and new line
b->last = ngx_sprintf(b->last, "],\n");
}
// implicit
unsigned implicit = 0;
if ((peers->number && (!peers->peer[0].peer_server || !peers->peer[0].peer_server->name.data))) {
implicit = 1;
}
b->last = ngx_sprintf(b->last, " %d\n", implicit);
b->last = ngx_sprintf(b->last, " ]");
if (i < conf->upstreams.nelts - 1) {
b->last = ngx_sprintf(b->last, ",");
}
b->last = ngx_sprintf(b->last, "\n");
}
b->last = ngx_sprintf(b->last, "}\n");
return b;
}
static ngx_buf_t *ngx_http_ustats_create_response_html(ngx_http_request_t *r) {
size_t size = sizeof(HTML) + 3 * sizeof("0000000"); /* table width, height and update timer */
ngx_buf_t *b = ngx_create_temp_buf(r->pool, size);
ngx_http_ustats_loc_conf_t *uslc = ngx_http_get_module_loc_conf(r, ngx_http_ustats_module);
char buf1[8], buf2[8];
ngx_memset(buf1, 0, 8);
ngx_memset(buf2, 0, 8);
ngx_sprintf((u_char *)buf1, "%d%s", uslc->html_table_width,
uslc->html_table_width <= 100 ? "%" : "");
ngx_sprintf((u_char *)buf2, "%d%s", uslc->html_table_width,
uslc->html_table_height <= 100 ? "%" : "");
b->last = ngx_sprintf(b->last, HTML, buf1, buf2, uslc->refresh_interval);
return b;
}
static ngx_int_t ngx_http_ustats_log_handler(ngx_http_request_t *r) {
ngx_msec_int_t ms;
ngx_http_upstream_state_t *state;
if (!stats_data || r->upstream_states == NULL || r->upstream_states->nelts == 0) {
return NGX_OK;
}
state = r->upstream_states->elts;
if (state[0].peer && state[0].status) {
ms = (ngx_msec_int_t)(state[0].response_sec * 1000 + state[0].response_msec);
ms = ngx_max(ms, 0);
ngx_http_upstream_rr_peer_data_t *rrp = r->upstream->peer.rr_data ? r->upstream->peer.rr_data : r->upstream->peer.data;
volatile ngx_uint_t *ts_ptr = (ngx_uint_t *)USTATS_CALC_ADDRESS(rrp->peers->peer[rrp->current].shm_start_offset,
USTATS_TS_OFFSET);
volatile ngx_uint_t *rps_ptr = (ngx_uint_t *)USTATS_CALC_ADDRESS(rrp->peers->peer[rrp->current].shm_start_offset,
USTATS_REQ_COUNT_OFFSET);
volatile ngx_uint_t *speed_ptr = (ngx_uint_t *)USTATS_CALC_ADDRESS(rrp->peers->peer[rrp->current].shm_start_offset,
USTATS_REQ_TIMES_OFFSET);
ngx_time_t *tp = ngx_timeofday();
time_t stat_now = ngx_atomic_fetch_add(ts_ptr, 0);
if (tp->sec != stat_now && ngx_atomic_cmp_set(ts_ptr, stat_now, tp->sec)) {
ngx_uint_t rps_offset = 0;
ngx_uint_t speed_offset = 0;
switch (tp->sec % USTATS_REQ_MEASURE_COUNT) {
case 2:
rps_offset = USTATS_REQ_COUNT_3_OFFSET;
speed_offset = USTATS_REQ_TIMES_3_OFFSET;
break;
case 1:
rps_offset = USTATS_REQ_COUNT_2_OFFSET;
speed_offset = USTATS_REQ_TIMES_2_OFFSET;
break;
default:
rps_offset = USTATS_REQ_COUNT_1_OFFSET;
speed_offset = USTATS_REQ_TIMES_1_OFFSET;
}
// reset the data of the current cell
ngx_uint_t rps_count = ngx_atomic_fetch_add(rps_ptr, 0);
ngx_uint_t speed_count = ngx_atomic_fetch_add(speed_ptr, 0);