当前位置: 首页>>代码示例>>Python>>正文


Python NetDevices.find方法代码示例

本文整理汇总了Python中trigger.netdevices.NetDevices.find方法的典型用法代码示例。如果您正苦于以下问题:Python NetDevices.find方法的具体用法?Python NetDevices.find怎么用?Python NetDevices.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在trigger.netdevices.NetDevices的用法示例。


在下文中一共展示了NetDevices.find方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: NetDevicesTest

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class NetDevicesTest(unittest.TestCase):

    def setUp(self):
        self.nd = NetDevices()
        self.nodename = self.nd.keys()[0]
        self.nodeobj = self.nd.values()[0]

    def testBasics(self):
        """Basic test of NetDevices functionality."""
        self.assertEqual(len(self.nd), 1)
        self.assertEqual(self.nodeobj.nodeName, self.nodename)
        self.assertEqual(self.nodeobj.manufacturer, 'JUNIPER')

    def testAclsdb(self):
        """Test acls.db handling."""
        self.assert_('181j' in self.nodeobj.acls)

    def testAutoacls(self):
        """Test autoacls.py handling."""
        self.assert_('115j' in self.nodeobj.acls)

    def testFind(self):
        """Test the find() method."""
        self.assertEqual(self.nd.find(self.nodename), self.nodeobj)
        nodebasename = self.nodename[:self.nodename.index('.')]
        self.assertEqual(self.nd.find(nodebasename), self.nodeobj)
        self.assertRaises(KeyError, lambda: self.nd.find(self.nodename[0:3]))
开发者ID:altoplano,项目名称:trigger,代码行数:29,代码来源:netdevices.py

示例2: TestNetDevicesWithAcls

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class TestNetDevicesWithAcls(unittest.TestCase):
    """
    Test NetDevices with ``settings.WITH_ACLs set`` to ``True``.
    """
    def setUp(self):
        self.nd = NetDevices()
        self.nodename = self.nd.keys()[0]
        self.device = self.nd.values()[0]
        self.device.explicit_acls = set(['test1-abc-only'])

    def test_basics(self):
        """Basic test of NetDevices functionality."""
        self.assertEqual(len(self.nd), 1)
        self.assertEqual(self.device.nodeName, self.nodename)
        self.assertEqual(self.device.manufacturer, 'JUNIPER')

    def test_aclsdb(self):
        """Test acls.db handling."""
        self.assertTrue('test1-abc-only' in self.device.explicit_acls)

    def test_autoacls(self):
        """Test autoacls.py handling."""
        self.assertTrue('router-protect.core' in self.device.implicit_acls)

    def test_find(self):
        """Test the find() method."""
        self.assertEqual(self.nd.find(self.nodename), self.device)
        nodebasename = self.nodename[:self.nodename.index('.')]
        self.assertEqual(self.nd.find(nodebasename), self.device)
        self.assertRaises(KeyError, lambda: self.nd.find(self.nodename[0:3]))

    def test_all(self):
        """Test the all() method."""
        expected = [self.device]
        self.assertEqual(expected, self.nd.all())

    def test_search(self):
        """Test the search() method."""
        expected = [self.device]
        self.assertEqual(expected, self.nd.search(self.nodename))
        self.assertEqual(expected, self.nd.search('17', field='onCallID'))
        self.assertEqual(expected, self.nd.search('juniper', field='vendor'))

    def test_match(self):
        """Test the match() method."""
        expected = [self.device]
        self.assertEqual(expected, self.nd.match(nodename=self.nodename))
        self.assertEqual(expected, self.nd.match(vendor='juniper'))
        self.assertNotEqual(expected, self.nd.match(vendor='cisco'))

    def tearDown(self):
        NetDevices._Singleton = None
开发者ID:ArnesSI,项目名称:trigger,代码行数:54,代码来源:test_netdevices.py

示例3: NetDevicesTest

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class NetDevicesTest(unittest.TestCase):
    def setUp(self):
        self.nd = NetDevices(with_acls=False)
        print self.nd.values()
        self.nodename = self.nd.keys()[0]
        self.nodeobj = self.nd.values()[0]

    def testBasics(self):
        """Basic test of NetDevices functionality."""
        self.assertEqual(len(self.nd), 3)
        self.assertEqual(self.nodeobj.nodeName, self.nodename)
        self.assertEqual(self.nodeobj.manufacturer, "JUNIPER")

    def testFind(self):
        """Test the find() method."""
        self.assertEqual(self.nd.find(self.nodename), self.nodeobj)
        nodebasename = self.nodename[: self.nodename.index(".")]
        self.assertEqual(self.nd.find(nodebasename), self.nodeobj)
        self.assertRaises(KeyError, lambda: self.nd.find(self.nodename[0:3]))
开发者ID:jjaissle,项目名称:trigger,代码行数:21,代码来源:trigger_acceptance_tests.py

示例4: TestAclsDB

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class TestAclsDB(unittest.TestCase):
    def setUp(self):
        self.nd = NetDevices()
        self.acl = ACL_NAME
        self.device = self.nd.find(DEVICE_NAME)
        self.implicit_acls = set(['115j', 'router-protect.core'])

    def test_01_add_acl_success(self):
        """Test associate ACL to device success"""
        exp = 'added acl %s to %s' % (self.acl, self.device)
        self.assertEqual(exp, adb.add_acl(self.device, self.acl))

    def test_02_add_acl_failure(self):
        """Test associate ACL to device failure"""
        exp = exceptions.ACLSetError
        self.assertRaises(exp, adb.add_acl, self.device, self.acl)

    def test_03_remove_acl_success(self):
        """Test remove ACL from device success"""
        exp = 'removed acl %s from %s' % (self.acl, self.device)
        self.assertEqual(exp, adb.remove_acl(self.device, self.acl))

    def test_04_remove_acl_failure(self):
        """Test remove ACL from device failure"""
        exp = exceptions.ACLSetError
        self.assertRaises(exp, adb.remove_acl, self.device, self.acl)

    def test_05_get_acl_dict(self):
        """Test get dict of associations"""
        exp = {'all': self.implicit_acls, 'explicit': set(),
               'implicit': self.implicit_acls}
        self.assertEqual(exp, adb.get_acl_dict(self.device))

    def test_06_get_acl_set_success(self):
        """Test get set of associations success"""
        exp = self.implicit_acls
        self.assertEqual(exp, adb.get_acl_set(self.device))

    def test_07_get_acl_set_failure(self):
        """Test get set of associations failure"""
        exp = exceptions.InvalidACLSet
        acl_set = 'bogus'
        self.assertRaises(exp, adb.get_acl_set, self.device, acl_set)

    def tearDown(self):
        NetDevices._Singleton = None
开发者ID:ArnesSI,项目名称:trigger,代码行数:48,代码来源:test_acl_db.py

示例5: Commando

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]

#.........这里部分代码省略.........
                else:
                    #self.supported_platforms[vendor] = types
                    supported_platforms[vendor] = types
            else:
                raise exceptions.ImproperlyConfigured('Platforms for vendor %r not found. Please provide it at either the class level or using the arguments.' % vendor)

        return supported_platforms

    def _decrement_connections(self, data=None):
        """
        Self-explanatory. Called by _add_worker() as both callback/errback
        so we can accurately refill the jobs queue, which relies on the
        current connection count.
        """
        self.curr_conns -= 1
        return True

    def _increment_connections(self, data=None):
        """Increment connection count."""
        self.curr_conns += 1
        return True

    def _setup_jobs(self):
        """
        "Maps device hostnames to `~trigger.netdevices.NetDevice` objects and
        populates the job queue.
        """
        for dev in self.devices:
            if self.verbose:
                print 'Adding', dev

            # Make sure that devices are actually in netdevices and keep going
            try:
                devobj = self.nd.find(str(dev))
            except KeyError:
                if self.verbose:
                    msg = 'Device not found in NetDevices: %s' % dev
                    print 'ERROR:', msg

                # Track the errors and keep moving
                self.errors[dev] = msg
                continue

            # We only want to add devices for which we've enabled support in
            # this class
            if devobj.vendor not in self.vendors:
                raise exceptions.UnsupportedVendor("The vendor '%s' is not specified in ``vendors``. Could not add %s to job queue. Please check the attribute in the class object." % (devobj.vendor, devobj))

            self.jobs.append(devobj)

    def select_next_device(self, jobs=None):
        """
        Select another device for the active queue.

        Currently only returns the next device in the job queue. This is
        abstracted out so that this behavior may be customized, such as for
        future support for incremental callbacks.

        :param jobs:
            (Optional) The jobs queue. If not set, uses ``self.jobs``.

        :returns:
            A `~trigger.netdevices.NetDevice` object
        """
        if jobs is None:
            jobs = self.jobs
开发者ID:gurteshwar,项目名称:trigger,代码行数:70,代码来源:cmds.py

示例6: TestAclQueue

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class TestAclQueue(unittest.TestCase):
    def setUp(self):
        self.nd = NetDevices()
        _setup_aclsdb(self.nd)
        self.q = queue.Queue(verbose=False)
        self.acl = ACL_NAME
        self.acl_list = [self.acl]
        self.device = self.nd.find(DEVICE_NAME)
        self.device_name = DEVICE_NAME
        self.device_list = [self.device_name]
        self.user = USERNAME

    #
    # Integrated queue tests
    #

    def test_01_insert_integrated_success(self):
        """Test insert success into integrated queue"""
        self.assertTrue(self.q.insert(self.acl, self.device_list) is None)

    def test_02_insert_integrated_failure_device(self):
        """Test insert invalid device"""
        self.assertRaises(exceptions.TriggerError, self.q.insert, self.acl, ['bogus'])

    def test_03_insert_integrated_failure_acl(self):
        """Test insert devices w/ no ACL association"""
        self.assertRaises(exceptions.TriggerError, self.q.insert, 'bogus',
                          self.device_list)

    def test_04_list_integrated_success(self):
        """Test listing integrated queue"""
        self.q.insert(self.acl, self.device_list)
        expected = [(u'test1-abc.net.aol.com', u'foo')]
        self.assertEqual(sorted(expected), sorted(self.q.list()))

    def test_05_complete_integrated(self):
        """Test mark task complete"""
        self.q.complete(self.device_name, self.acl_list)
        expected = []
        self.assertEqual(sorted(expected), sorted(self.q.list()))

    def test_06_delete_integrated_with_devices(self):
        """Test delete ACL from queue providing devices"""
        self.q.insert(self.acl, self.device_list)
        self.assertTrue(self.q.delete(self.acl, self.device_list))

    def test_07_delete_integrated_no_devices(self):
        """Test delete ACL from queue without providing devices"""
        self.q.insert(self.acl, self.device_list)
        self.assertTrue(self.q.delete(self.acl))

    def test_08_remove_integrated_success(self):
        """Test remove (set as loaded) ACL from integrated queue"""
        self.q.insert(self.acl, self.device_list)
        self.q.remove(self.acl, self.device_list)
        expected = []
        self.assertEqual(sorted(expected), sorted(self.q.list()))

    def test_10_remove_integrated_failure(self):
        """Test remove (set as loaded) failure"""
        self.assertRaises(exceptions.ACLQueueError, self.q.remove, '', self.device_list)

    #
    # Manual queue tests
    #

    def test_11_insert_manual_success(self):
        """Test insert success into manual queue"""
        self.assertTrue(self.q.insert('manual task', None) is None)

    def test_12_list_manual_success(self):
        """Test list success of manual queue"""
        self.q.insert('manual task', None)
        expected = ('manual task', self.user)
        result = self.q.list('manual')
        actual = result[0][:2] # First tuple, items 0-1
        self.assertEqual(sorted(expected), sorted(actual))

    def test_13_delete_manual_success(self):
        """Test delete from manual queue"""
        self.q.delete('manual task')
        expected = []
        self.assertEqual(sorted(expected), sorted(self.q.list('manual')))

    #
    # Generic tests
    #

    def test_14_delete_failure(self):
        """Test delete of task not in queue"""
        self.assertFalse(self.q.delete('bogus'))

    def test_15_list_invalid(self):
        """Test list of invalid queue name"""
        self.assertFalse(self.q.list('bogus'))

    # Teardown

    def test_ZZ_cleanup_db(self):
        """Cleanup the temp database file"""
#.........这里部分代码省略.........
开发者ID:ArnesSI,项目名称:trigger,代码行数:103,代码来源:test_acl_queue.py

示例7: Commando

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]

#.........这里部分代码省略.........
                    #self.supported_platforms[vendor] = types
                    supported_platforms[vendor] = types
            else:
                raise exceptions.ImproperlyConfigured('Platforms for vendor %r not found. Please provide it at either the class level or using the arguments.' % vendor)

        return supported_platforms

    def _decrement_connections(self, data=None):
        """
        Self-explanatory. Called by _add_worker() as both callback/errback
        so we can accurately refill the jobs queue, which relies on the
        current connection count.
        """
        self.curr_conns -= 1
        return data

    def _increment_connections(self, data=None):
        """Increment connection count."""
        self.curr_conns += 1
        return True

    def _setup_jobs(self):
        """
        "Maps device hostnames to `~trigger.netdevices.NetDevice` objects and
        populates the job queue.
        """
        for dev in self.devices:
            log.msg('Adding', dev)
            if self.verbose:
                print 'Adding', dev

            # Make sure that devices are actually in netdevices and keep going
            try:
                devobj = self.nd.find(str(dev))
            except KeyError:
                msg = 'Device not found in NetDevices: %s' % dev
                log.err(msg)
                if self.verbose:
                    print 'ERROR:', msg

                # Track the errors and keep moving
                self.store_error(dev, msg)
                continue

            # We only want to add devices for which we've enabled support in
            # this class
            if devobj.vendor not in self.vendors:
                raise exceptions.UnsupportedVendor("The vendor '%s' is not specified in ``vendors``. Could not add %s to job queue. Please check the attribute in the class object." % (devobj.vendor, devobj))

            self.jobs.append(devobj)

    def select_next_device(self, jobs=None):
        """
        Select another device for the active queue.

        Currently only returns the next device in the job queue. This is
        abstracted out so that this behavior may be customized, such as for
        future support for incremental callbacks.

        If a device is determined to be invalid, you must return ``None``.

        :param jobs:
            (Optional) The jobs queue. If not set, uses ``self.jobs``.

        :returns:
            A `~trigger.netdevices.NetDevice` object or ``None``.
开发者ID:simudream,项目名称:trigger,代码行数:70,代码来源:cmds.py

示例8: AclsDB

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
__all__ = ['mock_redis']

# misc
from . import misc
from misc import *
__all__.extend(misc.__all__)

if __name__ == '__main__':
    os.environ['NETDEVICES_SOURCE'] = 'data/netdevices.xml'

    mock_redis.install()
    import redis
    from trigger.netdevices import NetDevices
    from trigger.acl.db import AclsDB

    r = redis.Redis()
    a = AclsDB()
    nd = NetDevices()

    dev = nd.find('test1-abc')

    print r.keys('*')
    print a.add_acl(dev, 'bacon')
    print r.keys('*')

    _k = 'acls:explicit:'
    key = _k + dev.nodeName

    print r.smembers(key)
开发者ID:ArnesSI,项目名称:trigger,代码行数:31,代码来源:__init__.py

示例9: TestNetDevicesWithAcls

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class TestNetDevicesWithAcls(unittest.TestCase):
    """
    Test NetDevices with ``settings.WITH_ACLs set`` to ``True``.
    """
    def setUp(self):
        self.nd = NetDevices()
        self.device = self.nd[DEVICE_NAME]
        self.device2 = self.nd[DEVICE2_NAME]
        self.nodename = self.device.nodeName
        self.device.explicit_acls = set(['test1-abc-only'])

    def test_basics(self):
        """Basic test of NetDevices functionality."""
        self.assertEqual(len(self.nd), 2)
        self.assertEqual(self.device.nodeName, self.nodename)
        self.assertEqual(self.device.manufacturer, 'JUNIPER')

    def test_aclsdb(self):
        """Test acls.db handling."""
        self.assertTrue('test1-abc-only' in self.device.explicit_acls)

    def test_autoacls(self):
        """Test autoacls.py handling."""
        self.assertTrue('router-protect.core' in self.device.implicit_acls)

    def test_find(self):
        """Test the find() method."""
        self.assertEqual(self.nd.find(self.nodename), self.device)
        nodebasename = self.nodename[:self.nodename.index('.')]
        self.assertEqual(self.nd.find(nodebasename), self.device)
        self.assertRaises(KeyError, lambda: self.nd.find(self.nodename[0:3]))

    def test_all(self):
        """Test the all() method."""
        expected = [self.device, self.device2]
        self.assertEqual(sorted(expected), sorted(self.nd.all()))

    def test_search(self):
        """Test the search() method."""
        expected = [self.device]
        self.assertEqual([self.device], self.nd.search(self.nodename))
        self.assertEqual(self.nd.all(), self.nd.search('17', field='onCallID'))

    def test_match(self):
        """Test the match() method."""
        self.assertEqual([self.device], self.nd.match(nodename=self.nodename))
        self.assertEqual(self.nd.all(), self.nd.match(vendor='juniper'))
        self.assertEqual([], self.nd.match(vendor='cisco'))

    def test_multiple_filter_match(self):
        """Test that passing multiple kwargs filters properly."""
        # There should be only one Juniper router.
        self.assertEqual(
            self.nd.match(nodename='test1-abc'),
            self.nd.match(vendor='juniper', devicetype='router')
        )

        # And only one Juniper switch.
        self.assertEqual(
            self.nd.match(nodename='test2-abc'),
            self.nd.match(vendor='juniper', devicetype='switch')
        )

    def test_match_with_null_value(self):
        """Test the match() method when attr value is ``None``."""
        self.device.site = None  # Zero it out!
        expected = [self.device]

        # None raw
        self.assertEqual(expected, self.nd.match(site=None))

        # "None" string
        self.assertEqual(expected, self.nd.match(site='None'))

        # Case-insensitive attr *and* value
        self.assertEqual(expected, self.nd.match(SITE='NONE'))

    def tearDown(self):
        _reset_netdevices()
开发者ID:cyclops3590,项目名称:trigger,代码行数:81,代码来源:test_netdevices.py

示例10: NetDevices

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
import sys
from time import sleep
from twisted.internet.defer import Deferred
from zope.interface import implements
from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.internet.defer import succeed
from twisted.web.iweb import IBodyProducer
# from twisted.python import log
# log.startLogging(sys.stdout, setStdout=False)
from trigger.netdevices import NetDevices

# Create reference to upgraded switch.
nd = NetDevices()
dev = nd.find('arista-sw1.demo.local')

# Create payload body
class StringProducer(object):
    implements(IBodyProducer)

    def __init__(self, body):
        self.body = body
        self.length = len(body)

    def startProducing(self, consumer):
        consumer.write(self.body)
        return succeed(None)

    def pauseProducing(self):
        pass
开发者ID:anl-cyberscience,项目名称:trigger,代码行数:33,代码来源:sshendpoint_updatecmdb.py

示例11: Queue

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class Queue(object):
    """
    Interacts with firewalls database to insert/remove items into the queue. You
    may optionally suppress informational messages by passing ``verbose=False``
    to the constructor.

    :param verbose: Toggle verbosity
    :type verbose: Boolean
    """
    def __init__(self, verbose=True):
        self.dbconn = self._get_firewall_db_conn()
        self.cursor = self.dbconn.cursor()
        self.nd = NetDevices()
        self.verbose = verbose

    def _get_firewall_db_conn(self):
        """Returns a MySQL db connection used for the ACL queues using database
        settings found withing ``settings.py``."""
        if MySQLdb is None:
            raise RuntimeError("You must install ``MySQL-python`` to use the queue")
        try:
            return MySQLdb.connect(host=settings.DATABASE_HOST,
                                   db=settings.DATABASE_NAME,
                                   port=settings.DATABASE_PORT,
                                   user=settings.DATABASE_USER,
                                   passwd=settings.DATABASE_PASSWORD)
        # catch if we can't connect, and shut down
        except MySQLdb.OperationalError as e:
            sys.exit("Can't connect to the database - %s (error %d)" % (e[1],e[0]))

    def _normalize(self, arg):
        if arg.startswith('acl.'):
            arg = arg[4:]
        escalation = False
        if arg.upper().endswith(' ESCALATION'):
            escalation = True
            arg = arg[:-11]
        return (escalation, arg)

    def insert(self, acl, routers, escalation=False):
        """
        Insert an ACL and associated devices into the ACL load queue.  

        Attempts to insert into integrated queue.  If ACL test fails, then 
        item is inserted into manual queue.
        """
        assert acl, 'no ACL defined'
        if not routers: 
            routers = []

        (escalation, acl) = self._normalize(acl)
        if len(routers):
            for router in routers:
                try:
                    dev = self.nd.find(router)
                except KeyError:
                    raise  "Could not find %s in netdevices" % router
                    return
                if acl not in dev.acls:
                    raise "Could not find %s in %s's acl list" % (acl, router)
                    return

                self.cursor.execute('''insert into acl_queue 
                                        (acl, router, queued, escalation) 
                                        values (%s, %s, now(), %s)''', 
                                        (acl, router, escalation))

            if self.verbose:
                print 'ACL', acl, 'injected into integrated load queue for',
                print ', '.join([dev[:dev.find('.')] for dev in routers])

        else:
            self.cursor.execute('''insert into queue (q_name, login) values (%s, %s)''',
                                    (acl, os.getlogin()))
            if self.verbose: print '"%s" injected into manual load queue' % acl

        self.dbconn.commit()

    def delete(self, acl, routers=None, escalation=False):
        """
        Delete an ACL from the firewall database queue.

        Attempts to delete from integrated queue.  If ACL test fails, then 
        item is deleted from manual queue.
        """
        assert acl, 'no ACL defined' 
        (escalation, acl) = self._normalize(acl)

        if routers is not None:
            devs = routers
        else:
            if self.verbose: print 'fetching routers from database'
            self.cursor.execute('''select distinct router from acl_queue
                                where acl = %s and loaded is null
                                order by router''', (acl,))
            rows = self.cursor.fetchall()
            devs = [row[0] for row in rows] or []

        if len(devs):
            for dev in devs:
#.........这里部分代码省略.........
开发者ID:altoplano,项目名称:trigger,代码行数:103,代码来源:queue.py

示例12: Queue

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]
class Queue(object):
    """
    Interacts with firewalls database to insert/remove items into the queue.

    :param verbose:
        Toggle verbosity

    :type verbose:
        Boolean
    """
    def __init__(self, verbose=True):
        self.nd = NetDevices()
        self.verbose = verbose
        self.login = get_user()

    def vprint(self, msg):
        """
        Print something if ``verbose`` instance variable is set.

        :param msg:
            The string to print
        """
        if self.verbose:
            print msg

    def get_model(self, queue):
        """
        Given a queue name, return its DB model.

        :param queue:
            Name of the queue whose object you want
        """
        return models.MODEL_MAP.get(queue, None)

    def create_task(self, queue, *args, **kwargs):
        """
        Create a task in the specified queue.

        :param queue:
            Name of the queue whose object you want
        """
        model = self.get_model(queue)
        taskobj = model.create(*args, **kwargs)

    def _normalize(self, arg, prefix=''):
        """
        Remove ``prefix`` from ``arg``, and set "escalation" bit.

        :param arg:
            Arg (typically an ACL filename) to trim

        :param prefix:
            Prefix to trim from arg
        """
        if arg.startswith(prefix):
            arg = arg[len(prefix):]
        escalation = False
        if arg.upper().endswith(' ESCALATION'):
            escalation = True
            arg = arg[:-11]
        return (escalation, arg)

    def insert(self, acl, routers, escalation=False):
        """
        Insert an ACL and associated devices into the ACL load queue.

        Attempts to insert into integrated queue. If ACL test fails, then
        item is inserted into manual queue.

        :param acl:
            ACL name

        :param routers:
            List of device names

        :param escalation:
            Whether this is an escalated task
        """
        if not acl:
            raise exceptions.ACLQueueError('You must specify an ACL to insert into the queue')
        if not routers:
            routers = []

        escalation, acl = self._normalize(acl)
        if routers:
            for router in routers:
                try:
                    dev = self.nd.find(router)
                except KeyError:
                    msg = 'Could not find device %s' % router
                    raise exceptions.TriggerError(msg)

                if acl not in dev.acls:
                    msg = "Could not find %s in ACL list for %s" % (acl, router)
                    raise exceptions.TriggerError(msg)

                self.create_task(queue='integrated', acl=acl, router=router,
                                 escalation=escalation)

            self.vprint('ACL %s injected into integrated load queue for %s' %
#.........这里部分代码省略.........
开发者ID:aakapoor,项目名称:trigger,代码行数:103,代码来源:queue.py

示例13: Commando

# 需要导入模块: from trigger.netdevices import NetDevices [as 别名]
# 或者: from trigger.netdevices.NetDevices import find [as 别名]

#.........这里部分代码省略.........
            'ARISTA NETWORKS':[dev, execute_ioslike,
                              self.generate_arista_cmd,
                              self.arista_parse],
            'BROCADE':       [dev, execute_ioslike,
                              self.generate_brocade_cmd,
                              self.brocade_parse],
            'CISCO SYSTEMS': [dev, execute_ioslike,
                              self.generate_ios_cmd,
                              self.ios_parse],
            'CITRIX':        [dev, execute_netscaler,
                              self.generate_netscaler_cmd,
                              self.netscaler_parse],
            'DELL':          [dev, execute_ioslike,
                              self.generate_dell_cmd,
                              self.dell_parse],
            'FOUNDRY':       [dev, execute_ioslike,
                              self.generate_foundry_cmd,
                              self.foundry_parse],
            'JUNIPER':       [dev, execute_junoscript,
                              self.generate_junos_cmd,
                              self.junos_parse],
        }
        result = callback_map[dev.manufacturer]

        return result

    def _setup_jobs(self):
        for dev in self.devices:
            if self.verbose:
                print 'Adding', dev

            # Make sure that devices are actually in netdevices and keep going
            try:
                devobj = self.nd.find(str(dev))
            except KeyError:
                msg = 'Device not found in NetDevices: %s' % dev
                if self.verbose:
                    print 'ERROR:', msg

                # Track the errors and keep moving
                self.errors[dev] = msg
                continue

            this_callback = self._setup_callback(devobj)
            self.jobs.append(this_callback)

    def run(self):
        """Nothing happens until you execute this to perform the actual work."""
        self._add_worker()
        self._start()

    def eb(self, x):
        self._decrement_connections(x)
        return True

    def _add_worker(self):
        work = None

        try:
            work = self.jobs.pop()
            if self.verbose:
                print 'Adding work to queue...'
        except (AttributeError, IndexError):
            #if not self.curr_connections:
            if not self.curr_connections and self.reactor_running:
                self._stop()
开发者ID:bwheatley,项目名称:trigger,代码行数:70,代码来源:cmds.py


注:本文中的trigger.netdevices.NetDevices.find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。