Example #1
0
 def opendb(self):
     if self.app: return
     self.connection = self.db.open()
     root = self.connection.root()
     app = root['Application']
     self.app = set_context(app)
     self.app._p_jar.sync()
Example #2
0
 def opendb(self):
     if self.app: return 
     self.connection=self.db.open()
     root=self.connection.root()
     app = root['Application']
     self.app = set_context(app)
     self.app._p_jar.sync()
Example #3
0
 def getConnection(self):
     """Return a wrapped app connection from the connection pool.
     """
     if not self.db:
         raise ZentinelException(
             "running inside zope can't open connections.")
     with self.poollock:
         connection = self.db.open()
         root = connection.root()
         app = root['Application']
         app = set_context(app)
         app._p_jar.sync()
         return app
Example #4
0
 def getConnection(self):
     """Return a wrapped app connection from the connection pool.
     """
     if not self.db:
         raise ZentinelException(
             "running inside zope can't open connections.")
     with self.poollock:
         connection=self.db.open()
         root=connection.root()
         app=root['Application']
         app = set_context(app)
         app._p_jar.sync()
         return app
Example #5
0
def _customStuff():
    """
    Everything available in the console is defined here.
    """

    import socket
    from transaction import commit
    from pprint import pprint
    from Products.ZenUtils.Utils import setLogLevel
    from Products.Zuul import getFacade, listFacades

    # Connect to the database, set everything up
    app = Zope2.app()
    app = set_context(app)

    def login(username="******"):
        utool = getToolByName(app, "acl_users")
        user = utool.getUserById(username)
        if user is None:
            user = app.zport.acl_users.getUserById(username)
        user = user.__of__(utool)
        newSecurityManager(None, user)
        from AccessControl.Implementation import setImplementation

        # Chip's pitched battle against segfault.
        # import pdb;pdb.set_trace()
        # setImplementation('PYTHON')

    login("admin")

    # Useful references
    zport = app.zport
    dmd = zport.dmd
    sync = zport._p_jar.sync
    find = dmd.Devices.findDevice
    devices = dmd.Devices
    me = find(socket.getfqdn())
    auditComment = audit.auditComment
    shell_stdout = []
    shell_stderr = []
    # evaluate any command the user has defined to startup
    for idx, line in enumerate(dmd.getZenDMDStartupCommands()):
        try:
            exec line in globals(), locals()
        except Exception, e:
            print "Error evaluating zendmd startup command #%s  %s, %s" % (idx, line, str(e))
Example #6
0
def _customStuff():
    """
    Everything available in the console is defined here.
    """

    import socket
    from transaction import commit
    from pprint import pprint
    from Products.ZenUtils.Utils import setLogLevel
    from Products.Zuul import getFacade, listFacades

    # Connect to the database, set everything up
    app = Zope2.app()
    app = set_context(app)

    def login(username='******'):
        utool = getToolByName(app, 'acl_users')
        user = utool.getUserById(username)
        if user is None:
            user = app.zport.acl_users.getUserById(username)
        user = user.__of__(utool)
        newSecurityManager(None, user)
        from AccessControl.Implementation import setImplementation
        #Chip's pitched battle against segfault.
        #import pdb;pdb.set_trace()
        #setImplementation('PYTHON')

    login('admin')

    # Useful references
    zport = app.zport
    dmd   = zport.dmd
    sync  = zport._p_jar.sync
    find  = dmd.Devices.findDevice
    devices = dmd.Devices
    me = find(socket.getfqdn())
    auditComment = audit.auditComment
    shell_stdout = []
    shell_stderr = []
    # evaluate any command the user has defined to startup
    for idx, line in enumerate(dmd.getZenDMDStartupCommands()):
        try:
            exec line in globals(), locals()
        except Exception, e:
            print "Error evaluating zendmd startup command #%s  %s, %s" %(idx, line, str(e))
# this is the first code that is run by a session
import Zope2
import os
from Products.ZenUtils.Utils import set_context
from Testing.makerequest import makerequest
from cStringIO import StringIO

CONF_FILE = os.path.join(os.environ["ZENHOME"], "etc", "zope.conf")
_ = Zope2.configure(CONF_FILE)
app = Zope2.app()
app = set_context(app)
dmd = app.zport.dmd
zport = app.zport
sync = zport._p_jar.sync
find = dmd.Devices.findDevice
devices = dmd.Devices


# login the current user
response_output = StringIO()
app = makerequest(app, stdout=response_output)

# load the zcmls

# context is added in the new_namespace
if context:
    context = app.unrestrictedTraverse(context, None)
    if context is None:
        del context
else:
    # not needed
Example #8
0
def _customStuff():
    """
    Everything available in the console is defined here.
    """

    import socket
    from transaction import commit
    from pprint import pprint
    from Products.ZenUtils.Utils import setLogLevel
    from Products.Zuul import getFacade, listFacades

    # Connect to the database, set everything up
    app = Zope2.app()
    app = set_context(app)

    def login(username='******'):
        utool = getToolByName(app, 'acl_users')
        user = utool.getUserById(username)
        if user is None:
            user = app.zport.acl_users.getUserById(username)
        user = user.__of__(utool)
        newSecurityManager(None, user)
        from AccessControl.Implementation import setImplementation
        #Chip's pitched battle against segfault.
        #import pdb;pdb.set_trace()
        #setImplementation('PYTHON')

    login('admin')

    # Useful references
    zport = app.zport
    dmd   = zport.dmd
    sync  = zport._p_jar.sync
    find  = dmd.Devices.findDevice
    devices = dmd.Devices
    me = find(socket.getfqdn())
    auditComment = audit.auditComment
    shell_stdout = []
    shell_stderr = []

    def reindex():
        sync()
        dmd.Devices.reIndex()
        dmd.Events.reIndex()
        dmd.Manufacturers.reIndex()
        dmd.Networks.reIndex()
        commit()

    def logout():
        noSecurityManager()

    def zhelp():
        cmds = sorted(filter(lambda x: not x.startswith("_"), _CUSTOMSTUFF))
        for cmd in cmds:
            print cmd

    def grepdir(obj, regex=""):
        if regex:
            import re
            pattern = re.compile(regex)
            for key in dir(obj):
                if pattern.search(key):
                    print key

    def lookupGuid(guid):
        """
        Given a guid this returns the object that it identifies
        """
        from Products.ZenUtils.guid.interfaces import IGUIDManager
        manager = IGUIDManager(dmd)
        return manager.getObject(guid)

    def version():
        for info in zport.About.getAllVersions():
            print "%10s: %s" % (info['header'], info['data'])
        print "%10s: %s" % ("DMD", dmd.version)

    def printNets(net=dmd.Networks, format="text", out=sys.stdout):
        """
        Print out the IpNetwork and IpAddress hierarchy under net.  To print
        out everything call printNets(dmd.Networks).  format can be text,
        python, or xml.
        """
        factory = IpNetworkPrinterFactory()
        printer = factory.createIpNetworkPrinter(format, out)
        printer.printIpNetwork(net)


    def cleandir(obj):
        portaldir = set(dir(dmd))
        objdir = set(dir(obj))
        appdir = set(dir(app))
        result = sorted(objdir - portaldir - appdir)
        pprint(result)

    def history(start=None, end=None, lines=30,
                   number=False):
        """
        Display the history starting from entry 'start' to
        entry 'end'. Only available on platforms where the
        readline module can be imported.

        History starts from 0 and goes to a large number.
        The history file is $ZENHOME/.pyhistory by default.

        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        @parameter number: show the line numbers?
        @type number: boolean
        """
        if readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                if number:
                    print i, readline.get_history_item(i)
                else:
                    print readline.get_history_item(i)

    def sh(cmd, interactive=True):
        """
        Execute a shell command.  If interactive is False, then
        direct the contents of stdout into shell_stdout and the
        output of stderr into shell_stderr.

        @parameter cmd: shell command to execute
        @type cmd: string
        @parameter interactive: show outut to the screen or not
        @type interactive: boolean
        """
        if interactive:
            proc = Popen(cmd, shell=True)
        else:
            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        output, errors = proc.communicate()
        proc.wait()
        if not interactive:
            output = output.split('\n')[:-1]
            errors = errors.split('\n')[:-1]
            _CUSTOMSTUFF['shell_stdout'] = output
            _CUSTOMSTUFF['shell_stderr'] = errors
        return output, errors

    def edit(file=None, start=None, end=None, lines=30):
        """
        Use the value of the EDITOR environment variable to
        edit a file.  Defaults to the original Unix IDE -- vi.

        @parameter file: name of file to edit -- defaults to a temp file
        @type file: string
        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        """
        editor = os.environ.get('EDITOR', 'vi')
        isNewFile = True
        isTmpName = False
        if file == None:
            isTmpName = True
            file = os.tempnam()
            fp = open(file, 'w')
        elif os.path.exists(file):
            isNewFile = False
        else:
            fp = open(file, 'w')

        if isNewFile and readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                fp.write(readline.get_history_item(i) + '\n')
            fp.close()

        sh('%s %s' % (editor, file))
        execfile(file, globals(), _CUSTOMSTUFF)
        if isTmpName:
            os.unlink(file)

    _CUSTOMSTUFF = locals()
    return _CUSTOMSTUFF
Example #9
0
def _customStuff():
    """
    Everything available in the console is defined here.
    """

    import socket
    from transaction import commit
    from pprint import pprint
    from Products.ZenUtils.Utils import setLogLevel
    from Products.Zuul import getFacade, listFacades

    # Connect to the database, set everything up
    app = Zope2.app()
    app = set_context(app)

    def login(username="******"):
        utool = getToolByName(app, "acl_users")
        user = utool.getUserById(username)
        if user is None:
            user = app.zport.acl_users.getUserById(username)
        user = user.__of__(utool)
        newSecurityManager(None, user)
        from AccessControl.Implementation import setImplementation

        # Chip's pitched battle against segfault.
        # import pdb;pdb.set_trace()
        # setImplementation('PYTHON')

    login("admin")

    # Useful references
    zport = app.zport
    dmd = zport.dmd
    sync = zport._p_jar.sync
    find = dmd.Devices.findDevice
    devices = dmd.Devices
    me = find(socket.getfqdn())
    auditComment = audit.auditComment
    shell_stdout = []
    shell_stderr = []

    def reindex():
        sync()
        dmd.Devices.reIndex()
        dmd.Events.reIndex()
        dmd.Manufacturers.reIndex()
        dmd.Networks.reIndex()
        commit()

    def logout():
        noSecurityManager()

    def zhelp():
        cmds = sorted(filter(lambda x: not x.startswith("_"), _CUSTOMSTUFF))
        for cmd in cmds:
            print cmd

    def grepdir(obj, regex=""):
        if regex:
            import re

            pattern = re.compile(regex)
            for key in dir(obj):
                if pattern.search(key):
                    print key

    def indexObject(obj):
        """
        Updates every index available for the object.
        """
        if hasattr(obj, "index_object"):
            obj.index_object()
        notify(IndexingEvent(obj))

    def lookupGuid(guid):
        """
        Given a guid this returns the object that it identifies
        """
        from Products.ZenUtils.guid.interfaces import IGUIDManager

        manager = IGUIDManager(dmd)
        return manager.getObject(guid)

    def version():
        for info in zport.About.getAllVersions():
            print "%10s: %s" % (info["header"], info["data"])
        print "%10s: %s" % ("DMD", dmd.version)

    def printNets(net=dmd.Networks, format="text", out=sys.stdout):
        """
        Print out the IpNetwork and IpAddress hierarchy under net.  To print
        out everything call printNets(dmd.Networks).  format can be text,
        python, or xml.
        """
        factory = IpNetworkPrinterFactory()
        printer = factory.createIpNetworkPrinter(format, out)
        printer.printIpNetwork(net)

    def cleandir(obj):
        portaldir = set(dir(dmd))
        objdir = set(dir(obj))
        appdir = set(dir(app))
        result = sorted(objdir - portaldir - appdir)
        pprint(result)

    def search(obj, p=None, s=None, a=None):
        """Search obj for matching attribute and method names.
           p: pattern to match
           s: super depth (how many inheritance levels to search)
           a: acquisition depth
        (ignores any attribute with '__' in its name)
        """
        pattern = None if p is None else re.compile(p, re.IGNORECASE)
        aq_end = None if a is None else a + 1
        seen = set([])
        all_print_args = {}
        chain = [x for x in aq_chain(obj)[:aq_end] if safe_hasattr(x, "id") and not inspect.ismethod(x.id)]
        for obj_ in chain:
            new_seen, print_args = _search_super(aq_base(obj_), pattern, s, seen)
            seen |= new_seen
            all_print_args[obj_.id] = print_args
        for obj_ in reversed(chain):
            mro_slice, attrs, methods = all_print_args[obj_.id]
            for cls in mro_slice:
                if attrs[cls] or methods[cls]:
                    print "\n", "=" * 79, "\n", path(obj_)
                    _search_print(mro_slice, attrs, methods)
                    break

    def path(obj):
        path_ = "/".join(x.id for x in reversed(aq_chain(obj)) if safe_hasattr(x, "id") and not inspect.ismethod(x.id))
        if path_ == "":
            return obj
        if path_ == "zport":
            return path_
        if path_ == "zport/dmd":
            return "dmd"
        return path_[len("zport/dmd/") :]

    def history(start=None, end=None, lines=30, number=False):
        """
        Display the history starting from entry 'start' to
        entry 'end'. Only available on platforms where the
        readline module can be imported.

        History starts from 0 and goes to a large number.
        The history file is $ZENHOME/.pyhistory by default.

        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        @parameter number: show the line numbers?
        @type number: boolean
        """
        if readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                if number:
                    print i, readline.get_history_item(i)
                else:
                    print readline.get_history_item(i)

    def sh(cmd, interactive=True):
        """
        Execute a shell command.  If interactive is False, then
        direct the contents of stdout into shell_stdout and the
        output of stderr into shell_stderr.

        @parameter cmd: shell command to execute
        @type cmd: string
        @parameter interactive: show outut to the screen or not
        @type interactive: boolean
        """
        if interactive:
            proc = Popen(cmd, shell=True)
        else:
            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        output, errors = proc.communicate()
        proc.wait()
        if not interactive:
            output = output.split("\n")[:-1]
            errors = errors.split("\n")[:-1]
            _CUSTOMSTUFF["shell_stdout"] = output
            _CUSTOMSTUFF["shell_stderr"] = errors
        return output, errors

    def edit(file=None, start=None, end=None, lines=30):
        """
        Use the value of the EDITOR environment variable to
        edit a file.  Defaults to the original Unix IDE -- vi.

        @parameter file: name of file to edit -- defaults to a temp file
        @type file: string
        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        """
        editor = os.environ.get("EDITOR", "vi")
        isNewFile = True
        isTmpName = False
        if file == None:
            isTmpName = True
            file = os.tempnam()
            fp = open(file, "w")
        elif os.path.exists(file):
            isNewFile = False
        else:
            fp = open(file, "w")

        if isNewFile and readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                fp.write(readline.get_history_item(i) + "\n")
            fp.close()

        sh("%s %s" % (editor, file))
        execfile(file, globals(), _CUSTOMSTUFF)
        if isTmpName:
            os.unlink(file)

    _CUSTOMSTUFF = locals()
    return _CUSTOMSTUFF
Example #10
0
def _customStuff():
    """
    Everything available in the console is defined here.
    """

    import socket
    from pprint import pprint
    from Products.ZenUtils.Utils import setLogLevel
    from Products.Zuul import getFacade, listFacades

    # Connect to the database, set everything up
    app = Zope2.app()
    app = set_context(app)

    def login(username='******'):
        utool = getToolByName(app, 'acl_users')
        user = utool.getUserById(username)
        if user is None:
            user = app.zport.acl_users.getUserById(username)
        user = user.__of__(utool)
        newSecurityManager(None, user)
        from AccessControl.Implementation import setImplementation
        #Chip's pitched battle against segfault.
        #import pdb;pdb.set_trace()
        #setImplementation('PYTHON')

    login('admin')

    # Useful references
    zport = app.zport
    dmd   = zport.dmd
    sync  = zport._p_jar.sync
    find  = dmd.Devices.findDevice
    devices = dmd.Devices
    me = find(socket.getfqdn())
    auditComment = audit.auditComment
    shell_stdout = []
    shell_stderr = []
    # evaluate any command the user has defined to startup
    for idx, line in enumerate(dmd.getZenDMDStartupCommands()):
        try:
            exec line in globals(), locals()
        except Exception as e:
            print "Error evaluating zendmd startup command #%s  %s, %s" %(idx, line, str(e))
    def reindex():
        sync()
        dmd.Devices.reIndex()
        dmd.Events.reIndex()
        dmd.Manufacturers.reIndex()
        dmd.Networks.reIndex()
        commit()

    def logout():
        noSecurityManager()

    def zhelp():
        cmds = sorted(filter(lambda x: not x.startswith("_"), _CUSTOMSTUFF))
        for cmd in cmds:
            print cmd

    def commit():
        audit.audit('Shell.Script.Commit')
        from transaction import commit
        commit()

    def grepdir(obj, regex=""):
        if regex:
            import re
            pattern = re.compile(regex)
            for key in dir(obj):
                if pattern.search(key):
                    print key

    def indexObject(obj):
        """
        Updates every index available for the object.
        """
        if hasattr(obj, 'index_object'):
            obj.index_object()
        notify(IndexingEvent(obj))

    def lookupGuid(guid):
        """
        Given a guid this returns the object that it identifies
        """
        from Products.ZenUtils.guid.interfaces import IGUIDManager
        manager = IGUIDManager(dmd)
        return manager.getObject(guid)

    def version():
        for info in zport.About.getAllVersions():
            print "%10s: %s" % (info['header'], info['data'])
        print "%10s: %s" % ("DMD", dmd.version)

    def printNets(net=dmd.Networks, format="text", out=sys.stdout):
        """
        Print out the IpNetwork and IpAddress hierarchy under net.  To print
        out everything call printNets(dmd.Networks).  format can be text,
        python, or xml.
        """
        factory = IpNetworkPrinterFactory()
        printer = factory.createIpNetworkPrinter(format, out)
        printer.printIpNetwork(net)


    def cleandir(obj):
        portaldir = set(dir(dmd))
        objdir = set(dir(obj))
        appdir = set(dir(app))
        result = sorted(objdir - portaldir - appdir)
        pprint(result)

    def search(obj, p=None, s=None, a=None):
        """Search obj for matching attribute and method names.
           p: pattern to match
           s: super depth (how many inheritance levels to search)
           a: acquisition depth
        (ignores any attribute with '__' in its name)
        """
        pattern = None if p is None else re.compile(p, re.IGNORECASE)
        aq_end = None if a is None else a + 1
        seen = set([])
        all_print_args = {}
        chain = [x for x in aq_chain(obj)[:aq_end] if safe_hasattr(x, 'id') \
                                            and not inspect.ismethod(x.id)]
        for obj_ in chain:
            new_seen, print_args = _search_super(aq_base(obj_), pattern, s, seen)
            seen |= new_seen
            all_print_args[obj_.id] = print_args
        for obj_ in reversed(chain):
            mro_slice, attrs, methods = all_print_args[obj_.id]
            for cls in mro_slice:
                if attrs[cls] or methods[cls]:
                    print '\n', '=' * 79, '\n', path(obj_)
                    _search_print(mro_slice, attrs, methods)
                    break

    def path(obj):
        path_ = '/'.join(x.id for x in reversed(aq_chain(obj)) \
                                            if safe_hasattr(x, 'id') \
                                            and not inspect.ismethod(x.id))
        if path_ == '':
            return obj
        if path_ == 'zport':
            return path_
        if path_ == 'zport/dmd':
            return 'dmd'
        return path_[len('zport/dmd/'):]

    def history(start=None, end=None, lines=30,
                   number=False):
        """
        Display the history starting from entry 'start' to
        entry 'end'. Only available on platforms where the
        readline module can be imported.

        History starts from 0 and goes to a large number.
        The history file is $ZENHOME/.pyhistory by default.

        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        @parameter number: show the line numbers?
        @type number: boolean
        """
        if readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                if number:
                    print i, readline.get_history_item(i)
                else:
                    print readline.get_history_item(i)

    def sh(cmd, interactive=True):
        """
        Execute a shell command.  If interactive is False, then
        direct the contents of stdout into shell_stdout and the
        output of stderr into shell_stderr.

        @parameter cmd: shell command to execute
        @type cmd: string
        @parameter interactive: show outut to the screen or not
        @type interactive: boolean
        """
        if interactive:
            proc = Popen(cmd, shell=True)
        else:
            proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        output, errors = proc.communicate()
        proc.wait()
        if not interactive:
            output = output.split('\n')[:-1]
            errors = errors.split('\n')[:-1]
            _CUSTOMSTUFF['shell_stdout'] = output
            _CUSTOMSTUFF['shell_stderr'] = errors
        return output, errors

    def edit(file=None, start=None, end=None, lines=30):
        """
        Use the value of the EDITOR environment variable to
        edit a file.  Defaults to the original Unix IDE -- vi.

        @parameter file: name of file to edit -- defaults to a temp file
        @type file: string
        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        """
        editor = os.environ.get('EDITOR', 'vi')
        isNewFile = True
        isTmpName = False
        if file == None:
            isTmpName = True
            file = os.tempnam()
            fp = open(file, 'w')
        elif os.path.exists(file):
            isNewFile = False
        else:
            fp = open(file, 'w')

        if isNewFile and readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                fp.write(readline.get_history_item(i) + '\n')
            fp.close()

        sh('%s %s' % (editor, file))
        execfile(file, globals(), _CUSTOMSTUFF)
        if isTmpName:
            os.unlink(file)

    _CUSTOMSTUFF = locals()
    return _CUSTOMSTUFF