Пример #1
0
    def _create_duplicate_app_connectors_requests(
        self, app: ReservationAppResource, app_connectors: List[Connector],
        new_app_name: str
    ) -> Tuple[List[SetConnectorRequest], List[ConnectorsAttrUpdateRequest]]:
        # Copy all attribute values for connectors including vnic requests set before
        set_connector_requests = []
        connectors_attr_updates = []
        for connector in app_connectors:
            atts_with_values = [
                AttributeNameValue(att.Name, att.Value)
                for att in connector.Attributes if att.Value
            ]
            source = None
            target = None

            if connector.Target == app.Name:
                source = connector.Source
                target = new_app_name

            if connector.Source == app.Name:
                source = new_app_name
                target = connector.Target

            connector_request = SetConnectorRequest(source, target, 'bi', '')
            set_connector_requests.append(connector_request)
            if atts_with_values:
                connectors_attr_updates.append(
                    ConnectorsAttrUpdateRequest(source, target,
                                                atts_with_values))

        return set_connector_requests, connectors_attr_updates
Пример #2
0
 def connect_ports_with_connector(self, reservation_id: ReservationId,
                                  port1: str, port2: str,
                                  connector_name: str):
     """Connect two ports with connector."""
     logger.info(f"Creating connector between {port1} and {port2}")
     connector = SetConnectorRequest(port1, port2, "bi", connector_name)
     self._api.SetConnectorsInReservation(reservation_id, [connector])
     self._api.ConnectRoutesInReservation(reservation_id, [port1, port2],
                                          "bi")
Пример #3
0
 def update_connector(self, connector):
     """
     :param cloudshell.migration.entities.Connector connector:
     :return:
     """
     self._logger.debug('Updating connector {}'.format(connector))
     self._api.SetConnectorsInReservation(connector.reservation_id, [
         SetConnectorRequest(connector.source, connector.target,
                             connector.direction, connector.alias)
     ])
 def create_health_check_services(self, source: str, aliases: Optional[dict] = None) -> None:
     """ Create health check service and connect it to to the requested source. """
     if not aliases:
         aliases = {HEALTH_CHECK_STATUS_MODEL: 'none'}
     for alias, status_selector in aliases.items():
         attributes = [AttributeNameValue(f'{HEALTH_CHECK_STATUS_MODEL}.status_selector', status_selector)]
         self.session.AddServiceToReservation(self.reservation_id, HEALTH_CHECK_STATUS_MODEL, alias, attributes)
         connector = SetConnectorRequest(source, alias, Direction='bi', Alias=alias)
         self.session.SetConnectorsInReservation(self.reservation_id, [connector])
     wait_for_services(self.session, self.reservation_id, list(aliases.keys()), timeout=8)
     wait_for_connectors(self.session, self.reservation_id, list(aliases.keys()))
Пример #5
0
def move_connectors_of(api, resid, oldresource, mapfunc, logger):
    """

    :param api: CloudShellAPISession
    :param resid: str
    :param oldresource: str
    :param mapfunc: (str) -> (str) : full path of new connector endpoint from old endpoint
    :param logger: Logger
    :return:
    """
    connectors = get_connectors_of(api, resid, oldresource)
    logger.info('All connectors before move: %s' % [(c.Source, c.Target) for c in connectors])

    delete_connectors(api, resid, connectors)

    ab = []
    movehist = []
    for c in connectors:
        if c.Source.startswith(oldresource + '/'):
            a, b = mapfunc(c.Source), c.Target
            ab.append((a, b, c.Direction, c.Alias, c.Attributes))
            movehist.append((c.Source, c.Target, a, b))
        if c.Target.startswith(oldresource + '/'):
            a, b = c.Source, mapfunc(c.Target)
            ab.append((a, b, c.Direction, c.Alias, c.Attributes))
            movehist.append((c.Source, c.Target, a, b))

    if ab:
        api.SetConnectorsInReservation(resid, [
            SetConnectorRequest(a, b, direction, alias) for a, b, direction, alias, _ in ab
        ])
    for _, _, a, b, attrs in ab:
        if attrs and attrs[0].Name:
            api.SetConnectorAttributes(resid, a, b, attrs)
    logger.info('Moved connectors: %s' % ['%s -- %s  ->  %s -- %s' % (a, b, c, d) for a, b, c, d in movehist])
    rd = api.GetReservationDetails(resid).ReservationDescription
    logger.info('All connectors after move: %s' % [(c.Source, c.Target) for c in rd.Connectors])
Пример #6
0
def post_creation_vm_setup(api,
                           resid,
                           deployed,
                           deployed_vcp,
                           deployed_vfp,
                           internal_vlan_service_name,
                           requested_vmx_ip,
                           rootpassword,
                           userfullname,
                           username,
                           userpassword,
                           vmname2details,
                           vmx_resource,
                           logger):
    cpdet = get_cloud_provider_attributes(api, deployed_vcp[0])
    cpname = cpdet['ResourceName']
    cpmodel = cpdet['ResourceModel']
    logger.info('Cloud provider model: %s' % cpmodel)
    mac2nicname = {}
    vmxip = None
    if 'vsphere' in cpmodel.lower() or 'vcenter' in cpmodel.lower():
        vcenterip = cpdet['ResourceAddress']
        vcenteruser = cpdet['User']
        vcenterpassword = cpdet['Password']

        with Vcenter(vcenterip, vcenteruser, vcenterpassword, logger) as vcenter:
            name2vm = vcenter.get_name2vm()

            for cardvmname in deployed_vfp:
                cardvm = name2vm[cardvmname]
                mac2nicname.update(vcenter.get_mac2nicname(cardvm))
            logger.info('mac2nicname = %s' % mac2nicname)

            telnetport = allocate_number_from_pool(api, resid, 'vmxconsoleport', 9310, 9330)

            vm = name2vm[deployed_vcp[0]]
            esxi_ip = vm.runtime.host.name
            vcenter.add_serial_port(vm, telnetport, logger)

        with Mutex(api, resid, logger):
            api.AddServiceToReservation(resid, internal_vlan_service_name, 'vMX internal network', [])
            api.SetConnectorsInReservation(resid, [
                SetConnectorRequest('vMX internal network', d, 'bi', 'br-int') for d in deployed
            ])
            endpoints = []
            for d in deployed:
                endpoints.append('vMX internal network')
                endpoints.append(d)
                api.SetConnectorAttributes(resid, 'vMX internal network', d, [
                    AttributeNameValue('Requested Target vNIC Name', '2')
                ])
            api.ConnectRoutesInReservation(resid, endpoints, 'bi')

        for d in deployed:
            api.ExecuteResourceConnectedCommand(resid, d, 'PowerOn', 'power')

        vmxip = vsphere_telnet_setup(api, resid, deployed_vcp, esxi_ip, telnetport, rootpassword, userfullname, username, userpassword, requested_vmx_ip, logger)

    netid50 = None
    tocleanup = []

    if 'openstack' in cpmodel.lower():
        for d in deployed:
            api.ExecuteResourceConnectedCommand(resid, d, 'PowerOff', 'power')

        osurlbase = cpdet['Controller URL']
        osprojname = cpdet['OpenStack Project Name'] or 'admin'
        osdomain = cpdet['OpenStack Domain Name'] or 'default'
        osusername = cpdet['User Name']
        ospassword = cpdet['Password']

        openstack = OpenStack(osurlbase, osprojname, osdomain, osusername, ospassword, logger)

        netid128 = openstack.create_network('net128-%s' % vmx_resource)
        subnetid128 = openstack.create_subnet('net128-%s-subnet' % vmx_resource, netid128, '128.0.0.0/24', [('128.0.0.1', '128.0.0.254')], None, False)

        netid50 = openstack.create_network('net50-%s' % vmx_resource)
        subnetid50 = openstack.create_subnet('net50-%s-subnet' % vmx_resource, netid50, '50.0.0.0/24', [('50.0.0.1', '50.0.0.254')], None, False)

        for ip, vmname in zip(
                        ['128.0.0.%d' % (1 + i) for i in range(len(deployed_vcp))] +
                        ['128.0.0.%d' % (16 + i) for i in range(len(deployed_vfp))],

                        sorted(deployed_vcp) + sorted(deployed_vfp)):
            port128id = openstack.create_fixed_ip_port('%s-%s' % (vmx_resource, ip.replace('.', '-')), netid128, subnetid128, ip)
            tocleanup.append('port:%s' % port128id)
            openstack.remove_security_groups(port128id)
            openstack.set_port_security_enabled(port128id, False)
            cid = vmname2details[vmname].VmDetails.UID
            openstack.attach_port(cid, port128id)
            sleep(5)

        tocleanup.append('net:%s' % netid128)
        tocleanup.append('net:%s' % netid50)

        try:
            api.RemoveServicesFromReservation(resid, [vmx_resource + ' OpenStack cleanup'])
        except:
            pass
        api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' OpenStack cleanup', [
            AttributeNameValue('Cloud Provider Objects to Delete', ','.join(tocleanup)),
            AttributeNameValue('Cloud Provider Name', cpname),
        ])

        for c in sorted(deployed_vfp):
            cid = vmname2details[c].VmDetails.UID
            openstack.attach_net(cid, netid50)
            sleep(5)

        cid = vmname2details[deployed_vcp[0]].VmDetails.UID
        wsurl = openstack.get_serial_console_url(cid)

        for d in deployed:
            api.ExecuteResourceConnectedCommand(resid, d, 'PowerOn', 'power')

        openstack_telnet_setup(api, resid, wsurl, len(deployed_vfp), rootpassword, username, userpassword, requested_vmx_ip, logger)

        vmxdetails = api.GetResourceDetails(deployed_vcp[0])
        vmxip = vmxdetails.Address
        for a in vmxdetails.ResourceAttributes:
            if a.Name == 'Public IP' and a.Value:
                vmxip = a.Value
                break

    return vmxip, mac2nicname, netid50, cpname
Пример #7
0
    def connect_child_resources(self, context):
        """
        :type context: cloudshell.shell.core.driver_context.ResourceCommandContext
        :rtype: str
        """
        api = CloudShellAPISession(host=context.connectivity.server_address,
                                   token_id=context.connectivity.admin_auth_token,
                                   domain='Global')
        resource_name = context.resource.fullname
        reservation_id = context.reservation.reservation_id
        connectors = context.connectors

        if not context.connectors:
            return 'Success'

        resource = api.GetResourceDetails(resource_name)

        to_disconnect = []
        to_connect = []
        temp_connectors = []
        ports = self._get_ports(resource)

        for connector in connectors:
            me, other = self._set_remap_connector_details(connector, resource_name, temp_connectors)
            to_disconnect.extend([me, other])

        connectors = temp_connectors

        # these are connectors from app to vlan where user marked to which interface the connector should be connected
        connectors_with_predefined_target = [connector for connector in connectors if connector.vnic_id != '']

        # these are connectors from app to vlan where user left the target interface unspecified
        connectors_without_target = [connector for connector in connectors if connector.vnic_id == '']

        for connector in connectors_with_predefined_target:
            if connector.vnic_id not in ports.keys():
                raise Exception('Tried to connect an interface that is not on reservation - ' + connector.vnic_id)

            else:
                if hasattr(ports[connector.vnic_id], 'allocated'):
                    raise Exception('Tried to connect several connections to same interface: ' + ports[connector.vnic_id])

                else:
                    to_connect.append(SetConnectorRequest(SourceResourceFullName=ports[connector.vnic_id].Name,
                                                          TargetResourceFullName=connector.other,
                                                          Direction=connector.direction,
                                                          Alias=connector.alias))
                    ports[connector.vnic_id].allocated = True

        unallocated_ports = [port for key, port in ports.items() if not hasattr(port, 'allocated')]

        if len(unallocated_ports) < len(connectors_without_target):
            raise Exception('There were more connections to TeraVM than available interfaces after deployment.')
        else:
            for port in unallocated_ports:
                if connectors_without_target:
                    connector = connectors_without_target.pop()
                    to_connect.append(SetConnectorRequest(SourceResourceFullName=port.Name,
                                                          TargetResourceFullName=connector.other,
                                                          Direction=connector.direction,
                                                          Alias=connector.alias))

        if connectors_without_target:
            raise Exception('There were more connections to TeraVM than available interfaces after deployment.')

        api.RemoveConnectorsFromReservation(reservation_id, to_disconnect)
        api.SetConnectorsInReservation(reservation_id, to_connect)

        return 'Success'
    def execute_flow(self, connectors, ports, resource_name, reservation_id):
        if not connectors:
            return "Success"

        new_connectors_data = []
        to_disconnect = []

        for connector in connectors:
            source_remap_vnics = connector.attributes.get(
                ATTR_REQUESTED_SOURCE_VNIC, "").split(",")
            target_remap_vnics = connector.attributes.get(
                ATTR_REQUESTED_TARGET_VNIC, "").split(",")

            source = connector.source
            target = connector.target

            # remove old connector
            to_disconnect.extend([source, target])

            if resource_name in connector.source.split("/"):
                is_source = True
            else:
                is_source = False

            for source_vnic, target_vnic in itertools.izip_longest(
                    source_remap_vnics, target_remap_vnics):
                new_connector_data = self._create_connector_data(
                    is_source=is_source,
                    source_vnic=source_vnic,
                    target_vnic=target_vnic,
                    ports=ports,
                    connector=connector)
                new_connectors_data.append(new_connector_data)

        self._cs_api.RemoveConnectorsFromReservation(reservation_id,
                                                     to_disconnect)

        new_connectors = []
        for connector_data in new_connectors_data:
            conn = SetConnectorRequest(
                SourceResourceFullName=connector_data.source,
                TargetResourceFullName=connector_data.target,
                Direction=connector_data.direction,
                Alias=None)
            new_connectors.append(conn)

        self._cs_api.SetConnectorsInReservation(reservation_id, new_connectors)

        for connector_data in new_connectors_data:
            connector_attrs = []

            if connector_data.source_vnic:
                connector_attr = AttributeNameValue(
                    Name=ATTR_REQUESTED_SOURCE_VNIC,
                    Value=connector_data.source_vnic)
                connector_attrs.append(connector_attr)

            if connector_data.target_vnic:
                connector_attr = AttributeNameValue(
                    Name=ATTR_REQUESTED_TARGET_VNIC,
                    Value=connector_data.target_vnic)
                connector_attrs.append(connector_attr)

            if connector_attrs:
                self._cs_api.SetConnectorAttributes(
                    reservationId=reservation_id,
                    sourceResourceFullName=connector_data.source,
                    targetResourceFullName=connector_data.target,
                    attributeRequests=connector_attrs)