-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathiiab-cmdsrv3.py
4216 lines (3510 loc) · 149 KB
/
iiab-cmdsrv3.py
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
#!/usr/bin/python3
"""
Multi-threaded Polling Command server
Author: Tim Moody <tim(at)timmoody(dot)com>
Contributions: Guillaume Aubert (gaubert) <guillaume(dot)aubert(at)gmail(dot)com>
Felipe Cruz <felipecruz@loogica.net>
Accepts commands in the form COMMAND <optional json-encoded arguments>
Returns json-encoded results
"""
import os, sys, syslog, signal
from glob import glob
import logging
from systemd import journal
import pwd, grp
import time
from datetime import date, datetime, timedelta
import threading, subprocess
import shlex
import shutil
import zmq
import sqlite3
import json
import xml.etree.ElementTree as ET
import yaml
import configparser
import re
import urllib.request, urllib.error, urllib.parse
import string
import mimetypes
import cracklib
import socket
import hashlib
import binascii
import iiab.adm_lib as adm
# import cgi # keep to escape html in future
# cmdsrv config file
# if run standalone is in current directory
# if run as service the directory is passed as an environment variable by systemd
if 'CMDSRV_DIR' in os.environ:
cmdsrv_dir = os.environ['CMDSRV_DIR']
else:
cmdsrv_dir = "."
cmdsrv_config_file = cmdsrv_dir + "/cmdsrv.conf"
cmdsrv_pid_file = "/run/iiab-cmdsrv.pid"
cmdsrv_ready_file = "/run/iiab-cmdsrv-ready"
# IIAB Config Files
iiab_config_file = None
iiab_ini_file = None
iiab_local_vars_file = None
# Variables that should be read from config file
# All of these variables will be read from config files and recomputed in init()
iiab_repo = None
iiab_base = None
cmdsrv_dbname = None
cmdsrv_no_workers = 5
cmdsrv_job_poll_sleep_interval = 1
cmdsrv_max_concurrent_jobs = 7
cmdsrv_lower_job_priority_flag = None
cmdsrv_lower_job_priority_str= None
# Derived Variables
cmdsrv_dbpath = None
# Constants
# for kiwix zims
kiwix_catalog_file = None
doc_root = None
content_base = None
zim_downloads_dir = None
zim_download_prefix = None
zim_working_dir = None
zim_dir = None
zim_content_dir = None
zim_index_dir = None
oer2go_catalog_file = None
oer2go_mods_url = None
rachel_downloads_dir = None
rachel_working_dir = None
rachel_version = None
maps_downloads_dir = None
maps_working_dir = None
adm_maps_catalog_file = None # used exclusively by admin console
adm_maps_catalog_url = None
adm_maps_catalog_path = None
maps_tiles_base = None
maps_sat_base = None
maps_download_src = None
vector_map_path = None
vector_map_tiles_path = None
osm_version = None
modules_dir = None
small_device_size = 525000 # bigger than anticipated boot partition
js_menu_dir = None
# Global Variables
last_command_rowid = 0
last_job_rowid = 0
active_commands = {}
zims_wip = {}
#
# CLEAN UP
#
#zims_wip["DOWNLOAD"] = {}
#zims_wip["IMPORT"] = {}
#zims_wip["EXPORT"] = {}
zims_downloading = {} # not used
zims_copying = {} # not used
oer2go_wip = {}
#oer2go_downloading = {}
#oer2go_copying = {}
oer2go_installed = []
osm_vect_installed = []
maps_wip = {}
jobs_requested = {}
jobs_to_restart = {}
jobs_to_cancel = {}
prereq_jobs = {}
jobs_running = {}
running_job_count = 0
SENSITIVE_COMMANDS = ["CHGPW", "AUTHENTICATE", "CTL-HOTSPOT", "SET-WIFI-CONNECTION-PARAMS"]
NO_LOG_COMMANDS = ["AUTHENTICATE"]
ANSIBLE_COMMANDS = ["RUN-ANSIBLE", "RESET-NETWORK", "RUN-ANSIBLE-ROLES"]
FULL_LOG_COMMANDS = ["RUN-ANSIBLE", "RESET-NETWORK", "RUN-ANSIBLE-ROLES"]
ansible_running_flag = False
iiab_roles_status = {}
daemon_mode = False
init_error = False
# Logging
journal_log = logging.getLogger('IIAB-CMDSRV')
journal_log.setLevel(5) # having two different severity scales is nuts
journal_log.propagate = False
jhandler = journal.JournalHandler(SYSLOG_IDENTIFIER='IIAB-CMDSRV')
journal_log.addHandler(jhandler)
# Locking
lock = threading.Lock() # for updating global variables
db_lock = threading.Lock() # for sqlite db concurrency
# vars read from ansible vars directory
# effective is composite where local takes precedence
adm_conf = {} # for use by front end
default_vars = {} # /opt/iiab/iiab/vars/default_vars.yml
local_vars = {} # /etc/iiab/local_vars.yml
effective_vars = {}
ansible_facts = {}
ansible_tags = {}
iiab_ini = {}
kiwix_catalog = {}
oer2go_catalog = {}
maps_catalog = {} # this has been flattened when read to include both maps and base
is_rpi = False
# vars set by admin-console
# config_vars = {} no longer distinct from local vars
# available commands are in cmd_handler
def main():
"""Server routine"""
#global daemon_mode
#daemon_mode = True # for testing
global init_error
# if not in daemon mode don't trap errors
if daemon_mode == False:
init()
else:
try:
init()
except:
init_error = True
log(syslog.LOG_INFO, 'Command Server Initialization Failed' )
worker_data_url = "inproc://worker_data"
worker_control_url = "inproc://worker_control"
ipc_sock = "/run/cmdsrv_sock"
client_url = "ipc://" + ipc_sock
owner = pwd.getpwnam(apache_user)
group = grp.getgrnam(apache_user)
# Prepare our context and sockets
context = zmq.Context.instance()
# Socket to talk to clients
clients = context.socket(zmq.ROUTER)
clients.bind(client_url)
os.chown(ipc_sock, owner.pw_uid, group.gr_gid)
os.chmod(ipc_sock, 0o770)
# Socket to talk to workers
workers_data = context.socket(zmq.DEALER)
workers_data.bind(worker_data_url)
workers_control = context.socket(zmq.PUB)
workers_control.bind(worker_control_url)
# Launch thread to monitor jobs
thread = threading.Thread(target=job_minder_thread, args=(client_url, worker_control_url,))
thread.start()
# Launch pool of worker threads
for i in range(cmdsrv_no_workers):
thread = threading.Thread(target=cmd_proc_thread, args=(worker_data_url, worker_control_url,))
thread.start()
poll = zmq.Poller()
poll.register(clients, zmq.POLLIN)
poll.register(workers_data, zmq.POLLIN)
server_run = True
set_ready_flag("ON")
while server_run == True:
sockets = dict(poll.poll())
if clients in sockets:
ident, msg = clients.recv_multipart()
msg = msg.decode('utf8') # byte to str
#tprint(f'sending message server received from client to worker %s id %s' % (msg, ident))
tprint(f'sending message server received from client to worker {msg} id {ident}')
if msg == 'STOP':
# Tell the worker threads to shut down
set_ready_flag("OFF")
tprint('sending control message server received from client to worker %s id %s' % (msg, ident))
workers_control.send(b'EXIT')
clients.send_multipart([ident, b'{"Status": "Stopping"}'])
log(syslog.LOG_INFO, 'Stopping Command Server')
time.sleep(3)
server_run = False
else:
# if in daemon mode report and init failed always return same error message
if daemon_mode == True and init_error == True:
msg = '{"Error": "IIAB-CMDSRV failed to initialize","Alert": "True"}'
clients.send_multipart([ident, msg.encode('utf8')])
else:
tprint('sending data message server received from client to worker %s id %s' % (msg, ident))
workers_data.send_multipart([ident, msg.encode('utf8')])
if workers_data in sockets:
ident, msg = workers_data.recv_multipart()
tprint('Sending worker message to client %s id %s' % (msg[:60], ident))
clients.send_multipart([ident, msg])
# Clean up if server is stopped
clients.close()
workers_data.close()
workers_control.close()
context.term()
# Delete any pid file to keep systemd happy
try:
os.remove(cmdsrv_pid_file)
except OSError:
pass
sys.exit()
def job_minder_thread(client_url, worker_control_url, context=None):
"""Job Monitoring Worker Routine"""
global jobs_requested # queue from command processor
global jobs_to_restart # queue from incomplete jobs in init
global jobs_to_cancel # queue of scheduled or running jobs to be cancellled from cancel command
global prereq_jobs # status of predecessor job = depend_on_job_id; used to cascade job steps; we do not support multiple descendents
global jobs_running # queue of jobs running, started from jobs requested
global ansible_running_flag
global running_job_count
tprint ("in job_minder_thread")
log(syslog.LOG_INFO, 'Job Minder Thread Started')
# working lists
jobs_requested_list = [] # just the job_id from jobs_requested
jobs_requested_done = [] # list of processed job_id from jobs_requested
prereq_jobs_to_clear = [] # prerequisite jobs whose descendent has been processed
jobs_to_close = [] # list of running jobs that have completed or been cancelled
# control signals from main thread
context = context or zmq.Context.instance()
control_socket = context.socket(zmq.SUB)
control_socket.connect(worker_control_url)
control_socket.setsockopt_string(zmq.SUBSCRIBE,"")
# Socket to send job status back to main
resp_socket = context.socket(zmq.DEALER)
resp_socket.connect(client_url)
poll = zmq.Poller()
poll.register(control_socket, zmq.POLLIN)
# Restart any incomplete jobs found during init
for job_id in jobs_to_restart:
job_info = jobs_to_restart[job_id]
if job_info['has_dependent'] == "Y":
prereq_jobs[job_id] = {'status': 'STARTED'} # for both 'STARTED' and 'RESTARTED'
else:
add_wip(job_info)
job_info = start_job(job_id, job_info, status='RESTARTED')
jobs_running[job_id] = job_info
jobs_to_restart = {}
thread_run = True
# Main loop of IIAB-CMDSRV
while thread_run == True:
lock.acquire() # will block if lock is already held
try:
jobs_requested_list = list(jobs_requested.keys()) # create copy of keys so we can update global dictionary in loop
finally:
lock.release() # release lock, no matter what
# Go through each job in requested queue and conditionally start or cancel
# These are marked Scheduled
jobs_requested_done = [] # list of processed job_ids from jobs_requested to be cleared later
jobs_requested_list.sort()
for job_id in jobs_requested_list:
job_info = jobs_requested[job_id]
#print "starting cancel of requested"
# Remove cancelled jobs
if job_id in jobs_to_cancel:
job_info = cancel_req_job(job_id, job_info)
jobs_requested[job_id] = job_info
jobs_requested_done.append(job_id)
# we will pop from jobs_to_cancel later when clearing jobs_requested
continue
# don't create ansible job if one is running
if job_info['cmd'] in ANSIBLE_COMMANDS and ansible_running_flag == True:
continue
# don't start job if at max allowed
if running_job_count >= cmdsrv_max_concurrent_jobs:
# print(f'Waiting for queue: running_job_count {running_job_count}, cmdsrv_max_concurrent_jobs {cmdsrv_max_concurrent_jobs}')
continue
#print "starting prereq check"
# don't start job if it depends on another job that is not finished
depend_on_job_id = job_info['depend_on_job_id']
if depend_on_job_id in prereq_jobs:
prereq_status = prereq_jobs[depend_on_job_id]['status']
if prereq_status in ('SCHEDULED', 'STARTED'):
continue # successor step can't start yet
else:
if prereq_status == 'SUCCEEDED':
job_info = start_job(job_id, job_info) # Create running job
jobs_running[job_id] = job_info
if job_id in prereq_jobs:
prereq_jobs[job_id]['status'] = 'STARTED'
jobs_requested_done.append(job_id)
prereq_jobs_to_clear.append(depend_on_job_id) # mark for deletion
else: # predecessor failed or was cancelled
job_info = cancel_req_job(job_id, job_info)
jobs_requested_done.append(job_id)
prereq_jobs_to_clear.append(depend_on_job_id) # mark for deletion
else: # not a multi-step job or first step of multi
# don't start if depends on uninstalled or inactive service
service_required = job_info.get('service_required') # array that holds service and required state
if service_required:
if not iiab_roles_status.get(service_required[0], {}).get(service_required[1]):
continue
job_info = start_job(job_id, job_info) # Create running job
jobs_running[job_id] = job_info
jobs_requested_done.append(job_id)
#print 'starting clear'
# WRONG prereq_jobs_to_clear = []
# Clear started or cancelled jobs from requested queue and prereq dict
for job_id in jobs_requested_done:
jobs_requested.pop(job_id, None)
if job_id in jobs_to_cancel:
jobs_to_cancel.pop(job_id, None)
jobs_requested_done = []
# clear prerequisites for started or failed jobs from prereq_jobs
for depend_on_job_id in prereq_jobs_to_clear:
prereq_jobs.pop (depend_on_job_id, None)
prereq_jobs_to_clear = []
#print 'starting poll'
# poll jobs_running for completed jobs
for job_id in jobs_running:
jobs_running[job_id]['subproc'].poll()
returncode = jobs_running[job_id]['subproc'].returncode
if returncode == None:
tprint (str(job_id) + ' still running.')
# Cancel job if requested
if job_id in jobs_to_cancel:
tprint (str(job_id) + ' cancelled.')
p = jobs_running[job_id]['subproc']
p.send_signal(signal.SIGINT)
t = 0
while t < 5:
rc = p.poll()
if rc != None:
break
time.sleep(1)
t += 1
if rc == None:
p.kill()
job_info = end_job(job_id, jobs_running[job_id], 'CANCELLED')
jobs_to_close.append(job_id)
upd_job_cancelled(job_id)
else:
tprint (str(job_id) + ' terminated.')
# job_info['status_datetime'] = str(datetime.now()) ?
if returncode == 0:
status = 'SUCCEEDED'
else:
status = 'FAILED'
job_info = end_job(job_id, jobs_running[job_id], status)
# flag job for removal
jobs_to_close.append(job_id)
# print 'starting close jobs'
# now remove closed jobs from running list
for key in jobs_to_close:
if jobs_running[key]['has_dependent'] == "N": # delete from command list if last step of command
active_commands.pop(jobs_running[key]['cmd_rowid'], None)
remove_wip(jobs_running[key])
jobs_running.pop(key, None)
if key in jobs_to_cancel:
jobs_to_cancel.pop(key, None)
jobs_to_close = []
#print 'starting socket poll'
sockets = dict(poll.poll(1000))
if control_socket in sockets:
ctl_msg = control_socket.recv_string()
tprint('got ctl msg %s in monitor' % ctl_msg)
if ctl_msg == "EXIT":
# stop loop in order to terminate thread
log(syslog.LOG_INFO, 'Stopping Command Server Monitor Thread')
thread_run = False
#print 'starting sleep'
time.sleep(cmdsrv_job_poll_sleep_interval)
#print 'ready to loop'
# Clean up if thread is stopped
resp_socket.close()
control_socket.close()
#context.term()
#sys.exit()
def add_wip(job_info):
global zims_wip
global oer2go_wip
global maps_wip
dest = "internal"
source = "kiwix"
action = ""
cmd = job_info['cmd']
if cmd in {"INST-ZIMS", "COPY-ZIMS"}:
zim_id = job_info['cmd_args']['zim_id']
if cmd == "INST-ZIMS":
action = "DOWNLOAD"
dest = "internal"
source = "kiwix"
else:
dest = job_info['cmd_args']['dest']
source = job_info['cmd_args']['source']
if cmd == "COPY-ZIMS" and dest == "internal":
action = "IMPORT"
elif cmd == "COPY-ZIMS" and dest != "internal":
action = "EXPORT"
zims_wip[zim_id] = {"cmd":cmd, "action":action, "dest":dest, "source":source}
elif cmd in {"INST-OER2GO-MOD", "COPY-OER2GO-MOD"}:
moddir = job_info['cmd_args']['moddir']
if cmd == "INST-OER2GO-MOD":
action = "DOWNLOAD"
source = "oer2go"
else:
dest = job_info['cmd_args']['dest']
source = job_info['cmd_args']['source']
if cmd == "COPY-OER2GO-MOD" and dest == "internal":
action = "IMPORT"
elif cmd == "COPY-OER2GO-MOD" and dest != "internal":
action = "EXPORT"
oer2go_wip[moddir] = {"cmd":cmd, "action":action, "dest":dest, "source":source}
elif cmd in {"INST-OSM-VECT-SET"}:
# handle V1?
map_id = job_info['cmd_args']['osm_vect_id']
download_url = job_info['extra_vars']['download_url']
size = job_info['extra_vars']['size']
maps_wip[map_id] = {"cmd":cmd, "action":action, "dest":dest, "source":source, "download_url":download_url, "size": size}
elif cmd in {"INST-SAT-AREA"}:
pass
# radius = job_info['extra_vars']['radius'] not much housekeeping to do
def remove_wip(job_info):
global zims_wip
global oer2go_wip
global maps_wip
#print job_info
#print "in remove_wip"
if job_info['cmd'] in ["INST-ZIMS", "COPY-ZIMS"]:
zims_wip.pop(job_info['cmd_args']['zim_id'], None)
elif job_info['cmd'] in ["INST-OER2GO-MOD", "COPY-OER2GO-MOD"]:
oer2go_wip.pop(job_info['cmd_args']['moddir'], None)
elif job_info['cmd'] in {"INST-OSM-VECT-SET"}:
maps_wip.pop(job_info['cmd_args']['osm_vect_id'], None)
def start_job(job_id, job_info, status='STARTED'):
global running_job_count
global ansible_running_flag
global prereq_jobs
global cmdsrv_lower_job_priority_flag
global cmdsrv_lower_job_priority_str
job_info['output_file'] = '/tmp/job-' + str(job_id)
job_info['file'] = open(job_info['output_file'], 'w')
if cmdsrv_lower_job_priority_flag:
args = shlex.split(cmdsrv_lower_job_priority_str + job_info['job_command'])
else:
args = shlex.split(job_info['job_command'])
job_info['subproc'] = subprocess.Popen(args, stdout=job_info['file'], stderr=subprocess.STDOUT)
job_info['job_pid'] = job_info['subproc'].pid
job_info['status'] = status
job_info['status_datetime'] = str(datetime.now())
job_info['job_output'] = ""
#print (job_info)
if job_id in prereq_jobs:
prereq_jobs[job_id]['status'] = 'STARTED'
if job_info['cmd'] in ANSIBLE_COMMANDS:
ansible_running_flag = True
if status == 'STARTED':
log_msg = "Starting"
else:
log_msg = "Restarting"
log(syslog.LOG_INFO, "%s Job: %s, job_id: %s, pid: %s" % (log_msg, job_info['cmd'], job_id, job_info['job_pid']))
# update jobs table
upd_job_started(job_id, job_info['job_pid'], status)
running_job_count += 1
return (job_info)
def end_job(job_id, job_info, status): # modify to use tail of job_output
global prereq_jobs
global jobs_running
global ansible_running_flag
global running_job_count
jobs_running[job_id]['file'].close()
# load output from tmp file
job_output = read_job_output(job_id)
output_file = jobs_running[job_id]['output_file']
#file = open(output_file, 'r')
#job_output = file.read()
#file.close()
#command = "tail " + output_file
#args = shlex.split(command)
#job_output = subproc_check_output(args)
#print(job_output)
# make html safe
#job_output = escape_html(job_output)
# remove non-printing chars as an alternative
#job_output = job_output.encode('ascii', 'replace').decode()
# print(job_id)
tprint(job_output)
jobs_running[job_id]['job_output'] = job_output
# job_info['status_datetime'] = str(datetime.now()) ?
jobs_running[job_id]['status'] = status
if job_id in prereq_jobs:
prereq_jobs[job_id]['status'] = status
log(syslog.LOG_INFO, "Job: %s, job_id: %s, pid: %s, status:%s" % (jobs_running[job_id]['cmd'], job_id, jobs_running[job_id]['job_pid'], status))
# update jobs table and remove tmp output file
upd_job_finished(job_id, job_output, status)
os.remove(output_file)
if job_info['cmd'] in ANSIBLE_COMMANDS:
#if 1 == 1:
ansible_running_flag = False
#if status == "SUCCEEDED":
read_iiab_ini_file() # reread ini file after running ansible
read_iiab_roles_stat() # refresh global iiab_roles_status
running_job_count -= 1
if running_job_count < 0:
running_job_count = 0
return (job_info)
def cancel_req_job(job_id, job_info):
global active_commands
job_info['output_file'] = None
job_info['file'] = None
job_info['subproc'] = None
#job_info['job_pid'] = None
job_info['status'] = 'CANCELLED'
job_info['status_datetime'] = str(datetime.now())
#job_info['job_output'] = ""
if job_id in prereq_jobs:
prereq_jobs[job_id]['status'] = job_info['status']
log(syslog.LOG_INFO, "Cancelling Job: %s, job_id: %s" % (job_info['cmd'], job_id))
# update jobs table
upd_job_cancelled(job_id)
# Remove Active Command and any WIP tracking
if job_info['has_dependent'] == "N": # delete from command list if last step of command
active_commands.pop(job_info['cmd_rowid'], None)
remove_wip(job_info)
return (job_info)
def cmd_proc_thread(worker_data_url, worker_control_url, context=None):
"""Command Processing Worker Routine"""
context = context or zmq.Context.instance()
# Socket to talk to dispatcher
data_socket = context.socket(zmq.DEALER)
data_socket.connect(worker_data_url)
# control signals from main thread
control_socket = context.socket(zmq.SUB)
control_socket.connect(worker_control_url)
control_socket.setsockopt_string(zmq.SUBSCRIBE,"")
poll = zmq.Poller()
poll.register(data_socket, zmq.POLLIN)
poll.register(control_socket, zmq.POLLIN)
thread_run = True
while thread_run == True:
sockets = dict(poll.poll())
# process command
if data_socket in sockets:
ident, cmd_msg = data_socket.recv_multipart()
cmd_msg = cmd_msg.decode("utf8")
tprint('sending message server received from client to worker %s id %s' % (cmd_msg, ident))
cmd_resp = cmd_handler(cmd_msg)
#print cmd_resp
# 8/23/2015 added .encode() to response as list_library was giving unicode errors
data_socket.send_multipart([ident, cmd_resp.encode()])
if control_socket in sockets:
ctl_msg = control_socket.recv_string()
tprint('got ctl msg %s in worker' % ctl_msg)
if ctl_msg == "EXIT":
# stop loop in order to terminate thread
log(syslog.LOG_INFO, 'Stopping Command Server Worker Thread')
thread_run = False
# Clean up if thread is stopped
data_socket.close()
control_socket.close()
#context.term()
#sys.exit()
########################################
# cmdlist List of all Commands is Here #
########################################
def cmd_handler(cmd_msg):
# List of recognized commands and corresponding routine
# Don't do anything else
avail_cmds = {
"TEST": {"funct": do_test, "inet_req": False},
"TEST-JOB": {"funct": do_test_job, "inet_req": False},
"LIST-LIBR": {"funct": list_library, "inet_req": False},
"WGET": {"funct": wget_file, "inet_req": True},
"GET-ADM-CONF": {"funct": get_adm_conf, "inet_req": False},
"GET-ANS": {"funct": get_ans_facts, "inet_req": False},
"GET-ANS-TAGS": {"funct": get_ans_tags, "inet_req": False},
"GET-VARS": {"funct": get_install_vars, "inet_req": False},
"GET-IIAB-INI": {"funct": get_iiab_ini, "inet_req": False},
"SET-CONF": {"funct": set_config_vars, "inet_req": False},
"GET-RPI-STATE": {"funct": get_rpi_state, "inet_req": False},
"GET-MEM-INFO": {"funct": get_mem_info, "inet_req": False},
"GET-SPACE-AVAIL": {"funct": get_space_avail, "inet_req": False},
"GET-STORAGE-INFO": {"funct": get_storage_info_lite, "inet_req": False},
"GET-EXTDEV-INFO": {"funct": get_external_device_info, "inet_req": False},
"GET-REM-DEV-LIST": {"funct": get_rem_dev_list, "inet_req": False},
"GET-SYSTEM-INFO": {"funct": get_system_info, "inet_req": False},
"GET-NETWORK-INFO": {"funct": get_network_info, "inet_req": False},
"CTL-HOTSPOT": {"funct": ctl_hotspot, "inet_req": False},
"CTL-WIFI": {"funct": ctl_wifi, "inet_req": False},
"SET-WIFI-CONNECTION-PARAMS": {"funct": set_wifi_connection_params, "inet_req": False},
"REMOVE-WIFI-CONNECTION-PARAMS": {"funct": remove_wifi_connection_params_nm, "inet_req": False},
"CTL-BLUETOOTH": {"funct": ctl_bluetooth, "inet_req": False},
"CTL-VPN": {"funct": ctl_vpn, "inet_req": True},
"REMOVE-USB": {"funct": umount_usb, "inet_req": False},
"RUN-ANSIBLE": {"funct": run_ansible, "inet_req": False},
"RUN-ANSIBLE-ROLES": {"funct": run_ansible_roles, "inet_req": False},
"GET-ROLES-STAT": {"funct": get_roles_stat, "inet_req": False},
"RESET-NETWORK": {"funct": run_ansible, "inet_req": False},
"GET-JOB-STAT": {"funct": get_last_jobs_stat, "inet_req": False},
"GET-JOB-ACTIVE-SUM": {"funct": get_jobs_active_sum, "inet_req": False},
"CANCEL-JOB": {"funct": cancel_job, "inet_req": False},
"GET-WHLIST": {"funct": get_white_list, "inet_req": False},
"SET-WHLIST": {"funct": set_white_list, "inet_req": False},
"GET-INET-SPEED": {"funct": get_inet_speed, "inet_req": True},
"GET-INET-SPEED2": {"funct": get_inet_speed2, "inet_req": True},
"GET-KIWIX-CAT": {"funct": get_kiwix_catalog, "inet_req": True},
"GET-ZIM-STAT": {"funct": get_zim_stat, "inet_req": False},
"GET-PRESET-LIST": {"funct": get_preset_list, "inet_req": False},
"INST-PRESETS": {"funct": install_presets, "inet_req": True},
"INST-ZIMS": {"funct": install_zims, "inet_req": True},
"COPY-ZIMS": {"funct": copy_zims, "inet_req": False},
"MAKE-KIWIX-LIB": {"funct": make_kiwix_lib, "inet_req": False}, # runs as job
"RESTART-KIWIX": {"funct": restart_kiwix, "inet_req": False}, # runs immediately
"GET-OER2GO-CAT": {"funct": get_oer2go_catalog, "inet_req": True},
"INST-OER2GO-MOD": {"funct": install_oer2go_mod, "inet_req": True},
"COPY-OER2GO-MOD": {"funct": copy_oer2go_mod, "inet_req": False},
"GET-OER2GO-STAT": {"funct": get_oer2go_stat, "inet_req": False},
"GET-RACHEL-STAT": {"funct": get_rachel_stat, "inet_req": False},
"INST-RACHEL": {"funct": install_rachel, "inet_req": True},
"GET-OSM-VECT-CAT": {"funct": get_osm_vect_catalog, "inet_req": True},
"INST-OSM-VECT-SET": {"funct": install_osm_vect_set, "inet_req": True},
"INST-SAT-AREA": {"funct": install_sat_area, "inet_req": True},
"GET-OSM-VECT-STAT": {"funct": get_osm_vect_stat, "inet_req": False},
"INST-KALITE": {"funct": install_kalite, "inet_req": True},
"DEL-DOWNLOADS": {"funct": del_downloads, "inet_req": False},
"DEL-MODULES": {"funct": del_modules, "inet_req": False},
"DEL-CONTENT": {"funct": del_content, "inet_req": False},
"GET-MENU-ITEM-DEF-LIST": {"funct": get_menu_item_def_list, "inet_req": False},
"UPDATE-HOME-MENU": {"funct": update_home_menu, "inet_req": False},
"SAVE-MENU-DEF": {"funct": save_menu_def, "inet_req": False},
"SAVE-MENU-ITEM-DEF": {"funct": save_menu_item_def, "inet_req": False},
"SYNC-MENU-ITEM-DEFS": {"funct": sync_menu_item_defs, "inet_req": True},
"MOVE-UPLOADED-FILE": {"funct": move_uploaded_file, "inet_req": False},
"COPY-DEV-IMAGE": {"funct": copy_dev_image, "inet_req": False},
"REBOOT": {"funct": reboot_server, "inet_req": False},
"POWEROFF": {"funct": poweroff_server, "inet_req": False},
#"REMOTE-ADMIN-CTL": {"funct": remote_admin_ctl, "inet_req": True}, #true/false
#"GET-REMOTE-ADMIN-STATUS": {"funct": get_remote_admin_status, "inet_req": True}, #returns activated
"AUTHENTICATE": {"funct": authenticate, "inet_req": False},
"CHGPW": {"funct": change_password, "inet_req": False}
}
# parse the command
parse_failed, cmd_info = parse_cmd_msg(cmd_msg)
if parse_failed:
return cmd_malformed(cmd_info['cmd'])
cmd_info['cmd_msg'] = cmd_msg
cmd = cmd_info['cmd']
display_cmd_msg = cmd_msg
if cmd in SENSITIVE_COMMANDS:
display_cmd_msg = cmd + ' ***'
# log the command
if cmd not in NO_LOG_COMMANDS:
log(syslog.LOG_INFO, 'Received CMD Message %s.' % display_cmd_msg )
# Check for Duplicate Command
dup_cmd = next((job_id for job_id, active_cmd_msg in list(active_commands.items()) if active_cmd_msg == cmd_msg), None)
if dup_cmd != None:
strip_cmd_msg = cmd_msg.replace('\"','')
if cmd in SENSITIVE_COMMANDS:
strip_cmd_msg = cmd + ' ***'
log(syslog.LOG_ERR, "Error: %s duplicates an Active Command." % strip_cmd_msg)
resp = '{"Error": "' + strip_cmd_msg + ' duplicates an Active Command"}'
return (resp)
# store the command in database
if cmd not in NO_LOG_COMMANDS:
cmd_rowid = insert_command(display_cmd_msg)
cmd_info['cmd_rowid'] = cmd_rowid
#print (cmd_info)
# commands that run scripts should check for malicious characters in cmd_arg_str and return error if found
# bad_command = validate_command(cmd_arg_str)
# if not in daemon mode don't trap errors
if daemon_mode == False:
resp = avail_cmds[cmd]["funct"](cmd_info)
else:
if cmd in avail_cmds:
if avail_cmds[cmd]["inet_req"]:
if not is_internet_avail():
resp = cmd_error(cmd, msg='Internet is Required for this Command, but Not Available.')
return resp
try:
resp = avail_cmds[cmd]["funct"](cmd_info)
except:
log(syslog.LOG_ERR, "Error: Unexpected error in Command %s." % cmd)
resp = '{"Error": "Unexpected error in Command ' + cmd + '"}'
else:
log(syslog.LOG_ERR, "Error: Unknown Command %s." % cmd)
resp = '{"Error": "Unknown Command"}'
return (resp)
# Helper functions
def parse_cmd_msg(cmd_msg):
# convert string from client to cmd and cmd_args
cmd_dict = {}
parse_failed = False
parse = cmd_msg.split(' ')
cmd_dict['cmd'] = parse[0]
cmd_dict['cmd_args'] = {} # always have cmd_args
if len(parse) > 1:
try:
cmd_args_str = cmd_msg.split(cmd_dict['cmd'] + ' ')[1]
cmd_dict['cmd_args'] = json.loads(cmd_args_str)
except:
parse_failed = True
return parse_failed, cmd_dict
def is_internet_avail():
# return is_url_avail("www.google.com")
# return is_url_avail("neverssl.com") # 12/26/2024 does not exist
return is_url_avail("en.wikipedia.org") # something not caught by captive portal
def is_url_avail(url):
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection((url, 80))
return True
except: # any exception means no connection
pass
return False
#
# Functions to process Commands
#
def do_test(cmd_info):
#resp = cmd_success("TEST")
#return (resp)
outp = subproc_check_output(["scripts/test.sh"])
json_outp = json_array("TEST",outp)
return (json_outp)
def do_test_job(cmd_info):
if 'cmd_args' in cmd_info:
steps = cmd_info['cmd_args']['steps']
else:
return cmd_malformed(cmd_info['cmd'])
step_no = 1
job_id = -1
for step_sleep in steps:
job_command = "scripts/test-job.sh " + str(step_sleep)
if step_no < len(steps):
job_id = request_one_job(cmd_info, job_command, step_no, job_id, "Y")
else:
resp = request_job(cmd_info=cmd_info, job_command=job_command, cmd_step_no=step_no, depend_on_job_id=job_id, has_dependent="N")
step_no += 1
return resp
def list_library(cmd_info):
libr_list = {}
file_list = []
target_dir = "/library/"
try:
target_dir += cmd_info['cmd_args']['sub_dir']
except:
return cmd_malformed(cmd_info['cmd'])
libr_list['path'] = target_dir
cmdstr = "/usr/bin/du -ah " + target_dir
if not os.path.exists(target_dir):
resp = cmd_error(cmd='LIST-LIBR', msg='Path not Found.')
return (resp)
try:
outp = subproc_cmd(cmdstr)
file_arr = outp.split('\n')
for file in file_arr:
if file == "":
continue
tmp_arr = file.split("\t")
if tmp_arr[1] == target_dir:
continue
size = tmp_arr[0]
filename = tmp_arr[1].split("/")[-1]
file_attr = {}
file_attr['size'] = size
file_attr['filename'] = filename
file_list.append(file_attr)
libr_list['file_list'] = file_list
#str_json = json.dumps(library_list)
#json_resp = '{ "' + target_dir + '":' + str_json + '}'
json_resp = json.dumps(libr_list)
#print json_resp
except:
return cmd_malformed(cmd_info['cmd'])
return (json_resp)
def del_downloads(cmd_info):
if cmd_info['cmd_args']['sub_dir'] == "zims":
target_dir = zim_downloads_dir
elif cmd_info['cmd_args']['sub_dir'] == "rachel":
target_dir = rachel_downloads_dir
else:
return cmd_malformed(cmd_info['cmd'])
error_flag = False
try:
file_list = cmd_info['cmd_args']['file_list']
except:
return cmd_malformed(cmd_info['cmd'])
cmdstr = "rm " + target_dir
for file in file_list:
try:
outp = subproc_cmd(cmdstr + file)
except:
# ignore for now but report
error_flag = True
pass
if error_flag:
resp = cmd_success_msg(cmd_info['cmd'], "- Some errors occurred")
else:
resp = cmd_success(cmd_info['cmd'])
return (resp)
def del_content(cmd_info): # includes zims
error_flag = False
rm_menu_items = []
device = cmd_info['cmd_args']['device']
content = cmd_info['cmd_args']['content']
for content_type in content:
if content_type not in ["zims", "modules"]:
return cmd_malformed(cmd_info['cmd'])