This repository has been archived by the owner on Feb 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
publish_subscribe.py
159 lines (126 loc) · 4.91 KB
/
publish_subscribe.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
import os
import sys
import sleekxmpp.componentxmpp
import logging
import logging.handlers
import sleekpubsub
#import sleekpubsub.jobnode
try:
import configparser
except ImportError:
import ConfigParser as configparser
from optparse import OptionParser
logging.addLevelName(5, "VERBOSE")
#import sleekxmpp.xmlstream.xmlstream
#sleekxmpp.xmlstream.xmlstream.HANDLER_THREADS = 5
#Default daemon parameters
#File mode creation mask of the daemon
UMASK = 0
# Default working directory for the daemon
WORKDIR = sys.path[0]
# Default maximum for the number of available file descriptors.
MAXFD = 1024
# The standard I/O file descriptors are redirected to /dev/null by default.
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
def createDaemon():
"""Detach this process from the controlling terminal and run it in the background as a daemon."""
try:
pid = os.fork()
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if pid == 0: #The first child
os.setsid() #Become session leader of this new session. Also be guaranteed not to have a controlling terminal
try:
pid = os.fork() #Fork a second child
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if pid == 0: #The second child
os.chdir(WORKDIR) #TODO define WORKDIR in ini
os.umask(UMASK) #TODO define UMASK in ini
else:
os._exit(0) #Exit parent (the first child) of the second child.
else:
os._exit(0) #Exit parent of the first child.
import resource # Resource usage information.
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
# Iterate through and close all file descriptors.
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
os.open(REDIRECT_TO, os.O_RDWR) # standard input (0)
# Duplicate standard input to standard output and standard error.
os.dup2(0, 1) # standard output (1)
os.dup2(0, 2) # standard error (2)
return(0)
if __name__ == '__main__':
#parse command line arguements
optp = OptionParser()
optp.add_option('--daemon', action="store_true", dest='daemonize', help="run as daemon")
optp.add_option('-q','--quiet', help='set logging to ERROR', action='store_const', dest='loglevel', const=logging.ERROR, default=None)
optp.add_option('-d','--debug', help='set logging to DEBUG', action='store_const', dest='loglevel', const=logging.DEBUG, default=None)
optp.add_option('-v','--verbose', help='set logging to COMM', action='store_const', dest='loglevel', const=5, default=None)
optp.add_option("-c","--config", dest="configfile", default="config.ini", help="set config file to use")
opts,args = optp.parse_args()
retCode = 0
if opts.daemonize:
retCode = createDaemon()
config = configparser.RawConfigParser()
config.read(opts.configfile)
loglevel = opts.loglevel or getattr(logging, config.get('settings', 'loglevel'))
#print loglevel
logfile = config.get('settings', 'logfile')
if opts.daemonize:
rootlogger = logging.getLogger('')
rootlogger.setLevel(loglevel)
formatter = logging.Formatter('%(levelname)-8s %(message)s')
handler = logging.handlers.RotatingFileHandler(logfile)
handler.setFormatter(formatter)
rootlogger.addHandler(handler)
logging.info("Daemonized")
else:
logging.basicConfig(level=loglevel, format='%(levelname)-8s %(message)s')
logging.info("Not daemonized")
f = open(config.get('pubsub', 'pid'), 'w')
f.write("%s" % os.getpid())
f.close()
xmpp = sleekxmpp.componentxmpp.ComponentXMPP(config.get('pubsub', 'host'), config.get('pubsub', 'secret'), config.get('pubsub', 'server'), config.getint('pubsub', 'port'))
xmpp.registerPlugin('xep_0004')
xmpp.registerPlugin('xep_0030')
xmpp.registerPlugin('xep_0045')
xmpp.registerPlugin('xep_0050')
xmpp.registerPlugin('xep_0060')
#load config
settings = {
'node_creation': config.get('settings', 'node_creation'),
#'addtorosteraddtonode': config.getboolean('settings', 'addtorosteraddtonode'),
'eventsfromsubscribedjid': config.getboolean('settings', 'eventsfromsubscribedjid'),
'eachjiduserisnode': config.getboolean('settings', 'eachjiduserisnode'),
}
rest = {
'enabled': config.getboolean('rest', 'enabled'),
'server': config.get('rest', 'server'),
'port': config.getint('rest', 'port'),
'user': config.get('rest', 'user'),
'passwd': config.get('rest', 'passwd'),
'userasjid':config.get('rest', 'userasjid'),
}
overridedefault = {}
for option in config.options('defaultnodeconfig'):
overridedefault[option] = config.get('defaultnodeconfig', option)
pubsub = sleekpubsub.PublishSubscribe(xmpp, config.get('pubsub', 'dbfile'), settings, rest, overridedefault)
#pubsub.registerNodeType(sleekpubsub.jobnode)
if xmpp.connect():
xmpp.process(threaded=False)
xmpp.disconnect()
logging.info("Saving...")
pubsub.save()
sys.exit(retCode)
else:
logging.log(logging.CRITICAL, "Unable to connect.")