-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmm.lua
4257 lines (3827 loc) · 111 KB
/
mm.lua
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
--go@ plink d10 -t -batch mm/sdk/bin/linux/luajit mm/mm.lua -v run
--go@ x:\sdk\bin\windows\luajit x:\mm\mm.lua -v run
--go@ plink mm-prod -t -batch mm/sdk/bin/linux/luajit mm/mm.lua -vv run
--[[
Many Machines, the independent man's SAAS provisioning tool.
Written by Cosmin Apreutesei. Public Domain.
Many Machines is a bare-bones provisioning and administration tool
for web apps deployed on dedicated machines or VPS, as opposed to cloud
services as it's customary these days (unless you count VPS as cloud).
FEATURES
- Lua API, HTTP API, web UI & cmdline UI for every operation.
- Windows-native sysadmin tools (sshfs, putty, etc.).
- agentless: all relevant bash scripts are uploaded with each command.
- keeps all data in a relational database (machines, deployments, etc.).
- all processes are tracked by a task system with output capturing and autokill.
- maintains secure access to all services via bulk updating of:
- SSH root keys.
- MySQL root password.
- SSH git hosting (github, etc.) keys.
- quick-launch of ssh, putty and mysql shells.
- quick remote commands: ssh, mysql, rsync, deployed app commands.
- remote fs mounts via sshfs (Windows & Linux).
- machine prepare script (one-time install script for a new machine).
- scheduled tasks.
- app control: deploy, start, stop, restart.
- live monitoring:
- CPU, RAM, Lua allocations and object counts
- log capturing
- live objects list
- env vars list
- Lua profiler
- running Lua scripts
- MySQL stats
- controlling Lua JIT and GC.
- db & file backups:
- MySQL: incremental, per-server, with xtrabackup.
- MySQL: non-incremental, per-db, with mysqldump.
- files: always incremental, with hardlinking via rsync.
- backup copies kept on multiple machines.
- machine restore: create new deploys and/or override existing.
- deployment restore: create new or override existing.
- https proxy with automatic SSL certificate issuing and updating.
LIMITATIONS
- the machines need to run Debian 10 and have a public IP.
- single shared MySQL server instance for all deployments on a machine.
- one MySQL DB per deployment.
- one global SSH key for root access on all machines.
- one SSH key for git access for each git hosting provider.
]]
--db schema ------------------------------------------------------------------
local function mm_schema()
types.git_version = {strid, null_text = 'master'}
tables.git_hosting = {
name , strpk,
host , strid, not_null,
ssh_hostkey , public_key, not_null,
ssh_key , private_key, not_null,
pos , pos,
}
tables.provider = {
provider , strpk,
website , url,
note , text,
pos , pos,
ctime , ctime,
}
tables.machine = {
machine , strpk,
provider , strid, not_null, fk,
location , strid, not_null,
public_ip , strid,
local_ip , strid,
cost_per_month, money,
cost_per_year , money,
active , bool1, --enable/disable all automation
ssh_hostkey , public_key,
ssh_key , private_key,
ssh_key_ok , bool,
admin_page , url,
os_ver , name,
mysql_ver , name,
mysql_local_port , uint16,
log_local_port , uint16,
cpu , name,
cores , uint16,
ram , filesize,
hdd , filesize,
--backup task scheduling
full_backup_active , bool,
full_backup_start_hours , timeofday,
full_backup_run_every , duration, {duration_format = 'long'},
incr_backup_active , bool,
incr_backup_start_hours , timeofday,
incr_backup_run_every , duration, {duration_format = 'long'},
backup_remove_older_than, duration, {duration_format = 'long'},
pos , pos,
ctime , ctime,
}
tables.machine_backup_copy_machine = {
machine , strid, not_null, child_fk,
dest_machine , strid, not_null, child_fk(machine), pk,
synced , bool0,
}
tables.deploy = {
deploy , strpk,
machine , strid, weak_fk,
repo , url, not_null,
app , strid, not_null,
domain , strid,
http_port , uint16,
wanted_app_version , git_version,
wanted_sdk_version , git_version,
deployed_app_version , git_version,
deployed_sdk_version , git_version,
deployed_app_commit , strid,
deployed_sdk_commit , strid,
deployed_at , timeago,
started_at , timeago,
env , strid, not_null,
secret , secret_key, not_null, --multi-purpose
mysql_pass , hash, not_null,
restored_from_dbk, id, weak_fk(dbk),
restored_from_mbk, id, weak_fk(mbk),
active, bool1, --enable/disable all automation
--backup task scheduling
backup_active , bool,
backup_start_hours , timeofday,
backup_run_every , duration, {duration_format = 'long'},
backup_remove_older_than, duration, {duration_format = 'long'},
ctime , ctime,
mtime , mtime,
pos , pos,
}
tables.deploy_backup_copy_machine = {
deploy , strid, not_null, child_fk,
dest_machine , strid, not_null, child_fk(machine), pk,
synced , bool0,
}
tables.env_var = {
tag , strid, not_null,
env_var , strid, not_null, pk,
val , text , not_null,
}
tables.deploy_env_var = { aka'deploy_vars',
deploy , strid, not_null, fk,
env_var , strid, not_null, pk, aka'name',
val , text , not_null,
}
tables.deploy_env_var_tag = {
deploy , strid, not_null, fk,
tag , strid, not_null, pk,
pos , pos , not_null,
}
tables.deploy_log = {
deploy , strid, not_null, child_fk,
ctime , ctime, pk,
severity , strid,
module , strid,
event , strid,
message , text,
}
tables.script = {
script , strpk,
code , longtext,
ctime , ctime,
mtime , mtime,
pos , pos,
}
--machine backups: ideally backups should be per-deployment, not per-machine.
--but mysql only supports incremental backups for the entire server instance
--not per schema, so the idea of "machine backups" come from this limitation.
tables.mbk = {
mbk , idpk,
machine , strid, fk(machine),
parent_mbk , id, fk(mbk),
start_time , timeago,
duration , duration,
checksum , hash,
note , text, aka'name',
stdouterr , text,
}
tables.mbk_deploy = {
mbk , id , not_null, child_fk,
deploy , strid, not_null, fk, pk,
app_version , git_version,
sdk_version , git_version,
app_commit , strid,
sdk_commit , strid,
}
tables.mbk_copy = {
mbk_copy , idpk,
parent_mbk_copy, id, fk(mbk_copy),
mbk , id, not_null, fk,
machine , strid, not_null, child_fk, uk(mbk, machine),
start_time , timeago,
duration , duration,
size , filesize,
}
--deploy backups: done with mysqldump so they are slow and non-incremental,
--but they're the only way to backup & restore a single schema out of many
--on a mysql server.
tables.dbk = {
dbk , idpk,
deploy , strid, not_null, fk,
app_version , git_version,
sdk_version , git_version,
app_commit , strid,
sdk_commit , strid,
start_time , timeago,
duration , duration,
checksum , hash,
note , text, aka'name',
stdouterr , text,
}
tables.dbk_copy = {
dbk_copy , idpk,
dbk , id, not_null, fk,
machine , strid, not_null, child_fk, uk(dbk, machine),
start_time , timeago,
duration , duration,
size , filesize,
}
tables.task_last_run = {
sched_name , longstrpk,
last_run , time,
}
tables.task_run = {
task_run , idpk,
start_time , timeago, not_null,
name , longstrid,
duration , duration,
stdin , text,
stdouterr , text,
exit_code , int,
}
end
--modules, config, tools, install --------------------------------------------
--debug.traceback = require'stacktraceplus'.stacktrace
local xapp = require'xapp'
require'base64'
require'mustache'
require'queue'
require'mess'
require'tasks'
require'mysql_print'
require'http_client'
if win then
winapi = require'winapi'
require'winapi.registry'
end
config('allow_create_user', false)
config('auto_create_user', false)
local mm = xapp(...)
--logging.filter.mysql = true
mm.sshfsdir = [[C:\PROGRA~1\SSHFS-Win\bin]] --no spaces!
mm.bindir = indir(scriptdir(), 'bin', win and 'windows' or 'linux')
mm.sshdir = mm.bindir
config('page_title_suffix', 'Many Machines')
config('sign_in_logo', '/sign-in-logo.png')
config('favicon_href', '/favicon1.ico')
--client config.
config('mm_host', 'mm.allegory.ro')
--dev server config. you add: dev_email, smtp_{host,user,pass}, noreply_email.
config('secret', '!xpAi$^!@#)fas!`5@cXiOZ{!9fdsjdkfh7zk')
--logging.filter[''] = true
--config('http_debug', 'protocol')
--config('getpage_debug', 'stream')
--load_opensans()
mm.schema:import(mm_schema)
local function NYI(event)
log('ERROR', 'mm', event, 'NYI')
error('NYI: '..event)
end
local function split2(sep, s)
if not s then return nil, nil end
local s1, s2 = s:match('^(.-)'..esc(sep)..'(.*)')
return repl(s1, ''), repl(s2, '')
end
mm.print_rowset_cols = {}
--web api / server -----------------------------------------------------------
local mm_api = {} --{action->fn}
local out_term = streaming_terminal{send = out}
action['api.txt'] = function(action, ...)
setcompress(false)
--^^required so that each out() call is a HTTP chunk and there's no buffering.
setheader('content-type', 'application/octet-stream')
--^^the only way to make chrome fire onreadystatechange() for each chunk.
allow(usr'roles'.admin)
checkarg(method'post', 'try POST')
local handler = checkfound(mm_api[action:gsub('-', '_')], 'action not found: %s', action)
local post = repl(repl_nulls(post()), '')
checkarg(post == nil or istab(post))
--Args are passed to the API handler as `getarg1, ..., postarg1, ...`
--so you can pass args as GET or POST or a combination, the API won't know.
--GET args come from the URI path so they're all strings. POST args come
--as a JSON array so you can pass in structured data in them. That said,
--args from cmdline can only be strings so better assume all args untyped.
--String args and options coming from the command line are trimmed and
--empty strings are passed as `nil`. Empty GET args (as in `/foo//bar`)
--are also passed as `nil` but not trimmed. POST args and options are
--JSON-decoded with all `null` values transformed into `nil`.
--To make the API scriptable, errors are caught and sent to the client to
--be re-raised in the Lua client (the JS client calls notify() for them).
--Because the API is for both JS and Lua to consume, we don't support
--multiple return values (you have to return arrays instead).
local args = extend(pack(...), post and post.args)
local opt = post and post.options or empty
ownthreadenv().debug = opt.debug
ownthreadenv().verbose = opt.verbose
local prev_term = set_current_terminal(out_term)
local ok, ret = pcall(handler, opt, unpack(args))
if not ok then
local ret = tostring(ret)
log('ERROR', 'mm', 'api', '%s %s %s -> ERROR %s', action, opt, args, ret)
out_term:send_on('e', ret)
elseif ret ~= nil then
log('', 'mm', 'api', '%s %s %s -> %s', action, opt, args, ret)
out_term:send_on('r', json_encode(ret))
end
set_current_terminal(prev_term)
end
--web api / client for cmdline API -------------------------------------------
local function call_api(action, opt, ...)
local retval
local term = null_terminal():pipe(current_terminal())
function term:receive_on(chan, s)
if chan == 'e' then
raise('mm', '%s', s) --no stacktrace
elseif chan == 'r' then
retval = json_decode(s)
else
assertf(false, 'invalid channel: "%s"', chan)
end
end
local write = streaming_terminal_reader(term)
local function receive_content(req, in_buf, sz)
if not in_buf then --eof
--
else
write(in_buf, sz)
end
end
local function headers_received(res)
check('mm', 'api-call', res.status == 200,
'http error: %d %s', res.status, res.status_message) --bug?
end
local opt = update({ --pass verbosity to server
debug = repl(logging.debug , false),
verbose = repl(logging.verbose, false),
}, opt)
local ret, res = getpage{
host = config'mm_host',
port = config'mm_port',
https = config'mm_https',
uri = url_format{segments = {'', 'api.txt', action}},
headers = {
cookie = {
session = config'session_cookie',
},
},
method = 'POST',
upload = {options = opt, args = json_pack(...)},
receive_content = receive_content,
headers_received = headers_received,
}
assertf(ret ~= nil, '%s', res)
return retval
end
local function call_json_api(opt, action, ...)
if opt ~= nil and not istab(opt) then --action, ...
return call_json_api(empty, opt, action, ...)
end
opt = repl(opt, nil, empty)
local ret, res = getpage{
host = config'mm_host',
port = config'mm_port',
https = config'mm_https',
uri = url_format{
segments = {n = select('#', ...) + 2, '', action, ...},
args = opt.args,
},
headers = {
cookie = {
session = config'session_cookie',
},
},
upload = opt.upload,
}
assertf(ret ~= nil, '%s', res)
assertf(res.status == 200, 'http error: %d %s', res.status, res.status_message)
assertf(istab(ret), 'invalid JSON rsponse: %s', res.rawcontent)
return ret
end
--Lua+web+cmdline api generator ----------------------------------------------
local function from_server()
return config'mm_host' and not server_running
end
local function pass_opt(opt, ...) --pass an optional options table at arg#1
if opt ~= nil and not istab(opt) then
return empty, opt, ...
else
return repl(opt, nil, empty), ...
end
end
local api = setmetatable({}, {__newindex = function(_, name, fn)
local api_name = name:gsub('_', '-')
mm[name] = function(opt, ...)
if from_server() then
return call_api(api_name, pass_opt(opt, ...))
end
return fn(pass_opt(opt, ...))
end
mm_api[name] = fn
end})
local function wrap(fn)
return function(...)
local ok, ret = pcall(fn, ...)
if ok then return ret end --handlers can return an explicit exit code.
die('%s', ret)
end
end
local cmd_ssh_keys = cmdsection('SSH KEY MANAGEMENT', wrap)
local cmd_ssh = cmdsection('SSH TERMINALS' , wrap)
local cmd_ssh_tunnels = cmdsection('SSH TUNNELS' , wrap)
local cmd_ssh_mounts = cmdsection('SSH-FS MOUNTS' , wrap)
local cmd_files = cmdsection('FILES' , wrap)
local cmd_mysql = cmdsection('MYSQL' , wrap)
local cmd_machines = cmdsection('MACHINES' , wrap)
local cmd_deploys = cmdsection('DEPLOYMENTS' , wrap)
local cmd_mbk = cmdsection('MACHINE-LEVEL BACKUP & RESTORE', wrap)
local cmd_dbk = cmdsection('DEPLOYMENT-LEVEL BACKUP & RESTORE', wrap)
local cmd_tasks = cmdsection('TASKS' , wrap)
cmdhelp(function()
local server = config'mm_host'
say('MM SERVER: %s', server or 'none')
end)
--task system ----------------------------------------------------------------
local function mm_task_init(self)
if not server_running then
self.free_after = 0
end
if self.visible then
rowset_changed'running_tasks'
self:on('event', function(self, ev, source, ...)
if source ~= self then return end
rowset_changed'running_tasks'
end)
self.terminal:on('event', function(self, ev, source, ...)
if source ~= self then return end
rowset_changed'running_tasks'
end)
self:on('setstatus', function(self, ev, source_task, status)
if source_task ~= self then return end
if status == 'finished' then
if not self.nolog then
if not self.task_run then
self.task_run = insert_row('task_run', {
start_time = self.start_time,
name = self.name,
duration = self.duration,
stdin = self.stdin,
stdouterr = self:stdouterr(),
exit_code = self.exit_code,
}, nil, {quiet = true})
else
update_row('task_run', {
self.task_run,
duration = self.duration,
stdouterr = self:stdouterr(),
exit_code = self.exit_code,
}, nil, nil, {quiet = true})
end
end
end
end)
end
if not self.bg then
--release all db connections now in case this is a long running task.
release_dbs()
end
end
mm.task = task:subclass()
mm.exec = exec_task:subclass()
mm.task:after('init', mm_task_init)
mm.exec:after('init', mm_task_init)
local function cmp_start_time(t1, t2)
return (t1.start_time or 0) < (t2.start_time or 0)
end
rowset.running_tasks = virtual_rowset(function(self)
self.allow = 'admin'
self.fields = {
{name = 'id' , 'id'},
{name = 'pinned' , 'bool'},
{name = 'type' , },
{name = 'name' , w = 200},
{name = 'machine' , hint = 'Machine(s) that this task affects'},
{name = 'status' , },
{name = 'start_time', 'time_timeago'},
{name = 'duration' , 'duration', w = 20,
hint = 'Duration till last change in input, output or status'},
{name = 'stdin' , hidden = true, maxlen = 16*1024^2},
{name = 'out' , hidden = true, maxlen = 16*1024^2},
{name = 'exit_code' , 'double', w = 20},
{name = 'notif' , hidden = true, maxlen = 16*1024^2},
{name = 'cmd' , hidden = true, maxlen = 16*1024^2},
}
self.pk = 'id'
self.rw_cols = 'pinned'
local function task_row(task)
return {
task.id,
task.pinned or false,
task.type,
task.name,
task.machine,
task.status,
task.start_time,
task.duration,
task.stdin,
task:stdouterr(),
task.exit_code,
cat(imap(task:notifications(), 'message'), '\n\n'),
istab(task.cmd)
and cmdline_quote_args(nil, unpack(task.cmd))
or task.cmd,
}
end
function self:load_rows(rs, params)
local filter = params['param:filter']
rs.rows = {}
for task in sortedpairs(tasks, cmp_start_time) do
if task.visible then
add(rs.rows, task_row(task))
end
end
end
function self:load_row(row)
local task = tasks_by_id[row['id:old']]
return task and task_row(task)
end
function self:update_row(row)
local task = tasks_by_id[row['id:old']]
if not task then return end
task.pinned = row.pinned
end
function self:delete_row(row)
local task = tasks_by_id[row['id:old']]
assert(task:kill())
end
end)
mm.print_rowset_cols.running_tasks = [[
id
type
name
machine
deploy
status
start_time
duration
exit_code
errors
]]
function mm.print_running_tasks()
mm.print_rowset('running_tasks')
end
function api.tail_running_task(opt, task_id)
local task = checkarg(tasks_by_id[id_arg(task_id)], 'invalid task id: %s', task_id)
NYI'tail'
end
cmd_tasks('t|tasks [ID]', 'Show running tasks', function(opt, task_id)
if task_id then
mm.tail_running_task(task_id)
else
mm.print_running_tasks()
end
end)
rowset.task_runs = sql_rowset{
allow = 'admin',
select = [[
select
task_run ,
start_time ,
name ,
duration ,
stdin ,
stdouterr ,
exit_code
from
task_run
]],
pk = 'task_run',
hide_cols = 'stdin stdouterr',
}
--scheduled tasks ------------------------------------------------------------
rowset.scheduled_tasks = virtual_rowset(function(self)
self.allow = 'admin'
self.fields = {
{name = 'sched_name' , 'longstrid'},
{name = 'task_name' , 'longstrid'},
{name = 'ctime' , 'time_ctime'},
--sched
{name = 'start_hours' , 'timeofday_in_seconds'},
{name = 'run_every' , 'duration', duration_format = 'long'},
{name = 'active' , 'bool1'},
--stats
{name = 'last_run' , 'time_timeago'},
{name = 'last_duration', 'duration'},
{name = 'last_status' , 'strid'},
--child fks for cascade removal.
{name = 'machine' , 'strid'},
{name = 'deploy' , 'strid'},
}
self.pk = 'sched_name'
local function sched_row(t)
return {
t.sched_name,
t.task_name,
t.ctime,
t.start_hours,
t.run_every,
t.active,
t.last_run,
t.last_duration,
t.last_status,
t.machine,
t.deploy,
}
end
local function load_rows()
local rows = {}
for name, sched in sortedpairs(scheduled_tasks, cmp_ctime) do
add(rows, sched_row(sched))
end
return rows
end
local function cmp_ctime(t1, t2)
return t1.ctime < t2.ctime
end
function self:load_rows(rs, params)
local filter = params['param:filter']
rs.rows = load_rows()
end
function self:load_row(row)
local name = row['sched_name:old']
local t = scheduled_tasks[name]
return t and sched_row(t)
end
function self:update_row(row)
local name = row['sched_name:old']
local t = scheduled_tasks[name]
if not t then return end
t.active = row.active
end
function self:delete_row(row)
local name = row['sched_name:old']
local t = scheduled_tasks[name]
if not t then return end
t.active = false
end
end)
function mm.print_scheduled_tasks()
mm.print_rowset('scheduled_tasks')
end
cmd_tasks('ts|task-schedule', 'Show task schedule', mm.print_scheduled_tasks)
local function load_tasks_last_run()
for _, sched_name, last_run in each_row_vals[[
select sched_name, last_run from task_last_run
]] do
local t = scheduled_tasks[sched_name]
if t then t.last_run = last_run end
end
end
--client rowset API ----------------------------------------------------------
--filter: {k1v1,k1v2,...} or {{k1v1,k1v2},{k1v3,k2v4},...} for composite pks.
function mm.get_rowset(name, filter)
local t
if from_server() then
local call_opt = filter and {args = {filter = json_encode(filter)}}
t = call_json_api(call_opt, 'rowset.json', name)
else
NYI'get_rowset'
end
--add unserializable field attrs (eg. to_text) back on the client-side.
mm.schema:resolve_types(t.fields)
return t
end
function parse_key_and_vals(row_type, name, key, vals) --col1=val1,...
checkarg(name, 'rowset name required')
local rowset = checkfound(rowset[name], 'unknown rowset: '..name)
local pk_vals = collect(key:gmatch'[^,]+')
local t = {}
for i,pk_name in ipairs(rowset.pk) do
local k = row_type == 'new' and pk_name or pk_name..':old'
t[k] = pk_vals[i]
end
for kv in (vals or ''):gmatch'[^,]+' do
local k,v = split2('=', kv)
assert(k, 'key1=value1,... expected')
t[k] = repl(v, nil, null)
end
return t
end
function print_update_result(rowset_name, t)
local row = t.rows and t.rows[1]
if row.error then
print('Error: '..row.error)
end
if row.field_errors then
print'Field errors:'
for k,v in sortedpairs(row.field_errors) do
print(_('%20s: %s', k, v))
end
end
if row.values then
--add unserializable field attrs (eg. to_text) back on the client-side.
mm.schema:resolve_types(t.fields)
mysql_print_result({
rows = {t.rows[1].values},
fields = t.fields,
showcols = mm.print_rowset_cols[rowset_name],
})
end
end
mm.print_rowset_cols = {} --{rowset->'col1 '}
function mm.print_rowset(opt, name, cols, filter)
if opt ~= nil and not istab(opt) then
return mm.print_rowset(nil, opt, name, cols, filter)
end
local t = mm.get_rowset(name or 'rowsets', filter)
mysql_print_result(update({
rows = t.rows, fields = t.fields,
showcols = cols or mm.print_rowset_cols[name],
}, opt))
end
cmd('r|rowset [-cols=col1,...] [NAME] [FILTER]', 'Show a rowset', function(opt, name, filter)
local cols = opt.cols and opt.cols:gsub(',', ' ')
mm.print_rowset(name, cols, filter)
end)
function mm.update_row(row_type, name, vals)
local t
if from_server() then
local rows = {{type = row_type, values = vals}}
local changes = {rows = rows}
local post = {exec = 'save', changes = changes}
t = call_json_api({upload = post}, 'rowset.json', name)
else
NYI'update_row'
end
return t
end
cmd('add NAME KEY col1=val1,...', 'Insert a row into a rowset', function(opt, name, key, vals)
print_update_result(name, mm.update_row('new', name,
parse_key_and_vals('new', name, key, vals)))
end)
cmd('set NAME KEY col1=val1,...', 'Update a row from a rowset', function(opt, name, key, vals)
print_update_result(name, mm.update_row('update', name,
parse_key_and_vals('update', name, key, vals)))
end)
function mm.delete_row(name, key)
--check if the row exists first
local t = mm.get_rowset(name, key)
checkfound(#t.rows > 0, cat(rowset[name].pk, ',')..' not found: '..cat(key, ','))
--delete the row
return mm.update_row('remove', name, key)
end
cmd('del NAME KEY', 'Delete a row from a rowset', function(opt, name, key)
print_update_result(name, mm.delete_row(name, parse_key_and_vals('delete', name, key)))
end)
--client info api ------------------------------------------------------------
function api.active_machines()
return (query'select machine from machine where active = 1')
end
function mm.each_machine(f, fmt, ...)
local machines = mm.active_machines()
local threads = sock.threadset()
for _,machine in ipairs(machines) do
resume(threads:thread(f, fmt, machine, ...), machine)
end
threads:wait()
end
--for each machine run a Lua API on the client-side.
local function callm(cmd, machine)
if not machine then
mm.each_machine(function(m)
mm[cmd](m)
end, cmd..' %s')
return
end
mm[cmd](machine)
end
function api.deploy_info(opt, deploy)
return checkfound(first_row([[
select
deploy,
machine,
active,
mysql_pass,
domain,
app
from deploy where deploy = ?
]], checkarg(deploy, 'deploy required')), 'deploy not found')
end
function api.ip_and_machine(opt, md)
local md = checkarg(md, 'machine or deploy required')
local m = first_row('select machine from deploy where deploy = ?', md) or md
local t = first_row('select machine, public_ip from machine where machine = ?', m)
checkfound(t, 'machine not found: %s', m)
checkfound(t.public_ip, 'machine does not have a public ip: %s', m)
return {t.public_ip, m}
end
function mm.ip(md)
return unpack(mm.ip_and_machine(md))
end
cmd_machines('ip MACHINE|DEPLOY', 'Get the IP address of a machine or deployment',
function(opt, md)
print((mm.ip(md)))
end)
--ssh / host keys ------------------------------------------------------------
function sshcmd(cmd)
return win and indir(mm.sshdir, cmd) or cmd
end
local function known_hosts_file()
return varpath'known_hosts'
end
function api.known_hosts_file_contents()
return load(known_hosts_file())
end
function mm.known_hosts_file()
local file = known_hosts_file()
if from_server() then
save(file, mm.known_hosts_file_contents(), nil, '0600')
end
return file
end
local function gen_known_hosts_file()
local t = {}
for i, ip, s in each_row_vals[[
select public_ip, ssh_hostkey
from machine
where ssh_hostkey is not null
order by pos, ctime
]] do
add(t, s)
end
save(mm.known_hosts_file(), concat(t, '\n'), nil, '0600')
end
function api.ssh_hostkey_update(opt, machine)
local ip, machine = mm.ip(machine)
local s = mm.exec({
sshcmd'ssh-keyscan', '-4', '-T', '2', '-t', 'rsa', ip
}, {
name = 'ssh_hostkey_update '..machine,
out_stdout = false,
out_stderr = false,
}):stdout()
assert(update_row('machine', {machine, ssh_hostkey = s}).affected_rows == 1)
gen_known_hosts_file()
notify('Host key updated for %s.', machine)
end
cmd_ssh_keys('ssh-hostkey-update MACHINE', 'Make a machine known again to us',
mm.ssh_hostkey_update)
function api.ssh_hostkey(opt, machine)
return checkfound(first_row([[
select ssh_hostkey from machine where machine = ?
]], checkarg(machine, 'machine required')), 'hostkey not found for machine: %s', machine):trim()
end
cmd_ssh_keys('ssh-hostkey MACHINE', 'Show a SSH host key', function(...)
print(mm.ssh_hostkey(...))
end)
function api.ssh_hostkey_sha(opt, machine)
machine = checkarg(machine, 'machine required')
local key = first_row([[
select ssh_hostkey from machine where machine = ?
]], machine)
local key = checkfound(key, 'hostkey not found for machine: %s', machine):trim()
local task = mm.exec(sshcmd'ssh-keygen'..' -E sha256 -lf -', {
stdin = key,
out_stdout = false,
name = 'ssh_hostkey_sha '..machine,
nolog = true,
})
return (task:stdout():trim():match'%s([^%s]+)')
end