1
0
mirror of https://github.com/dkmstr/openuds.git synced 2024-12-22 13:34:04 +03:00

* Efectively remove support for thick client from current version (code

removed)
This commit is contained in:
Adolfo Gómez García 2014-09-15 10:23:56 +02:00
parent 3562e4ca56
commit 084ad39fc9
30 changed files with 0 additions and 3038 deletions

View File

@ -1,206 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _, activate
from django.contrib.sessions.backends.db import SessionStore
from uds.models import Authenticator
from uds.xmlrpc.util.Exceptions import AuthException
from uds.core.util.Config import GlobalConfig
from uds.core.util import log
from uds.core.auths.auth import authenticate
from functools import wraps
from django.conf import settings
import logging
logger = logging.getLogger(__name__)
ADMIN_AUTH = '#'
CLIENT_VERSION_REQUIRED = '1.4.0'
class Credentials(object):
'''
Represents a valid credential from a user connected to administration.
'''
def __init__(self, request, session, credential_key):
self.request = request
self.idAuth = session['idAuth']
self.isAdmin = session['isAdmin']
self.user = session['username']
self.locale = session['locale']
self.key = credential_key
def __unicode__(self):
return "authId: {0}, isAdmin: {1}, user: {2}, locale: {3}, key: {4}".format(self.idAuth, self.isAdmin, self.user, self.locale, self.key)
def __str__(self):
return "authId: {0}, isAdmin: {1}, user: {2}, locale: {3}, key: {4}".format(self.idAuth, self.isAdmin, self.user, self.locale, self.key)
def logout(self):
'''
Logout administration user
'''
logger.info('Logged out admin user {0}'.format(self))
if self.idAuth == ADMIN_AUTH: # Root administrator does nothing on logout
return ''
try:
a = Authenticator.objects.get(pk=self.idAuth).getInstance()
log.doLog(self.user, log.INFO, 'Logged out from administration', log.WEB)
return a.logout(self.user)
except Exception:
logger.exception('Exception at logout (managed)')
return ''
def makeCredentials(idAuth, username, locale, isAdmin):
session = SessionStore()
session.set_expiry(GlobalConfig.ADMIN_IDLE_TIME.getInt())
session['idAuth'] = idAuth
session['username'] = username
session['locale'] = locale
session['isAdmin'] = isAdmin
session.save()
return { 'credentials' : session.session_key, 'versionRequired' : CLIENT_VERSION_REQUIRED, 'url' : settings.STATIC_URL + "bin/UDSAdminSetup.exe",
'urlLinux' : settings.STATIC_URL + "bin/UDSAdminSetup.tar.gz", 'isAdmin' : isAdmin }
# Decorator for validate credentials
def needs_credentials(xmlrpc_func):
'''
Validates the credentials
'''
@wraps(xmlrpc_func)
def _wrapped_xmlrcp_func(credentials, *args, **kwargs):
# We expect that request is passed in as last argument ALWAYS (look at views)
args = list(args)
request = args.pop() # Last argumment is request
args = tuple(args)
logger.debug('Checkin credentials {0} for function {1}'.format(credentials, xmlrpc_func.__name__))
cred = validateCredentials(request, credentials)
if cred is not None:
logger.debug('Credentials valid, executing')
return xmlrpc_func(cred, *args, **kwargs)
raise AuthException(_('Credentials no longer valid'))
return _wrapped_xmlrcp_func
def validateCredentials(request, credentials):
'''
Validates the credentials of an user
:param credentials:
'''
session = SessionStore(session_key=credentials)
if session.exists(credentials) is False:
return None
if session.has_key('idAuth') is False:
return None
activate(session['locale'])
logger.debug('Locale activated')
# Updates the expire key, this is the slow part as we can see at debug log, better if we can only update the expire_key this takes 80 ms!!!
session.save()
logger.debug('Session updated')
return Credentials(request, session, credentials)
def invalidateCredentials(credentials):
session = SessionStore(session_key=credentials.key)
session.delete()
def getAdminAuths(locale):
'''
Returns the authenticators
'''
activate(locale)
res = []
for a in Authenticator.all():
if a.getType().isCustom() is False:
res.append({ 'id' : str(a.id), 'name' : a.name })
return res + [ {'id' : ADMIN_AUTH, 'name' : _('Administration') }]
# Xmlrpc functions
def login(username, password, idAuth, locale, request):
'''
Validates the user/password credentials, assign to it the specified locale for this session and returns a credentials response
'''
logger.info("Validating user {0} with authenticator {1} with locale {2}".format(username, idAuth, locale))
activate(locale)
if idAuth == ADMIN_AUTH:
if GlobalConfig.SUPER_USER_LOGIN.get(True) == username and GlobalConfig.SUPER_USER_PASS.get(True) == password:
return makeCredentials(idAuth, username, locale, True)
else:
raise AuthException(_('Invalid credentials'))
try:
auth = Authenticator.objects.get(pk=idAuth)
user = authenticate(username, password, auth)
except Exception:
raise AuthException(_('Invalid authenticator'))
if user is None:
log.doLog(auth, log.ERROR, 'Invalid credentials for {0} from {1}'.format(username, request.ip), log.ADMIN)
try:
user = auth.users.get(name=username)
log.doLog(user, log.ERROR, 'Invalid credentials from {0}'.format(request.ip), log.ADMIN)
except:
pass
raise AuthException(_('Access denied'))
if user.staff_member is False:
log.doLog(auth, log.ERROR, 'Access denied from {1}. User {0} is not membef of staff'.format(username, request.ip), log.ADMIN)
log.doLog(user, log.ERROR, 'Access denied from {0}. This user is not membef of staff'.format(request.ip), log.ADMIN)
raise AuthException(_('Access denied'))
log.doLog(auth, log.INFO, 'Access granted to user {0} from {1} to administration'.format(username, request.ip), log.ADMIN)
log.doLog(user, log.INFO, 'Access granted from {0} to administration'.format(request.ip), log.ADMIN)
return makeCredentials(idAuth, username, locale, user.is_admin)
@needs_credentials
def logout(credentials):
'''
Logs out and administration user
'''
ret = credentials.logout() or ''
invalidateCredentials(credentials)
return ret
def registerAdminAuthFunctions(dispatcher):
dispatcher.register_function(login, 'login')
dispatcher.register_function(getAdminAuths, 'getAdminAuths')
dispatcher.register_function(logout, 'logout')

View File

@ -1,279 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from django.db import IntegrityError
from uds.models import Authenticator
from Groups import getRealGroups
from uds.xmlrpc.util.Helpers import dictFromData
from uds.xmlrpc.util.Exceptions import InsertException, ParametersException, FindException, ValidationException
from uds.core.auths.Exceptions import AuthenticatorException
from uds.core import auths
from AdminAuth import needs_credentials
from uds.core.Environment import Environment
import logging
logger = logging.getLogger(__name__)
def dictFromAuthType(type_):
'''
Returns a dictionary that describes the authenticator, so the administration
interface has the info to handle it.
Args:
type_: Authenticator type (class) where to get information
Returns:
Dictionary describing the Authenticator type
'''
return { 'name' : type_.name(), 'type' : type_.type(), 'description' : type_.description(),
'icon' : type_.icon(), 'isExternalSource' : type_.isExternalSource,
'canSearchUsers' : type_.searchUsers != auths.Authenticator.searchUsers,
'canSearchGroups' : type_.searchGroups != auths.Authenticator.searchGroups,
'needsPassword' : type_.needsPassword, 'userNameLabel' : _(type_.userNameLabel),
'groupNameLabel' : _(type_.groupNameLabel), 'passwordLabel' : _(type_.passwordLabel),
'canCreateUsers' : type_.createUser != auths.Authenticator.createUser,
}
@needs_credentials
def getAuthenticatorsTypes(credentials):
'''
Returns the types of authenticators registered in system
'''
res = []
for _type in auths.factory().providers().values():
res.append(dictFromAuthType(_type))
return res
@needs_credentials
def getAuthenticators(credentials):
'''
Returns the services providers managed (at database)
'''
logger.debug("Returning authenticators...")
res = []
for auth in Authenticator.objects.all().order_by('priority'):
try:
val = { 'id' : str(auth.id), 'name' : auth.name, 'comments' : auth.comments, 'type' : auth.data_type, 'typeName' : auth.getInstance().name(),
'priority' : str(auth.priority), 'smallName' : auth.small_name }
res.append(val)
except Exception, e:
logger.debug("Exception: {0}".format(e))
return res
@needs_credentials
def getAuthenticatorType(credentials, id):
'''
Return the type of an authenticator
'''
logger.debug('Returning authenticator type')
try:
auth = Authenticator.objects.get(pk=id)
logger.debug('Auth: {0}'.format(auth))
return dictFromAuthType(auths.factory().lookup(auth.data_type))
except Authenticator.DoesNotExist:
raise InsertException(_('Authenticator does not exists'))
@needs_credentials
def getAuthenticatorGui(credentials, type):
'''
Returns the description of an gui for the specified authenticator
'''
logger.debug('Authenticator type requested: {0}'.format(type))
authType = auths.factory().lookup(type)
return authType.guiDescription()
@needs_credentials
def getAuthenticator(credentials, id):
'''
Returns the specified authenticator (at database)
'''
data = Authenticator.objects.get(pk=id)
res = [
{ 'name' : 'name', 'value' : data.name },
{ 'name' : 'comments', 'value' : data.comments },
{ 'name' : 'priority', 'value' : str(data.priority)}
]
for key, value in data.getInstance().valuesDict().iteritems():
valtext = 'value'
if value.__class__ == list:
valtext = 'values'
val = {'name' : key, valtext : value }
res.append(val)
return res
@needs_credentials
def getAuthenticatorGroups(credentials, id):
'''
'''
return getRealGroups(id)
@needs_credentials
def createAuthenticator(credentials, type, data):
'''
Creates a new authenticator with specified type and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
dict_ = dictFromData(data)
# First create data without serialization, then serialies data with correct environment
dict_['_request'] = credentials.request
auth = None
try:
auth = Authenticator.objects.create(name=dict_['name'], comments=dict_['comments'],
data_type=type, priority=int(dict_['priority']), small_name=dict_['smallName'])
auth.data = auth.getInstance(dict_).serialize()
auth.save()
except auths.Authenticator.ValidationException as e:
auth.delete()
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dict_['name']))
except Exception as e:
logger.exception("Exception at createAuthenticator")
logger.error(auth)
if auth is not None:
auth.delete()
raise e
# Returns true always,
return True
@needs_credentials
def modifyAuthenticator(credentials, id, data):
'''
Modifies an existing service provider with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
try:
auth = Authenticator.objects.get(pk=id)
dict_ = dictFromData(data)
dict_['_request'] = credentials.request
a = auth.getInstance(dict_)
auth.data = a.serialize()
auth.name = dict_['name']
auth.comments = dict_['comments']
auth.priority = int(dict_['priority'])
auth.small_name = dict_['smallName']
auth.save()
except auths.Authenticator.ValidationException as e:
raise ValidationException(str(e))
except Exception as e:
logger.exception(e)
raise ValidationException(str(e))
return True
@needs_credentials
def removeAuthenticator(credentials, id):
'''
Removes from database authenticator with specified id
'''
Authenticator.objects.get(pk=id).delete()
return True
@needs_credentials
def testAuthenticator(credentials, type_, data):
'''
invokes the test function of the specified authenticator type, with the suplied data
'''
logger.debug("Testing authenticator, type: {0}, data:{1}".format(type, data))
authType = auths.factory().lookup(type_)
# We need an "temporary" environment to test this service
dict_ = dictFromData(data)
dict_['_request'] = credentials.request
res = authType.test(Environment.getTempEnv(), dict_)
return {'ok' : res[0], 'message' : res[1]}
@needs_credentials
def checkAuthenticator(credentials, id):
'''
Invokes the check function of the specified authenticator
'''
auth = Authenticator.objects.get(id=id)
a = auth.getInstance()
return a.check()
@needs_credentials
def searchAuthenticator(credentials, id, srchUser, srchString):
'''
Search for the users that match srchString
'''
logger.debug("srchUser: {0}".format(srchUser))
try:
auth = Authenticator.objects.get(pk=id).getInstance()
canDoSearch = srchUser is True and (auth.searchUsers != auths.Authenticator.searchUsers) or (auth.searchGroups != auths.Authenticator.searchGroups)
if canDoSearch is False:
raise ParametersException(_('Authenticator do not supports search'))
if srchUser is True:
return auth.searchUsers(srchString)
else:
return auth.searchGroups(srchString)
except Authenticator.DoesNotExist:
raise FindException(_('Specified authenticator do not exists anymore. Please, reload gui'))
except AuthenticatorException, e:
raise ParametersException(str(e))
raise FindException(_('BUG: Reached a point that should never have been reached!!!'))
def registerAuthenticatorFunctions(dispatcher):
dispatcher.register_function(getAuthenticatorsTypes, 'getAuthenticatorsTypes')
dispatcher.register_function(getAuthenticatorType, 'getAuthenticatorType')
dispatcher.register_function(getAuthenticators, 'getAuthenticators')
dispatcher.register_function(getAuthenticatorGui, 'getAuthenticatorGui')
dispatcher.register_function(getAuthenticator, 'getAuthenticator')
dispatcher.register_function(getAuthenticatorGroups, 'getAuthenticatorGroups')
dispatcher.register_function(createAuthenticator, 'createAuthenticator')
dispatcher.register_function(modifyAuthenticator, 'modifyAuthenticator')
dispatcher.register_function(removeAuthenticator, 'removeAuthenticator')
dispatcher.register_function(testAuthenticator, 'testAuthenticator')
dispatcher.register_function(checkAuthenticator, 'checkAuthenticator')
dispatcher.register_function(searchAuthenticator, 'searchAuthenticator')

View File

@ -1,185 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from uds.models import Group, Authenticator
from uds.core.util.State import State
from django.db import IntegrityError
from ..util.Exceptions import DuplicateEntryException, InsertException
from uds.core.auths.Exceptions import AuthenticatorException
from AdminAuth import needs_credentials
import logging
logger = logging.getLogger(__name__)
def dictFromGroup(grp):
state = True if grp.state == State.ACTIVE else False
dct = { 'idParent' : str(grp.manager.id), 'nameParent': grp.manager.name, 'id' : str(grp.id), 'name' : grp.name,
'comments' : grp.comments, 'active' : state, 'isMeta' : grp.is_meta }
if grp.is_meta is True:
dct['groupsIds'] = list(str(x.id) for x in grp.groups.all())
return dct
def getRealGroups(idParent):
auth = Authenticator.objects.get(pk=idParent)
res = []
for grp in auth.groups.order_by('name'):
try:
res.append(dictFromGroup(grp))
except Exception, e:
logger.debug(e)
return res
@needs_credentials
def getGroups(credentials, idParent):
'''
Returns the groups contained at idParent authenticator
'''
return getRealGroups(idParent)
@needs_credentials
def getGroup(__, id_):
'''
'''
grp = Group.objects.get(pk=id_)
return dictFromGroup(grp)
def __createSimpleGroup(grp):
auth = Authenticator.objects.get(pk=grp['idParent'])
state = State.ACTIVE if grp['active'] == True else State.INACTIVE
try:
authInstance = auth.getInstance()
authInstance.createGroup(grp) # Remenber, this throws an exception if there is an error
auth.groups.create(name=grp['name'], comments=grp['comments'], state=state, is_meta=False)
except IntegrityError:
raise DuplicateEntryException(grp['name'])
except AuthenticatorException, e:
logger.debug(e)
raise InsertException(str(e))
return True
def __createMetaGroup(grp):
auth = Authenticator.objects.get(pk=grp['idParent'])
state = State.ACTIVE if grp['active'] == True else State.INACTIVE
try:
group = auth.groups.create(name=grp['name'], comments=grp['comments'], state=state, is_meta=True)
group.groups = grp['groupsIds']
except IntegrityError:
raise DuplicateEntryException(grp['name'])
except AuthenticatorException, e:
logger.debug(e)
raise InsertException(str(e))
return True
@needs_credentials
def createGroup(credentials, grp):
'''
Creates a new group associated with an authenticator
'''
if grp['isMeta'] == False:
return __createSimpleGroup(grp)
return __createMetaGroup(grp)
def __modifySimpleGroup(grp):
try:
grp['state'] = State.ACTIVE if grp['active'] == True else State.INACTIVE
group = Group.objects.get(pk=grp['id'])
authInstance = group.manager.getInstance()
authInstance.modifyGroup(grp)
# group.name = grp['name']
group.comments = grp['comments']
group.state = grp['state']
group.is_meta = False;
group.groups.clear()
group.save()
except IntegrityError:
raise DuplicateEntryException(grp['name'])
except Exception as e:
logger.exception(e)
raise(InsertException(str(e)))
return True
def __modifyMetaGroup(grp):
try:
group = Group.objects.get(pk=grp['id'])
group.name = grp['name']
group.comments = grp['comments']
group.state = State.ACTIVE if grp['active'] == True else State.INACTIVE
group.is_meta = True
group.groups = grp['groupsIds']
group.save()
except IntegrityError:
raise DuplicateEntryException(grp['name'])
except Exception as e:
logger.exception(e)
raise(InsertException(str(e)))
return True
@needs_credentials
def modifyGroup(credentials, grp):
'''
Modifies an existing service provider with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
if grp['isMeta'] == False:
return __modifySimpleGroup(grp)
return __modifyMetaGroup(grp)
@needs_credentials
def removeGroups(credentials, ids):
'''
Deletes a group
'''
Group.objects.filter(id__in=ids).delete()
return True
@needs_credentials
def changeGroupsState(credentials, ids, newState):
'''
Changes the state of the specified group
'''
state = State.ACTIVE if newState == True else State.INACTIVE
Group.objects.filter(id__in=ids).update(state=state)
return True
# Registers XML RPC Methods
def registerGroupsFunctions(dispatcher):
dispatcher.register_function(getGroups, 'getGroups')
dispatcher.register_function(getGroup, 'getGroup')
dispatcher.register_function(createGroup, 'createGroup')
dispatcher.register_function(modifyGroup, 'modifyGroup')
dispatcher.register_function(removeGroups, 'removeGroups')
dispatcher.register_function(changeGroupsState, 'changeGroupsState')

View File

@ -1,59 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from uds.models import User
from uds.core.managers.UserPrefsManager import UserPrefsManager
from ..util.Helpers import dictFromData
from AdminAuth import needs_credentials
import logging
logger = logging.getLogger(__name__)
@needs_credentials
def getPrefsForUser(credentials, id):
user = User.objects.get(pk=id)
return UserPrefsManager().manager().getGuiForUserPreferences(user)
@needs_credentials
def setPrefsForUser(credentials, id, data):
user = User.objects.get(pk=id)
data = dictFromData(data)
logger.debug("Data: {0}".format(data))
UserPrefsManager().manager().processGuiForUserPreferences(user, data)
return False
def registerPreferencesFunctions(dispatcher):
dispatcher.register_function(getPrefsForUser, 'getPrefsForUser')
dispatcher.register_function(setPrefsForUser, 'setPrefsForUser')

View File

@ -1,204 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.db import IntegrityError
from uds.models import User as DbUser, Group as DbGroup, Authenticator as DbAuthenticator
from uds.core.managers.CryptoManager import CryptoManager
from uds.xmlrpc.util.Exceptions import DuplicateEntryException, InsertException, ParametersException, FindException
from AdminAuth import needs_credentials
from Groups import dictFromGroup
from uds.core.auths.User import User
import logging
logger = logging.getLogger(__name__)
INVALID_PASS = '@#&&/%&$%&/adffa'
def dictFromUser(usr, groups = None):
dct = { 'idParent' : str(usr.manager.id), 'nameParent' : usr.manager.name, 'id' : str(usr.id), 'name' : usr.name, 'realName' : usr.real_name,
'comments' : usr.comments, 'state' : usr.state, 'lastAccess' : usr.last_access, 'password' : INVALID_PASS, 'oldPassword' : INVALID_PASS,
'staffMember' : usr.staff_member, 'isAdmin' : usr.is_admin }
if groups != None:
dct['groups'] = groups
return dct
@needs_credentials
def getUsers(credentials, idParent):
'''
Returns the users contained at idParent authenticator
'''
auth = DbAuthenticator.objects.get(pk=idParent)
res = []
for usr in auth.users.order_by('name'):
try:
res.append(dictFromUser(usr))
except Exception, e:
logger.debug(e)
return res
@needs_credentials
def getUser(credentials, id_):
'''
'''
try:
usr = User(DbUser.objects.get(pk=id_))
grps = []
for g in usr.groups():
logger.debug(g)
grps.append(dictFromGroup(g.dbGroup()))
logger.debug(grps)
return dictFromUser(usr.dbUser(), grps)
except Exception as e:
logger.exception('Unhandled exception')
raise ParametersException(str(e))
@needs_credentials
def createUser(credentials, usr):
'''
Creates a new user associated with an authenticator
'''
auth = DbAuthenticator.objects.get(pk=usr['idParent'])
try:
authInstance = auth.getInstance()
usr['real_name'] = usr['realName'] # Copy to keep this in the right place
authInstance.createUser(usr) # Remenber, this throws an exception if there is an error
staffMember = isAdmin = False
if credentials.isAdmin is True:
staffMember = usr['staffMember']
isAdmin = usr['isAdmin']
password = ''
if authInstance.needsPassword is True:
password = CryptoManager.manager().hash(usr['password'])
user = auth.users.create(name = usr['name'], real_name = usr['real_name'], comments = usr['comments'], state = usr['state'],
password = password, staff_member = staffMember, is_admin = isAdmin)
if authInstance.isExternalSource == False:
for grp in usr['groups']:
group = DbGroup.objects.get(pk=grp['id'])
user.groups.add(group)
except IntegrityError, e:
raise DuplicateEntryException(usr['name'])
except Exception as e:
logger.exception(e)
raise InsertException(str(e))
return True
@needs_credentials
def modifyUser(credentials, usr):
'''
Modifies an existing service provider with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
try:
user = DbUser.objects.get(pk=usr['id'])
auth = user.manager.getInstance()
usr['real_name'] = usr['realName'] # Copy to keep this in the right place
auth.modifyUser(usr) # Notifies authenticator
logger.debug(usr)
user.name = usr['name']
user.real_name = usr['real_name']
user.comments = usr['comments']
if credentials.isAdmin is True:
logger.debug('Is an admin')
user.is_admin = usr['isAdmin']
user.staff_member = usr['staffMember']
if usr['password'] != usr['oldPassword']:
user.password = CryptoManager.manager().hash(usr['password'])
user.state = usr['state']
user.save()
# Now add/removes groups acordly
if auth.isExternalSource == False and user.parent == -1:
newGrps = {}
knownGrps = user.groups.all()
# Add new groups, and keep a dict of all groups selected
for g in usr['groups']:
newGrps[int(g['id'])] = g['name']
grp = DbGroup.objects.get(pk=g['id'])
if (grp in knownGrps) == False:
user.groups.add(grp)
# Remove unselected groups
for g in knownGrps:
if newGrps.has_key(g.id) == False:
user.groups.remove(g)
# Add new groups
except Exception as e:
logger.exception(e)
raise(InsertException(str(e)))
return True
@needs_credentials
def removeUsers(credentials, ids):
'''
Deletes a group
'''
DbUser.objects.filter(id__in=ids).delete()
return True
@needs_credentials
def getUserGroups(credentials, id_):
'''
Get groups assigned to this user
'''
try:
user = DbUser.objects.get(pk=id_)
#auth = user.manager.getInstance()
res = []
#if auth.isExternalSource == False:
for grp in user.getGroups():
res.append(dictFromGroup(grp))
return res
except Exception as e:
logger.exception(e)
raise FindException(str(e))
@needs_credentials
def changeUsersState(credentials, ids, newState):
'''
Changes the state of the specified group
'''
#state = State.ACTIVE if newState == True else State.INACTIVE
DbUser.objects.filter(id__in=ids).update(state = newState)
return True
# Registers XML RPC Methods
def registerUserFunctions(dispatcher):
dispatcher.register_function(getUsers, 'getUsers')
dispatcher.register_function(getUser, 'getUser')
dispatcher.register_function(getUserGroups, 'getUserGroups')
dispatcher.register_function(createUser, 'createUser')
dispatcher.register_function(modifyUser, 'modifyUser')
dispatcher.register_function(removeUsers, 'removeUsers')
dispatcher.register_function(changeUsersState, 'changeUsersState')

View File

@ -1,3 +0,0 @@
'''
This module is responsible of the communication betwen administration client and authenticator part of UDS
'''

View File

@ -1,88 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _
from ..auths.AdminAuth import needs_credentials
from ..util.Exceptions import FindException
from uds.core.util import log
from uds.models import DeployedService
from uds.models import UserService
from uds.models import User
from uds.models import Authenticator
import logging
logger = logging.getLogger(__name__)
@needs_credentials
def getDeployedServiceLogs(credentials, id):
try:
ds = DeployedService.objects.get(pk=id)
return log.getLogs(ds)
except:
logger.exception('Exception')
raise FindException(_('Deployed service does not exists'))
@needs_credentials
def getUserServiceLogs(credentials, id):
try:
us = UserService.objects.get(pk=id)
return log.getLogs(us)
except:
raise FindException(_('User service does not exists'))
@needs_credentials
def getUserLogs(credentials, id):
try:
user = User.objects.get(pk=id)
return log.getLogs(user)
except:
raise FindException('User does not exists')
@needs_credentials
def getAuthLogs(credentials, id):
try:
auth = Authenticator.objects.get(pk=id)
return log.getLogs(auth)
except:
raise FindException('Authenticator does not exists')
# Registers XML RPC Methods
def registerLogFunctions(dispatcher):
dispatcher.register_function(getDeployedServiceLogs, 'getDeployedServiceLogs')
dispatcher.register_function(getUserServiceLogs, 'getUserServiceLogs')
dispatcher.register_function(getUserLogs, 'getUserLogs')
dispatcher.register_function(getAuthLogs, 'getAuthLogs')

View File

@ -1,186 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from django.db import IntegrityError
from uds.models import OSManager
from uds.core.osmanagers.OSManagersFactory import OSManagersFactory
from ..util.Exceptions import DeleteException, FindException, ValidationException, InsertException, ModifyException
from ..util.Helpers import dictFromData
from ..auths.AdminAuth import needs_credentials
from uds.core.Environment import Environment
from uds.core import osmanagers
import logging
logger = logging.getLogger(__name__)
@needs_credentials
def getOSManagersTypes(credentials):
'''
Returns the types of services providers registered in system
'''
res = []
for type_ in OSManagersFactory.factory().providers().values():
val = { 'name' : type_.name(), 'type' : type_.type(), 'description' : type_.description(), 'icon' : type_.icon() }
res.append(val)
return res
@needs_credentials
def getOSManagers(credentials):
'''
Returns the services providers managed (at database)
'''
res = []
for prov in OSManager.objects.order_by('name'):
try:
val = { 'id' : str(prov.id), 'name' : prov.name, 'comments' : prov.comments, 'type' : prov.data_type, 'typeName' : prov.getInstance().name() }
res.append(val)
except Exception:
pass
return res
@needs_credentials
def getOSManagerGui(credentials, type_):
'''
Returns the description of an gui for the specified service provider
'''
spType = OSManagersFactory.factory().lookup(type_)
return spType.guiDescription()
@needs_credentials
def getOSManager(credentials, id_):
'''
Returns the specified service provider (at database)
'''
data = OSManager.objects.get(pk=id_)
res = [
{ 'name' : 'name', 'value' : data.name },
{ 'name' : 'comments', 'value' : data.comments },
]
for key, value in data.getInstance().valuesDict().iteritems():
valtext = 'value'
if value.__class__ == list:
valtext = 'values'
val = {'name' : key, valtext : value }
res.append(val)
return res
@needs_credentials
def createOSManager(credentials, type_, data):
'''
Creates a new service provider with specified type_ and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
dct = dictFromData(data)
try:
# First create data without serialization, then serialies data with correct environment
sp = OSManager.objects.create(name = dct['name'], comments = dct['comments'], data_type = type_)
sp.data = sp.getInstance(dct).serialize()
sp.save()
except osmanagers.OSManager.ValidationException, e:
sp.delete()
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dct['name']))
return True
@needs_credentials
def modifyOSManager(credentials, id_, data):
'''
Modifies an existing service provider with specified id_ and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
osm = OSManager.objects.get(pk=id_)
dps = osm.deployedServices.all().count()
if dps > 0:
errorDps = ','.join([ o.name for o in osm.deployedServices.all()])
raise ModifyException(_('This os mnager is being used by deployed services') + ' ' + errorDps)
dct = dictFromData(data)
sp = osm.getInstance(dct)
osm.data = sp.serialize()
osm.name = dct['name']
osm.comments = dct['comments']
osm.save()
return True
@needs_credentials
def removeOSManager(credentials, id_):
'''
Removes from os manager with specified id_
'''
try:
if OSManager.objects.get(pk=id_).remove() == False:
raise DeleteException(_('There is deployed services using this os manager'))
except OSManager.DoesNotExist:
raise FindException(_('Can\'t find os manager'))
return True
@needs_credentials
def testOsManager(credentials, type_, data):
'''
invokes the test function of the specified service provider type_, with the suplied data
'''
logger.debug("Testing service provider, type_: {0}, data:{1}".format(type_, data))
spType = OSManagersFactory.factory().lookup(type_)
# We need an "temporary" environment to test this service
dct = dictFromData(data)
res = spType.test(Environment.getTempEnv(), dct)
return {'ok' : res[0], 'message' : res[1]}
@needs_credentials
def checkOSManager(credentials, id_):
'''
Invokes the check function of the specified service provider
'''
prov = OSManager.objects.get(pk=id_)
sp = prov.getInstance()
return sp.check()
# Registers XML RPC Methods
def registerOSManagersFunctions(dispatcher):
dispatcher.register_function(getOSManagersTypes, 'getOSManagersTypes')
dispatcher.register_function(getOSManagers, 'getOSManagers')
dispatcher.register_function(getOSManagerGui, 'getOSManagerGui')
dispatcher.register_function(getOSManager, 'getOSManager')
dispatcher.register_function(createOSManager, 'createOSManager')
dispatcher.register_function(modifyOSManager, 'modifyOSManager')
dispatcher.register_function(removeOSManager, 'removeOSManager')
dispatcher.register_function(testOsManager, 'testOsManager')
dispatcher.register_function(checkOSManager, 'checkOSManager')

View File

@ -1,310 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _
from uds.models import DeployedService, Service, OSManager, Transport, Group
from uds.core.util.State import State
from ..auths.AdminAuth import needs_credentials
from django.db import IntegrityError
from ..util.Exceptions import DuplicateEntryException, InsertException, FindException
from Services import infoDictFromServiceInstance
from ..auths.Groups import dictFromGroup
from ..transports.Transports import dictFromTransport
import logging
logger = logging.getLogger(__name__)
def dictFromDeployedService(srv):
if srv.service is not None:
service = srv.service.getInstance()
svrName = srv.service.name
else:
service = None
svrName = _('Unknown')
if srv.osmanager is not None:
osManagerName = srv.osmanager.name
else:
osManagerName = ''
transports = []
for trans in srv.transports.order_by('name'):
transports.append({'id': str(trans.id), 'name': trans.name})
groups = []
for grp in srv.assignedGroups.order_by('name'):
groups.append({'id': str(grp.id), 'name': grp.name})
return {'id': str(srv.id), 'name': srv.name, 'comments': srv.comments, 'idService': str(srv.service_id),
'idOsManager': str(srv.osmanager_id), 'initialServices': srv.initial_srvs, 'cacheL1': srv.cache_l1_srvs,
'cacheL2': srv.cache_l2_srvs, 'maxServices': srv.max_srvs, 'state': srv.state,
'serviceName': svrName, 'osManagerName': osManagerName,
'transports': transports, 'groups': groups, 'info': infoDictFromServiceInstance(service)
}
def addTransportsToDeployedService(deployedService, transports):
'''
Uses the dictionary transport to add transport to a deployedService.
We simply remmoves all previous transports and add the indicated transports
'''
deployedService.transports.clear()
for tr in transports:
try:
transport = Transport.objects.get(pk=tr['id'])
logger.debug('Adding transport {0}'.format(transport))
deployedService.transports.add(transport)
except Exception:
pass # Silently ignore unknown transports ids
return True
@needs_credentials
def getDeployedServices(credentials, all_):
'''
Returns the available deployed services
'''
logger.debug('Returning list of deployed services')
res = []
if all_ == True:
dss = DeployedService.objects.all().order_by('name')
else:
dss = DeployedService.objects.filter(state=State.ACTIVE).order_by('name')
for ds in dss:
try:
res.append(dictFromDeployedService(ds))
except Exception:
logger.exception('Exception adding deployed service')
return res
@needs_credentials
def getDeployedService(credentials, id_):
'''
Returns the available deployed services
'''
logger.debug('Returning list of deployed services')
ds = DeployedService.objects.get(pk=id_)
if ds.state == State.ACTIVE:
return dictFromDeployedService(ds)
raise InsertException(_('Deployed Service does not exists'))
@needs_credentials
def createDeployedService(credentials, deployedService):
'''
Creates a new deployed service based on params
'''
logger.debug('Creating deployed service with params {0}'.format(deployedService))
try:
service = Service.objects.get(pk=deployedService['idService'])
serviceInstance = service.getInstance()
initialServices = deployedService['initialServices']
cacheL1 = deployedService['cacheL1']
cacheL2 = deployedService['cacheL2']
maxServices = deployedService['maxServices']
if serviceInstance.usesCache == False:
initialServices = cacheL1 = cacheL2 = maxServices = 0
osManager = None
if serviceInstance.needsManager:
osManager = OSManager.objects.get(pk=deployedService['idOsManager'])
dps = DeployedService.objects.create(name=deployedService['name'], comments=deployedService['comments'], service=service,
osmanager=osManager, state=State.ACTIVE, initial_srvs=initialServices, cache_l1_srvs=cacheL1,
cache_l2_srvs=cacheL2, max_srvs=maxServices, current_pub_revision=1)
# Now we add transports
addTransportsToDeployedService(dps, deployedService['transports'])
except IntegrityError as e:
logger.error("Integrity error adding deployed service {0}".format(e))
raise DuplicateEntryException(deployedService['name'])
except Exception as e:
logger.error("Exception adding deployed service {0}".format(deployedService))
raise InsertException(str(e))
return str(dps.id)
@needs_credentials
def modifyDeployedService(credentials, deployedService):
'''
Modifies a deployed service
'''
logger.debug('Modifying deployed service'.format(deployedService))
try:
dps = DeployedService.objects.get(pk=deployedService['id'])
serviceInstance = dps.service.getInstance()
initialServices = deployedService['initialServices']
cacheL1 = deployedService['cacheL1']
cacheL2 = deployedService['cacheL2']
maxServices = deployedService['maxServices']
if serviceInstance.usesCache == False:
initialServices = cacheL1 = cacheL2 = maxServices = 0
dps.name = deployedService['name']
dps.comments = deployedService['comments']
dps.initial_srvs = initialServices
dps.cache_l1_srvs = cacheL1
dps.cache_l2_srvs = cacheL2
dps.max_srvs = maxServices
dps.save()
# Now add transports
addTransportsToDeployedService(dps, deployedService['transports'])
except IntegrityError as e:
logger.error("Integrity error modifiying deployed service {0}".format(e))
raise DuplicateEntryException(deployedService['name'])
except DeployedService.DoesNotExist:
logger.error("Requested deployed service does not exists")
raise InsertException(_('Deployed Service does not exists'))
except Exception as e:
logger.error("Exception modifiying deployed service {0}".format(deployedService))
raise InsertException(str(e))
return True
@needs_credentials
def getGroupsAssignedToDeployedService(credentials, deployedServiceId):
'''
Return groups assigned to this deployed service
'''
logger.debug('Returning assigned groups to deployed service {0}'.format(deployedServiceId))
grps = []
try:
dps = DeployedService.objects.get(pk=deployedServiceId)
groups = dps.assignedGroups.all()
for grp in groups:
grps.append(dictFromGroup(grp))
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed Service does not exists'))
return grps
@needs_credentials
def assignGroupToDeployedService(credentials, deployedServiceId, groupId):
'''
Assigns a group to a deployed service
'''
logger.debug('Assigning group {0} to deployed service {1}'.format(groupId, deployedServiceId))
try:
grp = Group.objects.get(pk=groupId)
dps = DeployedService.objects.get(pk=deployedServiceId)
dps.assignedGroups.add(grp)
except Group.DoesNotExist:
raise InsertException(_('Group does not exists'))
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed Service does not exists'))
return True
@needs_credentials
def removeGroupsFromDeployedService(credentials, deployedServiceId, groupIds):
'''
Removes a group from a deployed service
'''
logger.debug('Removing groups {0} from deployed service {1}'.format(groupIds, deployedServiceId))
try:
dps = DeployedService.objects.get(pk=deployedServiceId)
dps.assignedGroups.remove(*groupIds)
# TODO: Mark groups for this deployed services as "must clean" so services are correctly cleaned
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed Service does not exists'))
return True
@needs_credentials
def getTransportsAssignedToDeployedService(credentias, idDS):
'''
Returns the transports associated with an iDS
'''
try:
ds = DeployedService.objects.get(id=idDS)
return [dictFromTransport(t) for t in ds.transports.all()]
except DeployedService.DoesNotExist:
raise FindException(_('Can\'t find deployed service'))
except Exception as e:
logger.exception("getTransportsForDeployedService: ")
raise FindException(str(e))
@needs_credentials
def assignTransportToDeployedService(credentials, deployedServiceId, transportId):
logger.debug('Assigning transport {0} to service {1}'.format(transportId, deployedServiceId))
try:
trans = Transport.objects.get(pk=transportId)
dps = DeployedService.objects.get(pk=deployedServiceId)
dps.transports.add(trans)
except Transport.DoesNotExist:
raise InsertException(_('Transport does not exists'))
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed Service does not exists'))
return True
@needs_credentials
def removeTransportFromDeployedService(credentials, deployedServiceId, transportIds):
'''
Removes a group from a deployed service
'''
logger.debug('Removing transports {1} from deployed service {1}'.format(transportIds, deployedServiceId))
try:
dps = DeployedService.objects.get(pk=deployedServiceId)
dps.transports.remove(*transportIds)
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed Service does not exists'))
return True
@needs_credentials
def removeDeployedService(credentials, deployedServiceId):
'''
Removes a deployed service
'''
# First, mark all services as removable
logger.debug('Removing deployed service {0}'.format(deployedServiceId))
try:
ds = DeployedService.objects.get(pk=deployedServiceId)
ds.remove()
except DeployedService.DoesNotExist:
raise InsertException(_('Deployed service does not exists'))
return True
# Registers XML RPC Methods
def registerDeployedServicesFunctions(dispatcher):
dispatcher.register_function(getDeployedServices, 'getDeployedServices')
dispatcher.register_function(getDeployedService, 'getDeployedService')
dispatcher.register_function(createDeployedService, 'createDeployedService')
dispatcher.register_function(modifyDeployedService, 'modifyDeployedService')
dispatcher.register_function(assignGroupToDeployedService, 'assignGroupToDeployedService')
dispatcher.register_function(removeGroupsFromDeployedService, 'removeGroupsFromDeployedService')
dispatcher.register_function(getGroupsAssignedToDeployedService, 'getGroupsAssignedToDeployedService')
dispatcher.register_function(assignTransportToDeployedService, 'assignTransportToDeployedService')
dispatcher.register_function(removeTransportFromDeployedService, 'removeTransportFromDeployedService')
dispatcher.register_function(getTransportsAssignedToDeployedService, 'getTransportsAssignedToDeployedService')
dispatcher.register_function(removeDeployedService, 'removeDeployedService')

View File

@ -1,90 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from uds.models import DeployedService, DeployedServicePublication
from uds.core.util.State import State
from django.utils.translation import ugettext as _
from ..util.Helpers import dictFromData
from ..auths.AdminAuth import needs_credentials
from ..util.Exceptions import PublicationException
from uds.core.managers.PublicationManager import PublicationManager
import logging
logger = logging.getLogger(__name__)
def dictFromPublication(pub):
res = { 'idParent' : str(pub.deployed_service_id), 'id' : str(pub.id),
'state' : pub.state, 'publishDate' : pub.publish_date, 'reason' : State.toString(pub.state), 'revision' : str(pub.revision)
}
if State.isErrored(pub.state):
publication = pub.getInstance()
res['reason'] = publication.reasonOfError()
return res
@needs_credentials
def getPublications(credentials, idParent):
dps = DeployedService.objects.get(pk=idParent)
res = []
for pub in dps.publications.all().order_by('-publish_date'):
try:
val = dictFromPublication(pub)
res.append(val)
except Exception, e:
logger.debug(e)
return res
@needs_credentials
def publishDeployedService(credentials, idParent):
try:
ds = DeployedService.objects.get(pk=idParent)
ds.publish()
except Exception, e:
raise PublicationException(unicode(e))
return True
@needs_credentials
def cancelPublication(credentials, id):
try:
ds = DeployedServicePublication.objects.get(pk=id)
ds.cancel()
except Exception, e:
raise PublicationException(unicode(e))
return True
# Registers XML RPC Methods
def registerPublicationsFunctions(dispatcher):
dispatcher.register_function(getPublications, 'getPublications')
dispatcher.register_function(publishDeployedService, 'publishDeployedService')
dispatcher.register_function(cancelPublication, 'cancelPublication')

View File

@ -1,217 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _
from django.db import IntegrityError
from uds.models import Provider
from uds.core.services.ServiceProviderFactory import ServiceProviderFactory
from ..util.Helpers import dictFromData
from ..util.Exceptions import ValidationException, InsertException, FindException, DeleteException
from ..auths.AdminAuth import needs_credentials
from uds.core.Environment import Environment
import logging
from uds.core import services
logger = logging.getLogger(__name__)
@needs_credentials
def getServiceProvidersTypes(credentials):
'''
Returns the types of services providers registered in system
'''
res = []
for type_ in ServiceProviderFactory.factory().providers().values():
val = { 'name' : _(type_.name()), 'type' : type_.type(), 'description' : _(type_.description()), 'icon' : type_.icon() }
res.append(val)
return res
@needs_credentials
def getServiceProviders(credentials):
'''
Returns the services providers managed (at database)
'''
res = []
for prov in Provider.objects.order_by('name'):
try:
val = { 'id' : str(prov.id), 'name' : prov.name, 'comments' : prov.comments, 'type' : prov.data_type, 'typeName' : _(prov.getInstance().name()) }
res.append(val)
except Exception:
pass
return res
@needs_credentials
def getServiceProviderGui(credentials, type_):
'''
Returns the description of an gui for the specified service provider
'''
spType = ServiceProviderFactory.factory().lookup(type_)
return spType.guiDescription()
@needs_credentials
def getServiceProvider(credentials, id_):
'''
Returns the specified service provider (at database)
'''
data = Provider.objects.get(pk=id_)
res = [
{ 'name' : 'name', 'value' : data.name },
{ 'name' : 'comments', 'value' : data.comments },
]
for key, value in data.getInstance().valuesDict().iteritems():
valtext = 'value'
if value.__class__ == list:
valtext = 'values'
val = {'name' : key, valtext : value }
res.append(val)
return res
@needs_credentials
def createServiceProvider(credentials, type_, data):
'''
Creates a new service provider with specified type and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
try:
dic = dictFromData(data)
# First create data without serialization, then serialies data with correct environment
sp = Provider.objects.create(name=dic['name'], comments=dic['comments'], data_type=type_)
sp.data = sp.getInstance(dic).serialize()
sp.save()
except services.ServiceProvider.ValidationException as e:
sp.delete()
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dic['name']))
except Exception as e:
logger.exception('Unexpected exception')
raise ValidationException(str(e))
return True
@needs_credentials
def modifyServiceProvider(credentials, id_, data):
'''
Modifies an existing service provider with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
try:
prov = Provider.objects.get(pk=id_)
dic = dictFromData(data)
sp = prov.getInstance(dic)
prov.data = sp.serialize()
prov.name = dic['name']
prov.comments = dic['comments']
prov.save()
except services.ServiceProvider.ValidationException as e:
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dic['name']))
except Exception as e:
logger.exception('Unexpected exception')
raise ValidationException(str(e))
return True
@needs_credentials
def removeServiceProvider(credentials, id_):
'''
Removes from database provider with specified id
'''
try:
prov = Provider.objects.get(pk=id_)
if prov.services.count() > 0:
raise DeleteException(_('Can\'t delete service provider with services associated'))
prov.delete()
except Provider.DoesNotExist:
raise FindException(_('Can\'t locate the service provider') + '.' + _('Please, refresh interface'))
return True
@needs_credentials
def getOffersFromServiceProvider(credentials, type_):
'''
Returns the services offered from the provider
'''
spType = ServiceProviderFactory.factory().lookup(type_)
res = []
for t in spType.getServicesTypes():
val = { 'name' : _(t.name()), 'type' : t.type(), 'description' : _(t.description()), 'icon' : t.icon() }
res.append(val)
return res
@needs_credentials
def testServiceProvider(credentials, type_, data):
'''
invokes the test function of the specified service provider type, with the suplied data
'''
logger.debug("Testing service provider, type: {0}, data:{1}".format(type, data))
spType = ServiceProviderFactory.factory().lookup(type_)
# We need an "temporary" environment to test this service
dct = dictFromData(data)
res = spType.test(Environment.getTempEnv(), dct)
return {'ok' : res[0], 'message' : res[1]}
@needs_credentials
def checkServiceProvider(credentials, id_):
'''
Invokes the check function of the specified service provider
'''
prov = Provider.objects.get(id=id_)
sp = prov.getInstance()
return sp.check()
# Registers XML RPC Methods
def registerServiceProvidersFunctions(dispatcher):
dispatcher.register_function(getServiceProvidersTypes, 'getServiceProvidersTypes')
dispatcher.register_function(getServiceProviders, 'getServiceProviders')
dispatcher.register_function(getServiceProviderGui, 'getServiceProviderGui')
dispatcher.register_function(getServiceProvider, 'getServiceProvider')
dispatcher.register_function(createServiceProvider, 'createServiceProvider')
dispatcher.register_function(modifyServiceProvider, 'modifyServiceProvider')
dispatcher.register_function(removeServiceProvider, 'removeServiceProvider')
dispatcher.register_function(getOffersFromServiceProvider, 'getOffersFromServiceProvider')
dispatcher.register_function(testServiceProvider, 'testServiceProvider')
dispatcher.register_function(checkServiceProvider, 'checkServiceProvider')

View File

@ -1,227 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _
from django.db import IntegrityError
from uds.models import Provider, Service
from uds.xmlrpc.util.Helpers import dictFromData
from uds.xmlrpc.auths.AdminAuth import needs_credentials
from uds.xmlrpc.util.Exceptions import InsertException, FindException, DeleteException, ValidationException
from uds.core.Environment import Environment
from uds.core import services
import logging
logger = logging.getLogger(__name__)
def infoDictFromServiceInstance(service):
if service is not None:
needsPublication = service.publicationType is not None
maxDeployed = service.maxDeployed
usesCache = service.usesCache
usesCache_L2 = service.usesCache_L2
cacheTooltip = _(service.cacheTooltip)
cacheTooltip_L2 = _(service.cacheTooltip_L2)
needsManager = service.needsManager
mustAssignManually = service.mustAssignManually
typeName = service.name()
else:
needsPublication = False
maxDeployed = 0
usesCache = False
usesCache_L2 = False
cacheTooltip = ''
cacheTooltip_L2 = ''
needsManager = False
mustAssignManually = False
typeName = ''
return { 'needsPublication' : needsPublication, 'maxDeployed' : maxDeployed,
'usesCache' : usesCache, 'usesCacheL2' : usesCache_L2,
'cacheTooltip' : cacheTooltip, 'cacheTooltipL2' : cacheTooltip_L2,
'needsManager' : needsManager, 'mustAssignManually' : mustAssignManually,
'typeName' : typeName
}
def dictFromService(serv):
service = serv.getInstance()
return { 'idParent' : str(serv.provider_id), 'id' : str(serv.id), 'name' : serv.name,
'comments' : serv.comments, 'type' : serv.data_type, 'typeName' : _(service.name()), 'info' : infoDictFromServiceInstance(service)
}
@needs_credentials
def getServices(credentials, idParent):
'''
Returns the services providers managed (at database)
'''
provider = Provider.objects.get(id=idParent)
res = []
for serv in provider.services.order_by('name'):
try:
val = dictFromService(serv)
res.append(val)
except Exception, e:
logger.debug(e)
return res
@needs_credentials
def getAllServices(credentials):
'''
Returns all services, don't limited by parent id
'''
res = []
for serv in Service.objects.all().order_by('name'):
try:
val = dictFromService(serv)
val['name'] = serv.provider.name + '\\' + val['name']
res.append(val)
except:
logger.exception('getAllServices')
return res
@needs_credentials
def getServiceGui(credentials, idParent, type):
'''
Returns the description of an gui for the specified service provider
'''
try:
logger.debug('getServiceGui parameters: {0}, {1}'.format(idParent, type))
provider = Provider.objects.get(id=idParent).getInstance()
serviceType = provider.getServiceByType(type)
service = serviceType(Environment.getTempEnv(), provider) # Instantiate it so it has the opportunity to alter gui description based on parent
return service.guiDescription(service)
except:
logger.exception('Exception at getServiceGui')
raise
@needs_credentials
def getService(credentials, id):
'''
Returns the specified service provider (at database)
'''
logger.debug('getService parameters: {0}'.format(id))
srv = Service.objects.get(id=id)
res = [
{ 'name' : 'name', 'value' : srv.name },
{ 'name' : 'comments', 'value' : srv.comments },
]
for key, value in srv.getInstance().valuesDict().iteritems():
valtext = 'value'
if value.__class__ == list:
valtext = 'values'
val = {'name' : key, valtext : value }
res.append(val)
logger.debug('getService res: {0}'.format(res))
return res
@needs_credentials
def createService(credentials, idParent, type, data):
'''
Creates a new service with specified type and data associated to the specified parent
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider, getServices, ...
'''
provider = Provider.objects.get(id=idParent)
dic = dictFromData(data)
try:
srv = provider.services.create(name=dic['name'], comments=dic['comments'], data_type=type)
# Invoque serialization with correct environment
srv.data = srv.getInstance(dic).serialize()
srv.save()
except services.Service.ValidationException as e:
srv.delete()
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dic['name']))
except Exception as e:
logger.exception('Unexpected exception')
raise ValidationException(str(e))
return True
@needs_credentials
def modifyService(credentials, id, data):
'''
Modifies an existing service with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
try:
serv = Service.objects.get(pk=id)
dic = dictFromData(data)
sp = serv.getInstance(dic)
serv.data = sp.serialize()
serv.name = dic['name']
serv.comments = dic['comments']
serv.save()
except services.Service.ValidationException as e:
raise ValidationException(str(e))
except IntegrityError: # Must be exception at creation
raise InsertException(_('Name %s already exists') % (dic['name']))
except Exception as e:
logger.exception('Unexpected exception')
raise ValidationException(str(e))
return True
@needs_credentials
def removeService(credentials, id):
'''
Removes from database provider with specified id
'''
try:
s = Service.objects.get(id=id)
if s.deployedServices.count() > 0:
raise DeleteException(_('Can\'t delete services with deployed services associated'))
s.delete()
except Service.DoesNotExist:
raise FindException(_('Can\'t locate the service') + '.' + _('Please, refresh interface'))
return True
# Registers XML RPC Methods
def registerServiceFunctions(dispatcher):
dispatcher.register_function(getServices, 'getServices')
dispatcher.register_function(getAllServices, 'getAllServices')
dispatcher.register_function(getServiceGui, 'getServiceGui')
dispatcher.register_function(getService, 'getService')
dispatcher.register_function(createService, 'createService')
dispatcher.register_function(modifyService, 'modifyService')
dispatcher.register_function(removeService, 'removeService')

View File

@ -1,223 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from uds.models import DeployedService, User, UserService
from uds.core.util.State import State
from django.utils.translation import ugettext as _
from ..auths.AdminAuth import needs_credentials
from ..util.Exceptions import FindException
from uds.core.managers.UserServiceManager import UserServiceManager
import logging
logger = logging.getLogger(__name__)
def dictFromCachedDeployedService(cs):
if cs.publication is not None:
revision = str(cs.publication.revision)
else:
revision = ''
res = {
'idParent': str(cs.deployed_service_id),
'id': str(cs.id),
'uniqueId': cs.unique_id,
'friendlyName': cs.friendly_name,
'state': cs.state,
'osState': cs.os_state,
'stateDate': cs.state_date,
'creationDate': cs.creation_date,
'cacheLevel': str(cs.cache_level),
'revision': revision
}
return res
def dictFromAssignedDeployedService(ads):
if ads.publication is not None:
revision = str(ads.publication.revision)
else:
revision = ''
res = {
'idParent': str(ads.deployed_service_id),
'id': str(ads.id),
'uniqueId': ads.unique_id,
'friendlyName': ads.friendly_name,
'state': ads.state,
'osState': ads.os_state,
'stateDate': ads.state_date,
'creationDate': ads.creation_date,
'revision': revision,
'user': ads.user.manager.name + "-" + ads.user.name,
'inUse': ads.in_use,
'inUseDate': ads.in_use_date,
'sourceHost': ads.src_hostname,
'sourceIp': ads.src_ip
}
return res
@needs_credentials
def getCachedDeployedServices(credentials, idParent):
dps = DeployedService.objects.get(pk=idParent)
res = []
for cache in dps.cachedUserServices().order_by('-creation_date'):
try:
val = dictFromCachedDeployedService(cache)
res.append(val)
except Exception, e:
logger.debug(e)
return res
@needs_credentials
def getAssignedDeployedServices(credentials, idParent):
dps = DeployedService.objects.get(pk=idParent)
res = []
for assigned in dps.assignedUserServices().order_by('-creation_date'):
try:
val = dictFromAssignedDeployedService(assigned)
res.append(val)
except Exception, e:
logger.debug(e)
logger.debug(res)
return res
@needs_credentials
def getAssignableDeployedServices(crecentials, idParent):
res = []
try:
dps = DeployedService.objects.get(pk=idParent)
if dps.state != State.ACTIVE:
raise FindException(_('The deployed service is not active'))
servInstance = dps.service.getInstance()
if servInstance.mustAssignManually is False:
raise FindException(_('This service don\'t allows assignations'))
assignables = servInstance.requestServicesForAssignation()
for ass in assignables:
res.append({'id': ass.getName(), 'name': ass.getName()})
except DeployedService.DoesNotExist:
raise FindException(_('Deployed service not found!!! (refresh interface)'))
return res
@needs_credentials
def assignDeployedService(credentials, idParent, idDeployedUserService, idUser):
try:
dps = DeployedService.objects.get(pk=idParent)
if dps.state != State.ACTIVE:
raise FindException(_('The deployed service is not active'))
servInstance = dps.service.getInstance()
if servInstance.mustAssignManually is False:
raise FindException(_('This service don\'t allows assignations'))
user = dps.authenticator.users.get(pk=idUser)
assignables = servInstance.requestServicesForAssignation()
for ass in assignables:
if ass.getName() == idDeployedUserService: # Found, create it
UserServiceManager.manager().createAssignable(dps, ass, user)
except DeployedService.DoesNotExist:
raise FindException(_('Deployed service not found!!! (refresh interface)'))
except User.DoesNotExist:
raise FindException(_('User not found!!! (refresh interface)'))
return True
@needs_credentials
def removeUserService(cretentials, ids):
try:
for service in UserService.objects.filter(id__in=ids):
if service.state == State.USABLE:
service.remove()
elif service.state == State.PREPARING:
service.cancel()
except Exception:
logger.exception("Exception at removeUserService:")
return False
return True
@needs_credentials
def getUserDeployedServiceError(credentials, idService):
error = _('No error')
try:
uds = UserService.objects.get(pk=idService)
if uds.state == State.ERROR:
error = uds.getInstance().reasonOfError()
except UserService.DoesNotExist:
raise FindException(_('User deployed service not found!!!'))
return error
@needs_credentials
def develAction(credentials, action, ids):
logger.debug('Devel action invoked: {0} for {1}'.format(action, ids))
try:
for uds in UserService.objects.filter(id__in=ids):
if action == "inUse":
logger.debug('Setting {0} to in use'.format(uds.friendly_name))
uds.setInUse(True)
elif action == "releaseInUse":
logger.debug('Releasing in use from {0}'.format(uds.friendly_name))
uds.setState(State.USABLE)
uds.setInUse(False)
elif action == 'notifyReady':
logger.debug('Notifying ready from os manager to {0}'.format(uds.friendly_name))
uds.getInstance().osmanager().process(uds, 'ready', '{0}=1.2.3.4'.format(uds.unique_id))
else:
logger.debug('Setting {0} to usable'.format(uds.friendly_name))
uds.setState(State.USABLE)
if uds.needsOsManager():
uds.setOsState(State.USABLE)
uds.save()
except UserService.DoesNotExist:
raise FindException(_('User deployed service not found!!!'))
return True
# Registers XML RPC Methods
def registerUserDeployedServiceFunctions(dispatcher):
dispatcher.register_function(getCachedDeployedServices, 'getCachedDeployedServices')
dispatcher.register_function(getAssignedDeployedServices, 'getAssignedDeployedServices')
dispatcher.register_function(getAssignableDeployedServices, 'getAssignableDeployedServices')
dispatcher.register_function(assignDeployedService, 'assignDeployedService')
dispatcher.register_function(removeUserService, 'removeUserService')
dispatcher.register_function(getUserDeployedServiceError, 'getUserDeployedServiceError')
dispatcher.register_function(develAction, "develAction")

View File

@ -1,79 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from django.utils.translation import ugettext as _
from uds.models import DeployedService
from ..auths.AdminAuth import needs_credentials
from ..util.Exceptions import FindException
from uds.core.util.stats import counters
from uds.core.util.Cache import Cache
import cPickle
import time
import logging
logger = logging.getLogger(__name__)
cache = Cache('StatsDispatcher')
@needs_credentials
def getDeployedServiceCounters(credentials, id, counter_type, since, to, points, use_max):
try:
cacheKey = id + str(counter_type)+str(since)+str(to)+str(points)+str(use_max)
val = cache.get(cacheKey)
if val is None:
if id == '-1':
us = DeployedService()
all = True
else:
us = DeployedService.objects.get(pk=id)
all = False
val = []
for x in counters.getCounters(us, counter_type, since=since, to=to, limit=points, use_max=use_max, all=all):
val.append({ 'stamp': x[0], 'value': int(x[1]) })
if len(val) > 2:
cache.put(cacheKey, cPickle.dumps(val).encode('zip'), 3600)
else:
val = [{'stamp':since, 'value':0 }, {'stamp':to, 'value':0}]
else:
val = cPickle.loads(val.decode('zip'))
return { 'title': counters.getCounterTitle(counter_type), 'data': val }
except:
logger.exception('exception')
raise FindException(_('Service does not exists'))
# Registers XML RPC Methods
def registerStatsFunctions(dispatcher):
dispatcher.register_function(getDeployedServiceCounters, 'getDeployedServiceCounters')

View File

@ -1,48 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from ..auths.AdminAuth import needs_credentials
from uds.core.util.Cache import Cache
import logging
logger = logging.getLogger(__name__)
@needs_credentials
def flushCache(credentials):
Cache.purge()
return True
# Registers XML RPC Methods
def registerCacheFunctions(dispatcher):
dispatcher.register_function(flushCache, 'flushCache')

View File

@ -1,68 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from ..auths.AdminAuth import needs_credentials
from uds.core.util.Config import Config, GLOBAL_SECTION, SECURITY_SECTION
import logging
logger = logging.getLogger(__name__)
@needs_credentials
def getConfiguration(credentials):
res = []
addCrypt = credentials.isAdmin
priorities = { GLOBAL_SECTION: 0, SECURITY_SECTION: 1 }
for cfg in (v[0] for v in sorted([(x, priorities.get(x.section(), 20)) for x in Config.enumerate()], key = lambda c:c[1])):
if cfg.isCrypted() is True and addCrypt is False:
continue
res.append( {'section': cfg.section(), 'key' : cfg.key(), 'value' : cfg.get(), 'crypt': cfg.isCrypted(), 'longText': cfg.isLongText() } )
logger.debug('Configuration: {0}'.format(res))
return res
@needs_credentials
def updateConfiguration(credentials, configuration):
'''
Configuration is an array of dicts containing 'section', 'key' and 'value' (crypt is in fact ignored, used the one from database)
'''
for cfg in configuration:
Config.update( cfg['section'], cfg['key'], cfg['value'] )
return True
# Registers XML RPC Methods
def registerConfigurationFunctions(dispatcher):
dispatcher.register_function(getConfiguration, 'getConfiguration')
dispatcher.register_function(updateConfiguration, 'updateConfiguration')

View File

@ -1,117 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from django.db import IntegrityError
from uds.models import Network, Transport
from uds.xmlrpc.util.Exceptions import InsertException, FindException, DeleteException
from uds.xmlrpc.auths.AdminAuth import needs_credentials
import logging
logger = logging.getLogger(__name__)
def dictFromNetwork(net):
return { 'id' : str(net.id), 'name' : net.name, 'netRange' : net.net_string }
@needs_credentials
def getNetworks(credentials):
'''
Returns the services providers managed (at database)
'''
res = []
for net in Network.objects.all():
res.append(dictFromNetwork(net))
return res
@needs_credentials
def getNetworksForTransport(credentials, id_):
try:
res = [ str(n.id) for n in Transport.objects.get(pk=id_).networks.all().order_by('name') ]
except Exception:
res = []
return res
@needs_credentials
def setNetworksForTransport(credentials, id_, networks):
try:
trans = Transport.objects.get(pk=id_)
trans.networks = Network.objects.filter(id__in=networks)
except Transport.DoesNotExist:
raise FindException(_('Can\'t locate the transport') + '.' + _('Please, refresh interface'))
return True
@needs_credentials
def getNetwork(credentials, id_):
try:
net = Network.objects.get(pk=id_)
except Network.DoesNotExist:
raise FindException(_('Can\'t locate the network') + '.' + _('Please, refresh interface'))
return dictFromNetwork(net)
@needs_credentials
def createNetwork(credentials, network):
try:
Network.create(network['name'], network['netRange'])
except IntegrityError:
raise InsertException(_('Name %s already exists') % (network['name']))
return True
@needs_credentials
def modifyNetwork(credentials, network):
try:
net = Network.objects.get(pk=network['id'])
net.update(network['name'], network['netRange'])
except Network.DoesNotExist:
raise FindException(_('Can\'t locate the network') + '.' + _('Please, refresh interface'))
except IntegrityError:
raise InsertException(_('Name %s already exists') % (network['name']))
return True
@needs_credentials
def removeNetworks(credentials, ids):
try:
Network.objects.filter(id__in=ids).delete()
except Exception as e:
raise DeleteException(unicode(e))
return True
def registerNetworksFunctions(dispatcher):
dispatcher.register_function(getNetworks, 'getNetworks')
dispatcher.register_function(getNetworksForTransport, 'getNetworksForTransport')
dispatcher.register_function(setNetworksForTransport, 'setNetworksForTransport')
dispatcher.register_function(getNetwork, 'getNetwork')
dispatcher.register_function(createNetwork, 'createNetwork')
dispatcher.register_function(modifyNetwork, 'modifyNetwork')
dispatcher.register_function(removeNetworks, 'removeNetworks')

View File

@ -1,159 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from uds.models import Transport
from uds.core.transports.TransportsFactory import TransportsFactory
from uds.core.ui.UserInterface import gui
from ..util.Helpers import dictFromData
from ..auths.AdminAuth import needs_credentials
import logging
logger = logging.getLogger(__name__)
def dictFromTransport(trans):
return {
'id' : str(trans.id),
'name' : trans.name,
'comments' : trans.comments,
'type' : trans.data_type,
'typeName' : trans.getInstance().name(),
'priority' : str(trans.priority),
'networks' : [ t.name for t in trans.networks.all().order_by('name') ]
}
@needs_credentials
def getTransportsTypes(credentials):
'''
Returns the types of services providers registered in system
'''
res = []
for type_ in TransportsFactory.factory().providers().values():
val = { 'name' : type_.name(), 'type' : type_.type(), 'description' : type_.description(), 'icon' : type_.icon() }
res.append(val)
return res
@needs_credentials
def getTransports(credentials):
'''
Returns the services providers managed (at database)
'''
res = []
for trans in Transport.objects.order_by('priority'):
try:
res.append(dictFromTransport(trans))
except Exception:
logger.exception("At getTransports: ")
return res
@needs_credentials
def getTransportGui(credentials, type_):
'''
Returns the description of an gui for the specified service provider
'''
spType = TransportsFactory.factory().lookup(type_)
return spType.guiDescription()
@needs_credentials
def getTransport(credentials, id_):
'''
Returns the specified service provider (at database)
'''
data = Transport.objects.get(pk=id_)
res = [
{ 'name' : 'name', 'value' : data.name },
{ 'name' : 'comments', 'value' : data.comments },
{ 'name' : 'priority', 'value' : str(data.priority) },
{ 'name' : 'positiveNet', 'value' : gui.boolToStr(data.nets_positive) },
]
for key, value in data.getInstance().valuesDict().iteritems():
valtext = 'value'
if value.__class__ == list:
valtext = 'values'
val = {'name' : key, valtext : value }
res.append(val)
return res
@needs_credentials
def createTransport(credentials, type_, data):
'''
Creates a new service provider with specified type and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
dct = dictFromData(data)
# First create data without serialization, then serialies data with correct environment
sp = Transport.objects.create(name = dct['name'], comments = dct['comments'], data_type = type_,
priority=int(dct['priority']), nets_positive=gui.strToBool(dct['positiveNet']) )
sp.data = sp.getInstance(dct).serialize()
sp.save()
return str(sp.id)
@needs_credentials
def modifyTransport(credentials, id_, data):
'''
Modifies an existing service provider with specified id and data
It's mandatory that data contains at least 'name' and 'comments'.
The expected structure is the same that provided at getServiceProvider
'''
trans = Transport.objects.get(pk=id_)
dct = dictFromData(data)
sp = trans.getInstance(dct)
trans.data = sp.serialize()
trans.name = dct['name']
trans.comments = dct['comments']
trans.priority = int(dct['priority'])
trans.nets_positive = gui.strToBool(dct['positiveNet'])
trans.save()
return True
@needs_credentials
def removeTransport(credentials, id_):
'''
Removes from database provider with specified id
'''
Transport.objects.get(pk=id_).delete()
return True
# Registers XML RPC Methods
def registerTransportsFunctions(dispatcher):
dispatcher.register_function(getTransportsTypes, 'getTransportsTypes')
dispatcher.register_function(getTransports, 'getTransports')
dispatcher.register_function(getTransportGui, 'getTransportGui')
dispatcher.register_function(getTransport, 'getTransport')
dispatcher.register_function(createTransport, 'createTransport')
dispatcher.register_function(modifyTransport, 'modifyTransport')
dispatcher.register_function(removeTransport, 'removeTransport')

View File

@ -1,51 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from ..auths.AdminAuth import needs_credentials
from uds.core.ui.UserInterface import gui
@needs_credentials
def chooseCallback(credentials, name, parameters):
res = {}
params = {}
for p in parameters:
params[p['name']] = p['value']
if gui.callbacks.has_key(name):
res = gui.callbacks[name](params)
return res
def registerCallbackFunctions(dispatcher):
dispatcher.register_function(chooseCallback, 'chooseCallback')

View File

@ -1,82 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from xmlrpclib import Fault
AUTH_CLASS = 0x1000
DATA_CLASS = 0x2000
ACTION_CLASS = 0x3000
FAIL = 0x0100
AUTH_FAILED = AUTH_CLASS | FAIL | 0x0001
DUPLICATE_FAIL = DATA_CLASS | FAIL | 0x0001
INSERT_FAIL = DATA_CLASS | FAIL | 0x0002
DELETE_FAIL = DATA_CLASS | FAIL | 0x0003
FIND_FAIL = DATA_CLASS | FAIL | 0x0004
VALIDATION_FAIL = DATA_CLASS | FAIL | 0x0005
PARAMETERS_FAIL = DATA_CLASS | FAIL | 0x0006
MODIFY_FAIL = DATA_CLASS | FAIL | 0x0007
PUBLISH_FAIL = ACTION_CLASS | FAIL | 0x0001
CANCEL_FAIL = ACTION_CLASS | FAIL | 0x0001
def AuthException(msg):
return Fault(AUTH_FAILED, msg)
def DuplicateEntryException(msg):
return Fault(DUPLICATE_FAIL, msg)
def InsertException(msg):
return Fault(INSERT_FAIL, msg)
def FindException(msg):
return Fault(FIND_FAIL, msg)
def DeleteException(msg):
return Fault(DELETE_FAIL, msg)
def ModifyException(msg):
return Fault(MODIFY_FAIL, msg)
def PublicationException(msg):
return Fault(PUBLISH_FAIL, msg)
def CancelationException(msg):
return Fault(CANCEL_FAIL, msg)
def ValidationException(msg):
return Fault(VALIDATION_FAIL, msg)
def ParametersException(msg):
return Fault(PARAMETERS_FAIL, msg)

View File

@ -1,60 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
import logging
logger = logging.getLogger(__name__)
def dictFromData(data):
'''
This function converts an array of dicts of type { 'name' : ..., 'value' : ...} to a single dictionary where keys are the "name"s and the values are the "value"s
example:
data = [ { 'name' : 'var1', 'value' : 'value1' }, { 'name' : 'var2', 'value' : 'value2' }, 'name' : 'var3', 'values' : [ ...] ]
this will return { 'var1' : 'value1', 'var2' : 'value2' }
'''
dictionary = {}
for val in data:
if val.has_key('value'):
dictionary[val['name']] = val['value']
else:
ary = []
for value in val['values']:
if isinstance(value, dict):
ary.append(value['id'])
else:
ary.append(value)
dictionary[val['name']] = ary
logger.debug("Dictionary obtained: {0} from {1}".format(dictionary, data))
return dictionary

View File

@ -1,60 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
import cStringIO
from xmlrpclib import Transport, ServerProxy
from django.test.client import Client
class TestTransport(Transport,object):
""" Handles connections to XML-RPC server through Django test client."""
def __init__(self, *args, **kwargs):
super(TestTransport, self).__init__(*args, **kwargs)
self.client = Client()
def request(self, host, handler, request_body, verbose=0):
self.verbose = verbose
response = self.client.post(handler,
request_body,
content_type="text/xml")
res = cStringIO.StringIO(response.content)
res.seek(0)
return self.parse_response(res)
rpcServer = ServerProxy("http://test:test@172.27.0.1:8000/xmlrpc", verbose = 1, transport=TestTransport())

View File

@ -35,25 +35,7 @@ from django.http import HttpResponse
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.views.decorators.csrf import csrf_exempt
# from services.ServiceProviders import registerServiceProvidersFunctions
# from services.Services import registerServiceFunctions
# from services.DeployedServices import registerDeployedServicesFunctions
# from services.Publications import registerPublicationsFunctions
# from services.UserDeployedServices import registerUserDeployedServiceFunctions
from uds.xmlrpc.actor.Actor import registerActorFunctions
# from util.Callbacks import registerCallbackFunctions
# from auths.AdminAuth import registerAdminAuthFunctions
# from auths.Authenticators import registerAuthenticatorFunctions
# from osmanagers.OSManagers import registerOSManagersFunctions
# from transports.Transports import registerTransportsFunctions
# from transports.Networks import registerNetworksFunctions
# from auths.Groups import registerGroupsFunctions
# from auths.Users import registerUserFunctions
# from auths.UserPreferences import registerPreferencesFunctions
# from tools.Cache import registerCacheFunctions
# from tools.Config import registerConfigurationFunctions
# from log.logs import registerLogFunctions
# from stats.stats import registerStatsFunctions
import logging
@ -114,23 +96,4 @@ def xmlrpc(request):
response['Content-length'] = str(len(response.content))
return response
# Register every xmlrpc function
# registerServiceProvidersFunctions(dispatcher)
# registerServiceFunctions(dispatcher)
# registerPublicationsFunctions(dispatcher)
# registerUserDeployedServiceFunctions(dispatcher)
# registerOSManagersFunctions(dispatcher)
# registerTransportsFunctions(dispatcher)
# registerNetworksFunctions(dispatcher)
# registerAdminAuthFunctions(dispatcher)
# registerAuthenticatorFunctions(dispatcher)
# registerGroupsFunctions(dispatcher)
# registerUserFunctions(dispatcher)
# registerCallbackFunctions(dispatcher)
# registerDeployedServicesFunctions(dispatcher)
registerActorFunctions(dispatcher)
# registerPreferencesFunctions(dispatcher)
# registerCacheFunctions(dispatcher)
# registerConfigurationFunctions(dispatcher)
# registerLogFunctions(dispatcher)
# registerStatsFunctions(dispatcher)