示例#1
0
    def create(cls, name, datacenter, subnet=None, gateway=None,
               background=False):
        """Create a new vlan."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        vlan_params = {
            'name': name,
            'datacenter_id': datacenter_id_,
        }

        if subnet:
            vlan_params['subnet'] = subnet
        if gateway:
            vlan_params['gateway'] = gateway

        result = cls.call('hosting.vlan.create', vlan_params)

        if not background:
            # interactive mode, run a progress bar
            cls.echo('Creating your vlan.')
            cls.display_progress(result)
            cls.echo('Your vlan %s has been created.' % name)

        return result
示例#2
0
文件: iaas.py 项目: Gandi/gandi.cli
    def list(cls, datacenter=None, flavor=None, match='', exact_match=False):
        """ List available kernels for datacenter."""
        if not datacenter:
            dc_ids = [dc['id'] for dc in Datacenter.filtered_list()]
            kmap = {}
            for dc_id in dc_ids:
                vals = cls.safe_call('hosting.disk.list_kernels', dc_id)
                for key in vals:
                    kmap.setdefault(key, []).extend(vals.get(key, []))
            # remove duplicates
            for key in kmap:
                kmap[key] = list(set(kmap[key]))
        else:
            dc_id = Datacenter.usable_id(datacenter)
            kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)

        if match:
            for flav in kmap:
                if exact_match:
                    kmap[flav] = [x for x in kmap[flav] if match == x]
                else:
                    kmap[flav] = [x for x in kmap[flav] if match in x]
        if flavor:
            if flavor not in kmap:
                cls.error('flavor %s not supported here' % flavor)
            return dict([(flavor, kmap[flavor])])

        return kmap
示例#3
0
    def create(cls,
               name,
               datacenter,
               subnet=None,
               gateway=None,
               background=False):
        """Create a new vlan."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        vlan_params = {
            'name': name,
            'datacenter_id': datacenter_id_,
        }

        if subnet:
            vlan_params['subnet'] = subnet
        if gateway:
            vlan_params['gateway'] = gateway

        result = cls.call('hosting.vlan.create', vlan_params)

        if not background:
            # interactive mode, run a progress bar
            cls.echo('Creating your vlan.')
            cls.display_progress(result)
            cls.echo('Your vlan %s has been created.' % name)

        return result
示例#4
0
    def list(cls, datacenter=None, flavor=None, match='', exact_match=False):
        """ List available kernels for datacenter."""
        if not datacenter:
            dc_ids = [dc['id'] for dc in Datacenter.filtered_list()]
            kmap = {}
            for dc_id in dc_ids:
                vals = cls.safe_call('hosting.disk.list_kernels', dc_id)
                for key in vals:
                    kmap.setdefault(key, []).extend(vals.get(key, []))
            # remove duplicates
            for key in kmap:
                kmap[key] = list(set(kmap[key]))
        else:
            dc_id = Datacenter.usable_id(datacenter)
            kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)

        if match:
            for flav in kmap:
                if exact_match:
                    kmap[flav] = [x for x in kmap[flav] if match == x]
                else:
                    kmap[flav] = [x for x in kmap[flav] if match in x]
        if flavor:
            if flavor not in kmap:
                cls.error('flavor %s not supported here' % flavor)
            return dict([(flavor, kmap[flavor])])

        return kmap
示例#5
0
    def list(cls, datacenter=None):
        """List virtual machine vlan

        (in the future it should also handle PaaS vlan)."""
        options = {}
        if datacenter:
            datacenter_id = int(Datacenter.usable_id(datacenter))
            options['datacenter_id'] = datacenter_id

        return cls.call('hosting.vlan.list', options)
示例#6
0
    def list(cls, datacenter=None):
        """List virtual machine vlan

        (in the future it should also handle PaaS vlan)."""
        options = {}
        if datacenter:
            datacenter_id = int(Datacenter.usable_id(datacenter))
            options['datacenter_id'] = datacenter_id

        return cls.call('hosting.vlan.list', options)
示例#7
0
    def list(cls, datacenter=None, label=None):
        """List available images for vm creation."""
        options = {}
        if datacenter:
            datacenter_id = int(Datacenter.usable_id(datacenter))
            options['datacenter_id'] = datacenter_id

        # implement a filter by label as API doesn't handle it
        images = cls.safe_call('hosting.image.list', options)
        if not label:
            return images
        return [img for img in images if label.lower() in img['label'].lower()]
示例#8
0
    def list(cls, datacenter=None, label=None):
        """List available images for vm creation."""
        options = {}
        if datacenter:
            datacenter_id = int(Datacenter.usable_id(datacenter))
            options['datacenter_id'] = datacenter_id

        # implement a filter by label as API doesn't handle it
        images = cls.safe_call('hosting.image.list', options)
        if not label:
            return images
        return [img for img in images
                if label.lower() in img['label'].lower()]
示例#9
0
    def create(cls, name, datacenter, backends, vhosts, algorithm, ssl_enable,
               zone_alter):
        """ Create a webaccelerator """
        datacenter_id_ = int(Datacenter.usable_id(datacenter))
        params = {
            'datacenter_id': datacenter_id_,
            'name': name,
            'lb': {
                'algorithm': algorithm
            },
            'override': True,
            'ssl_enable': ssl_enable,
            'zone_alter': zone_alter
        }
        if vhosts:
            params['vhosts'] = vhosts
        if backends:
            params['servers'] = backends
        try:
            result = cls.call('hosting.rproxy.create', params)
            cls.echo('Creating your webaccelerator %s' % params['name'])
            cls.display_progress(result)
            cls.echo('Your webaccelerator have been created')
            return result
        except Exception as err:
            if err.code == 580142:
                for vhost in params['vhosts']:
                    dns_entry = cls.call(
                        'hosting.rproxy.vhost.get_dns_entries', {
                            'datacenter': datacenter_id_,
                            'vhost': vhost
                        })
                    txt_record = "@ 3600 IN TXT \"%s=%s\"" % (dns_entry['key'],
                                                              dns_entry['txt'])

                    cname_record = "%s 3600 IN CNAME %s" % (dns_entry['key'],
                                                            dns_entry['cname'])

                    cls.echo('The domain %s don\'t use Gandi DNS or you have'
                             ' not sufficient right to alter the zone file. '
                             'Edit your zone file adding this TXT and CNAME '
                             'record and try again :' % vhost)
                    cls.echo(txt_record)
                    cls.echo(cname_record)
                    cls.echo('\nOr add a file containing %s at :\n'
                             'http://%s/%s.txt\n' %
                             (dns_entry['txt'], dns_entry['domain'],
                              dns_entry['txt']))
                    cls.separator_line('-', 4)
            else:
                cls.echo(err)
示例#10
0
    def list(cls, datacenter, flavor=None, match=''):
        """ List available kernels for datacenter."""
        dc_id = Datacenter.usable_id(datacenter)
        kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)

        if match:
            for flav in kmap:
                kmap[flav] = [x for x in kmap[flav] if match in x]

        if flavor:
            if flavor not in kmap:
                cls.error('flavor %s not supported here' % flavor)
            return kmap[flavor]

        return kmap
示例#11
0
    def list(cls, datacenter, flavor=None, match=''):
        """ List available kernels for datacenter."""
        dc_id = Datacenter.usable_id(datacenter)
        kmap = cls.safe_call('hosting.disk.list_kernels', dc_id)

        if match:
            for flav in kmap:
                kmap[flav] = [x for x in kmap[flav] if match in x]

        if flavor:
            if flavor not in kmap:
                cls.error('flavor %s not supported here' % flavor)
            return dict([(flavor, kmap[flavor])])

        return kmap
示例#12
0
文件: webacc.py 项目: Gandi/gandi.cli
    def create(cls, name, datacenter, backends, vhosts, algorithm,
               ssl_enable, zone_alter):
        """ Create a webaccelerator """
        datacenter_id_ = int(Datacenter.usable_id(datacenter))
        params = {
            'datacenter_id': datacenter_id_,
            'name': name,
            'lb': {'algorithm': algorithm},
            'override': True,
            'ssl_enable': ssl_enable,
            'zone_alter': zone_alter
        }
        if vhosts:
            params['vhosts'] = vhosts
        if backends:
            params['servers'] = backends
        try:
            result = cls.call('hosting.rproxy.create', params)
            cls.echo('Creating your webaccelerator %s' % params['name'])
            cls.display_progress(result)
            cls.echo('Your webaccelerator have been created')
            return result
        except Exception as err:
            if err.code == 580142:
                for vhost in params['vhosts']:
                    dns_entry = cls.call(
                        'hosting.rproxy.vhost.get_dns_entries',
                        {'datacenter': datacenter_id_, 'vhost': vhost})
                    txt_record = "@ 3600 IN TXT \"%s=%s\"" % (dns_entry['key'],
                                                              dns_entry['txt'])

                    cname_record = "%s 3600 IN CNAME %s" % (dns_entry['key'],
                                                            dns_entry['cname'])

                    cls.echo('The domain %s don\'t use Gandi DNS or you have'
                             ' not sufficient right to alter the zone file. '
                             'Edit your zone file adding this TXT and CNAME '
                             'record and try again :' % vhost)
                    cls.echo(txt_record)
                    cls.echo(cname_record)
                    cls.echo('\nOr add a file containing %s at :\n'
                             'http://%s/%s.txt\n' % (dns_entry['txt'],
                                                     dns_entry['domain'],
                                                     dns_entry['txt']))
                    cls.separator_line('-', 4)
            else:
                cls.echo(err)
示例#13
0
文件: network.py 项目: ziir/gandi.cli
    def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip,
               background):
        """ Create a new iface """
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        iface_params = {
            'ip_version': ip_version,
            'datacenter_id': datacenter_id_,
            'bandwidth': bandwidth,
        }
        if vlan:
            iface_params['vlan'] = Vlan.usable_id(vlan)
            if ip:
                iface_params['ip'] = ip

        result = cls.call('hosting.iface.create', iface_params)

        if background and not vm:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your iface.')
        cls.display_progress(result)
        iface_info = cls._info(result['iface_id'])
        cls.echo('Your iface has been created with the following IP '
                 'addresses:')
        for _ip in iface_info['ips']:
            cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip']))

        if not vm:
            return result

        vm_id = Iaas.usable_id(vm)
        result = cls._attach(result['iface_id'], vm_id)

        if background:
            return result

        cls.echo('Attaching your iface.')
        cls.display_progress(result)
        return result
示例#14
0
    def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip,
               background):
        """ Create a new iface """
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        iface_params = {
            'ip_version': ip_version,
            'datacenter_id': datacenter_id_,
            'bandwidth': bandwidth,
        }
        if vlan:
            iface_params['vlan'] = Vlan.usable_id(vlan)
            if ip:
                iface_params['ip'] = ip

        result = cls.call('hosting.iface.create', iface_params)

        if background and not vm:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your iface.')
        cls.display_progress(result)
        iface_info = cls._info(result['iface_id'])
        cls.echo('Your iface has been created with the following IP '
                 'addresses:')
        for _ip in iface_info['ips']:
            cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip']))

        if not vm:
            return result

        vm_id = Iaas.usable_id(vm)
        result = cls._attach(result['iface_id'], vm_id)

        if background:
            return result

        cls.echo('Attaching your iface.')
        cls.display_progress(result)
        return result
示例#15
0
文件: paas.py 项目: ziir/gandi.cli
    def create(cls, name, size, type, quantity, duration, datacenter, vhosts,
               password, snapshot_profile, background, sshkey):
        """Create a new PaaS instance."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        paas_params = {
            'name': name,
            'size': size,
            'type': type,
            'duration': duration,
            'datacenter_id': datacenter_id_,
        }

        if password:
            paas_params['password'] = password

        if quantity:
            paas_params['quantity'] = quantity

        paas_params.update(cls.convert_sshkey(sshkey))

        if snapshot_profile:
            paas_params['snapshot_profile'] = snapshot_profile

        result = cls.call('paas.create', paas_params)

        if not background:
            # interactive mode, run a progress bar
            cls.echo('Creating your PaaS instance.')
            cls.display_progress(result)
            cls.echo('Your PaaS instance %s has been created.' % name)


        if vhosts:
            paas_info = cls.info(name)
            Vhost.create(paas_info, vhosts, True, background)

        return result
示例#16
0
    def create(cls, name, size, type, quantity, duration, datacenter, vhosts,
               password, snapshot_profile, background, sshkey):
        """Create a new PaaS instance."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        paas_params = {
            'name': name,
            'size': size,
            'type': type,
            'duration': duration,
            'datacenter_id': datacenter_id_,
        }

        if password:
            paas_params['password'] = password

        if quantity:
            paas_params['quantity'] = quantity

        paas_params.update(cls.convert_sshkey(sshkey))

        if snapshot_profile:
            paas_params['snapshot_profile'] = snapshot_profile

        result = cls.call('paas.create', paas_params)

        if not background:
            # interactive mode, run a progress bar
            cls.echo('Creating your PaaS instance.')
            cls.display_progress(result)
            cls.echo('Your PaaS instance %s has been created.' % name)

        if vhosts:
            paas_info = cls.info(name)
            Vhost.create(paas_info, vhosts, True, background)

        return result
示例#17
0
文件: iaas.py 项目: JD-Labs/gandi.cli
    def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey):
        """Create a new virtual machine."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring()
            disk_name = 'sys_%s' % hostname[4:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
            'ip_version': ip_version,
            'bandwidth': bandwidth,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        if ip_version == 4:
            ip_summary = 'ip v4+v6'
        else:
            ip_summary = 'ip v6'
        cls.echo('* Configuration used: %d cores, %dMb memory, %s, '
                 'image %s, hostname: %s' % (cores, memory, ip_summary, image,
                                             hostname))
        if background:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine.')
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vm_id:
            time.sleep(5)
            cls.ssh(oper['vm_id'], login='******', identity=None, wipe_key=True)
示例#18
0
    def create(cls, datacenter, memory, cores, ip_version, bandwidth, login,
               password, hostname, image, run, background, sshkey, size, vlan,
               ip, script, script_args, ssh):
        """Create a new virtual machine."""
        from gandi.cli.modules.network import Ip, Iface
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring('vm')
            disk_name = 'sys_%s' % hostname[2:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        if ip_version:
            vm_params['ip_version'] = ip_version
            vm_params['bandwidth'] = bandwidth

        if script:
            with open(script) as fd:
                vm_params['script'] = fd.read()
            if script_args:
                vm_params['script_args'] = script_args

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {
            'datacenter_id': vm_params['datacenter_id'],
            'name': disk_name[:15]
        }

        if size:
            if isinstance(size, tuple):
                prefix, size = size
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        ip_summary = []
        if ip_version == 4:
            ip_summary = ['v4', 'v6']
        elif ip_version == 6:
            ip_summary = ['v6']

        if vlan:
            ip_ = None
            ip_summary.append('private')
            if ip:
                try:
                    ip_ = Ip.info(ip)
                except Exception:
                    pass
                else:
                    if not Ip._check_and_detach(ip_, None):
                        return
            if ip_:
                iface_id = ip_['iface_id']
            else:
                ip_create = Ip.create(4, vm_params['datacenter_id'], bandwidth,
                                      None, vlan, ip)

                iface_id = ip_create['iface_id']

            # if there is a public ip, will attach this one later, else give
            # the iface to vm.create
            if not ip_version:
                vm_params['iface_id'] = iface_id

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        cls.echo(
            '* Configuration used: %d cores, %dMb memory, ip %s, '
            'image %s, hostname: %s, datacenter: %s' %
            (cores, memory, '+'.join(ip_summary), image, hostname, datacenter))

        # background mode, bail out now (skip interactive part)
        if background and (not vlan or not ip_version):
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vlan and ip_version:
            attach = Iface._attach(iface_id, vm_id)
            if background:
                return attach

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        if vm_id and ip_version:
            cls.wait_for_sshd(vm_id)
            if ssh:
                cls.ssh_keyscan(vm_id)
                cls.ssh(vm_id, 'root', None)
示例#19
0
文件: iaas.py 项目: ziir/gandi.cli
    def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size, vlan, ip, script, script_args, ssh):
        """Create a new virtual machine."""
        from gandi.cli.modules.network import Ip, Iface
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring('vm')
            disk_name = 'sys_%s' % hostname[2:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        if ip_version:
            vm_params['ip_version'] = ip_version
            vm_params['bandwidth'] = bandwidth

        if script:
            with open(script) as fd:
                vm_params['script'] = fd.read()
            if script_args:
                vm_params['script_args'] = script_args

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            if isinstance(size, tuple):
                prefix, size = size
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        ip_summary = []
        if ip_version == 4:
            ip_summary = ['v4', 'v6']
        elif ip_version == 6:
            ip_summary = ['v6']

        if vlan:
            ip_ = None
            ip_summary.append('private')
            if ip:
                try:
                    ip_ = Ip.info(ip)
                except Exception:
                    pass
                else:
                    if not Ip.check_and_detach(ip_, None, force=False):
                        return
            if ip_:
                iface_id = ip_['iface_id']
            else:
                ip_create = Ip.create(4,
                                      vm_params['datacenter_id'],
                                      bandwidth,
                                      None,
                                      vlan,
                                      ip)

                iface_id = ip_create['iface_id']

            # if there is a public ip, will attach this one later, else give
            # the iface to vm.create
            if not ip_version:
                vm_params['iface_id'] = iface_id

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        cls.echo('* Configuration used: %d cores, %dMb memory, ip %s, '
                 'image %s, hostname: %s, datacenter: %s' %
                 (cores, memory, '+'.join(ip_summary), image, hostname,
                  datacenter))

        # background mode, bail out now (skip interactive part)
        if background and (not vlan or not ip_version):
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vlan and ip_version:
            attach = Iface._attach(iface_id, vm_id)
            if background:
                return attach

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        if vm_id and ip_version:
            cls.wait_for_sshd(vm_id)
            if ssh:
                cls.ssh_keyscan(vm_id)
                cls.ssh(vm_id, 'root', None)
示例#20
0
    def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size):
        """Create a new virtual machine."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring()
            disk_name = 'sys_%s' % hostname[4:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
            'ip_version': ip_version,
            'bandwidth': bandwidth,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        if ip_version == 4:
            ip_summary = 'ip v4+v6'
        else:
            ip_summary = 'ip v6'
        cls.echo('* Configuration used: %d cores, %dMb memory, %s, '
                 'image %s, hostname: %s' % (cores, memory, ip_summary, image,
                                             hostname))
        if background:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vm_id:
            time.sleep(5)
            cls.ssh(oper['vm_id'], login='******', identity=None, wipe_key=True)
示例#21
0
    def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size, script):
        """Create a new virtual machine."""
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring()
            disk_name = 'sys_%s' % hostname[4:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
            'ip_version': ip_version,
            'bandwidth': bandwidth,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        ip_summary = 'ip v4+v6'
        if ip_version == 6:
            ip_summary = 'ip v6'
        cls.echo('* Configuration used: %d cores, %dMb memory, %s, '
                 'image %s, hostname: %s' % (cores, memory, ip_summary, image,
                                             hostname))

        # background mode, bail out now (skip interactive part)
        if background:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vm_id:
            cls.wait_for_sshd(vm_id)
            cls.ssh_keyscan(vm_id)
            if script:
                ret = cls.scp(vm_id, 'root', None, script, '/var/tmp/gscript')
                if not ret:
                    cls.error('Failed to scp script %s to VM %s (id: %s)' %
                              (script, hostname, vm_id))

            ret = cls.ssh(vm_id, 'root', None, script and ['/var/tmp/gscript'])
            if not ret and (script and ['/var/tmp/gscript']):
                cls.error('Failed to execute script %s on VM %s (id: %s)' %
                          ('/var/tmp/gscript', hostname, vm_id))