Esempio n. 1
0
    def get(self):
        logger.debug('args: {0}'.format(self._args))
        if len(self._args) == 1:
            if self._args[0] == 'overview':  # System overview
                users = User.objects.count()
                services = Service.objects.count()
                user_services = UserService.objects.exclude(
                    state__in=(State.REMOVED, State.ERROR)).count()
                restrained_services_pools = len(
                    DeployedService.getRestraineds())
                return {
                    'users': users,
                    'services': services,
                    'user_services': user_services,
                    'restrained_services_pools': restrained_services_pools,
                }

        if len(self._args) == 2:
            if self._args[0] == 'stats':
                if self._args[1] == 'assigned':
                    return getServicesPoolsCounters(None, counters.CT_ASSIGNED)
                if self._args[1] == 'inuse':
                    return getServicesPoolsCounters(None, counters.CT_INUSE)

        raise RequestError('invalid request')
Esempio n. 2
0
def getServicesPoolsCounters(servicePool, counter_type):
    # pylint: disable=no-value-for-parameter
    try:
        cacheKey = (servicePool and servicePool.id or 'all') + str(counter_type) + str(POINTS) + str(SINCE)
        to = getSqlDatetime()
        since = to - timedelta(days=SINCE)
        val = cache.get(cacheKey)
        if val is None:
            if servicePool is None:
                us = DeployedService()
                complete = True  # Get all deployed services stats
            else:
                us = servicePool
                complete = False
            val = []
            for x in counters.getCounters(us, counter_type, since=since, to=to, limit=POINTS, use_max=USE_MAX, all=complete):
                val.append({'stamp': x[0], 'value': int(x[1])})
            if len(val) > 2:
                cache.put(cacheKey, pickle.dumps(val).encode('zip'), 600)
            else:
                val = [{'stamp': since, 'value': 0}, {'stamp': to, 'value': 0}]
        else:
            val = pickle.loads(val.decode('zip'))

        return val
    except:
        logger.exception('exception')
        raise ResponseError('can\'t create stats for objects!!!')
Esempio n. 3
0
    def serviceList(self):
        # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
        groups = list(self._user.getGroups())
        availServices = DeployedService.getDeployedServicesForGroups(groups)
        availUserServices = UserService.getUserAssignedServices(self._user)

        # Extract required data to show to user
        services = []
        # Select assigned user services
        for svr in availUserServices:
            # Skip maintenance services...
            trans = []
            for t in svr.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType(
                ).providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            services.append({
                'id': 'A' + svr.uuid,
                'name': svr['name'],
                'transports': trans,
                'maintenance': svr.isInMaintenance(),
                'in_use': svr.in_use
            })

        logger.debug(services)

        # Now generic user service
        for svr in availServices:
            trans = []
            for t in svr.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType(
                ).providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            # Locate if user service has any already assigned user service for this
            ads = UserServiceManager.manager().getExistingAssignationForUser(
                svr, self._user)
            if ads is None:
                in_use = False
            else:
                in_use = ads.in_use

            services.append({
                'id': 'F' + svr.uuid,
                'name': svr.name,
                'transports': trans,
                'maintenance': svr.isInMaintenance(),
                'in_use': in_use
            })

        logger.debug('Services: {0}'.format(services))

        services = sorted(services, key=lambda s: s['name'].upper())

        return Connection.result(result=services)
Esempio n. 4
0
    def serviceList(self):
        # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
        groups = list(self._user.getGroups())
        availServices = DeployedService.getDeployedServicesForGroups(groups)
        availUserServices = UserService.getUserAssignedServices(self._user)

        # Extract required data to show to user
        services = []
        # Select assigned user services
        for svr in availUserServices:
            # Skip maintenance services...
            trans = []
            for t in svr.transports.all().order_by('priority'):
                typeTrans = t.getType()
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name, 'needsJava': t.getType().needsJava})
            services.append({'id': 'A' + svr.uuid,
                             'name': svr['name'],
                             'transports': trans,
                             'maintenance': svr.deployed_service.service.provider.maintenance_mode,
                             'in_use': svr.in_use})

        logger.debug(services)

        # Now generic user service
        for svr in availServices:
            trans = []
            for t in svr.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    typeTrans = t.getType()
                    trans.append({'id': t.uuid, 'name': t.name, 'needsJava': typeTrans.needsJava})

            # Locate if user service has any already assigned user service for this
            ads = UserServiceManager.manager().getExistingAssignationForUser(svr, self._user)
            if ads is None:
                in_use = False
            else:
                in_use = ads.in_use

            services.append({'id': 'F' + svr.uuid,
                             'name': svr.name,
                             'transports': trans,
                             'maintenance': svr.service.provider.maintenance_mode,
                             'in_use': in_use})

        logger.debug('Services: {0}'.format(services))

        services = sorted(services, key=lambda s: s['name'].upper())

        return Connection.result(result=services)
Esempio n. 5
0
    def get(self):
        logger.debug('args: {0}'.format(self._args))
        if len(self._args) == 1:
            if self._args[0] == 'overview':  # System overview
                users = User.objects.count()
                services = Service.objects.count()
                user_services = UserService.objects.count()
                restrained_services_pools = len(DeployedService.getRestraineds())
                return {
                    'users': users,
                    'services': services,
                    'user_services': user_services,
                    'restrained_services_pools': restrained_services_pools,
                }

        if len(self._args) == 2:
            if self._args[0] == 'stats':
                if self._args[1] == 'assigned':
                    return getServicesPoolsCounters(None, counters.CT_ASSIGNED)
                if self._args[1] == 'inuse':
                    return getServicesPoolsCounters(None, counters.CT_INUSE)

        raise RequestError('invalid request')
Esempio n. 6
0
def index(request):
    """
    Renders the main page.
    :param request: http request
    """
    if request.session.get('ticket') == '1':
        return webLogout(request)

    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services (manually assigned)
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})

        servicePool = svr.deployed_service

        if servicePool.image is not None:
            imageId = servicePool.image.uuid
        else:
            imageId = 'x'  # Invalid

        # Extract app group
        group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default(
        ).as_dict

        services.append({
            'id': 'A' + svr.uuid,
            'name': servicePool.name,
            'visual_name': servicePool.visual_name,
            'description': servicePool.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': servicePool.show_transports,
            'allow_users_remove': servicePool.allow_users_remove,
            'allow_users_reset': servicePool.allow_users_reset,
            'maintenance': servicePool.isInMaintenance(),
            'not_accesible': not servicePool.isAccessAllowed(),
            'in_use': svr.in_use,
            'to_be_replaced':
            False,  # Manually assigned will not be autoremoved never
            'comments': servicePool.comments,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(
            svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default(
        ).as_dict

        tbr = svr.toBeReplaced()
        if tbr is not None:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext(
                'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.'
            ).format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
            'comments': svr.comments,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(
            True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    # List of services groups
    allGroups = [
        v for v in sorted([ser['group'] for ser in services],
                          key=lambda s: s['priority'])
    ]
    # Now remove duplicates
    groups = []
    already = []
    for g in allGroups:
        if g['name'] not in already:
            already.append(g['name'])
            groups.append(g)

    logger.debug('Groups: {}'.format(groups))

    response = render(
        request, theme.template('index.html'), {
            'groups': groups,
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
        })
    return response
Esempio n. 7
0
def index(request):
    '''
    Renders the main page.
    :param request: http request
    '''
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.deployed_service.image is not None:
            imageId = svr.deployed_service.image.uuid
        else:
            imageId = 'x'  # Invalid

        services.append({
            'id': 'A' + svr.uuid,
            'name': svr['name'],
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.deployed_service.show_transports,
            'maintenance':
            svr.deployed_service.service.provider.maintenance_mode,
            'in_use': svr.in_use,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        # Generate ticket

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(
            svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'maintenance': svr.service.provider.maintenance_mode,
            'in_use': in_use,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get(
            True) == '1' and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            # TODO: Make this to redirect to uds link directly
            return redirect('uds.web.views.service',
                            idService=services[0]['id'],
                            idTransport=services[0]['transports'][0]['id'])

    response = render_to_response(theme.template('index.html'), {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
    },
                                  context_instance=RequestContext(request))
    return response
Esempio n. 8
0
    def serviceList(self):
        # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
        groups = list(self._user.getGroups())
        availServices = DeployedService.getDeployedServicesForGroups(groups)
        availUserServices = UserService.getUserAssignedServices(self._user)

        # Extract required data to show to user
        services = []
        # Select assigned user services
        for svr in availUserServices:
            # Skip maintenance services...
            trans = []
            for t in svr.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            servicePool = svr.deployed_service

            services.append({'id': 'A' + svr.uuid,
                             'name': servicePool.name,
                             'description': servicePool.comments,
                             'visual_name': servicePool.visual_name,
                             'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict,
                             'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64,
                             'show_transports': servicePool.show_transports,
                             'allow_users_remove': servicePool.allow_users_remove,
                             'maintenance': servicePool.isInMaintenance(),
                             'not_accesible': not servicePool.isAccessAllowed(),
                             'to_be_replaced': False,  # Manually assigned will not be autoremoved never
                             'transports': trans,
                             'in_use': svr.in_use})

        logger.debug(services)

        # Now generic user service
        for servicePool in availServices:
            trans = []
            for t in servicePool.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            # Locate if user service has any already assigned user service for this
            ads = userServiceManager().getExistingAssignationForUser(servicePool, self._user)
            if ads is None:
                in_use = False
            else:
                in_use = ads.in_use

            services.append({'id': 'F' + servicePool.uuid,
                             'name': servicePool.name,
                             'description': servicePool.comments,
                             'visual_name': servicePool.visual_name,
                             'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict,
                             'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64,
                             'show_transports': servicePool.show_transports,
                             'allow_users_remove': servicePool.allow_users_remove,
                             'maintenance': servicePool.isInMaintenance(),
                             'not_accesible': not servicePool.isAccessAllowed(),
                             'to_be_replaced': servicePool.toBeReplaced(),
                             'transports': trans,
                             'in_use': in_use})

        logger.debug('Services: {0}'.format(services))

        services = sorted(services, key=lambda s: s['name'].upper())

        return Connection.result(result=services)
Esempio n. 9
0
def index(request):
    '''
    Renders the main page.
    :param request: http request
    '''
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.deployed_service.image is not None:
            imageId = svr.deployed_service.image.uuid
        else:
            imageId = 'x'  # Invalid

        services.append({
            'id': 'A' + svr.uuid,
            'name': svr['name'],
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.deployed_service.show_transports,
            'maintenance': svr.deployed_service.service.provider.maintenance_mode,
            'in_use': svr.in_use,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        # Generate ticket

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'maintenance': svr.service.provider.maintenance_mode,
            'in_use': in_use,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get(True) == '1' and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            # TODO: Make this to redirect to uds link directly
            return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    response = render_to_response(
        theme.template('index.html'),
        {
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
        },
        context_instance=RequestContext(request)
    )
    return response
Esempio n. 10
0
def getServicesData(request):
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availMetas = MetaPool.getForGroups(groups)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetas)
    services = []
    # Add meta pools data first
    for meta in availMetas:
        # Check that we have access to at least one transport on some of its children
        hasUsablePools = False
        in_use = False
        for pool in meta.pools.all():
            # if pool.isInMaintenance():
            #    continue
            for t in pool.transports.all():
                typeTrans = t.getType()
                if t.getType() and t.validForIp(
                        request.ip) and typeTrans.supportsOs(
                            os['OS']) and t.validForOs(os['OS']):
                    hasUsablePools = True
                    break

            if not in_use:
                assignedUserService = UserServiceManager.manager(
                ).getExistingAssignationForUser(pool, request.user)
                if assignedUserService:
                    in_use = assignedUserService.in_use

            # Stop when 1 usable pool is found
            if hasUsablePools:
                break

        # If no usable pools, this is not visible
        if hasUsablePools:
            group = meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup else ServicesPoolGroup.default(
            ).as_dict

            services.append({
                'id':
                'M' + meta.uuid,
                'name':
                meta.name,
                'visual_name':
                meta.visual_name,
                'description':
                meta.comments,
                'group':
                group,
                'transports': [{
                    'id':
                    'meta',
                    'name':
                    'meta',
                    'link':
                    html.udsMetaLink(request, 'M' + meta.uuid),
                    'priority':
                    0
                }],
                'imageId':
                meta.image and meta.image.uuid or 'x',
                'show_transports':
                False,
                'allow_users_remove':
                False,
                'allow_users_reset':
                False,
                'maintenance':
                meta.isInMaintenance(),
                'not_accesible':
                not meta.isAccessAllowed(),
                'in_use':
                in_use,
                'to_be_replaced':
                None,
                'to_be_replaced_text':
                '',
            })

    # Now generic user service
    for svr in availServices:
        # Skip pools that are part of meta pools
        if svr.is_meta:
            continue

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({
                    'id': t.uuid,
                    'name': t.name,
                    'link': link,
                    'priority': t.priority
                })

        # If empty transports, do not include it on list
        if not trans:
            continue

        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(
            svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup else ServicesPoolGroup.default(
        ).as_dict

        tbr = svr.toBeReplaced(request.user)
        if tbr:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext(
                'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.'
            ).format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
        })

    logger.debug('Services: {0}'.format(services))

    # Sort services and remove services with no transports...
    services = [
        s for s in sorted(services, key=lambda s: s['name'].upper())
        if len(s['transports']) > 0
    ]

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(
            True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    return {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
        'autorun': autorun
    }
Esempio n. 11
0
def getServicesData(request):
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availMetas = MetaPool.getForGroups(groups)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetas)
    services = []
    # Add meta pools data first
    for meta in availMetas:
        # Check that we have access to at least one transport on some of its children
        hasUsablePools = False
        in_use = False
        for pool in meta.pools.all():
            # if pool.isInMaintenance():
            #    continue
            for t in pool.transports.all():
                typeTrans = t.getType()
                if t.getType() and t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                    hasUsablePools = True
                    break

            if not in_use:
                assignedUserService = UserServiceManager.manager().getExistingAssignationForUser(pool, request.user)
                if assignedUserService:
                    in_use = assignedUserService.in_use

            # Stop when 1 usable pool is found
            if hasUsablePools:
                break

        # If no usable pools, this is not visible
        if hasUsablePools:
            group = meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup else ServicesPoolGroup.default().as_dict

            services.append({
                'id': 'M' + meta.uuid,
                'name': meta.name,
                'visual_name': meta.visual_name,
                'description': meta.comments,
                'group': group,
                'transports': [{
                    'id': 'meta',
                    'name': 'meta',
                    'link': html.udsMetaLink(request, 'M' + meta.uuid),
                    'priority': 0
                }],
                'imageId': meta.image and meta.image.uuid or 'x',
                'show_transports': False,
                'allow_users_remove': False,
                'allow_users_reset': False,
                'maintenance': meta.isInMaintenance(),
                'not_accesible': not meta.isAccessAllowed(),
                'in_use': in_use,
                'to_be_replaced': None,
                'to_be_replaced_text': '',
            })

    # Now generic user service
    for svr in availServices:
        # Skip pools that are part of meta pools
        if svr.is_meta:
            continue

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link,
                        'priority': t.priority
                    }
                )

        # If empty transports, do not include it on list
        if not trans:
            continue

        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup else ServicesPoolGroup.default().as_dict

        tbr = svr.toBeReplaced(request.user)
        if tbr:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
        })

    logger.debug('Services: {0}'.format(services))

    # Sort services and remove services with no transports...
    services = [s for s in sorted(services, key=lambda s: s['name'].upper()) if len(s['transports']) > 0]

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    return {
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
    }
Esempio n. 12
0
def index(request):
    """
    Renders the main page.
    :param request: http request
    """
    if request.session.get('ticket') == '1':
        return webLogout(request)

    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services (manually assigned)
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )

        servicePool = svr.deployed_service

        if servicePool.image is not None:
            imageId = servicePool.image.uuid
        else:
            imageId = 'x'  # Invalid

        # Extract app group
        group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict

        services.append({
            'id': 'A' + svr.uuid,
            'name': servicePool.name,
            'visual_name': servicePool.visual_name,
            'description': servicePool.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': servicePool.show_transports,
            'allow_users_remove': servicePool.allow_users_remove,
            'maintenance': servicePool.isInMaintenance(),
            'not_accesible': not servicePool.isAccessAllowed(),
            'in_use': svr.in_use,
            'to_be_replaced': False,  # Manually assigned will not be autoremoved never
            'comments': servicePool.comments,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict

        tbr = svr.toBeReplaced()
        if tbr is not None:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
            'comments': svr.comments,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    # List of services groups
    allGroups = [v for v in sorted([ser['group'] for ser in services], key=lambda s: s['priority'])]
    # Now remove duplicates
    groups = []
    already = []
    for g in allGroups:
        if g['name'] not in already:
            already.append(g['name'])
            groups.append(g)

    logger.debug('Groups: {}'.format(groups))

    response = render(
        request,
        theme.template('index.html'),
        {
            'groups': groups,
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
        }
    )
    return response
Esempio n. 13
0
    def serviceList(self):
        # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
        groups = list(self._user.getGroups())
        availServices = DeployedService.getDeployedServicesForGroups(groups)
        availUserServices = UserService.getUserAssignedServices(self._user)

        # Extract required data to show to user
        services = []
        # Select assigned user services
        for svr in availUserServices:
            # Skip maintenance services...
            trans = []
            for t in svr.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            servicePool = svr.deployed_service

            services.append({'id': 'A' + svr.uuid,
                             'name': servicePool.name,
                             'description': servicePool.comments,
                             'visual_name': servicePool.visual_name,
                             'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict,
                             'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64,
                             'show_transports': servicePool.show_transports,
                             'allow_users_remove': servicePool.allow_users_remove,
                             'maintenance': servicePool.isInMaintenance(),
                             'not_accesible': not servicePool.isAccessAllowed(),
                             'to_be_replaced': False,  # Manually assigned will not be autoremoved never
                             'transports': trans,
                             'maintenance': servicePool.isInMaintenance(),
                             'in_use': servicePool.in_use})

        logger.debug(services)

        # Now generic user service
        for servicePool in availServices:
            trans = []
            for t in servicePool.transports.all().order_by('priority'):
                if t.validForIp(self._request.ip) and t.getType().providesConnetionInfo():
                    trans.append({'id': t.uuid, 'name': t.name})

            # Locate if user service has any already assigned user service for this
            ads = userServiceManager().getExistingAssignationForUser(servicePool, self._user)
            if ads is None:
                in_use = False
            else:
                in_use = ads.in_use

            services.append({'id': 'F' + servicePool.uuid,
                             'name': servicePool.name,
                             'description': servicePool.comments,
                             'visual_name': servicePool.visual_name,
                             'group': servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict,
                             'thumb': servicePool.image.thumb64 if servicePool.image is not None else DEFAULT_THUMB_BASE64,
                             'show_transports': servicePool.show_transports,
                             'allow_users_remove': servicePool.allow_users_remove,
                             'maintenance': servicePool.isInMaintenance(),
                             'not_accesible': not servicePool.isAccessAllowed(),
                             'to_be_replaced': servicePool.toBeReplaced(),
                             'transports': trans,
                             'maintenance': servicePool.isInMaintenance(),
                             'in_use': in_use})

        logger.debug('Services: {0}'.format(services))

        services = sorted(services, key=lambda s: s['name'].upper())

        return Connection.result(result=services)