/usr/share/pyshared/jsb/lib/fleet.py is in jsonbot 0.84.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # jsb/lib/fleet.py
#
#
""" fleet is a list of bots. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.generic import waitforqueue
from jsb.utils.trace import whichmodule
from config import Config, getmainconfig
from datadir import getdatadir
from users import users
from plugins import plugs
from persist import Persist
from errors import NoSuchBotType, BotNotEnabled
from threads import start_new_thread
from eventhandler import mainhandler
from jsb.utils.name import stripname
from jsb.lib.factory import BotFactory
from jsb.utils.lazydict import LazyDict## simplejson imports
from jsb.imports import getjson
json = getjson()
## basic imports
import Queue
import os
import types
import time
import glob
import logging
import threading
import thread
import copy
## defines
cpy = copy.deepcopy
## classes
class FleetBotAlreadyExists(Exception):
pass
## locks
from jsb.utils.locking import lockdec
lock = thread.allocate_lock()
locked = lockdec(lock)
## Fleet class
class Fleet(Persist):
"""
a fleet contains multiple bots (list of bots).
"""
def __init__(self, datadir):
Persist.__init__(self, datadir + os.sep + 'fleet' + os.sep + 'fleet.main')
if not self.data.has_key('names'): self.data['names'] = []
if not self.data.has_key('types'): self.data['types'] = {}
self.startok = threading.Event()
self.bots = []
def addnametype(self, name, type):
if name not in self.data['names']:
self.data['names'].append(name)
self.data['types'][name] = type
self.save()
return True
def getenabled(self, exclude=[]):
res = []
for name in self.data.names:
cfg = Config("fleet" + os.sep + name + os.sep + "config")
if cfg.type in exclude: continue
if not cfg.disable: res.append(name)
return res
def loadall(self, names=[]):
""" load all bots. """
target = names or self.data.names or []
threads = []
bots = []
for name in target:
if not name: logging.warn("name is not set") ; continue
try:
bot = self.makebot(self.data.types[name], name)
except KeyError: continue
except BotNotEnabled: logging.info("%s is not enabled" % name) ; continue
except KeyError: logging.error("no type know for %s bot" % name)
except Exception, ex: handle_exception()
if bot and bot not in bots: bots.append(bot)
return bots
def avail(self):
""" return available bots. """
return self.data['names']
def getfirstbot(self, type="irc"):
""" return the first bot in the fleet. """
for bot in self.bots:
if type in bot.type: return bot
def getfirstjabber(self, isgae=False):
""" return the first jabber bot of the fleet. """
return self.getfirstbot("xmpp")
def size(self):
""" return number of bots in fleet. """
return len(self.bots)
def settype(self, name, type):
""" set the type of a bot. """
cfg = Config('fleet' + os.sep + stripname(name) + os.sep + 'config')
cfg['name'] = name
logging.debug("%s - setting type to %s" % (self.cfile, type))
cfg.type = type
cfg.save()
def makebot(self, type, name, config={}, domain="", showerror=False):
""" create a bot .. use configuration if provided. """
if not name: logging.error(" name is not correct: %s" % name) ; return
if not type: type = self.data.types.get(name)
if not type: logging.error("no type found for %s bot" % name) ; return
if config: logging.debug('making %s (%s) bot - %s - from: %s' % (type, name, config.tojson(), whichmodule()))
bot = None
if not config: cfg = Config('fleet' + os.sep + stripname(name) + os.sep + 'config')
else: cfg = config
cfg.init()
if not cfg.name: cfg['name'] = name
cfg['botname'] = cfg['name']
if cfg.disable:
logging.info("%s bot is disabled. see %s" % (name, cfg.cfile))
raise BotNotEnabled(name)
if not cfg.type and type:
logging.debug("%s - setting type to %s" % (cfg.cfile, type))
cfg.type = type
if not cfg['type']:
try:
self.data['names'].remove(name)
self.save()
except ValueError: pass
raise Exception("no bot type specified")
if not cfg.owner:
logging.debug("%s - owner not set .. using global config." % cfg.name)
cfg.owner = getmainconfig().owner
if not cfg.domain and domain: cfg.domain = domain
if not cfg: raise Exception("can't make config for %s" % name)
#cfg.save()
bot = BotFactory().create(type, cfg)
return bot
def save(self):
""" save fleet data and call save on all the bots. """
Persist.save(self)
for i in self.bots:
try: i.save()
except Exception, ex: handle_exception()
def list(self):
""" return list of bot names. """
result = []
for i in self.bots: result.append(i.cfg.name)
return result
def stopall(self):
""" call stop() on all fleet bots. """
for i in self.bots:
try: i.stop()
except: handle_exception()
def byname(self, name):
""" return bot by name. """
for i in self.bots:
if name == i.cfg.name: return i
def replace(self, name, bot):
""" replace bot with a new bot. """
for i in range(len(self.bots)):
if name == self.bots[i].cfg.name:
self.bots[i] = bot
return True
def enable(self, cfg):
""" enable a bot baed of provided config. """
if cfg.name and cfg.name not in self.data['names']:
self.data['names'].append(cfg.name)
self.data['types'][cfg.name] = cfg.type
self.save()
return True
def addbot(self, bot):
"""
add a bot to the fleet .. remove all existing bots with the
same name.
"""
assert bot
if not bot in self.bots: self.bots.append(bot)
else: logging.error("%s bot is already in fleet" % bot.cfg.name) ; return False
self.addnametype(bot.cfg.name, bot.type)
logging.info('added %s' % bot.cfg.name)
return True
def delete(self, name):
""" delete bot with name from fleet. """
for bot in self.bots:
if bot.cfg.name == name:
bot.exit()
self.remove(bot)
bot.cfg['disable'] = 1
bot.cfg.save()
logging.debug('%s disabled' % bot.cfg.name)
return True
return False
def remove(self, bot):
""" delete bot by object. """
try:
self.bots.remove(bot)
return True
except ValueError:
return False
def exit(self, name=None, jabber=False):
""" call exit on all bots. """
if not name:
threads = []
for bot in self.bots:
if jabber and bot.type != 'sxmpp' and bot.type != 'jabber': continue
threads.append(start_new_thread(bot.exit, ()))
for thread in threads: thread.join()
return
for bot in self.bots:
if bot.cfg.name == name:
if jabber and bot.type != 'sxmpp' and bot.type != 'jabber': continue
try: bot.exit()
except: handle_exception()
self.remove(bot)
return True
return False
def cmnd(self, event, name, cmnd):
""" do command on a bot. """
bot = self.byname(name)
if not bot: return 0
j = cpy(event)
j.bot = bot
j.txt = cmnd
j.displayname = j.bot.cfg.name
j.execute()
return j.wait()
def cmndall(self, event, cmnd):
""" do a command on all bots. """
for bot in self.bots: self.cmnd(event, bot.cfg.name, cmnd)
def broadcast(self, txt):
""" broadcast txt to all bots. """
for bot in self.bots: bot.broadcast(txt)
def boot(self, botnames=[], exclude=[]):
if not botnames: botnames = self.getenabled(exclude)
bots = self.loadall(botnames)
todo = []
done = []
for bot in bots:
if not bot: continue
logging.debug("%s bot type is %s" % (bot.cfg.name, bot.type))
if bot.type not in exclude: todo.append(bot) ; done.append(bot.cfg.name)
if todo: start_new_thread(self.startall, (todo, ))
if done: logging.warn("fleet bots are %s" % ", ".join(done))
else: logging.warn("no fleet bots are enabled, see %s" % getdatadir() + os.sep + "config" + os.sep +'fleet')
def startall(self, bots, usethreads=True):
threads = []
target = bots or self.bots
for bot in target:
logging.debug('starting %s bot (%s)' % (bot.cfg.name, bot.type))
if usethreads or bot.type in ["sleek", "tornado"]: threads.append(start_new_thread(bot.boot, ())) ; continue
try: bot.boot()
except Excepton, ex: handle_exception()
time.sleep(1)
if usethreads:
for t in threads: t.join(15)
time.sleep(5)
self.startok.set()
def resume(self, sessionfile, exclude=[]):
""" resume bot from session file. """
session = json.load(open(sessionfile, 'r'))
chan = session.get("channel")
for name, cfg in session['bots'].iteritems():
dont = False
for ex in exclude:
if ex in name: dont = True
if dont: continue
cfg = LazyDict(cfg)
#cfg = LazyDict(session['bots'][name])
try:
if not cfg.disable:
logging.info("resuming %s" % cfg)
start_new_thread(self.resumebot, (cfg, chan))
except: handle_exception() ; return
time.sleep(10)
self.startok.set()
def resumebot(self, botcfg, chan=None):
""" resume single bot. """
botname = botcfg.name
logging.warn("resuming %s bot" % botname)
oldbot = self.byname(botname)
if oldbot and botcfg['type'] in ["sxmpp", "convore"]: oldbot.exit()
#cfg = Config('fleet' + os.sep + stripname(botname) + os.sep + 'config')
#if cfg.disable: logging.warn("%s - bot is disabled .. not resuming it" % botname) ; return
bot = self.makebot(botcfg.type, botname)
bot._resume(botcfg, botname)
bot.start(False)
self.addbot(bot)
if chan and chan in bot.state["joinedchannels"]: bot.say(chan, "done!")
## global fleet object
fleet = None
@locked
def getfleet(datadir=None, new=False):
if not datadir:
from jsb.lib.datadir import getdatadir
datadir = getdatadir()
global fleet
if not fleet or new:
fleet = Fleet(datadir)
fleet.loadall()
return fleet
def size():
return getfleet().size()
|