예제 #1
0
    def privmsg(self, user, channel, msg):
        """Handles user messages from channels

        This hooks every privmsg sent to the channel and sends the commands off
        to cmds.dispatch to process, then replies to the channel accordingly.

        The @reload command needs to be handled here though, as it allows edits
        to be made to trailbot without disconnecting from IRC. It should get a
        list from cmds.dispatch if it needs to pm someone, otherwise it gets a
        string back and msgs the channel.

        """
        user = user.split('!', 1)[0]

        if msg == '%reload':
            rebuild.rebuild(cmds)
            rebuild.rebuild(voice)
            self.msg(channel, 'reloaded and ready to go')
        else:
            reply = cmds.dispatch(user, msg)

            if type(reply) is types.StringType:
                self.msg(channel, reply)
            else:
                if len(reply):
                    self.msg(channel, reply[0])
                    for trip in reply[1:]:
                        self.msg(user, trip)
예제 #2
0
파일: jobs.py 프로젝트: D3f0/txscada
    def remote_registerClasses(self, *args):
        """
        Instructs my broker to register the classes specified by the
        argument(s).

        The classes will be registered for B{all} jobs, and are specified by
        their string representations::
        
            <package(s).module.class>
        
        """
        modules = []
        for stringRep in args:
            # Load the class for the string representation
            cls = reflect.namedObject(stringRep)
            # Register instances of the class, including its type and module
            pb.setUnjellyableForClass(stringRep, cls)
            if cls.__module__ not in modules:
                modules.append(cls.__module__)
        # Try to build the modules for the classes in case they've changed
        # since the last run
        for module in modules:
            try:
                rebuild(reflect.namedModule(module), doLog=False)
            except:
                pass
예제 #3
0
    def test_FileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time

        shutil.copyfile(
            sibpath(__file__, "myrebuilder1.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"),
        )
        from twisted_rebuild_fakelib import myrebuilder  # type: ignore[import]

        a = myrebuilder.A()
        b = myrebuilder.B()
        i = myrebuilder.Inherit()
        self.assertEqual(a.a(), "a")
        # Necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(
            sibpath(__file__, "myrebuilder2.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"),
        )
        rebuild.rebuild(myrebuilder)
        b2 = myrebuilder.B()
        self.assertEqual(b2.b(), "c")
        self.assertEqual(b.b(), "c")
        self.assertEqual(i.a(), "d")
        self.assertEqual(a.a(), "b")
예제 #4
0
파일: module.py 프로젝트: cypreess/mamba
    def reload(self, module):
        """Reload a controller module

        :param module: the module to reload
        :type module: str
        """

        module_store = self.lookup(module)
        object = module_store.get('object')
        tmp_module = module_store.get('module')
        if object is None or object.loaded is False:
            raise ModuleError('Tried to reload %s that is not yet loaded' %
                              module)

        log.msg('{}: {} {}'.format(output.green('Reloading module'),
                                   object.__class__.__name__, object))

        try:
            rebuild.rebuild(tmp_module, False)
        except Exception as error:
            log.msg('{}: {}\n{}'.format(output.brown('Error reloading module'),
                                        error,
                                        traceback.format_exc()[:-1]))
        finally:
            object_name = object.__class__.__name__
            del self._modules[module]['object']
            gc.collect()
            temp_object = getattr(tmp_module, object_name)()
            temp_object.loaded = True
            self._modules[module]['object'] = temp_object
예제 #5
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if module.name and module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.", ModuleLoadType.LOAD)
예제 #6
0
    def on_modified(self, event):
        handlerModuleDetails = evaluateHandlerFileEvent(event)

        if not handlerModuleDetails:
            return

        handlerModulePath, handlerModule = handlerModuleDetails

        if handlerModule not in sys.modules:
            return False

        self.logger.info("Reloading %s", handlerModule)

        xtHandlersCollection, xmlHandlersCollection = removeHandlersByModule(
            handlerModulePath)

        handlerModuleObject = sys.modules[handlerModule]

        try:
            rebuild.rebuild(handlerModuleObject)

            self.logger.info("Successfully reloaded %s!", handlerModule)

        except Exception as rebuildError:
            self.logger.error("%s detected in %s, not reloading.",
                              rebuildError.__class__.__name__, handlerModule)
            self.logger.info("Restoring handler references...")

            Handlers.XTHandlers = xtHandlersCollection
            Handlers.XMLHandlers = xmlHandlersCollection

            self.logger.info("Handler references restored. Phew!")
예제 #7
0
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf('dirdbm.rebuild.test')
        s['key'] = 'value'
        rebuild.rebuild(dirdbm)
예제 #8
0
    def irc_PRIVMSG(self, line):
        msg = line.args[1]

        if line.args[0].startswith("#"):
            if msg[1:].startswith(self.nick):
                if msg[1+len(self.nick)+1:].strip() == "pointer":
                    answerURI = self.factory.rootURI + line.args[0][1:].lower() + '/' + line.ztime.rstrip("Z").replace("T", "#")
                    answer = "That line is " + answerURI
                    self.sendLine(Line("NOTICE", [line.args[0], answer]))

        if line.args[0] != self.nick:
            return False # not to us
        if parseprefix(line.prefix)[0] != self.factory.admin:
            return False # not from admin

        if msg == "+rebuild":
            try:
                rebuild(sioclogbot)
                info("rebuilt")
            except:
                print_exc()
        elif msg.startswith("+do "):
            try:
                self.sendLine(Line(linestr=msg[len("+do "):]))
            except:
                print_exc()

        return False # log
예제 #9
0
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf("dirdbm.rebuild.test")
        s["key"] = "value"
        rebuild.rebuild(dirdbm)
예제 #10
0
    def remote_registerClasses(self, *args):
        """
        Instructs my broker to register the classes specified by the
        argument(s).

        The classes will be registered for B{all} jobs, and are specified by
        their string representations::
        
            <package(s).module.class>
        
        """
        modules = []
        for stringRep in args:
            # Load the class for the string representation
            cls = reflect.namedObject(stringRep)
            # Register instances of the class, including its type and module
            pb.setUnjellyableForClass(stringRep, cls)
            if cls.__module__ not in modules:
                modules.append(cls.__module__)
        # Try to build the modules for the classes in case they've changed
        # since the last run
        for module in modules:
            try:
                rebuild(reflect.namedModule(module), doLog=False)
            except:
                pass
예제 #11
0
 def testRebuild(self):
     """Rebuilding an unchanged module."""
     x = crash_test_dummy.X('a')
     rebuild.rebuild(crash_test_dummy, doLog=False)
     x.do()
     self.failUnlessIdentical(x.__class__, crash_test_dummy.X)
     self.failUnlessIdentical(f, crash_test_dummy.foo)
예제 #12
0
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf('dirdbm.rebuild.test')
        s['key'] = 'value'
        rebuild.rebuild(dirdbm)
예제 #13
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if module.name and module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.",
                             ModuleLoadType.LOAD)
예제 #14
0
 def reload(self, request):
     request.redirect("..")
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br />' % module.__name__)
     return x
예제 #15
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if not module.name:
             raise ModuleLoaderError("???", "Module did not provide a name")
         if module.name == name:
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             break
예제 #16
0
    def loadModule(self, name):
        for module in getPlugins(IModule, pymoronbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower() == name.lower():
                rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                print('-- {} loaded'.format(module.__class__.__name__))

                return module.__class__.__name__
예제 #17
0
파일: widgets.py 프로젝트: lhl/songclub
 def reload(self, request):
     request.setHeader("location", "..")
     request.setResponseCode(http.MOVED_PERMANENTLY)
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br>' % module.__name__)
     return x
예제 #18
0
파일: botbot.py 프로젝트: fxia22/ASM_xf
 def bot_rebuild(self, sender, message, metadata):
     self.loadBotList()
     from twisted.words import botbot
     from twisted.python.rebuild import rebuild
     from twisted.python.reflect import namedModule
     if message:
         rebuild(namedModule(message))
     else:
         rebuild(botbot)
예제 #19
0
 def reload(self, request):
     request.setHeader("location", "..")
     request.setResponseCode(http.MOVED_PERMANENTLY)
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br>' % module.__name__)
     return x
예제 #20
0
 def call_from_console(self):
     if len(self.args.split(' ')) < 2:
         return "[Command] Invalid usage. (Usage: reloadplugin <Plugin Name>)"
     modulearg = self.args.split(' ')[1]
     if modulearg not in sys.modules.keys():
         return "That plugin (%s) is not loaded." % modulearg
     output = "[ShipProxy] Reloading plugin: %s..." % modulearg
     rebuild.rebuild(sys.modules[modulearg])
     output += "[ShipProxy] Plugin reloaded!\n"
     return output
예제 #21
0
 def call_from_console(self):
     if len(self.args.split(' ')) < 2:
         return "[Command] Invalid usage. (Usage: reloadplugin <Plugin Name>)"
     modulearg = self.args.split(' ')[1]
     if modulearg not in sys.modules.keys():
         return "That plugin (%s) is not loaded." % modulearg
     output = "[ShipProxy] Reloading plugin: %s..." % modulearg
     rebuild.rebuild(sys.modules[modulearg])
     output += "[ShipProxy] Plugin reloaded!\n"
     return output
예제 #22
0
    def loadModule(self, name: str, rebuild_: bool=True) -> str:
        for module in getPlugins(IModule, desertbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower() == name.lower():
                if rebuild_:
                    rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                self.logger.info('Module {} loaded'.format(module.__class__.__name__))

                return module.__class__.__name__
예제 #23
0
 def do_reload(self, *modules):
     """ try to reload one or more python modules.
         KNOW WHAT YOU ARE DOING!
     """
     self.sendLine("reloading module(s) %s" % ", ".join(modules))
     for m in modules:
         try:
             m_ = import_module(m)
             rebuild.rebuild(m_)
         except Exception, e:
             self.sendLine("reloading module %s threw Exception %s" % (m, e))
예제 #24
0
 def reloadModules(self, name=None):
     for i in range(len(self.modules)):
         try:
             if name == None:
                 self.modules[i] = rebuild(self.modules[i])
             elif self.modules[i].__name__ == name:
                 self.modules[i] = rebuild(self.modules[i])
         except Exception, e:
             self.logger.error("Error rebuilding - {0}".format(
                 self.modules[i].__name__))
             self.logger.error("[TE030] {0}".format(e))
예제 #25
0
 def testComponentInteraction(self):
     x = crash_test_dummy.XComponent()
     x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
     oldComponent = x.getComponent(crash_test_dummy.IX)
     rebuild.rebuild(crash_test_dummy, 0)
     newComponent = x.getComponent(crash_test_dummy.IX)
     newComponent.method()
     self.assertEquals(newComponent.__class__, crash_test_dummy.XA)
     from twisted.python import components
     self.failUnlessRaises(ValueError, components.registerAdapter,
                           crash_test_dummy.XA, crash_test_dummy.X,
                           crash_test_dummy.IX)
예제 #26
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, desertbot.modules):
         if not module.name:
             raise ModuleLoaderError("???",
                                     "Module did not provide a name.",
                                     ModuleLoadType.LOAD)
         if module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.",
                             ModuleLoadType.LOAD)
예제 #27
0
    def loadModule(self, name: str, rebuild_: bool = True) -> str:
        for module in getPlugins(IModule, desertbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower(
            ) == name.lower():
                if rebuild_:
                    rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                self.logger.info('Module {} loaded'.format(
                    module.__class__.__name__))

                return module.__class__.__name__
예제 #28
0
파일: Debug.py 프로젝트: Kays/cia-vc
def rebuildPackage(package):
    """Recursively rebuild all loaded modules in the given package"""
    rebuild.rebuild(package)
    # If this is really a package instead of a module, look for children
    try:
        f = package.__file__
    except AttributeError:
        return
    if package.__file__.find("__init__") >= 0:
        for item in package.__dict__.itervalues():
            # Is it a module?
            if type(item) == type(package):
                rebuildPackage(item)
예제 #29
0
 def test_hashException(self):
     """
     Rebuilding something that has a __hash__ that raises a non-TypeError
     shouldn't cause rebuild to die.
     """
     global unhashableObject
     unhashableObject = HashRaisesRuntimeError()
     def _cleanup():
         global unhashableObject
         unhashableObject = None
     self.addCleanup(_cleanup)
     rebuild.rebuild(rebuild)
     self.assertEquals(unhashableObject.hashCalled, True)
예제 #30
0
def rebuildPackage(package):
    """Recursively rebuild all loaded modules in the given package"""
    rebuild.rebuild(package)
    # If this is really a package instead of a module, look for children
    try:
        f = package.__file__
    except AttributeError:
        return
    if package.__file__.find("__init__") >= 0:
        for item in package.__dict__.itervalues():
            # Is it a module?
            if type(item) == type(package):
                rebuildPackage(item)
예제 #31
0
 def child_rebuild(self, ctx):
     import pages_base
     rebuild(pages_base)
     import pages_index
     rebuild(pages_index)
     import pages_rooms
     rebuild(pages_rooms)
     import pages_edit
     rebuild(pages_edit)
     import pages_exits
     rebuild(pages_exits)
     self.goback(ctx)
     return self
예제 #32
0
 def test_hashException(self):
     """
     Rebuilding something that has a __hash__ that raises a non-TypeError
     shouldn't cause rebuild to die.
     """
     global unhashableObject
     unhashableObject = HashRaisesRuntimeError()
     def _cleanup():
         global unhashableObject
         unhashableObject = None
     self.addCleanup(_cleanup)
     rebuild.rebuild(rebuild)
     self.assertEqual(unhashableObject.hashCalled, True)
예제 #33
0
파일: app.py 프로젝트: spicerack/sage
    def reload(self, name, event_src_path=None):
        """ Try to fully rebuild an app """

        # Don't reload the same app if we did it within last the 5 sec
        if time.time() - self._last_reload.get(name, 0) < 5:
            return

        self._last_reload[name] = time.time()

        if name not in self:
            return False

        if hasattr(self[name], 'pre_reload'):
            self[name].pre_reload()

        try:
            if event_src_path:

                if event_src_path.endswith('.py'):
                    path, f = os.path.split(event_src_path)
                    pyc = path + '/' + f[:-3] + '.pyc'
                    if os.path.isfile(pyc):
                        os.remove(pyc)

                targets = []

                for mname, module in sys.modules.items():
                    if module:
                        if hasattr(module, '__file__'):
                            if event_src_path in module.__file__:
                                targets.append(module)

                for target in targets:
                    rebuild(target, False)

            else:
                # generally try to reload the app
                self[name] = rebuild(self[name], False)
        except:
            sage._log.msg("Error reloading '%s'" % name)
            sage._log.err()
            return False

        gc.collect()

        if hasattr(self[name], 'post_reload'):
            self[name].post_reload()

        sage._log.msg("Reloaded app '%s'" % self.meta[name].name)

        return True
예제 #34
0
    def testRebuild(self):
        """Rebuilding an unchanged module."""
        # This test would actually pass if rebuild was a no-op, but it
        # ensures rebuild doesn't break stuff while being a less
        # complex test than testFileRebuild.
        
        x = crash_test_dummy.X('a')

        rebuild.rebuild(crash_test_dummy, doLog=False)
        # Instance rebuilding is triggered by attribute access.
        x.do()
        self.failUnlessIdentical(x.__class__, crash_test_dummy.X)

        self.failUnlessIdentical(f, crash_test_dummy.foo)
예제 #35
0
    def testRebuild(self):
        """Rebuilding an unchanged module."""
        # This test would actually pass if rebuild was a no-op, but it
        # ensures rebuild doesn't break stuff while being a less
        # complex test than testFileRebuild.

        x = crash_test_dummy.X('a')

        rebuild.rebuild(crash_test_dummy, doLog=False)
        # Instance rebuilding is triggered by attribute access.
        x.do()
        self.failUnlessIdentical(x.__class__, crash_test_dummy.X)

        self.failUnlessIdentical(f, crash_test_dummy.foo)
예제 #36
0
    def on_modified(self, event):
        # Ignore all directory events
        if event.is_directory:
            return

        handlerModulePath = event.src_path[2:]
        handlerModule = handlerModulePath.replace("/", ".")[:-3]

        if handlerModule not in sys.modules:
            return

        self.logger.debug("Reloading %s", handlerModule)

        if "Houdini.Handlers.Play" in handlerModule:
            handlerItems = Handlers.XTHandlers.items()
            handlerCollection = copy.deepcopy(Handlers.XTHandlers)

        else:
            handlerItems = Handlers.XMLHandlers.items()
            handlerCollection = copy.deepcopy(Handlers.XMLHandlers)

        for handlerId, handlerListeners in handlerItems:
            for handlerListener in handlerListeners:
                # Look through the list of listeners to determine which need to be removed
                # self.logger.debug("Comparing %s to %s", handlerListener.functionFile, handlerModulePath)

                if handlerListener.functionFile == handlerModulePath:
                    self.logger.debug("Removing a %s listener", handlerId)
                    handlerListeners.remove(handlerListener)

        handlerModuleObject = sys.modules[handlerModule]

        try:
            rebuild.rebuild(handlerModuleObject)

        except (IndentationError, SyntaxError) as rebuildError:
            self.logger.error("%s detected in %s, not reloading.",
                              rebuildError.__class__.__name__, handlerModule)
            self.logger.info("Restoring handler references...")

            if "Houdini.Handlers.Play" in handlerModule:
                Handlers.XTHandlers = handlerCollection
            else:
                Handlers.XMLHandlers = handlerCollection

            self.logger.info("Handler references restored. Phew!")
        except:
            self.logger.error("Unable to reload %s due to an unknown reason!",
                              handlerModule)
예제 #37
0
    def check_and_reload(self, subOptions):
        modules_changed = code_changed()
        if modules_changed:
            for module in modules_changed:

                try:
                    rebuild(module)
                except Exception as e:
                    self.logger.critical("Error reloading %s: %s", module.__name__, e)
                    self.app = NoResource("There was an error reloading the app.")
                    break
                else:
                    self.logger.critical("Reloaded %s (%d modules loaded)", module.__name__, len(sys.modules))
            else:
                self.attach_app(subOptions)
 def patch(self):
     try:
         access_token = cfg.reload_token  # Access Token
         try:
             request_token = request.get_json(force=True)['token']
         except BaseException:
             request_token = ''
         if request_token == access_token:
             rebuild.rebuild(wf)
             rebuild.rebuild(misc)
             return 'Successfully reloaded modules.', 200
         else:
             return 'Access Denied.', 403
     except Exception as e:
         return repr(e), 500
예제 #39
0
    def privmsg(self, user, channel, message):
        print 'privmsg', user, channel, message
        username = user[:user.index('!')]
        host = user[user.rindex('@') + 1:]
        if channel.startswith('#'):
            dest = channel
        else:
            dest = username

        if message == 'rebuild':
            try:
                rebuild(darcsbot)
                print 'rebuilt'
            except:
                print_exc()
            return
예제 #40
0
파일: BaneBot.py 프로젝트: Hasimir/eventsdb
    def reloadPluginModule(self, stuff, filepath, mask):
        # Get the actual filepath
        afpath = os.path.abspath(filepath.path).replace('.conf', '.py')

        # See if we need to reload a plugin, load a new plugin, or ignore
        if mask == inotify.IN_MODIFY and afpath in self.modules:
            try:
                self.modules[afpath] = rebuild(self.modules[afpath])
                self.loadPluginObject(self.modules[afpath], reloading=True)
                if self.logging:
                    log.msg('Reloaded {}'.format(filepath))
            except:
                if self.logging:
                    log.err('Failed to reload {} | {} | {}'.\
                            format( filepath
                                  , sys.exc_info()[0]
                                  , traceback.format_exc()
                                  )
                           )

        elif mask == inotify.IN_CREATE and afpath.endswith('.py'):
            plugin = afpath.split('/')[-1].rstrip('.py')
            self.modules[afpath] = import_module('plugins.{}'.format(plugin))

        else:
            return
예제 #41
0
    def testComponentInteraction(self):
        x = crash_test_dummy.XComponent()
        x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
        x.getComponent(crash_test_dummy.IX)
        rebuild.rebuild(crash_test_dummy, 0)
        newComponent = x.getComponent(crash_test_dummy.IX)

        newComponent.method()

        self.assertEqual(newComponent.__class__, crash_test_dummy.XA)

        # Test that a duplicate registerAdapter is not allowed
        from twisted.python import components
        self.assertRaises(ValueError, components.registerAdapter,
                              crash_test_dummy.XA, crash_test_dummy.X,
                              crash_test_dummy.IX)
예제 #42
0
    def reloadPluginModule(self, stuff, filepath, mask):
        # Get the actual filepath
        afpath = os.path.abspath(filepath.path).replace('.conf', '.py')

        # See if we need to reload a plugin, load a new plugin, or ignore
        if mask == inotify.IN_MODIFY and afpath in self.modules:
            try:
                self.modules[afpath] = rebuild(self.modules[afpath])
                self.loadPluginObject(self.modules[afpath], reloading=True)
                if self.logging:
                    log.msg('Reloaded {}'.format(filepath))
            except:
                if self.logging:
                    log.err('Failed to reload {} | {} | {}'.\
                            format( filepath
                                  , sys.exc_info()[0]
                                  , traceback.format_exc()
                                  )
                           )

        elif mask == inotify.IN_CREATE and afpath.endswith('.py'):
            plugin = afpath.split('/')[-1].rstrip('.py')
            self.modules[afpath] = import_module('plugins.{}'.format(plugin))

        else:
            return
예제 #43
0
    def testComponentInteraction(self):
        x = crash_test_dummy.XComponent()
        x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
        oldComponent = x.getComponent(crash_test_dummy.IX)
        rebuild.rebuild(crash_test_dummy, 0)
        newComponent = x.getComponent(crash_test_dummy.IX)

        newComponent.method()

        self.assertEqual(newComponent.__class__, crash_test_dummy.XA)

        # Test that a duplicate registerAdapter is not allowed
        from twisted.python import components
        self.failUnlessRaises(ValueError, components.registerAdapter,
                              crash_test_dummy.XA, crash_test_dummy.X,
                              crash_test_dummy.IX)
예제 #44
0
def reloadFlumotion():
    """Properly reload all flumotion-related modules currently loaded."""
    needs_reload = lambda name: name.startswith('flumotion')
    for name in filter(needs_reload, sys.modules.keys()):
        if not name in sys.modules:
            log.warning("reload", "hm, %s disappeared from the modules" % name)
            continue
        module = sys.modules[name]
        if not module:
            log.log("reload", "hm, module '%s' == None" % name)
            continue
        log.log("reload", "rebuilding %s" % module)
        try:
            rebuild(module, doLog=0)
        except SyntaxError, msg:
            from flumotion.common import errors
            raise errors.ReloadSyntaxError(msg)
예제 #45
0
def reloadFlumotion():
    """Properly reload all flumotion-related modules currently loaded."""
    needs_reload = lambda name: name.startswith('flumotion')
    for name in filter(needs_reload, sys.modules.keys()):
        if not name in sys.modules:
            log.warning("reload", "hm, %s disappeared from the modules" % name)
            continue
        module = sys.modules[name]
        if not module:
            log.log("reload", "hm, module '%s' == None" % name)
            continue
        log.log("reload", "rebuilding %s" % module)
        try:
            rebuild(module, doLog=0)
        except SyntaxError, msg:
            from flumotion.common import errors
            raise errors.ReloadSyntaxError(msg)
예제 #46
0
	def loadModule(self, moduleName):
		"""
		Loads a module of the specified name.
		Raises ModuleLoadError if the module cannot be loaded.
		If the specified module is currently being unloaded, returns the
		DeferredList specified by the module when it was unloading with a
		callback to try to load the module again once it succeeds.
		"""
		if moduleName in self._unloadingModules:
			deferList = self._unloadingModules[moduleName]
			deferList.addCallback(self._tryLoadAgain, moduleName)
			return deferList
		for module in getPlugins(IModuleData, txircd.modules):
			if module.name == moduleName:
				rebuild(importlib.import_module(module.__module__)) # getPlugins doesn't recompile modules, so let's do that ourselves.
				self._loadModuleData(module)
				self.log.info("Loaded module {module}.", module=moduleName)
				break
예제 #47
0
파일: main.py 프로젝트: MilkSR/WooferedBot
def keyboard_handler():
    print 'Hi, keyboard input here plz'
    while True:
        try:
            cmd = raw_input()
            if cmd == 'q': break
            elif cmd == ' ':
                command = raw_input("What do you want to do?:")
                if command.lower() == "join":
                    newChannel = raw_input("Which channel do you want to join?:")

                    if newChannel in config['channels']:
                        print 'We\'re already in channel #{}'.format(newChannel)
                    else:
                        # add to last bot, or create new bot if none exist yet
                        if len(bots) > 0:
                            (bot, tcp) = bots[-1]
                        else:
                            bot = WooferBotFactory([newChannel])
                            tcp = reactor.connectTCP("irc.twitch.tv", 6667, bot)
                            bots.append((bot, tcp))
                        bot.addChannel(newChannel)

                elif command.lower() == "chat":
                    channel = raw_input("Where do you want to chat?:")
                    # find bot associated to channel
                    try:
                        bot = next(bot for (bot,tcp) in bots if channel in bot.channels)
                        msg = raw_input("What do you want to say?:")
                        bot.irc.say(channel, msg)
                    except StopIteration:
                        print 'I don\'t know that channel'

                elif command.lower() == "reload":
                    rebuild(handler)
                    rebuild(api)
                
                elif command.lower() == "load":
                    loadChannel = raw_input("Which channel's config should I load?:")
                    config.load(loadChannel)
                    
        except Exception,e:
            print e
예제 #48
0
    def connectionMade(self, irc, secret=None):
        self._irc = irc
        self.readState()
        try:
            helper = rebuild.rebuild(helper, doLog=0)
        except:
            pass

        self.periodic_commands = LoopingCall(self.do_periodics)
        self.periodic_commands.start(1800)
        self.loopers.append(self.periodic_commands)
예제 #49
0
 def load_plugins(self):
     from twisted.plugin import getPlugins, IPlugin
     import plugins
     if not self.irc_auth.q_auth():
         print "Plugins failed to load"
         return
     else:
         for plugin in getPlugins(IPlugin, plugins):
             try:
                 for cmd, fun in plugin.commands.items():
                     object_path = plugin.__module__ + "." + plugin.name
                     # Could be un-needed.
                     #p_module = rebuild(self.my_import(plugin.__module__))
                     rebuild(self.my_import(plugin.__module__))
                     p_object = eval(object_path[5:])()
                     self.thoughts[cmd] = p_object.__getattribute__(fun)
             except AttributeError:
                 print "Error on importing plugins: " + str(plugin)
         for key, value in self.thoughts.items():
             print str(key) + " : " + str(value)
    def testFileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time
        shutil.copyfile(
            sibpath(__file__, "myrebuilder1.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"))
        from twisted_rebuild_fakelib import myrebuilder
        a = myrebuilder.A()
        try:
            object
        except NameError:
            pass
        else:
            from twisted.test import test_rebuild
            b = myrebuilder.B()

            class C(myrebuilder.B):
                pass

            test_rebuild.C = C
            c = C()
        i = myrebuilder.Inherit()
        self.assertEquals(a.a(), 'a')
        # necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(
            sibpath(__file__, "myrebuilder2.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"))
        rebuild.rebuild(myrebuilder)
        try:
            object
        except NameError:
            pass
        else:
            b2 = myrebuilder.B()
            self.assertEquals(b2.b(), 'c')
            self.assertEquals(b.b(), 'c')
        self.assertEquals(i.a(), 'd')
        self.assertEquals(a.a(), 'b')
예제 #51
0
파일: gtkmanhole.py 프로젝트: fxia22/ASM_xf
 def codeInput(self, text):
     methodName = 'do'
     if text[0] == '/':
         split = string.split(text[1:],' ',1)
         statement = split[0]
         if len(split) == 2:
             remainder = split[1]
         if statement in ('browse', 'explore'):
             methodName = 'explore'
             text = remainder
         elif statement == 'watch':
             methodName = 'watch'
             text = remainder
         elif statement == 'self_rebuild':
             rebuild.rebuild(explorer)
             if _GNOME_POWER:
                 rebuild.rebuild(spelunk_gnome)
             rebuild.rebuild(sys.modules[__name__])
             return
     try:
         self.perspective.callRemote(methodName, text)
     except pb.ProtocolError:
         # ASSUMPTION: pb.ProtocolError means we lost our connection.
         (eType, eVal, tb) = sys.exc_info()
         del tb
         s = string.join(traceback.format_exception_only(eType, eVal),
                         '')
         self.connectionLost(s)
     except:
         traceback.print_exc()
         gtk.mainquit()
예제 #52
0
 def codeInput(self, text):
     methodName = 'do'
     if text[0] == '/':
         split = string.split(text[1:],' ',1)
         statement = split[0]
         if len(split) == 2:
             remainder = split[1]
         if statement in ('browse', 'explore'):
             methodName = 'explore'
             text = remainder
         elif statement == 'watch':
             methodName = 'watch'
             text = remainder
         elif statement == 'self_rebuild':
             rebuild.rebuild(explorer)
             if _GNOME_POWER:
                 rebuild.rebuild(spelunk_gnome)
             rebuild.rebuild(sys.modules[__name__])
             return
     try:
         self.perspective.callRemote(methodName, text)
     except pb.ProtocolError:
         # ASSUMPTION: pb.ProtocolError means we lost our connection.
         (eType, eVal, tb) = sys.exc_info()
         del tb
         s = string.join(traceback.format_exception_only(eType, eVal),
                         '')
         self.connectionLost(s)
     except:
         traceback.print_exc()
         gtk.mainquit()
예제 #53
0
    def testFileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time
        shutil.copyfile(sibpath(__file__, "myrebuilder1.py"),
                        os.path.join(self.fakelibPath, "myrebuilder.py"))
        from twisted_rebuild_fakelib import myrebuilder
        a = myrebuilder.A()
        try:
            object
        except NameError:
            pass
        else:
            from twisted.test import test_rebuild
            b = myrebuilder.B()

            class C(myrebuilder.B):
                pass

            test_rebuild.C = C
            c = C()
        i = myrebuilder.Inherit()
        self.assertEqual(a.a(), 'a')
        # necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(sibpath(__file__, "myrebuilder2.py"),
                        os.path.join(self.fakelibPath, "myrebuilder.py"))
        rebuild.rebuild(myrebuilder)
        try:
            object
        except NameError:
            pass
        else:
            b2 = myrebuilder.B()
            self.assertEqual(b2.b(), 'c')
            self.assertEqual(b.b(), 'c')
        self.assertEqual(i.a(), 'd')
        self.assertEqual(a.a(), 'b')
예제 #54
0
    def on_modified(self, event):
        pluginModuleDetails = evaluatePluginFileEvent(event)

        if not pluginModuleDetails:
            return

        pluginModulePath, pluginModule = pluginModuleDetails

        if pluginModule not in sys.modules:
            return

        self.logger.info("Reloading %s", pluginModule)

        xtHandlersCollection, xmlHandlersCollection = removeHandlersByModule(pluginModulePath)
        eventHandlersCollection = createDeepCopy(Events.EventHandlers)

        pluginModuleObject = sys.modules[pluginModule]
        pluginClass = pluginModuleObject.__name__.split(".")[2]

        try:
            removeEventsByInstance(pluginModuleObject)

            newPluginModule = rebuild.rebuild(pluginModuleObject)
            newPluginObject = getattr(newPluginModule, pluginClass)(self.server)
            self.server.plugins[pluginClass] = newPluginObject

            self.logger.info("Successfully reloaded %s!", pluginModule)

        except LookupError as lookupError:
            self.logger.warn("Did not reload plugin '%s': %s." % (pluginClass, lookupError.message))

        except Exception as rebuildError:
            self.logger.error("%s detected in %s, not reloading.", rebuildError.__class__.__name__, pluginModule)
            self.logger.info("Restoring handler references...")

            Handlers.XTHandlers = xtHandlersCollection
            Handlers.XMLHandlers = xmlHandlersCollection
            Events.EventHandlers = eventHandlersCollection

            self.logger.info("Handler references restored. Phew!")
예제 #55
0
    def sendMessage(self, unused_data=None):
        text = self.get_chars(0,-1)
        if self.linemode:
            self.blockcount = self.blockcount + 1
            fmt = ">>> # begin %s\n%%s\n#end %s\n" % (
                self.blockcount, self.blockcount)
        else:
            fmt = ">>> %s\n"
        self.history.append(text)
        self.histpos = len(self.history)
        self.toplevel.output.console([['command',fmt % text]])

        method = self.toplevel.perspective.do

        if text[0] == '/':
            split = string.split(text[1:],' ',1)
            statement = split[0]
            if len(split) == 2:
                remainder = split[1]
            if statement == 'browse':
                method = self.toplevel.perspective.browse
                text = remainder
            elif statement == 'watch':
                method = self.toplevel.perspective.watch
                text = remainder
            elif statement == 'self_rebuild':
                rebuild.rebuild(explorer)
                if _GNOME_POWER:
                    rebuild.rebuild(gnomehole)
                rebuild.rebuild(sys.modules[__name__])
                return
        try:
            method(text)
        except pb.ProtocolError:
            # ASSUMPTION: pb.ProtocolError means we lost our connection.
            (eType, eVal, tb) = sys.exc_info()
            del tb
            s = string.join(traceback.format_exception_only(eType, eVal),
                            '')
            self.toplevel.connectionLost(s)
        except:
            traceback.print_exc()
            gtk.mainquit()
예제 #56
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from collections import deque
from datetime import datetime, timedelta
from random import randint, choice
import cPickle
from os import fstat, stat, getpid
import re
import subprocess
import psycopg2
from time import time
from twisted.python.rebuild import rebuild

import markov
rebuild(markov)  # Update in case of dynamic reload

DEFAULT_MARKOV_LENGTH = 4  # Valid values:  1-4

CONTEXT_CHAIN_BIAS = 100  # Adjust response-ranking priority of chain
# length vs. context score (higher numbers
# favor longer chain length more)

#------------------------------------------------------------------------------


class Nikky_error(Exception):
    pass


class Dont_know_how_to_respond_error(Nikky_error):
예제 #57
0
 def test_rebuildInteraction(self):
     s = dirdbm.Shelf("dirdbm.rebuild.test")
     s[b"key"] = b"value"
     rebuild.rebuild(dirdbm)