-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmppmoted.py
executable file
·208 lines (153 loc) · 5.92 KB
/
xmppmoted.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
#!/usr/bin/env python
#Copyright (C) 2012 Niklas Thorne.
#
#This file is part of XMPPMote.
#
#XMPPMote 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.
#
#XMPPMote 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 XMPPMote. If not, see <http://www.gnu.org/licenses/>.
""" XMPPMote - XMPP remote administration framework
XMPPMote provides a basic remote administration facility, by means of the XMPP
protocol. """
from bot.client import Client
from bot.statusprovider import StatusProvider
from ConfigParser import NoOptionError
from ConfigParser import NoSectionError
from configuration.configurationparser import ConfigurationParser
from configuration import credentials
from configuration import updates
from lib.daemon import Daemon
from pyxmpp.all import JID
import codecs
import locale
import logging
import logging.handlers
import sys
import traceback
class XMPPMoteDaemon(Daemon):
""" This type subclasses the Daemon type in order to implement the XMPPMote
daemon. """
def __init__(self):
self.__usr = self.__pwd = None
self.__parse_config_file()
Daemon.__init__(self, self.__get_pidfile())
def start(self):
""" This method overrides Daemon.start in order to read the credentials
when attempting to start a session. """
# we need to read the credentials here, so that we won't attempt access
# stdin and/or stdout after having daemonized..
self.__usr, self.__pwd = credentials.get_credentials()
Daemon.start(self)
def stop(self):
""" This method overrides Daemon.stop in order to disconnect the session
when stopping the daemon. """
client = Client()
client.disconnect()
Daemon.stop(self)
def run(self):
""" This method provides the main function of the daemon, i.e.
connecting the XMPP client, and entering the application message loop.
"""
try:
self.__setup_logging()
client = Client(JID(self.__usr), self.__pwd)
client.connect()
provider = StatusProvider()
provider.start()
update_handler = updates.get_update_handler()
if update_handler:
update_handler.start()
client.loop(1)
except Exception, exc:
logger = logging.getLogger()
logger.critical(u"encountered exception %s. terminating XMPPMote." %
repr(exc))
for line in filter(None, traceback.format_exc().split("\n")):
logger.critical(line)
client.disconnect()
@staticmethod
def __parse_config_file():
""" Helper method that sets up the ConfigurationParser. """
config = ConfigurationParser()
fil = open("xmppmoterc", "a+")
config.parse(fil)
@staticmethod
def __get_pidfile():
""" Helper method that reads an (optionally) configured pidfile from the
configuration file. """
config = ConfigurationParser()
try:
pidfile = config.get("general", "pidfile")
except (NoOptionError, NoSectionError):
pidfile = None
if not pidfile:
pidfile = "/tmp/xmppmote.pid"
return pidfile
@staticmethod
def __setup_logging():
""" Set logging format and log level in order to get nicely written
log statements from both PyXMPP and XMPPMote. """
logging.basicConfig(format = '%(asctime)-15s %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
syslog_handler = logging.handlers.SysLogHandler(
facility = logging.handlers.SysLogHandler.LOG_DAEMON,
address = "/dev/log")
syslog_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)-15s XMPPMote: %(message)s')
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
logging.info(u"redirecting logs to syslog..")
# remove the StreamHandler for syslog-only logging
logger.removeHandler(logger.handlers[0])
def set_encoding():
""" Convert unicode input to current locale. """
locale.setlocale(locale.LC_CTYPE, "")
encoding = locale.getlocale()[1]
if not encoding:
encoding = "us-ascii"
sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors = "replace")
sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors = "replace")
def display_usage(appname):
""" Display the usage screen. """
print u"Usage: %s -h | --help | start | stop | restart" % (appname)
print u"Connect the XMPPMote bot."
def parse_arguments(args):
""" Parse command line arguments. """
if None == args or 0 == len(args):
print u"Error: argv is None or empty"
sys.exit(1)
elif 2 == len(args):
if "-h" == args[1] or "--help" == args[1]:
display_usage(args[0])
sys.exit(0)
elif "start" == args[1]:
daemon = XMPPMoteDaemon()
daemon.start()
elif "stop" == args[1]:
daemon = XMPPMoteDaemon()
daemon.stop()
elif "restart" == args[1]:
daemon = XMPPMoteDaemon()
daemon.restart()
else:
print u"Error: unknown argument"
print
display_usage(args[0])
sys.exit(1)
def main():
""" main functionalities placed here in order to prevent pollution
of the module-level namespace. """
set_encoding()
parse_arguments(sys.argv)
if "__main__" == __name__:
main()