This repository has been archived by the owner on Apr 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathldrm.py
executable file
·643 lines (573 loc) · 28.6 KB
/
ldrm.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
#!venv/bin/python
# -*- coding: utf-8 -*-
import ConfigParser
from collections import deque
import datetime
import hashlib
import json
import logging
import os.path
from signal import SIGTERM
import socket
import sys
import threading
import time
import daemon.pidfile
import memcache
import mysql.connector
import psycopg2
import ssh2
from ssh2.session import Session
#
# pylibmc
class conSQL:
def __init__(self):
self.basePath = basePath
self.loadConf()
def loadConf(self):
config = ConfigParser.ConfigParser()
config.readfp(open(self.basePath + '/conf/ldrm.conf'))
self.type = config.get('db', 'type')
self.ip = config.get('db', 'ip')
self.port = int(config.get('db', 'port'))
self.dbname = config.get('db', 'dbname')
self.login = config.get('db', 'login')
self.passwd = config.get('db', 'passwd')
def getDataFromDB(self, mac):
if self.type == 'mysql':
results = self.selectMySQL("""SELECT n.id as id, inet_ntoa(n.ipaddr) as ip, n.name as nodename, access, warning
FROM nodes as n, macs as m
WHERE upper(m.mac) = '%s'
AND n.id = m.nodeid
ORDER by n.id""" % (mac))
if results is False:
return False
dataMac = None
if len(results) > 0:
dataMac = {"id":results[0][0], "ip":results[0][1], "nodename":results[0][2], "access":results[0][3], "warning":results[0][4]}
results = self.selectMySQL("""SELECT CONCAT(ROUND(COALESCE(x.upceil, y.upceil, z.upceil)),'k','/', ROUND(COALESCE(x.downceil, y.downceil, z.downceil)),'k') AS mrt
FROM (
SELECT n.id, MIN(n.name) AS name, SUM(t.downceil/o.cnt) AS downceil, SUM(t.upceil/o.cnt) AS upceil
FROM nodeassignments na
JOIN assignments a ON (na.assignmentid = a.id)
JOIN tariffs t ON (a.tariffid = t.id)
JOIN nodes n ON (na.nodeid = n.id)
JOIN macs m ON (m.nodeid = n.id)
JOIN (
SELECT assignmentid, COUNT(*) AS cnt
FROM nodeassignments
GROUP BY assignmentid
) o ON (o.assignmentid = na.assignmentid)
WHERE (a.datefrom <= unix_timestamp() OR a.datefrom = 0)
AND (a.dateto > unix_timestamp() OR a.dateto = 0)
AND upper(m.mac) = '%s'
GROUP BY n.id
) x
LEFT JOIN (
SELECT SUM(t.downceil)/o.cnt AS downceil,
SUM(t.upceil)/o.cnt AS upceil
FROM assignments a
JOIN tariffs t ON (a.tariffid = t.id)
JOIN nodes n ON (a.customerid = n.ownerid)
JOIN macs m ON (m.nodeid = n.id)
JOIN (
SELECT COUNT(*) AS cnt, ownerid FROM vnodes
WHERE NOT EXISTS (
SELECT 1 FROM nodeassignments, assignments a
WHERE assignmentid = a.id AND nodeid = vnodes.id
AND (a.dateto > unix_timestamp() OR a.dateto = 0))
GROUP BY ownerid
) o ON (o.ownerid = n.ownerid)
WHERE (a.datefrom <= unix_timestamp() OR a.datefrom = 0)
AND (a.dateto > unix_timestamp() OR a.dateto = 0)
AND NOT EXISTS (SELECT 1 FROM nodeassignments WHERE assignmentid = a.id)
AND upper(m.mac) = '%s'
GROUP BY n.id
) y ON (1=1)
RIGHT JOIN (
SELECT n.id, n.name, 64 AS downceil, 64 AS upceil
FROM nodes as n,macs as m
WHERE upper(m.mac) = '%s'
AND m.nodeid = n.id
) z ON (1=1)""" % (mac, mac, mac))
if results is False:
return False
if len(results) > 0:
dataMac.update({"mrt":results[0][0]})
else:
logging.warn("conSQL: can't find tariff for %s" % (mac))
else:
logging.warn("conSQL: wrong mac address: %s, don't exist in DB" % (mac))
return dataMac
elif self.type == 'pgsql':
results = self.selectPG("""SELECT n.id as id, inet_ntoa(n.ipaddr) as ip, n.name as nodename, access, warning
FROM nodes as n, macs as m
WHERE upper(m.mac) = '%s'
AND n.id = m.nodeid
ORDER by n.id""" % (mac))
if results is False:
return False
dataMac = None
if len(results) > 0:
dataMac = {"id":results[0][0], "ip":results[0][1], "nodename":results[0][2], "access":results[0][3], "warning":results[0][4]}
results = self.selectPG("""SELECT CONCAT(ROUND(COALESCE(x.upceil, y.upceil, z.upceil)),'k','/', ROUND(COALESCE(x.downceil, y.downceil, z.downceil)),'k') AS mrt
FROM (
SELECT n.id, MIN(n.name) AS name, SUM(t.downceil/o.cnt) AS downceil, SUM(t.upceil/o.cnt) AS upceil
FROM nodeassignments na
JOIN assignments a ON (na.assignmentid = a.id)
JOIN tariffs t ON (a.tariffid = t.id)
JOIN nodes n ON (na.nodeid = n.id)
JOIN macs m ON (m.nodeid = n.id)
JOIN (
SELECT assignmentid, COUNT(*) AS cnt
FROM nodeassignments
GROUP BY assignmentid
) o ON (o.assignmentid = na.assignmentid)
WHERE (a.datefrom <= extract(epoch from now()) OR a.datefrom = 0)
AND (a.dateto > extract(epoch from now()) OR a.dateto = 0)
AND upper(m.mac) = '%s'
GROUP BY n.id
) x
LEFT JOIN (
SELECT SUM(t.downceil)/o.cnt AS downceil,
SUM(t.upceil)/o.cnt AS upceil
FROM assignments a
JOIN tariffs t ON (a.tariffid = t.id)
JOIN nodes n ON (a.customerid = n.ownerid)
JOIN macs m ON (m.nodeid = n.id)
JOIN (
SELECT COUNT(*) AS cnt, ownerid FROM vnodes
WHERE NOT EXISTS (
SELECT 1 FROM nodeassignments, assignments a
WHERE assignmentid = a.id AND nodeid = vnodes.id
AND (a.dateto > extract(epoch from now()) OR a.dateto = 0))
GROUP BY ownerid
) o ON (o.ownerid = n.ownerid)
WHERE (a.datefrom <= extract(epoch from now()) OR a.datefrom = 0)
AND (a.dateto > extract(epoch from now()) OR a.dateto = 0)
AND NOT EXISTS (SELECT 1 FROM nodeassignments WHERE assignmentid = a.id)
AND upper(m.mac) = '%s'
GROUP BY n.id, o.cnt
) y ON (1=1)
RIGHT JOIN (
SELECT n.id, n.name, 64 AS downceil, 64 AS upceil
FROM nodes as n,macs as m
WHERE upper(m.mac) = '%s'
AND m.nodeid = n.id
) z ON (1=1)""" % (mac, mac, mac))
if results is False:
return False
if len(results) > 0:
dataMac.update({"mrt":results[0][0]})
else:
logging.warn("conSQL: can't find tariff for %s" % (mac))
else:
logging.warn("conSQL: wrong mac address: %s, don't exist in DB" % (mac))
return dataMac
else:
logging.error("conSQL: wrong type of db: %s, supported only mysql or pgslq" % (self.type))
def selectMySQL(self, query):
try:
cnx = mysql.connector.connect(host=self.ip, database=self.dbname, user=self.login, password=self.passwd)
except Exception as e:
logging.error('conSQL: ' + str(e))
return False
else:
cursor = cnx.cursor()
try:
cursor.execute(query)
except Exception as e:
logging.error('conSQL: ' + str(e))
return False
else:
results = cursor.fetchall()
return results
finally:
cnx.close()
def selectPG(self, query):
try:
con = psycopg2.connect(host=self.ip, dbname=self.dbname, user=self.login, password=self.passwd)
except Exception as e:
logging.error('conSQL: ' + str(e))
return False
else:
cur = con.cursor()
try:
cur.execute(query)
except Exception as e:
logging.error('conSQL: ' + str(e))
return False
else:
results = cur.fetchall()
return results
finally:
con.close()
class queueDrd:
queueDrd = deque([])
dataClient = {}
size = 1000
lock = threading.Lock()
def fetch(self):
if len(self.queueDrd) > 0:
self.lock.acquire()
try:
machash = self.queueDrd.popleft()
data = self.dataClient.pop(machash)
finally:
self.lock.release()
return [machash, data]
else:
return None
def add(self, machash, data):
if len(self.queueDrd) < self.size:
self.lock.acquire()
try:
if machash not in self.queueDrd:
self.queueDrd.append(machash)
self.dataClient.update({machash:data})
finally:
self.lock.release()
class deamonMT(threading.Thread):
def __init__(self, QH):
threading.Thread.__init__(self)
self.setDaemon(True)
self.basePath = basePath
self.loadConf()
self.cache = memcache.Client([self.ip + ':' + self.port], debug=0)
self.QH = QH
self.SQL = conSQL()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def run(self):
logging.info("deamonMT: ready and waiting..")
ql=0
while True:
if ql > 0:
data = self.QH.fetch()
if data is not None:
if self.api == 'ssh':
MTCommands=self.createMTCommands(data)
if MTCommands is not False:
logging.info("deamonMT: sending commands to execute on Mikrotik :\n" + str(MTCommands))
self.executeMT(MTCommands[1],MTCommands[0])
else:
logging.error('deamonMT: incorrect api: %s' % (self.api))
ql = len(self.QH.queueDrd)
logging.info("deamonMT: size of queue: %s" % (ql))
if ql == 0:
time.sleep(60)
elif ql == 1:
time.sleep(30)
elif ql < 10:
time.sleep(15)
elif ql > 0 and ql < 50:
time.sleep(5)
elif ql > 0 and ql < 100:
time.sleep(1)
elif ql > 0 and ql < 300:
time.sleep(0.5)
else:
time.sleep(0.1)
def createMTCommands(self, data):
if self.is_valid_ipv4_address(data[1]['Framed_IP_Address']):
self.macData = self.cache.get(hashlib.sha1(data[0] + data[1]['Framed_IP_Address']).hexdigest())
if self.macData is None:
logging.info('deamonMT: miss cache for mac: %s ip: %s, extracting data from DB' % (data[1]['User_Name'], data[1]['Framed_IP_Address']))
while True:
dataSQL = self.SQL.getDataFromDB(data[1]['User_Name'])
if dataSQL is False:
time.sleep(5)
else:
if dataSQL is not None:
data[1].update({"nodeId":dataSQL["id"]})
data[1].update({"access":dataSQL["access"]})
data[1].update({"warning":dataSQL["warning"]})
data[1].update({"nodename":dataSQL["nodename"]})
data[1].update({"mrt":dataSQL["mrt"]})
self.cache.set(hashlib.sha1(data[0] + data[1]['Framed_IP_Address']).hexdigest(), data[1], self.time)
self.macData = data[1]
else:
# cant find mac in db, send info?
data[1].update({"nodeId":None})
self.cache.set(hashlib.sha1(data[0] + data[1]['Framed_IP_Address']).hexdigest(), data[1], self.time)
self.macData = data[1]
break
else:
logging.info('deamonMT: hit cache for mac: %s ip: %s, extracting data from memcached' % (data[1]['User_Name'], data[1]['Framed_IP_Address']))
execOnMT = None
logging.debug(self.macData)
if self.macData['nodeId'] is not None and self.macData['nodename'] is not None and self.macData['mrt'] is not None and self.is_valid_ipv4_address(self.macData['Framed_IP_Address']) and self.is_valid_ipv4_address(self.macData['NAS_IP_Address']):
datenow = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')
execOnMT = '/queue simple remove [find target=' + str(self.macData['Framed_IP_Address']) + '/32]; '
execOnMT += '/queue simple remove [find name=%s]; ' % (str(self.macData['nodename']))
execOnMT += '/ip firewall nat remove [find src-address="' + str(self.macData['Framed_IP_Address']) + '" and chain="'+self.warnchainName+'"]; '
execOnMT += '/ip firewall address-list remove [find address="' + str(self.macData['Framed_IP_Address']) + '" and list="'+self.blockListName+'"]; '
if str(self.macData['mrt']) =='0k/0k':
execOnMT += """/queue simple add name=""" + str(self.macData['nodename']) + """ target=""" + str(self.macData['Framed_IP_Address']) + """/32 parent=none packet-marks="" priority=8/8 queue=s100/s100 limit-at=64k/64k max-limit=64k/64k burst-limit=0/0 burst-threshold=0/0 burst-time=0s/0s comment=""" + str(datenow) + """; """
else:
execOnMT += """/queue simple add name=""" + str(self.macData['nodename']) + """ target=""" + str(self.macData['Framed_IP_Address']) + """/32 parent=none packet-marks="" priority=8/8 queue=s100/s100 limit-at=64k/64k max-limit=""" + str(self.macData['mrt']) + """ burst-limit=0/0 burst-threshold=0/0 burst-time=0s/0s comment=""" + str(datenow) + """; """
if self.macData['access'] == 0:
execOnMT += """/ip firewall address-list add list="""+self.blockListName+""" address=""" + str(self.macData['Framed_IP_Address']) + """ comment=""" + str(self.macData['nodeId']) + """; """
if self.macData['warning'] == 1:
execOnMT += """/ip firewall nat add chain="""+self.warnchainName+""" action=dst-nat to-addresses=""" + self.lmswarn + """ to-ports=8001 protocol=tcp src-address=""" + str(self.macData['Framed_IP_Address']) + """ limit=10/1h,1:packet log=no log-prefix="" comment=""" + str(datenow) + """; """
if self.macData['access'] == 1:
if self.macData['warning'] == 1:
execOnMT += """/ip firewall nat add chain="""+self.warnchainName+""" action=dst-nat to-addresses=""" + self.lmswarn + """ to-ports=8001 protocol=tcp src-address=""" + str(self.macData['Framed_IP_Address']) + """ limit=10/1h,1:packet log=no log-prefix="" comment=""" + str(datenow) + """; """
logging.debug("deamonMT: Mikrotik commands for ip %s:\n %s" % (self.macData['NAS_IP_Address'], execOnMT))
return (self.macData['NAS_IP_Address'], execOnMT)
else:
logging.info('deamonMT: incorrect data: nodeId, access, warning, nodename, mtr, NAS_IP_Address or Framed_IP_Address')
return False
else:
logging.info('deamonMT: incorrect Framed_IP_Address or null')
return False
def is_valid_ipv4_address(self, address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError:
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error:
return False
return True
def loadConf(self):
config = ConfigParser.ConfigParser()
config.readfp(open(self.basePath + '/conf/ldrm.conf'))
self.ip = config.get('memcached', 'ip')
self.port = config.get('memcached', 'port')
self.time = int(config.get('memcached', 'time'))
self.lmswarn = config.get('lms', 'warnserver')
self.api = config.get('mt', 'api')
self.loginSsh = config.get('mt', 'login')
self.passwdSsh = config.get('mt', 'pass')
self.portSsh = int(config.get('mt', 'port'))
self.timeoutSsh = int(config.get('mt', 'timeout'))
self.warnchainName = config.get('mt', 'warnchainName')
self.blockListName = config.get('mt', 'blockListName')
def executeMT(self, execOnMT, ipToCon):
host = ipToCon
user = self.loginSsh
passwd = self.passwdSsh
port = int(self.portSsh)
timeout = self.timeoutSsh
i = 0
while (True):
if i < 3:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((host, port))
session = Session()
session.handshake(sock)
session.userauth_password(user, passwd)
channel = session.open_session()
channel.execute(execOnMT)
channel.wait_eof()
channel.close()
channel.wait_closed()
except Exception as e:
logging.warn('deamonMT: %s', (e))
else:
logging.info('deamonMT: ssh commands has been sent, SUCCESS')
break
finally:
sock.close()
time.sleep(1)
i += 1
else:
logging.info("deamonMT: ssh can't connect to host: %s", (host))
break
class servertcp(threading.Thread):
def __init__(self, QH):
threading.Thread.__init__(self)
self.setDaemon(True)
self.basePath = basePath
self.loadConf()
self.QH = QH
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.host, int(self.port)))
s.listen(5)
logging.info("servertcp(on port %s): ready and waiting.." % (self.port))
while True:
client, ipPort = s.accept()
client.settimeout(int(self.connectionTimeout))
if ipPort[0] == '127.0.0.1':
try:
data = json.loads(client.recv(1024))
if data[0] == 'DATA':
self.QH.add(hashlib.sha1(data[1]).hexdigest(), data[2])
client.send(json.dumps(['OK']))
logging.info("servertcp: new data, mac: %s from %s" % (data[2]['User_Name'], ipPort[0]))
else:
client.send(json.dumps(['BADCOMMAND']))
client.close
except ValueError as e:
logging.warn('servertcp: recived data is not json, %s' % (e))
client.close
except socket.timeout as e:
logging.warn('servertcp: connection Timeout, %s' % (e))
client.close
else:
logging.warn("servertcp: dont't accept conections form %s, only localhost is accepted" % (ipPort[0]))
client.close
def loadConf(self):
config = ConfigParser.ConfigParser()
config.readfp(open(self.basePath + '/conf/ldrm.conf'))
self.host = config.get('tcpserver', 'host')
self.port = config.get('tcpserver', 'port')
self.connectionTimeout = config.get('tcpserver', 'connectionTimeout')
class ldrm:
def __init__(self, basePath):
self.basePath = basePath
self.loadConf()
def run(self):
if 'debug' == sys.argv[1]:
if self.log == 'debug':
logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
elif self.log == 'info':
logging.basicConfig(level=logging.INFO, format='%(relativeCreated)6d %(threadName)s %(message)s')
elif self.log == 'warn':
logging.basicConfig(level=logging.WARN, format='%(relativeCreated)6d %(threadName)s %(message)s')
elif self.log == 'error':
logging.basicConfig(level=logging.ERROR, format='%(relativeCreated)6d %(threadName)s %(message)s')
elif self.log == 'critical':
logging.basicConfig(level=logging.CRITICAL, format='%(relativeCreated)6d %(threadName)s %(message)s')
else:
logging.basicConfig(level=logging.INFO, format='%(relativeCreated)6d %(threadName)s %(message)s')
else:
if self.log == 'debug':
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
elif self.log == 'info':
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
elif self.log == 'warn':
logging.basicConfig(level=logging.WARN,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
elif self.log == 'error':
logging.basicConfig(level=logging.ERROR,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
elif self.log == 'critical':
logging.basicConfig(level=logging.CRITICAL,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
else:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s',
datefmt='%d-%m-%d %H:%M',
filename=self.logFile,
filemode='w')
logging.info("ldrm: start main thread")
QH = queueDrd()
ST = servertcp(QH)
ST.start()
DMT = deamonMT(QH)
DMT.start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
if 'debug' == sys.argv[1]:
break
if ST.is_alive() is False:
logging.error("ldrm: threads servertcp is down, starting new")
ST = servertcp(QH)
ST.start()
if DMT.is_alive() is False:
logging.error("ldrm: threads deamonMT is down, starting new")
DMT = deamonMT(QH)
DMT.start()
logging.info("ldrm: stop main thread")
def loadConf(self):
config = ConfigParser.ConfigParser()
config.readfp(open(self.basePath + '/conf/ldrm.conf'))
self.log = config.get('main', 'log')
self.logFile = config.get('main', 'logFile')
def start(self):
"""
Start the daemon
"""
if os.path.isfile(self.basePath + '/conf/ldrm.conf') is False:
print 'ldrm: Where is conf, should be in main directory\nfile: ldrm.conf'
sys.exit(1)
pidfile = '/tmp/ldrm.pid'
try:
pf = file(pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "ldrm: pidfile %s already exist. Daemon already running?"
sys.stderr.write(message % pidfile)
sys.exit(1)
working_directory = self.basePath
pidfile = daemon.pidfile.PIDLockFile(pidfile)
with daemon.DaemonContext(working_directory=working_directory, pidfile=pidfile):
self.run()
def stop(self):
"""
Stop the daemon
"""
pidfile = '/tmp/ldrm.pid'
try:
pf = file(pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?"
sys.stderr.write(message % pidfile)
return
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(pidfile):
os.remove(pidfile)
else:
print str(err)
sys.exit(1)
if __name__ == "__main__":
basePath = os.path.dirname(os.path.abspath(__file__))
if len(sys.argv) == 2:
if 'debug' == sys.argv[1]:
ldrm(basePath).run()
elif 'start' == sys.argv[1]:
ldrm(basePath).start()
elif 'stop' == sys.argv[1]:
ldrm(basePath).stop()
elif 'restart' == sys.argv[1]:
ldrm(basePath).stop()
ldrm(basePath).start()
elif 'help' == sys.argv[1]:
print "usage: %s \n\trestart \t\t-> restart deamon \n\tstart \t\t-> start deamon \n\tstop \t\t-> stop deamon \n\tdebug \t-> non-daemon mode \n\thelp \t-> show this" % sys.argv[0]
sys.exit(2)
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s \n\tstart \t-> start deamon \n\tstop \t-> stop deamon \n\tdebug \t-> non-daemon mode \n\thelp \t-> show this" % sys.argv[0]
sys.exit(2)