Example #1
0
    def update_static_route(self,
                            network=None,
                            next_hop=None,
                            mtu=None,
                            description=None,
                            vnic=None):
        """Update the Static Route.

        param network str: vApp/Org vDC Network in CIDR format
        e.g. 192.169.1.0/24
        param next_hop str: IP address of next hop
        param mtu int: Maximum Transmission Units (MTU) e.g 1500 MTU
        param description str: static route description
        param vnic int: interface of gateway

        """
        static_resource = self._get_resource()
        for static_route in static_resource.staticRoutes.route:
            if static_route.network == self.resource_id:
                if network:
                    static_route.network = E.network(network)
                if next_hop:
                    static_route.nextHop = E.nextHop(next_hop)
                if mtu:
                    static_route.mtu = E.mtu(mtu)
                if description:
                    static_route.description = E.description(description)
                if vnic:
                    static_route.vnic = E.vnic(vnic)
                break

        self.client.put_resource(self.href, static_resource,
                                 EntityType.DEFAULT_CONTENT_TYPE.value)
Example #2
0
    def update_nat_rule(self,
                        original_address=None,
                        translated_address=None,
                        description=None,
                        protocol=None,
                        original_port=None,
                        translated_port=None,
                        icmp_type=None,
                        logging_enabled=None,
                        enabled=None,
                        vnic=None):
        """Update a Nat Rule.

        param original_address str: original IP address
        param translated_address str: translated IP address
        param description str: nat rule description
        param protocol str: protocol such as tcp/udp/icmp
        param original_port: port no. such as FTP(21)
        param translated_port: port no. such as HTTP(80)
        param icmp_type str: icmp type such as "Echo-request"
        param logging_enabled bool: enable logging
        param enable bool: enable nat rule
        param int vnic: interface of gateway

        """
        nat_rule = self.get_resource()

        if original_address is not None:
            nat_rule.originalAddress = E.originalAddress(original_address)
        if translated_address is not None:
            nat_rule.translatedAddress = \
                E.translatedAddress(translated_address)
        if description is not None:
            nat_rule.description = E.description(description)
        if protocol is not None:
            nat_rule.protocol = E.protocol(protocol)
        if original_port is not None:
            nat_rule.originalPort = E.originalPort(original_port)
        if translated_port is not None:
            nat_rule.translatedPort = E.translatedPort(translated_port)
        if icmp_type is not None:
            nat_rule.icmpType = E.icmpType(icmp_type)
        if logging_enabled is not None:
            nat_rule.loggingEnabled = E.loggingEnabled(logging_enabled)
        if enabled is not None:
            nat_rule.enabled = E.enabled(enabled)
        if vnic is not None:
            nat_rule.vnic = E.vnic(vnic)

        return self.client.put_resource(
            self.href,
            nat_rule,
            EntityType.DEFAULT_CONTENT_TYPE.value)
Example #3
0
    def create_provider_vdc(self,
                            vim_server_name,
                            resource_pool_names,
                            storage_profiles,
                            pvdc_name,
                            is_enabled=None,
                            description=None,
                            highest_hw_vers=None,
                            vxlan_network_pool=None,
                            nsxt_manager_name=None):
        """Create a Provider Virtual Datacenter.

        :param str vim_server_name: vim_server_name (VC name).
        :param list resource_pool_names: list of resource_pool_names.
        :param list storage_profiles: (list): list of storageProfile namespace.
        :param str pvdc_name: name of PVDC to be created.
        :param bool is_enabled: flag, True to enable and False to disable.
        :param str description: description of pvdc.
        :param str highest_hw_vers: highest supported hw version number.
        :param str vxlan_network_pool: name of vxlan_network_pool.
        :param str nsxt_manager_name: name of nsx-t manager.

        :return: an object containing vmext:VMWProviderVdc XML element that
            represents the new provider VDC.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        vc_record = self.get_vcenter(vim_server_name)
        vc_href = vc_record.get('href')
        rp_morefs = self.get_resource_pool_morefs(vim_server_name, vc_href,
                                                  resource_pool_names)
        vmw_prov_vdc_params = E_VMEXT.VMWProviderVdcParams(name=pvdc_name)
        if description is not None:
            vmw_prov_vdc_params.append(E.Description(description))
        resource_pool_refs = E_VMEXT.ResourcePoolRefs()
        for rp_moref in rp_morefs:
            vim_object_ref = E_VMEXT.VimObjectRef()
            vim_object_ref.append(E_VMEXT.VimServerRef(href=vc_href))
            vim_object_ref.append(E_VMEXT.MoRef(rp_moref))
            vim_object_ref.append(E_VMEXT.VimObjectType('RESOURCE_POOL'))
            resource_pool_refs.append(vim_object_ref)
        vmw_prov_vdc_params.append(resource_pool_refs)
        vmw_prov_vdc_params.append(E_VMEXT.VimServer(href=vc_href))
        if vxlan_network_pool is not None:
            network_pool_rec = self.get_res_by_name(ResourceType.NETWORK_POOL,
                                                    vxlan_network_pool)
            vx_href = network_pool_rec.get('href')
            vmw_prov_vdc_params.append(E_VMEXT.VxlanNetworkPool(href=vx_href))
        if nsxt_manager_name is not None:
            nsxt_manager_rec = self.get_res_by_name(ResourceType.NSXT_MANAGER,
                                                    nsxt_manager_name)
            nsxt_href = nsxt_manager_rec.get('href')
            vmw_prov_vdc_params.append(
                E_VMEXT.NsxTManagerReference(href=nsxt_href))
        if highest_hw_vers is not None:
            vmw_prov_vdc_params.append(
                E_VMEXT.HighestSupportedHardwareVersion(highest_hw_vers))
        if is_enabled is not None:
            vmw_prov_vdc_params.append(E_VMEXT.IsEnabled(is_enabled))
        for storage_profile in storage_profiles:
            vmw_prov_vdc_params.append(E_VMEXT.StorageProfile(storage_profile))
        random_username_suffix = uuid.uuid4().hex
        default_user = '******' + random_username_suffix[:8]
        default_pwd = 'PWD' + random_username_suffix[:8]
        vmw_prov_vdc_params.append(E_VMEXT.DefaultPassword(default_pwd))
        vmw_prov_vdc_params.append(E_VMEXT.DefaultUsername(default_user))

        return self.client.post_linked_resource(
            self.extension.get_resource(),
            rel=RelationType.ADD,
            media_type=EntityType.PROVIDER_VDC_PARAMS.value,
            contents=vmw_prov_vdc_params)
Example #4
0
    def to_instantiate_vm_template_params(self, spec):
        source_vapp = VApp(self.client, resource=spec['vapp'])
        vm_template = source_vapp.get_vm(spec['source_vm_name'])

        params = E.InstantiateVmTemplateParams(
            E.SourcedVmTemplateItem(
                E.Source(
                    href=vm_template.get('href'),
                    id=vm_template.get('id'),
                    type=vm_template.get('type'),
                    name=vm_template.get('name'),
                )),
            name=spec['target_vm_name'],
            powerOn='true' if spec['power_on'] else 'false')

        vm_general_params = E.VmGeneralParams()
        vm_instantiation_param = E.VmTemplateInstantiationParams()

        if spec.get('network'):
            primary_index = int(vm_template.NetworkConnectionSection.
                                PrimaryNetworkConnectionIndex.text)
            vm_instantiation_param.append(
                E.NetworkConnectionSection(
                    E_OVF.Info(),
                    E.NetworkConnection(
                        E.NetworkConnectionIndex(primary_index),
                        E.IsConnected(True),
                        E.IpAddressAllocationMode(
                            spec['ip_allocation_mode'].upper()),
                        network=spec['network'])))

        needs_customization = 'disk_size' in spec or 'password' in spec or \
            'cust_script' in spec or 'hostname' in spec
        if needs_customization:
            guest_customization_param = E.GuestCustomizationSection(
                E_OVF.Info(),
                E.Enabled(True),
            )
            if spec.get('password'):
                guest_customization_param.append(E.AdminPasswordEnabled(True))
                guest_customization_param.append(E.AdminPasswordAuto(False))
                guest_customization_param.append(
                    E.AdminPassword(spec['password']))
            else:
                if spec.get('password_auto'):
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(True))
                    guest_customization_param.append(E.AdminPasswordAuto(True))
                else:
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(False))
            if spec.get('password_reset'):
                guest_customization_param.append(
                    E.ResetPasswordRequired(spec['password_reset']))
            if spec.get('cust_script'):
                guest_customization_param.append(
                    E.CustomizationScript(spec['cust_script']))
            if spec.get('hostname'):
                guest_customization_param.append(
                    E.ComputerName(spec['hostname']))
            vm_instantiation_param.append(guest_customization_param)

        vm_general_params.append(E.NeedsCustomization(needs_customization))

        params.SourcedVmTemplateItem.append(vm_general_params)
        params.SourcedVmTemplateItem.append(vm_instantiation_param)

        if spec.get('storage_profile'):
            sp = spec['storage_profile']
            storage_profile = E.StorageProfile(
                href=sp.get('href'),
                id=sp.get('href').split('/')[-1],
                type=sp.get('type'),
                name=sp.get('name'))
            params.SourcedVmTemplateItem.append(storage_profile)

        return params
Example #5
0
    def update_ipsec_vpn(self,
                         name=None,
                         peer_id=None,
                         peer_ip_address=None,
                         local_id=None,
                         local_ip_address=None,
                         local_subnet=None,
                         peer_subnet=None,
                         shared_secret_encrypted=None,
                         encryption_protocol=None,
                         authentication_mode=None,
                         dh_group=None,
                         description=None,
                         mtu=None,
                         is_enabled=None,
                         enable_pfs=None):
        """Update IPsec VPN of the gateway.

        param str name: new name of IPSec VPN
        param str description: new description of IPSec VPN
        param str peer_id: new peer id
        param str peer_ip_address: new peer IP address
        param str local_id: new local id
        param str local_ip_address: new local IP address
        param str local_subnet: new local subnet in CIDR format
        param str peer_subnet: new peer subnet in CIDR format
        param str shared_secret_encrypted: new shared secret encrypted
        param str encryption_protocol: new encryption protocol
        param str authentication_mode: new authentication mode
        param str dh_group: new dh group
        param str mtu: new MTU
        param bool is_enabled: new enabled status Default : false
        param bool enable_pfs: new enabled pfs status Default : false
        :return: Ipsec Vpn object
        :rtype: lxml.objectify.ObjectifiedElement
        """
        end_points = self.end_point.split('-')
        local_ip = end_points[0]
        peer_ip = end_points[1]
        ipsec_vpn = self.resource
        vpn_sites = ipsec_vpn.sites
        for site in vpn_sites.site:
            if site.localIp == local_ip and site.peerIp == peer_ip:
                if is_enabled is not None:
                    site.enabled = E.enabled(is_enabled)
                if name is not None:
                    site.name = E.name(name)
                if description is not None:
                    site.description = E.description(description)
                if local_id is not None:
                    site.localId = E.localId(local_id)
                if local_ip_address is not None:
                    site.localIp = E.localIp(local_ip_address)
                if peer_id is not None:
                    site.peerId = E.peerId(peer_id)
                if peer_ip_address is not None:
                    site.peerIp = E.peerIp(peer_ip_address)
                if encryption_protocol is not None:
                    site.encryptionAlgorithm = \
                        E.encryptionAlgorithm(encryption_protocol)
                if mtu is not None:
                    site.mtu = E.mtu(mtu)
                if enable_pfs is not None:
                    site.enablePfs = E.enablePfs(enable_pfs)
                if local_subnet is not None:
                    local_subnets = E.localSubnets()
                    if ',' in local_subnet:
                        subnet_list = local_subnet.split(",")
                        for subnet in subnet_list:
                            local_subnets.append(E.subnet(subnet))
                    else:
                        local_subnets.append(E.subnet(local_subnet))
                    site.localSubnets = local_subnets
                if peer_subnet is not None:
                    peer_subnets = E.peerSubnets()
                    if ',' in peer_subnet:
                        subnet_list = peer_subnet.split(",")
                        for subnet in subnet_list:
                            peer_subnets.append(E.subnet(subnet))
                    else:
                        peer_subnets.append(E.subnet(peer_subnet))
                    site.peerSubnets = peer_subnets
                if shared_secret_encrypted is not None:
                    site.psk = E.psk(shared_secret_encrypted)
                if authentication_mode is not None:
                    site.authenticationMode = \
                        E.authenticationMode(authentication_mode)
                if dh_group is not None:
                    site.dhGroup = E.dhGroup(dh_group)
                break

        self.client.put_resource(self.href, ipsec_vpn,
                                 EntityType.DEFAULT_CONTENT_TYPE.value)
Example #6
0
    def to_sourced_item(self, spec):
        """Creates a VM SourcedItem from a VM specification.

        :param spec: (dict) containing:
            vapp: (resource): (required) source vApp or vAppTemplate resource
            source_vm_name: (str): (required) source VM name
            target_vm_name: (str): (optional) target VM name
            hostname: (str): (optional) target guest hostname
            password: (str): (optional) set the administrator password of this
                machine to this value
            password_auto: (bool): (optional) autogenerate administrator
                password
            password_reset: (bool): (optional) True if the administrator
                password for this virtual machine must be reset after first use
            cust_script: (str): (optional) script to run on guest customization
            network: (str): (optional) Name of the vApp network to connect.
                If omitted, the VM won't be connected to any network
            storage_profile: (str): (optional) the name of the storage profile
                to be used for this VM

        :return: SourcedItem: (:class:`lxml.objectify.StringElement`): object
            representing the 'SourcedItem' xml object created from the
            specification.
        """

        source_vapp = VApp(self.client, resource=spec['vapp'])
        source_vm_resource = source_vapp.get_vm(spec['source_vm_name'])

        sourced_item = E.SourcedItem(
            E.Source(
                href=source_vm_resource.get('href'),
                id=source_vm_resource.get('id'),
                name=source_vm_resource.get('name'),
                type=source_vm_resource.get('type')))

        vm_general_params = E.VmGeneralParams()
        if 'target_vm_name' in spec:
            vm_general_params.append(E.Name(spec['target_vm_name']))

        vm_instantiation_param = E.InstantiationParams()
        if 'network' in spec:
            primary_index = int(source_vm_resource.NetworkConnectionSection.
                                PrimaryNetworkConnectionIndex.text)
            if 'ip_allocation_mode' in spec:
                ip_allocation_mode = spec['ip_allocation_mode']
            else:
                ip_allocation_mode = 'DHCP'
            vm_instantiation_param.append(
                E.NetworkConnectionSection(
                    E_OVF.Info(),
                    E.NetworkConnection(
                        E.NetworkConnectionIndex(primary_index),
                        E.IsConnected(True),
                        E.IpAddressAllocationMode(ip_allocation_mode.upper()),
                        network=spec['network'])))

        needs_customization = 'disk_size' in spec or 'password' in spec or \
            'cust_script' in spec or 'hostname' in spec
        if needs_customization:
            guest_customization_param = E.GuestCustomizationSection(
                E_OVF.Info(),
                E.Enabled(True),
            )
            if 'password' in spec:
                guest_customization_param.append(E.AdminPasswordEnabled(True))
                guest_customization_param.append(E.AdminPasswordAuto(False))
                guest_customization_param.append(
                    E.AdminPassword(spec['password']))
            else:
                if 'password_auto' in spec:
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(True))
                    guest_customization_param.append(E.AdminPasswordAuto(True))
                else:
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(False))
            if 'password_reset' in spec:
                guest_customization_param.append(
                    E.ResetPasswordRequired(spec['password_reset']))
            if 'cust_script' in spec:
                guest_customization_param.append(
                    E.CustomizationScript(spec['cust_script']))
            if 'hostname' in spec:
                guest_customization_param.append(
                    E.ComputerName(spec['hostname']))
            vm_instantiation_param.append(guest_customization_param)

        vm_general_params.append(E.NeedsCustomization(needs_customization))
        sourced_item.append(vm_general_params)
        sourced_item.append(vm_instantiation_param)

        if 'storage_profile' in spec:
            sp = spec['storage_profile']
            storage_profile = E.StorageProfile(
                href=sp.get('href'),
                id=sp.get('href').split('/')[-1],
                type=sp.get('type'),
                name=sp.get('name'))
            sourced_item.append(storage_profile)

        return sourced_item
Example #7
0
    def create_user(self,
                    user_name,
                    password,
                    role_href,
                    full_name='',
                    description='',
                    email='',
                    telephone='',
                    im='',
                    alert_email='',
                    alert_email_prefix='',
                    stored_vm_quota=0,
                    deployed_vm_quota=0,
                    is_group_role=False,
                    is_default_cached=False,
                    is_external=False,
                    is_alert_enabled=False,
                    is_enabled=False):
        """Create User in the current Org

        :param user_name: The username of the user
        :param password: The password of the user
        :param role_href: The href of the user role
        :param full_name: The full name of the user
        :param description: The description for the User
        :param email: The email of the user
        :param telephone: The telephone of the user
        :param im: The im address of the user
        :param alert_email: The alert email address
        :param alert_email_prefix: The string to prepend to the alert message
                subject line
        :param stored_vm_quota: The quota of vApps that this user can store
        :param deployed_vm_quota: The quota of vApps that this user can deploy
                concurrently
        :param is_group_role: Indicates if the user has a group role
        :param is_default_cached: Indicates if user should be cached
        :param is_external: Indicates if user is imported from an external
                source
        :param is_alert_enabled: The alert email address
        :param is_enabled: Enable user
        :return: (UserType) Created user object
        """
        resource_admin = self.client.get_resource(self.href_admin)
        user = E.User(E.Description(description),
                      E.FullName(full_name),
                      E.EmailAddress(email),
                      E.Telephone(telephone),
                      E.IsEnabled(is_enabled),
                      E.IM(im),
                      E.IsAlertEnabled(is_alert_enabled),
                      E.AlertEmailPrefix(alert_email_prefix),
                      E.AlertEmail(alert_email),
                      E.IsExternal(is_external),
                      E.IsDefaultCached(is_default_cached),
                      E.IsGroupRole(is_group_role),
                      E.StoredVmQuota(stored_vm_quota),
                      E.DeployedVmQuota(deployed_vm_quota),
                      E.Role(href=role_href),
                      E.Password(password),
                      name=user_name)
        return self.client.post_linked_resource(resource_admin,
                                                RelationType.ADD,
                                                EntityType.USER.value, user)
Example #8
0
    def to_sourced_item(self, spec):
        """Creates a vm SourcedItem from a vm specification.

        :param dict spec: a dictionary containing

            - vapp: (resource): (required) source vApp or vAppTemplate
                resource.
            - source_vm_name: (str): (required) source vm name.
            - target_vm_name: (str): (optional) target vm name.
            - hostname: (str): (optional) target guest hostname.
            - password: (str): (optional) the administrator password of the vm.
            - password_auto: (bool): (optional) auto generate administrator
                password.
            - password_reset: (bool): (optional) True, if the administrator
                password for this vm must be reset after first use.
            - cust_script: (str): (optional) script to run on guest
                customization.
            - network: (str): (optional) name of the vApp network to connect.
                If omitted, the vm won't be connected to any network.
            - storage_profile: (str): (optional) the name of the storage
                profile to be used for this vm.

        :return: an object containing SourcedItem XML element.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        source_vapp = VApp(self.client, resource=spec['vapp'])
        source_vm_resource = source_vapp.get_vm(spec['source_vm_name'])

        sourced_item = E.SourcedItem(
            E.Source(href=source_vm_resource.get('href'),
                     id=source_vm_resource.get('id'),
                     name=source_vm_resource.get('name'),
                     type=source_vm_resource.get('type')))

        vm_general_params = E.VmGeneralParams()
        if 'target_vm_name' in spec:
            vm_general_params.append(E.Name(spec['target_vm_name']))

        vm_instantiation_param = E.InstantiationParams()
        if 'network' in spec:
            primary_index = int(source_vm_resource.NetworkConnectionSection.
                                PrimaryNetworkConnectionIndex.text)
            if 'ip_allocation_mode' in spec:
                ip_allocation_mode = spec['ip_allocation_mode']
            else:
                ip_allocation_mode = 'DHCP'
            vm_instantiation_param.append(
                E.NetworkConnectionSection(
                    E_OVF.Info(),
                    E.NetworkConnection(
                        E.NetworkConnectionIndex(primary_index),
                        E.IsConnected(True),
                        E.IpAddressAllocationMode(ip_allocation_mode.upper()),
                        network=spec['network'])))

        needs_customization = 'disk_size' in spec or 'password' in spec or \
            'cust_script' in spec or 'hostname' in spec
        if needs_customization:
            guest_customization_param = E.GuestCustomizationSection(
                E_OVF.Info(),
                E.Enabled(True),
            )
            if 'password' in spec:
                guest_customization_param.append(E.AdminPasswordEnabled(True))
                guest_customization_param.append(E.AdminPasswordAuto(False))
                guest_customization_param.append(
                    E.AdminPassword(spec['password']))
            else:
                if 'password_auto' in spec:
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(True))
                    guest_customization_param.append(E.AdminPasswordAuto(True))
                else:
                    guest_customization_param.append(
                        E.AdminPasswordEnabled(False))
            if 'password_reset' in spec:
                guest_customization_param.append(
                    E.ResetPasswordRequired(spec['password_reset']))
            if 'cust_script' in spec:
                guest_customization_param.append(
                    E.CustomizationScript(spec['cust_script']))
            if 'hostname' in spec:
                guest_customization_param.append(
                    E.ComputerName(spec['hostname']))
            vm_instantiation_param.append(guest_customization_param)

        vm_general_params.append(E.NeedsCustomization(needs_customization))
        sourced_item.append(vm_general_params)
        sourced_item.append(vm_instantiation_param)

        if 'storage_profile' in spec:
            sp = spec['storage_profile']
            storage_profile = E.StorageProfile(
                href=sp.get('href'),
                id=sp.get('href').split('/')[-1],
                type=sp.get('type'),
                name=sp.get('name'))
            sourced_item.append(storage_profile)

        return sourced_item
Example #9
0
    def add_firewall_rule(self,
                          name,
                          is_enabled=False,
                          policy='drop',
                          protocols=['Any'],
                          source_port_range='Any',
                          source_ip='Any',
                          destination_port_range='Any',
                          destination_ip='Any',
                          enable_logging=False):
        """Add firewall rule on firewall services to vApp network.

        :param str name: name of firewall rule.
        :param str policy: policy on firewall rule.
        :param list protocols: list of protocols on firewall rule.
        :param str source_port_range: source port range for firewall rule.
        :param str source_ip: source IP.
        :param str destination_port_range:destination port range for firewall
            rule.
        :param str destination_ip: destination IP.
        :param str enable_logging: enable logging on firewall rule.
        :return: an object containing EntityType.TASK XML data which represents
            the asynchronous task that is updating the vApp network.
        :rtype: lxml.objectify.ObjectifiedElement
        :raises: InvalidParameterException: Enable firewall service failed as
            given network's connection is not routed
        """
        self._get_resource()
        fence_mode = self.resource.Configuration.FenceMode
        if fence_mode != 'natRouted':
            raise InvalidParameterException(
                "Enable firewall service failed as given network's connection "
                "is not routed")
        firewall_service = self.resource.Configuration.Features.FirewallService
        firewall_rule = E.FirewallRule()
        firewall_rule.append(E.IsEnabled(is_enabled))
        firewall_rule.append(E.Description(name))
        firewall_rule.append(E.Policy(policy))
        protocol = E.Protocols()
        for proto in protocols:
            if proto == 'Any':
                protocol.append(E.Any(True))
            elif proto == 'Icmp':
                protocol.append(E.Icmp(True))
            elif proto == 'Tcp':
                protocol.append(E.Tcp(True))
            elif proto == 'Udp':
                protocol.append(E.Udp(True))
        firewall_rule.append(protocol)
        firewall_rule.append(E.DestinationPortRange(destination_port_range))
        firewall_rule.append(E.DestinationIp(destination_ip))
        firewall_rule.append(E.SourcePortRange(source_port_range))
        firewall_rule.append(E.SourceIp(source_ip))
        firewall_rule.append(E.EnableLogging(enable_logging))
        firewall_service.append(firewall_rule)
        return self.client.put_linked_resource(self.resource,
                                               RelationType.EDIT,
                                               EntityType.vApp_Network.value,
                                               self.resource)
Example #10
0
    def update(self,
               status,
               namespace,
               operation,
               operation_name,
               details,
               progress,
               owner_href,
               owner_name,
               owner_type,
               user_href,
               user_name,
               org_href=None,
               task_href=None,
               error_message=None,
               stack_trace=''):
        """Update a task in vCD.

        :param str status: new status of the task.
        :param str namespace: identifier of the service that created the task.
            It must not start with com.vmware.vcloud and the length must be
            between 1 and 128 symbols.
        :param str operation: new message describing the operation that is
            being tracked by this task.
        :param str operation_name: new short name of the operation that is
            being tracked by the task.
        :param details: new detailed message about the task.
        :param str progress: read-only indicator of task progress as an
            approximate percentage between 0 and 100. Not available for all
            tasks.
        :param str owner_href: href of the owner of the task. This is typically
            the object that the task is creating or updating.
        :param str owner_name: name of the owner of the task.
        :param str owner_type: XML type of the owner object
        :param str user_href: href of the user who started the task.
        :param str user_name: name of the user who started the task.
        :param str org_href: href of the organization, which the user mentioned
            above belongs to.
        :param str task_href: href of the task.
        :param str error_message: represents error information from a failed
            task.
        :param str stack_trace: stack trace of the error message from a
            failed task.

        :return: an object containing EntityType.TASK XML data representing the
            updated task.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        t = E.Task(status=status,
                   serviceNamespace=namespace,
                   type=EntityType.TASK.value,
                   operation=operation,
                   operationName=operation_name,
                   name='task')
        t.append(E.Owner(href=owner_href, name=owner_name, type=owner_type))
        if error_message is not None:
            t.append(
                E.Error(stackTrace=stack_trace,
                        majorErrorCode='500',
                        message=error_message,
                        minorErrorCode='INTERNAL_SERVER_ERROR'))
        t.append(
            E.User(href=user_href, name=user_name, type=EntityType.USER.value))
        if progress is not None:
            t.append(E.Progress(progress))
        t.append(E.Details(details))
        if task_href is None:
            org_resource = self.client.get_resource(org_href)
            link = find_link(org_resource, RelationType.DOWN,
                             EntityType.TASKS_LIST.value)
            return self.client.post_resource(link.href, t,
                                             EntityType.TASK.value)
        else:
            return self.client.put_resource(task_href, t,
                                            EntityType.TASK.value)
 def _makeStaticRouteServiceAttr(features):
     route_service = E.StaticRoutingService()
     route_service.append(E.IsEnabled(True))
     features.append(route_service)
Example #12
0
    def test_0000_setup(self):
        """Setup the gateway required for the other tests in this module.

        Create a gateway as per the configuration stated
        above.

        This test passes if the gateway is created successfully.
        """
        TestGateway._client = Environment.get_sys_admin_client()
        TestGateway._vdc = Environment.get_test_vdc(TestGateway._client)

        TestGateway._org_client = Environment.get_client_in_default_org(
            CommonRoles.ORGANIZATION_ADMINISTRATOR)
        TestGateway._config = Environment.get_config()
        TestGateway._api_version = TestGateway._config['vcd']['api_version']

        external_network = Environment.get_test_external_network(
            TestGateway._client)

        ext_net_resource = external_network.get_resource()
        ip_scopes = ext_net_resource.xpath(
            'vcloud:Configuration/vcloud:IpScopes/vcloud:IpScope',
            namespaces=NSMAP)
        first_ipscope = ip_scopes[0]
        gateway_ip = first_ipscope.Gateway.text
        prefix_len = netmask_to_cidr_prefix_len(gateway_ip,
                                                first_ipscope.Netmask.text)
        subnet_addr = gateway_ip + '/' + str(prefix_len)
        ext_net_to_participated_subnet_with_ip_settings = {
            ext_net_resource.get('name'): {
                subnet_addr: self._ip_address_for_config_ip_setting
            }
        }

        ext_net_to_subnet_with_ip_range = {
            ext_net_resource.get('name'): {
                subnet_addr: [self._ip_address_for_ip_range]
            }
        }
        ext_net_to_rate_limit = {ext_net_resource.get('name'): {100: 100}}
        if float(TestGateway._api_version) <= float(
                ApiVersion.VERSION_30.value):
            TestGateway._gateway = \
                TestGateway._vdc.create_gateway_api_version_30(
                    self._name, [ext_net_resource.get('name')], 'compact',
                    None,
                    True, ext_net_resource.get('name'), gateway_ip, True,
                    False,
                    False, False, True,
                    ext_net_to_participated_subnet_with_ip_settings, True,
                    ext_net_to_subnet_with_ip_range, ext_net_to_rate_limit)
        elif float(TestGateway._api_version) == float(
                ApiVersion.VERSION_31.value):
            TestGateway._gateway = \
                TestGateway._vdc.create_gateway_api_version_31(
                    self._name, [ext_net_resource.get('name')], 'compact',
                    None, True, ext_net_resource.get('name'), gateway_ip,
                    True, False, False, False, True,
                    ext_net_to_participated_subnet_with_ip_settings, True,
                    ext_net_to_subnet_with_ip_range, ext_net_to_rate_limit)
        elif float(TestGateway._api_version) >= float(
                ApiVersion.VERSION_32.value):
            TestGateway._gateway = \
                TestGateway._vdc.create_gateway_api_version_32(
                    self._name, [ext_net_resource.get('name')], 'compact',
                    None, True, ext_net_resource.get('name'), gateway_ip,
                    True, False, False, False, True,
                    ext_net_to_participated_subnet_with_ip_settings, True,
                    ext_net_to_subnet_with_ip_range, ext_net_to_rate_limit)

        result = TestGateway._client.get_task_monitor().wait_for_success(
            task=TestGateway._gateway.Tasks.Task)
        self.assertEqual(result.get('status'), TaskStatus.SUCCESS.value)

        TestGateway._extension = Extension(TestGateway._client)
        TestGateway._extension.get_resource()
        link = find_link(TestGateway._extension.resource, RelationType.DOWN,
                         EntityType.SYSTEM_SETTINGS.value)
        settings = TestGateway._client.get_resource(link.href)
        syslog_server_settings = settings.GeneralSettings.SyslogServerSettings

        if hasattr(syslog_server_settings,
                   '{' + NSMAP['vcloud'] + '}SyslogServerIp1'):
            return
        syslog_server_settings.append(
            E.SyslogServerIp1(TestGateway._syslog_server_ip1))
        TestGateway._client.put_resource(link.href, settings,
                                         EntityType.SYSTEM_SETTINGS.value)
        TestGateway._extension.reload()
        settings = TestGateway._client.get_resource(link.href)
        self.assertTrue(
            hasattr(syslog_server_settings,
                    '{' + NSMAP['vcloud'] + '}SyslogServerIp1'))
Example #13
0
    def add_external_network(self, network_name, ip_configuration):
        """Add the given external network to the gateway.

        :param str network_name: external network name.

        :param list ip_configuration: list of tuples that contain subnet in
            CIDR format and allocated ip address.
            Example [(10.10.10.1/24, Auto), (10.10.20.1/24, 10.10.20.3)]

        :return: object containing EntityType.TASK XML data representing the
            asynchronous task.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        if self.resource is None:
            self.reload()

        gateway = self.resource
        for inf in gateway.Configuration.GatewayInterfaces.GatewayInterface:
            if inf.Network.get('name') == network_name:
                raise AlreadyExistsException('External network ' +
                                             network_name +
                                             'already added to the gateway.')

        ext_nw = self._get_external_network(network_name)
        gw_interface = self._create_gateway_interface(ext_nw, 'uplink')

        # Add subnet participation
        ip_scopes = ext_nw.xpath(
            'vcloud:Configuration/vcloud:IpScopes/vcloud:IpScope',
            namespaces=NSMAP)
        for ip_scope in ip_scopes:
            subnet_participation_param = E.SubnetParticipation()
            subnet = None
            ext_nw_subnet = ip_scope.Gateway.text + '/' + \
                str(netmask_to_cidr_prefix_len(ip_scope.Gateway.text,
                                               ip_scope.Netmask.text))
            for sn in ip_configuration:
                if len(sn) != 2:
                    raise InvalidParameterException(
                        'IP Configuration should have both subnet and IP.')
                if sn[0] == ext_nw_subnet:
                    subnet = sn
                    break
            if subnet is None:
                continue

            ip_assigned = subnet[1].strip()
            # Configure Ip Settings
            subnet_participation_param.append(E.Gateway(ip_scope.Gateway.text))
            subnet_participation_param.append(E.Netmask(ip_scope.Netmask.text))

            if not ip_assigned and ip_assigned.lower() != 'auto':
                subnet_participation_param.append(E.IpAddress(ip_assigned))

            gw_interface.append(subnet_participation_param)

        gateway.Configuration.GatewayInterfaces.append(gw_interface)
        return self.client.put_linked_resource(
            self.resource, RelationType.GATEWAY_UPDATE_PROPERTIES,
            EntityType.EDGE_GATEWAY.value, gateway)
Example #14
0
    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        hostname = params.get('hostname')
        source_vm_name = params.get('source_vm_name')
        target_vapp = params.get('target_vapp')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        power_on = params.get('power_on')
        ip_allocation_mode = params.get('ip_allocation_mode')
        cust_script = params.get('cust_script')
        storage_profile_name = params.get('storage_profile')
        storage_profile = None
        all_eulas_accepted = params.get('all_eulas_accepted')
        response = dict()
        response['msg'] = dict()
        response['changed'] = False

        if storage_profile_name:
            storage_profile = self.get_storage_profile(storage_profile_name)

        try:
            self.vdc.get_vapp(target_vapp)
        except EntityNotFoundException:
            spec = {
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                'cust_script': cust_script,
                'storage_profile': storage_profile,
                'power_on': power_on
            }

            params = self.to_instantiate_vm_template_params(spec)

            if all_eulas_accepted is not None:
                params.append(E.AllEULAsAccepted(all_eulas_accepted))

            add_vms_task = self.client.post_linked_resource(
                self.vdc.resource, RelationType.ADD,
                'application/vnd.vmware.vcloud.instantiateVmTemplateParams+xml',
                params)
            result = self.execute_task(add_vms_task)
            result = task_to_dict(result)
            if isinstance(result.get('details'), StringElement):
                del result['details']
            response['msg'].update(result)
            response['changed'] = True

        else:
            response['warnings'] = "Vapp {} is already present.".format(
                target_vapp)

        return response
Example #15
0
def update_vm_compute_policy_element(api_version,
                                     vm,
                                     sizing_policy_href=None,
                                     placement_policy_href=None):
    """Update the compute policy element of a VM.

    Note: This method only adds the policy elements if supported by the
        api_version

    :param api_version float:
    :param vm lxml.objectify.ObjectifiedElement: Element representing a VM
    :param sizing_policy_href: href of the sizing policy to be added
    :param placement_policy_href: href of the placement policy to be added

    :return: Boolean which indicates if update is required. (VM resource is
        manipulated in-place)

    :rtype: bool
    """
    # boolean which indicates if template vm element has been changed
    update_required = False
    if api_version < VM_SIZING_POLICY_MIN_API_VERSION and \
            not (sizing_policy_href or placement_policy_href):
        return update_required

    date_created_node = vm.find(
        '{http://www.vmware.com/vcloud/v1.5}DateCreated')  # noqa: E501
    if hasattr(vm, 'ComputePolicy'):
        compute_policy_element = vm.ComputePolicy
    else:
        update_required = True
        compute_policy_element = E.ComputePolicy()
        date_created_node.addprevious(compute_policy_element)

    if placement_policy_href:
        placement_policy_id = retrieve_compute_policy_id_from_href(
            placement_policy_href)  # noqa: E501
        if hasattr(compute_policy_element, 'VmPlacementPolicy'):
            if compute_policy_element.VmPlacementPolicy.get(
                    'href', '') != placement_policy_href:  # noqa: E501
                update_required = True
            vm_placement_policy_element = compute_policy_element.VmPlacementPolicy  # noqa: E501
        else:
            update_required = True
            vm_placement_policy_element = E.VmPlacementPolicy()
            # VmPlacementPolicy should always precede VmSizingPolicy
            compute_policy_element.insert(0, vm_placement_policy_element)
            compute_policy_element.insert(
                1, E.VmPlacementPolicyFinal('false'))  # noqa: E501
        vm_placement_policy_element.set('href', placement_policy_href)
        vm_placement_policy_element.set('id', placement_policy_id)
        vm_placement_policy_element.set('type', 'application/json')

    if sizing_policy_href:
        sizing_policy_id = retrieve_compute_policy_id_from_href(
            sizing_policy_href)  # noqa: E501
        if hasattr(compute_policy_element, 'VmSizingPolicy'):
            if compute_policy_element.VmSizingPolicy.get(
                    'href', '') != sizing_policy_href:  # noqa: E501
                update_required = True
            vm_sizing_policy_element = compute_policy_element.VmSizingPolicy  # noqa: E501
        else:
            update_required = True
            vm_sizing_policy_element = E.VmSizingPolicy()
            compute_policy_element.append(vm_sizing_policy_element)
            compute_policy_element.append(E.VmSizingPolicyFinal('false'))
        vm_sizing_policy_element.set('href', sizing_policy_href)
        vm_sizing_policy_element.set('id', sizing_policy_id)
        vm_sizing_policy_element.set('type', 'application/json')

    return update_required
Example #16
0
    def add_subnet(self,
                   name,
                   gateway_ip,
                   netmask,
                   ip_ranges,
                   primary_dns_ip=None,
                   secondary_dns_ip=None,
                   dns_suffix=None):
        """Add subnet to an external network.

        :param str name: Name of external network.

        :param str gateway_ip: IP address of the gateway of the new network.

        :param str netmask: Netmask of the gateway.

        :param list ip_ranges: list of IP ranges used for static pool
            allocation in the network. For example, [192.168.1.2-192.168.1.49,
            192.168.1.100-192.168.1.149].

        :param str primary_dns_ip: IP address of primary DNS server.

        :param str secondary_dns_ip: IP address of secondary DNS Server.

        :param str dns_suffix: DNS suffix.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        if self.resource is None:
            self.reload()

        platform = Platform(self.client)
        ext_net = platform.get_external_network(name)
        config = ext_net['{' + NSMAP['vcloud'] + '}Configuration']
        ip_scopes = config.IpScopes

        ip_scope = E.IpScope()
        ip_scope.append(E.IsInherited(False))
        ip_scope.append(E.Gateway(gateway_ip))
        ip_scope.append(E.Netmask(netmask))
        if primary_dns_ip is not None:
            ip_scope.append(E.Dns1(primary_dns_ip))
        if secondary_dns_ip is not None:
            ip_scope.append(E.Dns2(secondary_dns_ip))
        if dns_suffix is not None:
            ip_scope.append(E.DnsSuffix(dns_suffix))
        e_ip_ranges = E.IpRanges()
        for ip_range in ip_ranges:
            e_ip_range = E.IpRange()
            ip_range_token = ip_range.split('-')
            e_ip_range.append(E.StartAddress(ip_range_token[0]))
            e_ip_range.append(E.EndAddress(ip_range_token[1]))
            e_ip_ranges.append(e_ip_range)
        ip_scope.append(e_ip_ranges)
        ip_scopes.append(ip_scope)

        return self.client.put_linked_resource(
            ext_net,
            rel=RelationType.EDIT,
            media_type=EntityType.EXTERNAL_NETWORK.value,
            contents=ext_net)
Example #17
0
 def connect_vm(self, mode='DHCP', reset_mac_address=False):
     if self.resource is None:
         self.resource = self.client.get_resource(self.href)
     if hasattr(self.resource, 'Children') and \
        hasattr(self.resource.Children, 'Vm') and \
        len(self.resource.Children.Vm) > 0:
         network_name = 'none'
         for nc in self.resource.NetworkConfigSection.NetworkConfig:
             if nc.get('networkName') != 'none':
                 network_name = nc.get('networkName')
                 break
         self.resource.Children.Vm[0].NetworkConnectionSection.NetworkConnection.set('network', network_name) # NOQA
         self.resource.Children.Vm[0].NetworkConnectionSection.NetworkConnection.IsConnected = E.IsConnected('true') # NOQA
         if reset_mac_address:
             self.resource.Children.Vm[0].NetworkConnectionSection.NetworkConnection.MACAddress = E.MACAddress('') # NOQA
         self.resource.Children.Vm[0].NetworkConnectionSection.NetworkConnection.IpAddressAllocationMode = E.IpAddressAllocationMode(mode.upper()) # NOQA
         return self.client.put_linked_resource(
             self.resource.Children.Vm[0].NetworkConnectionSection,
             RelationType.EDIT,
             EntityType.NETWORK_CONNECTION_SECTION.value,
             self.resource.Children.Vm[0].NetworkConnectionSection
             )
Example #18
0
    def add_vm(self):
        params = self.params
        source_vapp_resource = self.get_source_resource()
        target_vm_name = params.get('target_vm_name')
        source_vm_name = params.get('source_vm_name')
        hostname = params.get('hostname')
        vmpassword = params.get('vmpassword')
        vmpassword_auto = params.get('vmpassword_auto')
        vmpassword_reset = params.get('vmpassword_reset')
        network = params.get('network')
        all_eulas_accepted = params.get('all_eulas_accepted')
        power_on = params.get('power_on')
        ip_allocation_mode = params.get('ip_allocation_mode')
        cust_script = params.get('cust_script')
        storage_profile = params.get('storage_profile')
        properties = params.get('properties')
        response = dict()
        response['changed'] = False

        try:
            self.get_vm()
        except EntityNotFoundException:
            spec = {
                'source_vm_name': source_vm_name,
                'vapp': source_vapp_resource,
                'target_vm_name': target_vm_name,
                'hostname': hostname,
                'password': vmpassword,
                'password_auto': vmpassword_auto,
                'password_reset': vmpassword_reset,
                'ip_allocation_mode': ip_allocation_mode,
                'network': network,
                'cust_script': cust_script
            }
            if storage_profile != '':
                spec['storage_profile'] = self.get_storage_profile(
                    storage_profile)
            spec = {k: v for k, v in spec.items() if v}
            source_vm = self.vapp.to_sourced_item(spec)

            # Check the source vm if we need to inject OVF properties.
            source_vapp = VApp(self.client, resource=source_vapp_resource)
            vm = source_vapp.get_vm(source_vm_name)
            productsection = vm.find('ovf:ProductSection', NSMAP)
            if productsection is not None:
                for prop in productsection.iterfind('ovf:Property', NSMAP):
                    if properties and prop.get('{' + NSMAP['ovf'] +
                                               '}key') in properties:
                        val = prop.find('ovf:Value', NSMAP)
                        if val:
                            prop.remove(val)
                        val = E_OVF.Value()
                        val.set(
                            '{' + NSMAP['ovf'] + '}value',
                            properties[prop.get('{' + NSMAP['ovf'] + '}key')])
                        prop.append(val)
                source_vm.InstantiationParams.append(productsection)
                source_vm.VmGeneralParams.NeedsCustomization = E.NeedsCustomization(
                    'true')

            params = E.RecomposeVAppParams(
                deploy='true', powerOn='true' if power_on else 'false')
            params.append(source_vm)
            if all_eulas_accepted is not None:
                params.append(E.AllEULAsAccepted(all_eulas_accepted))

            add_vms_task = self.client.post_linked_resource(
                self.get_target_resource(), RelationType.RECOMPOSE,
                EntityType.RECOMPOSE_VAPP_PARAMS.value, params)
            self.execute_task(add_vms_task)
            response['msg'] = 'Vapp VM {} has been created.'.format(
                target_vm_name)
            response['changed'] = True
        else:
            response['warnings'] = 'Vapp VM {} is already present.'.format(
                target_vm_name)

        return response
Example #19
0
    def instantiate_vapp(self,
                         name,
                         catalog,
                         template,
                         network=None,
                         fence_mode='bridged',
                         ip_allocation_mode='dhcp',
                         deploy=True,
                         power_on=True,
                         accept_all_eulas=True,
                         memory=None,
                         cpu=None,
                         password=None,
                         cust_script=None):
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)

        network_href = None
        if hasattr(self.resource, 'AvailableNetworks') and \
           hasattr(self.resource.AvailableNetworks, 'Network'):
            for n in self.resource.AvailableNetworks.Network:
                if network is None or network == n.get('name'):
                    network_href = n.get('href')
                    network_name = n.get('name')
        if network_href is None:
            raise Exception('Network not found in the Virtual Datacenter.')

        org_href = find_link(self.resource, RelationType.UP,
                             EntityType.ORG.value).href
        org = Org(self.client, href=org_href)
        template_resource = org.get_catalog_item(catalog, template)
        v = self.client.get_resource(template_resource.Entity.get('href'))
        n = v.xpath(
            '//ovf:NetworkSection/ovf:Network',
            namespaces={'ovf': 'http://schemas.dmtf.org/ovf/envelope/1'})
        assert len(n) > 0
        network_name_from_template = n[0].get(
            '{http://schemas.dmtf.org/ovf/envelope/1}name')
        deploy_param = 'true' if deploy else 'false'
        power_on_param = 'true' if power_on else 'false'
        network_configuration = E.Configuration(
            E.ParentNetwork(href=network_href), E.FenceMode(fence_mode))
        # if fence_mode == 'natRouted':
        #     network_configuration.append(
        #         E.Features(
        #             E.NatService(
        #                 E.IsEnabled('true'),
        #                 E.NatType('ipTranslation'),
        #                 E.Policy('allowTraffic'),
        #                 E.NatRule(
        #                     E.OneToOneVmRule(
        #                         E.MappingMode('automatic'),
        #                         E.VAppScopedVmId(vm_id),
        #                         E.VmNicId(0)
        #                     )
        #                 )
        #             )
        #         )
        #     )
        vapp_network_name = network_name_from_template
        if vapp_network_name == 'none':
            vapp_network_name = network_name
        vapp_template_params = E.InstantiateVAppTemplateParams(
            name=name, deploy=deploy_param, powerOn=power_on_param)
        if network_name is not None:
            vapp_template_params.append(
                E.InstantiationParams(
                    E.NetworkConfigSection(
                        E_OVF.Info('Configuration for logical networks'),
                        E.NetworkConfig(network_configuration,
                                        networkName=vapp_network_name))))
        vapp_template_params.append(
            E.Source(href=template_resource.Entity.get('href')))
        vm = v.xpath('//vcloud:VAppTemplate/vcloud:Children/vcloud:Vm',
                     namespaces=NSMAP)
        assert len(vm) > 0
        ip = E.InstantiationParams()
        gc = E.GuestCustomizationSection(
            E_OVF.Info('Specifies Guest OS Customization Settings'),
            E.Enabled('false'),
        )
        if password is not None:
            gc.append(E.AdminPasswordEnabled('true'))
            gc.append(E.AdminPasswordAuto('false'))
            gc.append(E.AdminPassword(password))
            gc.append(E.ResetPasswordRequired('false'))
        else:
            gc.append(E.AdminPasswordEnabled('false'))
        if cust_script is not None:
            gc.append(E.CustomizationScript(cust_script))
        gc.Enabled = E.Enabled('true')
        gc.append(E.ComputerName(name))
        ip.append(gc)
        primary_index = int(
            vm[0].NetworkConnectionSection.PrimaryNetworkConnectionIndex.text)
        ip.append(
            E.NetworkConnectionSection(
                E_OVF.Info('Specifies the available VM network connections'),
                E.NetworkConnection(E.NetworkConnectionIndex(primary_index),
                                    E.IsConnected('true'),
                                    E.IpAddressAllocationMode(
                                        ip_allocation_mode.upper()),
                                    network=vapp_network_name)))
        if memory is not None:
            items = v.Children[0].Vm.xpath(
                '//ovf:VirtualHardwareSection/ovf:Item',
                namespaces={'ovf': 'http://schemas.dmtf.org/ovf/envelope/1'})
            for item in items:
                if item['{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}ResourceType'] == 4:  # NOQA
                    item[
                        '{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}ElementName'] = '%s MB of memory' % memory  # NOQA
                    item[
                        '{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}VirtualQuantity'] = memory  # NOQA
                    memory_params = item
                    break
        if cpu is not None:
            items = v.Children[0].Vm.xpath(
                '//ovf:VirtualHardwareSection/ovf:Item',
                namespaces={'ovf': 'http://schemas.dmtf.org/ovf/envelope/1'})
            for item in items:
                if item['{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}ResourceType'] == 3:  # NOQA
                    item[
                        '{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}ElementName'] = '%s virtual CPU(s)' % cpu  # NOQA
                    item[
                        '{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}VirtualQuantity'] = cpu  # NOQA
                    cpu_params = item
                    break

        if memory is not None or cpu is not None:
            vhs = E_OVF.VirtualHardwareSection(
                E_OVF.Info('Virtual hardware requirements'))
            if memory is not None:
                vhs.append(memory_params)
            if cpu is not None:
                vhs.append(cpu_params)
            ip.append(vhs)

        if password is None and cust_script is None:
            needs_customization = 'false'
        else:
            needs_customization = 'true'
        si = E.SourcedItem(
            E.Source(href=vm[0].get('href'),
                     id=vm[0].get('id'),
                     name=vm[0].get('name'),
                     type=vm[0].get('type')),
            E.VmGeneralParams(E.Name(name),
                              E.NeedsCustomization(needs_customization)), ip)
        # if network_name != network_name_from_template:
        #     si.append(E.NetworkAssignment(
        #         innerNetwork=network_name_from_template,
        #         containerNetwork=network_name))
        vapp_template_params.append(si)
        all_eulas_accepted = 'true' if accept_all_eulas else 'false'
        vapp_template_params.append(E.AllEULAsAccepted(all_eulas_accepted))
        return self.client.post_resource(
            self.href + '/action/instantiateVAppTemplate',
            vapp_template_params,
            EntityType.INSTANTIATE_VAPP_TEMPLATE_PARAMS.value)
Example #20
0
 def upload_ovf(self,
                catalog_name,
                file_name,
                item_name=None,
                description='',
                chunk_size=DEFAULT_CHUNK_SIZE,
                callback=None):
     catalog = self.get_catalog(catalog_name)
     if item_name is None:
         item_name = os.path.basename(file_name)
     tempdir = tempfile.mkdtemp(dir='.')
     total_bytes = 0
     try:
         ova = tarfile.open(file_name)
         ova.extractall(path=tempdir)
         ova.close()
         ovf_file = None
         files = os.listdir(tempdir)
         for f in files:
             fn, ex = os.path.splitext(f)
             if ex == '.ovf':
                 ovf_file = os.path.join(tempdir, f)
                 break
         if ovf_file is not None:
             stat_info = os.stat(ovf_file)
             total_bytes += stat_info.st_size
             ovf = objectify.parse(ovf_file)
             files = []
             ns = '{' + NSMAP['ovf'] + '}'
             for f in ovf.getroot().References.File:
                 source_file = {
                     'href': f.get(ns + 'href'),
                     'name': f.get(ns + 'id'),
                     'size': f.get(ns + 'size')
                 }
                 files.append(source_file)
             if item_name is None:
                 item_name = os.path.basename(file_name)
             params = E.UploadVAppTemplateParams(name=item_name)
             params.append(E.Description(description))
             catalog_item = self.client.post_resource(
                 catalog.get('href') + '/action/upload', params,
                 EntityType.UPLOAD_VAPP_TEMPLATE_PARAMS.value)
             entity = self.client.get_resource(
                 catalog_item.Entity.get('href'))
             file_href = entity.Files.File.Link.get('href')
             self.client.put_resource(file_href, ovf, 'text/xml')
             while True:
                 time.sleep(5)
                 entity = self.client.get_resource(
                     catalog_item.Entity.get('href'))
                 if len(entity.Files.File) > 1:
                     break
             for source_file in files:
                 for target_file in entity.Files.File:
                     if source_file.get('href') == target_file.get('name'):
                         file_path = os.path.join(tempdir,
                                                  source_file.get('href'))
                         total_bytes += self.upload_file(
                             file_path,
                             target_file.Link.get('href'),
                             chunk_size=chunk_size,
                             callback=callback)
         shutil.rmtree(tempdir)
     except Exception as e:
         print(traceback.format_exc())
         shutil.rmtree(tempdir)
         raise e
     return total_bytes
Example #21
0
    def instantiate_vapp(self,
                         name,
                         catalog,
                         template,
                         network=None,
                         fence_mode=FenceMode.BRIDGED.value,
                         ip_allocation_mode='dhcp',
                         deploy=True,
                         power_on=True,
                         accept_all_eulas=False,
                         memory=None,
                         cpu=None,
                         disk_size=None,
                         password=None,
                         cust_script=None,
                         vm_name=None,
                         hostname=None,
                         storage_profile=None):
        """Instantiate a vApp from a vApp template in a catalog.

        If customization parameters are provided, it will customize the VM and
        guest OS, taking some assumptions.
        See each parameter for details.

        :param name: (str): The name of the new vApp.
        :param catalog: (str): The name of the catalog.
        :param template: (str): The name of the vApp template.
        :param network: (str): The name of a vdc network.
            When provided, connects the VM to the network.
            It assumes one VM in the vApp and one NIC in the VM.
        :param fence_mode: (str): Fence mode.
            Possible values are `bridged` and `natRouted`
        :param ip_allocation_mode: (str): IP allocation mode.
            Possible values are `pool`, `dhcp` and `static`
        :param deploy: (bool):
        :param power_on: (bool):
        :param accept_all_eulas: (bool): True confirms acceptance of all EULAs
            in a vApp template.
        :param memory: (int):
        :param cpu: (int):
        :param disk_size: (int):
        :param password: (str):
        :param cust_script: (str):
        :param vm_name: (str): When provided, set the name of the VM.
            It assumes one VM in the vApp.
        :param hostname: (str): When provided, set the hostname of the guest
            OS. It assumes one VM in the vApp.
        :param storage_profile: (str):

        :return:  A :class:`lxml.objectify.StringElement` object describing the
            new vApp.
        """
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)

        # Get hold of the template
        org_href = find_link(self.resource, RelationType.UP,
                             EntityType.ORG.value).href
        org = Org(self.client, href=org_href)
        catalog_item = org.get_catalog_item(catalog, template)
        template_resource = self.client.get_resource(
            catalog_item.Entity.get('href'))

        # If network is not specified by user then default to
        # vApp network name specified in the template
        template_networks = template_resource.xpath(
            '//ovf:NetworkSection/ovf:Network',
            namespaces={'ovf': NSMAP['ovf']})
        assert len(template_networks) > 0
        network_name_from_template = template_networks[0].get('{' +
                                                              NSMAP['ovf'] +
                                                              '}name')
        if ((network is None) and (network_name_from_template != 'none')):
            network = network_name_from_template

        # Find the network in vdc referred to by user, using
        # name of the network
        network_href = network_name = None
        if network is not None:
            if hasattr(self.resource, 'AvailableNetworks') and \
               hasattr(self.resource.AvailableNetworks, 'Network'):
                for n in self.resource.AvailableNetworks.Network:
                    if network == n.get('name'):
                        network_href = n.get('href')
                        network_name = n.get('name')
                        break
            if network_href is None:
                raise Exception(
                    'Network \'%s\' not found in the Virtual Datacenter.' %
                    network)

        # Configure the network of the vApp
        vapp_instantiation_param = None
        if network_name is not None:
            network_configuration = E.Configuration(
                E.ParentNetwork(href=network_href), E.FenceMode(fence_mode))

            if fence_mode == 'natRouted':
                # TODO(need to find the vm_id)
                vm_id = None
                network_configuration.append(
                    E.Features(
                        E.NatService(
                            E.IsEnabled('true'), E.NatType('ipTranslation'),
                            E.Policy('allowTraffic'),
                            E.NatRule(
                                E.OneToOneVmRule(E.MappingMode('automatic'),
                                                 E.VAppScopedVmId(vm_id),
                                                 E.VmNicId(0))))))

            vapp_instantiation_param = E.InstantiationParams(
                E.NetworkConfigSection(
                    E_OVF.Info('Configuration for logical networks'),
                    E.NetworkConfig(network_configuration,
                                    networkName=network_name)))

        # Get all vms in the vapp template
        vms = template_resource.xpath(
            '//vcloud:VAppTemplate/vcloud:Children/vcloud:Vm',
            namespaces=NSMAP)
        assert len(vms) > 0

        vm_instantiation_param = E.InstantiationParams()

        # Configure network of the first vm
        if network_name is not None:
            primary_index = int(vms[0].NetworkConnectionSection.
                                PrimaryNetworkConnectionIndex.text)
            vm_instantiation_param.append(
                E.NetworkConnectionSection(
                    E_OVF.Info(
                        'Specifies the available VM network connections'),
                    E.NetworkConnection(
                        E.NetworkConnectionIndex(primary_index),
                        E.IsConnected('true'),
                        E.IpAddressAllocationMode(ip_allocation_mode.upper()),
                        network=network_name)))

        # Configure cpu, memory, disk of the first vm
        cpu_params = memory_params = disk_params = None
        if memory is not None or cpu is not None or disk_size is not None:
            virtual_hardware_section = E_OVF.VirtualHardwareSection(
                E_OVF.Info('Virtual hardware requirements'))
            items = vms[0].xpath('//ovf:VirtualHardwareSection/ovf:Item',
                                 namespaces={'ovf': NSMAP['ovf']})
            for item in items:
                if memory is not None and memory_params is None:
                    if item['{' + NSMAP['rasd'] + '}ResourceType'] == 4:
                        item['{' + NSMAP['rasd'] +
                             '}ElementName'] = '%s MB of memory' % memory
                        item['{' + NSMAP['rasd'] + '}VirtualQuantity'] = memory
                        memory_params = item
                        virtual_hardware_section.append(memory_params)

                if cpu is not None and cpu_params is None:
                    if item['{' + NSMAP['rasd'] + '}ResourceType'] == 3:
                        item['{' + NSMAP['rasd'] +
                             '}ElementName'] = '%s virtual CPU(s)' % cpu
                        item['{' + NSMAP['rasd'] + '}VirtualQuantity'] = cpu
                        cpu_params = item
                        virtual_hardware_section.append(cpu_params)

                if disk_size is not None and disk_params is None:
                    if item['{' + NSMAP['rasd'] + '}ResourceType'] == 17:
                        item['{' + NSMAP['rasd'] + '}Parent'] = None
                        item['{' + NSMAP['rasd'] + '}HostResource'].attrib[
                            '{' + NSMAP['vcloud'] +
                            '}capacity'] = '%s' % disk_size
                        item['{' + NSMAP['rasd'] +
                             '}VirtualQuantity'] = disk_size * 1024 * 1024
                        disk_params = item
                        virtual_hardware_section.append(disk_params)
            vm_instantiation_param.append(virtual_hardware_section)

        # Configure guest customization for the vm
        if password is not None or cust_script is not None or \
           hostname is not None:
            guest_customization_param = E.GuestCustomizationSection(
                E_OVF.Info('Specifies Guest OS Customization Settings'),
                E.Enabled('true'),
            )
            if password is None:
                guest_customization_param.append(
                    E.AdminPasswordEnabled('false'))
            else:
                guest_customization_param.append(
                    E.AdminPasswordEnabled('true'))
                guest_customization_param.append(E.AdminPasswordAuto('false'))
                guest_customization_param.append(E.AdminPassword(password))
                guest_customization_param.append(
                    E.ResetPasswordRequired('false'))
            if cust_script is not None:
                guest_customization_param.append(
                    E.CustomizationScript(cust_script))
            if hostname is not None:
                guest_customization_param.append(E.ComputerName(hostname))
            vm_instantiation_param.append(guest_customization_param)

        # Craft the <SourcedItem> element for the first VM
        sourced_item = E.SourcedItem(
            E.Source(href=vms[0].get('href'),
                     id=vms[0].get('id'),
                     name=vms[0].get('name'),
                     type=vms[0].get('type')))

        vm_general_params = E.VmGeneralParams()
        if vm_name is not None:
            vm_general_params.append(E.Name(vm_name))

        # TODO(check if it needs customization if network, cpu or memory...)
        if disk_size is None and \
           password is None and \
           cust_script is None and \
           hostname is None:
            needs_customization = 'false'
        else:
            needs_customization = 'true'
        vm_general_params.append(E.NeedsCustomization(needs_customization))
        sourced_item.append(vm_general_params)
        sourced_item.append(vm_instantiation_param)

        if storage_profile is not None:
            sp = self.get_storage_profile(storage_profile)
            vapp_storage_profile = E.StorageProfile(
                href=sp.get('href'),
                id=sp.get('href').split('/')[-1],
                type=sp.get('type'),
                name=sp.get('name'))
            sourced_item.append(vapp_storage_profile)

        # Cook the entire vApp Template instantiation element
        deploy_param = 'true' if deploy else 'false'
        power_on_param = 'true' if power_on else 'false'
        all_eulas_accepted = 'true' if accept_all_eulas else 'false'

        vapp_template_params = E.InstantiateVAppTemplateParams(
            name=name, deploy=deploy_param, powerOn=power_on_param)

        if vapp_instantiation_param is not None:
            vapp_template_params.append(vapp_instantiation_param)

        vapp_template_params.append(
            E.Source(href=catalog_item.Entity.get('href')))

        vapp_template_params.append(sourced_item)

        vapp_template_params.append(E.AllEULAsAccepted(all_eulas_accepted))

        # TODO(use post_linked_resource?)
        return self.client.post_resource(
            self.href + '/action/instantiateVAppTemplate',
            vapp_template_params,
            EntityType.INSTANTIATE_VAPP_TEMPLATE_PARAMS.value)
Example #22
0
    def create_org_vdc(self,
                       vdc_name,
                       provider_vdc_name,
                       description='',
                       allocation_model='AllocationVApp',
                       cpu_units='MHz',
                       cpu_allocated=0,
                       cpu_limit=0,
                       mem_units='MB',
                       mem_allocated=0,
                       mem_limit=0,
                       nic_quota=0,
                       network_quota=0,
                       vm_quota=0,
                       storage_profiles=[],
                       resource_guaranteed_memory=None,
                       resource_guaranteed_cpu=None,
                       vcpu_in_mhz=None,
                       is_thin_provision=None,
                       network_pool_name=None,
                       uses_fast_provisioning=None,
                       over_commit_allowed=None,
                       vm_discovery_enabled=None,
                       is_enabled=True):
        """Create Organization VDC in the current Org.

        :param vdc_name (str): The name of the new org vdc.
        :param provider_vdc_name (str): The name of an existing provider vdc.
        :param description (str): The description of the new org vdc.
        :param allocation_model (str): The allocation model used by this vDC.
            One of AllocationVApp, AllocationPool or ReservationPool.
        :param cpu_units (str): The cpu units compute capacity allocated to
            this vDC. One of MHz or GHz
        :param cpu_allocated (int): Capacity that is committed to be available.
        :param cpu_limit (int): Capacity limit relative to the value specified
            for Allocation.
        :param mem_units (str): The memory units compute capacity allocated to
            this vDC. One of MB or GB.
        :param mem_allocated (int): Memory capacity that is committed to be
            available.
        :param mem_limit (int): Memory capacity limit relative to the value
            specified for Allocation.
        :param nic_quota (int): Maximum number of virtual NICs allowed in this
            vDC. Defaults to 0, which specifies an unlimited number.
        :param network_quota (int): Maximum number of network objects that can
            be deployed in this vDC. Defaults to 0, which means no networks can
            be deployed.
        :param vm_quota (int): The maximum number of VMs that can be created in
            this vDC. Defaults to 0, which specifies an unlimited number.
        :param storage_profiles: List of provider vDC storage profiles to add
            to this vDC.
            Each item is a dictionary that should include the following
                elements:
                name: (string) name of the PVDC storage profile.
                enabled: (bool) True if the storage profile is enabled for this
                    vDC.
                units: (string) Units used to define limit. One of MB or GB.
                limit: (int) Max number of units allocated for this storage
                    profile.
                default: (bool) True if this is default storage profile for
                    this vDC.
        :param resource_guaranteed_memory (float): Percentage of allocated CPU
            resources guaranteed to vApps deployed in this vDC.
            Value defaults to 1.0 if the element is empty.
        :param resource_guaranteed_cpu (float): Percentage of allocated memory
            resources guaranteed to vApps deployed in this vDC.
            Value defaults to 1.0 if the element is empty.
        :param vcpu_in_mhz (int): Specifies the clock frequency, in Megahertz,
            for any virtual CPU that is allocated to a VM.
        :param is_thin_provision (bool): Boolean to request thin provisioning.
        :param network_pool_name (str): Reference to a network pool in the
            Provider vDC.
        :param uses_fast_provisioning (bool): Boolean to request fast
            provisioning.
        :param over_commit_allowed (bool): Set to false to disallow creation of
            the VDC if the AllocationModel is AllocationPool or ReservationPool
            and the ComputeCapacity you specified is greater than what the
            backing Provider VDC can supply. Defaults to true if empty or
            missing.
        :param vm_discovery_enabled (bool): True if discovery of vCenter VMs
            is enabled for resource pools backing this vDC.
        :param is_enabled (bool): True if this vDC is enabled for use by the
            organization users.
        :return:  A :class:`lxml.objectify.StringElement` object describing
            the new VDC.
        """
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)
        sys_admin_resource = self.client.get_admin()
        system = System(self.client, admin_resource=sys_admin_resource)
        pvdc = system.get_provider_vdc(provider_vdc_name)
        resource_admin = self.client.get_resource(self.href_admin)
        params = E.CreateVdcParams(E.Description(description),
                                   E.AllocationModel(allocation_model),
                                   E.ComputeCapacity(
                                       E.Cpu(E.Units(cpu_units),
                                             E.Allocated(cpu_allocated),
                                             E.Limit(cpu_limit)),
                                       E.Memory(E.Units(mem_units),
                                                E.Allocated(mem_allocated),
                                                E.Limit(mem_limit))),
                                   E.NicQuota(nic_quota),
                                   E.NetworkQuota(network_quota),
                                   E.VmQuota(vm_quota),
                                   E.IsEnabled(is_enabled),
                                   name=vdc_name)
        for sp in storage_profiles:
            pvdc_sp = system.get_provider_vdc_storage_profile(sp['name'])
            params.append(
                E.VdcStorageProfile(
                    E.Enabled(sp['enabled']), E.Units(sp['units']),
                    E.Limit(sp['limit']), E.Default(sp['default']),
                    E.ProviderVdcStorageProfile(href=pvdc_sp.get('href'))))
        if resource_guaranteed_memory is not None:
            params.append(
                E.ResourceGuaranteedMemory(resource_guaranteed_memory))
        if resource_guaranteed_cpu is not None:
            params.append(E.ResourceGuaranteedCpu(resource_guaranteed_cpu))
        if vcpu_in_mhz is not None:
            params.append(E.VCpuInMhz(vcpu_in_mhz))
        if is_thin_provision is not None:
            params.append(E.IsThinProvision(is_thin_provision))
        if network_pool_name is not None:
            npr = system.get_network_pool_reference(network_pool_name)
            href = npr.get('href')
            params.append(
                E.NetworkPoolReference(href=href,
                                       id=href.split('/')[-1],
                                       type=npr.get('type'),
                                       name=npr.get('name')))
        params.append(pvdc)
        if uses_fast_provisioning is not None:
            params.append(E.UsesFastProvisioning(uses_fast_provisioning))
        if over_commit_allowed is not None:
            params.append(E.OverCommitAllowed(over_commit_allowed))
        if vm_discovery_enabled is not None:
            params.append(E.VmDiscoveryEnabled(vm_discovery_enabled))
        return self.client.post_linked_resource(resource_admin,
                                                RelationType.ADD,
                                                EntityType.VDCS_PARAMS.value,
                                                params)
Example #23
0
    def create_isolated_vdc_network(self,
                                    network_name,
                                    gateway_ip,
                                    netmask,
                                    description=None,
                                    primary_dns_ip=None,
                                    secondary_dns_ip=None,
                                    dns_suffix=None,
                                    ip_range_start=None,
                                    ip_range_end=None,
                                    is_dhcp_enabled=None,
                                    default_lease_time=None,
                                    max_lease_time=None,
                                    dhcp_ip_range_start=None,
                                    dhcp_ip_range_end=None,
                                    is_shared=None):
        """Create a new isolated OrgVdc network in this vdc.

        :param network_name: (str): Name of the new network.
        :param gateway_ip: (str): IP address of the gateway of the new network.
        :param netmask: (str): Network mask.
        :param description: (str): Description of the new network.
        :param primary_dns_ip: (str): IP address of primary DNS server.
        :param secondary_dns_ip: (str): IP address of secondary DNS Server.
        :param dns_suffix: (str): DNS suffix.
        :param ip_range_start: (str): Start address of the IP ranges used for
            static pool allocation in the network.
        :param ip_range_end: (str): End address of the IP ranges used for
            static pool allocation in the network.
        :param is_dhcp_enabled: (bool): Is DHCP service enabled on the new
            network.
        :param default_lease_time: (int): Default lease in seconds for DHCP
            addresses.
        :param max_lease_time: (int): Max lease in seconds for DHCP addresses.
        :param dhcp_ip_range_start: (str): Start address of the IP range
            used for DHCP addresses.
        :param dhcp_ip_range_end: (str): End address of the IP range used for
            DHCP addresses.
        :param is_shared: (bool): True, if the network is shared with other
            vdc(s) in the organization, else False.

        :return: A :class:`lxml.objectify.StringElement` object representing
            a sparsely populated OrgVdcNetwork element.
        """
        if self.resource is None:
            self.resource = self.client.get_resource(self.href)

        request_payload = E.OrgVdcNetwork(name=network_name)
        if description is not None:
            request_payload.append(E.Description(description))

        vdc_network_configuration = E.Configuration()
        ip_scope = E.IpScope()
        ip_scope.append(E.IsInherited('false'))
        ip_scope.append(E.Gateway(gateway_ip))
        ip_scope.append(E.Netmask(netmask))
        if primary_dns_ip is not None:
            ip_scope.append(E.Dns1(primary_dns_ip))
        if secondary_dns_ip is not None:
            ip_scope.append(E.Dns2(secondary_dns_ip))
        if dns_suffix is not None:
            ip_scope.append(E.DnsSuffix(dns_suffix))
        if ip_range_start is not None and ip_range_end is not None:
            ip_range = E.IpRange()
            ip_range.append(E.StartAddress(ip_range_start))
            ip_range.append(E.EndAddress(ip_range_end))
            ip_scope.append(E.IpRanges(ip_range))
        vdc_network_configuration.append(E.IpScopes(ip_scope))
        vdc_network_configuration.append(E.FenceMode(FenceMode.ISOLATED.value))
        request_payload.append(vdc_network_configuration)

        dhcp_service = E.DhcpService()
        if is_dhcp_enabled is not None:
            dhcp_service.append(E.IsEnabled(is_dhcp_enabled))
        if default_lease_time is not None:
            dhcp_service.append(E.DefaultLeaseTime(str(default_lease_time)))
        if max_lease_time is not None:
            dhcp_service.append(E.MaxLeaseTime(str(max_lease_time)))
        if dhcp_ip_range_start is not None and dhcp_ip_range_end is not None:
            dhcp_ip_range = E.IpRange()
            dhcp_ip_range.append(E.StartAddress(dhcp_ip_range_start))
            dhcp_ip_range.append(E.EndAddress(dhcp_ip_range_end))
            dhcp_service.append(dhcp_ip_range)
        request_payload.append(E.ServiceConfig(dhcp_service))

        if is_shared is not None:
            request_payload.append(E.IsShared(is_shared))

        return self.client.post_linked_resource(
            self.resource, RelationType.ADD, EntityType.ORG_VDC_NETWORK.value,
            request_payload)
Example #24
0
 def _makeNatServiceAttr(features):
     nat_service = E.NatService()
     nat_service.append(E.IsEnabled(True))
     nat_service.append(E.NatType('ipTranslation'))
     nat_service.append(E.Policy('allowTrafficIn'))
     features.append(nat_service)
Example #25
0
    def validate_add_nic(self):
        '''
            Error - More than 10 Nics are not permissible in vCD
        '''
        vm = self.get_vm()
        vm_name = self.params.get('vm_name')
        nic_id = self.params.get('nic_id')
        network = self.params.get('network')
        ip_address = self.params.get('ip_address')
        ip_allocation_mode = self.params.get('ip_allocation_mode')
        adapter_type = self.params.get('adapter_type')
        uri = vm.resource.get('href') + '/networkConnectionSection'
        response = defaultdict(dict)
        response['changed'] = False
        new_nic_id = None
        network_section = self.net_connection_section_obj_create()
        net_conn = self.net_connection_obj_create()
        nics = self.get_vm_nics()
        nics_indexes = [
            int(nic.NetworkConnectionIndex) for nic in nics.NetworkConnection
        ]
        nics_indexes.sort()

        for nic in nics.NetworkConnection:
            if nic.NetworkConnectionIndex == nic_id:
                response[
                    'warnings'] = 'Validate add: NIC {} is already present on VM {}'.format(
                        nic_id, vm_name)
                return response

        if not adapter_type:
            nics_adapters = [
                int(nic.NetworkAdapterType) for nic in nics.NetworkConnection
            ]
            adapter_type = nics_adapters[
                0]  # select the first nic NetworkAdapterType

        if nic_id is None or nic_id < 0:
            for index, nic_index in enumerate(nics_indexes):
                new_nic_id = nic_index + 1
                if index != nic_index:
                    new_nic_id = index
                    break
            nic_id = new_nic_id

        if ip_allocation_mode not in ('DHCP', 'POOL', 'MANUAL'):
            raise Exception(
                'IpAllocationMode should be one of DHCP/POOL/MANUAL')

        if ip_allocation_mode in ('DHCP', 'POOL'):
            nic = E.NetworkConnection(
                E.NetworkConnectionIndex(nic_id),
                E.IsConnected(True),
                E.IpAddressAllocationMode(ip_allocation_mode),
                E.NetworkAdapterType(adapter_type),
                network=network)
        else:
            if not ip_address:
                raise Exception('IpAddress is missing.')
            nic = E.NetworkConnection(
                E.NetworkConnectionIndex(nic_id),
                E.IpAddress(ip_address),
                E.IsConnected(True),
                E.IpAddressAllocationMode(ip_allocation_mode),
                E.NetworkAdapterType(adapter_type),
                network=network)

        nics.NetworkConnection.addnext(nic)
        add_nic_task = self.client.put_resource(
            uri, nics, EntityType.NETWORK_CONNECTION_SECTION.value)
        self.execute_task(add_nic_task)
        response['msg'] = {
            'nic_id': nic_id,
            'adapter_type': adapter_type,
            'ip_allocation_mode': ip_allocation_mode,
            'ip_address': ip_address,
            'network': network,
            'Validate add: ': 'true'
        }
        response['changed'] = True

        return response
Example #26
0
    def validate_nic(self):
        '''
            Following update scenarios are covered
            1. IP allocation mode change: DHCP, POOL, MANUAL
            2. Update IP address in MANUAL mode
            3. Network change
        '''
        vm = self.get_vm()
        nic_id = self.params.get('nic_id')
        network = self.params.get('network')
        ip_address = self.params.get('ip_address')
        adapter_type = self.params.get('adapter_type')
        is_connected = self.params.get('is_connected')
        ip_allocation_mode = self.params.get('ip_allocation_mode')
        uri = vm.resource.get('href') + '/networkConnectionSection'
        response = defaultdict(dict)
        response['changed'] = False
        vm_name = self.params.get('vm_name')
        nics = self.get_vm_nics()
        nic_indexes = []
        if hasattr(nics, "NetworkConnection"):
            # If we find attr in nics object
            for nic in nics.NetworkConnection:
                nic_indexes.append(nic.NetworkConnectionIndex)
                self.nic_indexes = nic_indexes
                return self.nic_indexes
        else:
            #if getattr(nics, 'NetworkConnection', None):
            # Go add nic because no any adapters are present in VM
            #   we find attr in nics object
            # nic_id = self.params.get('nic_id')
            # nic = E.NetworkConnection(
            #     E.NetworkConnectionIndex(nic_id),
            #     E.IpAddress(ip_address),
            #     E.IsConnected(True),
            #     E.IpAddressAllocationMode(ip_allocation_mode),
            #     network=network)
            add_nic_task = vm.add_nic(adapter_type=adapter_type,
                                      is_connected=is_connected,
                                      network_name=network,
                                      ip_address_mode=ip_allocation_mode,
                                      ip_address=ip_address,
                                      nic_id=nic_id)
            self.execute_task(add_nic_task)
            response['msg'] = {
                'nic_id': nic_id,
                'adapter_type': adapter_type,
                'ip_allocation_mode': ip_allocation_mode,
                'ip_address': ip_address,
                'network': network,
                'is_connected': is_connected,
                'malinki': "vecerinki"
            }
            response['changed'] = True
            nics = self.vm.list_nics()
            nic_indexes = [
                nic.NetworkConnectionIndex for nic in nics.NetworkConnection
            ]
            # for nic in nics.NetworkConnection:
            #     nic_indexes.append(nic.NetworkConnectionIndex)
            #     self.nic_indexes = nic_indexes
            #     return self.nic_indexes
            return response
        #     # adding_nic = self.execute_task(add_nic_task)
        #     nics.NetworkConnection.addnext(nic_id)
        #     #add_nic_task = self.client.put_resource(uri, nics, EntityType.NETWORK_CONNECTION_SECTION.value)
        #     self.execute_task(add_nic_task)
        #     response['msg'] = {
        #         'VM': vm_name,
        #         'A added nic with ID:': nic_id,
        #         'ip_allocation_mode': ip_allocation_mode,
        #         'ip_address': ip_address,
        #         'we_at_here': "we_at_here"
        #     }
        #     response['changed'] = True
        #     return response

        #     # response['msg'] = 'A new nic has been added to VM {0}, NICs list: {1}'.format(vm_name,str(nics))
        #     # response['changed'] = True
        #     # return self.add_nic()
        # #else:

        if nic_id not in nic_indexes:
            response['changed'] = 'go add NIC, because his not are found.'
            return self.validate_add_nic()
            #response['warnings'] = 'NIC not found.'
            # nic_to_update = nic_indexes.index(nic_id)
        if network:
            nics.NetworkConnection[nic_id].set('network', network)
            response['changed'] = True

        if ip_allocation_mode:
            allocation_mode_element = E.IpAddressAllocationMode(
                ip_allocation_mode)
            nics.NetworkConnection[
                nic_id].IpAddressAllocationMode = allocation_mode_element
            response['changed'] = True

        if ip_address:
            response['changed'] = True
            if hasattr(nics.NetworkConnection[nic_id], 'IpAddress'):
                nics.NetworkConnection[nic_id].IpAddress = E.IpAddress(
                    ip_address)
            else:
                network = nics.NetworkConnection[nic_id].get('network')
                nics.NetworkConnection[nic_id] = E.NetworkConnection(
                    E.NetworkConnectionIndex(nic_id),
                    E.IpAddress(ip_address),
                    E.IsConnected(True),
                    E.IpAddressAllocationMode(ip_allocation_mode),
                    network=network)

        if response['changed']:
            update_nic_task = self.client.put_resource(
                uri, nics, EntityType.NETWORK_CONNECTION_SECTION.value)
            self.execute_task(update_nic_task)
            response['msg'] = 'vApp VM nic has been updated.'

        return response
Example #27
0
    def create_vapp_network(self,
                            name,
                            network_cidr,
                            description=None,
                            primary_dns_ip=None,
                            secondary_dns_ip=None,
                            dns_suffix=None,
                            ip_ranges=None,
                            is_guest_vlan_allowed=False):
        """Create a vApp network.

        :param str network_name: name of vApp network to be created.
        :param str network_cidr: CIDR in the format of 192.168.1.1/24.
        :param str description: description of vApp network.
        :param str primary_dns_ip: IP address of primary DNS server.
        :param str secondary_dns_ip: IP address of secondary DNS Server.
        :param str dns_suffix: DNS suffix.
        :params list ip_ranges: list of IP ranges used for static pool
            allocation in the network. For example, [192.168.1.2-192.168.1.49,
            192.168.1.100-192.168.1.149].

        :return: an object containing EntityType.TASK XML data which represents
            the asynchronous task that is creating the vApp network.

        :rtype: lxml.objectify.ObjectifiedElement
        """
        network_config_section = \
            deepcopy(self.resource.NetworkConfigSection)
        network_config = E.NetworkConfig(networkName=name)
        if description is not None:
            network_config.append(E.Description(description))

        config = E.Configuration()
        ip_scopes = E.IpScopes()
        ip_scope = E.IpScope()

        ip_scope.append(E.IsInherited(False))
        gateway_ip, netmask = cidr_to_netmask(network_cidr)
        ip_scope.append(E.Gateway(gateway_ip))
        ip_scope.append(E.Netmask(netmask))
        if primary_dns_ip is not None:
            ip_scope.append(E.Dns1(primary_dns_ip))
        if secondary_dns_ip is not None:
            ip_scope.append(E.Dns2(secondary_dns_ip))
        if dns_suffix is not None:
            ip_scope.append(E.DnsSuffix(dns_suffix))

        e_ip_ranges = E.IpRanges()
        for ip_range in ip_ranges:
            e_ip_range = E.IpRange()
            ip_range_token = ip_range.split('-')
            e_ip_range.append(E.StartAddress(ip_range_token[0]))
            e_ip_range.append(E.EndAddress(ip_range_token[1]))
            e_ip_ranges.append(e_ip_range)

        ip_scope.append(e_ip_ranges)
        ip_scopes.append(ip_scope)
        config.append(ip_scopes)
        config.append(E.FenceMode(FenceMode.ISOLATED.value))
        config.append(E.GuestVlanAllowed(is_guest_vlan_allowed))
        network_config.append(config)

        network_config_section.append(network_config)
        return self.client.put_linked_resource(
            self.resource.NetworkConfigSection, RelationType.EDIT,
            EntityType.NETWORK_CONFIG_SECTION.value, network_config_section)