Fixing up proxy

This commit is contained in:
Adolfo Gómez García 2017-05-10 09:50:49 +02:00
parent e8888afd22
commit bdefd11ade
11 changed files with 91 additions and 46 deletions

View File

@ -32,10 +32,9 @@
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext, ugettext_lazy as _
from uds.models import Service, UserService, Tag
from uds.models import Service, UserService, Tag, Proxy
from uds.core.services import Service as coreService
from uds.core.util import log
@ -46,6 +45,7 @@ from uds.REST.model import DetailHandler
from uds.REST import NotFound, ResponseError, RequestError
from django.db import IntegrityError
from uds.core.ui.images import DEFAULT_THUMB_BASE64
from uds.core.ui.UserInterface import gui
from uds.core.util.State import State
import six
@ -93,6 +93,8 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
'comments': item.comments,
'type': item.data_type,
'type_name': _(itemType.name()),
'proxy_id': item.proxy.uuid if item.proxy is not None else '-1',
'proxy': item.proxy.name if item.proxy is not None else '',
'deployed_services_count': item.deployedServices.count(),
'user_services_count': UserService.objects.filter(deployed_service__service=item).exclude(state__in=(State.REMOVED, State.ERROR)).count(),
'maintenance_mode': item.provider.maintenance_mode,
@ -135,10 +137,22 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
# Extract item db fields
# We need this fields for all
logger.debug('Saving service {0} / {1}'.format(parent, item))
fields = self.readFieldsFromParams(['name', 'comments', 'data_type', 'tags'])
fields = self.readFieldsFromParams(['name', 'comments', 'data_type', 'tags', 'proxy_id'])
tags = fields['tags']
del fields['tags']
service = None
proxyId = fields['proxy_id']
fields['proxy_id'] = None
logger.debug('Proxy id: {}'.format(proxyId))
proxy = None
if proxyId != '-1':
try:
proxy = Proxy.objects.get(uuid=processUuid(proxyId))
except Exception:
logger.exception('Getting proxy ID')
try:
if item is None: # Create new
service = parent.services.create(**fields)
@ -147,6 +161,7 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
service.__dict__.update(fields)
service.tags = [Tag.objects.get_or_create(tag=val)[0] for val in tags]
service.proxy = proxy
service.data = service.getInstance(self._params).serialize() # This may launch an validation exception (the getInstance(...) part)
service.save()
@ -190,6 +205,7 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
{'name': {'title': _('Service name'), 'visible': True, 'type': 'iconType'}},
{'comments': {'title': _('Comments')}},
{'type_name': {'title': _('Type')}},
{'proxy': {'title': _('Proxy')}},
{'deployed_services_count': {'title': _('Services Pools'), 'type': 'numeric'}},
{'user_services_count': {'title': _('User services'), 'type': 'numeric'}},
{'tags': {'title': _('tags'), 'visible': False}},
@ -220,7 +236,21 @@ class Services(DetailHandler): # pylint: disable=too-many-public-methods
parentInstance = parent.getInstance()
serviceType = parentInstance.getServiceByType(forType)
service = serviceType(Environment.getTempEnv(), parentInstance) # Instantiate it so it has the opportunity to alter gui description based on parent
return self.addDefaultFields(service.guiDescription(service), ['name', 'comments', 'tags'])
g = self.addDefaultFields(service.guiDescription(service), ['name', 'comments', 'tags'])
for f in [{
'name': 'proxy_id',
'values': [gui.choiceItem(-1, '')] + gui.sortedChoices([gui.choiceItem(v.uuid, v.name) for v in Proxy.objects.all()]),
'label': ugettext('Proxy'),
'tooltip': ugettext('Proxy for services behind a firewall'),
'type': gui.InputField.CHOICE_TYPE,
'tab': ugettext('Advanced'),
'order': 132,
},
]:
self.addField(g, f)
return g
except Exception as e:
logger.exception('getGui')
raise ResponseError(six.text_type(e))

View File

@ -33,7 +33,7 @@
from __future__ import unicode_literals
from django.utils.translation import ugettext, ugettext_lazy as _
from uds.models import DeployedService, OSManager, Service, Image, ServicesPoolGroup, Account, Proxy
from uds.models import DeployedService, OSManager, Service, Image, ServicesPoolGroup, Account
from uds.models.CalendarAction import CALENDAR_ACTION_INITIAL, CALENDAR_ACTION_MAX, CALENDAR_ACTION_CACHE_L1, CALENDAR_ACTION_CACHE_L2, CALENDAR_ACTION_PUBLISH
from uds.core.ui.images import DEFAULT_THUMB_BASE64
from uds.core.util.State import State
@ -78,7 +78,6 @@ class ServicesPools(ModelHandler):
'osmanager_id',
'image_id',
'account_id',
'proxy_id',
'servicesPoolGroup_id',
'initial_srvs',
'cache_l1_srvs',
@ -134,13 +133,11 @@ class ServicesPools(ModelHandler):
'state': state,
'thumb': item.image.thumb64 if item.image is not None else DEFAULT_THUMB_BASE64,
'account': item.account.name if item.account is not None else '',
'proxy': item.proxy.name if item.proxy is not None else '',
'service_id': item.service.uuid,
'provider_id': item.service.provider.uuid,
'image_id': item.image.uuid if item.image is not None else None,
'servicesPoolGroup_id': poolGroupId,
'account_id': item.account.uuid if item.account is not None else None,
'proxy_id': item.proxy.uuid if item.proxy is not None else None,
'pool_group_name': poolGroupName,
'pool_group_thumb': poolGroupThumb,
'initial_srvs': item.initial_srvs,
@ -263,14 +260,6 @@ class ServicesPools(ModelHandler):
'type': gui.InputField.CHOICE_TYPE,
'tab': ugettext('Advanced'),
'order': 131,
}, {
'name': 'proxy_id',
'values': [gui.choiceItem(-1, '')] + gui.sortedChoices([gui.choiceItem(v.uuid, v.name) for v in Proxy.objects.all()]),
'label': ugettext('Proxy'),
'tooltip': ugettext('Proxy for services behind a firewall'),
'type': gui.InputField.CHOICE_TYPE,
'tab': ugettext('Advanced'),
'order': 132,
},
]:
@ -331,18 +320,6 @@ class ServicesPools(ModelHandler):
except Exception:
logger.exception('Getting account ID')
# *** PROXY ***
proxyId = fields['proxy_id']
fields['proxy_id'] = None
logger.debug('Proxy id: {}'.format(proxyId))
if proxyId != '-1':
try:
fields['proxy_id'] = Proxy.objects.get(uuid=processUuid(proxyId)).id
except Exception:
logger.exception('Getting proxy ID')
# **** IMAGE ***
imgId = fields['image_id']
fields['image_id'] = None

View File

@ -42,7 +42,7 @@ from uds.core.util import connection
import six
import logging
__updated__ = '2017-03-10'
__updated__ = '2017-05-10'
logger = logging.getLogger(__name__)
@ -109,7 +109,7 @@ class Transport(Module):
pass
def testServer(self, userService, ip, port, timeout=4):
proxy = userService.deployed_service.proxy
proxy = userService.deployed_service.service.proxy
if proxy is not None:
return proxy.doTestServer(ip, port, timeout)
return connection.testServer(ip, six.text_type(port), timeout)

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 19:58
# Generated by Django 1.11.1 on 2017-05-10 08:21
from __future__ import unicode_literals
import datetime
@ -79,8 +79,8 @@ class Migration(migrations.Migration):
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='servicesPools', to='uds.Account'),
),
migrations.AddField(
model_name='deployedservice',
model_name='service',
name='proxy',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='servicesPools', to='uds.Proxy'),
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='services', to='uds.Proxy'),
),
]

View File

@ -42,13 +42,16 @@ from uds.core.util import log
from uds.core.util import unique
from uds.models.ManagedObjectModel import ManagedObjectModel
from uds.models.Tag import TaggingMixin
from uds.models.Proxy import Proxy
from uds.core.util import connection
from uds.models.Provider import Provider
import logging
import six
__updated__ = '2016-03-09'
__updated__ = '2017-05-10'
logger = logging.getLogger(__name__)
@ -63,6 +66,10 @@ class Service(ManagedObjectModel, TaggingMixin):
# pylint: disable=model-missing-unicode
provider = models.ForeignKey(Provider, related_name='services')
# Proxy for this service
proxy = models.ForeignKey(Proxy, null=True, blank=True, related_name='services')
class Meta(ManagedObjectModel.Meta):
'''
Meta class to declare default order and unique multiple field index
@ -133,6 +140,11 @@ class Service(ManagedObjectModel, TaggingMixin):
def isInMaintenance(self):
return self.provider is not None and self.provider.isInMaintenance()
def testServer(self, host, port, timeout=4):
if self.proxy is not None:
return self.proxy.doTestServer(host, port, timeout)
return connection.testServer(host, six.text_type(port), timeout)
def __str__(self):
return u"{0} of type {1} (id:{2})".format(self.name, self.data_type, self.id)

View File

@ -52,7 +52,6 @@ from uds.models.Image import Image
from uds.models.ServicesPoolGroup import ServicesPoolGroup
from uds.models.Calendar import Calendar
from uds.models.Account import Account
from uds.models.Proxy import Proxy
from uds.models.Util import NEVER
from uds.models.Util import getSqlDatetime
@ -63,7 +62,7 @@ from datetime import datetime, timedelta
import logging
import pickle
__updated__ = '2017-04-06'
__updated__ = '2017-05-10'
logger = logging.getLogger(__name__)
@ -96,9 +95,6 @@ class DeployedService(UUIDModel, TaggingMixin):
# Usage accounting
account = models.ForeignKey(Account, null=True, blank=True, related_name='servicesPools')
# Proxy for this pool
proxy = models.ForeignKey(Proxy, null=True, blank=True, related_name='servicesPools')
initial_srvs = models.PositiveIntegerField(default=0)
cache_l1_srvs = models.PositiveIntegerField(default=0)
cache_l2_srvs = models.PositiveIntegerField(default=0)
@ -472,6 +468,9 @@ class DeployedService(UUIDModel, TaggingMixin):
'''
return self.userServices.filter(cache_level=0, user=None)
def testServer(self, host, port, timeout=4):
return self.service.testServer(host, port, timeout)
@staticmethod
def beforeDelete(sender, **kwargs):
'''

View File

@ -57,7 +57,7 @@ import six
import pickle
import logging
__updated__ = '2016-04-26'
__updated__ = '2017-05-10'
logger = logging.getLogger(__name__)
@ -512,6 +512,9 @@ class UserService(UUIDModel):
'''
return self.deployed_service.service.getType().publicationType is None or self.publication == self.deployed_service.activePublication()
def testServer(self, host, port, timeout=4):
return self.deployed_service.testServer(host, port, timeout)
def __str__(self):
return "User service {0}, cache_level {1}, user {2}, name {3}, state {4}:{5}".format(self.id, self.cache_level, self.user, self.friendly_name,
State.toString(self.state), State.toString(self.os_state))

View File

@ -1,5 +1,18 @@
# jshint strict: true
gui.providers = new GuiElement(api.providers, "provi")
gui.providers.fastLink = (event, obj) ->
gui.doLog 'FastLink clicked', obj
event.preventDefault()
event.stopPropagation()
$obj = $(obj);
if $obj.hasClass('goProxyGroupLink')
gui.lookupUuid = $obj.attr('href').substr(1)
setTimeout( ->
$(".lnk-proxies").click();
, 50
)
gui.providers.link = (event) ->
"use strict"
@ -187,6 +200,17 @@ gui.providers.link = (event) ->
onLoad: (k) ->
gui.tools.unblockUI()
return
onData: (data) ->
$.each data, (index, value) ->
try
if value.proxy_id != '-1'
value.proxy = gui.fastLink(value.proxy, value.proxy_id, 'gui.providers.fastLink', 'goProxyGroupLink')
catch e
value.name = "<span class=\"fa fa-asterisk text-alert\"></span> " + value.name
return
return
)
logTable = gui.providers.logTable(id,
container: "logs-placeholder"

View File

@ -479,7 +479,7 @@ gui.servicesPools.link = (event) ->
style_grp = "display:inline-block; background: url(data:image/png;base64," + value.pool_group_thumb + "); background-size: 16px 16px; background-repeat: no-repeat; width: 16px; height: 16px; vertical-align: middle;"
value.parent = gui.fastLink(value.parent, "#{value.provider_id},#{value.service_id}", 'gui.servicesPools.fastLink', 'goServiceLink')
value.pool_group_name = "<span style='#{style_grp}'></span> #{value.pool_group_name}"
if value.pool_group_id?
if value.servicesPoolGroup_id?
value.pool_group_name = gui.fastLink(value.pool_group_name, value.pool_group_id, 'gui.servicesPools.fastLink', 'goPoolGroupLink')
if value.restrained
value.name = "<span class=\"fa fa-exclamation text-danger\"></span> " + value.name

View File

@ -68,7 +68,7 @@ def js_template_path(context, path):
@register.simple_tag(name='js_template', takes_context=True)
def js_template(context, template_name, template_id=None):
template_id = (template_id or 'tmpl_' + template_name).replace('/', '_')
tmpl = template.loader.get_template(context['template_path'] + '/' + template_name + '.html').render(context)
tmpl = template.loader.get_template(context['template_path'] + '/' + template_name + '.html').render(context.flatten())
# Clean tmpl
if not settings.DEBUG:
tmpl = re.sub(r'\s+', ' ', tmpl)
@ -78,7 +78,7 @@ def js_template(context, template_name, template_id=None):
@register.simple_tag(name='js_template_jade', takes_context=True)
def js_template_jade(context, template_name, template_id=None):
template_id = (template_id or 'tmpl_' + template_name).replace('/', '_')
tmpl = template.loader.get_template(context['template_path'] + '/' + template_name + '.jade').render(context)
tmpl = template.loader.get_template(context['template_path'] + '/' + template_name + '.jade').render(context.flatten())
# Clean tmpl
if not settings.DEBUG:
tmpl = re.sub('\s+', ' ', tmpl)

View File

@ -44,7 +44,7 @@ from uds.services.OVirt.OVirtProvider import Provider as oVirtProvider
import logging
import os
__updated__ = '2017-05-09'
__updated__ = '2017-05-10'
logger = logging.getLogger(__name__)
@ -141,7 +141,7 @@ class BaseSpiceTransport(Transport):
logger.info('SPICE didn\'t find has any port: {}'.format(con))
return False
if connection.testServer(con['address'], port_to_test) is True:
if self.testServer(userService, con['address'], port_to_test) is True:
self.cache.put(ip, 'Y', READY_CACHE_TIMEOUT)
ready = 'Y'