def _run(self, option, value): section, sep, key = option.rpartition('.') prefix = 'cloud.' if section.startswith(prefix): cloudname = section[len(prefix):] if cloudname: self.config.set_cloud(cloudname, key, value) else: raise CLISyntaxError('Empty cloud alias (%s)' % option, importance=2) elif section in ('cloud', ): raise CLISyntaxError( 'Invalid syntax for cloud definition', importance=2, details=[ 'To define a cloud "%s"' % key, 'set the cloud\'s authentication url and token:', ' /config set cloud.%s.url <URL>' % key, ' /config set cloud.%s.token <t0k3n>' % key ]) else: section = section or 'global' self.config.set(section, key, value) self.config.write() self.config.reload()
def main(self, server_id): super(self.__class__, self)._run() if all([self['attachment_id'], self['volume_id']]): raise CLISyntaxError('Invalid argument compination', details=[ '%s and %s are mutually exclusive' % ( self.arguments['attachment_id'].lvalue, self.arguments['volume_id'].lvalue)]) self._run(server_id=server_id)
def parse(self, new_args=None): """Parse user input""" try: pkargs = (new_args,) if new_args else () self._parsed, unparsed = self.parser.parse_known_args(*pkargs) parsed_args = [ k for k, v in vars(self._parsed).items() if v not in (None, )] if not self._parse_required_arguments(self.required, parsed_args): self.print_help() raise CLISyntaxError('Missing required arguments') except SystemExit: raiseCLIError(CLISyntaxError('Argument Syntax Error')) for name, arg in self.arguments.items(): arg.value = getattr(self._parsed, name, arg.default) self._unparsed = [] for term in unparsed: self._unparsed += split_input(' \'%s\' ' % term) self._parser_modified = False
def wrap(self, *args, **kwargs): try: token = kwargs.pop('token') except KeyError: raise CLISyntaxError('A token is needed for %s' % func) token_bu = self.client.token try: self.client.token = token or token_bu return func(self, *args, **kwargs) finally: self.client.token = token_bu
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 value(self, newvalue): if newvalue == self.default: self._value = newvalue return try: if int(newvalue) == float(newvalue): self._value = int(newvalue) else: raise ValueError('Raise int argument error') except ValueError: raiseCLIError( CLISyntaxError('IntArgument Error', details=['Value %s not an int' % newvalue]))
def _run(self, server_id): hard_reboot = None if self['type']: if self['type'].lower() in ('soft', ): hard_reboot = False elif self['type'].lower() in ('hard', ): hard_reboot = True else: raise CLISyntaxError( 'Invalid reboot type %s' % self['type'], importance=2, details=[ '--type values are either SOFT (default) or HARD']) self.client.reboot_server(int(server_id), hard_reboot) if self['wait']: self.wait_while(server_id, 'REBOOT')
def value(self, options): if options == self.default: return if not isinstance(options, list): options = ['%s' % options] for option in options: keypath, sep, val = option.partition('=') if not sep: raiseCLIError(CLISyntaxError('Argument Syntax Error '), details=[ '%s is missing a "="', ' (usage: -o section.key=val)' % option ]) section, sep, key = keypath.partition('.') if not sep: key = section section = 'global' self._config_arg.value.override(section.strip(), key.strip(), val.strip())
def _run(self): if self['uuid'] and self['name']: raise CLISyntaxError( 'Arguments uuid and username are mutually exclusive', details=['Use either uuid OR username OR none, but NOT both']) uuid = self['uuid'] or (self._username2uuid(self['name']) if ( self['name']) else None) try: if any([self['uuid'], self['name']]) and not uuid: raise KeyError() token = self.astakos.get_token(uuid) if uuid else None except KeyError: msg = ('id %s' % self['uuid']) if ( self['uuid']) else 'username %s' % self['name'] raise CLIError( 'No user with %s in the cached session list' % msg, details=[ 'To see all cached session users:', ' kamaki user list', 'To authenticate and add a new user in the session list:', ' kamaki user add NEW_TOKEN']) self.print_(self.astakos.user_info(token), self.print_dict)
def _raise(self, cmd_ids, *args, **kwargs): if not cmd_ids: raise CLISyntaxError('Usage: <id1|id1-id2> [id3|id3-id4] ...', details=self.__doc__.split('\n')) return func(self, cmd_ids, *args, **kwargs)
def rescue_old_file(self, err=stderr): lost_terms = [] global_terms = DEFAULTS['global'].keys() translations = dict( config=dict(serv='', cmd='config'), history=dict(serv='', cmd='history'), pithos=dict(serv='pithos', cmd='file'), file=dict(serv='pithos', cmd='file'), store=dict(serv='pithos', cmd='file'), storage=dict(serv='pithos', cmd='file'), image=dict(serv='plankton', cmd='image'), plankton=dict(serv='plankton', cmd='image'), compute=dict(serv='compute', cmd=''), cyclades=dict(serv='compute', cmd='server'), server=dict(serv='compute', cmd='server'), flavor=dict(serv='compute', cmd='flavor'), keypair=dict(serv='compute', cmd='keypair'), network=dict(serv='network', cmd='network'), astakos=dict(serv='astakos', cmd='user'), user=dict(serv='astakos', cmd='user'), ) dc = 'default_' + CLOUD_PREFIX self.set('global', dc, self.get('global', dc) or 'default') for s in self.sections(): if s in ('global', ): # global.url, global.token --> # cloud.default.url, cloud.default.token for term in set(self.keys(s)).difference(global_terms): if term not in ('url', 'token'): lost_terms.append('%s.%s = %s' % (s, term, self.get(s, term))) self.remove_option(s, term) continue gval = self.get(s, term) default_cloud = self.get('global', 'default_cloud') or 'default' try: cval = self.get_cloud(default_cloud, term) except KeyError: cval = '' if gval and cval and (gval.lower().strip('/') != cval.lower().strip('/')): raise CLISyntaxError( 'Conflicting values for default %s' % (term), importance=2, details=[ ' global.%s: %s' % (term, gval), ' %s.%s.%s: %s' % (CLOUD_PREFIX, default_cloud, term, cval), 'Please remove one of them manually:', ' /config delete global.%s' % term, ' or' ' /config delete %s.%s.%s' % (CLOUD_PREFIX, default_cloud, term), 'and try again' ]) elif gval: err.write(u'... rescue %s.%s => %s.%s.%s\n' % (s, term, CLOUD_PREFIX, default_cloud, term)) err.flush() self.set_cloud('default', term, gval) self.remove_option(s, term) for term, wrong, right in ( ('ip', 'cyclades', 'network'), ('network', 'cyclades', 'network'), ): k = '%s_cli' % term v = self.get(s, k) if v in (wrong, ): err.write('... change %s.%s value: `%s` => `%s`\n' % (s, k, wrong, right)) err.flush() self.set(s, k, right) # translation for <service> or <command> settings # <service> or <command group> settings --> translation --> global elif s in translations: if s in ('history', ): k = 'file' v = self.get(s, k) if v: err.write(u'... rescue %s.%s => global.%s_%s\n' % (s, k, s, k)) err.flush() self.set('global', '%s_%s' % (s, k), v) self.remove_option(s, k) trn = translations[s] for k, v in self.items(s, False): if v and k in ('cli', ): err.write(u'... rescue %s.%s => global.%s_cli\n' % (s, k, trn['cmd'])) err.flush() self.set('global', '%s_cli' % trn['cmd'], v) elif k in ('container', ) and trn['serv'] in ('pithos', ): err.write( u'... rescue %s.%s => %s.default.pithos_%s\n' % (s, k, CLOUD_PREFIX, k)) err.flush() self.set_cloud('default', 'pithos_%s' % k, v) else: lost_terms.append('%s.%s = %s' % (s, k, v)) self.remove_section(s) # self.pretty_print() return lost_terms
def test___init__(self): from kamaki.cli.errors import CLISyntaxError clise = CLISyntaxError() self.assertEqual('%s' % clise, 'Syntax Error\n') self.assertEqual(clise.details, []) self.assertEqual(clise.importance, 1)