# or implied, of GRNET S.A.
from base64 import b64encode
-from os.path import exists
+from os.path import exists, expanduser
from io import StringIO
from pydoc import pager
from kamaki.cli import command
from kamaki.cli.command_tree import CommandTree
from kamaki.cli.utils import remove_from_items, filter_dicts_by_dict
-from kamaki.cli.errors import raiseCLIError, CLISyntaxError, CLIBaseUrlError
-from kamaki.clients.cyclades import CycladesClient, ClientError
-from kamaki.cli.argument import FlagArgument, ValueArgument, KeyValueArgument
-from kamaki.cli.argument import ProgressBarArgument, DateArgument, IntArgument
+from kamaki.cli.errors import (
+ raiseCLIError, CLISyntaxError, CLIBaseUrlError, CLIInvalidArgument)
+from kamaki.clients.cyclades import CycladesClient
+from kamaki.cli.argument import (
+ FlagArgument, ValueArgument, KeyValueArgument, RepeatableArgument,
+ ProgressBarArgument, DateArgument, IntArgument, StatusArgument)
from kamaki.cli.commands import _command_init, errors, addLogSettings
from kamaki.cli.commands import (
_optional_output_cmd, _optional_json, _name_filter, _id_filter)
server_cmds = CommandTree('server', 'Cyclades/Compute API server commands')
flavor_cmds = CommandTree('flavor', 'Cyclades/Compute API flavor commands')
-network_cmds = CommandTree('network', 'Cyclades/Compute API network commands')
-_commands = [server_cmds, flavor_cmds, network_cmds]
+_commands = [server_cmds, flavor_cmds]
about_authentication = '\nUser Authentication:\
howto_personality = [
'Defines a file to be injected to virtual servers file system.',
'syntax: PATH,[SERVER_PATH,[OWNER,[GROUP,[MODE]]]]',
- ' PATH: local file to be injected (relative or absolute)',
- ' SERVER_PATH: destination location inside server Image',
- ' OWNER: virtual servers user id of the remote destination file',
- ' GROUP: virtual servers group id or name of the destination file',
- ' MODEL: permition in octal (e.g. 0777 or o+rwx)']
+ ' [local-path=]PATH: local file to be injected (relative or absolute)',
+ ' [server-path=]SERVER_PATH: destination location inside server Image',
+ ' [owner=]OWNER: virtual servers user id for the remote file',
+ ' [group=]GROUP: virtual servers group id or name for the remote file',
+ ' [mode=]MODE: permission in octal (e.g., 0777)',
+ 'e.g., -p /tmp/my.file,owner=root,mode=0777']
+
+server_states = ('BUILD', 'ACTIVE', 'STOPPED', 'REBOOT')
class _service_wait(object):
'do not show progress bar', ('-N', '--no-progress-bar'), False)
)
- def _wait(self, service, service_id, status_method, currect_status):
+ def _wait(
+ self, service, service_id, status_method, current_status,
+ countdown=True, timeout=60):
(progress_bar, wait_cb) = self._safe_progress_bar(
- '%s %s still in %s mode' % (service, service_id, currect_status))
+ '%s %s: status is still %s' % (
+ service, service_id, current_status),
+ countdown=countdown, timeout=timeout)
try:
new_mode = status_method(
- service_id, currect_status, wait_cb=wait_cb)
+ service_id, current_status, max_wait=timeout, wait_cb=wait_cb)
+ if new_mode:
+ self.error('%s %s: status is now %s' % (
+ service, service_id, new_mode))
+ else:
+ self.error('%s %s: status is still %s' % (
+ service, service_id, current_status))
+ except KeyboardInterrupt:
+ self.error('\n- canceled')
finally:
self._safe_progress_bar_finish(progress_bar)
- if new_mode:
- self.error('%s %s is now in %s mode' % (
- service, service_id, new_mode))
- else:
- raiseCLIError(None, 'Time out')
class _server_wait(_service_wait):
- def _wait(self, server_id, currect_status):
+ def _wait(self, server_id, current_status, timeout=60):
super(_server_wait, self)._wait(
- 'Server', server_id, self.client.wait_server, currect_status)
-
-
-class _network_wait(_service_wait):
-
- def _wait(self, net_id, currect_status):
- super(_network_wait, self)._wait(
- 'Network', net_id, self.client.wait_network, currect_status)
+ 'Server', server_id, self.client.wait_server, current_status,
+ countdown=(current_status not in ('BUILD', )),
+ timeout=timeout if current_status not in ('BUILD', ) else 100)
class _init_cyclades(_command_init):
@command(server_cmds)
class server_list(_init_cyclades, _optional_json, _name_filter, _id_filter):
- """List Virtual Machines accessible by user"""
+ """List virtual servers accessible by user
+ Use filtering arguments (e.g., --name-like) to manage long server lists
+ """
PERMANENTS = ('id', 'name')
- __doc__ += about_authentication
-
arguments = dict(
detail=FlagArgument('show detailed output', ('-l', '--details')),
since=DateArgument(
if withmeta:
servers = self._filter_by_metadata(servers)
- if self['detail'] and not self['json_output']:
+ if self['detail'] and not (
+ self['json_output'] or self['output_format']):
servers = self._add_user_name(servers)
- elif not (self['detail'] or self['json_output']):
+ elif not (self['detail'] or (
+ self['json_output'] or self['output_format'])):
remove_from_items(servers, 'links')
if detail and not self['detail']:
for srv in servers:
@command(server_cmds)
class server_info(_init_cyclades, _optional_json):
- """Detailed information on a Virtual Machine
- Contains:
- - name, id, status, create/update dates
- - network interfaces
- - metadata (e.g. os, superuser) and diagnostics
- - hardware flavor and os image ids
- """
+ """Detailed information on a Virtual Machine"""
+
+ arguments = dict(
+ nics=FlagArgument(
+ 'Show only the network interfaces of this virtual server',
+ '--nics'),
+ network_id=ValueArgument(
+ 'Show the connection details to that network', '--network-id'),
+ stats=FlagArgument('Get URLs for server statistics', '--stats'),
+ diagnostics=FlagArgument('Diagnostic information', '--diagnostics')
+ )
@errors.generic.all
@errors.cyclades.connection
@errors.cyclades.server_id
def _run(self, server_id):
- vm = self.client.get_server_details(server_id)
- uuids = self._uuids2usernames([vm['user_id'], vm['tenant_id']])
- vm['user_id'] += ' (%s)' % uuids[vm['user_id']]
- vm['tenant_id'] += ' (%s)' % uuids[vm['tenant_id']]
- self._print(vm, self.print_dict)
+ if self['nics']:
+ self._print(
+ self.client.get_server_nics(server_id), self.print_dict)
+ elif self['network_id']:
+ self._print(
+ self.client.get_server_network_nics(
+ server_id, self['network_id']), self.print_dict)
+ elif self['stats']:
+ self._print(
+ self.client.get_server_stats(server_id), self.print_dict)
+ elif self['diagnostics']:
+ self._print(self.client.get_server_diagnostics(server_id))
+ else:
+ vm = self.client.get_server_details(server_id)
+ uuids = self._uuids2usernames([vm['user_id'], vm['tenant_id']])
+ vm['user_id'] += ' (%s)' % uuids[vm['user_id']]
+ vm['tenant_id'] += ' (%s)' % uuids[vm['tenant_id']]
+ self._print(vm, self.print_dict)
def main(self, server_id):
super(self.__class__, self)._run()
+ choose_one = ('nics', 'stats', 'diagnostics')
+ count = len([a for a in choose_one if self[a]])
+ if count > 1:
+ raise CLIInvalidArgument('Invalid argument combination', details=[
+ 'Arguments %s cannot be used simultaneously' % ', '.join(
+ [self.arguments[a].lvalue for a in choose_one])])
self._run(server_id=server_id)
class PersonalityArgument(KeyValueArgument):
+
+ terms = (
+ ('local-path', 'contents'),
+ ('server-path', 'path'),
+ ('owner', 'owner'),
+ ('group', 'group'),
+ ('mode', 'mode'))
+
@property
def value(self):
- return self._value if hasattr(self, '_value') else []
+ return getattr(self, '_value', [])
@value.setter
def value(self, newvalue):
if newvalue == self.default:
return self.value
- self._value = []
+ self._value, input_dict = [], {}
for i, terms in enumerate(newvalue):
termlist = terms.split(',')
- if len(termlist) > 5:
- msg = 'Wrong number of terms (should be 1 to 5)'
+ if len(termlist) > len(self.terms):
+ msg = 'Wrong number of terms (1<=terms<=%s)' % len(self.terms)
raiseCLIError(CLISyntaxError(msg), details=howto_personality)
- path = termlist[0]
+
+ 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):
- raiseCLIError(
- None,
+ raise CLIInvalidArgument(
'--personality: File %s does not exist' % path,
- importance=1, details=howto_personality)
+ details=howto_personality)
+
self._value.append(dict(path=path))
- with open(path) as f:
+ with open(expanduser(path)) as f:
self._value[i]['contents'] = b64encode(f.read())
- try:
- self._value[i]['path'] = termlist[1]
- self._value[i]['owner'] = termlist[2]
- self._value[i]['group'] = termlist[3]
- self._value[i]['mode'] = termlist[4]
- except IndexError:
- pass
+ 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])
+
+
+class NetworkArgument(RepeatableArgument):
+ """[id=]NETWORK_ID[,[ip=]IP]"""
+
+ @property
+ def value(self):
+ return getattr(self, '_value', self.default)
+
+ @value.setter
+ def value(self, new_value):
+ for v in new_value or []:
+ part1, sep, part2 = v.partition(',')
+ netid, ip = '', ''
+ if part1.startswith('id='):
+ netid = part1[len('id='):]
+ elif part1.startswith('ip='):
+ ip = part1[len('ip='):]
+ else:
+ netid = part1
+ if part2:
+ if (part2.startswith('id=') and netid) or (
+ part2.startswith('ip=') and ip):
+ raise CLIInvalidArgument(
+ 'Invalid network argument %s' % v, details=[
+ 'Valid format: [id=]NETWORK_ID[,[ip=]IP]'])
+ if part2.startswith('id='):
+ netid = part2[len('id='):]
+ elif part2.startswith('ip='):
+ ip = part2[len('ip='):]
+ elif netid:
+ ip = part2
+ else:
+ netid = part2
+ if not netid:
+ raise CLIInvalidArgument(
+ 'Invalid network argument %s' % v, details=[
+ 'Valid format: [id=]NETWORK_ID[,[ip=]IP]'])
+ self._value = getattr(self, '_value', [])
+ self._value.append(dict(uuid=netid))
+ if ip:
+ self._value[-1]['fixed_ip'] = ip
@command(server_cmds)
class server_create(_init_cyclades, _optional_json, _server_wait):
- """Create a server (aka Virtual Machine)
- Parameters:
- - name: (single quoted text)
- - flavor id: Hardware flavor. Pick one from: /flavor list
- - image id: OS images. Pick one from: /image list
- """
+ """Create a server (aka Virtual Machine)"""
arguments = dict(
+ server_name=ValueArgument('The name of the new server', '--name'),
+ flavor_id=IntArgument('The ID of the flavor', '--flavor-id'),
+ image_id=ValueArgument('The ID of the image', '--image-id'),
personality=PersonalityArgument(
(80 * ' ').join(howto_personality), ('-p', '--personality')),
- wait=FlagArgument('Wait server to build', ('-w', '--wait'))
+ wait=FlagArgument('Wait server to build', ('-w', '--wait')),
+ cluster_size=IntArgument(
+ 'Create a cluster of servers of this size. In this case, the name'
+ 'parameter is the prefix of each server in the cluster (e.g.,'
+ 'srv1, srv2, etc.',
+ '--cluster-size'),
+ max_threads=IntArgument(
+ 'Max threads in cluster mode (default 1)', '--threads'),
+ network_configuration=NetworkArgument(
+ 'Connect server to network: [id=]NETWORK_ID[,[ip=]IP] . '
+ 'Use only NETWORK_ID for private networks. . '
+ 'Use NETWORK_ID,[ip=]IP for networks with IP. . '
+ 'Can be repeated, mutually exclussive with --no-network',
+ '--network'),
+ no_network=FlagArgument(
+ 'Do not create any network NICs on the server. . '
+ 'Mutually exclusive to --network . '
+ 'If neither --network or --no-network are used, the default '
+ 'network policy is applied. These policies are set on the cloud, '
+ 'so kamaki is oblivious to them',
+ '--no-network')
)
+ required = ('server_name', 'flavor_id', 'image_id')
+
+ @errors.cyclades.cluster_size
+ def _create_cluster(self, prefix, flavor_id, image_id, size):
+ networks = self['network_configuration'] or (
+ [] if self['no_network'] else None)
+ servers = [dict(
+ name='%s%s' % (prefix, i if size > 1 else ''),
+ flavor_id=flavor_id,
+ image_id=image_id,
+ personality=self['personality'],
+ networks=networks) for i in range(1, 1 + size)]
+ if size == 1:
+ return [self.client.create_server(**servers[0])]
+ self.client.MAX_THREADS = int(self['max_threads'] or 1)
+ try:
+ r = self.client.async_run(self.client.create_server, servers)
+ return r
+ except Exception as e:
+ if size == 1:
+ raise e
+ try:
+ requested_names = [s['name'] for s in servers]
+ spawned_servers = [dict(
+ name=s['name'],
+ id=s['id']) for s in self.client.list_servers() if (
+ s['name'] in requested_names)]
+ self.error('Failed to build %s servers' % size)
+ self.error('Found %s matching servers:' % len(spawned_servers))
+ self._print(spawned_servers, out=self._err)
+ self.error('Check if any of these servers should be removed\n')
+ except Exception as ne:
+ self.error('Error (%s) while notifying about errors' % ne)
+ finally:
+ raise e
@errors.generic.all
@errors.cyclades.connection
@errors.plankton.id
@errors.cyclades.flavor_id
def _run(self, name, flavor_id, image_id):
- r = self.client.create_server(
- name, int(flavor_id), image_id, personality=self['personality'])
- usernames = self._uuids2usernames([r['user_id'], r['tenant_id']])
- r['user_id'] += ' (%s)' % usernames[r['user_id']]
- r['tenant_id'] += ' (%s)' % usernames[r['tenant_id']]
- self._print(r, self.print_dict)
- if self['wait']:
- self._wait(r['id'], r['status'])
+ for r in self._create_cluster(
+ name, flavor_id, image_id, size=self['cluster_size'] or 1):
+ if not r:
+ self.error('Create %s: server response was %s' % (name, r))
+ continue
+ usernames = self._uuids2usernames(
+ [r['user_id'], r['tenant_id']])
+ r['user_id'] += ' (%s)' % usernames[r['user_id']]
+ r['tenant_id'] += ' (%s)' % usernames[r['tenant_id']]
+ self._print(r, self.print_dict)
+ if self['wait']:
+ self._wait(r['id'], r['status'])
+ self.writeln(' ')
- def main(self, name, flavor_id, image_id):
+ def main(self):
super(self.__class__, self)._run()
- self._run(name=name, flavor_id=flavor_id, image_id=image_id)
+ if self['no_network'] and self['network_configuration']:
+ raise CLIInvalidArgument(
+ 'Invalid argument compination', importance=2, details=[
+ 'Arguments %s and %s are mutually exclusive' % (
+ self.arguments['no_network'].lvalue,
+ self.arguments['network_configuration'].lvalue)])
+ self._run(
+ name=self['server_name'],
+ flavor_id=self['flavor_id'],
+ image_id=self['image_id'])
+
+
+class FirewallProfileArgument(ValueArgument):
+
+ profiles = ('DISABLED', 'ENABLED', 'PROTECTED')
+
+ @property
+ def value(self):
+ return getattr(self, '_value', None)
+
+ @value.setter
+ def value(self, new_profile):
+ if new_profile:
+ new_profile = new_profile.upper()
+ if new_profile in self.profiles:
+ self._value = new_profile
+ else:
+ raise CLIInvalidArgument(
+ 'Invalid firewall profile %s' % new_profile,
+ details=['Valid values: %s' % ', '.join(self.profiles)])
@command(server_cmds)
-class server_rename(_init_cyclades, _optional_output_cmd):
- """Set/update a virtual server name
- virtual server names are not unique, therefore multiple servers may share
- the same name
- """
+class server_modify(_init_cyclades, _optional_output_cmd):
+ """Modify attributes of a virtual server"""
+
+ arguments = dict(
+ server_name=ValueArgument('The new name', '--name'),
+ flavor_id=IntArgument('Set a different flavor', '--flavor-id'),
+ firewall_profile=FirewallProfileArgument(
+ 'Valid values: %s' % (', '.join(FirewallProfileArgument.profiles)),
+ '--firewall'),
+ metadata_to_set=KeyValueArgument(
+ 'Set metadata in key=value form (can be repeated)',
+ '--metadata-set'),
+ metadata_to_delete=RepeatableArgument(
+ 'Delete metadata by key (can be repeated)', '--metadata-del')
+ )
+ required = [
+ 'server_name', 'flavor_id', 'firewall_profile', 'metadata_to_set',
+ 'metadata_to_delete']
@errors.generic.all
@errors.cyclades.connection
@errors.cyclades.server_id
- def _run(self, server_id, new_name):
- self._optional_output(
- self.client.update_server_name(int(server_id), new_name))
+ def _run(self, server_id):
+ if self['server_name']:
+ self.client.update_server_name((server_id), self['server_name'])
+ if self['flavor_id']:
+ self.client.resize_server(server_id, self['flavor_id'])
+ if self['firewall_profile']:
+ self.client.set_firewall_profile(
+ server_id=server_id, profile=self['firewall_profile'])
+ if self['metadata_to_set']:
+ self.client.update_server_metadata(
+ server_id, **self['metadata_to_set'])
+ for key in (self['metadata_to_delete'] or []):
+ errors.cyclades.metadata(
+ self.client.delete_server_metadata)(server_id, key=key)
+ if self['with_output']:
+ self._optional_output(self.client.get_server_details(server_id))
- def main(self, server_id, new_name):
+ def main(self, server_id):
super(self.__class__, self)._run()
- self._run(server_id=server_id, new_name=new_name)
+ self._run(server_id=server_id)
@command(server_cmds)
"""Delete a virtual server"""
arguments = dict(
- wait=FlagArgument('Wait server to be destroyed', ('-w', '--wait'))
+ wait=FlagArgument('Wait server to be destroyed', ('-w', '--wait')),
+ cluster=FlagArgument(
+ '(DANGEROUS) Delete all virtual servers prefixed with the cluster '
+ 'prefix. In that case, the prefix replaces the server id',
+ '--cluster')
)
+ def _server_ids(self, server_var):
+ if self['cluster']:
+ return [s['id'] for s in self.client.list_servers() if (
+ s['name'].startswith(server_var))]
+
+ @errors.cyclades.server_id
+ def _check_server_id(self, server_id):
+ return server_id
+
+ return [_check_server_id(self, server_id=server_var), ]
+
@errors.generic.all
@errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id):
- status = 'DELETED'
+ def _run(self, server_var):
+ for server_id in self._server_ids(server_var):
if self['wait']:
details = self.client.get_server_details(server_id)
status = details['status']
- r = self.client.delete_server(int(server_id))
+ r = self.client.delete_server(server_id)
self._optional_output(r)
if self['wait']:
self._wait(server_id, status)
- def main(self, server_id):
+ def main(self, server_id_or_cluster_prefix):
super(self.__class__, self)._run()
- self._run(server_id=server_id)
+ self._run(server_id_or_cluster_prefix)
@command(server_cmds)
@command(server_cmds)
-class server_console(_init_cyclades, _optional_json):
- """Get a VNC console to access an existing virtual server
- Console connection information provided (at least):
- - host: (url or address) a VNC host
- - port: (int) the gateway to enter virtual server on host
- - password: for VNC authorization
- """
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id):
- self._print(
- self.client.get_server_console(int(server_id)), self.print_dict)
-
- def main(self, server_id):
- super(self.__class__, self)._run()
- self._run(server_id=server_id)
-
-
-@command(server_cmds)
-class server_resize(_init_cyclades, _optional_output_cmd):
- """Set a different flavor for an existing server
- To get server ids and flavor ids:
- /server list
- /flavor list
- """
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.flavor_id
- def _run(self, server_id, flavor_id):
- self._optional_output(self.client.resize_server(server_id, flavor_id))
-
- def main(self, server_id, flavor_id):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, flavor_id=flavor_id)
-
-
-@command(server_cmds)
-class server_firewall(_init_cyclades):
- """Manage virtual server firewall profiles for public networks"""
-
-
-@command(server_cmds)
-class server_firewall_set(_init_cyclades, _optional_output_cmd):
- """Set the firewall profile on virtual server public network
- Values for profile:
- - DISABLED: Shutdown firewall
- - ENABLED: Firewall in normal mode
- - PROTECTED: Firewall in secure mode
- """
+class server_nics(_init_cyclades):
+ """DEPRECATED, use: [kamaki] server info SERVER_ID --nics"""
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.firewall
- def _run(self, server_id, profile):
- self._optional_output(self.client.set_firewall_profile(
- server_id=int(server_id), profile=('%s' % profile).upper()))
-
- def main(self, server_id, profile):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, profile=profile)
+ def main(self, *args):
+ raiseCLIError('DEPRECATED since v0.12', importance=3, details=[
+ 'Replaced by',
+ ' [kamaki] server info <SERVER_ID> --nics'])
@command(server_cmds)
-class server_firewall_get(_init_cyclades):
- """Get the firewall profile for a virtual servers' public network"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id):
- self.writeln(self.client.get_firewall_profile(server_id))
-
- def main(self, server_id):
- super(self.__class__, self)._run()
- self._run(server_id=server_id)
-
-
-@command(server_cmds)
-class server_addr(_init_cyclades, _optional_json):
- """List the addresses of all network interfaces on a virtual server"""
-
- arguments = dict(
- enum=FlagArgument('Enumerate results', '--enumerate')
- )
+class server_console(_init_cyclades, _optional_json):
+ """Create a VMC console and show connection information"""
@errors.generic.all
@errors.cyclades.connection
@errors.cyclades.server_id
def _run(self, server_id):
- reply = self.client.list_server_nics(int(server_id))
- self._print(reply, with_enumeration=self['enum'] and (reply) > 1)
+ self.error('The following credentials will be invalidated shortly')
+ self._print(
+ self.client.get_server_console(server_id), self.print_dict)
def main(self, server_id):
super(self.__class__, self)._run()
@command(server_cmds)
-class server_metadata(_init_cyclades):
- """Manage Server metadata (key:value pairs of server attributes)"""
-
-
-@command(server_cmds)
-class server_metadata_list(_init_cyclades, _optional_json):
- """Get server metadata"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.metadata
- def _run(self, server_id, key=''):
- self._print(
- self.client.get_server_metadata(int(server_id), key),
- self.print_dict)
-
- def main(self, server_id, key=''):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, key=key)
-
-
-@command(server_cmds)
-class server_metadata_set(_init_cyclades, _optional_json):
- """Set / update virtual server metadata
- Metadata should be given in key/value pairs in key=value format
- For example: /server metadata set <server id> key1=value1 key2=value2
- Old, unreferenced metadata will remain intact
- """
+class server_rename(_init_cyclades, _optional_json):
+ """DEPRECATED, use: [kamaki] server modify SERVER_ID --name=NEW_NAME"""
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id, keyvals):
- assert keyvals, 'Please, add some metadata ( key=value)'
- metadata = dict()
- for keyval in keyvals:
- k, sep, v = keyval.partition('=')
- if sep and k:
- metadata[k] = v
- else:
- raiseCLIError(
- 'Invalid piece of metadata %s' % keyval,
- importance=2, details=[
- 'Correct metadata format: key=val',
- 'For example:',
- '/server metadata set <server id>'
- 'key1=value1 key2=value2'])
- self._print(
- self.client.update_server_metadata(int(server_id), **metadata),
- self.print_dict)
-
- def main(self, server_id, *key_equals_val):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, keyvals=key_equals_val)
-
-
-@command(server_cmds)
-class server_metadata_delete(_init_cyclades, _optional_output_cmd):
- """Delete virtual server metadata"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.metadata
- def _run(self, server_id, key):
- self._optional_output(
- self.client.delete_server_metadata(int(server_id), key))
-
- def main(self, server_id, key):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, key=key)
+ def main(self, *args):
+ raiseCLIError('DEPRECATED since v0.12', importance=3, details=[
+ 'Replaced by',
+ ' [kamaki] server modify <SERVER_ID> --name=NEW_NAME'])
@command(server_cmds)
class server_stats(_init_cyclades, _optional_json):
- """Get virtual server statistics"""
+ """DEPRECATED, use: [kamaki] server info SERVER_ID --stats"""
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id):
- self._print(
- self.client.get_server_stats(int(server_id)), self.print_dict)
-
- def main(self, server_id):
- super(self.__class__, self)._run()
- self._run(server_id=server_id)
+ def main(self, *args):
+ raiseCLIError('DEPRECATED since v0.12', importance=3, details=[
+ 'Replaced by',
+ ' [kamaki] server info <SERVER_ID> --stats'])
@command(server_cmds)
class server_wait(_init_cyclades, _server_wait):
- """Wait for server to finish [BUILD, STOPPED, REBOOT, ACTIVE]"""
+ """Wait for server to change its status (default: BUILD)"""
+
+ arguments = dict(
+ timeout=IntArgument(
+ 'Wait limit in seconds (default: 60)', '--timeout', default=60),
+ server_status=StatusArgument(
+ 'Status to wait for (%s, default: %s)' % (
+ ', '.join(server_states), server_states[0]),
+ '--status',
+ valid_states=server_states)
+ )
@errors.generic.all
@errors.cyclades.connection
@errors.cyclades.server_id
- def _run(self, server_id, currect_status):
- self._wait(server_id, currect_status)
+ def _run(self, server_id, current_status):
+ r = self.client.get_server_details(server_id)
+ if r['status'].lower() == current_status.lower():
+ self._wait(server_id, current_status, timeout=self['timeout'])
+ else:
+ self.error(
+ 'Server %s: Cannot wait for status %s, '
+ 'status is already %s' % (
+ server_id, current_status, r['status']))
- def main(self, server_id, currect_status='BUILD'):
+ def main(self, server_id):
super(self.__class__, self)._run()
- self._run(server_id=server_id, currect_status=currect_status)
+ self._run(
+ server_id=server_id, current_status=self['server_status'] or '')
@command(flavor_cmds)
flavors = self._filter_by_id(flavors)
if withcommons:
flavors = self._apply_common_filters(flavors)
- if not (self['detail'] or self['json_output']):
+ if not (self['detail'] or (
+ self['json_output'] or self['output_format'])):
remove_from_items(flavors, 'links')
if detail and not self['detail']:
for flv in flavors:
net['user_id'] += ' (%s)' % usernames[user_id]
if tenant_id:
net['tenant_id'] += ' (%s)' % usernames[tenant_id]
-
-
-@command(network_cmds)
-class network_info(_init_cyclades, _optional_json):
- """Detailed information on a network
- To get a list of available networks and network ids, try /network list
- """
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.network_id
- def _run(self, network_id):
- network = self.client.get_network_details(int(network_id))
- _add_name(self, network)
- self._print(network, self.print_dict, exclude=('id'))
-
- def main(self, network_id):
- super(self.__class__, self)._run()
- self._run(network_id=network_id)
-
-
-@command(network_cmds)
-class network_list(_init_cyclades, _optional_json, _name_filter, _id_filter):
- """List networks"""
-
- PERMANENTS = ('id', 'name')
-
- arguments = dict(
- detail=FlagArgument('show detailed output', ('-l', '--details')),
- limit=IntArgument('limit # of listed networks', ('-n', '--number')),
- more=FlagArgument(
- 'output results in pages (-n to set items per page, default 10)',
- '--more'),
- enum=FlagArgument('Enumerate results', '--enumerate'),
- status=ValueArgument('filter by status', ('--status')),
- public=FlagArgument('only public networks', ('--public')),
- private=FlagArgument('only private networks', ('--private')),
- dhcp=FlagArgument('show networks with dhcp', ('--with-dhcp')),
- no_dhcp=FlagArgument('show networks without dhcp', ('--without-dhcp')),
- user_id=ValueArgument('filter by user id', ('--user-id')),
- user_name=ValueArgument('filter by user name', ('--user-name')),
- gateway=ValueArgument('filter by gateway (IPv4)', ('--gateway')),
- gateway6=ValueArgument('filter by gateway (IPv6)', ('--gateway6')),
- cidr=ValueArgument('filter by cidr (IPv4)', ('--cidr')),
- cidr6=ValueArgument('filter by cidr (IPv6)', ('--cidr6')),
- type=ValueArgument('filter by type', ('--type')),
- )
-
- def _apply_common_filters(self, networks):
- common_filter = dict()
- if self['public']:
- if self['private']:
- return []
- common_filter['public'] = self['public']
- elif self['private']:
- common_filter['public'] = False
- if self['dhcp']:
- if self['no_dhcp']:
- return []
- common_filter['dhcp'] = True
- elif self['no_dhcp']:
- common_filter['dhcp'] = False
- if self['user_id'] or self['user_name']:
- uuid = self['user_id'] or self._username2uuid(self['user_name'])
- common_filter['user_id'] = uuid
- for term in ('status', 'gateway', 'gateway6', 'cidr', 'cidr6', 'type'):
- if self[term]:
- common_filter[term] = self[term]
- return filter_dicts_by_dict(networks, common_filter)
-
- def _add_name(self, networks, key='user_id'):
- uuids = self._uuids2usernames(
- list(set([net[key] for net in networks])))
- for net in networks:
- v = net.get(key, None)
- if v:
- net[key] += ' (%s)' % uuids[v]
- return networks
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self):
- withcommons = False
- for term in (
- 'status', 'public', 'private', 'user_id', 'user_name', 'type',
- 'gateway', 'gateway6', 'cidr', 'cidr6', 'dhcp', 'no_dhcp'):
- if self[term]:
- withcommons = True
- break
- detail = self['detail'] or withcommons
- networks = self.client.list_networks(detail)
- networks = self._filter_by_name(networks)
- networks = self._filter_by_id(networks)
- if withcommons:
- networks = self._apply_common_filters(networks)
- if not (self['detail'] or self['json_output']):
- remove_from_items(networks, 'links')
- if detail and not self['detail']:
- for net in networks:
- for key in set(net).difference(self.PERMANENTS):
- net.pop(key)
- if self['detail'] and not self['json_output']:
- self._add_name(networks)
- self._add_name(networks, 'tenant_id')
- kwargs = dict(with_enumeration=self['enum'])
- if self['more']:
- kwargs['out'] = StringIO()
- kwargs['title'] = ()
- if self['limit']:
- networks = networks[:self['limit']]
- self._print(networks, **kwargs)
- if self['more']:
- pager(kwargs['out'].getvalue())
-
- def main(self):
- super(self.__class__, self)._run()
- self._run()
-
-
-@command(network_cmds)
-class network_create(_init_cyclades, _optional_json, _network_wait):
- """Create an (unconnected) network"""
-
- arguments = dict(
- cidr=ValueArgument('explicitly set cidr', '--with-cidr'),
- gateway=ValueArgument('explicitly set gateway', '--with-gateway'),
- dhcp=FlagArgument('Use dhcp (default: off)', '--with-dhcp'),
- type=ValueArgument(
- 'Valid network types are '
- 'CUSTOM, IP_LESS_ROUTED, MAC_FILTERED (default), PHYSICAL_VLAN',
- '--with-type',
- default='MAC_FILTERED'),
- wait=FlagArgument('Wait network to build', ('-w', '--wait'))
- )
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.network_max
- def _run(self, name):
- r = self.client.create_network(
- name,
- cidr=self['cidr'],
- gateway=self['gateway'],
- dhcp=self['dhcp'],
- type=self['type'])
- _add_name(self, r)
- self._print(r, self.print_dict)
- if self['wait']:
- self._wait(r['id'], 'PENDING')
-
- def main(self, name):
- super(self.__class__, self)._run()
- self._run(name)
-
-
-@command(network_cmds)
-class network_rename(_init_cyclades, _optional_output_cmd):
- """Set the name of a network"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.network_id
- def _run(self, network_id, new_name):
- self._optional_output(
- self.client.update_network_name(int(network_id), new_name))
-
- def main(self, network_id, new_name):
- super(self.__class__, self)._run()
- self._run(network_id=network_id, new_name=new_name)
-
-
-@command(network_cmds)
-class network_delete(_init_cyclades, _optional_output_cmd, _network_wait):
- """Delete a network"""
-
- arguments = dict(
- wait=FlagArgument('Wait network to build', ('-w', '--wait'))
- )
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.network_id
- @errors.cyclades.network_in_use
- def _run(self, network_id):
- status = 'DELETED'
- if self['wait']:
- r = self.client.get_network_details(network_id)
- status = r['status']
- if status in ('DELETED', ):
- return
-
- r = self.client.delete_network(int(network_id))
- self._optional_output(r)
-
- if self['wait']:
- self._wait(network_id, status)
-
- def main(self, network_id):
- super(self.__class__, self)._run()
- self._run(network_id=network_id)
-
-
-@command(network_cmds)
-class network_connect(_init_cyclades, _optional_output_cmd):
- """Connect a server to a network"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.network_id
- def _run(self, server_id, network_id):
- self._optional_output(
- self.client.connect_server(int(server_id), int(network_id)))
-
- def main(self, server_id, network_id):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, network_id=network_id)
-
-
-@command(network_cmds)
-class network_disconnect(_init_cyclades):
- """Disconnect a nic that connects a server to a network
- Nic ids are listed as "attachments" in detailed network information
- To get detailed network information: /network info <network id>
- """
-
- @errors.cyclades.nic_format
- def _server_id_from_nic(self, nic_id):
- return nic_id.split('-')[1]
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- @errors.cyclades.nic_id
- def _run(self, nic_id, server_id):
- num_of_disconnected = self.client.disconnect_server(server_id, nic_id)
- if not num_of_disconnected:
- raise ClientError(
- 'Network Interface %s not found on server %s' % (
- nic_id, server_id),
- status=404)
- print('Disconnected %s connections' % num_of_disconnected)
-
- def main(self, nic_id):
- super(self.__class__, self)._run()
- server_id = self._server_id_from_nic(nic_id=nic_id)
- self._run(nic_id=nic_id, server_id=server_id)
-
-
-@command(network_cmds)
-class network_wait(_init_cyclades, _network_wait):
- """Wait for server to finish [PENDING, ACTIVE, DELETED]"""
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.network_id
- def _run(self, network_id, currect_status):
- self._wait(network_id, currect_status)
-
- def main(self, network_id, currect_status='PENDING'):
- super(self.__class__, self)._run()
- self._run(network_id=network_id, currect_status=currect_status)
-
-
-@command(server_cmds)
-class server_ip(_init_cyclades):
- """Manage floating IPs for the servers"""
-
-
-@command(server_cmds)
-class server_ip_pools(_init_cyclades, _optional_json):
- """List all floating pools of floating ips"""
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self):
- r = self.client.get_floating_ip_pools()
- self._print(r if self['json_output'] else r['floating_ip_pools'])
-
- def main(self):
- super(self.__class__, self)._run()
- self._run()
-
-
-@command(server_cmds)
-class server_ip_list(_init_cyclades, _optional_json):
- """List all floating ips"""
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self):
- r = self.client.get_floating_ips()
- self._print(r if self['json_output'] else r['floating_ips'])
-
- def main(self):
- super(self.__class__, self)._run()
- self._run()
-
-
-@command(server_cmds)
-class server_ip_info(_init_cyclades, _optional_json):
- """A floating IPs' details"""
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self, ip):
- self._print(self.client.get_floating_ip(ip), self.print_dict)
-
- def main(self, ip):
- super(self.__class__, self)._run()
- self._run(ip=ip)
-
-
-@command(server_cmds)
-class server_ip_create(_init_cyclades, _optional_json):
- """Create a new floating IP"""
-
- arguments = dict(pool=ValueArgument('Source IP pool', ('--pool'), None))
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self, ip=None):
- self._print([self.client.alloc_floating_ip(self['pool'], ip)])
-
- def main(self, requested_address=None):
- super(self.__class__, self)._run()
- self._run(ip=requested_address)
-
-
-@command(server_cmds)
-class server_ip_delete(_init_cyclades, _optional_output_cmd):
- """Delete a floating ip"""
-
- @errors.generic.all
- @errors.cyclades.connection
- def _run(self, ip):
- self._optional_output(self.client.delete_floating_ip(ip))
-
- def main(self, ip):
- super(self.__class__, self)._run()
- self._run(ip=ip)
-
-
-@command(server_cmds)
-class server_ip_attach(_init_cyclades, _optional_output_cmd):
- """Attach a floating ip to a server with server_id
- """
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id, ip):
- self._optional_output(self.client.attach_floating_ip(server_id, ip))
-
- def main(self, server_id, ip):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, ip=ip)
-
-
-@command(server_cmds)
-class server_ip_detach(_init_cyclades, _optional_output_cmd):
- """Detach floating IP from server
- """
-
- @errors.generic.all
- @errors.cyclades.connection
- @errors.cyclades.server_id
- def _run(self, server_id, ip):
- self._optional_output(self.client.detach_floating_ip(server_id, ip))
-
- def main(self, server_id, ip):
- super(self.__class__, self)._run()
- self._run(server_id=server_id, ip=ip)