def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Exception as e: log.debug('Error stack:\n%s' % ''.join(format_stack())) log.debug(format_exc(e)) if isinstance(e, CLIError): raise e elif isinstance(e, ClientError): raise CLIError( '(%s) %s' % (getattr(e, 'status', 'no status'), e), details=getattr(e, 'details', []), importance=1 if ( e.status < 200) else 2 if ( e.status < 300) else 3 if ( e.status < 400) else 4) raise CLIError( '%s' % e, details=['%s, -d for debug info' % type(e)])
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status == 403: raise CLIError( 'Insufficient credentials for this operation', details=['%s %s' % (getattr(ce, 'status', ''), ce), ]) raise
def _raise(self, *args, **kwargs): local_path = kwargs.get('local_path', None) try: return func(self, *args, **kwargs) except IOError as ioe: raise CLIError('Failed to access file %s' % local_path, details=[ u'%s' % ioe, ], importance=2)
def _raise(self, *args, **kwargs): size = kwargs.get('size', None) start = kwargs.get('start', 0) end = kwargs.get('end', 0) if size: try: size = int(size) except ValueError as ve: raise CLIError( 'Invalid file size %s ' % size, details=['size must be a positive integer', '%s' % ve], importance=1) else: try: start = int(start) except ValueError as e: raise CLIError( 'Invalid start value %s in range' % start, details=['size must be a positive integer', '%s' % e], importance=1) try: end = int(end) except ValueError as e: raise CLIError( 'Invalid end value %s in range' % end, details=['size must be a positive integer', '%s' % e], importance=1) if start > end: raise CLIError( 'Invalid range %s-%s' % (start, end), details=['size must be a positive integer'], importance=1) size = end - start try: return func(self, *args, **kwargs) except ClientError as ce: if size and ce.status in (416, 400): raise CLIError( 'Remote object %s:%s <= %s %s' % ( self.container, self.path, format_size(size), ('(%sB)' % size) if size >= 1024 else ''), details=['%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): membership_id = kwargs.get('membership_id', None) try: return func(self, *args, **kwargs) except ClientError as ce: if membership_id and ce.status in (400, 404): raise CLIError( 'No membership with ID %s' % membership_id, importance=2, details=[ 'To list all memberships', ' kamaki membership list', '%s %s' % (getattr(ce, 'status', ''), ce)]) elif membership_id and ce.status in (403, ): raise CLIError( 'No access to membership %s' % membership_id, importance=3, details=[ 'To see all memberships', ' kamaki membership list', '%s %s' % (getattr(ce, 'status', ''), ce)])
def assert_not_in_status(self, server_id, status): """ :returns: current server status :raises CLIError: if server is already in this status :raises ClientError: (404) if server not found """ current = self.client.get_server_details(server_id).get('status', None) if current in (status, ): raise CLIError('Server %s is already %s' % (server_id, status)) return current
def _set_firewall_profile(self, server_id): vm = self._restruct_server_info( self.client.get_server_details(server_id)) ports = [p for p in vm['ports'] if 'firewallProfile' in p] pick_port = self.arguments['public_network_port_id'] if pick_port.value: ports = [p for p in ports if pick_port.value in ( '*', '%s' % p['id'])] elif len(ports) > 1: port_strings = ['Server %s ports to public networks:' % server_id] for p in ports: port_strings.append(' %s' % p['id']) for k in ('network_id', 'ipv4', 'ipv6', 'firewallProfile'): v = p.get(k) if v: port_strings.append('\t%s: %s' % (k, v)) raise CLIError( 'Multiple public connections on server %s' % ( server_id), details=port_strings + [ 'To select one:', ' %s PORT_ID' % pick_port.lvalue, 'To set all:', ' %s *' % pick_port.lvalue, ]) if not ports: pp = pick_port.value raise CLIError( 'No public networks attached on server %s%s' % ( server_id, ' through port %s' % pp if pp else ''), details=[ 'To see all networks:', ' kamaki network list', 'To see all connections:', ' kamaki server info %s --nics' % server_id, 'To connect to a network:', ' kamaki network connect NETWORK_ID --device-id %s' % ( server_id)]) for port in ports: self.error('Set port %s firewall to %s' % ( port['id'], self['firewall_profile'])) self.client.set_firewall_profile( server_id=server_id, profile=self['firewall_profile'], port_id=port['id'])
def _raise(self, *args, **kwargs): key = kwargs.get('key', None) try: func(self, *args, **kwargs) except ClientError as ce: if key and ce.status == 404 and ( 'metadata' in ('%s' % ce).lower()): raise CLIError( 'No virtual server metadata with key %s' % key, details=['%s %s' % (getattr(ce, 'status', ''), ce), ]) raise
def _raise(self, *args, **kwargs): key_name = kwargs.get('key_name', None) try: func(self, *args, **kwargs) except ClientError as ce: if key_name and ce.status in (404, 400): raise CLIError('No keypair with name %s found' % key_name, importance=2, details=this.about_keypair + ['%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _ip_ready(self, ip, network_id, cerror): network = self._get_network_client() ips = [fip for fip in network.list_floatingips() if ( fip['floating_ip_address'] == ip)] if not ips: msg = 'IP %s not available for current user' % ip raise CLIError(cerror, details=[msg] + errors.Cyclades.about_ips) ipnet, ipvm = ips[0]['floating_network_id'], ips[0]['instance_id'] if getattr(cerror, 'status', 0) in (409, ): msg = '' if ipnet != network_id: msg = 'IP %s belong to network %s, not %s' % ( ip, ipnet, network_id) elif ipvm: msg = 'IP %s is already used by device %s' % (ip, ipvm) if msg: raise CLIError(cerror, details=[ msg, 'To get details on IP', ' kamaki ip info %s' % ip] + errors.Cyclades.about_ips)
def test___init__(self, S): from kamaki.cli.errors import CLIError global _RET for message, details, importance in (('some msg', [], 0), ('some msg\n', 'details', 0), ('some msg', ['details1', 'details2'], 10)): clie = CLIError(message, details, importance) self.assertEqual(S.mock_calls[-1], call(CLIError, clie)) self.assertEqual( _RET[0], (message + '\n') if (message and not message.endswith('\n')) else message) self.assertEqual( clie.details, (list(details) if (isinstance(details, list)) else ['%s' % details]) if (details) else []) self.assertEqual(clie.importance, int(importance)) clie = CLIError(message, details, 'non int') self.assertEqual(clie.importance, 0)
def _raise(self, *args, **kwargs): image_id = kwargs.get('image_id', None) try: func(self, *args, **kwargs) except ClientError as ce: if image_id and ce.status in (404, 400): raise CLIError('No image with id %s found' % image_id, importance=2, details=this.about_image_id + ['%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _run(self): try: with open(self['file_path']) as f: provisions = loads(f.read()) except Exception as e: raise CLIError( 'Failed load a json dict from file %s' % self['file_path'], importance=2, details=['%s' % e]) self.print_(self.client.issue_one_commission( self['uuid'], self['source'], provisions, self['description'] or '', self['force'], self['accept']))
def _raise(self, *args, **kwargs): size = kwargs.get('size', None) try: size = int(size) assert size > 0, 'Cluster size must be a positive integer' return func(self, *args, **kwargs) except ValueError as ve: msg = 'Invalid cluster size value %s' % size raise CLIError(msg, importance=1, details=[ 'Cluster size must be a positive integer', '%s' % ve ]) except AssertionError as ae: raise CLIError('Invalid cluster size %s' % size, importance=1, details=['%s' % ae]) except ClientError: raise
def assert_option(option): if isinstance(option, unicode): try: option = str(option) except UnicodeError, ue: raise CLIError( 'Invalid config option %s' % option, details=[ 'Illegal character(s) in config option name', 'Non-ascii characters are only allowed as values', ue ])
def _raise(self, *args, **kwargs): dst_cont = kwargs.get('dst_cont', None) try: return func(self, *args, **kwargs) except ClientError as ce: if '/' in getattr(self, 'container', ''): raise CLIError( 'Invalid container name %s' % self.container, importance=2, details=[ '"/" is an invalid character for containers', '%s %s' % (getattr(ce, 'status', ''), ce) ]) elif ce.status in (404, ): cont = ('%s or %s' % (self.container, dst_cont)) if ( dst_cont) else self.container raise CLIError( 'Container "%s" does not exist' % cont, importance=2, details=this.container_howto + [ '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _assert_remote_file_not_exist(self, pithos, path): if pithos and not self['force_upload']: try: pithos.get_object_info(path) raise CLIError('File already exists', importance=2, details=[ 'A remote file /%s/%s already exists' % ( pithos.container, path), 'Use %s to force upload' % self.arguments[ 'force_upload'].lvalue]) except ClientError as ce: if ce.status != 404: raise
def _raise(self, *args, **kwargs): network_id = kwargs.get('network_id', None) try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (409, ): raise CLIError( 'Network with id %s is in use' % network_id, importance=3, details=[ 'To list all network ports', ' kamaki port list', '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): details = ['To get a list of all servers', ' kamaki server list'] server_id = kwargs.get('server_id', None) try: server_id = int(server_id) assert server_id > 0, 'error: %s is not positive' % server_id except (ValueError, AssertionError) as err: raise CLIError( 'Invalid server id %s' % server_id, importance=2, details=[ 'Server id must be a positive integer'] + details + [ err, ]) try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (404, ): raise CLIError( 'No servers with ID %s' % server_id, importance=2, details=details + [ '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def value(self, newvalue): if newvalue == self.default: return self.value self._value, input_dict = [], {} for i, terms in enumerate(newvalue): termlist = terms.split(',') if len(termlist) > len(self.terms): msg = 'Wrong number of terms (1<=terms<=%s)' % len(self.terms) raise CLIError(CLISyntaxError(msg), details=howto_personality) for k, v in self.terms: prefix = '%s=' % k for item in termlist: if item.lower().startswith(prefix): input_dict[k] = item[len(k) + 1:] break item = None if item: termlist.remove(item) try: path = input_dict['local-path'] except KeyError: path = termlist.pop(0) if not path: raise CLIInvalidArgument( '--personality: No local path specified', details=howto_personality) if not exists(path): raise CLIInvalidArgument( '--personality: File %s does not exist' % path, details=howto_personality) self._value.append(dict(path=path)) with open(expanduser(path)) as f: self._value[i]['contents'] = b64encode(f.read()) for k, v in self.terms[1:]: try: self._value[i][v] = input_dict[k] except KeyError: try: self._value[i][v] = termlist.pop(0) except IndexError: continue if k in ('mode', ) and self._value[i][v]: try: self._value[i][v] = int(self._value[i][v], 8) except ValueError as ve: raise CLIInvalidArgument( 'Personality mode must be in octal', details=[ '%s' % ve])
def _raise(self, *args, **kwargs): dst_cont = kwargs.get('dst_cont', None) try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (404, ): cont = ('%s or %s' % (self.container, dst_cont)) if ( dst_cont) else self.container raise CLIError('Container "%s" does not exist' % cont, importance=2, details=this.container_howto + ['%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (403, ): network_id = kwargs.get('network_id', '') raise CLIError( 'Insufficient permissions for this action', importance=2, details=[ 'To get information on network', ' kamaki network info %s' % network_id, '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except IOError as ioe: raise CLIError( 'Failed to access a local file', importance=2, details=[ 'To check if the file exists', ' kamaki file info PATH', 'All directories in a remote path must exist, or the ' 'download will fail', 'To create a remote directory', ' kamaki file mkdir REMOTE_DIRECTORY_PATH', u'%s' % ioe])
def _run(self, option): section, sep, key = option.rpartition('.') section = section or 'global' prefix = 'cloud.' if section.startswith(prefix): cloud = section[len(prefix):] try: self.config.remove_from_cloud(cloud, key) except KeyError: raise CLIError('Field %s does not exist' % option) else: self.config.remove_option(section, key, self['default']) self.config.write() self.config.reload()
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (401, ): subnet_id = kwargs.get('subnet_id', '') raise CLIError( 'Insufficient permissions for this action', importance=2, details=[ 'Make sure this subnet belongs to current user', 'To see information on subnet', ' kamaki subnet info %s' % subnet_id, '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): try: func(self, *args, **kwargs) except ClientError as ce: if ce.status in (403, 405): raise CLIError( 'Insufficient permissions for this action', importance=2, details=[ 'To see the owner of an image', ' kamaki image info IMAGE_ID', 'To see image file permissions', ' kamaki file info IMAGE_LOCATION --sharing', '%s %s' % (getattr(ce, 'status', ''), ce)]) raise
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status == 413: raise CLIError('User quota exceeded', details=[ 'To get total quotas', ' kamaki quota list --resource=pithos', 'To get container limit', ' kamaki container info CONTAINER --size-limit', 'Set a higher container limit:', ' kamaki container modify CONTAINER ' '--size-limit=NEW_LIMIT', '%s' % ce]) raise
def _raise(self, *args, **kwargs): try: return func(self, *args, **kwargs) except ClientError as ce: if ce.status in (404, ): _cnt = self.container _cnt = '[/%s]' % _cnt if _cnt == 'pithos' else '/%s' % _cnt raise CLIError( 'No object "%s" in container "%s"' % ( self.path, self.container), importance=2, details=[ 'To list contents in container', ' kamaki file list %s' % _cnt, '%s %s' % (getattr(ce, 'status', ''), ce), ]) raise
def _run(self): uuid = self['uuid_or_username'] if uuid == self.astakos.user_term('id'): raise CLIError('Cannot remove current session user', details=[ 'To see all cached session users', ' kamaki user list', 'To see current session user', ' kamaki user info', 'To select a different session user', ' kamaki user select --user=UUID_OR_USERNAME']) try: self.astakos.remove_user(uuid) except KeyError: raise CLIError( 'No user with uuid %s in session list' % uuid, details=[ 'To see all cached session users', ' kamaki user list', 'To authenticate and add a new user in the session list', ' kamaki user add --token=NEW_TOKEN']) if self.ask_user('Delete user token from config file?'): self['config'].set_cloud( self.cloud, 'token', ' '.join(self.astakos._uuids.keys())) self['config'].write()
def _run(self): ask = self['token'] and self['token'] not in self.astakos._uuids try: self.print_(self.astakos.authenticate(self['token']), self.print_dict) except ClientError as ce: if ce.status in (401, ): raise CLIError('Token %s was not authenticated' % self['token'], details=['%s' % ce]) if ask and self.ask_user( 'Token is temporarily stored in memory. Append it in ' 'configuration file as an alternative token?'): tokens = self.astakos._uuids.keys() tokens.remove(self.astakos.token) self['config'].set_cloud(self.cloud, 'token', ' '.join([self.astakos.token] + tokens)) self['config'].write()