Repository navigation
Expand file tree
/
Copy pathinit.lua
More file actions
1547 lines (1196 loc) · 46 KB
/
Copy pathinit.lua
File metadata and controls
1547 lines (1196 loc) · 46 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
-- Kong, the biggest ape in town
--
-- /\ ____
-- <> ( oo )
-- <>_| ^^ |_
-- <> @ \
-- /~~\ . . _ |
-- /~~~~\ | |
-- /~~~~~~\/ _| |
-- |[][][]/ / [m]
-- |[][][[m]
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[|--|]|
-- |[| |]|
-- ========
-- ==========
-- |[[ ]]|
-- ==========
local pcall = pcall
pcall(require, "luarocks.loader")
assert(package.loaded["resty.core"], "lua-resty-core must be loaded; make " ..
"sure 'lua_load_resty_core' is not "..
"disabled.")
local constants = require "kong.constants"
do
-- let's ensure the required shared dictionaries are
-- declared via lua_shared_dict in the Nginx conf
for _, dict in ipairs(constants.DICTS) do
if not ngx.shared[dict] then
return error("missing shared dict '" .. dict .. "' in Nginx " ..
"configuration, are you using a custom template? " ..
"Make sure the 'lua_shared_dict " .. dict .. " [SIZE];' " ..
"directive is defined.")
end
end
-- if we're running `nginx -t` then don't initialize
if os.getenv("KONG_NGINX_CONF_CHECK") then
return {
init = function() end,
}
end
end
10BC8
require("kong.globalpatches")()
local kong_global = require "kong.global"
local PHASES = kong_global.phases
_G.kong = kong_global.new() -- no versioned PDK for plugins for now
local DB = require "kong.db"
local dns = require "kong.tools.dns"
local meta = require "kong.meta"
local lapis = require "lapis"
local runloop = require "kong.runloop.handler"
local stream_api = require "kong.tools.stream_api"
local singletons = require "kong.singletons"
local declarative = require "kong.db.declarative"
local ngx_balancer = require "ngx.balancer"
local kong_resty_ctx = require "kong.resty.ctx"
local certificate = require "kong.runloop.certificate"
local concurrency = require "kong.concurrency"
local cache_warmup = require "kong.cache.warmup"
local balancer = require "kong.runloop.balancer"
local kong_error_handlers = require "kong.error_handlers"
local migrations_utils = require "kong.cmd.utils.migrations"
local plugin_servers = require "kong.runloop.plugin_servers"
local kong = kong
local ngx = ngx
local now = ngx.now
local update_time = ngx.update_time
local var = ngx.var
local arg = ngx.arg
local header = ngx.header
local ngx_log = ngx.log
local ngx_ALERT = ngx.ALERT
local ngx_CRIT = ngx.CRIT
local ngx_ERR = ngx.ERR
local ngx_WARN = ngx.WARN
local ngx_NOTICE = ngx.NOTICE
local ngx_INFO = ngx.INFO
local ngx_DEBUG = ngx.DEBUG
local is_http_module = ngx.config.subsystem == "http"
local is_stream_module = ngx.config.subsystem == "stream"
local start_time = ngx.req.start_time
local type = type
local error = error
local ipairs = ipairs
local assert = assert
local tostring = tostring
local coroutine = coroutine
local get_last_failure = ngx_balancer.get_last_failure
local set_current_peer = ngx_balancer.set_current_peer
local set_timeouts = ngx_balancer.set_timeouts
local set_more_tries = ngx_balancer.set_more_tries
local enable_keepalive = ngx_balancer.enable_keepalive
if not enable_keepalive then
ngx_log(ngx_WARN, "missing method 'ngx_balancer.enable_keepalive()' ",
"(was the dyn_upstream_keepalive patch applied?) ",
"set the 'nginx_upstream_keepalive' configuration ",
"property instead of 'upstream_keepalive_pool_size'")
end
local DECLARATIVE_LOAD_KEY = constants.DECLARATIVE_LOAD_KEY
local DECLARATIVE_HASH_KEY = constants.DECLARATIVE_HASH_KEY
local declarative_entities
local declarative_meta
local schema_state
local stash_init_worker_error
local log_init_worker_errors
do
local init_worker_errors
local init_worker_errors_str
local ctx_k = {}
stash_init_worker_error = function(err)
if err == nil then
return
end
err = tostring(err)
if not init_worker_errors then
init_worker_errors = {}
end
table.insert(init_worker_errors, err)
init_worker_errors_str = table.concat(init_worker_errors, ", ")
return ngx_log(ngx_CRIT, "worker initialization error: ", err,
"; this node must be restarted")
end
log_init_worker_errors = function(ctx)
if not init_worker_errors_str or ctx[ctx_k] then
return
end
ctx[ctx_k] = true
return ngx_log(ngx_ALERT, "unsafe request processing due to earlier ",
"initialization errors; this node must be ",
"restarted (", init_worker_errors_str, ")")
end
end
local reset_kong_shm
do
local DECLARATIVE_PAGE_KEY = constants.DECLARATIVE_PAGE_KEY
local preserve_keys = {
"kong:node_id",
"events:requests",
"events:requests:http",
"events:requests:https",
"events:requests:h2c",
"events:requests:h2",
"events:requests:grpc",
"events:requests:grpcs",
"events:requests:ws",
"events:requests:wss",
"events:requests:go_plugins",
"events:streams",
"events:streams:tcp",
"events:streams:tls",
}
reset_kong_shm = function(config)
local kong_shm = ngx.shared.kong
local dbless = config.database == "off"
if dbless then
-- prevent POST /config while initializing dbless
declarative.try_lock()
end
local old_page = kong_shm:get(DECLARATIVE_PAGE_KEY)
if old_page == nil then -- fresh node, just storing the initial page
kong_shm:set(DECLARATIVE_PAGE_KEY, 1)
return
end
local preserved = {}
local new_page = old_page
if dbless then
if config.declarative_config or config.declarative_config_string then
new_page = old_page == 1 and 2 or 1
else
preserved[DECLARATIVE_LOAD_KEY] = kong_shm:get(DECLARATIVE_LOAD_KEY)
preserved[DECLARATIVE_HASH_KEY] = kong_shm:get(DECLARATIVE_HASH_KEY)
end
end
preserved[DECLARATIVE_PAGE_KEY] = new_page
for _, key in ipairs(preserve_keys) do
preserved[key] = kong_shm:get(key) -- ignore errors
end
kong_shm:flush_all()
if dbless then
-- reinstate the lock to hold POST /config, which was flushed with the previous `flush_all`
declarative.try_lock()
end
for key, value in pairs(preserved) do
kong_shm:set(key, value)
end
kong_shm:flush_expired(0)
end
end
local function setup_plugin_context(ctx, plugin)
if plugin.handler._go then
ctx.ran_go_plugin = true
end
kong_global.set_named_ctx(kong, "plugin", plugin.handler, ctx)
kong_global.set_namespaced_log(kong, plugin.name, ctx)
end
local function reset_plugin_context(ctx, old_ws)
kong_global.reset_log(kong, ctx)
if old_ws then
ctx.workspace = old_ws
end
end
local function execute_init_worker_plugins_iterator(plugins_iterator, ctx)
local errors
for plugin in plugins_iterator:iterate_init_worker() do
kong_global.set_namespaced_log(kong, plugin.name, ctx)
-- guard against failed handler in "init_worker" phase only because it will
-- cause Kong to not correctly initialize and can not be recovered automatically.
local ok, err = pcall(plugin.handler.init_worker, plugin.handler)
if not ok then
errors = errors or {}
errors[#errors + 1] = {
plugin = plugin.name,
err = err,
}
end
kong_global.reset_log(kong, ctx)
end
return errors
end
local function execute_access_plugins_iterator(plugins_iterator, ctx)
local old_ws = ctx.workspace
ctx.delay_response = true
for plugin, configuration in plugins_iterator:iterate("access", ctx) do
if not ctx.delayed_response then
setup_plugin_context(ctx, plugin)
local co = coroutine.create(plugin.handler.access)
local cok, cerr = coroutine.resume(co, plugin.handler, configuration)
if not cok then
kong.log.err(cerr)
ctx.delayed_response = {
status_code = 500,
content = { message = "An unexpected error occurred" },
}
end
reset_plugin_context(ctx, old_ws)
end
end
ctx.delay_response = nil
end
local function execute_plugins_iterator(plugins_iterator, phase, ctx)
local old_ws = ctx.workspace
for plugin, configuration in plugins_iterator:iterate(phase, ctx) do
setup_plugin_context(ctx, plugin)
plugin.handler[phase](plugin.handler, configuration)
reset_plugin_context(ctx, old_ws)
end
end
local function execute_collected_plugins_iterator(plugins_iterator, phase, ctx)
local old_ws = ctx.workspace
for plugin, configuration in plugins_iterator.iterate_collected_plugins(phase, ctx) do
setup_plugin_context(ctx, plugin)
plugin.handler[phase](plugin.handler, configuration)
reset_plugin_context(ctx, old_ws)
end
end
local function execute_cache_warmup(kong_config)
if kong_config.database == "off" then
return true
end
if ngx.worker.id() == 0 then
local ok, err = cache_warmup.execute(kong_config.db_cache_warmup_entities)
if not ok then
return nil, err
end
end
return true
end
local function get_updated_now_ms()
update_time()
return now() * 1000 -- time is kept in seconds with millisecond resolution.
end
local function flush_delayed_response(ctx)
ctx.delay_response = nil
ctx.buffered_proxying = nil
if type(ctx.delayed_response_callback) == "function" then
ctx.delayed_response_callback(ctx)
return -- avoid tail call
end
kong.response.exit(ctx.delayed_response.status_code,
ctx.delayed_response.content,
ctx.delayed_response.headers)
end
local function parse_declarative_config(kong_config)
if kong_config.database ~= "off" then
return {}, nil, {}
end
local dc = declarative.new_config(kong_config)
if not kong_config.declarative_config and not kong_config.declarative_config_string then
-- return an empty configuration,
-- including only the default workspace
local entities, _, _, meta = dc:parse_table({ _format_version = "2.1" })
return entities, nil, meta
end
local entities, err, _, meta
if kong_config.declarative_config ~= nil then
entities, err, _, meta = dc:parse_file(kong_config.declarative_config)
elseif kong_config.declarative_config_string ~= nil then
entities, err, _, meta = dc:parse_string(kong_config.declarative_config_string)
end
if not entities then
if kong_config.declarative_config ~= nil then
return nil, "error parsing declarative config file " ..
kong_config.declarative_config .. ":\n" .. err
elseif kong_config.declarative_config_string ~= nil then
return nil, "error parsing declarative string " ..
kong_config.declarative_config_string .. ":\n" .. err
end
end
return entities, nil, meta
end
local function load_declarative_config(kong_config, entities, meta)
if kong_config.database ~= "off" then
return true
end
local opts = {
name = "declarative_config",
}
local kong_shm = ngx.shared.kong
local ok, err = concurrency.with_worker_mutex(opts, function()
local value = kong_shm:get(DECLARATIVE_LOAD_KEY)
if value then
return true
end
local ok, err = declarative.load_into_cache(entities, meta)
if not ok then
return nil, err
end
if kong_config.declarative_config then
kong.log.notice("declarative config loaded from ",
kong_config.declarative_config)
end
ok, err = kong_shm:safe_set(DECLARATIVE_LOAD_KEY, true)
if not ok then
kong.log.warn("failed marking declarative_config as loaded: ", err)
end
return true
end)
if ok then
declarative.try_unlock()
local default_ws = kong.db.workspaces:select_by_name("default")
kong.default_workspace = default_ws and default_ws.id or kong.default_workspace
ok, err = runloop.build_plugins_iterator("init")
if not ok then
return nil, "error building initial plugins iterator: " .. err
end
ok, err = runloop.build_router("init")
if not ok then
return nil, "error building initial router: " .. err
end
end
return ok, err
end
local function list_migrations(migtable)
local list = {}
for _, t in ipairs(migtable) do
local mignames = {}
for _, mig in ipairs(t.migrations) do
table.insert(mignames, mig.name)
end
table.insert(list, string.format("%s (%s)", t.subsystem,
table.concat(mignames, ", ")))
end
return table.concat(list, " ")
end
-- Kong public context handlers.
-- @section kong_handlers
local Kong = {}
function Kong.init()
local pl_path = require "pl.path"
local conf_loader = require "kong.conf_loader"
-- check if kong global is the correct one
if not kong.version then
error("configuration error: make sure your template is not setting a " ..
"global named 'kong' (please use 'Kong' instead)")
end
-- retrieve kong_config
local conf_path = pl_path.join(ngx.config.prefix(), ".kong_env")
local config = assert(conf_loader(conf_path, nil, { from_kong_env = true }))
reset_kong_shm(config)
-- special math.randomseed from kong.globalpatches not taking any argument.
-- Must only be called in the init or init_worker phases, to avoid
-- duplicated seeds.
math.randomseed()
kong_global.init_pdk(kong, config, nil) -- nil: latest PDK
local db = assert(DB.new(config))
assert(db:init_connector())
schema_state = assert(db:schema_state())
migrations_utils.check_state(schema_state)
if schema_state.missing_migrations or schema_state.pending_migrations then
if schema_state.missing_migrations then
ngx_log(ngx_WARN, "database is missing some migrations:\n",
schema_state.missing_migrations)
end
if schema_state.pending_migrations then
ngx_log(ngx_WARN, "database has pending migrations:\n",
schema_state.pending_migrations)
end
end
assert(db:connect())
-- LEGACY
singletons.dns = dns(config)
singletons.configuration = config
singletons.db = db
-- /LEGACY
kong.db = db
kong.dns = singletons.dns
if config.proxy_ssl_enabled or config.stream_ssl_enabled then
certificate.init()
end
if is_http_module and (config.role == "data_plane" or config.role == "control_plane")
then
kong.clustering = require("kong.clustering").new(config)
end
assert(db.vaults_beta:load_vault_schemas(config.loaded_vaults))
-- Load plugins as late as possible so that everything is set up
assert(db.plugins:load_plugin_schemas(config.loaded_plugins))
if is_stream_module then
stream_api.load_handlers()
end
if config.database == "off" then
local err
declarative_entities, err, declarative_meta = parse_declarative_config(kong.configuration)
if not declarative_entities then
error(err)
end
else
local default_ws = db.workspaces:select_by_name("default")
kong.default_workspace = default_ws and default_ws.id
local ok, err = runloop.build_plugins_iterator("init")
if not ok then
error("error building initial plugins: " .. tostring(err))
end
if config.role ~= "control_plane" then
assert(runloop.build_router("init"))
end
end
db:close()
require("resty.kong.var").patch_metatable()
end
function Kong.init_worker()
local ctx = ngx.ctx
ctx.KONG_PHASE = PHASES.init_worker
-- special math.randomseed from kong.globalpatches not taking any argument.
-- Must only be called in the init or init_worker phases, to avoid
-- duplicated seeds.
math.randomseed()
-- init DB
local ok, err = kong.db:init_worker()
if not ok then
stash_init_worker_error("failed to instantiate 'kong.db' module: " .. err)
return
end
if ngx.worker.id() == 0 then
if schema_state.missing_migrations then
ngx_log(ngx_WARN, "missing migrations: ",
list_migrations(schema_state.missing_migrations))
end
if schema_state.pending_migrations then
ngx_log(ngx_INFO, "starting with pending migrations: ",
list_migrations(schema_state.pending_migrations))
end
end
local worker_events, err = kong_global.init_worker_events()
if not worker_events then
stash_init_worker_error("failed to instantiate 'kong.worker_events' " ..
"module: " .. err)
return
end
kong.worker_events = worker_events
local cluster_events, err = kong_global.init_cluster_events(kong.configuration, kong.db)
if not cluster_events then
stash_init_worker_error("failed to instantiate 'kong.cluster_events' " ..
"module: " .. err)
return
end
kong.cluster_events = cluster_events
local cache, err = kong_global.init_cache(kong.configuration, cluster_events, worker_events)
if not cache then
stash_init_worker_error("failed to instantiate 'kong.cache' module: " ..
err)
return
end
kong.cache = cache
local core_cache, err = kong_global.init_core_cache(kong.configuration, cluster_events, worker_events)
if not core_cache then
stash_init_worker_error("failed to instantiate 'kong.core_cache' module: " ..
err)
return
end
kong.core_cache = core_cache
ok, err = runloop.set_init_versions_in_cache()
if not ok then
stash_init_worker_error(err) -- 'err' fully formatted
return
end
-- LEGACY
singletons.cache = cache
singletons.core_cache = core_cache
singletons.worker_events = worker_events
singletons.cluster_events = cluster_events
-- /LEGACY
kong.db:set_events_handler(worker_events)
ok, err = load_declarative_config(kong.configuration,
declarative_entities,
declarative_meta)
if not ok then
stash_init_worker_error("failed to load declarative config file: " .. err)
return
end
if kong.configuration.role ~= "control_plane" then
ok, err = execute_cache_warmup(kong.configuration)
if not ok then
ngx_log(ngx_ERR, "failed to warm up the DB cache: " .. err)
end
end
runloop.init_worker.before()
-- run plugins init_worker context
ok, err = runloop.update_plugins_iterator()
if not ok then
stash_init_worker_error("failed to build the plugins iterator: " .. err)
return
end
local plugins_iterator = runloop.get_plugins_iterator()
local errors = execute_init_worker_plugins_iterator(plugins_iterator, ctx)
if errors then
for _, e in ipairs(errors) do
local err = "failed to execute the \"init_worker\" " ..
"handler for plugin \"" .. e.plugin .."\": " .. e.err
stash_init_worker_error(err)
end
end
runloop.init_worker.after()
if kong.configuration.role ~= "control_plane" then
plugin_servers.start()
end
if kong.clustering then
kong.clustering:init_worker()
end
end
function Kong.ssl_certificate()
-- Note: ctx here is for a connection (not for a single request)
local ctx = ngx.ctx
ctx.KONG_PHASE = PHASES.certificate
log_init_worker_errors(ctx)
-- this is the first phase to run on an HTTPS request
ctx.workspace = kong.default_workspace
runloop.certificate.before(ctx)
local plugins_iterator = runloop.get_updated_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "certificate", ctx)
runloop.certificate.after(ctx)
-- TODO: do we want to keep connection context?
kong.table.clear(ngx.ctx)
end
function Kong.preread()
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = start_time() * 1000
end
if not ctx.KONG_PREREAD_START then
ctx.KONG_PREREAD_START = now() * 1000
end
ctx.KONG_PHASE = PHASES.preread
log_init_worker_errors(ctx)
local preread_terminate = runloop.preread.before(ctx)
-- if proxying to a second layer TLS terminator is required
-- abort further execution and return back to Nginx
if preread_terminate then
return
end
local plugins_iterator = runloop.get_updated_plugins_iterator()
execute_plugins_iterator(plugins_iterator, "preread", ctx)
if not ctx.service then
ctx.KONG_PREREAD_ENDED_AT = get_updated_now_ms()
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT - ctx.KONG_PREREAD_START
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_PREREAD_ENDED_AT - ctx.KONG_PROCESSING_START
ngx_log(ngx_WARN, "no Service found with those values")
return ngx.exit(503)
end
runloop.preread.after(ctx)
ctx.KONG_PREREAD_ENDED_AT = get_updated_now_ms()
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT - ctx.KONG_PREREAD_START
-- we intent to proxy, though balancer may fail on that
ctx.KONG_PROXIED = true
end
function Kong.rewrite()
local proxy_mode = var.kong_proxy_mode
if proxy_mode == "grpc" or proxy_mode == "unbuffered" then
kong_resty_ctx.apply_ref() -- if kong_proxy_mode is gRPC/unbuffered, this is executing
local ctx = ngx.ctx -- after an internal redirect. Restore (and restash)
kong_resty_ctx.stash_ref(ctx) -- context to avoid re-executing phases
ctx.KONG_REWRITE_ENDED_AT = now() * 1000
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
return
end
local ctx = ngx.ctx
if not ctx.KONG_PROCESSING_START then
ctx.KONG_PROCESSING_START = start_time() * 1000
end
if not ctx.KONG_REWRITE_START then
ctx.KONG_REWRITE_START = now() * 1000
end
ctx.KONG_PHASE = PHASES.rewrite
kong_resty_ctx.stash_ref(ctx)
local is_https = var.https == "on"
if not is_https then
log_init_worker_errors(ctx)
end
runloop.rewrite.before(ctx)
if not ctx.workspace then
ctx.workspace = kong.default_workspace
end
-- On HTTPS requests, the plugins iterator is already updated in the ssl_certificate phase
local plugins_iterator
if is_https then
plugins_iterator = runloop.get_plugins_iterator()
else
plugins_iterator = runloop.get_updated_plugins_iterator()
end
execute_plugins_iterator(plugins_iterator, "rewrite", ctx)
runloop.rewrite.after(ctx)
ctx.KONG_REWRITE_ENDED_AT = get_updated_now_ms()
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
end
function Kong.access()
local ctx = ngx.ctx
if not ctx.KONG_ACCESS_START then
ctx.KONG_ACCESS_START = now() * 1000
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT - ctx.KONG_REWRITE_START
end
end
ctx.KONG_PHASE = PHASES.access
runloop.access.before(ctx)
local plugins_iterator = runloop.get_plugins_iterator()
execute_access_plugins_iterator(plugins_iterator, ctx)
if ctx.delayed_response then
ctx.KONG_ACCESS_ENDED_AT = get_updated_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_PROCESSING_START
return flush_delayed_response(ctx)
end
ctx.delay_response = nil
if not ctx.service then
ctx.KONG_ACCESS_ENDED_AT = get_updated_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
ctx.KONG_RESPONSE_LATENCY = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_PROCESSING_START
ctx.buffered_proxying = nil
return kong.response.exit(503, { message = "no Service found with those values"})
end
runloop.access.after(ctx)
ctx.KONG_ACCESS_ENDED_AT = get_updated_now_ms()
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT - ctx.KONG_ACCESS_START
-- we intent to proxy, though balancer may fail on that
ctx.KONG_PROXIED = true
if ctx.buffered_proxying then
local version = ngx.req.http_version()
local upgrade = var.upstream_upgrade or ""
if version < 2 and upgrade == "" then
return Kong.response()
end
if version >= 2
AB00
then
ngx_log(ngx_NOTICE, "response buffering was turned off: incompatible HTTP version (", version, ")")
else
ngx_log(ngx_NOTICE, "response buffering was turned off: connection upgrade (", upgrade, ")")
end
ctx.buffered_proxying = nil
end
end
function Kong.balancer()
-- This may be called multiple times, and no yielding here!
local now_ms = now() * 1000
local ctx = ngx.ctx
if not ctx.KONG_BALANCER_START then
ctx.KONG_BALANCER_START = now_ms
if is_stream_module then
if ctx.KONG_PREREAD_START and not ctx.KONG_PREREAD_ENDED_AT then
ctx.KONG_PREREAD_ENDED_AT = ctx.KONG_BALANCER_START
ctx.KONG_PREREAD_TIME = ctx.KONG_PREREAD_ENDED_AT -
ctx.KONG_PREREAD_START
end
else
if ctx.KONG_REWRITE_START and not ctx.KONG_REWRITE_ENDED_AT then
ctx.KONG_REWRITE_ENDED_AT = ctx.KONG_ACCESS_START or
ctx.KONG_BALANCER_START
ctx.KONG_REWRITE_TIME = ctx.KONG_REWRITE_ENDED_AT -
ctx.KONG_REWRITE_START
end
if ctx.KONG_ACCESS_START and not ctx.KONG_ACCESS_ENDED_AT then
ctx.KONG_ACCESS_ENDED_AT = ctx.KONG_BALANCER_START
ctx.KONG_ACCESS_TIME = ctx.KONG_ACCESS_ENDED_AT -
ctx.KONG_ACCESS_START
end
end
end
ctx.KONG_PHASE = PHASES.balancer
local balancer_data = ctx.balancer_data
local tries = balancer_data.tries
local current_try = {}
balancer_data.try_count = balancer_data.try_count + 1
tries[balancer_data.try_count] = current_try
current_try.balancer_start = now_ms
if balancer_data.try_count > 1 then
-- only call balancer on retry, first one is done in `runloop.access.after`
-- which runs in the ACCESS context and hence has less limitations than
-- this BALANCER context where the retries are executed
-- record failure data
local previous_try = tries[balancer_data.try_count - 1]
previous_try.state, previous_try.code = get_last_failure()
-- Report HTTP status for health checks
local balancer_instance = balancer_data.balancer
if balancer_instance then
if previous_try.state == "failed" then
if previous_try.code == 504 then
balancer_instance.report_timeout(balancer_data.balancer_handle)
else
balancer_instance.report_tcp_failure(balancer_data.balancer_handle)
end
else
balancer_instance.report_http_status(balancer_data.balancer_handle,
previous_try.code)
end
end
local ok, err, errcode = balancer.execute(balancer_data, ctx)
if not ok then
ngx_log(ngx_ERR, "failed to retry the dns/balancer resolver for ",
tostring(balancer_data.host), "' with: ", tostring(err))
ctx.KONG_BALANCER_ENDED_AT = get_updated_now_ms()
ctx.KONG_BALANCER_TIME = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_BALANCER_START
ctx.KONG_PROXY_LATENCY = ctx.KONG_BALANCER_ENDED_AT - ctx.KONG_PROCESSING_START
return ngx.exit(errcode)
end
if is_http_module then
ok, err = balancer.set_host_header(balancer_data, var.upstream_scheme, var.upstream_host, true)
if not ok then
ngx_log(ngx_ERR, "failed to set balancer Host header: ", err)
return ngx.exit(500)
end
end
else
-- first try, so set the max number of retries
local retries = balancer_data.retries
if retries > 0 then
set_more_tries(retries)
end
end
local pool_opts
local kong_conf = kong.configuration
if enable_keepalive and kong_conf.upstream_keepalive_pool_size > 0 and is_http_module then
local pool = balancer_data.ip .. "|" .. balancer_data.port
if balancer_data.scheme == "https" then
-- upstream_host is SNI
pool = pool .. "|" .. var.upstream_host
if ctx.service and ctx.service.client_certificate then
pool = pool .. "|" .. ctx.service.client_certificate.id
end
end
pool_opts = {
pool = pool,
pool_size = kong_conf.upstream_keepalive_pool_size,
}
end