Repository navigation
Expand file tree
/
Copy pathinit.lua
More file actions
715 lines (549 loc) · 19.1 KB
/
Copy pathinit.lua
File metadata and controls
715 lines (549 loc) · 19.1 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
local version = require "version"
local DAO = require "kong.db.dao"
local Entity = require "kong.db.schema.entity"
local Errors = require "kong.db.errors"
local Strategies = require "kong.db.strategies"
local MetaSchema = require "kong.db.schema.metaschema"
local constants = require "kong.constants"
local log = require "kong.cmd.utils.log"
local workspaces = require "kong.workspaces"
local utils = require "kong.tools.utils"
local fmt = string.format
local type = type
local pairs = pairs
local error = error
local ipairs = ipairs
local rawget = rawget
local setmetatable = setmetatable
local DEFAULT_LOCKS_TTL = 60 -- seconds
local DB = {}
DB.__index = function(self, k)
return DB[k] or rawget(self, "daos")[k]
end
function DB.new(kong_config, strategy)
if not kong_config then
error("missing kong_config", 2)
end
if strategy ~= nil and type(strategy) ~= "string" then
error("strategy must be a string", 2)
end
strategy = strategy or kong_config.database
-- load errors
local errors = Errors.new(strategy)
local schemas = {}
do
-- load schemas
-- core entities are for now the only source of schemas.
-- TODO: support schemas from plugins entities as well.
for _, entity_name in ipairs(constants.CORE_ENTITIES) do
local entity_schema = require("kong.db.schema.entities." .. entity_name)
-- validate core entities schema via metaschema
local ok, err_t = MetaSchema:validate(entity_schema)
if not ok then
return nil, fmt("schema of entity '%s' is invalid: %s", entity_name,
tostring(errors:schema_violation(err_t)))
end
local entity, err = Entity.new(entity_schema)
if not entity then
return nil, fmt("schema of entity '%s' is invalid: %s", entity_name,
err)
end
schemas[entity_name] = entity
-- load core entities subschemas
local subschemas
ok, subschemas = utils.load_module_if_exists("kong.db.schema.entities." .. entity_name .. "_subschemas")
if ok then
for name, subschema in pairs(subschemas) do
local ok, err = entity:new_subschema(name, subschema)
if not ok then
return nil, ("error initializing schema for %s: %s"):format(entity_name, err)
end
end
end
end
end
-- load strategy
local connector, strategies, err = Strategies.new(kong_config, strategy,
schemas, errors)
if err then
return nil, err
end
local daos = {}
local self = {
daos = daos, -- each of those has the connector singleton
strategies = strategies,
connector = connector,
strategy = strategy,
errors = errors,
infos = connector:infos(),
kong_config = kong_config,
}
do
-- load DAOs
for _, schema in pairs(schemas) do
local strategy = strategies[schema.name]
if not strategy then
return nil, fmt("no strategy found for schema '%s'", schema.name)
end
daos[schema.name] = DAO.new(self, schema, strategy, errors)
end
end
-- we are 200 OK
return setmetatable(self, DB)
end
local function prefix_err(self, err)
return "[" .. self.infos.strategy .. " error] " .. err
end
local function fmt_err(self, err, ...)
return prefix_err(self, fmt(err, ...))
end
function DB:init_connector()
-- I/O with the DB connector singleton
-- Implementation up to the strategy's connector. A place for:
-- - connection check
-- - cluster retrieval (cassandra)
-- - prepare statements
-- - nop (default)
local ok, err = self.connector:init()
if not ok then
return nil, prefix_err(self, err)
end
self.infos = self.connector:infos()
local version_constants = constants.DATABASE[self.strategy:upper()]
if version_constants then
ok, err = self:check_version_compat(version_constants.MIN,
version_constants.DEPRECATED)
if not ok then
return nil, prefix_err(self, err)
end
end
return ok
end
function DB:init_worker()
-- Can be used to implement e.g. a timer jobs to
-- clean expired records from database in case the
-- database doesn't natively support TTL, such as
-- PostgreSQL
local ok, err = self.connector:init_worker(self.strategies)
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:connect()
local ok, err = self.connector:connect()
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:setkeepalive()
local ok, err = self.connector:setkeepalive()
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:close()
local ok, err = self.connector:close()
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:reset()
local ok, err = self.connector:reset()
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:truncate(table_name)
if table_name ~= nil and type(table_name) ~= "string" then
error("table_name must be a string", 2)
end
local ok, err
if table_name then
ok, err = self.connector:truncate_table(table_name)
else
ok, err = self.connector:truncate()
end
-- re-create default workspace on full or workspaces truncate
if not table_name or table_name == "workspaces" then
workspaces.upsert_default()
end
if not ok then
return nil, prefix_err(self, err)
end
return ok
end
function DB:set_events_handler(events)
for _, dao in pairs(self.daos) do
dao.events = events
end
end
function DB:check_version_compat(_min, _deprecated)
local _major_minor = self.connector.major_minor_version
if not _major_minor then
return false, "no version info on connector"
end
local major_minor = version(_major_minor)
local min = version(_min)
local deprecated = _deprecated and version(_deprecated)
if major_minor < min then
-- Deprecated is "ok"
if deprecated and major_minor >= deprecated then
log.warn("Currently using %s %s which is considered deprecated, " ..
"please use %s or greater", self.strategy, _major_minor, _min)
else
return false, fmt("Kong requires %s %s or greater (currently using %s)",
self.strategy, _min, _major_minor)
end
end
return true
end
do
local concurrency = require "kong.concurrency"
local knode = (kong and kong.node) and kong.node or
require "kong.pdk.node".new()
local MAX_LOCK_WAIT_STEP = 2 -- seconds
function DB:cluster_mutex(key, opts, cb)
if type(key) ~= "string" then
error("key must be a string", 2)
end
local owner
local ttl
local no_wait
local no_cleanup
if opts ~= nil then
if type(opts) ~= "table" then
error("opts must be a table", 2)
end
if opts.ttl and type(opts.ttl) ~= "number" then
error("opts.ttl must be a number", 2)
end
if opts.owner and type(opts.owner) ~= "string" then
error("opts.owner must be a string", 2)
end
if opts.no_wait and type(opts.no_wait) ~= "boolean" then
error("opts.no_wait must be a boolean", 2)
end
if opts.no_cleanup and type(opts.no_cleanup) ~= "boolean" then
error("opts.no_cleanup must be a boolean", 2)
end
owner = opts.owner
ttl = opts.ttl
no_wait = opts.no_wait
no_cleanup = opts.no_cleanup
end
if type(cb) ~= "function" then
local mt = getmetatable(cb)
if not mt or type(mt.__call) ~= "function" then
error("cb must be a function", 2)
end
end
if not owner then
-- generate a random string for this worker (resty-cli or runtime nginx
-- worker)
--
-- we use the `node.get_id()` from pdk, but in the CLI context, this
-- value is ephemeral, so no assumptions should be made about the real
-- owner of a lock
local id, err = knode.get_id()
if not id then
return nil, prefix_err(self, "failed to generate lock owner: " .. err)
end
owner = id
end
if not ttl then
ttl = DEFAULT_LOCKS_TTL
end
local mutex_opts = {
name = key,
timeout = ttl,
}
return concurrency.with_worker_mutex(mutex_opts, function(elapsed)
if elapsed ~= 0 then
-- we did not acquire the worker lock, but it was released
return false
end
-- worker lock acquired, other workers are waiting on it
-- now acquire cluster lock via strategy-specific connector
local ok, err = self.connector:insert_lock(key, ttl, owner)
if err then
return nil, prefix_err(self, "failed to insert cluster lock: " .. err)
end
if not ok then
if no_wait then
-- don't wait on cluster locked
return false
end
-- waiting on cluster lock
local step = 0.1
local cluster_elapsed = 0
while cluster_elapsed < ttl do
ngx.sleep(step)
cluster_elapsed = cluster_elapsed + step
if cluster_elapsed >= ttl then
break
end
local locked, err = self.connector:read_lock(key)
if err then
return nil, prefix_err(self, "failed to read cluster lock: " .. err)
end
if not locked then
-- the cluster lock was released
return false
end
step = math.min(step * 3, MAX_LOCK_WAIT_STEP)
end
return nil, prefix_err(self, "timeout")
end
-- cluster lock acquired, run callback
local pok, perr = xpcall(cb, debug.traceback)
if not pok then
self.connector:remove_lock(key, owner)
return nil, prefix_err(self, "cluster_mutex callback threw an error: "
.. perr)
end
if not no_cleanup then
self.connector:remove_lock(key, owner)
end
return true
end)
end
end
do
-- migrations
local utils = require "kong.tools.utils"
local MigrationHelpers = require "kong.db.migrations.helpers"
local MigrationsState = require "kong.db.migrations.state"
local last_schema_state
function DB:schema_state()
local err
last_schema_state, err = MigrationsState.load(self)
return last_schema_state, err
end
function DB:last_schema_state()
return last_schema_state or self:schema_state()
end
function DB:schema_bootstrap()
local ok, err = self.connector:connect_migrations({ no_keyspace = true })
if not ok then
return nil, prefix_err(self, err)
end
local ok, err = self.connector:schema_bootstrap(self.kong_config,
DEFAULT_LOCKS_TTL)
self.connector:close()
if not ok then
return nil, prefix_err(self, "failed to bootstrap database: " .. err)
end
return true
end
function DB:schema_reset()
local ok, err = self.connector:connect_migrations({ no_keyspace = true })
if not ok then
return nil, prefix_err(self, err)
end
local ok, err = self.connector:schema_reset()
self.connector:close()
if not ok then
return nil, prefix_err(self, err)
end
return true
end
function DB:run_migrations(migrations, options)
if type(migrations) ~= "table" then
error("migrations must be a table", 2)
end
if type(options) ~= "table" then
error("options must be a table", 2)
end
local run_up = options.run_up
local run_teardown = options.run_teardown
local skip_teardown_migrations = {}
if run_teardown and options.skip_teardown_migrations then
for _, t in ipairs(options.skip_teardown_migrations) do
for _, mig in ipairs(t.migrations) do
local ok, mod = utils.load_module_if_exists(t.namespace .. "." ..
mig.name)
if ok then
local strategy_migration = mod[self.strategy]
if strategy_migration and strategy_migration.teardown then
if not skip_teardown_migrations[t.subsystem] then
skip_teardown_migrations[t.subsystem] = {}
end
skip_teardown_migrations[t.subsystem][mig.name] = true
end
end
end
end
end
if not run_up and not run_teardown then
error("options.run_up or options.run_teardown must be given", 2)
end
local ok, err = self.connector:connect_migrations()
if not ok then
return nil, prefix_err(self, err)
end
local mig_helpers = MigrationHelpers.new(self.connector)
local n_migrations = 0
local n_pending = 0
for i, t in ipairs(migrations) do
log("migrating %s on %s '%s'...", t.subsystem, self.infos.db_desc,
self.infos.db_name)
for _, mig in ipairs(t.migrations) do
local ok, mod = utils.load_module_if_exists(t.namespace .. "." ..
mig.name)
if not ok then
self.connector:close()
return nil, fmt_err(self, "failed to load migration '%s': %s",
mig.name, mod)
end
local strategy_migration = mod[self.strategy]
if not strategy_migration then
self.connector:close()
return nil, fmt_err(self, "missing %s strategy for migration '%s'",
self.strategy, mig.name)
end
log.debug("running migration: %s", mig.name)
if run_up then
-- kong migrations bootstrap
-- kong migrations up
if strategy_migration.up and strategy_migration.up ~= "" then
ok, err = self.connector:run_up_migration(mig.name,
strategy_migration.up)
if not ok then
self.connector:close()
return nil, fmt_err(self, "failed to run migration '%s' up: %s",
mig.name, err)
end
end
if strategy_migration.up_f then
local pok, perr, err = xpcall(strategy_migration.up_f,
debug.traceback, self.connector,
mig_helpers)
if not pok or err then
self.connector:close()
return nil, fmt_err(self, "failed to run migration '%s' up_f: %s",
mig.name, perr or err)
end
end
local state = "executed"
if strategy_migration.teardown then
-- this migration has a teardown step for later
state = "pending"
n_pending = n_pending + 1
end
ok, err = self.connector:record_migration(t.subsystem, mig.name,
state)
if not ok then
self.connector:close()
return nil, fmt_err(self, "failed to record migration '%s': %s",
mig.name, err)
end
end
local skip_teardown = skip_teardown_migrations[t.subsystem] and
skip_teardown_migrations[t.subsystem][mig.name]
if not skip_teardown and run_teardown and strategy_migration.teardown then
if run_up then
-- ensure schema consensus is reached before running DML queries
-- that could span all peers
ok, err = self.connector:wait_for_schema_consensus()
if not ok then
self.connector:close()
return nil, prefix_err(self, err)
end
end
-- kong migrations teardown
local f = strategy_migration.teardown
local pok, perr, err = xpcall(f, debug.traceback, self.connector,
mig_helpers)
if not pok or err then
self.connector:close()
return nil, fmt_err(self, "failed to run migration '%s' teardown: %s",
mig.name, perr or err)
end
ok, err = self.connector:record_migration(t.subsystem, mig.name,
"teardown")
if not ok then
self.connector:close()
return nil, fmt_err(self, "failed to record migration '%s': %s",
mig.name, err)
end
n_pending = math.max(n_pending - 1, 0)
if not run_up then
-- ensure schema consensus is reached when the next migration to
-- run will execute its teardown step, since it may make further
-- DML queries; if the next migration runs its up step, it will
-- run DDL queries against the same node, so no need to reach
-- schema consensus
ok, err = self.connector:wait_for_schema_consensus()
if not ok then
self.connector:close()
return nil, prefix_err(self, err)
end
end
end
log("%s migrated up to: %s %s", t.subsystem, mig.name,
strategy_migration.teardown and not run_teardown and "(pending)"
or "(executed)")
n_migrations = n_migrations + 1
end
if run_up and i == #migrations then
-- wait for schema consensus after the last migration has run
-- (only if `run_up`, since if not, we just called it from the
-- teardown step)
ok, err = self.connector:wait_for_schema_consensus()
if not ok then
self.connector:close()
return nil, prefix_err(self, err)
end
end
end
log("%d migration%s processed", n_migrations,
n_migrations > 1 and "s" or "")
local n_executed = n_migrations - n_pending
if n_executed > 0 then
log("%d executed", n_executed)
end
if n_pending > 0 then
log("%d pending", n_pending)
end
self.connector:close()
return true
end
--[[
function DB:load_pending_migrations(migrations)
if type(migrations) ~= "table" then
error("migrations must be a table", 2)
end
for _, t in ipairs(migrations) do
for _, mig in ipairs(t.migrations) do
local ok, mod = utils.load_module_if_exists(t.namespace .. "." ..
mig.name)
if not ok then
return nil, fmt("failed to load migration '%s': %s", mig.name,
mod)
end
if mod.translations then
ngx.log(ngx.INFO, "loading translation functions for migration ",
"'", mig.name, "'")
for _, translation in ipairs(mod.translations) do
local dao = self.daos[translation.entity]
if not dao then
return nil, fmt("failed to load translation function for " ..
"migration '%s': no '%s' DAO exists", mig.name,
translation.entity)
end
dao:load_translations(mod.translations)
end
end
end
end
self.connector:close()
return true
end
--]]
end
return DB