forked from FRiCKLE/ngx_cache_purge
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathngx_cache_purge_module.c
More file actions
3438 lines (2894 loc) · 113 KB
/
ngx_cache_purge_module.c
File metadata and controls
3438 lines (2894 loc) · 113 KB
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) 2009-2014, FRiCKLE <info@frickle.com>
* Copyright (c) 2009-2014, Piotr Sikora <piotr.sikora@frickle.com>
* Copyright (C) 2016-2026 Denis Denisov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ngx_config.h>
#include <nginx.h>
#include <ngx_core.h>
#include <ngx_http.h>
#ifndef nginx_version
# error This module cannot be built against an unknown nginx version.
#endif
#define NGX_CACHE_PURGE_RESPONSE_TYPE_HTML 1
#define NGX_CACHE_PURGE_RESPONSE_TYPE_XML 2
#define NGX_CACHE_PURGE_RESPONSE_TYPE_JSON 3
#define NGX_CACHE_PURGE_RESPONSE_TYPE_TEXT 4
#define NGX_CACHE_PURGE_QUEUE_SIZE_DEFAULT 1024
#define NGX_CACHE_PURGE_BATCH_SIZE_DEFAULT 10
/*
* This constant is assigned directly to an ngx_msec_t field via
* ngx_conf_init_msec_value() — it bypasses ngx_parse_time() and is
* therefore in raw milliseconds. The corresponding directive,
* cache_purge_throttle_ms, is parsed by ngx_conf_set_msec_slot which
* calls ngx_parse_time(value, 0): bare integers are treated as seconds
* per the nginx time-value contract, so operators must write an explicit
* suffix ("10ms", "1s", …) to get the intended unit.
*/
#define NGX_CACHE_PURGE_THROTTLE_MS_DEFAULT 10 /* milliseconds */
#define NGX_CACHE_PURGE_KEY_MAX_LEN 512
#define NGX_CACHE_PURGE_QUEUE_TIMEOUT 60000 /* ms */
/*
* Byte offset from the start of a cache file to the first character of the
* cached key string. The nginx cache file layout is:
*
* [ ngx_http_file_cache_header_t ][ "\nKEY: " ][ <key> ][ "\n" ]...
*
* sizeof(ngx_http_file_cache_header_t) skips the binary header.
* NGX_CACHE_PURGE_KEY_HDR_OFFSET (6) accounts for the literal prefix
* "\nKEY: " (newline + 'K' + 'E' + 'Y' + ':' + ' ' = 6 bytes).
*
* This layout has been stable since nginx 0.7.x. If it ever changes, only
* this constant and its comment need updating.
*/
#define NGX_CACHE_PURGE_KEY_HDR_OFFSET 6
/*
* Minimum shared-memory size for the background queue, expressed in pages.
* The slab allocator consumes an amount of metadata (pool header, slot
* descriptors, stat entries, page descriptors, and an alignment gap) that
* varies with nginx version, build flags, and architecture. Rather than
* attempting to compute that overhead from internal slab structs — which
* differ between nginx 1.8/1.9+, are affected by NGX_HAVE_POSIX_SEM /
* --with-threads, and scale with the OS page size (4 KB on x86 Linux,
* 8–64 KB on some *BSD / ARM / POWER platforms) — we simply enforce a
* floor of 8 pages. ngx_pagesize is the runtime value, so the minimum
* scales automatically on big-page architectures. 8 pages is generous
* enough to accommodate all slab metadata overhead while leaving several
* full pages of usable heap even for queue_size=1.
*/
#define NGX_CACHE_PURGE_SHM_MIN_PAGES 8
static const char ngx_http_cache_purge_content_type_json[] = "application/json";
static const char ngx_http_cache_purge_content_type_html[] = "text/html";
static const char ngx_http_cache_purge_content_type_xml[] = "text/xml";
static const char ngx_http_cache_purge_content_type_text[] = "text/plain";
static const size_t ngx_http_cache_purge_content_type_json_size =
sizeof(ngx_http_cache_purge_content_type_json);
static const size_t ngx_http_cache_purge_content_type_html_size =
sizeof(ngx_http_cache_purge_content_type_html);
static const size_t ngx_http_cache_purge_content_type_xml_size =
sizeof(ngx_http_cache_purge_content_type_xml);
static const size_t ngx_http_cache_purge_content_type_text_size =
sizeof(ngx_http_cache_purge_content_type_text);
static const char ngx_http_cache_purge_body_templ_json[] =
"{\"Key\": \"%s\", \"Status\": \"%s\"}";
static const char ngx_http_cache_purge_body_templ_html[] =
"<html><head><title>Cache Purge</title></head>"
"<body bgcolor=\"white\"><center><h1>Cache Purge</h1>"
"<p>Key: %s</p><p>Status: %s</p></center></body></html>";
static const char ngx_http_cache_purge_body_templ_xml[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<status><Key><![CDATA[%s]]></Key><Status>%s</Status></status>";
static const char ngx_http_cache_purge_body_templ_text[] =
"Key: %s\nStatus: %s\n";
static const size_t ngx_http_cache_purge_body_templ_json_size =
sizeof(ngx_http_cache_purge_body_templ_json);
static const size_t ngx_http_cache_purge_body_templ_html_size =
sizeof(ngx_http_cache_purge_body_templ_html);
static const size_t ngx_http_cache_purge_body_templ_xml_size =
sizeof(ngx_http_cache_purge_body_templ_xml);
static const size_t ngx_http_cache_purge_body_templ_text_size =
sizeof(ngx_http_cache_purge_body_templ_text);
#if (NGX_HTTP_CACHE)
/* -- forward declarations ----------------------------------------------- */
typedef struct ngx_http_cache_purge_queue_item_s ngx_http_cache_purge_queue_item_t;
typedef struct ngx_http_cache_purge_queue_s ngx_http_cache_purge_queue_t;
typedef struct ngx_http_cache_purge_main_conf_s ngx_http_cache_purge_main_conf_t;
/* -- data structures ---------------------------------------------------- */
struct ngx_http_cache_purge_queue_item_s {
ngx_str_t cache_path;
ngx_str_t key_partial;
ngx_uint_t hash;
ngx_flag_t purge_all;
ngx_uint_t in_progress; /* reserved for ABI stability */
ngx_msec_t enqueued_at;
ngx_http_cache_purge_queue_item_t *next;
};
struct ngx_http_cache_purge_queue_s {
ngx_http_cache_purge_queue_item_t *head;
ngx_http_cache_purge_queue_item_t *tail;
/*
* size is always read and written while queue->mutex is held.
* ngx_atomic_t was used historically but implies lock-free semantics that
* do not exist here. ngx_uint_t is the correct plain unsigned type.
*/
ngx_uint_t size;
ngx_shmtx_sh_t sh;
ngx_shmtx_t mutex;
ngx_slab_pool_t *shpool;
ngx_uint_t max_size;
ngx_uint_t batch_size;
ngx_msec_t throttle_ms;
};
struct ngx_http_cache_purge_main_conf_s {
ngx_http_cache_purge_queue_t *queue;
ngx_shm_zone_t *shm_zone;
ngx_uint_t queue_size;
ngx_uint_t batch_size;
ngx_msec_t throttle_ms;
ngx_flag_t background_purge;
ngx_flag_t legacy_status_codes;
/*
* vary_aware: when on, an exact-key purge walks the cache directory after
* deleting the primary file and removes any remaining files that carry the
* same KEY: string (i.e. Vary / gzip_vary variants at different paths).
* Disabled by default because it adds a full cache walk per purge request.
*/
ngx_flag_t vary_aware;
};
typedef struct {
ngx_flag_t enable;
ngx_str_t method;
ngx_flag_t purge_all;
ngx_array_t *access; /* ngx_in_cidr_t */
ngx_array_t *access6; /* ngx_in6_cidr_t */
} ngx_http_cache_purge_conf_t;
typedef struct {
# if (NGX_HTTP_FASTCGI)
ngx_http_cache_purge_conf_t fastcgi;
# endif
# if (NGX_HTTP_PROXY)
ngx_http_cache_purge_conf_t proxy;
# endif
# if (NGX_HTTP_SCGI)
ngx_http_cache_purge_conf_t scgi;
# endif
# if (NGX_HTTP_UWSGI)
ngx_http_cache_purge_conf_t uwsgi;
# endif
ngx_http_cache_purge_conf_t *conf;
ngx_http_handler_pt handler;
ngx_http_handler_pt original_handler;
ngx_uint_t response_type;
# if (NGX_HTTP_PROXY)
/*
* Separate-location syntax stores the cache zone and purge key here
* instead of in plcf->upstream, which avoids triggering nginx's internal
* proxy_cache merge path and the resulting duplicate location "/" error
* introduced in nginx >= 1.27.x.
*/
ngx_shm_zone_t *proxy_separate_zone; /* static zone name */
ngx_http_complex_value_t *proxy_separate_value; /* dynamic zone expr */
ngx_http_complex_value_t proxy_separate_key; /* purge key template*/
# endif
} ngx_http_cache_purge_loc_conf_t;
typedef struct {
u_char *key_partial;
ngx_uint_t key_len;
u_char key_buffer[NGX_CACHE_PURGE_KEY_MAX_LEN];
ngx_uint_t files_deleted;
ngx_uint_t files_checked;
/*
* cache is set by ngx_http_cache_purge_delete_variants() so that
* delete_exact_file can update shm metadata (sh->size, node->exists,
* node->fs_size) for each variant it deletes. NULL in all other walk
* contexts where metadata updates are not needed.
*/
ngx_http_file_cache_t *cache;
} ngx_http_cache_purge_walk_ctx_t;
/* -- function prototypes ------------------------------------------------ */
static void *ngx_http_cache_purge_create_main_conf(ngx_conf_t *cf);
static char *ngx_http_cache_purge_init_main_conf(ngx_conf_t *cf, void *conf);
static ngx_int_t ngx_http_cache_purge_init_shm_zone(ngx_shm_zone_t *shm_zone,
void *data);
static ngx_int_t ngx_http_cache_purge_init_worker(ngx_cycle_t *cycle);
static void ngx_http_cache_purge_exit_worker(ngx_cycle_t *cycle);
static void ngx_http_cache_purge_background_handler(ngx_event_t *ev);
static ngx_int_t ngx_http_cache_purge_enqueue(ngx_http_request_t *r,
ngx_http_file_cache_t *cache, ngx_str_t *key, ngx_flag_t purge_all);
static ngx_int_t ngx_http_cache_purge_process_queue(ngx_cycle_t *cycle);
static ngx_uint_t ngx_http_cache_purge_hash_key(ngx_str_t *cache_path,
ngx_str_t *key);
static ngx_http_cache_purge_queue_item_t *ngx_http_cache_purge_find_duplicate(
ngx_http_cache_purge_queue_t *queue, ngx_uint_t hash,
ngx_str_t *cache_path, ngx_str_t *key);
# if (NGX_HTTP_FASTCGI)
char *ngx_http_fastcgi_cache_purge_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
ngx_int_t ngx_http_fastcgi_cache_purge_handler(ngx_http_request_t *r);
# endif
# if (NGX_HTTP_PROXY)
char *ngx_http_proxy_cache_purge_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
ngx_int_t ngx_http_proxy_cache_purge_handler(ngx_http_request_t *r);
# endif
# if (NGX_HTTP_SCGI)
char *ngx_http_scgi_cache_purge_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
ngx_int_t ngx_http_scgi_cache_purge_handler(ngx_http_request_t *r);
# endif
# if (NGX_HTTP_UWSGI)
char *ngx_http_uwsgi_cache_purge_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
ngx_int_t ngx_http_uwsgi_cache_purge_handler(ngx_http_request_t *r);
# endif
char *ngx_http_cache_purge_response_type_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
char *ngx_http_cache_purge_queue_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
char *ngx_http_cache_purge_legacy_status_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
char *ngx_http_cache_purge_vary_aware_conf(ngx_conf_t *cf,
ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_purge_file_cache_noop(ngx_tree_ctx_t *ctx,
ngx_str_t *path);
static ngx_int_t ngx_http_purge_file_cache_delete_file(ngx_tree_ctx_t *ctx,
ngx_str_t *path);
static ngx_int_t ngx_http_purge_file_cache_delete_partial_file(
ngx_tree_ctx_t *ctx, ngx_str_t *path);
/*
* ngx_http_purge_file_cache_delete_exact_file:
*
* Vary-aware exact-match handler. Reads (key_len + 1) bytes from the
* cache file at the KEY: offset. Deletes the file only when:
* - the first key_len bytes match key_partial exactly (case-insensitive), AND
* - the byte immediately following the key is '\n'
*
* The '\n' check confirms the stored key is exactly key_len characters, so
* keys that are longer but share a common prefix are not matched. Because all
* Vary variants of an entry store the same KEY: string, this walk removes every
* variant file regardless of the filesystem path each one occupies.
*/
static ngx_int_t ngx_http_purge_file_cache_delete_exact_file(
ngx_tree_ctx_t *ctx, ngx_str_t *path);
static void ngx_http_cache_purge_invalidate_node(ngx_http_file_cache_t *cache,
ngx_str_t *path);
static void ngx_http_cache_purge_delete_variants(ngx_http_request_t *r,
ngx_http_file_cache_t *cache);
ngx_int_t ngx_http_cache_purge_access_handler(ngx_http_request_t *r);
ngx_int_t ngx_http_cache_purge_access(ngx_array_t *a, ngx_array_t *a6,
struct sockaddr *s);
ngx_int_t ngx_http_cache_purge_send_response(ngx_http_request_t *r,
ngx_str_t *status);
# if (nginx_version >= 1007009)
ngx_int_t ngx_http_cache_purge_cache_get(ngx_http_request_t *r,
ngx_http_upstream_t *u, ngx_http_file_cache_t **cache);
# endif
ngx_int_t ngx_http_cache_purge_init(ngx_http_request_t *r,
ngx_http_file_cache_t *cache,
ngx_http_complex_value_t *cache_key);
void ngx_http_cache_purge_handler(ngx_http_request_t *r);
ngx_int_t ngx_http_file_cache_purge(ngx_http_request_t *r);
void ngx_http_cache_purge_all(ngx_http_request_t *r,
ngx_http_file_cache_t *cache);
ngx_uint_t ngx_http_cache_purge_partial(ngx_http_request_t *r,
ngx_http_file_cache_t *cache);
ngx_int_t ngx_http_cache_purge_is_partial(ngx_http_request_t *r);
char *ngx_http_cache_purge_conf(ngx_conf_t *cf,
ngx_http_cache_purge_conf_t *cpcf);
void *ngx_http_cache_purge_create_loc_conf(ngx_conf_t *cf);
char *ngx_http_cache_purge_merge_loc_conf(ngx_conf_t *cf,
void *parent, void *child);
/* -- module commands ---------------------------------------------------- */
static ngx_command_t ngx_http_cache_purge_module_commands[] = {
# if (NGX_HTTP_FASTCGI)
{ ngx_string("fastcgi_cache_purge"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_fastcgi_cache_purge_conf,
NGX_HTTP_LOC_CONF_OFFSET, 0, NULL },
# endif
# if (NGX_HTTP_PROXY)
{ ngx_string("proxy_cache_purge"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_proxy_cache_purge_conf,
NGX_HTTP_LOC_CONF_OFFSET, 0, NULL },
# endif
# if (NGX_HTTP_SCGI)
{ ngx_string("scgi_cache_purge"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_scgi_cache_purge_conf,
NGX_HTTP_LOC_CONF_OFFSET, 0, NULL },
# endif
# if (NGX_HTTP_UWSGI)
{ ngx_string("uwsgi_cache_purge"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_http_uwsgi_cache_purge_conf,
NGX_HTTP_LOC_CONF_OFFSET, 0, NULL },
# endif
{ ngx_string("cache_purge_response_type"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
ngx_http_cache_purge_response_type_conf,
NGX_HTTP_LOC_CONF_OFFSET, 0, NULL },
{ ngx_string("cache_purge_background_queue"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_http_cache_purge_queue_conf,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, background_purge), NULL },
{ ngx_string("cache_purge_queue_size"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, queue_size), NULL },
{ ngx_string("cache_purge_batch_size"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, batch_size), NULL },
/* Accepts standard nginx time values. A bare integer means seconds per
* the nginx time-value contract; use an explicit suffix for milliseconds:
* cache_purge_throttle_ms 10ms; -- 10 ms (correct)
* cache_purge_throttle_ms 10; -- 10 s (almost certainly wrong)
* Default when directive is absent: 10 ms (set via ngx_conf_init_msec_value,
* which bypasses the parser and assigns the raw integer directly). */
{ ngx_string("cache_purge_throttle_ms"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, throttle_ms), NULL },
{ ngx_string("cache_purge_legacy_status"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_http_cache_purge_legacy_status_conf,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, legacy_status_codes), NULL },
{ ngx_string("cache_purge_vary_aware"),
NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_http_cache_purge_vary_aware_conf,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(ngx_http_cache_purge_main_conf_t, vary_aware), NULL },
ngx_null_command
};
/* -- module context & descriptor ---------------------------------------- */
static ngx_http_module_t ngx_http_cache_purge_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
ngx_http_cache_purge_create_main_conf, /* create main conf */
ngx_http_cache_purge_init_main_conf, /* init main conf */
NULL, /* create srv conf */
NULL, /* merge srv conf */
ngx_http_cache_purge_create_loc_conf, /* create loc conf */
ngx_http_cache_purge_merge_loc_conf /* merge loc conf */
};
ngx_module_t ngx_http_cache_purge_module = {
NGX_MODULE_V1,
&ngx_http_cache_purge_module_ctx,
ngx_http_cache_purge_module_commands,
NGX_HTTP_MODULE,
NULL, /* init master */
NULL, /* init module */
ngx_http_cache_purge_init_worker, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
ngx_http_cache_purge_exit_worker, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
/* Per-worker globals — safe because nginx forks one process per worker */
static ngx_event_t ngx_cache_purge_event;
static ngx_http_cache_purge_main_conf_t *ngx_cache_purge_main_conf;
/* -- main configuration ------------------------------------------------- */
static void *
ngx_http_cache_purge_create_main_conf(ngx_conf_t *cf)
{
ngx_http_cache_purge_main_conf_t *cmcf;
cmcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_cache_purge_main_conf_t));
if (cmcf == NULL) {
return NULL;
}
cmcf->background_purge = NGX_CONF_UNSET;
cmcf->queue_size = NGX_CONF_UNSET_UINT;
cmcf->batch_size = NGX_CONF_UNSET_UINT;
cmcf->throttle_ms = NGX_CONF_UNSET_MSEC;
cmcf->legacy_status_codes = NGX_CONF_UNSET;
cmcf->vary_aware = NGX_CONF_UNSET;
return cmcf;
}
static char *
ngx_http_cache_purge_init_main_conf(ngx_conf_t *cf, void *conf)
{
ngx_http_cache_purge_main_conf_t *cmcf = conf;
ngx_str_t name = ngx_string("cache_purge_queue");
size_t shm_size;
size_t stride; /* bytes per queue slot (item + 2 keys) */
ngx_conf_init_value(cmcf->background_purge, 0);
ngx_conf_init_uint_value(cmcf->queue_size, NGX_CACHE_PURGE_QUEUE_SIZE_DEFAULT);
ngx_conf_init_uint_value(cmcf->batch_size, NGX_CACHE_PURGE_BATCH_SIZE_DEFAULT);
ngx_conf_init_msec_value(cmcf->throttle_ms, NGX_CACHE_PURGE_THROTTLE_MS_DEFAULT);
/* Default on: return 412 for missing entries (backwards compatibility) */
ngx_conf_init_value(cmcf->legacy_status_codes, 1);
/* Default off: vary-aware walk adds cost; opt in explicitly */
ngx_conf_init_value(cmcf->vary_aware, 0);
/*
* Reject zero values: queue_size=0 makes the queue permanently "full"
* (every enqueue hits the size >= max_size guard); batch_size=0 makes
* process_queue a no-op loop that never processes any item.
*/
if (cmcf->queue_size == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"cache_purge_queue_size must be greater than 0");
return NGX_CONF_ERROR;
}
if (cmcf->batch_size == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"cache_purge_batch_size must be greater than 0");
return NGX_CONF_ERROR;
}
if (!cmcf->background_purge) {
return NGX_CONF_OK;
}
/*
* Guard against unsigned integer overflow in the shm_size calculation.
*
* shm_size = sizeof(queue_t)
* + queue_size * sizeof(item_t)
* + queue_size * 2 * KEY_MAX_LEN
* = sizeof(queue_t) + queue_size * stride
*
* Overflow condition (unsigned arithmetic):
* queue_size > (SIZE_MAX - sizeof(queue_t)) / stride
*
* where SIZE_MAX is represented as (size_t) -1, valid in C89/C90.
*/
stride = sizeof(ngx_http_cache_purge_queue_item_t)
+ 2 * NGX_CACHE_PURGE_KEY_MAX_LEN;
if (cmcf->queue_size > ((size_t) -1
- sizeof(ngx_http_cache_purge_queue_t)) / stride)
{
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"cache_purge_queue_size %ui overflows shared "
"memory size calculation", cmcf->queue_size);
return NGX_CONF_ERROR;
}
shm_size = sizeof(ngx_http_cache_purge_queue_t)
+ cmcf->queue_size * sizeof(ngx_http_cache_purge_queue_item_t)
+ cmcf->queue_size * 2 * NGX_CACHE_PURGE_KEY_MAX_LEN;
/*
* The slab allocator imposes metadata overhead that is NOT reflected in
* the payload calculation above:
*
* ngx_slab_pool_t header — size varies by nginx version, build flags
* (e.g. NGX_HAVE_POSIX_SEM, --with-threads),
* and platform ABI.
* Slot descriptors — (pagesize_shift - min_shift) page structs.
* Stat entries — same count, added in nginx ~1.9.x.
* Page descriptors — one per allocatable page.
* Alignment gap — up to one full page between descriptors
* and the first usable byte (pool->start is
* rounded up to the next page boundary).
*
* Attempting to compute this precisely requires knowledge of internal
* nginx structs that differ across versions (1.8 vs 1.9+), build
* configurations, and architectures (Linux, *BSD, Solaris, macOS —
* each may have different page sizes: 4 KB, 8 KB, 16 KB, 64 KB).
*
* The portable, version-agnostic approach: round up the payload to a
* page boundary, then enforce a minimum of NGX_CACHE_PURGE_SHM_MIN_PAGES
* pages. This minimum is chosen so that, on every supported platform,
* the slab overhead leaves at least one full page of usable heap even
* when queue_size=1. ngx_pagesize is always the runtime system page
* size, so the minimum scales automatically on big-page architectures.
*/
shm_size = ngx_align(shm_size, ngx_pagesize);
if (shm_size < NGX_CACHE_PURGE_SHM_MIN_PAGES * ngx_pagesize) {
shm_size = NGX_CACHE_PURGE_SHM_MIN_PAGES * ngx_pagesize;
}
cmcf->shm_zone = ngx_shared_memory_add(cf, &name, shm_size,
&ngx_http_cache_purge_module);
if (cmcf->shm_zone == NULL) {
return NGX_CONF_ERROR;
}
cmcf->shm_zone->init = ngx_http_cache_purge_init_shm_zone;
cmcf->shm_zone->data = cmcf;
return NGX_CONF_OK;
}
/*
* Shared-memory zone initialiser — called by the master process once per
* nginx start or live reload.
*
* First boot (data == NULL):
* Allocate and initialise the queue struct inside the slab pool.
*
* Live reload (data == previous cycle's cmcf):
* Re-use the existing queue so that items already enqueued by the old
* workers are not lost. The queue pointer is transplanted to the new
* cmcf so workers spawned for the new cycle find it immediately.
*
* Configuration values that live inside the queue struct (batch_size,
* throttle_ms, max_size) are refreshed under the queue mutex so that
* worker timers that fire during the reload window see the new values
* atomically. max_size is intentionally NOT reduced below the current
* queue->size to avoid making the queue appear "always full" mid-reload.
*/
static ngx_int_t
ngx_http_cache_purge_init_shm_zone(ngx_shm_zone_t *shm_zone, void *data)
{
ngx_http_cache_purge_main_conf_t *cmcf = shm_zone->data;
ngx_http_cache_purge_main_conf_t *old = data;
ngx_http_cache_purge_queue_t *queue;
ngx_slab_pool_t *shpool;
if (old != NULL) {
/*
* Live reload path. Propagate the existing queue so that items
* queued before the reload are not dropped. Then refresh the
* tuneable fields so that changes to cache_purge_batch_size,
* cache_purge_throttle_ms, and cache_purge_queue_size take effect
* without requiring a full restart.
*
* max_size: use the larger of the new configured value and the
* current occupancy. Shrinking max_size below the live queue depth
* would cause every subsequent enqueue to be rejected as "queue
* full" until the background worker drains the backlog.
*/
queue = old->queue;
cmcf->queue = queue;
ngx_shmtx_lock(&queue->mutex);
queue->batch_size = cmcf->batch_size;
queue->throttle_ms = cmcf->throttle_ms;
queue->max_size = (cmcf->queue_size > queue->size)
? cmcf->queue_size : queue->size;
ngx_shmtx_unlock(&queue->mutex);
return NGX_OK;
}
shpool = (ngx_slab_pool_t *) shm_zone->shm.addr;
queue = ngx_slab_calloc(shpool, sizeof(ngx_http_cache_purge_queue_t));
if (queue == NULL) {
ngx_log_error(NGX_LOG_EMERG, shm_zone->shm.log, 0,
"ngx_cache_purge: could not allocate queue "
"in shared memory zone \"%V\"", &shm_zone->shm.name);
return NGX_ERROR;
}
queue->shpool = shpool;
queue->max_size = cmcf->queue_size;
queue->batch_size = cmcf->batch_size;
queue->throttle_ms = cmcf->throttle_ms;
if (ngx_shmtx_create(&queue->mutex, &queue->sh, NULL) != NGX_OK) {
return NGX_ERROR;
}
cmcf->queue = queue;
return NGX_OK;
}
/* -- worker lifecycle --------------------------------------------------- */
static ngx_int_t
ngx_http_cache_purge_init_worker(ngx_cycle_t *cycle)
{
ngx_http_core_main_conf_t *cmcf_core;
ngx_http_cache_purge_main_conf_t *cmcf;
cmcf_core = ngx_http_cycle_get_module_main_conf(cycle, ngx_http_core_module);
if (cmcf_core == NULL) {
return NGX_OK;
}
cmcf = ngx_http_cycle_get_module_main_conf(cycle, ngx_http_cache_purge_module);
if (cmcf == NULL || !cmcf->background_purge) {
return NGX_OK;
}
ngx_cache_purge_main_conf = cmcf;
ngx_memzero(&ngx_cache_purge_event, sizeof(ngx_event_t));
ngx_cache_purge_event.handler = ngx_http_cache_purge_background_handler;
ngx_cache_purge_event.log = cycle->log;
ngx_cache_purge_event.data = cycle;
/*
* Mark the timer as cancelable (nginx >= 1.11.11, June 2017).
* Without this flag nginx's graceful-shutdown path waits for every
* pending timer to fire before allowing the worker to exit. Because
* this handler re-arms itself on every invocation the worker would
* never exit cleanly, causing Test::Nginx (and real deployments) to
* time out and fall back to SIGKILL. "cancelable" tells the event
* loop: "discard this timer when the worker is exiting — do not wait
* for it." All nginx versions we support (≥ 1.20) have this field.
*/
ngx_cache_purge_event.cancelable = 1;
ngx_add_timer(&ngx_cache_purge_event, cmcf->throttle_ms);
return NGX_OK;
}
static void
ngx_http_cache_purge_exit_worker(ngx_cycle_t *cycle)
{
if (ngx_cache_purge_event.timer_set) {
ngx_del_timer(&ngx_cache_purge_event);
}
}
/*
* Background timer callback — fires every throttle_ms milliseconds.
*
* Each invocation calls process_queue(), which dequeues and walks exactly
* one item before returning. This one-item-per-tick design ensures the
* event loop is never blocked for more than the duration of a single
* directory walk, regardless of queue depth.
*
* NGX_AGAIN — one item was processed; re-arm with throttle_ms so the
* next item is handled promptly.
*
* NGX_OK — queue is empty; re-arm with throttle_ms * 10 to avoid
* busy-polling on an idle queue.
*
* NGX_ERROR — module not yet initialised; use the raw constant and
* retry next tick.
*
* Historical note: the previous implementation called ngx_msleep() inside
* the callback to throttle I/O. ngx_msleep() is a literal usleep() that
* blocks the OS thread — stalling every connection on that worker for the
* full sleep duration. Timer-based yielding is the correct nginx idiom.
*/
static void
ngx_http_cache_purge_background_handler(ngx_event_t *ev)
{
ngx_cycle_t *cycle = ev->data;
ngx_http_cache_purge_main_conf_t *cmcf = ngx_cache_purge_main_conf;
ngx_int_t rc;
ngx_msec_t next_delay;
if (cmcf == NULL || cmcf->queue == NULL) {
/* cmcf not yet initialised; use the raw-ms constant directly
* (not through ngx_parse_time, so no ×1000 conversion). */
ngx_add_timer(ev, NGX_CACHE_PURGE_THROTTLE_MS_DEFAULT);
return;
}
rc = ngx_http_cache_purge_process_queue(cycle);
/*
* NGX_AGAIN → an item was processed and more remain; come back soon.
* NGX_OK → queue is now empty; back off to avoid busy-polling.
* NGX_ERROR → configuration problem; back off.
*/
next_delay = (rc == NGX_AGAIN) ? cmcf->throttle_ms
: cmcf->throttle_ms * 10;
ngx_add_timer(ev, next_delay);
}
/* -- queue operations --------------------------------------------------- */
static ngx_int_t
ngx_http_cache_purge_enqueue(ngx_http_request_t *r,
ngx_http_file_cache_t *cache, ngx_str_t *key, ngx_flag_t purge_all)
{
ngx_http_cache_purge_main_conf_t *cmcf;
ngx_http_cache_purge_queue_t *queue;
ngx_http_cache_purge_queue_item_t *item;
ngx_uint_t hash;
u_char *p;
cmcf = ngx_http_get_module_main_conf(r, ngx_http_cache_purge_module);
if (cmcf == NULL || cmcf->queue == NULL) {
return NGX_ERROR;
}
queue = cmcf->queue;
hash = ngx_http_cache_purge_hash_key(&cache->path->name, key);
ngx_shmtx_lock(&queue->mutex);
if (queue->size >= queue->max_size) {
ngx_shmtx_unlock(&queue->mutex);
ngx_log_error(NGX_LOG_WARN, r->connection->log, 0,
"ngx_cache_purge: queue full (%ui/%ui items), "
"falling back to synchronous purge",
queue->size, queue->max_size);
return NGX_ERROR;
}
if (ngx_http_cache_purge_find_duplicate(queue, hash,
&cache->path->name, key) != NULL)
{
ngx_shmtx_unlock(&queue->mutex);
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"ngx_cache_purge: duplicate enqueue for \"%V\" "
"key \"%V\", skipping", &cache->path->name, key);
return NGX_OK;
}
item = ngx_slab_calloc(queue->shpool,
sizeof(ngx_http_cache_purge_queue_item_t));
if (item == NULL) {
ngx_shmtx_unlock(&queue->mutex);
ngx_log_error(NGX_LOG_CRIT, r->connection->log, 0,
"ngx_cache_purge: shared memory exhausted, "
"could not allocate queue item");
return NGX_ERROR;
}
/* +1: NUL terminator required by opendir / ngx_walk_tree */
p = ngx_slab_alloc(queue->shpool, cache->path->name.len + 1);
if (p == NULL) {
ngx_slab_free(queue->shpool, item);
ngx_shmtx_unlock(&queue->mutex);
ngx_log_error(NGX_LOG_CRIT, r->connection->log, 0,
"ngx_cache_purge: shared memory exhausted, "
"could not allocate cache path buffer");
return NGX_ERROR;
}
ngx_memcpy(p, cache->path->name.data, cache->path->name.len);
p[cache->path->name.len] = '\0';
item->cache_path.data = p;
item->cache_path.len = cache->path->name.len;
if (key->len > 0) {
/* +1: NUL terminator for string comparisons */
p = ngx_slab_alloc(queue->shpool, key->len + 1);
if (p == NULL) {
ngx_slab_free(queue->shpool, item->cache_path.data);
ngx_slab_free(queue->shpool, item);
ngx_shmtx_unlock(&queue->mutex);
ngx_log_error(NGX_LOG_CRIT, r->connection->log, 0,
"ngx_cache_purge: shared memory exhausted, "
"could not allocate key buffer");
return NGX_ERROR;
}
ngx_memcpy(p, key->data, key->len);
p[key->len] = '\0';
item->key_partial.data = p;
item->key_partial.len = key->len;
}
item->hash = hash;
item->purge_all = purge_all;
item->in_progress = 0;
item->enqueued_at = ngx_current_msec;
if (queue->tail != NULL) {
queue->tail->next = item;
} else {
queue->head = item;
}
queue->tail = item;
queue->size++;
/*
* Capture size while the mutex is still held. Reading queue->size
* after ngx_shmtx_unlock() would be a data race on a non-atomic
* variable: another worker could modify it between the unlock and the
* log call. The captured value is only used for a debug log, so a
* value that is one behind by the time the message is written is
* acceptable — correctness is not affected.
*/
hash = queue->size; /* reuse 'hash' (ngx_uint_t) as a size snapshot */
ngx_shmtx_unlock(&queue->mutex);
ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
"ngx_cache_purge: enqueued purge of \"%V\" key \"%V\" "
"(%ui item(s) in queue)",
&cache->path->name, key, hash);
return NGX_OK;
}
/*
* process_queue — dequeue and walk exactly one item per invocation.
*
* Design: one item per timer tick. The caller (background_handler) re-arms
* the timer with throttle_ms after each call, giving the nginx event loop a
* chance to handle connections between every directory walk. This keeps
* purge I/O from monopolising the worker for an unbounded duration.
*
* Two-phase execution:
* Phase 1 — dequeue under the mutex.
* The item is unlinked from the queue head and queue->size is decremented
* while the lock is held. Items older than NGX_CACHE_PURGE_QUEUE_TIMEOUT
* are freed in place (slab_free is called while the lock is held for
* timed-out items only, because no subsequent walk is needed).
* Phase 2 — walk outside the lock.
* ngx_walk_tree() and ngx_slab_free() run after ngx_shmtx_unlock().
* This keeps the critical section short and preserves the required
* lock ordering: queue_mutex → shpool_mutex (slab_free acquires shpool).
*
* Return values:
* NGX_AGAIN — one item was processed; caller should re-arm promptly.
* NGX_OK — queue is empty; caller should apply the backoff delay.
* NGX_ERROR — module not initialised; caller should apply backoff.
*/
static ngx_int_t
ngx_http_cache_purge_process_queue(ngx_cycle_t *cycle)
{
ngx_http_cache_purge_main_conf_t *cmcf;
ngx_http_cache_purge_queue_t *queue;
ngx_http_cache_purge_queue_item_t *item;
ngx_http_cache_purge_walk_ctx_t ctx;
ngx_tree_ctx_t tree;
ngx_msec_t now;
cmcf = ngx_cache_purge_main_conf;
if (cmcf == NULL || cmcf->queue == NULL) {
return NGX_ERROR;
}
queue = cmcf->queue;
now = ngx_current_msec;
item = NULL;
/* Phase 1: dequeue one live item under the lock */
ngx_shmtx_lock(&queue->mutex);
while (queue->head != NULL) {
item = queue->head;
queue->head = item->next;
if (queue->head == NULL) {
queue->tail = NULL;
}
queue->size--;
item->next = NULL;
if ((now - item->enqueued_at) > NGX_CACHE_PURGE_QUEUE_TIMEOUT) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"ngx_cache_purge: purge of \"%V\" key \"%V\" "
"timed out after %Mms, discarding",
&item->cache_path, &item->key_partial,
now - item->enqueued_at);
ngx_slab_free(queue->shpool, item->cache_path.data);
if (item->key_partial.data) {
ngx_slab_free(queue->shpool, item->key_partial.data);
}
ngx_slab_free(queue->shpool, item);
item = NULL;
continue; /* try the next head */
}
break; /* got a live item */
}
ngx_shmtx_unlock(&queue->mutex);
if (item == NULL) {
return NGX_OK; /* queue empty */
}
/* Phase 2: walk the cache directory outside the lock */
ngx_memzero(&ctx, sizeof(ngx_http_cache_purge_walk_ctx_t));
ngx_memzero(&tree, sizeof(ngx_tree_ctx_t));
tree.pre_tree_handler = ngx_http_purge_file_cache_noop;
tree.post_tree_handler = ngx_http_purge_file_cache_noop;
tree.spec_handler = ngx_http_purge_file_cache_noop;
tree.data = &ctx;
tree.log = cycle->log;
if (item->purge_all) {
tree.file_handler = ngx_http_purge_file_cache_delete_file;
ngx_walk_tree(&tree, &item->cache_path);
} else if (item->key_partial.len > 0) {
ctx.key_partial = item->key_partial.data;
ctx.key_len = item->key_partial.len;
if (ctx.key_len > 0 && ctx.key_partial[ctx.key_len - 1] == '*') {
ctx.key_len--;
}
tree.file_handler = ngx_http_purge_file_cache_delete_partial_file;
ngx_walk_tree(&tree, &item->cache_path);
}
ngx_log_debug3(NGX_LOG_DEBUG_HTTP, cycle->log, 0,
"ngx_cache_purge: background walk of \"%V\" key \"%V\" "
"deleted %ui file(s)",
&item->cache_path, &item->key_partial, ctx.files_deleted);
ngx_slab_free(queue->shpool, item->cache_path.data);
if (item->key_partial.data) {
ngx_slab_free(queue->shpool, item->key_partial.data);
}
ngx_slab_free(queue->shpool, item);
return NGX_AGAIN;
}