Example #1
0
    def beforeSave(self, fields: typing.Dict[str, typing.Any]) -> None:
        # logger.debug(self._params)
        try:
            # **** IMAGE ***
            imgId = fields['image_id']
            fields['image_id'] = None
            logger.debug('Image id: %s', imgId)
            try:
                if imgId != '-1':
                    image = Image.objects.get(uuid=processUuid(imgId))
                    fields['image_id'] = image.id
            except Exception:
                logger.exception('At image recovering')

            # Servicepool Group
            spgrpId = fields['servicesPoolGroup_id']
            fields['servicesPoolGroup_id'] = None
            logger.debug('servicesPoolGroup_id: %s', spgrpId)
            try:
                if spgrpId != '-1':
                    spgrp = ServicePoolGroup.objects.get(
                        uuid=processUuid(spgrpId))
                    fields['servicesPoolGroup_id'] = spgrp.id
            except Exception:
                logger.exception('At service pool group recovering')

        except (RequestError, ResponseError):
            raise
        except Exception as e:
            raise RequestError(str(e))

        logger.debug('Fields: %s', fields)
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(
            uuid=processUuid(self._params['calendarId']))
        action = self._params['action'].upper()
        eventsOffset = int(self._params['eventsOffset'])
        atStart = self._params['atStart'] not in ('false', False, '0', 0)
        params = json.dumps(self._params['params'])

        logger.debug('Got parameters: {} {} {} {} ----> {}'.format(
            calendar, action, eventsOffset, atStart, params))

        if uuid is not None:
            calAction = CalendarAction.objects.get(uuid=uuid)
            calAction.calendar = calendar
            calAction.service_pool = parent
            calAction.action = action
            calAction.at_start = atStart
            calAction.events_offset = eventsOffset
            calAction.params = params
            calAction.save()
        else:
            CalendarAction.objects.create(calendar=calendar,
                                          service_pool=parent,
                                          action=action,
                                          at_start=atStart,
                                          events_offset=eventsOffset,
                                          params=params)

        return self.success()
Example #3
0
    def saveItem(self, parent: 'ServicePool',
                 item: typing.Optional[str]) -> None:
        # If already exists
        uuid = processUuid(item) if item is not None else None

        try:
            calendar: Calendar = Calendar.objects.get(
                uuid=processUuid(self._params['calendarId']))
            access: str = self._params['access'].upper()
            if access not in (ALLOW, DENY):
                raise Exception()
        except Exception:
            raise self.invalidRequestException(
                _('Invalid parameters on request'))
        priority = int(self._params['priority'])

        if uuid is not None:
            calAccess: 'CalendarAccess' = parent.calendarAccess.get(uuid=uuid)
            calAccess.calendar = calendar  # type: ignore
            calAccess.service_pool = parent  # type: ignore
            calAccess.access = access
            calAccess.priority = priority
            calAccess.save()
        else:
            parent.calendarAccess.create(calendar=calendar,
                                         access=access,
                                         priority=priority)

        log.doLog(
            parent, log.INFO,
            "Added access calendar {}/{} by {}".format(calendar.name, access,
                                                       self._user.pretty_name),
            log.ADMIN)
Example #4
0
    def saveItem(self, parent: MetaPool, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        pool = ServicePool.objects.get(
            uuid=processUuid(self._params['pool_id']))
        enabled = self._params['enabled'] not in ('false', False, '0', 0)
        priority = int(self._params['priority'])

        if uuid is not None:
            member = parent.members.get(uuid=uuid)
            member.pool = pool
            member.enabled = enabled
            member.priority = priority
            member.save()
        else:
            parent.members.create(pool=pool,
                                  priority=priority,
                                  enabled=enabled)

        log.doLog(parent, log.INFO, (uuid is None and "Added" or "Modified") +
                  " meta pool member {}/{}/{} by {}".format(
                      pool.name, priority, enabled, self._user.pretty_name),
                  log.ADMIN)

        return self.success()
Example #5
0
    def saveItem(self, parent: models.ServicePool,
                 item: typing.Optional[str]) -> None:
        if not item:
            raise self.invalidItemException('Only modify is allowed')
        fields = self.readFieldsFromParams(['auth_id', 'user_id'])
        userService = parent.userServices.get(uuid=processUuid(item))
        user = models.User.objects.get(uuid=processUuid(fields['user_id']))

        logStr = 'Changing ownership of service from {} to {} by {}'.format(
            userService.user.pretty_name, user.pretty_name,
            self._user.pretty_name)

        # If there is another service that has this same owner, raise an exception
        if (parent.userServices.filter(user=user).exclude(
                uuid=userService.uuid).exclude(
                    state__in=State.INFO_STATES).count() > 0):
            raise self.invalidResponseException(
                'There is already another user service assigned to {}'.format(
                    user.pretty_name))

        userService.user = user
        userService.save()

        # Log change
        log.doLog(parent, log.INFO, logStr, log.ADMIN)
Example #6
0
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
        action = self._params['action'].upper()
        if action not in CALENDAR_ACTION_DICT:
            self.invalidRequestException()
        eventsOffset = int(self._params['eventsOffset'])
        atStart = self._params['atStart'] not in ('false', False, '0', 0)
        params = json.dumps(self._params['params'])

        # logger.debug('Got parameters: {} {} {} {} ----> {}'.format(calendar, action, eventsOffset, atStart, params))
        logStr = "Added scheduled action \"{},{},{},{},{}\" by {}".format(
            calendar.name, action, eventsOffset,
            atStart and 'Start' or 'End', params, self._user.pretty_name
        )

        if uuid is not None:
            calAction = CalendarAction.objects.get(uuid=uuid)
            calAction.calendar = calendar
            calAction.service_pool = parent
            calAction.action = action
            calAction.at_start = atStart
            calAction.events_offset = eventsOffset
            calAction.params = params
            calAction.save()
        else:
            CalendarAction.objects.create(calendar=calendar, service_pool=parent, action=action, at_start=atStart, events_offset=eventsOffset, params=params)

        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
Example #7
0
    def saveItem(self, parent: 'ServicePool', item: typing.Optional[str]) -> None:
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
        action = self._params['action'].upper()
        if action not in CALENDAR_ACTION_DICT:
            raise self.invalidRequestException()
        eventsOffset = int(self._params['eventsOffset'])
        atStart = self._params['atStart'] not in ('false', False, '0', 0)
        params = json.dumps(self._params['params'])

        # logger.debug('Got parameters: {} {} {} {} ----> {}'.format(calendar, action, eventsOffset, atStart, params))
        logStr = "Added scheduled action \"{},{},{},{},{}\" by {}".format(
            calendar.name, action, eventsOffset,
            atStart and 'Start' or 'End', params, self._user.pretty_name
        )

        if uuid is not None:
            calAction = CalendarAction.objects.get(uuid=uuid)
            calAction.calendar = calendar
            calAction.service_pool = parent
            calAction.action = action
            calAction.at_start = atStart
            calAction.events_offset = eventsOffset
            calAction.params = params
            calAction.save()
        else:
            CalendarAction.objects.create(calendar=calendar, service_pool=parent, action=action, at_start=atStart, events_offset=eventsOffset, params=params)

        log.doLog(parent, log.INFO, logStr, log.ADMIN)
Example #8
0
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(
            uuid=processUuid(self._params['calendarId']))
        access = self._params['access'].upper()
        priority = int(self._params['priority'])

        if uuid is not None:
            calAccess = parent.calendarAccess.get(uuid=uuid)
            calAccess.calendar = calendar
            calAccess.service_pool = parent
            calAccess.access = access
            calAccess.priority = priority
            calAccess.save()
        else:
            parent.calendarAccess.create(calendar=calendar,
                                         access=access,
                                         priority=priority)

        log.doLog(
            parent, log.INFO,
            "Added access calendar {}/{} by {}".format(calendar.name, access,
                                                       self._user.pretty_name),
            log.ADMIN)

        return self.success()
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
        action = self._params['action'].upper()
        eventsOffset = int(self._params['eventsOffset'])
        atStart = self._params['atStart'] not in ('false', False, '0', 0)
        params = json.dumps(self._params['params'])

        logger.debug('Got parameters: {} {} {} {} ----> {}'.format(calendar, action, eventsOffset, atStart, params))

        if uuid is not None:
            calAction = CalendarAction.objects.get(uuid=uuid)
            calAction.calendar = calendar
            calAction.service_pool = parent
            calAction.action = action
            calAction.at_start = atStart
            calAction.events_offset = eventsOffset
            calAction.params = params
            calAction.save()
        else:
            CalendarAction.objects.create(calendar=calendar, service_pool=parent, action=action, at_start=atStart, events_offset=eventsOffset, params=params)

        return self.success()
Example #10
0
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        try:
            calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
            access = self._params['access'].upper()
            if access not in ('ALLOW', 'DENY'):
                raise Exception()
        except Exception:
            self.invalidRequestException(_('Invalid parameters on request'))
        priority = int(self._params['priority'])

        if uuid is not None:
            calAccess = parent.calendarAccess.get(uuid=uuid)
            calAccess.calendar = calendar
            calAccess.service_pool = parent
            calAccess.access = access
            calAccess.priority = priority
            calAccess.save()
        else:
            parent.calendarAccess.create(calendar=calendar, access=access, priority=priority)

        log.doLog(parent, log.INFO, "Added access calendar {}/{} by {}".format(calendar.name, access, self._user.pretty_name), log.ADMIN)

        return self.success()
Example #11
0
    def beforeSave(self, fields):
        # logger.debug(self._params)
        try:
            # **** IMAGE ***
            imgId = fields['image_id']
            fields['image_id'] = None
            logger.debug('Image id: {}'.format(imgId))
            try:
                if imgId != '-1':
                    image = Image.objects.get(uuid=processUuid(imgId))
                    fields['image_id'] = image.id
            except Exception:
                logger.exception('At image recovering')

            # Servicepool Group
            spgrpId = fields['servicesPoolGroup_id']
            fields['servicesPoolGroup_id'] = None
            logger.debug('servicesPoolGroup_id: {}'.format(spgrpId))
            try:
                if spgrpId != '-1':
                    spgrp = ServicesPoolGroup.objects.get(uuid=processUuid(spgrpId))
                    fields['servicesPoolGroup_id'] = spgrp.id
            except Exception:
                logger.exception('At service pool group recovering')

        except (RequestError, ResponseError):
            raise
        except Exception as e:
            raise RequestError(str(e))

        logger.debug('Fields: {}'.format(fields))
Example #12
0
    def beforeSave(self, fields):
        # logger.debug(self._params)
        try:
            try:
                service = Service.objects.get(uuid=processUuid(fields['service_id']))
                fields['service_id'] = service.id
            except:
                raise RequestError(ugettext('Base service does not exist anymore'))

            try:
                serviceType = service.getType()

                if serviceType.publicationType is None:
                    self._params['publish_on_save'] = False

                if serviceType.needsManager is True:
                    osmanager = OSManager.objects.get(uuid=processUuid(fields['osmanager_id']))
                    fields['osmanager_id'] = osmanager.id
                else:
                    del fields['osmanager_id']

                if serviceType.usesCache is False:
                    for k in ('initial_srvs', 'cache_l1_srvs', 'cache_l2_srvs', 'max_srvs'):
                        fields[k] = 0

            except Exception:
                raise RequestError(ugettext('This service requires an OS Manager'))

            # If max < initial or cache_1 or cache_l2
            fields['max_srvs'] = max((int(fields['initial_srvs']), int(fields['cache_l1_srvs']), int(fields['max_srvs'])))

            imgId = fields['image_id']
            fields['image_id'] = None
            logger.debug('Image id: {}'.format(imgId))
            try:
                if imgId != '-1':
                    image = Image.objects.get(uuid=processUuid(imgId))
                    fields['image_id'] = image.id
            except Exception:
                logger.exception('At image recovering')

            # Servicepool Group
            spgrpId = fields['servicesPoolGroup_id']
            fields['servicesPoolGroup_id'] = None
            logger.debug('servicesPoolGroup_id: {}'.format(spgrpId))
            try:
                if spgrpId != '-1':
                    spgrp = ServicesPoolGroup.objects.get(uuid=processUuid(spgrpId))
                    fields['servicesPoolGroup_id'] = spgrp.id
            except Exception:
                logger.exception('At service pool group recovering')

        except (RequestError, ResponseError):
            raise
        except Exception as e:
            raise RequestError(str(e))
Example #13
0
 def getItems(self, parent, item):
     # Extract provider
     try:
         if item is None:
             return [AssignedService.itemToDict(k) for k in parent.assignedUserServices().all()
                     .prefetch_related('properties').prefetch_related('deployed_service').prefetch_related('publication')]
         else:
             return parent.assignedUserServices().get(processUuid(uuid=processUuid(item)))
     except Exception:
         logger.exception('getItems')
         self.invalidItemException()
Example #14
0
    def saveItem(self, parent: 'Provider', item: typing.Optional[str]) -> None:
        # Extract item db fields
        # We need this fields for all
        logger.debug('Saving service for %s / %s', parent, item)
        fields = self.readFieldsFromParams(
            ['name', 'comments', 'data_type', 'tags', 'proxy_id'])
        tags = fields['tags']
        del fields['tags']
        service: typing.Optional[Service] = None

        proxyId = fields['proxy_id']
        fields['proxy_id'] = None
        logger.debug('Proxy id: %s', proxyId)

        proxy: typing.Optional[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)
            else:
                service = parent.services.get(uuid=processUuid(item))
                service.__dict__.update(fields)

            if service is None:
                raise Exception('Cannot create service!')

            service.tags.set(
                [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()
        except Service.DoesNotExist:
            raise self.invalidItemException()
        except IntegrityError:  # Duplicate key probably
            raise RequestError(
                _('Element already exists (duplicate key error)'))
        except services.Service.ValidationException as e:
            if not item and service:  # Only remove partially saved element if creating new (if editing, ignore this)
                self._deleteIncompleteService(service)
            raise RequestError(_('Input error: {0}'.format(e)))
        except Exception as e:
            if not item and service:
                self._deleteIncompleteService(service)
            logger.exception('Saving Service')
            raise RequestError('incorrect invocation to PUT: {0}'.format(e))

        return self.getItems(parent, service.uuid)
Example #15
0
    def userServices(self, parent, item):
        uuid = processUuid(item)
        user = parent.users.get(uuid=processUuid(uuid))
        res = []
        for i in user.userServices.all():
            if i.state == State.USABLE:
                v = AssignedService.itemToDict(i)
                v['pool'] = i.deployed_service.name
                v['pool_id'] = i.deployed_service.uuid
                res.append(v)

        return res
Example #16
0
def serviceImage(request, idImage):
    try:
        icon = Image.objects.get(uuid=processUuid(idImage))
        return icon.imageResponse()
    except Image.DoesNotExist:
        pass  # Tries to get image from transport

    try:
        icon = Transport.objects.get(uuid=processUuid(idImage)).getInstance().icon(False)
        return HttpResponse(icon, content_type='image/png')
    except Exception:
        return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
Example #17
0
    def userServices(self, parent, item):
        uuid = processUuid(item)
        user = parent.users.get(uuid=processUuid(uuid))
        res = []
        for i in user.userServices.all():
            if i.state == State.USABLE:
                v = AssignedService.itemToDict(i)
                v['pool'] = i.deployed_service.name
                v['pool_id'] = i.deployed_service.uuid
                res.append(v)

        return res
Example #18
0
def serviceImage(request, idImage):
    try:
        icon = Image.objects.get(uuid=processUuid(idImage))
        return icon.imageResponse()
    except Image.DoesNotExist:
        pass  # Tries to get image from transport

    try:
        icon = Transport.objects.get(uuid=processUuid(idImage)).getInstance().icon(False)
        return HttpResponse(icon, content_type='image/png')
    except Exception:
        return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
Example #19
0
def serviceImage(request: 'ExtendedHttpRequest', idImage: str) -> HttpResponse:
    try:
        icon = Image.objects.get(uuid=processUuid(idImage))
        return icon.imageResponse()
    except Image.DoesNotExist:
        pass  # Tries to get image from transport

    try:
        transport: Transport = Transport.objects.get(uuid=processUuid(idImage))
        return HttpResponse(transport.getInstance().icon(),
                            content_type='image/png')
    except Exception:
        return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
Example #20
0
    def servicesPools(self, parent, item):
        uuid = processUuid(item)
        group = parent.groups.get(uuid=processUuid(uuid))
        res = []
        for i in getPoolsForGroups((group,)):
            res.append({
                'id': i.uuid,
                'name': i.name,
                'thumb': i.image.thumb64 if i.image is not None else DEFAULT_THUMB_BASE64,
                'user_services_count': i.userServices.exclude(state__in=(State.REMOVED, State.ERROR)).count(),
                'state': _('With errors') if i.isRestrained() else _('Ok'),
            })

        return res
Example #21
0
 def getLogs(self, parent, item):
     try:
         item = parent.cachedUserServices().get(uuid=processUuid(item))
         logger.debug('Getting logs for %s', item)
         return log.getLogs(item)
     except Exception:
         self.invalidItemException()
Example #22
0
    def saveItem(self, parent: 'Calendar', item: typing.Optional[str]) -> None:
        # Extract item db fields
        # We need this fields for all
        logger.debug('Saving rule %s / %s', parent, item)
        fields = self.readFieldsFromParams([
            'name', 'comments', 'frequency', 'start', 'end', 'interval',
            'duration', 'duration_unit'
        ])

        if int(fields['interval']) < 1:
            raise self.invalidItemException('Repeat must be greater than zero')

        # Convert timestamps to datetimes
        fields['start'] = datetime.datetime.fromtimestamp(fields['start'])
        if fields['end'] is not None:
            fields['end'] = datetime.datetime.fromtimestamp(fields['end'])

        calRule: CalendarRule
        try:
            if item is None:  # Create new
                calRule = parent.rules.create(**fields)
            else:
                calRule = parent.rules.get(uuid=processUuid(item))
                calRule.__dict__.update(fields)
                calRule.save()
        except CalendarRule.DoesNotExist:
            raise self.invalidItemException()
        except IntegrityError:  # Duplicate key probably
            raise RequestError(
                _('Element already exists (duplicate key error)'))
        except Exception as e:
            logger.exception('Saving calendar')
            raise RequestError('incorrect invocation to PUT: {0}'.format(e))

        return self.getItems(parent, calRule.uuid)
Example #23
0
    def getLogs(self, parent, item):
        try:
            user = parent.users.get(uuid=processUuid(item))
        except Exception:
            self.invalidItemException()

        return log.getLogs(user)
Example #24
0
 def getLogs(self, parent: 'Provider', item: str) -> typing.List[typing.Any]:
     try:
         service = parent.services.get(uuid=processUuid(item))
         logger.debug('Getting logs for %s', item)
         return log.getLogs(service)
     except Exception:
         raise self.invalidItemException()
Example #25
0
    def saveItem(self, parent, item):
        # 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"])
        service = None
        try:
            if item is None:  # Create new
                service = parent.services.create(**fields)
            else:
                service = parent.services.get(uuid=processUuid(item))
                service.__dict__.update(fields)

            service.data = service.getInstance(self._params).serialize()
            service.save()
        except Service.DoesNotExist:
            self.invalidItemException()
        except IntegrityError:  # Duplicate key probably
            raise RequestError(_("Element already exists (duplicate key error)"))
        except coreService.ValidationException as e:
            self._deleteIncompleteService(service)
            raise RequestError(_("Input error: {0}".format(unicode(e))))
        except Exception as e:
            self._deleteIncompleteService(service)
            logger.exception("Saving Service")
            raise RequestError("incorrect invocation to PUT: {0}".format(e))

        return self.getItems(parent, service.uuid)
Example #26
0
 def getItems(self, parent, item):
     try:
         multi = False
         if item is None:
             multi = True
             q = parent.groups.all().order_by('name')
         else:
             q = parent.groups.filter(uuid=processUuid(item))
         res = []
         for i in q:
             val = {
                 'id': i.uuid,
                 'name': i.name,
                 'comments': i.comments,
                 'state': i.state,
                 'type': i.is_meta and 'meta' or 'group',
                 'meta_if_any': i.meta_if_any
             }
             if i.is_meta:
                 val['groups'] = list(x.uuid for x in i.groups.all())
             res.append(val)
         if multi:
             return res
         return res[0]
     except:
         logger.exception('REST groups')
         self.invalidItemException()
Example #27
0
 def getLogs(self, parent, item):
     try:
         item = parent.cachedUserServices().get(uuid=processUuid(item))
         logger.debug('Getting logs for {0}'.format(item))
         return log.getLogs(item)
     except Exception:
         self.invalidItemException()
Example #28
0
    def getLogs(self, parent, item):
        try:
            user = parent.users.get(uuid=processUuid(item))
        except Exception:
            self.invalidItemException()

        return log.getLogs(user)
Example #29
0
 def getItems(self, parent, item):
     try:
         multi = False
         if item is None:
             multi = True
             q = parent.groups.all().order_by('name')
         else:
             q = parent.groups.filter(uuid=processUuid(item))
         res = []
         for i in q:
             val = {
                 'id': i.uuid,
                 'name': i.name,
                 'comments': i.comments,
                 'state': i.state,
                 'type': i.is_meta and 'meta' or 'group',
                 'meta_if_any': i.meta_if_any
             }
             if i.is_meta:
                 val['groups'] = list(x.uuid for x in i.groups.all())
             res.append(val)
         if multi:
             return res
         return res[0]
     except:
         logger.exception('REST groups')
         self.invalidItemException()
Example #30
0
    def saveItem(self, parent, item):
        # Extract item db fields
        # We need this fields for all
        logger.debug('Saving rule {0} / {1}'.format(parent, item))
        fields = self.readFieldsFromParams(['name', 'comments', 'frequency', 'start', 'end', 'interval', 'duration', 'duration_unit'])
        # Convert timestamps to datetimes
        fields['start'] = datetime.datetime.fromtimestamp(fields['start'])
        if fields['end'] != None:
            fields['end'] = datetime.datetime.fromtimestamp(fields['end'])

        calRule = None
        try:
            if item is None:  # Create new
                calRule = parent.rules.create(**fields)
            else:
                calRule = parent.rules.get(uuid=processUuid(item))
                calRule.__dict__.update(fields)
                calRule.save()
        except CalendarRule.DoesNotExist:
            self.invalidItemException()
        except IntegrityError:  # Duplicate key probably
            raise RequestError(_('Element already exists (duplicate key error)'))
        except Exception as e:
            logger.exception('Saving calendar')
            raise RequestError('incorrect invocation to PUT: {0}'.format(e))

        return self.getItems(parent, calRule.uuid)
Example #31
0
 def getItems(self, parent, item):
     # Extract provider
     try:
         if item is None:
             return [
                 AssignedService.itemToDict(k)
                 for k in parent.assignedUserServices().all().
                 prefetch_related('properties').prefetch_related(
                     'deployed_service').prefetch_related('publication')
             ]
         else:
             return parent.assignedUserServices().get(
                 processUuid(uuid=processUuid(item)))
     except Exception:
         logger.exception('getItems')
         self.invalidItemException()
Example #32
0
 def getItems(self, parent, item):
     try:
         multi = False
         if item is None:
             multi = True
             q = parent.groups.all().order_by('name')
         else:
             q = parent.groups.filter(uuid=processUuid(item))
         res = []
         for i in q:
             val = {
                 'id': i.uuid,
                 'name': i.name,
                 'comments': i.comments,
                 'state': i.state,
                 'type': i.is_meta and 'meta' or 'group',
                 'meta_if_any': i.meta_if_any
             }
             if i.is_meta:
                 val['groups'] = list(x.uuid for x in i.groups.all().order_by('name'))
             res.append(val)
         if multi:
             return res
         # Add pools field if 1 item only
         res = res[0]
         if i.is_meta:
             res['pools'] = []  # Meta groups do not have "assigned "pools, they get it from groups interaction
         else:
             res['pools'] = [v.uuid for v in  i.deployedServices.all()]
         return res
     except:
         logger.exception('REST groups')
         self.invalidItemException()
Example #33
0
 def getLogs(self, parent, item):
     try:
         item = parent.services.get(uuid=processUuid(item))
         logger.debug('Getting logs for {0}'.format(item))
         return log.getLogs(item)
     except Exception:
         self.invalidItemException()
Example #34
0
    def servicesPools(self, parent: 'Provider', item: str) -> typing.Any:
        service = parent.services.get(uuid=processUuid(item))
        logger.debug('Got parameters for servicepools: %s, %s', parent, item)
        res = []
        for i in service.deployedServices.all():
            try:
                self.ensureAccess(i, permissions.PERMISSION_READ
                                  )  # Ensures access before listing...
                res.append({
                    'id':
                    i.uuid,
                    'name':
                    i.name,
                    'thumb':
                    i.image.thumb64
                    if i.image is not None else DEFAULT_THUMB_BASE64,
                    'user_services_count':
                    i.userServices.exclude(state__in=(State.REMOVED,
                                                      State.ERROR)).count(),
                    'state':
                    _('With errors') if i.isRestrained() else _('Ok'),
                })
            except AccessDenied:
                pass

        return res
Example #35
0
def transportIcon(request, idTrans):
    try:
        icon = Transport.objects.get(
            uuid=processUuid(idTrans)).getInstance().icon(False)
        return HttpResponse(icon, content_type='image/png')
    except Exception:
        return HttpResponseRedirect('/static/img/unknown.png')
Example #36
0
 def getItems(self, parent, item):
     try:
         multi = False
         if item is None:
             multi = True
             q = parent.groups.all().order_by('name')
         else:
             q = parent.groups.filter(uuid=processUuid(item))
         res = []
         for i in q:
             val = {
                 'id': i.uuid,
                 'name': i.name,
                 'comments': i.comments,
                 'state': i.state,
                 'type': i.is_meta and 'meta' or 'group',
                 'meta_if_any': i.meta_if_any
             }
             if i.is_meta:
                 val['groups'] = list(
                     x.uuid for x in i.groups.all().order_by('name'))
             res.append(val)
         if multi:
             return res
         # Add pools field if 1 item only
         res = res[0]
         if i.is_meta:
             res['pools'] = [
             ]  # Meta groups do not have "assigned "pools, they get it from groups interaction
         else:
             res['pools'] = [v.uuid for v in i.deployedServices.all()]
         return res
     except:
         logger.exception('REST groups')
         self.invalidItemException()
Example #37
0
 def getTitle(self, parent):
     try:
         return _('Groups of {0}').format(
             Authenticator.objects.get(
                 uuid=processUuid(self._kwargs['parent_id'])).name)
     except Exception:
         return _('Current groups')
Example #38
0
 def getItems(self, parent, item):
     logger.debug(item)
     # Extract authenticator
     try:
         if item is None:
             values = list(
                 Users.uuid_to_id(parent.users.all().values(
                     'uuid', 'name', 'real_name', 'comments', 'state',
                     'staff_member', 'is_admin', 'last_access', 'parent')))
             for res in values:
                 res['role'] = res['staff_member'] and (
                     res['is_admin'] and _('Admin')
                     or _('Staff member')) or _('User')
             return values
         else:
             u = parent.users.get(uuid=processUuid(item))
             res = model_to_dict(u,
                                 fields=('name', 'real_name', 'comments',
                                         'state', 'staff_member',
                                         'is_admin', 'last_access',
                                         'parent'))
             res['id'] = u.uuid
             res['role'] = res['staff_member'] and (
                 res['is_admin'] and _('Admin')
                 or _('Staff member')) or _('User')
             usr = aUser(u)
             res['groups'] = [g.dbGroup().uuid for g in usr.groups()]
             logger.debug('Item: %s', res)
             return res
     except Exception:
         logger.exception('En users')
         self.invalidItemException()
Example #39
0
    def deleteItem(self, parent: models.ServicePool, item: str) -> None:
        try:
            userService: models.UserService = parent.userServices.get(
                uuid=processUuid(item))
        except Exception:
            logger.exception('deleteItem')
            raise self.invalidItemException()

        if userService.user:
            logStr = 'Deleted assigned service {} to user {} by {}'.format(
                userService.friendly_name, userService.user.pretty_name,
                self._user.pretty_name)
        else:
            logStr = 'Deleted cached service {} by {}'.format(
                userService.friendly_name, self._user.pretty_name)

        if userService.state in (State.USABLE, State.REMOVING):
            userService.remove()
        elif userService.state == State.PREPARING:
            userService.cancel()
        elif userService.state == State.REMOVABLE:
            raise self.invalidItemException(_('Item already being removed'))
        else:
            raise self.invalidItemException(_('Item is not removable'))

        log.doLog(parent, log.INFO, logStr, log.ADMIN)
Example #40
0
    def cancel(self, parent, uuid):
        """
        Invoked to cancel a running publication
        Double invocation (this means, invoking cancel twice) will mean that is a "forced cancelation"
        :param parent: Parent service pool
        :param uuid: uuid of the publication
        """
        if permissions.checkPermissions(
                self._user, parent,
                permissions.PERMISSION_MANAGEMENT) is False:
            logger.debug('Management Permission failed for user {}'.format(
                self._user))
            self.accessDenied()

        try:
            ds = DeployedServicePublication.objects.get(uuid=processUuid(uuid))
            ds.cancel()
        except Exception as e:
            raise ResponseError("{}".format(e))

        log.doLog(
            parent, log.INFO, "Canceled publication v{} by {}".format(
                parent.current_pub_revision, self._user.pretty_name),
            log.ADMIN)

        return self.success()
Example #41
0
    def deleteItem(self, parent: 'ServicePool', item: str) -> None:
        calendarAccess = parent.calendarAccess.get(uuid=processUuid(self._args[0]))
        logStr = "Removed access calendar {} by {}".format(calendarAccess.calendar.name, self._user.pretty_name)

        calendarAccess.delete()

        log.doLog(parent, log.INFO, logStr, log.ADMIN)
Example #42
0
 def getItems(self, parent: models.ServicePool, item: typing.Optional[str]):
     # Extract provider
     try:
         if not item:
             return [
                 AssignedService.itemToDict(k)
                 for k in parent.assignedUserServices().all().
                 prefetch_related('properties', 'deployed_service',
                                  'publication', 'user')
             ]
         return AssignedService.itemToDict(
             parent.assignedUserServices().get(
                 processUuid(uuid=processUuid(item))))
     except Exception:
         logger.exception('getItems')
         raise self.invalidItemException()
Example #43
0
    def deleteItem(self, parent, item):  # This is also used by CachedService, so we use "userServices" directly and is valid for both
        service = None
        try:
            service = parent.userServices.get(uuid=processUuid(item))
        except Exception:
            logger.exception('deleteItem')
            self.invalidItemException()

        if service.user:
            logStr = 'Deleted assigned service {} to user {} by {}'.format(service.friendly_name, service.user.pretty_name, self._user.pretty_name)
        else:
            logStr = 'Deleted cached service {} by {}'.format(service.friendly_name, self._user.pretty_name)

        if service.state in (State.USABLE, State.REMOVING):
            service.remove()
        elif service.state == State.PREPARING:
            service.cancel()
        elif service.state == State.REMOVABLE:
            self.invalidItemException(_('Item already being removed'))
        else:
            self.invalidItemException(_('Item is not removable'))

        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
Example #44
0
def transportIcon(request: 'HttpRequest', idTrans: str) -> HttpResponse:
    try:
        transport: Transport = Transport.objects.get(uuid=processUuid(idTrans))
        return HttpResponse(transport.getInstance().icon(),
                            content_type='image/png')
    except Exception:
        return HttpResponse(DEFAULT_IMAGE, content_type='image/png')
Example #45
0
    def deleteItem(
        self, parent, item
    ):  # This is also used by CachedService, so we use "userServices" directly and is valid for both
        service = None
        try:
            service = parent.userServices.get(uuid=processUuid(item))
        except Exception:
            logger.exception('deleteItem')
            self.invalidItemException()

        if service.user:
            logStr = 'Deleted assigned service {} to user {} by {}'.format(
                service.friendly_name, service.user.pretty_name,
                self._user.pretty_name)
        else:
            logStr = 'Deleted cached service {} by {}'.format(
                service.friendly_name, self._user.pretty_name)

        if service.state in (State.USABLE, State.REMOVING):
            service.remove()
        elif service.state == State.PREPARING:
            service.cancel()
        elif service.state == State.REMOVABLE:
            self.invalidItemException(_('Item already being removed'))
        else:
            self.invalidItemException(_('Item is not removable'))

        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
Example #46
0
    def saveItem(self, parent, item):
        # Extract item db fields
        # We need this fields for all
        logger.debug('Saving service for {0} / {1}'.format(parent, item))
        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)
            else:
                service = parent.services.get(uuid=processUuid(item))
                service.__dict__.update(fields)

            service.tags.set([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()
        except Service.DoesNotExist:
            self.invalidItemException()
        except IntegrityError:  # Duplicate key probably
            raise RequestError(_('Element already exists (duplicate key error)'))
        except coreService.ValidationException as e:
            if item is None:  # Only remove partially saved element if creating new (if editing, ignore this)
                self._deleteIncompleteService(service)
            raise RequestError(_('Input error: {0}'.format(six.text_type(e))))
        except Exception as e:
            if item is None:
                self._deleteIncompleteService(service)
            logger.exception('Saving Service')
            raise RequestError('incorrect invocation to PUT: {0}'.format(e))

        return self.getItems(parent, service.uuid)
    def execute(self, parent, item):
        self.ensureAccess(item, permissions.PERMISSION_MANAGEMENT)
        logger.debug('Launching action')
        uuid = processUuid(item)
        calAction = CalendarAction.objects.get(uuid=uuid)
        calAction.execute()

        return self.success()
Example #48
0
    def post(self):
        '''
        Processes post requests
        '''
        if len(self._args) != 2:
            raise RequestError('Invalid request')

        uuid, message = self._args[0], self._args[1]
        if self._params.get('data') is not None:
            data = self._params['data']
        else:
            data = None

        # Right now, only "message" posts
        try:
            service = UserService.objects.get(uuid=processUuid(uuid))
        except Exception:
            return Actor.result(_('User service not found'), error=ERR_USER_SERVICE_NOT_FOUND)

        if message == 'notifyComms':
            logger.debug('Setting comms url to {}'.format(data))
            service.setCommsUrl(data)
            return Actor.result('ok')
        elif message == 'ssoAvailable':
            logger.debug('Setting that SSO is available')
            service.setProperty('sso_available', 1)
            return Actor.result('ok')
        elif message == 'version':
            version = self._params.get('version', 'unknown')
            logger.debug('Got notified version {}'.format(version))
            service.setProperty('actor_version', version)

        # "Cook" some messages, common to all clients, such as "log"
        if message == 'log':
            logger.debug(self._params)
            data = '\t'.join((self._params.get('message'), six.text_type(self._params.get('level', 10000))))

        osmanager = service.getInstance().osmanager()

        try:
            if osmanager is None:
                if message in ('login', 'logout'):
                    osm = OSManager(None, None)  # Dummy os manager, just for using "logging" capability
                    if message == 'login':
                        osm.loggedIn(service)
                    else:
                        osm.loggedOut(service)
                        # Mark for removal...
                        service.release()  # Release for removal
                    return 'ok'
                raise Exception('Unknown message {} for an user service without os manager'.format(message))
            else:
                res = osmanager.process(service, message, data, options={'scramble': False})
        except Exception as e:
            logger.exception("Exception processing from OS Manager")
            return Actor.result(six.text_type(e), ERR_OSMANAGER_ERROR)

        return Actor.result(res)
Example #49
0
    def beforeSave(self, fields):
        # logger.debug(self._params)
        try:
            try:
                service = Service.objects.get(uuid=processUuid(fields['service_id']))
                fields['service_id'] = service.id
            except:
                raise RequestError(ugettext('Base service does not exist anymore'))

            try:
                serviceType = service.getType()

                if serviceType.publicationType is None:
                    self._params['publish_on_save'] = False

                if serviceType.needsManager is True:
                    osmanager = OSManager.objects.get(uuid=processUuid(fields['osmanager_id']))
                    fields['osmanager_id'] = osmanager.id
                else:
                    del fields['osmanager_id']

                if serviceType.usesCache is False:
                    for k in ('initial_srvs', 'cache_l1_srvs', 'cache_l2_srvs', 'max_srvs'):
                        fields[k] = 0

            except Exception:
                raise RequestError(ugettext('This service requires an OS Manager'))

            # If max < initial or cache_1 or cache_l2
            fields['max_srvs'] = max((int(fields['initial_srvs']), int(fields['cache_l1_srvs']), int(fields['max_srvs'])))

            imgId = fields['image_id']
            fields['image_id'] = None
            logger.debug('Image id: {}'.format(imgId))
            try:
                if imgId != '-1':
                    image = Image.objects.get(uuid=processUuid(imgId))
                    fields['image_id'] = image.id
            except Exception:
                logger.exception('At image recovering')

        except (RequestError, ResponseError):
            raise
        except Exception as e:
            raise RequestError(str(e))
Example #50
0
    def saveItem(self, parent, item):
        fields = self.readFieldsFromParams(['auth_id', 'user_id'])
        service = parent.userServices.get(uuid=processUuid(item))
        user = User.objects.get(uuid=processUuid(fields['user_id']))

        logStr = 'Changing ownership of service from {} to {} by {}'.format(service.user.pretty_name, user.pretty_name, self._user.pretty_name)

        # If there is another service that has this same owner, raise an exception
        if parent.userServices.filter(user=user).exclude(uuid=service.uuid).exclude(state__in=State.INFO_STATES).count() > 0:
            raise self.invalidResponseException('There is already another user service assigned to {}'.format(user.pretty_name))

        service.user = user
        service.save()

        # Log change
        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
Example #51
0
    def deleteItem(self, parent, item):
        try:
            user = parent.users.get(uuid=processUuid(item))

            user.delete()
        except Exception:
            self.invalidItemException()

        return 'deleted'
Example #52
0
    def deleteItem(self, parent, item):
        calendarAccess = parent.calendarAccess.get(uuid=processUuid(self._args[0]))
        logStr = "Removed access calendar {} by {}".format(calendarAccess.calendar.name, self._user.pretty_name)

        calendarAccess.delete()

        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
 def getItems(self, parent, item):
     try:
         if item is None:
             return [AccessCalendars.as_dict(i) for i in parent.calendaraccess_set.all()]
         else:
             i = CalendarAccess.objects.get(uuid=processUuid(item))
             return AccessCalendars.as_dict(i)
     except Exception:
         self.invalidItemException()
Example #54
0
 def _getAssignedService(self, metaPool, userServiceId):
     """
     Gets an assigned service and checks that it belongs to this metapool
     If not found, raises InvalidItemException
     """
     try:
         return UserService.objects.filter(uuid=processUuid(userServiceId), cache_level=0, deployed_service__meta=metaPool)[0]
     except Exception:
         self.invalidItemException()
Example #55
0
    def deleteItem(self, parent: MetaPool, item: str):
        member = parent.members.get(uuid=processUuid(self._args[0]))
        logStr = "Removed meta pool member {} by {}".format(member.pool.name, self._user.pretty_name)

        member.delete()

        log.doLog(parent, log.INFO, logStr, log.ADMIN)

        return self.success()
Example #56
0
    def post(self):
        '''
        This login uses parameters to generate auth token
        The alternative is to use the template tag inside "REST" that is called auth_token, that extracts an auth token from an user session
        We can use any of this forms due to the fact that the auth token is in fact a session key
        Parameters:
            mandatory:
                username:
                password:
                authId or auth or authSmallName: (must include at least one. If multiple are used, precedence is the list order)
        Result:
            on success: { 'result': 'ok', 'auth': [auth_code] }
            on error: { 'result: 'error', 'error': [error string] }

        Locale comes on "Header", as any HTTP Request (Accept-Language header)
        Calls to any method of REST that must be authenticated needs to be called with "X-Auth-Token" Header added
        '''
        try:
            if 'authId' not in self._params and 'authSmallName' not in self._params and 'auth' not in self._params:
                raise RequestError('Invalid parameters (no auth)')

            authId = self._params.get('authId', None)
            authSmallName = self._params.get('authSmallName', None)
            authName = self._params.get('auth', None)

            username, password = self._params['username'], self._params['password']
            locale = self._params.get('locale', 'en')
            if authName == 'admin' or authSmallName == 'admin':
                if GlobalConfig.SUPER_USER_LOGIN.get(True) == username and GlobalConfig.SUPER_USER_PASS.get(True) == password:
                    self.genAuthToken(-1, username, locale, True, True)
                    return{'result': 'ok', 'token': self.getAuthToken()}
                else:
                    raise Exception('Invalid credentials')
            else:
                try:
                    # Will raise an exception if no auth found
                    if authId is not None:
                        auth = Authenticator.objects.get(uuid=processUuid(authId))
                    elif authName is not None:
                        auth = Authenticator.objects.get(name=authName)
                    else:
                        auth = Authenticator.objects.get(small_name=authSmallName)

                    logger.debug('Auth obj: {0}'.format(auth))
                    user = authenticate(username, password, auth)
                    if user is None:  # invalid credentials
                        raise Exception()
                    self.genAuthToken(auth.id, user.name, locale, user.is_admin, user.staff_member)
                    return{'result': 'ok', 'token': self.getAuthToken()}
                except:
                    logger.exception('Credentials ')
                    raise Exception('Invalid Credentials (invalid authenticator)')

            raise Exception('Invalid Credentials')
        except Exception as e:
            logger.exception('exception')
            return {'result': 'error', 'error': unicode(e)}
Example #57
0
 def beforeSave(self, fields):
     imgId = fields['image_id']
     fields['image_id'] = None
     logger.debug('Image id: {}'.format(imgId))
     try:
         if imgId != '-1':
             image = Image.objects.get(uuid=processUuid(imgId))
             fields['image_id'] = image.id
     except Exception:
         logger.exception('At image recovering')
Example #58
0
    def deleteItem(self, parent, item):
        logger.debug('Deleting account usage {} from {}'.format(item, parent))
        try:
            usage = parent.usages.get(uuid=processUuid(item))
            usage.delete()
        except Exception:
            logger.exception('Exception')
            self.invalidItemException()

        return 'deleted'
Example #59
0
 def getItems(self, parent: MetaPool, item: str):
     try:
         if item is None:
             return [MetaServicesPool.as_dict(i) for i in parent.members.all()]
         else:
             i = parent.members.get(uuid=processUuid(item))
             return MetaServicesPool.as_dict(i)
     except Exception:
         logger.exception('err: %s', item)
         self.invalidItemException()
    def saveItem(self, parent, item):
        # If already exists
        uuid = processUuid(item) if item is not None else None

        calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
        access = self._params['access'].upper()
        priority = int(self._params['priority'])

        if uuid is not None:
            calAccess = CalendarAccess.objects.get(uuid=uuid)
            calAccess.calendar = calendar
            calAccess.service_pool = parent
            calAccess.access = access
            calAccess.priority = priority
            calAccess.save()
        else:
            CalendarAccess.objects.create(calendar=calendar, service_pool=parent, access=access, priority=priority)

        return self.success()