def configure(vca_client, **kwargs):
    ctx.logger.info("Configure server")
    server = {'name': ctx.instance.id}
    server.update(ctx.node.properties.get('server', {}))
    vapp_name = server['name']
    config = get_vcloud_config()
    custom = server.get(GUEST_CUSTOMIZATION, {})
    public_keys = _get_connected_keypairs()
    if custom or public_keys:
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        script = _build_script(custom, public_keys)
        password = custom.get('admin_password')
        computer_name = custom.get('computer_name')

        task = vapp.customize_guest_os(
            vapp_name,
            customization_script=script,
            computer_name=computer_name,
            admin_password=password
        )
        if task is None:
            raise cfy_exc.NonRecoverableError(
                "Could not set guest customization parameters. {0}".
                format(error_response(vapp)))
        wait_for_task(vca_client, task)
        if vapp.customize_on_next_poweron():
            ctx.logger.info("Customizations successful")
        else:
            raise cfy_exc.NonRecoverableError(
                "Can't run customization in next power on. {0}".
                format(error_response(vapp)))

    hardware = server.get('hardware')
    if hardware:
        cpu = hardware.get('cpu')
        memory = hardware.get('memory')
        _check_hardware(cpu, memory)
        vapp = vca_client.get_vapp(
            vca_client.get_vdc(config['vdc']), vapp_name
        )
        if memory:
            try:
                task = vapp.modify_vm_memory(vapp_name, memory)
                wait_for_task(vca_client, task)
                ctx.logger.info("Customize VM memory: '{0}'.".format(memory))
            except Exception:
                raise cfy_exc.NonRecoverableError(
                    "Customize VM memory failed: '{0}'. {1}".
                    format(task, error_response(vapp)))
        if cpu:
            try:
                task = vapp.modify_vm_cpu(vapp_name, cpu)
                wait_for_task(vca_client, task)
                ctx.logger.info("Customize VM cpu: '{0}'.".format(cpu))
            except Exception:
                raise cfy_exc.NonRecoverableError(
                    "Customize VM cpu failed: '{0}'. {1}".
                    format(task, error_response(vapp)))
Beispiel #2
0
def configure(vca_client, **kwargs):
    ctx.logger.info("Configure server")
    server = {'name': ctx.instance.id}
    server.update(ctx.node.properties.get('server', {}))
    vapp_name = server['name']
    config = get_vcloud_config()
    custom = server.get(GUEST_CUSTOMIZATION, {})
    public_keys = _get_connected_keypairs()
    if custom or public_keys:
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        script = _build_script(custom, public_keys)
        password = custom.get('admin_password')
        computer_name = custom.get('computer_name')
        ctx.logger.info("Customize guest OS")
        task = vapp.customize_guest_os(vapp_name,
                                       customization_script=script,
                                       computer_name=computer_name,
                                       admin_password=password)
        if task is None:
            raise cfy_exc.NonRecoverableError(
                "Could not set guest customization parameters. {0}".format(
                    error_response(vapp)))
        wait_for_task(vca_client, task)
        if vapp.customize_on_next_poweron():
            ctx.logger.info("Customizations successful")
        else:
            raise cfy_exc.NonRecoverableError(
                "Can't run customization in next power on. {0}".format(
                    error_response(vapp)))

    hardware = server.get('hardware')
    if hardware:
        cpu = hardware.get('cpu')
        memory = hardware.get('memory')
        _check_hardware(cpu, memory)
        vapp = vca_client.get_vapp(vca_client.get_vdc(config['vdc']),
                                   vapp_name)
        if memory:
            try:
                ctx.logger.info("Customize VM memory: '{0}'.".format(memory))
                task = vapp.modify_vm_memory(vapp_name, memory)
                wait_for_task(vca_client, task)
            except Exception:
                raise cfy_exc.NonRecoverableError(
                    "Customize VM memory failed: '{0}'. {1}".format(
                        task, error_response(vapp)))
        if cpu:
            try:
                ctx.logger.info("Customize VM cpu: '{0}'.".format(cpu))
                task = vapp.modify_vm_cpu(vapp_name, cpu)
                wait_for_task(vca_client, task)
            except Exception:
                raise cfy_exc.NonRecoverableError(
                    "Customize VM cpu failed: '{0}'. {1}".format(
                        task, error_response(vapp)))
Beispiel #3
0
def create(vca_client, **kwargs):
    """create vdc"""
    config = get_vcloud_config()
    # Subscription service does not support vdc create,
    # you must use predefined vdc only
    if is_subscription(config['service_type']):
        raise cfy_exc.NonRecoverableError(
            "Unable create VDC on subscription service.")
    if ctx.node.properties.get(USE_EXTERNAL_RESOURCE):
        # use external resource, does not create anything
        res_id = ctx.node.properties[RESOURCE_ID]
        ctx.instance.runtime_properties[VDC_NAME] = res_id
        vdc = vca_client.get_vdc(res_id)
        if not vdc:
            raise cfy_exc.NonRecoverableError(
                "Unable to find external VDC {0}.".format(res_id))
        ctx.logger.info("External resource {0} has been used".format(res_id))
    else:
        # create new vdc
        vdc_name = ctx.node.properties.get('name')
        if not vdc_name:
            raise cfy_exc.NonRecoverableError("'vdc_name' not specified.")
        task = vca_client.create_vdc(vdc_name)
        if not task:
            raise cfy_exc.NonRecoverableError(
                "Could not create VDC: {0}".format(error_response(vca_client)))
        wait_for_task(vca_client, task)
Beispiel #4
0
def create(vca_client, **kwargs):
    """create vdc"""
    config = get_vcloud_config()
    # Subscription service does not support vdc create,
    # you must use predefined vdc only
    if is_subscription(config['service_type']):
            raise cfy_exc.NonRecoverableError(
                "Unable create VDC on subscription service.")
    if ctx.node.properties.get(USE_EXTERNAL_RESOURCE):
        # use external resource, does not create anything
        res_id = ctx.node.properties[RESOURCE_ID]
        ctx.instance.runtime_properties[VDC_NAME] = res_id
        vdc = vca_client.get_vdc(res_id)
        if not vdc:
            raise cfy_exc.NonRecoverableError(
                "Unable to find external VDC {0}."
                .format(res_id))
        ctx.logger.info(
            "External resource {0} has been used".format(res_id))
    else:
        # create new vdc
        vdc_name = ctx.node.properties.get('name')
        if not vdc_name:
            raise cfy_exc.NonRecoverableError("'vdc_name' not specified.")
        task = vca_client.create_vdc(vdc_name)
        if not task:
            raise cfy_exc.NonRecoverableError("Could not create VDC: {0}"
                                              .format(error_response(vca_client)))
        wait_for_task(vca_client, task)
Beispiel #5
0
def start(vca_client, **kwargs):
    """
    power on server and wait network connection availability for host
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not starting server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        if _vapp_is_on(vapp) is False:
            ctx.logger.info("Power-on VApp {0}".format(vapp_name))
            task = vapp.poweron()
            if not task:
                raise cfy_exc.NonRecoverableError(
                    "Could not power-on vApp. {0}".format(
                        error_response(vapp)))
            wait_for_task(vca_client, task)

    if not _get_state(vca_client):
        return ctx.operation.retry(
            message="Waiting for VM's configuration to complete",
            retry_after=5)
def start(vca_client, **kwargs):
    """
    power on server and wait network connection availability for host
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not starting server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        if _vapp_is_on(vapp) is False:
            ctx.logger.info("Power-on VApp {0}".format(vapp_name))
            task = vapp.poweron()
            if not task:
                raise cfy_exc.NonRecoverableError(
                    "Could not power-on vApp. {0}".
                                                  format(error_response(vapp)))
            wait_for_task(vca_client, task)

    if not _get_state(vca_client):
        return ctx.operation.retry(
            message="Waiting for VM's configuration to complete",
            retry_after=5)
Beispiel #7
0
def _power_on_vm(vca_client, vapp, vapp_name):
    """Poweron VM"""
    if _vapp_is_on(vapp) is False:
        ctx.logger.info("Power-on VApp {0}".format(vapp_name))
        task = vapp.poweron()
        if not task:
            raise cfy_exc.NonRecoverableError(
                "Could not power-on vApp. {0}".
                format(error_response(vapp)))
        wait_for_task(vca_client, task)
Beispiel #8
0
def _volume_operation(vca_client, operation):
    """
        attach/detach volume
    """
    vdc_name = get_vcloud_config()['vdc']
    vdc = vca_client.get_vdc(vdc_name)
    vmName = get_vapp_name(ctx.target.instance.runtime_properties)
    if ctx.source.node.properties.get('use_external_resource'):
        volumeName = ctx.source.node.properties['resource_id']
    else:
        volumeName = ctx.source.node.properties['volume']['name']
    vapp = vca_client.get_vapp(vdc, vmName)
    for ref in vca_client.get_diskRefs(vdc):
        if ref.name == volumeName:
            if operation == 'ATTACH':
                ctx.logger.info("Attach volume node '{0}'.".format(volumeName))
                task = vapp.attach_disk_to_vm(vmName, ref)
                if task:
                    wait_for_task(vca_client, task)
                    ctx.logger.info(
                        "Volume node '{0}' has been attached".format(
                            volumeName))
                else:
                    raise cfy_exc.NonRecoverableError(
                        "Can't attach disk: '{0}' with error: {1}".format(
                            volumeName, error_response(vapp)))

            elif operation == 'DETACH':
                ctx.logger.info("Detach volume node '{0}'.".format(volumeName))
                task = vapp.detach_disk_from_vm(vmName, ref)
                if task:
                    wait_for_task(vca_client, task)
                    ctx.logger.info(
                        "Volume node '{0}' has been detached.".format(
                            volumeName))
                else:
                    raise cfy_exc.NonRecoverableError(
                        "Can't detach disk: '{0}'. With error: {1}".format(
                            volumeName, error_response(vapp)))
            else:
                raise cfy_exc.NonRecoverableError(
                    "Unknown operation '{0}'".format(operation))
def _volume_operation(vca_client, operation):
    """
        attach/detach volume
    """
    vdc_name = get_vcloud_config()['vdc']
    vdc = vca_client.get_vdc(vdc_name)
    vmName = get_vapp_name(ctx.target.instance.runtime_properties)
    if ctx.source.node.properties.get('use_external_resource'):
        volumeName = ctx.source.node.properties['resource_id']
    else:
        volumeName = ctx.source.node.properties['volume']['name']
    vapp = vca_client.get_vapp(vdc, vmName)
    for ref in vca_client.get_diskRefs(vdc):
        if ref.name == volumeName:
            if operation == 'ATTACH':
                ctx.logger.info("Attach volume node '{0}'.".format(volumeName))
                task = vapp.attach_disk_to_vm(vmName, ref)
                if task:
                    wait_for_task(vca_client, task)
                    ctx.logger.info(
                        "Volume node '{0}' has been attached".format(volumeName))
                else:
                    raise cfy_exc.NonRecoverableError(
                        "Can't attach disk: '{0}' with error: {1}".
                        format(volumeName, error_response(vapp)))

            elif operation == 'DETACH':
                ctx.logger.info("Detach volume node '{0}'.".format(volumeName))
                task = vapp.detach_disk_from_vm(vmName, ref)
                if task:
                    wait_for_task(vca_client, task)
                    ctx.logger.info(
                        "Volume node '{0}' has been detached.".
                        format(volumeName))
                else:
                    raise cfy_exc.NonRecoverableError(
                        "Can't detach disk: '{0}'. With error: {1}".
                        format(volumeName, error_response(vapp)))
            else:
                raise cfy_exc.NonRecoverableError(
                    "Unknown operation '{0}'".format(operation))
def del_ondemand_public_ip(vca_client, gateway, ip, ctx):
    """
        try to deallocate public ip
    """
    ctx.logger.info("Try to deallocate public IP {0}".format(ip))
    task = gateway.deallocate_public_ip(ip)
    if task:
        wait_for_task(vca_client, task)
        ctx.logger.info("Public IP {0} was deallocated".format(ip))
    else:
        raise cfy_exc.NonRecoverableError(
            "Can't deallocate public ip {0}. {1} for ondemand service".
            format(ip, error_response(gateway)))
Beispiel #11
0
def delete(vca_client, **kwargs):
    """delete vdc"""
    # external resource - no actions
    if ctx.node.properties.get(USE_EXTERNAL_RESOURCE):
        ctx.logger.info('Not deleting VDC since an external VDC is '
                        'being used')
    else:
        # created in our workflow
        vdc_name = ctx.node.properties.get('name')
        status, task = vca_client.delete_vdc(vdc_name)
        if not status:
            raise cfy_exc.NonRecoverableError(
                "Could not delete VDC: {0}".format(error_response(vca_client)))
        wait_for_task(vca_client, task)
    # clean up runtime_properties
    if VDC_NAME in ctx.instance.runtime_properties:
        del ctx.instance.runtime_properties[VDC_NAME]
Beispiel #12
0
def delete(vca_client, **kwargs):
    """delete vdc"""
    # external resource - no actions
    if ctx.node.properties.get(USE_EXTERNAL_RESOURCE):
        ctx.logger.info('Not deleting VDC since an external VDC is '
                        'being used')
    else:
        # created in our workflow
        vdc_name = ctx.node.properties.get('name')
        status, task = vca_client.delete_vdc(vdc_name)
        if not status:
            raise cfy_exc.NonRecoverableError("Could not delete VDC: {0}"
                                              .format(error_response(vca_client)))
        wait_for_task(vca_client, task)
    # clean up runtime_properties
    if VDC_NAME in ctx.instance.runtime_properties:
        del ctx.instance.runtime_properties[VDC_NAME]
def stop(vca_client, **kwargs):
    """
        poweroff server, if external resource - server stay poweroned
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not stopping server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        ctx.logger.info("Power-off and undeploy VApp {0}".format(vapp_name))
        task = vapp.undeploy()
        if not task:
            raise cfy_exc.NonRecoverableError("Could not undeploy vApp {0}".
                                              format(error_response(vapp)))
        wait_for_task(vca_client, task)
Beispiel #14
0
def stop(vca_client, **kwargs):
    """
        poweroff server, if external resource - server stay poweroned
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not stopping server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        ctx.logger.info("Power-off and undeploy VApp {0}".format(vapp_name))
        task = vapp.undeploy()
        if not task:
            raise cfy_exc.NonRecoverableError(
                "Could not undeploy vApp {0}".format(error_response(vapp)))
        wait_for_task(vca_client, task)
def delete(vca_client, **kwargs):
    """
        delete server
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not deleting server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        ctx.logger.info("Deleting VApp {0}".format(vapp_name))
        task = vapp.delete()
        if not task:
            raise cfy_exc.NonRecoverableError("Could not delete vApp {0}".
                                              format(error_response(vapp)))
        wait_for_task(vca_client, task)

    del ctx.instance.runtime_properties[VCLOUD_VAPP_NAME]
Beispiel #16
0
def delete(vca_client, **kwargs):
    """
        delete server
    """
    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('not deleting server since an external server is '
                        'being used')
    else:
        vapp_name = get_vapp_name(ctx.instance.runtime_properties)
        config = get_vcloud_config()
        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        ctx.logger.info("Deleting VApp {0}".format(vapp_name))
        task = vapp.delete()
        if not task:
            raise cfy_exc.NonRecoverableError(
                "Could not delete vApp {0}".format(error_response(vapp)))
        wait_for_task(vca_client, task)

    del ctx.instance.runtime_properties[VCLOUD_VAPP_NAME]
def get_ondemand_public_ip(vca_client, gateway, ctx):
    """
        try to allocate new public ip for ondemand service
    """
    old_public_ips = set(gateway.get_public_ips())
    ctx.logger.info("Try to allocate public IP")
    task = gateway.allocate_public_ip()
    if task:
        wait_for_task(vca_client, task)
    else:
        raise cfy_exc.NonRecoverableError(
            "Can't get public ip for ondemand service {0}".format(error_response(gateway)))
    # update gateway for new IP address
    gateway = vca_client.get_gateways(get_vcloud_config()['vdc'])[0]
    new_public_ips = set(gateway.get_public_ips())
    new_ip = new_public_ips - old_public_ips
    if new_ip:
        ctx.logger.info("Public IP {0} was asigned.".format(new_ip))
    else:
        raise cfy_exc.NonRecoverableError(
            "Can't get new public IP address")
    return list(new_ip)[0]
def get_ondemand_public_ip(vca_client, gateway, ctx):
    """
        try to allocate new public ip for ondemand service
    """
    old_public_ips = set(gateway.get_public_ips())
    allocated_ips = set([address.external
                         for address in collectAssignedIps(gateway)])
    available_ips = old_public_ips - allocated_ips
    if available_ips:
        new_ip = list(available_ips)[0]
        ctx.logger.info("Public IP {0} was reused.".format(new_ip))
        return new_ip
    for i in xrange(RETRY_COUNT):
        ctx.logger.info("Try to allocate public IP")
        wait_for_gateway(vca_client, gateway.get_name(), ctx)
        task = gateway.allocate_public_ip()
        if task:
            try:
                wait_for_task(vca_client, task)
                break
            except cfy_exc.NonRecoverableError:
                continue
        else:
            raise cfy_exc.NonRecoverableError(
                "Can't get public ip for ondemand service {0}".
                format(error_response(gateway)))
    # update gateway for new IP address
    gateway = vca_client.get_gateways(get_vcloud_config()['vdc'])[0]
    new_public_ips = set(gateway.get_public_ips())
    new_ip = new_public_ips - old_public_ips
    if new_ip:
        ctx.logger.info("Public IP {0} was asigned.".format(new_ip))
    else:
        raise cfy_exc.NonRecoverableError(
            "Can't get new public IP address")
    return list(new_ip)[0]
Beispiel #19
0
def remove_keys(vca_client, **kwargs):
    ctx.logger.info("Remove public keys from VM.")
    relationships = getattr(ctx.target.instance, 'relationships', None)
    if relationships:
        public_keys = [
            relationship.target.instance.runtime_properties['public_key']
            for relationship in relationships
            if 'public_key' in
            relationship.target.instance.runtime_properties
        ]
    else:
        return
    vdc = vca_client.get_vdc(get_vcloud_config()['vdc'])
    vapp_name = ctx.target.instance.id
    vapp = vca_client.get_vapp(vdc, vapp_name)
    if not vapp:
        vapp_name = ctx.target.node.properties['server'].get('name', '')
        vapp = vca_client.get_vapp(vdc, vapp_name)
        if not vapp:
            raise cfy_exc.NonRecoverableError(
                "Unable to find vAPP server "
                "by its name {0}.".format(vapp_name))
    ctx.logger.info("Using vAPP {0}".format(str(vapp_name)))
    script = "#!/bin/sh\n" + _build_public_keys_script(public_keys,
                                                       _remove_key_script)
    task = vapp.undeploy()
    if not task:
        raise cfy_exc.NonRecoverableError(
            "Can't power off VM. {0}".format(vapp_name))
    wait_for_task(vca_client, task)
    task = vapp.customize_guest_os(
        vapp_name,
        customization_script=script)
    if not task:
        raise cfy_exc.NonRecoverableError(
            "Could not set guest customization parameters. {0}.".
            format(error_response(vapp)))
    wait_for_task(vca_client, task)
    if vapp.customize_on_next_poweron():
        ctx.logger.info("Customizations successful.")
    else:
        customization_task = vapp.force_customization(vapp_name)
        if customization_task:
            ctx.logger.info("Customizations forced")
            wait_for_task(vca_client, customization_task)
        else:
            raise cfy_exc.NonRecoverableError(
                "Can't run customization on next power on. {0}.".
                format(error_response(vapp)))
    vapp = vca_client.get_vapp(vdc, vapp_name)
    task = vapp.poweron()
    if not task:
        raise cfy_exc.NonRecoverableError(
            "Can't poweron VM. {0}".format(vapp_name))
    wait_for_task(vca_client, task)
    ctx.logger.info("Power on after deleting public key successful.")

    ctx.logger.info("Remove keys from properties.")
    host_rt_properties = ctx.target.instance.runtime_properties
    if SSH_KEY in host_rt_properties:
        del host_rt_properties[SSH_KEY]
Beispiel #20
0
def _create(vca_client, config, server):
    """
        create server by template,
        customize:
         * hardware: memmory/cpu
         * software: root password, computer internal hostname
         connect vm to network
    """
    vapp_name = server['name']
    vapp_template = server['template']
    vapp_catalog = server['catalog']
    connections = _create_connections_list(vca_client)
    ctx.logger.info("Creating VApp with parameters: {0}".format(server))
    task = vca_client.create_vapp(config['vdc'],
                                  vapp_name,
                                  vapp_template,
                                  vapp_catalog,
                                  vm_name=vapp_name)
    if not task:
        raise cfy_exc.NonRecoverableError("Could not create vApp: {0}".format(
            error_response(vca_client)))
    wait_for_task(vca_client, task)

    ctx.instance.runtime_properties[VCLOUD_VAPP_NAME] = vapp_name

    # we allways have connection to management_network_name
    if connections:
        for index, connection in enumerate(connections):
            vdc = vca_client.get_vdc(config['vdc'])
            vapp = vca_client.get_vapp(vdc, vapp_name)
            if vapp is None:
                raise cfy_exc.NonRecoverableError(
                    "vApp '{0}' could not be found".format(vapp_name))

            network_name = connection.get('network')
            network = get_network(vca_client, network_name)
            ctx.logger.info("Connect network '{0}' to server '{1}'.".format(
                network_name, vapp_name))
            task = vapp.connect_to_network(network_name, network.get_href())
            if not task:
                raise cfy_exc.NonRecoverableError(
                    "Could not add network {0} to VApp {1}. {2}".format(
                        network_name, vapp_name, error_response(vapp)))
            wait_for_task(vca_client, task)

            connections_primary_index = None
            if connection.get('primary_interface'):
                connections_primary_index = index
            ip_address = connection.get('ip_address')
            mac_address = connection.get('mac_address')
            ip_allocation_mode = connection.get('ip_allocation_mode',
                                                'POOL').upper()
            connection_args = {
                'network_name': network_name,
                'connection_index': index,
                'connections_primary_index': connections_primary_index,
                'ip_allocation_mode': ip_allocation_mode,
                'mac_address': mac_address,
                'ip_address': ip_address
            }
            ctx.logger.info("Connecting network with parameters {0}".format(
                str(connection_args)))
            task = vapp.connect_vms(**connection_args)
            if task is None:
                raise cfy_exc.NonRecoverableError(
                    "Could not connect vApp {0} to network {1}. {2}".format(
                        vapp_name, network_name, error_response(vapp)))
            wait_for_task(vca_client, task)
def _create(vca_client, config, server):
    """
        create server by template,
        customize:
         * hardware: memmory/cpu
         * software: root password, computer internal hostname
         connect vm to network
    """
    vapp_name = server['name']
    vapp_template = server['template']
    vapp_catalog = server['catalog']
    connections = _create_connections_list(vca_client)
    ctx.logger.info("Creating VApp with parameters: {0}".format(server))
    task = vca_client.create_vapp(config['vdc'],
                                  vapp_name,
                                  vapp_template,
                                  vapp_catalog,
                                  vm_name=vapp_name)
    if not task:
        raise cfy_exc.NonRecoverableError("Could not create vApp: {0}"
                                          .format(error_response(vca_client)))
    wait_for_task(vca_client, task)

    ctx.instance.runtime_properties[VCLOUD_VAPP_NAME] = vapp_name

    # we allways have connection to management_network_name
    if connections:
        for index, connection in enumerate(connections):
            vdc = vca_client.get_vdc(config['vdc'])
            vapp = vca_client.get_vapp(vdc, vapp_name)
            if vapp is None:
                raise cfy_exc.NonRecoverableError(
                    "vApp '{0}' could not be found".format(vapp_name))

            network_name = connection.get('network')
            network = get_network(vca_client, network_name)

            task = vapp.connect_to_network(network_name, network.get_href())
            if not task:
                raise cfy_exc.NonRecoverableError(
                    "Could not add network {0} to VApp {1}. {2}"
                    .format(network_name, vapp_name, error_response(vapp)))
            wait_for_task(vca_client, task)

            connections_primary_index = None
            if connection.get('primary_interface'):
                connections_primary_index = index
            ip_address = connection.get('ip_address')
            mac_address = connection.get('mac_address')
            ip_allocation_mode = connection.get('ip_allocation_mode',
                                                'POOL').upper()
            connection_args = {
                'network_name': network_name,
                'connection_index': index,
                'connections_primary_index': connections_primary_index,
                'ip_allocation_mode': ip_allocation_mode,
                'mac_address': mac_address,
                'ip_address': ip_address
            }
            ctx.logger.info("Connecting network with parameters {0}"
                            .format(str(connection_args)))
            task = vapp.connect_vms(**connection_args)
            if task is None:
                raise cfy_exc.NonRecoverableError(
                    "Could not connect vApp {0} to network {1}. {2}"
                    .format(vapp_name, network_name, error_response(vapp)))
            wait_for_task(vca_client, task)
Beispiel #22
0
def configure(vca_client, **kwargs):

    if ctx.node.properties.get('use_external_resource'):
        ctx.logger.info('Avoiding external resource configuration.')
    else:
        ctx.logger.info("Configure server")
        server = {'name': ctx.instance.id}
        server.update(ctx.node.properties.get('server', {}))
        ctx.logger.info("Server properties: {0}"
                        .format(str(server)))
        vapp_name = server['name']
        config = get_vcloud_config()
        custom = server.get(GUEST_CUSTOMIZATION, {})
        public_keys = _get_connected_keypairs()

        vdc = vca_client.get_vdc(config['vdc'])
        vapp = vca_client.get_vapp(vdc, vapp_name)
        if not vapp:
            raise cfy_exc.NonRecoverableError(
                "Unable to find vAPP server "
                "by its name {0}.".format(vapp_name))
        ctx.logger.info("Using vAPP {0}".format(str(vapp_name)))

        hardware = server.get('hardware')
        if hardware:
            cpu = hardware.get('cpu')
            memory = hardware.get('memory')
            _check_hardware(cpu, memory)
            if memory:
                try:
                    ctx.logger.info(
                        "Customize VM memory: '{0}'.".format(memory)
                    )
                    task = vapp.modify_vm_memory(vapp_name, memory)
                    wait_for_task(vca_client, task)
                except Exception:
                    raise cfy_exc.NonRecoverableError(
                        "Customize VM memory failed: '{0}'. {1}".
                        format(task, error_response(vapp)))
            if cpu:
                try:
                    ctx.logger.info(
                        "Customize VM cpu: '{0}'.".format(cpu)
                    )
                    task = vapp.modify_vm_cpu(vapp_name, cpu)
                    wait_for_task(vca_client, task)
                except Exception:
                    raise cfy_exc.NonRecoverableError(
                        "Customize VM cpu failed: '{0}'. {1}".
                        format(task, error_response(vapp)))

        if custom or public_keys:
            script = _build_script(custom, public_keys)
            password = custom.get('admin_password')
            computer_name = custom.get('computer_name')
            ctx.logger.info("Customizing guest OS.")
            task = vapp.customize_guest_os(
                vapp_name,
                customization_script=script,
                computer_name=computer_name,
                admin_password=password
            )
            if task is None:
                raise cfy_exc.NonRecoverableError(
                    "Could not set guest customization parameters. {0}".
                    format(error_response(vapp)))
            wait_for_task(vca_client, task)
            if vapp.customize_on_next_poweron():
                ctx.logger.info("Customizations successful")
            else:
                customization_task = vapp.force_customization(vapp_name)
                if customization_task:
                    ctx.logger.info("Customizations forced")
                    wait_for_task(vca_client, customization_task)
                else:
                    raise cfy_exc.NonRecoverableError(
                        "Can't run customization in next power on. {0}".
                        format(error_response(vapp)))

        if not _is_primary_connection_has_ip(vapp):
            ctx.logger.info("Power on server for get dhcp ip.")
            # we have to start vapp before continue
            _power_on_vm(vca_client, vapp, vapp_name)
            for attempt in xrange(RETRY_COUNT):
                vapp = vca_client.get_vapp(vdc, vapp_name)
                if _is_primary_connection_has_ip(vapp):
                    return
                ctx.logger.info(
                    "No ip assigned. Retrying... {}/{} attempt."
                    .format(attempt + 1, RETRY_COUNT)
                )
                time.sleep(GATEWAY_TIMEOUT)
            ctx.logger.info("We dont recieve ip, try next time...")