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)
Beispiel #2
0
    def health_check(self, context):
        """
        :type context: ResourceCommandContext
        """
        self._logger = self._get_logger(context)
        self._api_session = self._get_api_session(context)

        self._write_message_to_reservation_console(
            "Starting Health Check on: \"" + context.resource.name + '"')
        time.sleep(5)
        cpu_load = random.randrange(0, 100)
        memory_load = random.randrange(0, 100)
        hdd_load = random.randrange(0, 100)
        self._write_message_to_reservation_console("CPU Load is: " +
                                                   str(cpu_load))
        self._write_message_to_reservation_console("Memory Load is: " +
                                                   str(memory_load))
        self._write_message_to_reservation_console("HDD Load is: " +
                                                   str(hdd_load))
        self._api_session.SetAttributesValues([
            ResourceAttributesUpdateRequest(context.resource.fullname, [
                AttributeNameValue('Putshell.CPU Load', str(cpu_load)),
                AttributeNameValue('Putshell.Memory Load', str(memory_load)),
                AttributeNameValue('Putshell.HDD Load', str(hdd_load))
            ])
        ])
        self._api_session.SetResourceLiveStatus(context.resource.fullname,
                                                'Online', '')
Beispiel #3
0
    def _upload_resource(self,
                         cs_session,
                         entry,
                         resource_family,
                         resource_model,
                         driver_name,
                         attribute_prefix=""):
        """

        :param cs_session:
        :param entry:
        :param resource_family:
        :param resource_model:
        :param driver_name:
        :param attribute_prefix:
        :return:
        """
        if entry.folder_path != "":
            # create folder before uploading resource. If folder was already created it will return successful result
            cs_session.CreateFolder(folderFullPath=entry.folder_path)

        try:
            resource_name = self._create_cs_resource(
                cs_session=cs_session,
                resource_name=entry.device_name,
                resource_family=resource_family,
                resource_model=resource_model,
                device_ip=entry.ip,
                folder_path=entry.folder_path)
        except CloudShellAPIError as e:
            if e.code == CloudshellAPIErrorCodes.UNABLE_TO_LOCATE_FAMILY_OR_MODEL:
                return
            else:
                raise

        self.logger.info(
            "Adding attributes to the resource {}".format(resource_name))
        attributes = [
            AttributeNameValue("{}{}".format(attribute_prefix, key), value)
            for key, value in entry.attributes.iteritems()
        ]

        cs_session.SetAttributesValues(
            [ResourceAttributesUpdateRequest(resource_name, attributes)])

        self.logger.info(
            "Attaching driver to the resource {}".format(resource_name))
        self._add_resource_driver(cs_session=cs_session,
                                  resource_name=resource_name,
                                  driver_name=driver_name)

        if self.autoload:
            self.logger.info("Autoloading resource {}".format(resource_name))
            cs_session.AutoLoad(resource_name)

        return resource_name
Beispiel #4
0
 def set_resource_attributes(self, resource_name: str, namespace: str,
                             attributes: dict[str, str]):
     """Set attributes for the resource."""
     logger.info(f"Setting attributes for {resource_name}\n{attributes}")
     namespace += "." if namespace else ""
     attributes = [
         AttributeNameValue(f"{namespace}{key}", value)
         for key, value in attributes.items()
     ]
     self._api.SetAttributesValues(
         [ResourceAttributesUpdateRequest(resource_name, attributes)])
 def create_autoload_resource(self, model: str, full_name: str, address: Optional[str] = 'na',
                              attributes: Optional[list] = None) -> ResourceInfo:
     """ Create resource for Autoload testing. """
     folder = path.dirname(full_name)
     name = path.basename(full_name)
     existing_resource = [r for r in self.session.GetResourceList().Resources if r.Name == name]
     if existing_resource:
         self.session.DeleteResource(existing_resource[0].Name)
     resource = self.session.CreateResource(resourceModel=model, resourceName=name, folderFullPath=folder,
                                            resourceAddress=address,
                                            resourceDescription='should be removed after test')
     self.session.UpdateResourceDriver(resource.Name, model)
     if attributes:
         self.session.SetAttributesValues([ResourceAttributesUpdateRequest(full_name, attributes)])
     return resource
Beispiel #6
0
def create_fake_L2(api, fakel2name, vlantype, portfullpath2vmname_nicname):
    """
    Creates a fake L2 switch and physically connects its ports
    to the specified user-facing VNF resource ports.

    Stores the underlying VM name and NIC name on each L2 port.

    The fake L2 driver will call the underlying cloud provider
    when connections are performed on the user-facing ports.

    :param api: CloudShellAPISession
    :param fakel2name: str
    :param vlantype: str : VLAN or VXLAN -- L2 switch resource must match the cloud provider
    :param portfullpath2vmname_nicname: dict(str, (str, str)) : map user-facing VNF port full path to (vm name, nic name)
    :return:
    """
    api.CreateResource('Switch', 'VNF Connectivity Manager Virtual L2', fakel2name, '0')
    api.SetAttributeValue(fakel2name, 'Vlan Type', vlantype)
    api.UpdateResourceDriver(fakel2name, 'VNF Connectivity Manager L2 Driver')

    portfullpaths = sorted(portfullpath2vmname_nicname.keys())
    api.CreateResources([
        ResourceInfoDto(
            'VNF Connectivity Manager Port',
            'VNF Connectivity Manager L2 Port',
            'port%d' % i,
            '%d' % i,
            '',
            fakel2name,
            ''
        )
        for i in range(0, len(portfullpaths))
    ])

    api.UpdatePhysicalConnections([
        PhysicalConnectionUpdateRequest(vmxport, '%s/port%d' % (fakel2name, i), '1')
        for i, vmxport in enumerate(portfullpaths)
    ])

    api.SetAttributesValues([
        ResourceAttributesUpdateRequest('%s/port%d' % (fakel2name, i), [
            AttributeNameValue('VM Name', portfullpath2vmname_nicname[portfullpath][0]),
            AttributeNameValue('VM Port vNIC Name', portfullpath2vmname_nicname[portfullpath][1]),
        ])
        for i, portfullpath in enumerate(portfullpaths)
    ])
 def _get_inventory(self, name, properties):
     self.resource = self.session.CreateResource(resourceFamily='Traffic Generator Chassis',
                                                 resourceModel='PerfectStorm Chassis',
                                                 resourceName=name,
                                                 resourceAddress=properties['address'],
                                                 folderFullPath='Testing',
                                                 parentResourceFullPath='',
                                                 resourceDescription='should be removed after test')
     self.session.UpdateResourceDriver(self.resource.Name, 'PerfectStormChassisDriver')
     attributes = [AttributeNameValue('Controller Address', properties['controller']),
                   AttributeNameValue('User', properties['user']),
                   AttributeNameValue('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)
Beispiel #8
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!")
Beispiel #9
0
    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")
from cloudshell.api.cloudshell_api import CloudShellAPISession, ResourceAttributesUpdateRequest, AttributeNameValue

username = '******'
password = '******'
server = 'localhost'
domain = 'Global'

session = CloudShellAPISession(username=username,
                               password=password,
                               domain=domain,
                               host=server)
res_id = '111'

attr_changes = []
a = ResourceAttributesUpdateRequest(ResourceFullName='resource_name',
                                    AttributeNamesValues=[
                                        AttributeNameValue(Name='Name',
                                                           Value='value'),
                                        AttributeNameValue(Name='Name_2',
                                                           Value='value_2')
                                    ])
attr_changes.append(a)
session.SetAttributesValues(resourcesAttributesUpdateRequests=attr_changes)