Extending SaltStack
上QQ阅读APP看书,第一时间看更新

The final module

When we put all of the preceding code together, we end up with the following module:

'''
This module should be saved as salt/modules/mysqltest.py
'''
import salt.utils

try:
    import MySQLdb
    HAS_LIBS = True
except ImportError:
    HAS_LIBS = False

import logging
log = logging.getLogger(__name__)

__func_alias__ = {
    'list_': 'list'
}


__virtualname__ = 'mysqltest'


def __virtual__():
    '''
    Check dependencies, using both methods from the chapter
    '''
    if not salt.utils.which('mysql'):
        return False

    if HAS_LIBS:
        return __virtualname__

    return False


def ping():
    '''
    Returns True

    CLI Example:
        salt '*' mysqltest.ping
    '''
    return True


def check_mysqld():
    '''
    Check to see if sshd is running and listening

    CLI Example:
        salt '*' testmodule.check_mysqld
    '''
    output = __salt__['cmd.run']('netstat -tulpn | grep mysqld', python_shell=True)
    if 'tcp' not in output:
        return False
    return True


def _get_conn():
    '''
    Get a database connection object
    '''
    user = __salt__['config.get']('mysql_user', 'root')
    passwd = __salt__['config.get']('mysql_pass', '')
    host = __salt__['config.get']('mysql_host', 'localhost')
    port = __salt__['config.get']('mysql_port', 3306)
    db_ = __salt__['config.get']('mysql_db', 'mysql')
    dbc = MySQLdb.connect(
        connection_user=user,
        connection_pass=passwd,
        connection_host=host,
        connection_port=port,
        connection_db=db_,
    )
    log.trace('Connected to the database')
    return dbc


def version():
    '''
    Returns MySQL Version

    CLI Example:
        salt '*' mysqltest.version
    '''
    dbc = _get_conn()
    cur = dbc.cursor()
    return cur.execute('SELECT VERSION()')


def list_(type_):
    '''
    List different resources in MySQL
    CLI Examples:
        salt '*' mysqltest.list tables
        salt '*' mysqltest.list databases
    '''
    dbc = _get_conn()
    cur = dbc.cursor()
    valid_types = ['tables', 'databases']
    if type_ not in valid_types:
        err_msg = 'A valid type was not specified'
        log.error(err_msg)
        raise CommandExecutionError(err_msg)
    return cur.execute('SHOW {0}()'.format(type_))