Ejemplo n.º 1
0
    def os_api(self):
        if self.__os_api is None:
            try:
                self.__os_api = self.get_identity_admin_api()
            except (ClientException, ConnectFailure):
                raise ServiceUnavailable(_('Could not connect to openstack'))

        return self.__os_api
Ejemplo n.º 2
0
    def os_user_api(self):
        if self.__os_user_api is None:
            try:
                self.__os_user_api = OpenStackStaffUserApi(
                    keystone_client=self.os_api.client)
            except (ClientException, ConnectFailure):
                raise ServiceUnavailable(_('Could not connect to openstack'))

        return self.__os_user_api
Ejemplo n.º 3
0
def set_license(request):
    """Wrapper view for _set_license."""
    serializer = LicenseKeySerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    license_key = serializer.validated_data['license_key']

    try:
        response, status = _set_license(license_key)
        return Response({'detail': response}, status=status)
    except requests.ConnectionError:
        raise ServiceUnavailable(
            detail=_('Can\'t connect to server. '
                     'Please check your internet connection and retry.'))
Ejemplo n.º 4
0
def refresh_license(request):
    try:
        key = Option.objects.get(section='LICENSE', field='key')
        license_key = fernet_decrypt(key.value)
    except Option.DoesNotExist as e:
        LOG.error(e)
        raise ObjectNotFound(detail=_('License not found'))
    else:
        try:
            response, status = _set_license(license_key)
            return Response({'detail': response}, status=status)
        except requests.ConnectionError as e:
            LOG.error(e)
            raise ServiceUnavailable(
                detail=_('Can\'t connect to server. '
                         'Please check your internet connection and retry.'))
Ejemplo n.º 5
0
    def create_openstack_service(self, request, pk):
        del pk  # unused

        # TODO - #1019: implement proper creation of service here
        serializer = CreateServiceSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        client = self.get_object()

        if client.first_project is not None and client.first_project.deleted is False:
            raise ForbiddenException(
                {'detail': _('Client already has a project')})

        project_id = serializer.validated_data.get('project_id', 'none')

        if Client.objects.filter(
                services__openstack_project__project_id=project_id):
            raise ForbiddenException(
                {'detail': _('Project already associated with a client')})

        openstack_product = Product.objects.get(
            id=serializer.validated_data['product_id'])
        openstack_product_cycle = openstack_product.cycles.filter(
            id=serializer.validated_data['product_cycle_id'])[0]
        service_external_id = serializer.validated_data.get(
            'service_external_id', None)

        with transaction.atomic():
            if serializer.validated_data['create_new_project']:
                try:
                    ProjectModel.objects.create_project(
                        client=client,
                        openstack_product=openstack_product,
                        openstack_product_cycle=openstack_product_cycle,
                        service_external_id=service_external_id,
                    )
                except Conflict:
                    return Response(
                        status=409,
                        data={
                            'detail':
                            _('A project already exists for this client')
                        })
                except RoleDoesNotExist:
                    # TODO: going to the exact settings page and field isn't implemented yet in frontend
                    # on implementation in frontend change section and configuration_id if necessary
                    # (Issue: https://git.fleio.org/fleio/fleio/issues/1922)
                    if plugin_settings.default_role:
                        error_message = _(
                            'Role "{}" does not exist in OpenStack. Set an existing role as default '
                            'role.').format(plugin_settings.default_role)
                    else:
                        error_message = _(
                            'OpenStack role was not set in OpenStack settings -> defaults tab. '
                            'Set an existing role as default role.')
                    raise ConfigException(message=error_message,
                                          section='openstack_plugin_defaults',
                                          configuration_id='default_role')
            else:
                try:
                    project = IdentityAdminApi(
                        request_session=request.session).client.projects.get(
                            project_id)
                except NotFound:
                    raise ObjectNotFound({'detail': _('Project not found')})
                except ConnectFailure:
                    raise ServiceUnavailable(
                        {'detail': _('Could not connect to openstack')})

                with transaction.atomic():
                    try:
                        ProjectModel.objects.create_project(
                            client=client,
                            openstack_product=openstack_product,
                            openstack_product_cycle=openstack_product_cycle,
                            service_external_id=service_external_id,
                            project_id=project.id,
                            project_domain_id=project.domain_id,
                            disabled=not project.enabled,
                            extras={
                                'name': project.name,
                                'description': project.description,
                                'is_domain': project.is_domain
                            }).save()
                    except RoleDoesNotExist:
                        # TODO: going to the exact settings page and field isn't implemented yet in frontend
                        # on implementation in frontend change section and configuration_id if necessary
                        # (Issue: https://git.fleio.org/fleio/fleio/issues/1922)
                        if plugin_settings.default_role:
                            error_message = _(
                                'Role "{}" does not exist in OpenStack. Set an existing role as default '
                                'role.').format(plugin_settings.default_role)
                        else:
                            error_message = _(
                                'OpenStack role was not set in OpenStack settings -> defaults tab. '
                                'Set an existing role as default role.')
                        raise ConfigException(
                            message=error_message,
                            section='openstack_plugin_defaults',
                            configuration_id='default_role')

        return Response({'detail': _('Ok')})
Ejemplo n.º 6
0
def hypervisors_summary_view(request):
    try:
        admin_session = IdentityAdminApi(
            request_session=request.session).session
    except ConfigException:
        # some openstack auth setting is missing, return empty array like others from the fleio dashboard
        return Response({'hypervisors': []})
    hv = Hypervisors(api_session=admin_session)
    openstack_regions = OpenstackRegion.objects.all()
    hypervisor_data = []
    hypervisors_region_data = []
    generic_representation = [{
        'region':
        None,
        'status':
        None,
        'host_ip':
        None,
        'type':
        None,
        'vcpus_data': [0, 0],
        'vcpus_labels': [_('Used vCPUs'), _('Not used vCPUs')],
        'disk_data': [0, 0],
        'disk_labels': [_('Used disk (GB)'),
                        _('Free disk (GB)')],
        'memory_data': [0, 0],
        'memory_labels': [_('Used memory (MB)'),
                          _('Free memory (MB)')]
    }]
    try:
        all_regions = copy.deepcopy(generic_representation)
        all_regions[0]['label'] = _('All Hypervisors...')
        hypervisor_data.append(all_regions)
        for region in openstack_regions:
            try:
                region_hypervisors = hv.get_hypervisors(region=region.id)
            except ConnectTimeout:
                region_hypervisors = None
            except SSLError:
                raise InvalidSSL(
                    'SSL certificate is invalid. '
                    'Check certificate for region: {0}'.format(region))
            if region_hypervisors:
                region_data = copy.deepcopy(generic_representation)
                region_data[0]['label'] = _('All {} hypervisors').format(
                    region)
                for hypervisor in region_hypervisors:
                    per_region = copy.deepcopy(generic_representation)
                    per_region[0]['label'] = _(
                        'Hypervisor {} - {} - {}').format(
                            hypervisor.hypervisor_hostname,
                            hypervisor.hypervisor_type, region.id)
                    per_region[0]['region'] = region.id
                    per_region[0]['status'] = hypervisor.status
                    per_region[0]['host_ip'] = hypervisor.host_ip
                    per_region[0]['type'] = hypervisor.hypervisor_type
                    per_region[0]['vcpus_data'] = [
                        hypervisor.vcpus_used,
                        hypervisor.vcpus - hypervisor.vcpus_used
                    ]
                    per_region[0]['disk_data'] = [
                        hypervisor.local_gb_used,
                        hypervisor.local_gb - hypervisor.local_gb_used
                    ]
                    per_region[0]['memory_data'] = [
                        hypervisor.memory_mb_used,
                        hypervisor.memory_mb - hypervisor.memory_mb_used
                    ]
                    hypervisors_region_data.append(per_region)

                    region_data[0]['vcpus_data'][0] += hypervisor.vcpus_used
                    region_data[0]['vcpus_data'][
                        1] += hypervisor.vcpus - hypervisor.vcpus_used
                    region_data[0]['disk_data'][0] += hypervisor.local_gb_used
                    region_data[0]['disk_data'][
                        1] += hypervisor.local_gb - hypervisor.local_gb_used
                    region_data[0]['memory_data'][
                        0] += hypervisor.memory_mb_used
                    region_data[0]['memory_data'][
                        1] += hypervisor.memory_mb - hypervisor.memory_mb_used
                hypervisor_data[0][0]['vcpus_data'][0] += region_data[0][
                    'vcpus_data'][0]
                hypervisor_data[0][0]['vcpus_data'][1] += region_data[0][
                    'vcpus_data'][1]
                hypervisor_data[0][0]['disk_data'][0] += region_data[0][
                    'disk_data'][0]
                hypervisor_data[0][0]['disk_data'][1] += region_data[0][
                    'disk_data'][1]
                hypervisor_data[0][0]['memory_data'][0] += region_data[0][
                    'memory_data'][0]
                hypervisor_data[0][0]['memory_data'][1] += region_data[0][
                    'memory_data'][1]

                hypervisor_data.append(region_data)
        for region_data in hypervisors_region_data:
            hypervisor_data.append(region_data)
    except (ClientException, ConnectFailure, NovaClientException):
        raise ServiceUnavailable(_('Could not connect to openstack'))
    return Response({
        'hypervisors':
        [item for sublist in hypervisor_data for item in sublist]
    })