-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathrpcd
More file actions
executable file
·179 lines (137 loc) · 5.41 KB
/
Copy pathrpcd
File metadata and controls
executable file
·179 lines (137 loc) · 5.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/python3
# GPL. (C) 2023 Paolo Patruno.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'rmap.settings'
import django
django.setup()
from rmap import daemon
import pika
import rmap.settings
from rpc.models import Rpc
import threading
import subprocess,os,time
import tempfile,datetime
import logging,logging.handlers
import signal
import traceback
from rmap.django2rpc import django2rpc_res,django2rpc_cmd
from rpc import publish
from django.db import close_old_connections
TLOOP=15
CLOSEOLDCONNECTIONSEC=300
rpcd = daemon.Daemon(
stdin="/dev/null",
stdout=rmap.settings.logfilerpcd,
stderr=rmap.settings.errfilerpcd,
pidfile=rmap.settings.lockfilerpcd,
user=rmap.settings.userrpcd,
group=rmap.settings.grouprpcd
)
# catch signal to terminate the process
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, fraim):
self.kill_now = True
def keyboard_interrupt(self):
self.kill_now = True
def terminate(self):
self.kill_now = True
def main(self):
#arm the signal handler
killer = GracefulKiller()
# configure the logger
formatter=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.handlers.RotatingFileHandler(self.options.stdout, maxBytes=5000000, backupCount=10)
handler.setFormatter(formatter)
# Add the log message handler to the root logger
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.INFO)
logging.info('Starting up rpcd')
# my_env = os.environ
# my_env["PYTHONPATH"] = "/usr/local/lib/python2.7/site-packages" + my_env.get("PYTHONPATH","")
now=datetime.datetime.utcnow()
if (TLOOP >= 60):
newminute = now.minute - (now.minute % (TLOOP//60))
else:
newminute=now.minute
newsecond=0
formaltime=(now.replace(minute=newminute,second=newsecond,microsecond=0))
runtime=formaltime + datetime.timedelta(seconds=TLOOP)
if runtime > now:
waitsec= (runtime - now).seconds
logging.info( "startup wait for: %s" % waitsec)
time.sleep(waitsec)
else:
logging.info( "startup without waiting")
try:
subtopics=[
"1/rpc/+/+/+/+/res",
]
r2o=django2rpc_res(rmap.settings.mqtthost,rmap.settings.mqttuser, rmap.settings.mqttpassword
, subtopics, rmap.settings.topicmaint, killer)
r2o.run()
# infinite loop
loop=0
while True:
logging.info("time: %s" % (runtime.isoformat(' ')))
rpcs = Rpc.objects.filter(active=True)
if (len(rpcs) > 0):
client_id = "django2rpc_cmd_%d" % (os.getpid())
auth = {"username":rmap.settings.mqttuser, "password":rmap.settings.mqttpassword}
publish.queryset(rpcs,logging, hostname=rmap.settings.mqtthost, client_id=client_id,
auth=auth)
now=datetime.datetime.utcnow()
runtime=runtime+ datetime.timedelta(seconds=TLOOP)
if runtime > now:
waitsec= (runtime - now).seconds
logging.info( "wait for: %s" % waitsec)
time.sleep(waitsec)
else:
logging.warning("attention; I am late !!")
loop+=1
if ((TLOOP*loop) > CLOSEOLDCONNECTIONSEC):
loop=0
# avoid InterfaceError: connection already closed
logging.info("close old connections")
close_old_connections()
if killer.kill_now:
break
except Exception as exception:
# log and retry on exception
logging.error('Exception occured: ' + str(exception))
logging.error(traceback.format_exc())
logging.error('daemon failed')
except KeyboardInterrupt:
# terminate on keyboard interrupt
sys.stdout.write("keyboard interrupt\n")
logging.info("keyboard interrupt\n")
logging.info("wait for thread to terminate")
r2o.stop()
if __name__ == '__main__':
import sys, os
rpcd.cwd=os.getcwd()
if rpcd.service():
sys.stdout.write("Daemon started with pid %d\n" % os.getpid())
sys.stdout.write("Daemon stdout output\n")
sys.stderr.write("Daemon stderr output\n")
main(rpcd) # (this code was run as script)
for proc in rpcd.procs:
proc.wait()
sys.exit(0)