class CloudShellAPILibrary(object): def __init__(self, cloudshell_address, cloudshell_api_port, user="******", auth_token='', domain="Global", sandbox_uuid: UUID =""): self.api_session = CloudShellAPISession(cloudshell_address, user, token_id=auth_token, domain=domain, port=cloudshell_api_port) if sandbox_uuid: self.sandbox_id = str(sandbox_uuid) def write_sandbox_message(self, message): self.api_session.WriteMessageToReservationOutput(self.sandbox_id, message) def execute_command(self, resource, resource_type, command_name, command_params: dict = {}): if command_params: api_params = [InputNameValue(param.name, param.value) for param in command_params.items()] output = self.api_session.ExecuteCommand(self.sandbox_id, resource, resource_type, command_name, api_params) else: output = self.api_session.ExecuteCommand(self.sandbox_id, resource, resource_type, command_name) return output.Output def execute_blueprint_command(self, command_name, command_params: dict = {}): if command_params: api_params = [InputNameValue(param.name, param.value) for param in command_params.items()] output = self.api_session.ExecuteEnvironmentCommand(self.sandbox_id, command_name, api_params, printOutput=True) else: output = self.api_session.ExecuteEnvironmentCommand(self.sandbox_id, command_name, printOutput=True) return output.Output def set_sandbox_status(self, status_name, status_reason): self.api_session.SetReservationLiveStatus(self.sandbox_id, status_name, status_reason)
def run(self, resource, cmd): try: csapi = CloudShellAPISession(self._serveraddr, self._adminuser, self._adminpw, self._admindom) out = csapi.ExecuteCommand(self._resid, resource, "Resource", cmd) csapi.Logoff() self._cmdOut = out.Output return self._cmdOut except: raise CSWrapperError("Could not run command")
def test_run_sequencer(self, session: CloudShellAPISession, context: ResourceCommandContext) -> None: self._load_config(session, context, Path(__file__).parent.joinpath("test_sequencer.tcc")) cmd_inputs = [InputNameValue("command", "Start")] session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "run_quick_test", cmd_inputs) cmd_inputs = [InputNameValue("command", "Wait")] session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "run_quick_test", cmd_inputs) time.sleep(2) cmd_inputs = [ InputNameValue("view_name", "generatorportresults"), InputNameValue("output_type", "JSON"), ] stats = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_statistics", cmd_inputs) assert int( json.loads( stats.Output)["Port 1"]["GeneratorIpv4FrameCount"]) == 8000
def test_run_traffic(self, session: CloudShellAPISession, context: ResourceCommandContext) -> None: self._load_config(session, context, Path(__file__).parent.joinpath("test_config.tcc")) session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "send_arp") session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "start_protocols") cmd_inputs = [InputNameValue("blocking", "True")] session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "start_traffic", cmd_inputs) time.sleep(2) cmd_inputs = [ InputNameValue("view_name", "generatorportresults"), InputNameValue("output_type", "JSON"), ] stats = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_statistics", cmd_inputs) assert int(json.loads( stats.Output)["Port 1"]["TotalFrameCount"]) >= 4000
def _load_config( self, session: CloudShellAPISession, context: ResourceCommandContext, config: Path, ) -> None: reservation_ports = get_resources_from_reservation( context, "STC Chassis Shell 2G.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") cmd_inputs = [ InputNameValue("config_file_location", config.as_posix()) ] session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "load_config", cmd_inputs)
def runinput(self, resource, cmd, inputs=''): try: csapi = CloudShellAPISession(self._serveraddr, self._adminuser, self._adminpw, self._admindom) inputList = inputs.split(',') argList = [] for item in inputList: kvp = item.split(':') qinv = InputNameValue(kvp[0], kvp[1]) argList.append(qinv) out = csapi.ExecuteCommand(self._resid, resource, "Resource", cmd, argList) csapi.Logoff() self._cmdOut = out.Output return self._cmdOut except: raise CSWrapperError("Could not run command with inputs")
def ApplyConnectivityChanges(self, context, request): """ Configures VLANs on multiple ports or port-channels :param ResourceCommandContext context: The context object for the command with resource and reservation info :param str request: A JSON object with the list of requested connectivity changes :return: a json object with the list of connectivity changes which were carried out by the switch :rtype: str """ logger = get_qs_logger(log_group=context.reservation.reservation_id, log_file_prefix='vMX') logger.info('ApplyConnectivityChanges called with json %s' % request) api = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) vmuid2portno_req_tuples = {} vmuid2cpname = {} vmuid2resourcename = {} o = json.loads(request) for action in o['driverRequest']['actions']: targetrd = api.GetResourceDetails( action['actionTarget']['fullName']) vmname = [ a.Value for a in targetrd.ResourceAttributes if a.Name == 'VM Name' ][0] nicno = [ a.Value for a in targetrd.ResourceAttributes if a.Name == 'VM Port vNIC Name' ][0] action['actionTarget']['fullName'] = vmname action['actionTarget']['fullAddress'] = vmname vmrd = api.GetResourceDetails(vmname) cpname = vmrd.VmDetails.CloudProviderFullName cpdetails = api.GetResourceDetails(cpname) vmuid = vmrd.VmDetails.UID vmuid2cpname[vmuid] = cpname vmuid2resourcename[vmuid] = vmrd.Name if 'customActionAttributes' not in action: action['customActionAttributes'] = [] action['customActionAttributes'].append({ 'attributeName': 'VM_UUID', 'attributeValue': vmuid, }) # Vnic Name is supported on vSphere only (OpenStack relies on requests being sorted by NIC number) action['customActionAttributes'].append({ 'attributeName': 'Vnic Name', 'attributeValue': nicno, }) req = json.dumps({'driverRequest': {'actions': [action]}}) if vmuid not in vmuid2portno_req_tuples: vmuid2portno_req_tuples[vmuid] = [] try: nn = int(nicno or '0') except: nn = nicno vmuid2portno_req_tuples[vmuid].append((nn, req)) results = [] for vmuid in vmuid2portno_req_tuples: if 'openstack' in cpdetails.ResourceModelName.lower(): api.ExecuteResourceConnectedCommand( context.reservation.reservation_id, vmuid2resourcename[vmuid], 'PowerOff', 'power') # send requests one by one in order by requested NIC number -- only way to control NIC order in OpenStack for portno, req in sorted(vmuid2portno_req_tuples[vmuid]): cpname = vmuid2cpname[vmuid] logger.info( 'Executing single translated request on cloud provider %s: vmuid=%s portno=%s req=%s' % (cpname, vmuid, str(portno), req)) nr = api.ExecuteCommand( context.reservation.reservation_id, cpname, 'Resource', 'ApplyConnectivityChanges', [InputNameValue('request', req)]).Output logger.info('Result: %s' % nr) onr = json.loads(nr) onra = onr['driverResponse']['actionResults'][0] results.append(onra) if 'openstack' in cpdetails.ResourceModelName.lower(): api.ExecuteResourceConnectedCommand( context.reservation.reservation_id, vmuid2resourcename[vmuid], 'PowerOn', 'power') return json.dumps({'driverResponse': {'actionResults': results}})
def test_session_id(self, session: CloudShellAPISession, context: ResourceCommandContext) -> None: session_id = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_session_id") assert os.environ["COMPUTERNAME"].replace("-", "_") in session_id.Output cmd_inputs = [ InputNameValue("obj_ref", "system1"), InputNameValue("child_type", "project"), ] project = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_children", cmd_inputs) assert len(json.loads(project.Output)) == 1 assert json.loads(project.Output)[0] == "project1" project_obj = json.loads(project.Output)[0] cmd_inputs = [InputNameValue("obj_ref", project_obj)] project_children = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_children", cmd_inputs) assert len(json.loads(project_children.Output)) > 1 cmd_inputs = [ InputNameValue("obj_ref", "system1"), InputNameValue("child_type", "AutomationOptions"), ] options = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_children", cmd_inputs) options_ref = json.loads(options.Output)[0] cmd_inputs = [InputNameValue("obj_ref", options_ref)] old_options_attrs = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_attributes", cmd_inputs) cmd_inputs = [ InputNameValue("obj_ref", options_ref), InputNameValue("attr_name", "LogLevel"), InputNameValue("attr_value", "INFO"), ] session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "set_attribute", cmd_inputs) cmd_inputs = [InputNameValue("obj_ref", options_ref)] new_options_attrs = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "get_attributes", cmd_inputs) assert json.loads(old_options_attrs.Output)["LogLevel"] != json.loads( new_options_attrs.Output)["LogLevel"] assert json.loads(new_options_attrs.Output)["LogLevel"] == "INFO" parameters = { "Parent": project_obj, "ResultParent": project_obj, "ConfigType": "Generator", "ResultType": "GeneratorPortResults", } cmd_inputs = [ InputNameValue("command", "ResultsSubscribe"), InputNameValue("parameters_json", json.dumps(parameters)), ] output = session.ExecuteCommand(get_reservation_id(context), ALIAS, "Service", "perform_command", cmd_inputs) assert json.loads(output.Output)["State"] == "COMPLETED"
sv_user = '******' sv_password = '******' sv_start_url = resource['attributes']['Web Interface'] sv_ip = re.search(r'://([^:/]*)[/:]', sv_start_url).groups()[0] sv_base_url = sv_start_url.replace('actions/start', '') r = requests.get(sv_base_url, auth=(sv_user, sv_password)) if r.status_code >= 400: raise Exception('Failed to query virtual service %s: %d: %s' % (sv_base_url, r.status_code, r.text)) port = re.search(r'<ResourceName>(\d+)', r.text).groups()[0] r = requests.post(sv_start_url, auth=(sv_user, sv_password)) # if r.status_code >= 400: # raise Exception('Failed to start virtual service %s: %d: %s' % (sv_start_url, r.status_code, r.text)) for r in rd.Resources: if 'Apache' in r.Name: # for ra in csapi.GetResourceDetails(r.Name).ResourceAttributes: # if ra.Name == 'Web Interface': # if ra.Value == '': csapi.ExecuteCommand(resid, r.Name, 'Resource', 'Configure_Service_Endpoint', [ InputNameValue('Endpoint', 'http://%s:%s' % (sv_ip, port)), ], True) csapi.Logoff() print 'Virtualized SalesForce endpoint: %s:%s' % (sv_ip, port)
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", # printOutput=True).Output output = api.ExecuteCommand(reservationId=SANDBOX_ID, targetName="vcenter 110", targetType="Resource", commandName="GetVmDetails", printOutput=True) pass
reservation = json.loads(os.environ["RESERVATIONCONTEXT"]) resource = json.loads(os.environ["RESOURCECONTEXT"]) connectivity = json.loads(os.environ["QUALICONNECTIVITYCONTEXT"]) attr = resource["attributes"] api = CloudShellAPISession(host=connectivity["serverAddress"], token_id=connectivity["adminAuthToken"], domain=reservation["domain"]) resource_state = api.GetResourceLiveStatus(resource["fullname"]) time.sleep(random.randint(4, 9)) if "Online" in resource_state.liveStatusName and attr["Power State"] == "On": status, description = InputNameValue( "Status", resource_state.liveStatusName), InputNameValue( "Description", "Healthcheck last ran at: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) elif attr["Power State"] == "On": status, description = InputNameValue("Status", "Online"), InputNameValue( "Description", "Healthcheck last ran at: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) else: status, description = InputNameValue("Status", "Error"), InputNameValue( "Description", "Healthcheck last failed at: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) api.ExecuteCommand(reservation["id"], resource["name"], 0, "GenericSetResourceStatus", [status, description]) api.Logoff()
import os import json from cloudshell.api.cloudshell_api import CloudShellAPISession, InputNameValue reservation = json.loads(os.environ["RESERVATIONCONTEXT"]) connectivity = json.loads(os.environ["QUALICONNECTIVITYCONTEXT"]) csapi = CloudShellAPISession(connectivity["serverAddress"], connectivity["adminUser"], connectivity["adminPass"], reservation["domain"]) resid = reservation["id"] rd = csapi.GetReservationDetails(resid).ReservationDescription for r in rd.Resources: if 'blaze' in r.Name.lower(): csapi.ExecuteCommand(resid, r.Name, 'Resource', 'Start_Traffic', [], True) break csapi.Logoff()
from cloudshell.api.cloudshell_api import CloudShellAPISession, InputNameValue # print os.environ reservation = json.loads(os.environ["RESERVATIONCONTEXT"]) connectivity = json.loads(os.environ["QUALICONNECTIVITYCONTEXT"]) csapi = CloudShellAPISession(connectivity["serverAddress"], connectivity["adminUser"], connectivity["adminPass"], reservation["domain"]) resid = reservation["id"] rd = csapi.GetReservationDetails(resid).ReservationDescription for r in rd.Resources: if 'salesforce' in r.Name.lower(): # for ra in csapi.GetResourceDetails(r.Name).ResourceAttributes: # if ra.Name == 'Web Interface': # if ra.Value == '': csapi.ExecuteCommand( resid, r.Name, 'Resource', 'Activate_Virtual_Endpoint', [ # InputNameValue('Endpoint', 'http://%s:%s' % (sv_ip, port)), ], True) csapi.Logoff()
# get matrices for inputs reservation = json.loads(os.environ["RESERVATIONCONTEXT"]) resource = json.loads(os.environ["RESOURCECONTEXT"]) connectivity = json.loads(os.environ["QUALICONNECTIVITYCONTEXT"]) # log into the API csapi = CloudShellAPISession(connectivity["serverAddress"], token_id=connectivity["adminAuthToken"], domain=reservation["domain"]) csapi.WriteMessageToReservationOutput(reservation["id"], "Beginning to restore " + resource["name"] + "...") # save the old status live_status = csapi.GetResourceLiveStatus(resource["name"]) # update to backing up 0% csapi.ExecuteCommand(reservation["id"], resource["name"], "Resource", "GenericSetResourceStatus", [CmdInput("Status", "Progress 0"), CmdInput("Description", "Restoring...")]) time.sleep(random.randint(3,5)) # update to backing up 40% csapi.ExecuteCommand(reservation["id"], resource["name"], "Resource", "GenericSetResourceStatus", [CmdInput("Status", "Progress 40"), CmdInput("Description", "Restoring...")]) time.sleep(random.randint(2,5)) # update to backing up 60% csapi.ExecuteCommand(reservation["id"], resource["name"], "Resource", "GenericSetResourceStatus", [CmdInput("Status", "Progress 60"), CmdInput("Description", "Restoring...")]) time.sleep(random.randint(3,6)) # update to backing up 80% csapi.ExecuteCommand(reservation["id"], resource["name"], "Resource", "GenericSetResourceStatus", [CmdInput("Status", "Progress 80"), CmdInput("Description", "Restoring...")]) time.sleep(random.randint(4,9)) newDescription = ""