千家信息网

SaltStack源码分析之使用MongoDB模块

发表于:2024-11-27 作者:千家信息网编辑
千家信息网最后更新 2024年11月27日,MongoDB模块/usr/lib/python2.6/site-packages/salt/modules/mongodb.pyMongoDB模块会先去检查是否安装有PyMongo模块# -*- c
千家信息网最后更新 2024年11月27日SaltStack源码分析之使用MongoDB模块

MongoDB模块/usr/lib/python2.6/site-packages/salt/modules/mongodb.py

MongoDB模块会先去检查是否安装有PyMongo模块

# -*- coding: utf-8 -*-'''Module to provide MongoDB functionality to Salt:configuration: This module uses PyMongo, and accepts configuration details as    parameters as well as configuration settings::        mongodb.host: 'localhost'        mongodb.port: 27017        mongodb.user: ''        mongodb.password: ''    This data can also be passed into pillar. Options passed into opts will    overwrite options passed into pillar.'''
# Import python libsimport logging# Import salt libsfrom salt._compat import string_types# Import third party libstry:    import pymongo    HAS_MONGODB = Trueexcept ImportError:    HAS_MONGODB = Falselog = logging.getLogger(__name__)

引入logging模块处理日志,再引入salt._compat.string_types

对检查pymongo进行异常处理,如果导入pymongo成功,设置HAS_MONGODB变量为True,导入失败设置为False


def __virtual__():    '''    Only load this module if pymongo is installed    '''    if HAS_MONGODB:        return 'mongodb'    else:        return False


如果定义一个__virtual__函数,可以控制是否允许这个模块可见。如果返回False,SaltStack将会忽略这个模块,如果返回一个字符串,SaltStack将使用这个字符串。


def _connect(user=None, password=None, host=None, port=None, database='admin'):    '''    Returns a tuple of (user, host, port) with config, pillar, or default    values assigned to missing values.    '''    if not user:        user = __salt__['config.option']('mongodb.user')    if not password:        password = __salt__['config.option']('mongodb.password')    if not host:        host = __salt__['config.option']('mongodb.host')    if not port:        port = __salt__['config.option']('mongodb.port')    try:        conn = pymongo.connection.Connection(host=host, port=port)        mdb = pymongo.database.Database(conn, database)        if user and password:            mdb.authenticate(user, password)    except pymongo.errors.PyMongoError:        log.error('Error connecting to database {0}'.format(database))        return False    return conn


pymongo.connection.Connection

这个方法PyMongo已经弃用,使用新的MongoClient代替。



def db_list(user=None, password=None, host=None, port=None):    '''    List all Mongodb databases    CLI Example:    .. code-block:: bash        salt '*' mongodb.db_list        '''    conn = _connect(user, password, host, port)    if not conn:        return 'Failed to connect to mongo database'    try:        log.info('Listing databases')        return conn.database_names()    except pymongo.errors.PyMongoError as err:        log.error(err)        return str(err)

列出所有的MongoDB数据库

$ sudo salt '*' mongodb.db_list '' '' 10.10.41.17 28018localhost.localdomain:    'mongodb.db_list' is not available.gintama-qa-server:    - pay    - clan    - test    - game1    - admin    - gam_server_1

SaltStack会先去检测是否包含有PyMongo模块,如果有就执行没有就不执行。


def db_exists(name, user=None, password=None, host=None, port=None):    '''    Checks if a database exists in Mongodb    CLI Example:    .. code-block:: bash        salt '*' mongodb.db_exists         '''    dbs = db_list(user, password, host, port)    if isinstance(dbs, string_types):        return False    return name in dbs

检查一个库是否存在

$ sudo salt 'gintama-qa-server' mongodb.db_exists pay  '' '' 10.10.41.17 28018gintama-qa-server:    True$ sudo salt 'gintama-qa-server' mongodb.db_exists pay3  '' '' 10.10.41.17 28018gintama-qa-server:    False


def db_remove(name, user=None, password=None, host=None, port=None):    '''    Remove a Mongodb database    CLI Example:    .. code-block:: bash        salt '*' mongodb.db_remove         '''    conn = _connect(user, password, host, port)    if not conn:        return 'Failed to connect to mongo database'    try:        log.info('Removing database {0}'.format(name))        conn.drop_database(name)    except pymongo.errors.PyMongoError as err:        log.error(            'Removing database {0} failed with error: {1}'.format(                name, str(err)            )        )        return str(err)    return True

删除一个库


def user_list(user=None, password=None, host=None, port=None, database='admin'):    '''    List users of a Mongodb database    CLI Example:    .. code-block:: bash        salt '*' mongodb.user_list          '''    conn = _connect(user, password, host, port)    if not conn:        return 'Failed to connect to mongo database'    try:        log.info('Listing users')        mdb = pymongo.database.Database(conn, database)        output = []        for user in mdb.system.users.find():            output.append([                ('user', user['user']),                ('readOnly', user.get('readOnly', 'None'))            ])        return output    except pymongo.errors.PyMongoError as err:        log.error(            'Listing users failed with error: {0}'.format(                str(err)            )        )        return str(err)

列出账号



def user_exists(name, user=None, password=None, host=None, port=None,                database='admin'):    '''    Checks if a user exists in Mongodb    CLI Example:    .. code-block:: bash        salt '*' mongodb.user_exists          '''    users = user_list(user, password, host, port, database)    for user in users:        if name == dict(user).get('user'):            return True    return False

查看账号是否存在



def user_create(name, passwd, user=None, password=None, host=None, port=None,                database='admin'):    '''    Create a Mongodb user    CLI Example:    .. code-block:: bash        salt '*' mongodb.user_create          '''    conn = _connect(user, password, host, port)    if not conn:        return 'Failed to connect to mongo database'    try:        log.info('Creating user {0}'.format(name))        mdb = pymongo.database.Database(conn, database)        mdb.add_user(name, passwd)    except pymongo.errors.PyMongoError as err:        log.error(            'Creating database {0} failed with error: {1}'.format(                name, str(err)            )        )        return str(err)    return True

创建账号

def user_remove(name, user=None, password=None, host=None, port=None,                database='admin'):    '''    Remove a Mongodb user    CLI Example:    .. code-block:: bash        salt '*' mongodb.user_remove          '''    conn = _connect(user, password, host, port)    if not conn:        return 'Failed to connect to mongo database'    try:        log.info('Removing user {0}'.format(name))        mdb = pymongo.database.Database(conn, database)        mdb.remove_user(name)    except pymongo.errors.PyMongoError as err:        log.error(            'Creating database {0} failed with error: {1}'.format(                name, str(err)            )        )        return str(err)    return True



测试情况

$ sudo salt 'gintama-qa-server' mongodb.user_create gintama gintama123 '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:    True$ sudo salt 'gintama-qa-server' mongodb.user_exists gintama  '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:    True$ sudo salt 'gintama-qa-server' mongodb.user_list   '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:    |_      |_        - user        - gintama      |_        - readOnly        - None$ sudo salt 'gintama-qa-server' mongodb.user_remove gintama  '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:    True$ sudo salt 'gintama-qa-server' mongodb.user_list   '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:$ sudo salt 'gintama-qa-server' mongodb.user_exists gintama  '' '' 10.10.41.17 28018 taiwan_game1gintama-qa-server:    False


0