forked from pyscada/PyScada
-
Notifications
You must be signed in to change notification settings - Fork 4
/
scheduler.py
1517 lines (1365 loc) · 61.3 KB
/
scheduler.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/python
# -*- coding: utf-8 -*-
"""
- > master_process
- > mail master
- > export master
- > export task A
- > export task B
- > event master
- > modbus master(registers a process for every device/port)
- > modbus device A (IP 1)
- > modbus device B (IP 2)
- > modbus device C, D (RTU, TTY1)
- > modbus device E, F (RTU, TTY2)
- > onewire (registers a process for every device/port)
- > onewire device G, H (server a)
- > visa (registers a process for every device/port)
- > visa device A
- > systemstat master
- > smbus (registers a process for every device/port)
- > jofra350 (registers a process for every device/port)
"""
from __future__ import unicode_literals
import atexit
import errno
from os import linesep, umask, access, W_OK, kill, remove, setsid, path, fork, F_OK, WNOHANG, getpid, waitpid
import signal
import sys
import traceback
from time import time, sleep
from datetime import datetime
import json
from django.conf import settings
from django.db import connection, connections
from django.utils.termcolors import colorize
from django.db.utils import OperationalError
from django.db.transaction import TransactionManagementError
from django.db.models import Q
from django.db.utils import IntegrityError
from pyscada.models import BackgroundProcess, DeviceWriteTask, Device, RecordedData, DeviceReadTask, VariableProperty
from pyscada.utils import set_bit
from django.utils.timezone import now
import logging
logger = logging.getLogger(__name__)
try:
import channels.layers
from channels.exceptions import InvalidChannelLayerError
from channels.exceptions import ChannelFull
from asgiref.sync import async_to_sync
from asyncio import wait_for
from aioredis.errors import ConnectionClosedError
try:
from asyncio.exceptions import TimeoutError as asyncioTimeoutError
from asyncio.exceptions import CancelledError as asyncioCancelledError
except ModuleNotFoundError:
# for python version < 3.8
from asyncio import TimeoutError as asyncioTimeoutError
from asyncio import CancelledError as asyncioCancelledError
if channels.layers.get_channel_layer() is None:
logger.warning("Django Channels is not working. Missing config in settings ?")
raise ConnectionRefusedError
else:
async def channels_test():
await wait_for(channels.layers.get_channel_layer().receive('test'), timeout=0.1)
async_to_sync(channels_test)()
channels_driver = True
except (ImportError, ModuleNotFoundError):
channels_driver = False
except ConnectionRefusedError:
logger.warning("Django Channels is not working. redis-server not running ?")
channels_driver = False
except (TimeoutError, asyncioTimeoutError):
channels_driver = True
def check_db_connection():
"""
from: https://stackoverflow.com/questions/7835272/django-operationalerror-2006-mysql-server-has-gone-away
"""
# mysql is lazily connected to in django.
# connection.connection is None means
# you have not connected to mysql before
if connection.connection and not connection.is_usable():
# destroy the default mysql connection
# after this line, when you use ORM methods
# django will reconnect to the default mysql
logger.debug('deleted default connection')
del connections._connections.default
def close_db_connection():
if connection.connection is not None:
connection.connection.close()
connection.connection = None
class Scheduler(object):
"""
Manages and monitor all the sub processes.
"""
PROCESSES = {}
SIG_QUEUE = []
SIGNALS = [signal.SIGTERM, signal.SIGUSR1, signal.SIGHUP, signal.SIGUSR2]
if hasattr(settings, 'PID_FILE_NAME'):
pid_file_name = str(settings.PID_FILE_NAME)
else:
pid_file_name = '/tmp/pyscada_daemon.pid'
def __init__(self, daemon_name='pyscada.utils.scheduler.Scheduler',
run_as_daemon=True, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr,
pid_file_name=pid_file_name):
"""
"""
self.pid_file_name = pid_file_name
self.run_as_daemon = run_as_daemon
self.pid = None
self.process_id = None
self.stdout = stdout
self.stdin = stdin
self.stderr = stderr
if not access(path.dirname(self.pid_file_name), W_OK) and self.run_as_daemon:
self.stdout.write("pidfile path is not writeable\n")
sys.exit(0)
if access(self.pid_file_name, F_OK) and not access(self.pid_file_name, W_OK) and self.run_as_daemon:
self.stdout.write("pidfile file is not writeable\n")
sys.exit(0)
self.label = daemon_name
def init_db(self, sig=0):
"""
"""
for process in BackgroundProcess.objects.filter(done=False, pid__gt=0):
try:
kill(process.pid, sig)
self.stderr.write("init db aborted, at least one process is alive\n")
return False
except OSError as e:
if e.errno == errno.ESRCH: # no such process
process.message = 'stopped'
process.pid = 0
process.last_update = now()
process.save()
elif e.errno == errno.EPERM: # Operation not permitted
self.stderr.write("can't stop process %d: %s with pid %d, 'Operation not permitted'\n" % (
process.pk, process.label, process.pid))
BackgroundProcess.objects.all().delete()
# add the Scheduler Process
parent_process = BackgroundProcess(pk=1, label='pyscada.utils.scheduler.Scheduler',
enabled=True,
process_class='pyscada.utils.scheduler.Process')
parent_process.save()
# check for processes to add in init block of each app
if 'pyscada.core' not in settings.INSTALLED_APPS:
# append core to initialize pyscada.event and pyscada.mail
settings.INSTALLED_APPS.append('pyscada.core')
for app in settings.INSTALLED_APPS:
m = __import__(app, fromlist=[str('a')])
self.stderr.write("app %s\n" % app)
if hasattr(m, 'parent_process_list'):
for process in m.parent_process_list:
self.stderr.write("--> add %s\n" % process['label'])
if 'enabled' not in process:
process['enabled'] = True
if 'parent_process' not in process:
process['parent_process'] = parent_process
bp = BackgroundProcess(**process)
bp.save()
self.stderr.write("init db completed\n")
return True
def demonize(self):
"""
do the double fork magic
"""
# check if a process is already running
if access(self.pid_file_name, F_OK):
# read the pid file
pid = self.read_pid()
try:
kill(pid, 0) # check if process is running
self.stderr.write("process is already running\n")
return False
except OSError as e:
if e.errno == errno.ESRCH:
# process is dead
self.delete_pid(force_del=True)
else:
self.stderr.write("demonize failed, something went wrong: %d (%s)\n" % (e.errno, e.strerror))
return False
try:
pid = fork()
if pid > 0:
# Exit from the first parent
timeout = time() + 60
while self.read_pid() is None:
self.stderr.write("waiting for pid..\n")
sleep(0.5)
if time() > timeout:
break
self.stderr.write("pid is %d\n" % self.read_pid())
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 1. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment
# os.chdir("/")
setsid()
umask(0)
# Do the Second fork
try:
pid = fork()
if pid > 0:
# Exit from the second parent
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 2. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
# sys.stdout.flush()
# sys.stderr.flush()
# si = file(self.stdin, 'r')
# so = file(self.stdout, 'a+')
# se = file(self.stderr, 'a+',
# os.dup2(si.fileno(), sys.stdin.fileno())
# os.dup2(so.fileno(), sys.stdout.fileno())
# os.dup2(se.fileno(), sys.stderr.fileno())
# Write the PID file
#atexit.register(self.delete_pid)
self.write_pid()
return True
def write_pid(self, pid=None):
if pid is None:
pid = getpid()
with open(self.pid_file_name, 'w+') as f:
f.write('%d\n' % pid)
logger.info('created pid %d' % pid)
def read_pid(self):
if not access(self.pid_file_name, F_OK):
return None
# try reading the pid during 5 seconds
for i in range(1, 6):
try:
with open(self.pid_file_name, 'r') as f:
pid = int(f.read().strip())
return pid
except ValueError:
sleep(1)
return None
def delete_pid(self, force_del=False):
"""
delete the pid file
"""
pid = self.read_pid()
if pid != getpid() or force_del:
logger.debug('process %d tried to delete pid' % getpid())
return False
if access(self.pid_file_name, F_OK):
try:
remove(self.pid_file_name) # remove the old pid file
logger.debug('delete pid (%d)' % getpid())
except:
logger.debug("can't delete pid file")
def start(self):
"""
start the scheduler
"""
# demonize
if self.run_as_daemon:
if not self.demonize():
self.delete_pid()
sys.exit(0)
# recreate the DB connection
close_db_connection()
try:
master_process = BackgroundProcess.objects.filter(parent_process__isnull=True,
label=self.label,
enabled=True).first()
except OperationalError as e:
logger.error("Cant't connect to the DB : " + str(e))
#self.delete_pid(force_del=True)
sys.exit(0)
self.pid = getpid()
if not master_process:
self.delete_pid(force_del=True)
logger.debug('no such process in BackgroundProcesses\n')
sys.exit(0)
# kill all the sub processes
for process in BackgroundProcess.objects.filter(done=False, pid__gt=0):
try:
kill(process.pid, 9)
except:
pass
# Init the DB
if not self.init_db():
logger.debug('Init DB failed\n')
sys.exit(0)
self.process_id = master_process.pk
master_process.pid = self.pid
master_process.last_update = now()
master_process.running_since = now()
master_process.done = False
master_process.failed = False
master_process.message = 'init master process'
master_process.save()
BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False).update(message='stopped')
for parent_process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False):
for process in BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False):
try:
kill(process.pid, 0)
except OSError as e:
if e.errno == errno.ESRCH:
process.delete()
continue
logger.debug('process %d is alive' % process.pk)
process.stop()
# clean up
BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False).delete()
# register signals
[signal.signal(s, self.signal) for s in self.SIGNALS]
#signal.signal(signal.SIGCHLD, self.handle_chld)
# start the main loop
self.run()
self.delete_pid()
sys.exit(0)
def run(self):
"""
the main loop
"""
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
master_process.save()
else:
self.delete_pid(force_del=True)
self.stderr.write("no such process in BackgroundProcesses")
sys.exit(0)
self.manage_processes()
while True:
# handle signals
sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None
# check the DB connection
check_db_connection()
# update the Process
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='running..')
if sig is None:
self.manage_processes()
elif sig not in self.SIGNALS:
logger.error('%s, unhandled signal %d' % (self.label, sig))
continue
elif sig == signal.SIGTERM:
logger.debug('%s, termination signal' % self.label)
raise StopIteration
elif sig == signal.SIGHUP:
# todo handle sighup
pass
elif sig == signal.SIGUSR1:
# restart all child processes
logger.debug('PID %d, LABEL %s, processed SIGUSR1 (%d) signal' % (self.pid, self.label, sig))
self.restart()
elif sig == signal.SIGUSR2:
# write the process status to stdout
self.status()
pass
close_db_connection()
sleep(5)
except StopIteration:
self.stop()
self.delete_pid()
sys.exit(0)
except SystemExit:
raise
except OperationalError:
logger.debug('%s, DB connection lost in run' % self.label)
self.stop()
self.delete_pid()
sys.exit(0)
except:
logger.error('%s(%d), unhandled exception\n%s' % (self.label, getpid(), traceback.format_exc()))
def manage_processes(self):
"""
"""
# check for new processes to spawn
process_list = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
process_list.append(process)
process_list += list(process.backgroundprocess_set.filter())
for process in process_list:
#
if not process.enabled or not process.parent_process.enabled or process.done:
if process.pk in self.PROCESSES:
timeout = time() + 60 # wait max 60 seconds
while True:
if process.pk not in self.PROCESSES or time() > timeout:
try:
self.kill_process(process.pk, signal.SIGKILL)
except:
pass
break
self.kill_process(process.pk)
sleep(1)
continue
continue
if process.pk in self.PROCESSES:
continue
if process.parent_process.pk not in self.PROCESSES and process.parent_process.pk != self.process_id:
continue
# spawn new process
process_inst = process.get_process_instance()
if process_inst is not None:
self.spawn_process(process_inst)
logger.debug('process %s started' % process.label)
else:
logger.debug('process %s returned None' % process.label)
# check all running processes
process_list = list(self.PROCESSES.values())
for process in process_list:
try:
kill(process.pid, 0)
waitpid(process.pid, WNOHANG)
except OSError as e:
if e.errno == errno.ESRCH:
logger.debug('process %d is dead' % process.process_id)
try:
self.PROCESSES.pop(process.process_id)
except:
pass
# process is dead, delete process
if process.parent_process_id == self.process_id:
p = BackgroundProcess.objects.filter(pk=process.process_id).first()
if p:
p.pid = 0
p.last_update = now()
p.failed = True
p.save()
else:
# delete grandchild process
BackgroundProcess.objects.filter(pk=process.process_id).delete()
def handle_chld(self, sig, frame):
"""
SIGCHLD handling
:param sig:
:param frame:
:return:
"""
try:
while True:
wpid, status = waitpid(-1, WNOHANG)
if not wpid:
break
# self.stdout.write('%d,%d\n' % (wpid, status))
except:
pass
def restart(self):
"""
restart all child processes
"""
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='restarting..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
sleep(0.1)
self.kill_processes(signal.SIGKILL)
self.manage_processes()
logger.debug('BD %d: restarted' % self.process_id)
def stop(self, sig=signal.SIGTERM):
"""
stop the scheduler and stop all processes
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
try:
sp = BackgroundProcess.objects.filter(pk=1).first()
except OperationalError as e:
logger.error("Cant't connect to the DB : " + str(e))
self.delete_pid(force_del=True)
sys.exit(0)
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
logger.error("can't determine process id exiting.")
return False
if self.pid != getpid():
# calling from outside the daemon instance
logger.debug('send sigterm to daemon')
try:
kill(self.pid, sig)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
logger.debug('start termination of the daemon')
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopping..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
self.kill_processes(signal.SIGTERM)
sleep(1)
self.kill_processes(signal.SIGKILL)
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopped')
logger.debug('termination of the daemon done')
return True
def kill_process(self, process_id, sig=signal.SIGTERM):
"""
"""
p = self.PROCESSES[process_id]
try:
kill(p.pid, sig)
logger.debug('try to terminate process id %d - label %s' % (p.pid, p.label))
except OSError as e:
if e.errno == errno.ESRCH:
try:
self.PROCESSES.pop(process_id)
logger.debug('%s: process id %d is terminated' % (self.label, p.pid))
return True
except:
return False
try:
while True:
wpid, status = waitpid(p.pid, WNOHANG)
if not wpid:
break
# self.stdout.write('%d,%d\n' % (wpid, status))
except:
pass
return False
def kill_processes(self, sig=signal.SIGTERM):
"""
"""
process_ids = list(self.PROCESSES.keys())
for process_id in process_ids:
self.kill_process(process_id, sig)
def spawn_process(self, process=None):
"""
spawn a new process
"""
if process is None:
return False
# start new child process
pid = fork()
if pid != 0:
# parent process
process.pid = pid
self.PROCESSES[process.process_id] = process
connections.close_all()
return True
# child process
process.pid = getpid()
# connection.connection.close()
# connection.connection = None
process.pre_init_process()
process.init_process()
process.run()
sys.exit(0)
def status(self):
"""
write the current daemon status to stdout
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
return False
if self.pid != getpid():
# calling from outside the daemon instance
try:
kill(self.pid, signal.SIGUSR2)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
process_list = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
process_list.append(process)
process_list += list(process.backgroundprocess_set.filter())
for process in process_list:
logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pid))
logger.debug('%s, process_id %d' % (process.label, process.pid))
def signal(self, signum=None, frame=None):
"""
handle signals
"""
logger.debug('PID %d, LABEL %s, received signal: %d' % (self.pid, self.label, signum))
if signum not in self.SIG_QUEUE:
self.SIG_QUEUE.append(signum)
class Process(object):
def __init__(self, dt=5, **kwargs):
self.pid = None
self.dt_set = dt
self.process_id = 0
self.parent_process_id = 0
self.label = ''
self.dwt_received = False
self.drt_received = False
# register signals
self.SIG_QUEUE = []
self.SIGNALS = [signal.SIGTERM, signal.SIGUSR1, signal.SIGHUP, signal.SIGUSR2]
self.grouped_ids = {}
scheduler = BackgroundProcess.objects.filter(id=1)
if len(scheduler):
self.scheduler_pid = scheduler.first().pid
else:
logger.warning("No PID found for the scheduler")
self.scheduler_pid = None
#
for key, value in kwargs.items():
setattr(self, key, value)
def pre_init_process(self):
"""
will be executed after process fork
"""
connections.close_all()
# update process info
BackgroundProcess.objects.filter(pk=self.process_id).update(
pid=self.pid,
last_update=now(),
running_since=now(),
done=False,
failed=False,
message='init process..',
)
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS] # reset
[signal.signal(s, self.signal) for s in self.SIGNALS] # set
def init_process(self):
"""
override this.
"""
return True
def run(self):
BackgroundProcess.objects.filter(pk=self.process_id).update(last_update=now(), message='running..')
exec_loop = True
try:
while True:
t_start = time()
# handle signals
sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None
# check the DB connection
check_db_connection()
# update progress
BackgroundProcess.objects.filter(pk=self.process_id).update(last_update=now())
if sig is None and exec_loop:
# run loop action
status, data = self.loop()
if data is not None:
# write data to the database
date_now = now()
for item in data:
for r in item:
r.date_saved = date_now
# todo add date field value
try:
RecordedData.objects.bulk_create(item, batch_size=1000)
except IntegrityError:
logger.debug('RecordedData objects already exists, retry ignoring conflicts')
RecordedData.objects.bulk_create(item, batch_size=1000, ignore_conflicts=True)
if status == 1: # Process OK
pass
elif status == -1:
# some thing went wrong
# todo handle
# raise StopIteration
BackgroundProcess.objects.filter(pk=self.process_id).update(last_update=now(),
failed=True, message='failed')
exec_loop = False
elif status == 0:
# loop is done exit
BackgroundProcess.objects.filter(pk=self.process_id).update(last_update=now(),
done=True, message='done')
#raise StopIteration
exec_loop = False
else:
pass
elif sig is None:
continue
elif sig not in self.SIGNALS:
logger.debug('%s, unhandled signal %d' % (self.label, sig))
continue
elif sig == signal.SIGTERM:
raise StopIteration
elif sig == signal.SIGHUP:
raise StopIteration
elif sig == signal.SIGUSR1:
logger.debug('PID %d, LABEL %s, process SIGUSR1 (%d) signal' % (self.pid, self.label, sig))
if not self.restart():
logger.debug("restart failed")
raise StopIteration
elif sig == signal.SIGUSR2:
# todo handle restart
pass
close_db_connection()
dt = self.dt_set - (time() - t_start)
if dt > 0:
try:
if hasattr(self, "device_ids") and not hasattr(self, "device_id") and len(self.device_ids) > 0:
self.device_id = self.device_ids[0]
if channels_driver and hasattr(self, "device_id") and self.device_id is not None:
message = str(self.scheduler_pid) + '_DeviceAction_for_' + str(self.device_id)
async_to_sync(self.waiting_action_receiver)(dt, message)
elif channels_driver and hasattr(self, "process_id") and self.process_id != 0:
message = str(self.scheduler_pid) + '_ProcessAction_for_' + str(self.process_id)
async_to_sync(self.waiting_action_receiver)(dt, message)
else:
#logger.debug("sleep for %s - %s" % (self.process_id, dt))
raise ConnectionResetError
except ConnectionResetError:
sleep(dt)
except OSError as e:
logger.warning(e)
sleep(dt)
except Exception as e:
logger.warning(e)
except StopIteration:
self.stop()
sys.exit(0)
except OperationalError as e:
logger.debug('%s, DB connection lost' % self.label)
logger.debug(e)
self.stop()
sys.exit(0)
except:
logger.debug('%s, unhandled exception\n%s' % (self.label, traceback.format_exc()))
self.stop()
sys.exit(0)
async def waiting_action_receiver(self, dt, message):
if not hasattr(self, 'channel_layer'):
try:
self.channel_layer = channels.layers.get_channel_layer()
if self.channel_layer is not None:
self.channel_layer.capacity = 1
except (ConnectionRefusedError, InvalidChannelLayerError):
#logger.debug("sleep for %s - %s" % (self.process_id, dt))
sleep(dt)
return None
if self.channel_layer is not None:
try:
a = await wait_for(self.channel_layer.receive(message), timeout=dt)
except asyncioTimeoutError:
pass
except (ConnectionRefusedError, ConnectionClosedError) as e:
logger.debug("Channels or Redis error:" + str(e))
sleep(dt)
else:
if 'DeviceReadTask' in a:
self.drt_received = True
if 'DeviceWriteTask' in a:
self.dwt_received = True
if 'ProcessSignal' in a:
logger.debug("Received ProcessSignal %s on channel_layer for %s" % (a['ProcessSignal'], self.label))
# BUG : need to empty the channel_layer, if not the channel layer keep the message for each run loop
try:
await wait_for(self.channel_layer.receive(message), timeout=0.01)
except asyncioTimeoutError:
pass
else:
#logger.debug("sleep for %s - %s" % (self.process_id, dt))
sleep(dt)
def loop(self):
"""
override this
"""
return 1, None
def cleanup(self):
"""
override this
"""
pass
def signal(self, signum=None, frame=None):
"""
receive signals
"""
logger.debug('PID %d, LABEL %s, received signal: %d' % (self.pid, self.label, signum))
if signum not in self.SIG_QUEUE:
self.SIG_QUEUE.append(signum)
if channels_driver:
if not hasattr(self, 'channel_layer'):
try:
self.channel_layer = channels.layers.get_channel_layer()
if self.channel_layer is not None:
self.channel_layer.capacity = 1
except (ConnectionRefusedError, InvalidChannelLayerError):
return None
if self.channel_layer is not None:
message = None
if hasattr(self, "device_ids") and not hasattr(self, "device_id") and len(self.device_ids) > 0:
self.device_id = self.device_ids[0]
if hasattr(self, "device_id") and self.device_id is not None:
message = str(self.scheduler_pid) + '_DeviceAction_for_' + str(self.device_id)
elif hasattr(self, "process_id") and self.process_id != 0:
message = str(self.scheduler_pid) + '_ProcessAction_for_' + str(self.process_id)
try:
if message is not None:
async_to_sync(self.channel_layer.send)(message, {'ProcessSignal': str(signum)})
except (ChannelFull, ConnectionRefusedError):
logger.info("Channel full : " + str(self.scheduler_pid) + '_ProcessAction_for_' + str(self.process_id))
pass
except (RuntimeWarning, RuntimeError):
pass
def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
try:
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
BackgroundProcess.objects.filter(pk=self.process_id).update(pid=0,
last_update=now(),
message='stopped')
logger.debug('Process %s(%s) is stopped' % (self.label, self.pid))
except OperationalError:
logger.debug('%s, DB connection lost in stop function' % self.label)
try:
self.cleanup()
except TransactionManagementError:
logger.debug('%s, TransactionManagementError in cleanup function' % self.label)
def restart(self):
"""
override this
"""
return None
class SingleDeviceDAQProcessWorker(Process):
processes = []
device_filter = dict(daqdevice__isnull=False)
process_class = 'pyscada.utils.scheduler.SingleDeviceDAQProcess'
bp_label = 'pyscada.device_class-%s'
def __init__(self, dt=5, **kwargs):
super(Process, self).__init__(dt=dt, **kwargs)
def create_bp(self, item):
bp = BackgroundProcess(label=self.bp_label % item.pk,
message='waiting..',
enabled=True,
parent_process_id=self.process_id,
process_class=self.process_class,
process_class_kwargs=json.dumps(
{'device_id': item.pk}))
bp.save()
self.processes.append({'id': bp.id,
'key': item.pk,
'device_id': item.pk,
'failed': 0})
def init_process(self):
self.processes = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False):
try:
kill(process.pid, 0)
except OSError as e:
if e.errno == errno.ESRCH:
process.delete()
continue
logger.debug('process %d is alive' % process.pk)
process.stop(cleanup=True)
# clean up
BackgroundProcess.objects.filter(parent_process__pk=self.process_id).delete()
self.grouped_ids = {}
for item in Device.objects.filter(active=True, **self.device_filter):
self.create_bp(item)
def loop(self):
"""
"""
# Add missing devices
for item in Device.objects.filter(active=True, **self.device_filter):
item_found = False
for process in self.processes:
if process['device_id'] == item.id:
item_found = True
if not item_found:
self.create_bp(item)
# check if all processes are running
for process in self.processes:
try:
if Device.objects.filter(pk=process['device_id']).count() < 1:
self.processes.remove(process)
logger.debug("Device %s not found for process %s. Process removed." % (process['device_id'], process['id']))
continue
if Device.objects.filter(pk=process['device_id'], active=1).count() < 1:
self.processes.remove(process)
logger.debug("Device %s not active. Process removed." % process['device_id'])
continue
if BackgroundProcess.objects.filter(pk=process['id']).count() != 1:
# Process is dead, spawn new instance
if process['failed'] < 3:
bp = BackgroundProcess(label=self.bp_label % process['key'],
message='waiting..',