class TestIxiaChassis2GShell(object): session = None def setup(self): self.session = CloudShellAPISession('localhost', 'admin', 'admin', 'Global') def teardown(self): for resource in self.session.GetResourceList('Testing').Resources: self.session.DeleteResource(resource.Name) def test_hello_world(self): pass def test_all(self): for key, value in ixchariot_servers.items(): self._get_inventory(key, value) def _get_inventory(self, name, properties): self.resource = self.session.CreateResource( resourceFamily='CS_TrafficGeneratorChassis', resourceModel='IxChariot Server Shell 2G', resourceName=name, resourceAddress=properties['address'], folderFullPath='Testing', parentResourceFullPath='', resourceDescription='should be removed after test') self.session.UpdateResourceDriver(self.resource.Name, 'IxChariot Server Shell 2G') attributes = [ AttributeNameValue('IxChariot Server Shell 2G.Client Install Path', properties['client_install_path']), AttributeNameValue('IxChariot Server Shell 2G.User', properties['user']), AttributeNameValue('IxChariot Server Shell 2G.Password', properties['password']) ] self.session.SetAttributesValues( ResourceAttributesUpdateRequest(self.resource.Name, attributes)) self.session.AutoLoad(self.resource.Name) resource_details = self.session.GetResourceDetails(self.resource.Name) assert (len(resource_details.ChildResources) == properties['modules']) self.session.DeleteResource(self.resource.Name)
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)
from cloudshell.api.cloudshell_api import CloudShellAPISession user = "******" password = "******" server = "localhost" domain = "Global" TOTAL_RESOURCES = 1000 api = CloudShellAPISession(host=server, username=user, password=password, domain=domain) print("building resources...") for i in range(TOTAL_RESOURCES): print("resource" + str(i + 1)) api.CreateResource(resourceModel="Generic Dut", resourceName="generic_dummy_b_{}".format(str(i + 1)), resourceAddress="{0}.{0}.{0}.{0}".format(str(i)), folderFullPath="dummy resources 2") print("done")
reservation_end_date = datetime.datetime.strptime(reservation_details.EndTime, "%m/%d/%Y %H:%M").replace(hour=0, minute=0, second=0, microsecond=0) reservation_end_time_in_ms = int((reservation_end_date - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000) # 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])
def on_message(self, message): obj = json.loads(message) if obj["TASK"] == "CREATE": resName = obj["NAME"] famName = obj["FAM"] modName = obj["MOD"] addr = obj["ADDR"] desc = obj["DESC"] dom = obj["DOM"] if (len(resName) > 0): try: creds = QSCreds() csapi = CloudShellAPISession(creds.Host, creds.Un, creds.Pw, creds.Dom) folder = "" parent = "" csapi.CreateResource(famName, modName, resName, addr, folder, parent, desc) csapi.AddResourcesToDomain(dom, [resName]) self.write_message("CREATED/" + message) except: e = sys.exc_info()[0] self.write_message("FAILED/EXCEPTION/" + str(e)) pass else: self.write_message("FAILED/CREATENAME") elif obj["TASK"] == "ATTR": resName = obj["NAME"] if (len(resName) > 0): try: creds = QSCreds() csapi = CloudShellAPISession(creds.Host, creds.Un, creds.Pw, creds.Dom) allRaud = [] for n, v in zip(obj["ATTS"], obj["VALS"]): if (n != "XXXNAXXX"): anv = AttributeNameValue(n, v) anvs = AttributeNamesValues(anv) raud = ResourceAttributesUpdateRequest( resName, anvs) allRaud.append(raud) csapi.SetAttributesValues(allRaud) self.write_message("ATTR/" + message) except: e = sys.exc_info()[0] self.write_message("FAILED/EXCEPTION/" + str(e)) pass else: self.write_message("FAILED/ATTRNAME") elif obj["TASK"] == "SUB": rootName = obj["ROOT"] if (len(rootName) > 0): try: creds = QSCreds() csapi = CloudShellAPISession(creds.Host, creds.Un, creds.Pw, creds.Dom) for f, m, n in zip(obj["SUBFAMS"], obj["SUBMODS"], obj["SUBNAMES"]): if (len(n) > 0): csapi.CreateResource(f, m, n, n, "", rootName, "") self.write_message("SUB/" + message) except: e = sys.exc_info()[0] self.write_message("FAILED/EXCEPTION/" + str(e)) pass else: self.write_message("FAILED/ROOTNAME") else: self.write_message("FAILED/UNKNOWN")
root_model = resource_details.ResourceModelName port_model = f"{root_model}.{PORT_MODEL_SUFFIX}" chassis = resource_details.ChildResources[0] module1 = chassis.ChildResources[0] for i, curr_port in enumerate(module1.ChildResources): port_split = curr_port.Name.split("/") port_name = port_split[-1] port_path = "/".join(port_split[:-1]) if port_name.endswith(LOGICAL_PORT_SUFFIX): continue logical_port_name = f"{port_name}_{LOGICAL_PORT_SUFFIX}" logical_full_path = f"{port_path}/{logical_port_name}" logical_address = f"{curr_port.Address}_logical" try: api.CreateResource(resourceFamily="CS_Port", resourceModel=port_model, resourceName=logical_port_name, resourceAddress=logical_address, parentResourceFullPath=module1.Name) print(f"created logical port {logical_port_name}") except CloudShellAPIError as e: if e.code == RESOURCE_EXISTS_ERROR_CODE: print(f"Port '{logical_port_name}' exists, skipping creation") api.SetAttributeValue(resourceFullPath=logical_full_path, attributeName=POLATIS_LOGICAL_PORT_ATTR_NAME, attributeValue="True")