Added initial version of mongodb module and state

This commit is contained in:
Bas Tichelaar 2012-08-07 22:19:30 +02:00
parent 3104549991
commit c61ec74969
3 changed files with 327 additions and 0 deletions

166
salt/modules/mongodb.py Normal file
View File

@ -0,0 +1,166 @@
'''
Module to provide MongoDB functionality to Salt
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 logging
# Import third party libs
try:
import pymongo
has_mongodb = True
except ImportError:
has_mongodb = False
log = logging.getLogger(__name__)
__opts__ = {}
def __virtual__():
'''
Only load this module if pymongo is installed
'''
if has_mongodb:
return 'mongodb'
else:
return False
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 = __opts__.get('mongodb.user') or __pillar__.get('mongodb.user')
if not password:
password = __opts__.get('mongodb.password') or __pillar__.get('mongodb.password')
if not host:
host = __opts__.get('mongodb.host') or __pillar__.get('mongodb.host')
if not port:
port = __opts__.get('mongodb.port') or __pillar__.get('mongodb.port')
try:
conn = pymongo.connection.Connection(host=host, port=port)
db = pymongo.database.Database(conn, database)
if user and password:
db.authenticate(user, password)
except pymongo.errors.PyMongoError as e:
log.error("Error connecting to database {0}".format(database.message))
return False
return conn
def db_list(user=None, password=None, host=None, port=None):
'''
List all Mongodb databases
'''
conn = _connect(user, password, host, port)
try:
log.info("Listing databases")
return conn.database_names()
except pymongo.errors.PyMongoError as e:
log.error(e)
return e.message
def db_exists(name, user=None, password=None, host=None, port=None, database="admin"):
'''
Checks if a database exists in Mongodb
'''
dbs = db_list(user, password, host, port)
for db in dbs:
if name == db:
return True
return False
def db_remove(name, user=None, password=None, host=None, port=None):
'''
Remove a Mongodb database
'''
conn = _connect(user, password, host, port)
try:
log.info("Removing database {0}".format(name))
conn.drop_database(name)
except pymongo.errors.PyMongoError as e:
log.error("Removing database {0} failed with error: {1}".format(
name, e.message))
return e.message
return True
def user_list(user=None, password=None, host=None, port=None, database="admin"):
'''
List users of a Mongodb database
'''
conn = _connect(user, password, host, port)
try:
log.info("Listing users")
db = pymongo.database.Database(conn, database)
output = []
for user in db.system.users.find():
output.append([("user", user['user']), ("readOnly", user['readOnly'])])
return output
except pymongo.errors.PyMongoError as e:
log.error("Listing users failed with error: {0}".format(e.message))
return e.message
def user_exists(name, user=None, password=None, host=None, port=None, database="admin"):
'''
Checks if a user exists in Mongodb
'''
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
'''
conn = _connect(user, password, host, port)
try:
log.info("Creating user {0}".format(name))
db = pymongo.database.Database(conn, database)
db.add_user(name, passwd)
except pymongo.errors.PyMongoError as e:
log.error("Creating database {0} failed with error: {1}".format(
name, e.message))
return e.message
return True
def user_remove(name, user=None, password=None, host=None, port=None, database="admin"):
'''
Remove a Mongodb user
'''
conn = _connect(user, password, host, port)
try:
log.info("Removing user {0}".format(name))
db = pymongo.database.Database(conn, database)
db.remove_user(name)
except pymongo.errors.PyMongoError as e:
log.error("Creating database {0} failed with error: {1}".format(
name, e.message))
return e.message
return True

View File

@ -0,0 +1,51 @@
'''
Management of Mongodb databases
Only deletion is supported, creation doesnt make sense
and can be done using mongodb_user.present
'''
def absent(name,
user=None,
password=None,
host=None,
port=None):
'''
Ensure that the named database is absent
name
The name of the database to remove
user
The user to connect as (must be able to create the user)
password
The password of the user
host
The host to connect to
port
The port to connect to
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
#check if database exists and remove it
if __salt__['mongodb.db_exists'](name, user, password, host, port):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('Database {0} is present and needs to be removed'
).format(name)
return ret
if __salt__['mongodb.db_remove'](name, user, password, host, port):
ret['comment'] = 'Database {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
# fallback
ret['comment'] = ('User {0} is not present, so it cannot be removed'
).format(name)
return ret

110
salt/states/mongodb_user.py Normal file
View File

@ -0,0 +1,110 @@
'''
Management of Mongodb users
===========================
'''
def present(name,
passwd,
database="admin",
user=None,
password=None,
host=None,
port=None):
'''
Ensure that the user is present with the specified properties
name
The name of the user to manage
passwd
The password of the user
user
The user to connect as (must be able to create the user)
password
The password of the user
host
The host to connect to
port
The port to connect to
database
The database to create the user in (if the db doesn't exist, it will be created)
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is already present'.format(name)}
# check if user exists
if __salt__['mongodb.user_exists'](name, user, password, host, port):
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('User {0} is not present and needs to be created'
).format(name)
return ret
# The user is not present, make it!
if __salt__['mongodb.user_create'](name, passwd, user, password, host, port, database=database):
ret['comment'] = 'User {0} has been created'.format(name)
ret['changes'][name] = 'Present'
else:
ret['comment'] = 'Failed to create database {0}'.format(name)
ret['result'] = False
return ret
def absent(name,
user=None,
password=None,
host=None,
port=None,
database="admin"):
'''
Ensure that the named user is absent
name
The name of the user to remove
user
The user to connect as (must be able to create the user)
password
The password of the user
host
The host to connect to
port
The port to connect to
database
The database to create the user in (if the db doesn't exist, it will be created)
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
#check if user exists and remove it
if __salt__['mongodb.user_exists'](name, user, password, host, port, database=database):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('User {0} is present and needs to be removed'
).format(name)
return ret
if __salt__['mongodb.user_remove'](name, user, password, host, port, database=database):
ret['comment'] = 'User {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
# fallback
ret['comment'] = ('User {0} is not present, so it cannot be removed'
).format(name)
return ret