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

* Improved cache for calendars checkings

* Added calentar access & actions models
* Started calendar-pool integration
This commit is contained in:
Adolfo Gómez García 2016-02-17 10:55:51 +01:00
parent 4f9085f0a2
commit cbb809db77
8 changed files with 249 additions and 9 deletions

View File

@ -44,6 +44,7 @@ from uds.models import ServicePool, UserService, getSqlDatetime, Transport
from uds.core import services
from uds.core.services import Service
from uds.core.util.stats import events
from uds.core.util.calendar import CalendarChecker
from .userservice.opchecker import UserServiceOpChecker
@ -51,7 +52,7 @@ import requests
import json
import logging
__updated__ = '2015-11-11'
__updated__ = '2016-02-17'
logger = logging.getLogger(__name__)
@ -420,6 +421,22 @@ class UserServiceManager(object):
uService.setState(State.PREPARING)
UserServiceOpChecker.makeUnique(uService, ui, state)
def accessAllowed(self, servicePool, chkDateTime=None):
'''
Checks if the access for a service pool is allowed or not (based esclusively on associated calendars)
'''
if chkDateTime is None:
chkDateTime = getSqlDatetime()
allow = servicePool.fallbackAccessAllow
# Let's see if we can access by current datetime
for ac in servicePool.accessCalendars.all():
if CalendarChecker(ac.calender).check(chkDateTime) is True:
allow = ac.allow
return allow
def getService(self, user, srcIp, idService, idTransport, doTest=True):
'''
Get service info from

View File

@ -38,20 +38,31 @@ from uds.models.Util import getSqlDatetime
from uds.models.Calendar import Calendar
from uds.core.util.Cache import Cache
import datetime
import six
import bitarray
import logging
__updated__ = '2015-09-18'
__updated__ = '2016-02-17'
logger = logging.getLogger(__name__)
class CalendarChecker(object):
data = None
data_time = None
calendar = None
inverse = False
cache = None
# For performance checking
updates = 0
cache_hit = 0
hits = 0
cache = Cache('calChecker')
def __init__(self, calendar, inverse=False):
self.calendar = calendar
@ -61,9 +72,20 @@ class CalendarChecker(object):
self.data_time = None
def _updateData(self, dtime):
self.updates += 1
# Else, update the array
CalendarChecker.updates += 1
self.calendar_modified = self.calendar.modified
self.data_time = dtime.date()
# First, try to get data from cache if it is valid
cacheKey = six.text_type(self.calendar.modified.toordinal()) + six.text_type(self.data_time.toordinal()) + self.calendar.uuid
cached = CalendarChecker.cache.get(cacheKey, None)
if cached is not None:
self.data = bitarray.bitarray() # Empty bitarray
self.data.frombytes(cached)
CalendarChecker.cache_hit += 1
return
self.data = bitarray.bitarray(60 * 24) # Granurality is minute
self.data.setall(False)
@ -100,17 +122,22 @@ class CalendarChecker(object):
posdur = 60 * 24
self.data[pos:posdur] = True
# Now self.data can be accessed as an array of booleans, and if
# Now self.data can be accessed as an array of booleans.
# Store data on persistent cache
CalendarChecker.cache.put(cacheKey, self.data.tobytes(), 3600 * 24)
def check(self, dtime=None):
'''
Checks if the given time is a valid event on calendar
@param dtime: Datetime object to check
TODO: We can improve performance of this by getting from a cache first if we can
'''
if dtime is None:
dtime = datetime.datetime.now()
if self.calendar_modified != self.calendar.modified or self.data is None or self.data_time != dtime.date():
self._updateData(dtime)
else:
CalendarChecker.hits += 1
return self.data[dtime.hour * 60 + dtime.minute]

View File

@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('uds', '0020_auto_20160216_0509'),
]
operations = [
migrations.CreateModel(
name='CalendarAccess',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('allow', models.BooleanField(default=True)),
('priority', models.IntegerField(default=0, db_index=True)),
('calendar', models.ForeignKey(to='uds.Calendar')),
],
options={
'db_table': 'uds_cal_access',
},
),
migrations.CreateModel(
name='CalendarAction',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('action', models.CharField(max_length=64)),
('params', models.CharField(max_length=1024)),
('calendar', models.ForeignKey(to='uds.Calendar')),
],
options={
'db_table': 'uds_cal_action',
},
),
migrations.AddField(
model_name='deployedservice',
name='fallbackAccessAllow',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='calendaraction',
name='servicePool',
field=models.ForeignKey(to='uds.DeployedService'),
),
migrations.AddField(
model_name='calendaraccess',
name='servicePool',
field=models.ForeignKey(to='uds.DeployedService'),
),
migrations.AddField(
model_name='deployedservice',
name='accessCalendars',
field=models.ManyToManyField(related_name='accessSP', through='uds.CalendarAccess', to='uds.Calendar'),
),
migrations.AddField(
model_name='deployedservice',
name='actionsCalendars',
field=models.ManyToManyField(related_name='actionsSP', through='uds.CalendarAction', to='uds.Calendar'),
),
]

View File

@ -34,7 +34,7 @@
from __future__ import unicode_literals
__updated__ = '2016-02-10'
__updated__ = '2016-02-17'
from django.db import models
from uds.models.UUIDModel import UUIDModel

View File

@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
# Model based on https://github.com/llazzaro/django-scheduler
#
# 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.
'''
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
__updated__ = '2016-02-17'
from django.db import models
from uds.models.Calendar import Calendar
from uds.models.ServicesPool import ServicePool
from django.utils.encoding import python_2_unicode_compatible
# from django.utils.translation import ugettext_lazy as _, ugettext
import logging
logger = logging.getLogger(__name__)
class CalendarAccess(models.Model):
calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)
servicePool = models.ForeignKey(ServicePool, on_delete=models.CASCADE)
allow = models.BooleanField(default=True)
priority = models.IntegerField(default=0, db_index=True)
class Meta:
'''
Meta class to declare db table
'''
db_table = 'uds_cal_access'
app_label = 'uds'

View File

@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
# Model based on https://github.com/llazzaro/django-scheduler
#
# 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.
'''
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
__updated__ = '2016-02-17'
from django.db import models
from uds.models.Calendar import Calendar
from uds.models.ServicesPool import ServicePool
from django.utils.encoding import python_2_unicode_compatible
# from django.utils.translation import ugettext_lazy as _, ugettext
import logging
logger = logging.getLogger(__name__)
class CalendarAction(models.Model):
calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)
servicePool = models.ForeignKey(ServicePool, on_delete=models.CASCADE)
action = models.CharField(max_length=64)
params = models.CharField(max_length=1024)
class Meta:
'''
Meta class to declare db table
'''
db_table = 'uds_cal_action'
app_label = 'uds'

View File

@ -50,6 +50,7 @@ from uds.models.Transport import Transport
from uds.models.Group import Group
from uds.models.Image import Image
from uds.models.ServicesPoolGroup import ServicesPoolGroup
from uds.models.Calendar import Calendar
from uds.models.Util import NEVER
from uds.models.Util import getSqlDatetime
@ -57,12 +58,11 @@ from uds.models.Util import getSqlDatetime
from datetime import timedelta
import logging
__updated__ = '2016-02-12'
__updated__ = '2016-02-17'
logger = logging.getLogger(__name__)
@python_2_unicode_compatible
class DeployedService(UUIDModel, TaggingMixin):
'''
@ -82,6 +82,12 @@ class DeployedService(UUIDModel, TaggingMixin):
servicesPoolGroup = models.ForeignKey(ServicesPoolGroup, null=True, blank=True, related_name='servicesPools', on_delete=models.SET_NULL)
accessCalendars = models.ManyToManyField(Calendar, related_name='accessSP', through='CalendarAccess')
# Default fallback action for access
fallbackAccessAllow = models.BooleanField(default=True)
actionsCalendars = models.ManyToManyField(Calendar, related_name='actionsSP', through='CalendarAction')
initial_srvs = models.PositiveIntegerField(default=0)
cache_l1_srvs = models.PositiveIntegerField(default=0)
cache_l2_srvs = models.PositiveIntegerField(default=0)

View File

@ -99,10 +99,13 @@ from .TicketStore import TicketStore
from .Calendar import Calendar
from .CalendarRule import CalendarRule
from .CalendarAccess import CalendarAccess
from .CalendarAction import CalendarAction
# Tagging
from .Tag import Tag
__updated__ = '2016-02-12'
__updated__ = '2016-02-17'
logger = logging.getLogger(__name__)