def main(): reservation = helpers.get_reservation_context_details() app = helpers.get_resource_context_details() app_attributes = app.attributes connectivity = helpers.get_connectivity_context_details() cloudshell = helpers.get_api_session() msg = lambda txt: cloudshell.WriteMessageToReservationOutput(reservation.id, txt) resource = helpers.get_resource_context_details_dict() resource['deployedAppData']['attributes'] = {attribute['name']: attribute['value'] for attribute in resource['deployedAppData']['attributes']} resource['deployedAppData']['attributes']['Password'] = cloudshell.DecryptPassword(resource['deployedAppData']['attributes']['Password']).Value repo = cloudshell.GetResourceDetails(app_attributes["Repository Name"]) repo_attributes = {attribute.Name: attribute.Value for attribute in repo.ResourceAttributes} repo_attributes["Host"] = repo.Address repo_attributes["Password"] = cloudshell.DecryptPassword(repo_attributes["Password"]).Value artifactory = Artifactory.from_dict(repo_attributes) build = ArtifactBuild.from_dict(repo_attributes) msg('- Looking for app dependencies') if not build.is_populated(): build = populate_build_from_sandbox(connectivity, reservation, msg) msg('- Found dependencies on Artifactory, associated with build {0} {1}'.format(build.name, build.number)) file_location, file_name = artifactory.download(build.name, build.number) msg('- Downloaded app dependencies to Execution Server at ' + os.path.join(file_location, file_name)) install_package(resource['deployedAppData']['address'], resource['deployedAppData']['attributes']['User'], resource['deployedAppData']['attributes']['Password'], os.path.join(file_location, file_name), app_attributes['Target Directory'] + '/' + file_name) msg('- Copied binaries to app server at ' + app_attributes['Target Directory'] + '/' + file_name)
def ExportBlueprint_and_commit(self): """ Export Blueprint on local machin and compare with old commit on Github before commiting and uploading the new exported package """ self.logger.info("Start Exporting Blueprint") self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Start Exporting blueprint") try: self.commit_comment = os.environ['comment'] except Exception as e: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Missing comment for commit") self.logger.info("Missing comment for commit") return self.commit_message = self.commit_comment + " commited by owner: " + self.sandbox.reservationContextDetails.owner_user ip = helpers.get_connectivity_context_details().server_address domain = helpers.get_reservation_context_details().domain contentlist = self.configs["GitPakageContentList"] temp_zip_path = self.configs['temp_zip_file'] if not os.path.isdir(temp_zip_path): os.makedirs(temp_zip_path) self.zip_package_name = self.sandbox.reservationContextDetails.environment_name + '.zip' self.fullZipfilePath = temp_zip_path + '\\' + self.zip_package_name GitHub_Token = self.configs["GitHub Token"] #repo_url = self.configs["repo_url"] try: self.logger.info("Export the package") qac = QualiAPIClient( ip, '9000', self.sandbox.reservationContextDetails.owner_user, self.sandbox.reservationContextDetails.owner_password, domain) qac.download_environment_zip( self.sandbox.reservationContextDetails.environment_name, self.fullZipfilePath) UnzipFolderName = temp_zip_path + '\\' + self.sandbox.reservationContextDetails.environment_name ## Unzip the pakage if not os.path.isdir(UnzipFolderName): os.makedirs(UnzipFolderName) self.logger.info("Unzip the package") zip = zipfile.ZipFile(self.fullZipfilePath) zip.extractall(UnzipFolderName) zip.close() ## Delete unrelevant files from package self.logger.info("Delete the unrelevant files from the package") for item in os.listdir(UnzipFolderName): if item not in contentlist: path = UnzipFolderName + '\\' + item shutil.rmtree(path) ## Zip the new package - overite the package self.logger.info("Zip the new blueprint package") os.chdir(os.path.dirname(UnzipFolderName)) shutil.make_archive(UnzipFolderName, 'zip', UnzipFolderName) is_uploaded = False try: #First try to connect to regular Github url : https://github.com self.logger.info("Try to connect to the organization") git = Github(login_or_token=GitHub_Token) org = git.get_organization(self.configs["organization_name"]) repo = org.get_repo(self.configs["Repository_name"]) except Exception as e: #For enterprise github URL which is different than "https://github.com" try: base_GitHubUrl = self.configs["GitHub_Link"] + '/api/v3' git = Github(login_or_token=GitHub_Token, base_url=base_GitHubUrl) org = git.get_organization( self.configs["organization_name"]) repo = org.get_repo(self.configs["Repository_name"]) except Exception as e: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Error getting git: {0}".format(str(e))) self.logger.error("Error getting git {0}".format(str(e))) raise e try: ##Download the previouse one self.logger.info( "Try to download the prev commit of this blueprint") Prev_file_contents = repo.get_file_contents( self.zip_package_name) self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "This is not the first commit for this blueprint") self.logger.info( "This is not the first commit for this blueprint") prev_zip_path = temp_zip_path + '\\' + self.configs[ "Prev_Package_name"] + '.zip' fh = open(prev_zip_path, "wb") fh.write(Prev_file_contents.content.decode('base64')) fh.close() ## unzip the prev one self.logger.info("Unzip the prev blueprint package") prev_unzip = temp_zip_path + '\\' + self.configs[ "Prev_Package_name"] if not os.path.isdir(prev_unzip): os.makedirs(prev_unzip) zip = zipfile.ZipFile(prev_zip_path) zip.extractall(prev_unzip) zip.close() if os.listdir(UnzipFolderName) and os.listdir(prev_unzip): self.logger.info("Compering with prev commit for diff") if self.are_dir_trees_equal(prev_unzip, UnzipFolderName): self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "There is no diff from the prev commit") self.logger.info( "There is no diff from the prev commit - Not uploading the new commit!" ) else: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "There is a diff from the prev commit") self.logger.info( "There is a diff from the prev commit") self.build_list_and_commit(repo, is_new_blueprint=False) is_uploaded = True self.logger.info("delete prev files") if os.path.isdir(prev_unzip): shutil.rmtree(prev_unzip) if os.path.isfile(prev_zip_path): os.remove(prev_zip_path) except Exception as e: self.logger.info("fail to download {0}".format(str(e))) if e.status == 404: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "This is the first commit for this blueprint") self.logger.info( "This is the first commit for this blueprint {0}". format(str(e))) try: if os.listdir(UnzipFolderName) and repo: self.build_list_and_commit(repo, is_new_blueprint=True) is_uploaded = True except Exception as e: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Error trying to build list and commit blueprint") self.logger.error( "Error trying to build list and commit blueprint {0}" .format(str(e))) DownloadLink = self.configs['GitHub_Link'] + '/'+ self.configs["organization_name"] + '/' +\ self.configs["Repository_name"] + "/blob/master/"+ self.zip_package_name try: self.logger.info("Export and commit to Github completed") self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Export and commit to Github completed ") if is_uploaded: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, DownloadLink) self.logger.info("delete tmp files") shutil.rmtree(UnzipFolderName) if os.path.isfile(self.fullZipfilePath): os.remove(self.fullZipfilePath) except Exception as e: self.logger.error("Error delete tmp files {0}".format(str(e))) except Exception as e: self.sandbox.automation_api.WriteMessageToReservationOutput( self.sandbox.id, "Failed to export and commit {0}".format(str(e))) self.logger.error("Error - fail to extport and commit {0}".format( str(e))) raise e
"type": "actionTarget" }, "customActionAttributes": [], "type": "setVlan" }] } } ''' import cloudshell.helpers.scripts.cloudshell_scripts_helpers as qs_helper import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev_help from cloudshell.shell.core.driver_context import * res_id = 'f7505eb3-b637-4795-9740-19a56244a33d' dev_help.attach_to_cloudshell_as('admin', 'admin', 'Global', res_id, 'localhost', '8029',resource_name='brocy') resource = qs_helper.get_resource_context_details() reservation = qs_helper.get_reservation_context_details() connectivity = qs_helper.get_connectivity_context_details() my_context = ResourceCommandContext(connectivity,resource,reservation,[]) my_context.reservation.reservation_id = '5695cf87-a4f3-4447-a08a-1a99a936010e' # cont = create_context() driv = BrocadeNOSDriver() driv.ApplyConnectivityChanges(my_context, request) # driv.get_inventory(cont) # driv.command(context=cont, command='conf t') # driv.command(context=cont, command='int fa 0/1') # driv.command(context=cont, command='speed 100')
attach_to_cloudshell_as(user=username, password=password, domain=domain, server_address=server, reservation_id=resId, service_name='UptimeEnforcer') get_debug_session() session = sh.get_api_session() token = session.token_id reservation_context = sh.get_reservation_context_details() reservation_context.reservation_id = reservation_context.id connectivity_context = sh.get_connectivity_context_details() connectivity_context.admin_auth_token = token resource_context = sh.get_resource_context_details() reservation_description = session.GetReservationDetails( reservation_context.id).ReservationDescription services = reservation_description.Services connectors = reservation_description.Connectors context_connectors = [ conn for conn in connectors if resource_context.name in [conn.Source, conn.Target] ] context_connectors_reformatted = [] for conn in context_connectors: temp_connector = Connector(source=conn.Source,
return decypted session = script_help.get_api_session() resid = script_help.get_reservation_context_details().id # resource_details = session address = script_help.get_resource_context_details().address username = script_help.get_resource_context_details().attributes.get('User') enc_cs_password = script_help.get_resource_context_details().attributes.get( 'Password') cleartext_password = session.DecryptPassword(enc_cs_password).Value pass_enc = os.popen("cryptRDP5.exe {}".format(cleartext_password)).read() rdp_text = rdp_populator(username=username, password=pass_enc, ip=address) FILEPATH = r'c:\temp\{}.rdp'.format( script_help.get_resource_context_details().name) with open(FILEPATH, 'w') as upload_file: upload_file.write(rdp_text) attach_to_reservation.attachFile( serverMachine=script_help.get_connectivity_context_details( ).server_address, resid=script_help.get_reservation_context_details().id, user=script_help.get_connectivity_context_details().admin_user, password=script_help.get_connectivity_context_details().admin_pass, domain=script_help.get_reservation_context_details().domain, file_path=FILEPATH, filename='machine')
def execute(): api = helpers.get_api_session() inputs = helpers.get_reservation_context_details().parameters.global_inputs res_id = helpers.get_reservation_context_details().id connectivity = helpers.get_connectivity_context_details() tempdir = tempfile.gettempdir() # install mock shells try: with zipfile.ZipFile(os.path.dirname(__file__), "r") as z: z.extractall(tempdir) shells = [ tempdir + "\\Trafficshell.zip", tempdir + "\\Putshell.zip", tempdir + "\\L2Mockswitch.zip" ] success = install_shells(connectivity, shells) api.WriteMessageToReservationOutput( reservationId=res_id, message='Shells installation results:\n' + success) except Exception as e: print e.message # get user/admin counts to create # admins_count = 0 # if 'Number of Sys Admins' in inputs: # admins_count = int(inputs['Number of Sys Admins']) users_count = 0 if 'Number of Users' in inputs: users_count = int(inputs['Number of Users']) domain_admins_count = 0 if 'Number of Domain Admins' in inputs: domain_admins_count = int(inputs['Number of Domain Admins']) # create domains and assign users group to them # first create users group try: api.AddNewGroup(groupName='Users Group', groupRole='Regular') except CloudShellAPIError as ex: pass # probably group exists already # then create domain admins group try: api.AddNewGroup(groupName='Domain Admins', groupRole='DomainAdmin') except CloudShellAPIError as ex: pass # probably group exists already # now create domains and assign the group to it domains_created = [] for domain in ['Test Team NY', 'Test Team Calif', 'Consulting Phili']: try: api.AddNewDomain(domainName=domain) api.AddGroupsToDomain(domainName=domain, groupNames=['Users Group']) domains_created.append(domain) # assign networking service category to the new domains #import_package(connectivity, domain, tempdir + "\\Networking Service Category.zip") api.AddGroupsToDomain(domainName=domain, groupNames=['Domain Admins']) #if domain == 'Test Team NY': # import_package(connectivity, domain, tempdir + "\\Apps for testing service category.zip") except CloudShellAPIError as ex: pass # probably domain exists already api.WriteMessageToReservationOutput( res_id, 'Domains created: ' + ','.join(domains_created)) # import the put blueprint try: api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint"') import_package(connectivity, 'Test Team NY', tempdir + "\\PUT Traffic Test Blueprint.zip") api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint" complete') except Exception as ex: api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint" failed') pass # create users/admins groups = None # if admins_count > 0: # groups = api.GetGroupsDetails() # sysadmin_group = [g for g in groups.Groups if g.Name == "System Administrators"][0] # a = len(sysadmin_group.Users) + 1 # added_count = 0 # admins_created = [] # while added_count < admins_count: # try: # api.AddNewUser('admin' + str(a), 'admin' + str(a), '', isActive=True, isAdmin=True) # added_count += 1 # admins_created.append('admin' + str(a)) # except: # pass # a += 1 # api.WriteMessageToReservationOutput(res_id, 'Admins created: ' + ','.join(admins_created)) if domain_admins_count > 0: if groups is None: groups = api.GetGroupsDetails() dom_admin_group = [ g for g in groups.Groups if g.Name == "Domain Admins" ][0] a = len(dom_admin_group.Users) + 1 added_count = 0 dom_admins_created = [] while added_count < domain_admins_count: try: api.AddNewUser('dadmin' + str(a), 'dadmin' + str(a), '', isActive=True, isAdmin=False) api.AddUsersToGroup(['dadmin' + str(a)], 'Domain Admins') added_count += 1 dom_admins_created.append('dadmin' + str(a)) except: pass a += 1 api.WriteMessageToReservationOutput( res_id, 'Domain Admins created: ' + ','.join(dom_admins_created)) if users_count > 0: api.WriteMessageToReservationOutput( res_id, 'Creating users and resources, this might take a while...') if groups is None: groups = api.GetGroupsDetails() users_group = [g for g in groups.Groups if g.Name == "Users Group"][0] a = len(users_group.Users) + 1 added_count = 0 users_created = [] l2_resource_created = False while added_count < users_count: try: api.AddNewUser('user' + str(a), 'user' + str(a), '', isActive=True, isAdmin=False) api.AddUsersToGroup(['user' + str(a)], 'Users Group') added_count += 1 users_created.append('user' + str(a)) except: pass a += 1 # create resources for this user (PUT+Traffic) try: api.CreateFolder('PUTs') #postfix_rn = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) postfix_rn = str(a - 1) resource_name = 'Product Under Test - ' + postfix_rn api.CreateResource('CS_GenericResource', 'Putshell', resource_name, '10.10.10.' + str(a), 'PUTs', '', 'A fake resource for training') api.UpdateResourceDriver(resource_name, 'Putshell') api.AutoLoad(resource_name) api.AddResourcesToDomain('Test Team NY', [resource_name], True) api.CreateFolder('Traffic Generators') #postfix_tg = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) postfix_tg = str(a - 1) traffic_name = 'Traffic Generator 2.0 - ' + postfix_tg api.CreateResource('CS_GenericResource', 'Trafficshell', traffic_name, '10.10.11.' + str(a), 'Traffic Generators', '', 'A fake resource for training') api.UpdateResourceDriver(traffic_name, 'Trafficshell') api.AutoLoad(traffic_name) api.AddResourcesToDomain('Test Team NY', [traffic_name], True) # connect devices to the patch panel patch_name = 'Patch Panel - Training' api.CreateResources([ ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 1 - PUT' + postfix_rn, '1', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 2 - PUT' + postfix_rn, '2', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 1 - TG' + postfix_tg, '1', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 2 - TG' + postfix_tg, '2', '', patch_name, '') ]) api.AddResourcesToDomain('Test Team NY', [patch_name], True) api.UpdatePhysicalConnections([ PhysicalConnectionUpdateRequest( resource_name + '/Port 1', patch_name + '/Port 1 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( resource_name + '/Port 2', patch_name + '/Port 2 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 1', patch_name + '/Port 1 - TG' + postfix_tg, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 2', patch_name + '/Port 2 - TG' + postfix_tg, '10') ]) # create L2 mock switch if needed l2_training = 'L2 Mock Switch - Training' try: if l2_resource_created == False: try: l2 = api.GetResourceDetails(l2_training) l2_resource_created = True except: pass if l2_resource_created == False: api.CreateResource( resourceFamily='CS_Switch', resourceModel='L2Mockswitch', resourceName=l2_training, resourceAddress='1.2.3.4', folderFullPath='', parentResourceFullPath='', resourceDescription='A fake resource for training') api.UpdateResourceDriver(l2_training, 'L2Mockswitch') api.CreateResource( resourceFamily='CS_Chassis', resourceModel='L2Mockswitch.GenericChassis', resourceName='Chassis1', resourceAddress='1', folderFullPath='', parentResourceFullPath=l2_training, resourceDescription='') except Exception as ex: api.WriteMessageToReservationOutput(res_id, ex.message) pass # resource probably exists already # add L2 ports and connect to PUT chassis_name = l2_training + '/Chassis1' api.CreateResources([ ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 3 - PUT' + postfix_rn, '3', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 4 - PUT' + postfix_rn, '4', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 3 - TG' + postfix_tg, '3', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 4 - TG' + postfix_tg, '4', '', chassis_name, '') ]) api.AddResourcesToDomain('Test Team NY', [l2_training], True) api.UpdatePhysicalConnections([ PhysicalConnectionUpdateRequest( resource_name + '/Port 3', chassis_name + '/Port 3 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( resource_name + '/Port 4', chassis_name + '/Port 4 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 3', chassis_name + '/Port 3 - TG' + postfix_tg, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 4', chassis_name + '/Port 4 - TG' + postfix_tg, '10') ]) except Exception as ex: api.WriteMessageToReservationOutput(res_id, ex.message) pass # try: # api.AddTopologiesToDomain('Test Team NY', ['PUT Traffic Test']) # except: # pass api.WriteMessageToReservationOutput( res_id, 'Users created: ' + ','.join(users_created)) print 'Process complete'
if "IxVM" in resource_name: IxVM = resource_name IxVM_address = resource.FullAddress for resource in reservation_details.ReservationDescription.Apps: resource_name = resource.Name if "/" in resource_name: continue if "IxVM" in resource_name: IxVM = resource_name IxVM_address = resource.FullAddress if IxVM_address: connectivity = helper.get_connectivity_context_details() api = QualiAPISession( connectivity.server_address, connectivity.admin_user, connectivity.admin_pass, domain=helper.get_reservation_context_details().domain) test_name = os.environ.get('test_name') config_name = os.environ.get('config_file_name') attachreport = lambda filename: attach_report_to_reservation( reservation_id, filename, api) output_logger = lambda message: session.WriteMessageToReservationOutput( reservation_id, message) with suppress_stdout(): result = loadQuickTest(IxVM=IxVM_address,
from cloudshell.shell.core.driver_context import InitCommandContext, AutoLoadCommandContext, ResourceCommandContext, \ AutoLoadAttribute, AutoLoadDetails, CancellationContext, ResourceRemoteCommandContext from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface # Debug Script # with open(r'c:\temp\HWC_Debug_creds', 'r') as debug_file: # my_debug_file = debug_file.read() dev_help.attach_to_cloudshell_as( user='******', password='******', domain='Global', reservation_id='c3f09270-58a6-4188-a11d-19239d73a0d8', server_address='192.168.85.15', resource_name='HWC') driver_interface = ResourceDriverInterface context = ResourceCommandContext( connectivity=script_help.get_connectivity_context_details(), reservation=script_help.get_reservation_context_details(), resource=script_help.get_resource_context_details(), connectors=None) with open('request.json', 'r') as file: my_request = json.load(file) my_hwc_driver = driver.HuaweicloudDriver() my_hwc_driver.initialize(context) my_hwc_driver.Deploy(context, request=my_request) pass