def get_console(request, console_type, instance):
    """Get a console url based on console type."""
    if console_type == 'AUTO':
        check_consoles = CONSOLES
    else:
        try:
            check_consoles = {'console_type': CONSOLES[console_type]}
        except KeyError:
            msg = _('Console type "%s" not supported.') % console_type
            raise exceptions.NotAvailable(msg)

    for api_call in check_consoles.values():
        # Ugly workaround due novaclient API change from 2.17 to 2.18.
        try:
            httpnotimplemented = nova_exception.HttpNotImplemented
        except AttributeError:
            httpnotimplemented = nova_exception.HTTPNotImplemented
        try:
            console = api_call(request, instance.id)
        # If not supported, don't log it to avoid lot of errors in case
        # of AUTO.
        except httpnotimplemented:
            continue
        except Exception:
            LOG.debug('Console not available', exc_info=True)
            continue

        console_url = "%s&%s(%s)" % (
            console.url, urlencode({'title': getattr(instance, "name", "")
                                    }), instance.id)
        return console_url

    raise exceptions.NotAvailable(_('No available console found.'))
Beispiel #2
0
def get_console(request, console_type, instance):
    """Get a console url based on console type."""
    if console_type == 'AUTO':
        check_consoles = CONSOLES
    else:
        try:
            check_consoles = {'console_type': CONSOLES[console_type]}
        except KeyError:
            msg = _('Console type "%s" not supported.') % console_type
            LOG.error(msg)
            raise exceptions.NotAvailable(msg)

    for api_call in check_consoles.values():
        try:
            console = api_call(request, instance.id)
        #if not supported don't log it to avoid lot of errors
        #in case of AUTO
        except nova_exception.HTTPNotImplemented:
            continue
        except Exception as e:
            LOG.exception(e)
            continue

        console_url = "%s&%s(%s)" % (
            console.url, urlencode({'title': getattr(instance, "name", "")
                                    }), instance.id)
        return console_url

    raise exceptions.NotAvailable(_('No available console found.'))
Beispiel #3
0
    def post(self, request, server_id):
        """Gets information about an available remote console for the given
        server.

        Example POST:
        http://localhost/api/nova/servers/abcd/console-info/
        """
        console_type = request.DATA.get('console_type', 'AUTO')
        CONSOLES = OrderedDict([('VNC', api.nova.server_vnc_console),
                                ('SPICE', api.nova.server_spice_console),
                                ('RDP', api.nova.server_rdp_console),
                                ('SERIAL', api.nova.server_serial_console)])

        """Get a tuple of console url and console type."""
        if console_type == 'AUTO':
            check_consoles = CONSOLES
        else:
            try:
                check_consoles = {console_type: CONSOLES[console_type]}
            except KeyError:
                msg = _('Console type "%s" not supported.') % console_type
                raise hz_exceptions.NotAvailable(msg)

        # Ugly workaround due novaclient API change from 2.17 to 2.18.
        try:
            httpnotimplemented = exceptions.HttpNotImplemented
        except AttributeError:
            httpnotimplemented = exceptions.HTTPNotImplemented

        for con_type, api_call in six.iteritems(check_consoles):
            try:
                console = api_call(request, server_id)
            # If not supported, don't log it to avoid lot of errors in case
            # of AUTO.
            except httpnotimplemented:
                continue
            except Exception:
                continue

            if con_type == 'SERIAL':
                console_url = console.url
            else:
                console_url = "%s&%s(%s)" % (
                              console.url,
                              utils_http.urlencode({'title': _("Console")}),
                              server_id)

            return {"type": con_type, "url": console_url}
        raise hz_exceptions.NotAvailable(_('No available console found.'))
Beispiel #4
0
    def test_detail_api_error_handle(self):
        dc_group_info = fixture.SERVICE_DATA_DEFAULT['dc_group_info']
        obj_id = '|'.join(['dcconnect', str(dc_group_info[0]['group_id'])])

        nal_api.get_services(IsA(http.HttpRequest),
                             group_id=obj_id.split('|')[1],
                             func_type=obj_id.split('|')[0]).AndRaise(
                                 exceptions.NotAvailable())

        tenant_data = []
        tenant_names = {}
        for data in TENANT_LIST_RETURN:
            tenant_data.append(Tenant(data))
            tenant_names[data['id']] = data['name']

        service_data = []
        check_service_data = []
        for data in fixture.SERVICE_DATA_LIST:
            service = Service(data, SERVICE_RETURN_MAPPING['all_dcconnect'])
            service_data.append(service)
            service.tenant_name = tenant_names.get(service.tenant_id, None)
            check_service_data.append(service)

        nal_api.get_services(IsA(http.HttpRequest),
                             func_type='all_dcconnect').AndReturn(service_data)

        api.keystone.tenant_list(IsA(http.HttpRequest),
                                 paginate=True).AndReturn([tenant_data, True])

        self.mox.ReplayAll()
        res = self.client.get(
            reverse(SERVICE_DETAIL_URL, kwargs={"group_id": obj_id}))
        self.assertRedirects(res, SERVICE_INDEX_URL)
Beispiel #5
0
def get_console(request, console_type, instance, password=None):
    """Get a tuple of console url and console type."""
    if console_type == 'AUTO':
        check_consoles = CONSOLES
    else:
        try:
            check_consoles = {console_type: CONSOLES[console_type]}
        except KeyError:
            msg = _('Console type "%s" not supported.') % console_type
            raise exceptions.NotAvailable(msg)

    # Ugly workaround due novaclient API change from 2.17 to 2.18.
    try:
        httpnotimplemented = nova_exception.HttpNotImplemented
    except AttributeError:
        httpnotimplemented = nova_exception.HTTPNotImplemented

    for con_type, api_call in six.iteritems(check_consoles):
        try:
            console = api_call(request, instance.id)
        # If not supported, don't log it to avoid lot of errors in case
        # of AUTO.
        except httpnotimplemented:
            continue
        except Exception:
            LOG.debug('Console not available', exc_info=True)
            continue

        if con_type == 'SERIAL':
            console_url = console.url
        else:
            if password:
                console_url = "%s&%s&%s(%s)" % (
                              console.url,
                              urlencode({'password': get_password(password)}),
                              urlencode({'title': getattr(instance, "name", "")}),
                              instance.id)
            else:
                console_url = "%s&%s(%s)" % (
                              console.url,
                              urlencode({'title': getattr(instance, "name", "")}),
                              instance.id)
        return (con_type, console_url)

    raise exceptions.NotAvailable(_('No available console found.'))
 def __init__(self, request, *args, **kwargs):
     super(CloneBackupJobNameAction, self).__init__(request, *args,
                                                    **kwargs)
     current_backup = get_backup_job(id=extract_object_id(request))
     if not current_backup:
         raise exceptions.NotAvailable("Object not found")
     self.fields[
         'name'].initial = constants.BACKUP_CLONE_DEFAULT_NAME_PATTERN.format(
             current_backup.name)
 def __init__(self, request, *args, **kwargs):
     super(UpdateBackupNotificationAction,
           self).__init__(request, *args, **kwargs)
     current_backup = get_backup_job(id=extract_object_id(request))
     if not current_backup:
         raise exceptions.NotAvailable("Object not found")
     self.fields['notification'].choices = [('', '')] + [
         (notif.id, notif.name) for notif in list_notifications()
     ]
     self.fields[
         'notification'].initial = current_backup.notification.id if current_backup.notification else ''
Beispiel #8
0
    def test_index_api_error_handle(self):
        tenant_data = []
        for data in TENANT_LIST_RETURN:
            tenant_data.append(Tenant(data))

        nal_api.get_services(IsA(http.HttpRequest),
                             func_type='all_dcconnect').AndRaise(
                                 exceptions.NotAvailable())

        self.mox.ReplayAll()
        res = self.client.get(SERVICE_INDEX_URL)
        self.assertItemsEqual(res.context['table'].data, [])
    def __init__(self, request, context, *args, **kwargs):
        super(UpdateScheduleAction, self).__init__(request, context, *args,
                                                   **kwargs)
        current_backup = get_backup_job(id=extract_object_id(request))
        if not current_backup:
            # TODO to improve
            raise exceptions.NotAvailable("Object not found")

        pattern_array = current_backup.schedule_pattern.split(' ')
        self.fields['minute'].initial = pattern_array[0]
        self.fields['hour'].initial = pattern_array[1]
        self.fields['day'].initial = pattern_array[2]
        self.fields['month'].initial = pattern_array[3]
        self.fields['weekday'].initial = pattern_array[4]
 def __init__(self, request, context, *args, **kwargs):
     super(UpdateNameAction, self).__init__(request, context, *args,
                                            **kwargs)
     current_backup = get_backup_job(id=extract_object_id(request))
     if not current_backup:
         raise exceptions.NotAvailable("Object not found")
     self.fields['name'].initial = current_backup.name
     workflow_input = loads(current_backup.workflow_input)
     self.fields['instance'].initial = workflow_input.get('instance')
     metadata = workflow_input.get('metadata')
     self.fields[
         'metadata_key'].initial = metadata['key'] if metadata else ''
     self.fields[
         'metadata_value'].initial = metadata['value'] if metadata else ''
Beispiel #11
0
    def test_index_api_error_handle(self):

        nal_api.get_nodes(IsA(http.HttpRequest),
                          func_type='all_node')\
            .AndRaise(exceptions.NotAvailable())

        tenant_list = []
        for data in TENANT_LIST_RETURN:
            tenant_list.append(Tenant(data))
        api.keystone.tenant_list(IsA(http.HttpRequest),
                                 paginate=True).AndReturn([tenant_list, True])

        self.mox.ReplayAll()
        res = self.client.get(NODE_INDEX_URL)
        self.assertItemsEqual(res.context['table'].data, [])
Beispiel #12
0
    def test_create_parameter_error(self):

        obj_id = '|'.join(['ext_globalip',
                           'globalip'])
        nal_api.update_resource(IsA(http.HttpRequest),
                                IsA({})).AndRaise(exceptions.NotAvailable())
        self.mox.ReplayAll()

        formData = {'resource_kind': 'ext_globalip',
                    'resource_id': obj_id,
                    'count': 1}
        res = self.client.post(reverse(RESOURCE_CREATE_URL,
                                       kwargs={"resource_id": obj_id}),
                               formData)

        self.assertTemplateUsed(res, 'project/resource/create.html')
Beispiel #13
0
    def delete(self, request, obj_id):
        user = self.table.get_object_by_id(obj_id)

        # NOTE(dale): There is a different endpoint to revoke an invited user
        #             than an Active user.
        result = None
        if user.cohort == 'Invited':
            # Revoke invite for the user
            result = adjutant.user_revoke(request, user.id)
        else:
            # Revoke all roles from the user.
            # That'll get them out of our project; they keep their account.
            result = adjutant.user_roles_remove(request, user.id, user.roles)
        if not result or result.status_code != 200:
            exception = exceptions.NotAvailable()
            exception._safe_message = False
            raise exception
Beispiel #14
0
    def test_update_parameter_error(self):

        resource_data = {}
        for key, value in RESOURCE_RETURN_MAPPING['ext_globalip'].iteritems():
            if isinstance(value, dict):
                resource_data[key] = []
                for resource_row in fixture.RESOURCE_DATA_GLOBALIP[key]:
                    resource_data[key].append(Resource(resource_row, value))

        node_data = []
        for data in fixture.NODE_DATA_LIST:
            node_data.append(Node(data,
                                  NODE_RETURN_MAPPING['all_node']['Virtual']))

        nal_api.get_resources(IsA(http.HttpRequest),
                              IsA('str'),
                              func_type='ext_globalip')\
            .AndReturn(resource_data)

        nal_api.get_nodes(IsA(http.HttpRequest),
                          IsA('str'),
                          func_type='all_node')\
            .AndReturn(node_data)

        nal_api.update_resource(IsA(http.HttpRequest),
                                IsA({}))\
            .AndRaise(exceptions.NotAvailable())

        self.mox.ReplayAll()

        obj_id = '|'.join(['ext_globalip',
                           'global_ip',
                           '133'])
        formData = {'func_type': 'ext_globalip',
                    'resource': '133',
                    'status': '2',
                    'node_id': 'xxxxx-xxxxx-xxxxx-xxxxx-xxxx1',
                    'update_type': 'change_status'}
        res = self.client.post(reverse(RESOURCE_UPDATE_URL,
                                       args=(obj_id, 'change_status')),
                               formData)

        self.assertTemplateUsed(res, 'project/resource/update.html')
 def __init__(self, request, context, *args, **kwargs):
     super(UpdateInputAction, self).__init__(request, context, *args,
                                             **kwargs)
     current_backup = get_backup_job(id=extract_object_id(request))
     if not current_backup:
         raise exceptions.NotAvailable("Object not found")
     workflow_input = loads(current_backup.workflow_input)
     self.fields['stop_instance'].initial = workflow_input['instance_stop']
     self.fields['pause_instance'].initial = workflow_input[
         'instance_pause']
     self.fields['max_snapshots'].initial = int(
         workflow_input['max_snapshots']
     ) if workflow_input['max_snapshots'] else 0
     self.fields['max_backups'].initial = int(
         workflow_input['max_backups']
     ) if workflow_input['max_backups'] else 0
     self.fields[
         'preserve_snapshot'].initial = not workflow_input['only_backup']
     self.fields['backup_type'].initial = workflow_input['backup_type']
     self.fields['backup_mode'].initial = workflow_input['cinder_backup']
 def verify_integrity(self):
     provided_keys = self.contributions | set(self.context_seed.keys())
     if len(self.depends_on - provided_keys):
         raise exceptions.NotAvailable(
             _("The current user has insufficient permission to complete "
               "the requested task."))
Beispiel #17
0
 def action(self, request, obj_id):
     result = adjutant.token_reissue(request, obj_id)
     if not result or result.status_code != 200:
         exception = exceptions.NotAvailable()
         exception._safe_message = False
         raise exception
Beispiel #18
0
 def delete(self, request, obj_id):
     result = adjutant.task_cancel(request, obj_id)
     if not result or result.status_code != 200:
         exception = exceptions.NotAvailable()
         exception._safe_message = False
         raise exception
Beispiel #19
0
 def action(self, request, obj_id):
     result = adjutant.notifications_acknowlege(request, obj_id)
     if not result or result.status_code != 200:
         exception = exceptions.NotAvailable()
         exception._safe_message = False
         raise exception