Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWireGate.py
More file actions
Latest commit
363 lines (297 loc) · 12 KB
/
Copy pathWireGate.py
File metadata and controls
363 lines (297 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python
# -*- coding: iso8859-1 -*-
## -----------------------------------------------------
## WireGate.py
## -----------------------------------------------------
## Copyright (c) 2010, knx-user-forum e.V, All rights reserved.
##
## 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 3 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, see <http://www.gnu.de/documents/gpl-3.0.de.html>.
importsys
importos
importtime
importsignal
importtraceback
importdaemon
importlog
importre
importthreading
importConfigParser
importdatastore
importscheduler
classWireGate(daemon.Daemon):
def__init__(self,REDIRECTIO=False):
self._parent=self
self.WG=self
self.watchdoglist= {}
self.connectors= {}
self.LOGGER= {}
self.LoggerCreateLock=threading.RLock()
self.REDIRECTIO=REDIRECTIO
## Get the path of this script
self.scriptpath=re.findall("from \x27(.*)\x2F",str(datastore))[0]
self.readWireGateConfig()
self.ErrorLOGGER=self.__createLog("WireGateErr",filename=self.config['WireGate']['errorlog'],maxlevel='error')
## Start the Datastore
self.DATASTORE=datastore.datastore(self)
## Start the Daemon
daemon.Daemon.__init__(self,self.config['WireGate']['pidfile'],REDIRECTIO)
defreadWireGateConfig(self):
self.config=self.readConfig("/etc/wiregate/pywiregate.conf")
defaultconfig= {
'pidfile' : "%s/wiregated.pid"%self.scriptpath,
'datastore' : "%s/datastore.db"%self.scriptpath,
'logfile' : "%s/wiregated.log"%self.scriptpath,
'errorlog' : "%s/wiregated-error.log"%self.scriptpath,
'loglevel': 'info',
'defaultencoding': 'iso-8859-15'
}
self.checkconfig("WireGate",defaultconfig)
## Remove this later
if"plugins"inself.config['WireGate']:
self.log("old Config",'critical')
defcheckconfig(self,instance,defaults):
ifinstancenotinself.config:
self.config[instance] =defaults
return
forcfgindefaults:
ifcfgnotinself.config[instance]:
self.config[instance][cfg] =defaults[cfg]
defreadConfig(self,configfile):
config= {}
configparse=ConfigParser.SafeConfigParser()
configparse.readfp(open(configfile))
forsectioninconfigparse.sections():
options=configparse.options(section)
config[section] = {}
foroptinoptions:
try:
config[section][opt] =configparse.getint(section,opt)
exceptValueError:
try:
config[section][opt] =configparse.getfloat(section,opt)
exceptValueError:
config[section][opt] =configparse.get(section,opt)
returnconfig
defisdaemon(self):
## Called when in Daemon state
signal.signal(signal.SIGTERM,self._signalhandler)
signal.signal(signal.SIGHUP,self._signalhandler)
def_signalhandler(self,signum,frame):
ifsignum==signal.SIGHUP:
self.debug("LOGROTATE")
elifsignum==signal.SIGTERM:
sys.exit(1)
else:
self.debug("Unknown Signal: %d "%signum)
defrun(self):
forconfigpartinself.config.keys():
if"connector"inself.config[configpart]:
name=configpart
connector=self.config[configpart]['connector']
else:
## no connector in Section
continue
try:
iflen(connector)>0:
## Import Connector
try:
exec("import %s"%connector)
except:
self.WG.errorlog(connector)
self.log("unknown connector: %s"%connector,'error')
continue
## Load the Connector
exec("self.connectors['%s'] = %s.%s(self,name)"% (name,connector,connector))
except:
self.WG.errorlog(connector)
pass
## Start the Sheduler
self.SCHEDULER=scheduler.scheduler(self)
self.SCHEDULER.start()
ifos.getuid() ==0:
importpwd
startuser=pwd.getpwuid(os.getuid())
try:
runasuser=pwd.getpwnam(self.config['WireGate']['user'])
getpath=lambdax: "/".join(x.split("/")[:-1])
##Set Permissions on
forsysfilein [self.config['WireGate']['pidfile'],self.config['WireGate']['logfile'],self.config['WireGate']['datastore']]:
ifnotos.path.exists(sysfile):
open(sysfile,'w').close()
os.chown(sysfile,runasuser[2],runasuser[3])
##removed until fixing permissions
#os.setregid(runasuser[3],runasuser[3])
#os.setreuid(runasuser[2],runasuser[2])
self.log("Change User/Group from %s(%d) to %s(%d) FIXME: disabled"% (startuser[0],startuser[2],runasuser[0],runasuser[2]))
exceptKeyError:
pass
ifos.getuid() ==0:
self.log("### Run as root is not recommend ### set user in pywiregate.conf",'warn')
## Mainloop only checking for Watchdog
whileTrue:
time.sleep(5)
self._checkwatchdog()
## always looping watchdog checker
def_checkwatchdog(self):
forobjinself.watchdoglist.keys():
iftime.time() >self.watchdoglist[obj]:
self.log("\n\nInstanz %s reagiert nicht\n\n"%obj,'error')
try:
self.connectors[obj].shutdown()
except:
pass
delself.watchdoglist[obj]
## set Watchdog
defwatchdog(self,instance,wtime):
self.watchdoglist[instance] =time.time()+wtime
defshutdown(self):
#for dobj in self.DATASTORE.dataobjects.keys():
# print dobj+": "+str(self.DATASTORE.dataobjects[dobj].getValue())
self.log("### Shutdown WireGated ###")
self.SCHEDULER.shutdown()
forinstanceinself.connectors.keys():
try:
self.connectors[instance].shutdown()
except:
pass
## now save Datastore
self.DATASTORE.shutdown()
## Handle Errors
deferrorlog(self,msg=False):
try:
exc_type, exc_value, exc_traceback=sys.exc_info()
tback=traceback.extract_tb(exc_traceback)
except:
exc_value=""
exc_type=""
tback=""
pass
ifmsg:
self.ErrorLOGGER.error(repr(msg))
errmsg="%r %r %r"% (exc_type, exc_value,tback)
self.ErrorLOGGER.error(errmsg)
## TODO: Check COnfig for seperate Logfiles and min level for logging
defcreateLog(self,instance):
ifinstanceinself.config:
loglevel=self.config[instance].get('loglevel',False)
filename=self.config[instance].get('logfile',False)
else:
loglevel=self.config['WireGate'].get('loglevel',False)
filename=self.config['WireGate'].get('logfile',False)
returnself.__createLog(instance,filename=filename,maxlevel=loglevel)
## Create the Loginstance
def__createLog(self,instance,filename=False,maxlevel=False):
ifnotmaxlevel:
maxlevel=self.config['WireGate']['loglevel']
ifnotfilename:
filename=self.config['WireGate']['logfile']
LEVELS= {'debug': log.logging.DEBUG,'info': log.logging.INFO,'notice': log.logging.NOTICE,'warning': log.logging.WARNING,'error': log.logging.ERROR,'critical': log.logging.CRITICAL}
level=LEVELS.get(maxlevel, log.logging.NOTSET)
# create logger
formatter=log.logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s %(message)s')
logger=log.logging.getLogger(instance)
logger.setLevel(level)
iffilename:
## python handle logrotating
handler=log.logging.handlers.TimedRotatingFileHandler(filename,'MIDNIGHT',encoding='UTF-8',backupCount=7)
## Handler if logrotate handles Logfiles
#handler = logging.handlers.WatchedFileHandle(filename)
handler.setFormatter(formatter)
handler.setLevel(level)
logger.addHandler(handler)
# create console handler and set level to debug
ifself.REDIRECTIO:
#console = logging.StreamHandler()
console=log.isoStreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)
returnlogger
## Logger for all instances that check/create logger based on Configfile
deflog(self,msg,severity="info",instance="WireGate"):
try:
self.LoggerCreateLock.acquire()
try:
logger=self.LOGGER[instance]
exceptKeyError:
logger=self.LOGGER[instance] =self.createLog(instance)
pass
finally:
self.LoggerCreateLock.release()
try:
ifseverity=="debug":
logger.debug(msg)
elifseverity=="info":
logger.info(msg)
elifseverity=="notice":
logger.notice(msg)
elifseverity=="warning":
logger.warning(msg)
elifseverity=="warn":
#print "SEVERITY: %r " % logging._levelNames
logger.warning(msg)
elifseverity=="error":
logger.error(msg)
elifseverity=="critical":
logger.critical(msg)
else:
logger.info(msg)
except:
## logging shouldnt break execution
#pass
raise
defdebug(self,msg):
self.log(msg,"debug")
## Decouple from dir to avoid unmount troubles
defdecouple(self):
os.chdir("/")
os.umask(0)
if__name__=="__main__":
try:
importos
importsys
importgetopt
try:
opts, args=getopt.getopt(sys.argv[1:], "", ["start","stop","logrotate","nodaemon","stdout"])
exceptgetopt.GetoptError:
print"Fehler"
sys.exit(2)
ACTION=""
RUNDAEMON=True
REDIRECTIO=True
foropt, arginopts:
ifoptin ("--start"):
ACTION="start"
ifoptin ("--stop"):
ACTION="stop"
ifoptin ("--logrotate"):
ACTION="logrotate"
ifoptin ("--nodaemon"):
RUNDAEMON=False
ifoptin ("--stdout"):
REDIRECTIO=False
WIREGATE=WireGate(REDIRECTIO)
ifACTION=="start":
WIREGATE.start(RUNDAEMON)
elifACTION=="stop":
WIREGATE.stop()
elifACTION=="logrotate":
WIREGATE.logrotate()
else:
print"--start oder --stop"
sys.exit(1)
ifnotRUNDAEMON:
whileTrue:
pass
exceptKeyboardInterrupt:
pass
print"Exiting"
sys.exit(0)