Пример #1
0
def context(session: CloudShellAPISession, test_helpers: TestHelpers,
            server: list) -> ResourceCommandContext:
    controller_address, controller_version, apikey, ports = server
    attributes = [
        AttributeNameValue(f'{IXLOAD_CONTROLLER_MODEL}.Address',
                           controller_address),
        AttributeNameValue(f'{IXLOAD_CONTROLLER_MODEL}.Controller Version',
                           controller_version),
        AttributeNameValue(f'{IXLOAD_CONTROLLER_MODEL}.ApiKey', apikey),
        AttributeNameValue(f'{IXLOAD_CONTROLLER_MODEL}.License Server',
                           '192.168.42.61'),
        AttributeNameValue(f'{IXLOAD_CONTROLLER_MODEL}.Licensing Mode',
                           'Perpetual')
    ]
    session.AddServiceToReservation(test_helpers.reservation_id,
                                    IXLOAD_CONTROLLER_MODEL, ALIAS, attributes)
    context = test_helpers.resource_command_context(service_name=ALIAS)
    session.AddResourcesToReservation(test_helpers.reservation_id, ports)
    reservation_ports = get_resources_from_reservation(
        context, f'{IXIA_CHASSIS_MODEL}.GenericTrafficGeneratorPort')
    set_family_attribute(context, reservation_ports[0].Name, 'Logical Name',
                         'Traffic1@Network1')
    set_family_attribute(context, reservation_ports[1].Name, 'Logical Name',
                         'Traffic2@Network2')
    yield context
Пример #2
0
def context(session: CloudShellAPISession, test_helpers: TestHelpers,
            server: list) -> ResourceCommandContext:
    controller_address, controller_port, ports = server
    attributes = [
        AttributeNameValue(f"{STC_CONTROLLER_MODEL}.Address",
                           controller_address),
        AttributeNameValue(f"{STC_CONTROLLER_MODEL}.Controller TCP Port",
                           controller_port),
    ]
    session.AddServiceToReservation(test_helpers.reservation_id,
                                    STC_CONTROLLER_MODEL, ALIAS, attributes)
    context = test_helpers.resource_command_context(service_name=ALIAS)
    session.AddResourcesToReservation(test_helpers.reservation_id, ports)
    reservation_ports = get_resources_from_reservation(
        context, f"{STC_CHASSIS_MODEL}.GenericTrafficGeneratorPort")
    set_family_attribute(context, reservation_ports[0].Name, "Logical Name",
                         "Port 1")
    set_family_attribute(context, reservation_ports[1].Name, "Logical Name",
                         "Port 2")
    yield context
Пример #3
0
    def vmx_orch_hook_during_provisioning(self, context):
        logger = get_qs_logger(log_group=context.reservation.reservation_id, log_file_prefix='vMX')

        logger.info('deploy called')
        api = CloudShellAPISession(host=context.connectivity.server_address,
                                   token_id=context.connectivity.admin_auth_token,
                                   domain=context.reservation.domain)
        resid = context.reservation.reservation_id
        vmxtemplate_resource = context.resource.name

        logger.info('context attrs: ' + str(context.resource.attributes))

        vmxuser = context.resource.attributes['User']
        vmxpassword = api.DecryptPassword(context.resource.attributes['Password']).Value

        vcp_app_template_name = context.resource.attributes['Chassis App']
        vfp_app_template_name_template = context.resource.attributes['Module App']

        internal_vlan_service_name = context.resource.attributes['Internal Network Service'] or 'VLAN Auto'
        vlantype = context.resource.attributes.get('Vlan Type') or 'VLAN'

        ncards = int(context.resource.attributes.get('Number of modules', '1'))

        router_family = context.resource.attributes['Deployed Resource Family']
        router_model = context.resource.attributes['Deployed Resource Model']
        router_driver = context.resource.attributes['Deployed Resource Driver']

        chassis_deployed_model_name = context.resource.attributes['Controller App Resource Model']
        card_deployed_model_name = context.resource.attributes['Card App Resource Model']

        requested_vmx_ip = context.resource.attributes.get('Management IP', 'dhcp')
        username = context.resource.attributes.get('User', 'user')
        userpassword = api.DecryptPassword(context.resource.attributes.get('Password', '')).Value
        rootpassword = userpassword
        userfullname = context.resource.attributes.get('User Full Name', username)

        missing = []
        for a in ['Chassis App', 'Module App', 'Deployed Resource Family', 'Deployed Resource Model']:
            if a not in context.resource.attributes:
                missing.append(a)
        if missing:
            raise Exception('Template resource missing values for attributes: %s' % ', '.join(missing))

        if '%d' not in vfp_app_template_name_template:
            vfp_app_template_name_template += '%d'

        px, py = get_resource_position(api, resid, vmxtemplate_resource)

        vmx_resource = vmxtemplate_resource.replace('Template ', '').replace('Template', '') + '_' + str(randint(1, 10000))
        fakel2name = '%s L2' % vmx_resource

        todeploy = [
            (vcp_app_template_name, '%s_vcp' % vmx_resource, px, py + 100)
        ] + [
            (vfp_app_template_name_template % i, '%s_vfp%d' % (vmx_resource, i), px, py+100+100+100*i)
            for i in range(ncards)
        ]

        for _ in range(5):
            with Mutex(api, resid, logger):
                for template, alias, x, y in todeploy:
                    add_app(api, resid, template, alias, x, y)

            app_aliases = [alias for template, alias, x, y in todeploy]
            api.DeployAppToCloudProviderBulk(resid, app_aliases)

            with Mutex(api, resid, logger):
                logger.info('original app aliases = %s' % str(app_aliases))
                vmname2details = get_details_of_deployed_app_resources(api, resid, app_aliases)

            deployed_vcp = sorted([x for x in vmname2details if 'vcp' in x])
            deployed_vfp = sorted([x for x in vmname2details if 'vfp' in x])
            deployed = deployed_vcp + deployed_vfp

            logger.info('deployed apps = %s' % str(deployed))

            vmxip, mac2nicname, netid50, cpname = 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)


            if not vmxip:
                raise Exception('VCP did not receive an IP (requested %s)' % (requested_vmx_ip))

            if not wait_for_ssh_up(api, resid, vmxip, vmxuser, vmxpassword, logger):
                raise Exception('VCP not reachable via SSH within 5 minutes at IP %s -- check management network' % vmxip)

            if ssh_wait_for_ge_interfaces(api, resid, vmxip, vmxpassword, ncards, logger):
                logger.info('All expected ge- interfaces found')
                break

            msg = '%d card(s) not discovered within 3 minutes - recreating VMs' % ncards
            logger.info(msg)
            api.WriteMessageToReservationOutput(resid, msg)

            api.DeleteResources(deployed)
            sleep(10)
        else:
            raise Exception('%d cards were not discovered after 10 minutes in 5 attempts' % ncards)

        for kj in deployed_vfp:
            api.UpdateResourceAddress(kj, kj)

        api.CreateResource(router_family, router_model, vmx_resource, vmxip)
        api.AddResourcesToReservation(resid, [vmx_resource])
        api.SetReservationResourcePosition(resid, vmxtemplate_resource, px, py-50)
        api.SetReservationResourcePosition(resid, vmx_resource, px, py)
        if router_driver:
            api.UpdateResourceDriver(vmx_resource, router_driver)

        try:
            api.RemoveServicesFromReservation(resid, [vmx_resource + ' vMX resource cleanup'])
        except:
            pass
        api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' vMX resource cleanup', [
            AttributeNameValue('Resources to Delete', ','.join([
                vmx_resource,
            ])),
        ])

        copy_resource_attributes(api, vmxtemplate_resource, vmx_resource)

        for _ in range(5):
            logger.info('Running autoload...')
            try:
                api.AutoLoad(vmx_resource)

                children_flat = get_all_child_resources(api, vmx_resource)
                ge_children_flat = {a: b
                                    for a, b in children_flat.iteritems()
                                    if '/' in a and '-' in a.split('/')[-1]}

                foundcards2ports = defaultdict(list)
                for fullpath, attrs in ge_children_flat.iteritems():
                    foundcards2ports[attrs['ResourceBasename'].split('-')[1]].append(attrs['ResourceBasename'])

                if len(foundcards2ports) >= ncards:
                    logger.info('Autoload found ports: %s' % (foundcards2ports))
                    break
                logger.info('Autoload did not find all cards (%d) or ports per card (10). Retrying in 10 seconds. Found: %s' % (ncards, foundcards2ports))
                sleep(10)
            except Exception as ek:
                logger.info('Autoload error: %s. Retrying in 30 seconds.' % str(ek))
                sleep(30)
        else:
            raise Exception('Autoload did not discover all expected ports - unhandled vMX failure')

        post_autoload_cleanup(api, resid, deployed_vfp, vmname2details, netid50, logger)

        vfpcardidstr2deployedapp3 = {vfpname.split('_')[2].replace('vfp', '').split('-')[0]: vfpname for vfpname in
                                     deployed_vfp}

        def vm_from_ge_port(portname):
            if '/' in portname:
                portname = portname.split('/')[-1]
            return vfpcardidstr2deployedapp3[portname.split('-')[1]]

        logger.info('vfpcardidstr2deployedapp = %s' % str(vfpcardidstr2deployedapp3))

        autoloadport2vmname_nicname = {}
        for ch, attrs in ge_children_flat.iteritems():
            for attr, val in attrs.iteritems():
                if 'mac' in attr.lower() and 'address' in attr.lower():
                    autoloadport2vmname_nicname[ch] = (vm_from_ge_port(ch), mac2nicname.get(val, attrs['ResourceBasename'].split('-')[-1]))

        create_fake_L2(api, fakel2name, vlantype, autoloadport2vmname_nicname)
        try:
            api.RemoveServicesFromReservation(resid, [vmx_resource + ' L2 cleanup'])
        except:
            pass
        api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' L2 cleanup', [
            AttributeNameValue('Resources to Delete', ','.join([
                fakel2name,
            ])),
        ])

        logger.info('deployed_vcp=%s deployed_vfp=%s deployed=%s' % (deployed_vcp, deployed_vfp, deployed))

        with Mutex(api, resid, logger):
            basename2fullpath = {fullpath.split('/')[-1]: fullpath for fullpath in autoloadport2vmname_nicname}

            def mapfunc(oldpath):
                basename = oldpath.split('/')[-1]
                return basename2fullpath[basename]

            move_connectors_of(api, resid, vmxtemplate_resource, mapfunc, logger)

            api.RemoveResourcesFromReservation(resid, [vmxtemplate_resource])

        logger.info('SUCCESS deploying vMX %s' % vmx_resource)
Пример #4
0
# Create Hubspot contact and enroll to Hubspot Workflow

hubspot_helper = Hubspot_API_Helper("cba66474-e4e4-4f5b-9b9b-35620577f343")
hubspot_helper.create_contact(first_name, last_name, email, company, phone)
hubspot_helper.change_contact_property(email, "cloudshell_trial_password", generated_password)
hubspot_helper.change_contact_property(email, "cloudshell_trial_end_date", str(reservation_end_time_in_ms))
hubspot_helper.change_contact_property(email, "cloudshell_trial_owner", owner_email)
hubspot_helper.enroll_contact_to_workflow(email, "1980406")

api.WriteMessageToReservationOutput(reservationContext["id"], "6. Creating Trial Resource")

# Create Trial Resource and add to reservation
create_res_result = api.CreateResource("CloudShell Trial", "CloudShell VE Trial", "CS Trial {0}".format(domain_name), "NA", "CloudShell Trials", resourceDescription="Trial resource for {0} {1}".format(first_name, last_name))
res_att_values = {"Company Name": company, "email": email, "First Name": first_name, "Last Name": last_name, "Phone Number": phone, "Quali Owner": owner_email}
api.SetAttributesValues([ResourceAttributesUpdateRequest(create_res_result.Name, [AttributeNameValue(k,v) for k,v in res_att_values.items()])])
api.AddResourcesToReservation(reservationContext["id"], [create_res_result.Name])


# Send Trial start notifications
api.WriteMessageToReservationOutput(reservationContext["id"], "7. Sending trial start notifications")

# Send E-mail to owner + admin
email_title = "CloudShell Trial: Trial setup complete"
email_body = "Setup of trial for {user} has been completed successfully".format(user=new_username)
smtp_client.send_email(",".join([owner_email, admin_email]), email_title, email_body, False)

api.AddPermittedUsersToReservation(reservationContext["id"], [owner_email])

api.WriteMessageToReservationOutput(reservationContext["id"], "Trial Started successfully!")
user = "******"
password = "******"
server = "192.168.85.25"
# server = "localhost"
domain = "Global"

SANDBOX_ID = "ade3ca37-ac99-4bee-9496-c53cb54ed8b2"

api = CloudShellAPISession(host=server,
                           username=user,
                           password=password,
                           domain=domain)

api.AddResourcesToReservation(reservationId=SANDBOX_ID,
                              resourcesFullPath=["DHCp 1500"],
                              shared=True)
api.SetReservationResourcePosition(reservationId=SANDBOX_ID,
                                   resourceFullName="DHCP 1500",
                                   x=100,
                                   y=50)
api.SetReservationServicePosition(reservationId=SANDBOX_ID,
                                  serviceAlias="Ansible Config 2G")
resource_details = api.GetResourceDetails(
    "2G - ubuntu snapshot ansible test_d9f9-caef")
vm_details = resource_details.VmDetails
# vm_details.NetworkData[0].AdditionalData[0]
# output = api.ExecuteResourceConnectedCommand(reservationId=SANDBOX_ID,
#                                              resourceFullPath="ubuntu snapshot ansible test_1_c56b-e60e",
#                                              commandName="GetVmDetails",
#                                              commandTag="allow_unreserved",