"""
Cobbler's Mongo database based object serializer.
Experimental version.
"""
from past.builtins import cmp
from future import standard_library
standard_library.install_aliases()
from configparser import ConfigParser
pymongo_loaded = False
try:
from pymongo import Connection
pymongo_loaded = True
except:
# FIXME: log message
pass
import yaml
from cobbler.cexceptions import CX
mongodb = None
def __connect():
cp = ConfigParser()
cp.read("/etc/cobbler/mongodb.conf")
host = cp.get("connection", "host")
port = int(cp.get("connection", "port"))
# TODO: detect connection error
global mongodb
try:
mongodb = Connection(host, port)['cobbler']
except:
# FIXME: log error
raise CX("Unable to connect to Mongo database")
[docs]def register():
"""
The mandatory cobbler module registration hook.
"""
# FIXME: only run this if enabled.
if not pymongo_loaded:
return ""
return "serializer"
[docs]def what():
"""
Module identification function
"""
return "serializer/mongodb"
[docs]def serialize_item(collection, item):
"""
Save a collection item to database
@param Collection collection collection
@param Item item collection item
"""
__connect()
collection = mongodb[collection.collection_type()]
data = collection.find_one({'name': item.name})
if data:
collection.update({'name': item.name}, item.to_dict())
else:
collection.insert(item.to_dict())
[docs]def serialize_delete(collection, item):
"""
Delete a collection item from database
@param Collection collection collection
@param Item item collection item
"""
__connect()
collection = mongodb[collection.collection_type()]
collection.remove({'name': item.name})
[docs]def serialize(collection):
"""
Save a collection to database
@param Collection collection collection
"""
# TODO: error detection
ctype = collection.collection_type()
if ctype != "settings":
for x in collection:
serialize_item(collection, x)
[docs]def deserialize_raw(collection_type):
# FIXME: code to load settings file should not be replicated in all
# serializer subclasses
if collection_type == "settings":
fd = open("/etc/cobbler/settings")
_dict = yaml.safe_load(fd.read())
fd.close()
return _dict
else:
__connect()
collection = mongodb[collection_type]
return collection.find()
[docs]def deserialize(collection, topological=True):
"""
Load a collection from database
@param Collection collection collection
@param bool topological
"""
datastruct = deserialize_raw(collection.collection_type())
if topological and type(datastruct) == list:
datastruct.sort(__depth_cmp)
if type(datastruct) == dict:
collection.from_dict(datastruct)
elif type(datastruct) == list:
collection.from_list(datastruct)
def __depth_cmp(item1, item2):
d1 = item1.get("depth", 1)
d2 = item2.get("depth", 1)
return cmp(d1, d2)
# EOF