<commit_before>#coding=utf-8

"""
Database interface for automated ACL queue. Used primarily by ``load_acl`` and
``acl``` commands for manipulating the work queue. 

    >>> from trigger.acl.queue import Queue
    >>> q = Queue()
    >>> q.list()
    (('dc1-abc.net.aol.com', 'datacenter-protect'), ('dc2-abc.net.aol.com',
    'datacenter-protect'))
"""

__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright 2010-2011, AOL Inc.'

import os
import sys
from trigger.conf import settings
from trigger.netdevices import NetDevices
import MySQLdb

# Exports
__all__ = ('Queue', 'QueueError',)

# Exceptions
class QueueError(Exception): pass

# Classes
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``."""
        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 = []
<commit_msg>Conditionally import MySQLdb so we can still do testing without it.<commit_after>#coding=utf-8

"""
Database interface for automated ACL queue. Used primarily by ``load_acl`` and
``acl``` commands for manipulating the work queue. 

    >>> from trigger.acl.queue import Queue
    >>> q = Queue()
    >>> q.list()
    (('dc1-abc.net.aol.com', 'datacenter-protect'), ('dc2-abc.net.aol.com',
    'datacenter-protect'))
"""

__author__ = '<NAME>'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright 2010-2011, AOL Inc.'

import os
import sys
from trigger.conf import settings
from trigger.netdevices import NetDevices
try:
    import MySQLdb
except ImportError:
    MySQLdb = None

# Exports
__all__ = ('Queue', 'QueueError',)

# Exceptions
class QueueError(Exception): pass

# Classes
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 = []

{'fraction_non_alphanumeric': 0.10398613518197573, 'fraction_numerical': 0.006162141344117081, 'mean_word_length': 2.3423423423423424, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4292995', 'n_tokens_mistral': 1547, 'n_tokens_neox': 1446, 'n_words': 454}