1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-02-03 13:47:14 +03:00

Upgrade to Django 1.9 and advances on advances on states fixes (cosmetic fixes to better identify what we refer to)

This commit is contained in:
Adolfo Gómez García 2016-02-19 08:16:55 +01:00
parent 12737df530
commit 56ac8aece9
23 changed files with 395 additions and 97 deletions

View File

@ -145,18 +145,17 @@ TEMPLATE_LOADERS = (
)
# Own context processors plus django's own
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + [
'uds.core.util.Config.context_processor',
'uds.core.util.html.context',
'django.core.context_processors.request',
)
]
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'uds.core.util.request.GlobalRequestMiddleware',
'uds.core.util.middleware.XUACompatibleMiddleware',
@ -245,7 +244,7 @@ LOGGING = {
'handlers': {
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
'class':'logging.NullHandler',
},
'file':{

View File

@ -64,7 +64,7 @@ class AccessCalendars(DetailHandler):
return [{
'id': i.uuid,
'name': i.calendar.name,
'allow': ALLOW if i.allow else DENY,
'action': ALLOW if i.allow else DENY,
'priority': i.priority,
} for i in parent.calendaraccess_set.all()]
@ -75,7 +75,7 @@ class AccessCalendars(DetailHandler):
return [
{'priority': {'title': _('Priority'), 'type': 'numeric', 'width': '6em'}},
{'name': {'title': _('Name')}},
{'allow': {'title': _('Rule')}},
{'action': {'title': _('Rule')}},
]
def saveItem(self, parent, item):

View File

@ -43,7 +43,7 @@ from uds.REST.model import ModelHandler
from uds.REST import RequestError, ResponseError
from uds.core.ui.UserInterface import gui
from .user_services import AssignedService, CachedService, Groups, Transports, Publications, Changelog
from .services_pool_calendars import AccessCalendars
from .services_pool_calendars import AccessCalendars, ALLOW, DENY
from .services import Services
import logging
@ -105,7 +105,7 @@ class ServicesPools(ModelHandler):
'user_services_count': item.userServices.count(),
'restrained': item.isRestrained(),
'show_transports': item.show_transports,
'allowAccessByDefault': item.fallbackAccessAllow,
'allowAccessByDefault': ALLOW if item.fallbackAccessAllow is True else DENY,
'permission': permissions.getEffectivePermission(self._user, item),
'info': Services.serviceInfo(item.service),
}

View File

@ -32,16 +32,6 @@
'''
# Make sure that all services are "available" at service startup
from . import services # to make sure that the packages are initialized at this point
from . import auths # To make sure that the packages are initialized at this point
from . import osmanagers # To make sure that packages are initialized at this point
from . import transports # To make sure that packages are initialized at this point
from . import dispatchers
from . import models
from . import plugins # To make sure plugins are loaded on memory
from . import REST # To make sure REST initializes all what it needs
import uds.xmlrpc # To make actor live
from django.db.backends.signals import connection_created
from django.dispatch import receiver
@ -56,7 +46,7 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-10-20'
__updated__ = '2016-02-19'
# Default ssl context is unverified, as MOST servers that we will connect will be with self signed certificates...
@ -79,6 +69,17 @@ class UDSAppConfig(AppConfig):
# We have to take care with this, because it's supposed to be executed
# with ANY command from manage.
logger.debug('Initializing app (ready) ***************')
from . import services # to make sure that the packages are initialized at this point
from . import auths # To make sure that the packages are initialized at this point
from . import osmanagers # To make sure that packages are initialized at this point
from . import transports # To make sure that packages are initialized at this point
from . import dispatchers
from . import models
from . import plugins # To make sure plugins are loaded on memory
from . import REST # To make sure REST initializes all what it needs
import uds.xmlrpc # To make actor live
default_app_config = 'uds.UDSAppConfig'

View File

@ -38,8 +38,8 @@ from __future__ import unicode_literals
from uds.core.Environment import Environmentable
from uds.core.Serializable import Serializable
from uds.core.BaseModule import Module
from uds.core import services
from uds.core import auths
from uds.core import transports
# from uds.core import services
# from uds.core import auths
# from uds.core import transports
VERSION = '1.9.0'
VERSION = '2.0.0'

View File

@ -35,7 +35,7 @@ from __future__ import unicode_literals
import os
import uuid
from django.http import HttpResponse, Http404
from django.core.servers.basehttp import FileWrapper
from wsgiref.util import FileWrapper
from uds.core.managers import cryptoManager

View File

@ -33,7 +33,7 @@ from __future__ import unicode_literals
from django.conf import settings
from django.apps import apps
from uds.models import Config as dbConfig
import uds.models.Config
from uds.core.managers.CryptoManager import CryptoManager
import logging
@ -86,7 +86,7 @@ class Config(object):
try:
if force or self._data is None:
# logger.debug('Accessing db config {0}.{1}'.format(self._section.name(), self._key))
readed = dbConfig.objects.get(section=self._section.name(), key=self._key) # @UndefinedVariable
readed = uds.models.Config.objects.get(section=self._section.name(), key=self._key) # @UndefinedVariable
self._data = readed.value
self._crypt = [self._crypt, True][readed.crypt] # True has "higher" precedende than False
self._longText = readed.long
@ -149,7 +149,7 @@ class Config(object):
'''
logger.debug('Saving config {0}.{1} as {2}'.format(self._section.name(), self._key, value))
try:
obj, _ = dbConfig.objects.get_or_create(section=self._section.name(), key=self._key) # @UndefinedVariable
obj, _ = uds.models.Config.objects.get_or_create(section=self._section.name(), key=self._key) # @UndefinedVariable
obj.value, obj.crypt, obj.long, obj.field_type = value, self._crypt, self._longText, self._type
obj.save()
except Exception:
@ -180,7 +180,7 @@ class Config(object):
@staticmethod
def enumerate():
GlobalConfig.initialize() # Ensures DB contains all values
for cfg in dbConfig.objects.all().order_by('key'): # @UndefinedVariable
for cfg in uds.models.Config.objects.all().order_by('key'): # @UndefinedVariable
logger.debug('{0}.{1}:{2},{3}'.format(cfg.section, cfg.key, cfg.value, cfg.field_type))
if cfg.crypt is True:
val = Config.section(cfg.section).valueCrypt(cfg.key)
@ -192,7 +192,7 @@ class Config(object):
def update(section, key, value):
# If cfg value does not exists, simply ignore request
try:
cfg = dbConfig.objects.filter(section=section, key=key)[0] # @UndefinedVariable
cfg = uds.models.Config.objects.filter(section=section, key=key)[0] # @UndefinedVariable
if cfg.crypt is True:
value = CryptoManager.manager().encrypt(value)
cfg.value = value

View File

@ -32,3 +32,9 @@
'''
from __future__ import unicode_literals
from . import action
from . import process
from . import userService
from . import servicePool
from . import task
from . import group

View File

@ -32,8 +32,7 @@
'''
from __future__ import unicode_literals
import logging
__updated__ = '2016-02-19'
__updated__ = '2015-11-17'
logger = logging.getLogger(__name__)
ALLOW = 'ALLOW'
DENY = 'DENY'

View File

@ -0,0 +1,141 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 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_noop as _, ugettext_lazy
import logging
__updated__ = '2016-02-19'
logger = logging.getLogger(__name__)
ACTIVE = 'A'
BLOCKED = 'B'
CANCELED = 'C'
ERROR = 'E'
FINISHED = 'F'
BALANCING = 'H'
INACTIVE = 'I'
CANCELING = 'K'
LAUNCHING = 'L'
REMOVING = 'M'
PREPARING = 'P'
REMOVABLE = 'R'
REMOVED = 'S'
USABLE = 'U'
RUNNING = 'W'
FOR_EXECUTE = 'X'
MAINTENANCE = 'Y' # "Visual" state, no element will be in fact in maintenance, but used to show "Services Pools" for which a Provider is in maintenance
WAITING_OS = 'Z' # "Visual" state, no element will be in fact in WAITING_OS, but used to show "User Services" that are whating for os manager
string = {
ACTIVE: _('Active'),
INACTIVE: _('Inactive'),
BLOCKED: _('Blocked'),
LAUNCHING: _('Waiting publication'),
PREPARING: _('In preparation'),
USABLE: _('Valid'),
REMOVABLE: _('Waiting for removal'),
REMOVING: _('Removing'),
REMOVED: _('Removed'),
CANCELED: _('Canceled'),
CANCELING: _('Canceling'),
ERROR: _('Error'),
RUNNING: _('Running'),
FINISHED: _('Finished'),
FOR_EXECUTE: _('Waiting execution'),
BALANCING: _('Balancing'),
MAINTENANCE: _('In maintenance'),
WAITING_OS: _('Waiting OS')
}
# States that are merely for "information" to the user. They don't contain any usable instance
INFO_STATES = [REMOVED, CANCELED, ERROR]
# States that indicates that the service is "Valid" for a user
VALID_STATES = [USABLE, PREPARING]
# Publication States
PUBLISH_STATES = [LAUNCHING, PREPARING]
def isActive(state):
return state == ACTIVE
def isInactive(state):
return state == INACTIVE
def isBlocked(state):
return state == BLOCKED
def isPreparing(state):
return state == PREPARING
def isUsable(state):
return state == USABLE
def isRemovable(state):
return state == REMOVABLE
def isRemoving(state):
return state == REMOVING
def isRemoved(state):
return state == REMOVED
def isCanceling(state):
return state == CANCELING
def isCanceled(state):
return state == CANCELED
def isErrored(state):
return state == ERROR
def isFinished(state):
return state == FINISHED
def isRuning(state):
return state == RUNNING
def isForExecute(state):
return state == FOR_EXECUTE
def toString(state):
return string.get(state, '')
def dictionary():
'''
Returns a dictionary with current active locale translation of States to States String
'''
return dict([(k, ugettext_lazy(v)) for k, v in string.iteritems()])

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 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
# pylint: disable=unused-import
from .common import ACTIVE # @UnusedImport
__updated__ = '2016-02-19'

View File

@ -32,12 +32,7 @@
'''
from __future__ import unicode_literals
import logging
# pylint: disable=unused-import
from .common import ERROR, FINISHED, RUNNING # @UnusedImport
__updated__ = '2015-11-17'
logger = logging.getLogger(__name__)
ERROR = 'E'
FINISHED = 'F'
RUNNING = 'W'
__updated__ = '2016-02-19'

View File

@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 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
# pylint: disable=unused-import
from .common import ERROR, USABLE # @UnusedImport

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 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
# pylint: disable=unused-import
from .common import ACTIVE, REMOVABLE, REMOVING, REMOVED # @UnusedImport
__updated__ = '2016-02-19'

View File

@ -32,10 +32,7 @@
'''
from __future__ import unicode_literals
import logging
# pylint: disable=unused-import
from .common import FOR_EXECUTE # @UnusedImport
__updated__ = '2015-11-17'
logger = logging.getLogger(__name__)
FOR_EXECUTE = 'X'
__updated__ = '2016-02-19'

View File

@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 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
# pylint: disable=unused-import
from .common import ERROR, USABLE, PREPARING, REMOVABLE, REMOVING, REMOVED # @UnusedImport
__updated__ = '2016-02-19'

View File

@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-19 07:26
from __future__ import unicode_literals
from django.db import models, migrations
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
@ -14,11 +16,11 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='CalendarAccess',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', models.CharField(default=None, max_length=50, unique=True, null=True)),
('allow', models.BooleanField(default=True)),
('priority', models.IntegerField(default=0, db_index=True)),
('calendar', models.ForeignKey(to='uds.Calendar')),
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=None, max_length=50, null=True, unique=True)),
('access', models.CharField(default='DENY', max_length=8)),
('priority', models.IntegerField(db_index=True, default=0)),
('calendar', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uds.Calendar')),
],
options={
'ordering': ('priority',),
@ -28,11 +30,11 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='CalendarAction',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', models.CharField(default=None, max_length=50, unique=True, null=True)),
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.CharField(default=None, max_length=50, null=True, unique=True)),
('action', models.CharField(max_length=64)),
('params', models.CharField(max_length=1024)),
('calendar', models.ForeignKey(to='uds.Calendar')),
('calendar', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uds.Calendar')),
],
options={
'db_table': 'uds_cal_action',
@ -40,18 +42,18 @@ class Migration(migrations.Migration):
),
migrations.AddField(
model_name='deployedservice',
name='fallbackAccessAllow',
field=models.BooleanField(default=True),
name='fallbackAccess',
field=models.CharField(default='ALLOW', max_length=8),
),
migrations.AddField(
model_name='calendaraction',
name='servicePool',
field=models.ForeignKey(to='uds.DeployedService'),
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uds.DeployedService'),
),
migrations.AddField(
model_name='calendaraccess',
name='servicePool',
field=models.ForeignKey(to='uds.DeployedService'),
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uds.DeployedService'),
),
migrations.AddField(
model_name='deployedservice',

View File

@ -34,9 +34,10 @@
from __future__ import unicode_literals
__updated__ = '2016-02-18'
__updated__ = '2016-02-19'
from django.db import models
from uds.core.util import states
from uds.models.UUIDModel import UUIDModel
from uds.models.Calendar import Calendar
from uds.models.ServicesPool import ServicePool
@ -46,11 +47,10 @@ import logging
logger = logging.getLogger(__name__)
class CalendarAccess(UUIDModel):
calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)
servicePool = models.ForeignKey(ServicePool, on_delete=models.CASCADE)
allow = models.BooleanField(default=True)
access = models.CharField(max_length=8, default=states.action.DENY)
priority = models.IntegerField(default=0, db_index=True)
class Meta:

View File

@ -39,7 +39,7 @@ from django.utils.encoding import python_2_unicode_compatible
from uds.core.Environment import Environment
from uds.core.util import log
from uds.core.util.State import State
from uds.core.util import states
from uds.core.services.Exceptions import InvalidServiceException
from uds.models.UUIDModel import UUIDModel
from uds.models.Tag import TaggingMixin
@ -60,7 +60,7 @@ from uds.core.util.calendar import CalendarChecker
from datetime import timedelta
import logging
__updated__ = '2016-02-18'
__updated__ = '2016-02-19'
logger = logging.getLogger(__name__)
@ -77,7 +77,7 @@ class DeployedService(UUIDModel, TaggingMixin):
osmanager = models.ForeignKey(OSManager, null=True, blank=True, related_name='deployedServices')
transports = models.ManyToManyField(Transport, related_name='deployedServices', db_table='uds__ds_trans')
assignedGroups = models.ManyToManyField(Group, related_name='deployedServices', db_table='uds__ds_grps')
state = models.CharField(max_length=1, default=State.ACTIVE, db_index=True)
state = models.CharField(max_length=1, default=states.servicePool.ACTIVE, db_index=True)
state_date = models.DateTimeField(default=NEVER)
show_transports = models.BooleanField(default=True)
image = models.ForeignKey(Image, null=True, blank=True, related_name='deployedServices', on_delete=models.SET_NULL)
@ -86,7 +86,7 @@ class DeployedService(UUIDModel, TaggingMixin):
accessCalendars = models.ManyToManyField(Calendar, related_name='accessSP', through='CalendarAccess')
# Default fallback action for access
fallbackAccessAllow = models.BooleanField(default=True)
fallbackAccess = models.CharField(default=states.action.ALLOW, max_length=8)
actionsCalendars = models.ManyToManyField(Calendar, related_name='actionsSP', through='CalendarAction')
@ -123,7 +123,7 @@ class DeployedService(UUIDModel, TaggingMixin):
None if there is no valid publication for this deployed service.
'''
try:
return self.publications.filter(state=State.USABLE)[0]
return self.publications.filter(state=states.publication.USABLE)[0]
except Exception:
return None
@ -154,7 +154,7 @@ class DeployedService(UUIDModel, TaggingMixin):
min_ = GlobalConfig.RESTRAINT_COUNT.getInt()
res = []
for v in UserService.objects.filter(state=State.ERROR, state_date__gt=date).values('deployed_service').annotate(how_many=Count('deployed_service')):
for v in UserService.objects.filter(state=states.userService.ERROR, state_date__gt=date).values('deployed_service').annotate(how_many=Count('deployed_service')):
if v['how_many'] >= min_:
res.append(v['deployed_service'])
return DeployedService.objects.filter(pk__in=res)
@ -183,7 +183,7 @@ class DeployedService(UUIDModel, TaggingMixin):
return False # Do not perform any restraint check if we set the globalconfig to 0 (or less)
date = getSqlDatetime() - timedelta(seconds=GlobalConfig.RESTRAINT_TIME.getInt())
if self.userServices.filter(state=State.ERROR, state_date__gt=date).count() >= GlobalConfig.RESTRAINT_COUNT.getInt():
if self.userServices.filter(state=states.userService.ERROR, state_date__gt=date).count() >= GlobalConfig.RESTRAINT_COUNT.getInt():
return True
return False
@ -198,13 +198,13 @@ class DeployedService(UUIDModel, TaggingMixin):
if chkDateTime is None:
chkDateTime = getSqlDatetime()
allow = self.fallbackAccessAllow
access = self.fallbackAccess
# Let's see if we can access by current datetime
for ac in self.calendaraccess_set.all():
if CalendarChecker(ac.calendar).check(chkDateTime) is True:
allow = ac.allow
access = ac.access
return allow
return access == states.action.ALLOW
def storeValue(self, name, value):
@ -250,7 +250,7 @@ class DeployedService(UUIDModel, TaggingMixin):
The background worker will be the responsible for removing the deployed service
'''
self.setState(State.REMOVABLE)
self.setState(states.servicePool.REMOVABLE)
def removed(self):
'''
@ -284,10 +284,10 @@ class DeployedService(UUIDModel, TaggingMixin):
logger.error('No active publication, don\'t know what to erase!!! (ds = {0})'.format(self))
return
for ap in self.publications.exclude(id=activePub.id):
for u in ap.userServices.filter(state=State.PREPARING):
for u in ap.userServices.filter(state=states.userService.PREPARING):
u.cancel()
ap.userServices.exclude(cache_level=0).filter(state=State.USABLE).update(state=State.REMOVABLE, state_date=now)
ap.userServices.filter(cache_level=0, state=State.USABLE, in_use=False).update(state=State.REMOVABLE, state_date=now)
ap.userServices.exclude(cache_level=0).filter(state=states.userService.USABLE).update(state=states.userService.REMOVABLE, state_date=now)
ap.userServices.filter(cache_level=0, state=states.userService.USABLE, in_use=False).update(state=states.userService.REMOVABLE, state_date=now)
def validateGroups(self, grps):
'''
@ -349,11 +349,11 @@ class DeployedService(UUIDModel, TaggingMixin):
'''
from uds.core import services
# Get services that HAS publications
list1 = DeployedService.objects.filter(assignedGroups__in=groups, assignedGroups__state=State.ACTIVE,
state=State.ACTIVE).distinct().annotate(cuenta=models.Count('publications')).exclude(cuenta=0)
list1 = DeployedService.objects.filter(assignedGroups__in=groups, assignedGroups__state=states.group.ACTIVE,
state=states.servicePool.ACTIVE).distinct().annotate(cuenta=models.Count('publications')).exclude(cuenta=0)
# Now get deployed services that DO NOT NEED publication
doNotNeedPublishing = [t.type() for t in services.factory().servicesThatDoNotNeedPublication()]
list2 = DeployedService.objects.filter(assignedGroups__in=groups, assignedGroups__state=State.ACTIVE, service__data_type__in=doNotNeedPublishing, state=State.ACTIVE)
list2 = DeployedService.objects.filter(assignedGroups__in=groups, assignedGroups__state=states.group.ACTIVE, service__data_type__in=doNotNeedPublishing, state=states.servicePool.ACTIVE)
# And generate a single list without duplicates
return list(set([r for r in list1] + [r for r in list2]))

View File

@ -543,6 +543,14 @@ gui.servicesPools.link = (event) ->
"delete"
"xls"
]
onData: (data) ->
data.push
id: -1,
name: 'DEFAULT',
priority: '<span style="visibility: hidden;">10000000</span>FallBack',
action: servPool.allowAccessByDefault
)
prevTables.push accessCalendarsTable

View File

@ -185,7 +185,6 @@
<!-- page contents -->
{% js_template 'dashboard' %}
{% js_template 'restricted' %}
{% js_template 'dashboard' %}
{% js_template 'providers' %}
{% js_template 'authenticators' %}
{% js_template 'osmanagers' %}

View File

@ -34,6 +34,7 @@ from __future__ import unicode_literals
from django import template
from django.conf import settings
from django.utils import safestring
from uds.REST import AUTH_TOKEN_HEADER
import re
@ -70,8 +71,8 @@ def js_template(context, template_name, template_id=None):
tmpl = template.loader.get_template(context['template_path'] + '/' + template_name + '.html').render(context)
# Clean tmpl
if not settings.DEBUG:
tmpl = re.sub('\s+', ' ', tmpl)
return '<script id="{0}" type="template/uds">{1}</script>'.format(template_id, tmpl)
tmpl = re.sub(r'\s+', ' ', tmpl)
return safestring.mark_safe('<script id="{0}" type="template/uds">{1}</script>'.format(template_id, tmpl))
@register.simple_tag(name='js_template_jade', takes_context=True)
@ -81,4 +82,4 @@ def js_template_jade(context, template_name, template_id=None):
# Clean tmpl
if not settings.DEBUG:
tmpl = re.sub('\s+', ' ', tmpl)
return '<script id="{0}" type="template/uds">{1}</script>'.format(template_id, tmpl)
return safestring.mark_safe('<script id="{0}" type="template/uds">{1}</script>'.format(template_id, tmpl))

View File

@ -36,7 +36,7 @@ from django.utils.translation import ugettext_lazy as _, ugettext
from django import forms
from django.utils.safestring import mark_safe
from django.forms.forms import NON_FIELD_ERRORS
from django.forms.util import ErrorDict
# from django.forms.util import ErrorDict
from uds.models import Authenticator
import logging
@ -58,20 +58,20 @@ class CustomSelect(forms.Select):
return mark_safe('<div class="form-group"{0}><label>'.format(visible) + unicode(_('authenticator')) + '</label>' + res + '</div>')
class BaseForm(forms.Form):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
def add_form_error(self, message):
if not self._errors:
self._errors = ErrorDict()
if NON_FIELD_ERRORS not in self._errors:
self._errors[NON_FIELD_ERRORS] = self.error_class()
self._errors[NON_FIELD_ERRORS].append(message)
# class BaseForm(forms.Form):
#
# def __init__(self, *args, **kwargs):
# super(BaseForm, self).__init__(*args, **kwargs)
#
# def add_form_error(self, message):
# if not self._errors:
# self._errors = ErrorDict()
# if NON_FIELD_ERRORS not in self._errors:
# self._errors[NON_FIELD_ERRORS] = self.error_class()
# self._errors[NON_FIELD_ERRORS].append(message)
class LoginForm(BaseForm):
class LoginForm(forms.Form):
user = forms.CharField(label=_('Username'), max_length=64, widget=forms.TextInput())
password = forms.CharField(label=_('Password'), widget=forms.PasswordInput(attrs={'title': _('Password')}), required=False)
authenticator = forms.ChoiceField(label=_('Authenticator'), choices=(), widget=CustomSelect(), required=False)