def transformTransports(apps, schema_editor):
    '''
    Move serialization to a better model (it's time, the mode is there since 1.1 :) )
    '''
    model = apps.get_model("uds", 'Transport')
    for t in model.objects.all():
        if t.data_type == RDPTransport.typeType:
            values = unmarshalRDP(t.data.decode(RDPTransport.CODEC))
            rdp = RDPTransport(Environment.getTempEnv(), values)
            t.data = rdp.serialize()
            t.save()

        if t.data_type == TRDPTransport.typeType:
            values = unmarshalTRDP(t.data.decode(TRDPTransport.CODEC))
            rdp = TRDPTransport(Environment.getTempEnv(), values)
            t.data = rdp.serialize()
            t.save()

        if t.data_type == RGSTransport.typeType:
            values = unmarshalRGS(t.data.decode(RGSTransport.CODEC))
            rgs = RGSTransport(Environment.getTempEnv(), values)
            t.data = rgs.serialize()
            t.save()

        if t.data_type == TRGSTransport.typeType:
            values = unmarshalTRGS(t.data.decode(TRGSTransport.CODEC))
            rgs = TRGSTransport(Environment.getTempEnv(), values)
            t.data = rgs.serialize()
            t.save()
Example #2
0
    def executeOneDelayedTask(self):
        now = getSqlDatetime()
        filt = Q(execution_time__lt=now) | Q(insert_date__gt=now + timedelta(seconds=30))
        # If next execution is before now or last execution is in the future (clock changed on this server, we take that task as executable)
        try:
            with transaction.atomic():  # Encloses
                # Throws exception if no delayed task is avilable
                task = dbDelayedTask.objects.select_for_update().filter(filt).order_by('execution_time')[0]  # @UndefinedVariable
                if task.insert_date > now + timedelta(seconds=30):
                    logger.warning('EXecuted {} due to insert_date being in the future!'.format(task.type))
                taskInstanceDump = encoders.decode(task.instance, 'base64')
                task.delete()
            taskInstance = loads(taskInstanceDump)
        except IndexError:
            return  # No problem, there is no waiting delayed task
        except Exception:
            # Transaction have been rolled back using the "with atomic", so here just return
            # Note that is taskInstance can't be loaded, this task will not be retried
            logger.exception('Executing one task')
            return

        if taskInstance is not None:
            logger.debug('Executing delayedTask:>{0}<'.format(task))
            taskInstance.env = Environment.getEnvForType(taskInstance.__class__)
            DelayedTaskThread(taskInstance).start()
Example #3
0
    def getEnvironment(self):
        '''
        Returns an environment valid for the record this object represents
        '''
        from uds.core.util.UniqueMacGenerator import UniqueMacGenerator
        from uds.core.util.UniqueNameGenerator import UniqueNameGenerator

        return Environment.getEnvForTableElement(self._meta.verbose_name, self.id, {'mac': UniqueMacGenerator, 'name': UniqueNameGenerator})
def transformTransports(apps, schema_editor):
    """
    Move serialization to a better model (it's time, the mode is there since 1.1 :) )
    """
    model = apps.get_model("uds", 'Transport')
    for t in model.objects.all():
        if t.data_type == RDPTransport.typeType:
            values = unmarshalRDP(encoders.decode(t.data, 'base64'))
            rdp = RDPTransport(Environment.getTempEnv(), values)
            t.data = rdp.serialize()
            t.save()

        if t.data_type == TRDPTransport.typeType:
            values = unmarshalTRDP(encoders.decode(t.data, 'base64'))
            rdp = TRDPTransport(Environment.getTempEnv(), values)
            t.data = rdp.serialize()
            t.save()
Example #5
0
 def getGui(self, parent, forType):
     try:
         logger.debug('getGui parameters: {0}, {1}'.format(parent, forType))
         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'])
     except Exception as e:
         logger.exception('getGui')
         raise ResponseError(unicode(e))
Example #6
0
    def getEnvironment(self):
        """
        Returns an environment valid for the record this object represents
        """
        # from uds.core.util.UniqueMacGenerator import UniqueMacGenerator
        # from uds.core.util.UniqueNameGenerator import UniqueNameGenerator

        return Environment.getEnvForTableElement(
            self._meta.verbose_name,
            self.id,
            {"mac": unique.UniqueMacGenerator, "name": unique.UniqueNameGenerator, "id": unique.UniqueGIDGenerator},
        )
Example #7
0
    def test(self, type_):
        from uds.core.Environment import Environment

        authType = auths.factory().lookup(type_)
        self.ensureAccess(authType, permissions.PERMISSION_MANAGEMENT, root=True)

        dct = self._params.copy()
        dct['_request'] = self._request
        res = authType.test(Environment.getTempEnv(), dct)
        if res[0]:
            return self.success()
        else:
            return res[1]
Example #8
0
    def test(self, type_):
        from uds.core.Environment import Environment

        logger.debug('Type: {}'.format(type_))
        spType = services.factory().lookup(type_)

        self.ensureAccess(spType, permissions.PERMISSION_MANAGEMENT, root=True)

        logger.debug('spType: {}'.format(spType))
        res = spType.test(Environment.getTempEnv(), self._params)
        if res[0]:
            return 'ok'
        else:
            return res[1]
Example #9
0
    def getEnvironment(self):
        '''
        Returns an environment valid for the record this object represents.

        In the case of the user, there is an instatiation of "generators".
        Right now, there is two generators provided to child instance objects, that are
        valid for generating unique names and unique macs. In a future, there could be more generators

        To access this generators, use the Envirnment class, and the keys 'name' and 'mac'.

        (see related classes uds.core.util.UniqueNameGenerator and uds.core.util.UniqueMacGenerator)
        '''
        from uds.core.util.UniqueMacGenerator import UniqueMacGenerator
        from uds.core.util.UniqueNameGenerator import UniqueNameGenerator
        return Environment.getEnvForTableElement(self._meta.verbose_name, self.id, {'mac': UniqueMacGenerator, 'name': UniqueNameGenerator})
Example #10
0
    def test(self, type_):
        from uds.core.Environment import Environment

        authType = auths.factory().lookup(type_)
        self.ensureAccess(authType,
                          permissions.PERMISSION_MANAGEMENT,
                          root=True)

        dct = self._params.copy()
        dct['_request'] = self._request
        res = authType.test(Environment.getTempEnv(), dct)
        if res[0]:
            return self.success()
        else:
            return res[1]
Example #11
0
def getResources(parameters):
    """
    This helper is designed as a callback for Project Selector
    """
    from .Provider import Provider
    from uds.core.Environment import Environment
    logger.debug(
        'Parameters received by getResources Helper: {0}'.format(parameters))
    env = Environment(parameters['ev'])
    provider = Provider(env)
    provider.unserialize(parameters['ov'])

    api = provider.api(parameters['project'], parameters['region'])

    zones = [gui.choiceItem(z, z) for z in api.listAvailabilityZones()]
    networks = [gui.choiceItem(z['id'], z['name']) for z in api.listNetworks()]
    flavors = [gui.choiceItem(z['id'], z['name']) for z in api.listFlavors()]
    securityGroups = [
        gui.choiceItem(z['id'], z['name']) for z in api.listSecurityGroups()
    ]
    volumeTypes = [gui.choiceItem('-', _('None'))] + [
        gui.choiceItem(t['id'], t['name']) for t in api.listVolumeTypes()
    ]

    data = [
        {
            'name': 'availabilityZone',
            'values': zones
        },
        {
            'name': 'network',
            'values': networks
        },
        {
            'name': 'flavor',
            'values': flavors
        },
        {
            'name': 'securityGroups',
            'values': securityGroups
        },
        {
            'name': 'volumeType',
            'values': volumeTypes
        },
    ]
    logger.debug('Return data: {}'.format(data))
    return data
Example #12
0
    def test(self, type_):
        from uds.core.Environment import Environment

        logger.debug('Type: %s', type_)
        spType = services.factory().lookup(type_)

        self.ensureAccess(spType, permissions.PERMISSION_MANAGEMENT, root=True)

        logger.debug('spType: %s', spType)

        dct = self._params.copy()
        dct['_request'] = self._request
        res = spType.test(Environment.getTempEnv(), dct)
        if res[0]:
            return 'ok'
        else:
            return res[1]
Example #13
0
    def getEnvironment(self) -> Environment:
        """
        Returns an environment valid for the record this object represents.

        In the case of the user, there is an instatiation of "generators".
        Right now, there is two generators provided to child instance objects, that are
        valid for generating unique names and unique macs. In a future, there could be more generators

        To access this generators, use the Envirnment class, and the keys 'name' and 'mac'.

        (see related classes uds.core.util.UniqueNameGenerator and uds.core.util.UniqueMacGenerator)
        """
        return Environment.getEnvForTableElement(
            self._meta.verbose_name, self.id, {
                'mac': unique.UniqueMacGenerator,
                'name': unique.UniqueNameGenerator,
                'id': unique.UniqueGIDGenerator,
            })
Example #14
0
    def executeOneDelayedTask(self):
        now = getSqlDatetime()
        filt = Q(execution_time__lt=now) | Q(insert_date__gt=now + timedelta(seconds=30))
        # If next execution is before now or last execution is in the future (clock changed on this server, we take that task as executable)
        taskInstance = None
        try:
            with transaction.atomic():  # Encloses
                task = dbDelayedTask.objects.select_for_update().filter(filt).order_by('execution_time')[0]  # @UndefinedVariable
                taskInstanceDump = encoders.decode(task.instance, 'base64')
                task.delete()
            taskInstance = loads(taskInstanceDump)
        except Exception:
            # Transaction have been rolled back using the "with atomic", so here just return
            # Note that is taskInstance can't be loaded, this task will not be retried
            return

        if taskInstance is not None:
            logger.debug('Executing delayedTask:>{0}<'.format(task))
            taskInstance.env = Environment.getEnvForType(taskInstance.__class__)
            DelayedTaskThread(taskInstance).start()
    def executeOneDelayedTask(self):
        now = getSqlDatetime()
        filt = Q(execution_time__lt=now) | Q(insert_date__gt=now)
        # If next execution is before now or last execution is in the future (clock changed on this server, we take that task as executable)
        taskInstance = None
        try:
            with transaction.atomic():  # Encloses
                task = dbDelayedTask.objects.select_for_update().filter(filt).order_by('execution_time')[0]  # @UndefinedVariable
                taskInstanceDump = task.instance.decode(self.CODEC)
                task.delete()
            taskInstance = loads(taskInstanceDump)
        except Exception:
            # Transaction have been rolled back using the "with atomic", so here just return
            # Note that is taskInstance can't be loaded, this task will not be retried
            return

        if taskInstance is not None:
            logger.debug('Executing delayedTask:>{0}<'.format(task))
            env = Environment.getEnvForType(taskInstance.__class__)
            taskInstance.setEnv(env)
            DelayedTaskThread(taskInstance).start()
Example #16
0
def getResources(parameters):
    """
    This helper is designed as a callback for Project Selector
    """
    from .Provider import OGProvider
    from uds.core.Environment import Environment
    logger.debug('Parameters received by getResources Helper: {0}'.format(parameters))
    env = Environment(parameters['ev'])
    provider = OGProvider(env)
    provider.unserialize(parameters['ov'])

    api = provider.api

    labs = [gui.choiceItem('0', _('All Labs'))] + [gui.choiceItem(l['id'], l['name']) for l in api.getLabs(ou=parameters['ou'])]
    images = [gui.choiceItem(z['id'], z['name']) for z in api.getImages(ou=parameters['ou'])]

    data = [
        {'name': 'lab', 'values': labs},
        {'name': 'image', 'values': images},
    ]
    logger.debug('Return data: {}'.format(data))
    return data
Example #17
0
def getVolumes(parameters):
    '''
    This helper is designed as a callback for Zone Selector
    '''
    if parameters['legacy'] == 'true':
        from .ProviderLegacy import ProviderLegacy as Provider
    else:
        from .Provider import Provider
    from uds.core.Environment import Environment
    logger.debug('Parameters received by getVolumes Helper: {0}'.format(parameters))
    env = Environment(parameters['ev'])
    provider = Provider(env)
    provider.unserialize(parameters['ov'])

    api = provider.api(parameters['project'], parameters['region'])

    volumes = [gui.choiceItem(v['id'], v['name']) for v in api.listVolumes() if v['name'] != '' and v['availability_zone'] == parameters['availabilityZone']]

    data = [
        {'name': 'volume', 'values': volumes },
    ]
    logger.debug('Return data: {}'.format(data))
    return data
Example #18
0
    def getGui(self, parent, forType):
        try:
            logger.debug('getGui parameters: {0}, {1}'.format(parent, forType))
            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
            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':
                    _('Proxy'),
                    'tooltip':
                    _('Proxy for services behind a firewall'),
                    'type':
                    gui.InputField.CHOICE_TYPE,
                    'tab':
                    _('Advanced'),
                    'order':
                    132,
                },
            ]:
                self.addField(g, f)

            return g

        except Exception as e:
            logger.exception('getGui')
            raise ResponseError(six.text_type(e))
Example #19
0
    def getResources(parameters):
        """
        This helper is designed as a callback for machine selector, so we can provide valid clusters and datastores domains based on it
        """
        from OVirtProvider import Provider
        from uds.core.Environment import Environment
        logger.debug('Parameters received by getResources Helper: {0}'.format(
            parameters))
        env = Environment(parameters['ev'])
        provider = Provider(env)
        provider.unserialize(parameters['ov'])

        # Obtains datacenter from cluster
        ci = provider.getClusterInfo(parameters['cluster'])

        res = []
        # Get storages for that datacenter
        for storage in provider.getDatacenterInfo(
                ci['datacenter_id'])['storage']:
            if storage['type'] == 'data':
                space, free = (storage['available'] +
                               storage['used']) / 1024 / 1024 / 1024, storage[
                                   'available'] / 1024 / 1024 / 1024

                res.append({
                    'id':
                    storage['id'],
                    'text':
                    "%s (%4.2f Gb/%4.2f Gb) %s" %
                    (storage['name'], space, free, storage['active'] and '(ok)'
                     or '(disabled)')
                })
        data = [{'name': 'datastore', 'values': res}]

        logger.debug('return data: {0}'.format(data))
        return data
Example #20
0
    def getGui(self, parent, forType):
        try:
            logger.debug('getGui parameters: {0}, {1}'.format(parent, forType))
            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
            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': _('Proxy'),
                'tooltip': _('Proxy for services behind a firewall'),
                'type': gui.InputField.CHOICE_TYPE,
                'tab': _('Advanced'),
                'order': 132,
                },
            ]:
                self.addField(g, f)

            return g

        except Exception as e:
            logger.exception('getGui')
            raise ResponseError(six.text_type(e))
Example #21
0
 def getEnvironment(self):
     """
     Returns an environment valid for the record this object represents
     """
     return Environment.getEnvForTableElement(self._meta.verbose_name, self.id)
 def getEnvironment(self):
     """
     Returns an environment valid for the record this object represents
     """
     return Environment.getEnvForTableElement(self._meta.verbose_name, self.id)