Ejemplo n.º 1
0
 def test_auth_error(self):
     with self.assertRaises(pyone.OneAuthenticationException):
         # Disable SSL checks for TEST environment only, and deal with Centos, see issue #13
         if "PYTHONHTTPSVERIFY" in os.environ:
             xone = pyone.OneServer(testEndpoint,
                                    session="oneadmin:invalidpass")
         else:
             xone = pyone.OneServer(
                 testEndpoint,
                 session="oneadmin:invalidpass",
                 context=ssl._create_unverified_context())
         xone.hostpool.info()
Ejemplo n.º 2
0
    def __init__(self):

        self.defaultgroup = 'group_all'
        self.one_server = None
        self.one_username = None
        self.one_password = None
        self.validate_certs = True
        self.read_host_inventory = False
        self.use_host_interface = True
        self.meta = {}
        self.read_settings()
        self.read_cli()

        if self.one_server and self.one_username:
            try:
                one = pyone.OneServer(self.one_server, session=self.one_username+":"+self.one_password)
            except (Exception, SystemExit) as e:
                print("Error: Could not login to One server. Check your one.ini.", file=sys.stderr)
                sys.exit(1)

            
	    if self.options.list:
	        vm = self.get_list(one)
 	        print(json.dumps(vm, indent=2))

		
            else:
                print("usage: --list>", file=sys.stderr)
                sys.exit(1)

        else:
            print("Error: credentials are required.", file=sys.stderr)
            sys.exit(1)
Ejemplo n.º 3
0
    def Conectar(self, ip, user, passwd):
        self.HPVS = "http://{}:2633/RPC2".format(ip)
        credencial = "{}:{}".format(user, passwd)

        self.one = pyone.OneServer(self.HPVS,
                                   session=credencial,
                                   context=ssl._create_unverified_context())
Ejemplo n.º 4
0
    def create_slice_prerequisites(
        self,
        tenant_project_name,
        tenant_project_description,
        tenant_project_user,
        tenant_project_password,
        slice_uuid,
    ):
        """
        Creates the tenant (project, user, security_group) on the specified vim
        """
        conn = pyone.OneServer(self.auth_url,
                               session="{0}:{1}".format(
                                   self.username, self.password))
        # creates the project in OpenNebula
        project = self.create_project(conn, tenant_project_name,
                                      tenant_project_description)

        # creates the user
        user = self.create_user(conn, tenant_project_user, "password", project)

        # creates the security group and rules
        # sec_group = self.create_sec_group(conn, tenant_project_name, project)
        sec_group = "dummy"

        return {
            "sliceProjectName": project,
            "sliceUserName": user,
            "secGroupName": sec_group
        }
Ejemplo n.º 5
0
    def get_list(self, one):

	    if self.one_server and self.one_username:
            try:
                one = pyone.OneServer(self.one_server, session=self.one_username+":"+self.one_password)
            except (Exception, SystemExit) as e:
                print("Error: Could not login to One server. Check your one.ini.", file=sys.stderr)
                sys.exit(1)


        hosts_data = one.vmpool.info(-1,-1,-1,3)
        data2 = {'_meta': {'hostvars': {}}}
        data2[self.defaultgroup] = self.hoststub()
        for host in range(len(hosts_data.VM)):
            hostname = hosts_data.VM[host].get_NAME()
            hostvars = dict()
            data2[hostname[0:4]] =  self.hoststub()
  	    for i in range(len(hosts_data.VM)):
		hostname2 = hosts_data.VM[i].get_NAME()
		if hostname[0:4] in hostname2:       
	            data2[hostname[0:4]]['hosts'].append(hostname2)
            if isinstance(hosts_data.VM[host].TEMPLATE['NIC'], list):
               hostvars['ansible_ssh_host'] = hosts_data.VM[host].TEMPLATE['NIC'][0]['IP']
               data2['_meta']['hostvars'][hostname] = hostvars

        return data2
Ejemplo n.º 6
0
def main():
    fields = {
        "api_url": {
            "required": False,
            "type": "str"
        },
        "api_username": {
            "required": False,
            "type": "str"
        },
        "api_password": {
            "required": False,
            "type": "str",
            "no_log": True
        },
        "ids": {
            "required": False,
            "aliases": ['id'],
            "type": "list"
        },
        "name": {
            "required": False,
            "type": "str"
        },
    }

    module = AnsibleModule(argument_spec=fields,
                           mutually_exclusive=[['ids', 'name']],
                           supports_check_mode=True)
    if module._name in ('one_image_facts',
                        'community.general.one_image_facts'):
        module.deprecate(
            "The 'one_image_facts' module has been renamed to 'one_image_info'",
            version='3.0.0',
            collection_name='community.general')  # was Ansible 2.13

    if not HAS_PYONE:
        module.fail_json(msg='This module requires pyone to work!')

    auth = get_connection_info(module)
    params = module.params
    ids = params.get('ids')
    name = params.get('name')
    client = pyone.OneServer(auth.url,
                             session=auth.username + ':' + auth.password)

    result = {'images': []}
    images = []

    if ids:
        images = get_images_by_ids(module, client, ids)
    elif name:
        images = get_images_by_name(module, client, name)
    else:
        images = get_all_images(client).IMAGE

    for image in images:
        result['images'].append(get_image_info(image))

    module.exit_json(**result)
Ejemplo n.º 7
0
 def get_one_server(self):
     """
     Connect to OpenNebula server
     """
     uname = self.config['one']['username']
     pwd = self.config['one']['password']
     endpoint = self.config['one']['endpoint']
     one_client = pyone.OneServer(endpoint, session = uname+':'+pwd)
     self.client = one_client
Ejemplo n.º 8
0
    def upload_image(auth_url,
                     one_username,
                     one_password,
                     f,
                     server_ip,
                     server_username,
                     server_password,
                     image_dir,
                     ssh_port=22,
                     image_type="OS"):
        """
        Transfers the image file to the ONE server and registers it to the ONE
        """
        import os

        try:
            ssh_scp_files(server_ip, server_username, server_password, f,
                          image_dir, ssh_port)
            #ssh_transfer_files(server_ip, server_username, server_password, f, image_dir, ssh_port)

            # sife of the file in bytes
            size = os.path.getsize(f)
            # convert to MB
            size = int(size / (1024 * 1024))

            # Resgister the image
            conn = pyone.OneServer(auth_url,
                                   session="{0}:{1}".format(
                                       one_username, one_password))
            name, file_extension = os.path.splitext(f)
            description = f
            source = image_dir + f

            # find the default datastore
            dsid = 0
            datastores = conn.datastorepool.info()
            for ds in datastores.DATASTORE:
                if ds.NAME == "default":
                    dsid = ds.ID
                    break

            # creation of the image template and registration
            #template='''\nNAME="%s"\nPATH="%s"\nTYPE="%s"\nDESCRIPTION="%s"\nSIZE="%d"''' % \
            template='''\nNAME="%s"\nPATH="%s"\nTYPE="%s"\nDRIVER="qcow2"\nDESCRIPTION="%s"\nSIZE="%d"''' % \
                     (name, source, image_type, description, size*3)
            logger.debug("template: {}".format(template))
            logger.debug("DSID: {}".format(dsid))
            r = conn.image.allocate(template, dsid)
        except Exception as e:
            logger.exception("Failed uploading image: {}".format(str(e)))
            delete_remote_file(server_ip, server_username, server_password,
                               str(image_dir + f), ssh_port)
            return "Failed uploading image: {}".format(str(e)), 400
        delete_remote_file(server_ip, server_username, server_password,
                           str(image_dir + f), ssh_port)
        return "Image uploaded successfully", 201
Ejemplo n.º 9
0
    def get_vm_list(self):
        if self.socket is None:
            socket = pyone.OneServer(self.config['api'],
                                     session="{}:{}".format(
                                         self.config['username'],
                                         self.config['password']))

            self.socket = socket.vmpool.info(-2, -1, -1, -1)

        return self.socket.VM
Ejemplo n.º 10
0
 def __init__(self):
     self._server = pyone.OneServer("http://192.168.1.10:2633/RPC2",
                                    session="oneadmin:opennebula")
     self.upper = 0.7
     self.lower = 0.3
     self.times = 0
     self.minimal = 10
     self.minimal_vms = 1
     self.running_vms = 0
     self.monitor_period = 1
Ejemplo n.º 11
0
 def __init__(self, uuid, auth_url, project_name, username, password):
     """
     Initialize an object of the class
     """
     self.uuid = uuid
     self.auth_url = auth_url
     self.project_name = project_name
     self.username = username
     self.password = password
     conn = pyone.OneServer(self.auth_url,
                            session="{0}:{1}".format(username, password))
Ejemplo n.º 12
0
def main():
    fields = {
        "api_url": {
            "required": False,
            "type": "str"
        },
        "api_username": {
            "required": False,
            "type": "str"
        },
        "api_password": {
            "required": False,
            "type": "str",
            "no_log": True
        },
        "ids": {
            "required": False,
            "aliases": ['id'],
            "type": "list",
            "elements": "str"
        },
        "name": {
            "required": False,
            "type": "str"
        },
    }

    module = AnsibleModule(argument_spec=fields,
                           mutually_exclusive=[['ids', 'name']],
                           supports_check_mode=True)

    if not HAS_PYONE:
        module.fail_json(msg='This module requires pyone to work!')

    auth = get_connection_info(module)
    params = module.params
    ids = params.get('ids')
    name = params.get('name')
    client = pyone.OneServer(auth.url,
                             session=auth.username + ':' + auth.password)

    if ids:
        images = get_images_by_ids(module, client, ids)
    elif name:
        images = get_images_by_name(module, client, name)
    else:
        images = get_all_images(client).IMAGE

    result = {
        'images': [get_image_info(image) for image in images],
    }

    module.exit_json(**result)
Ejemplo n.º 13
0
    def __init__(self, host=config.host, port=config.port,
                 protocol=config.protocol, path=config.path,
                 user=config.user, password=config.password):

        self.host = host
        self.port = port
        self.protocol = protocol
        self.path = path
        self.user = user
        self.password = password
        self.vms = None

        self.api = pyone.OneServer(self.url(), session=config.user + ":" + config.password)
Ejemplo n.º 14
0
    def _get_vm_pool(self):
        auth = self._get_connection_info()

        if not (auth.username and auth.password):
            raise AnsibleError('API Credentials missing. Check OpenNebula inventory file.')
        else:
            one_client = pyone.OneServer(auth.url, session=auth.username + ':' + auth.password)

        # get hosts (VMs)
        try:
            vm_pool = one_client.vmpool.infoextended(-2, -1, -1, 3)
        except Exception as e:
            raise AnsibleError("Something happened during XML-RPC call: {e}".format(e=to_native(e)))

        return vm_pool
Ejemplo n.º 15
0
 def delete_proj_user_by_name(self, name):
     """
     Deletes user and project
     """
     conn = pyone.OneServer(self.auth_url,
                            session="{0}:{1}".format(
                                self.username, self.password))
     userpool = conn.userpool.info(-1, -1, -1)
     for user in userpool.USER:
         if user.get_NAME() == name:
             group = user.get_GROUPS()[0]
             # delete group
             conn.group.delete(group)
             # delete user
             return conn.user.delete(user.get_ID())
     logger.warning("Delete user ONE: user does not exist: ", name)
def get_vms():
    """List active VMs in the pool, return a list.

    The values essentailly mean display all running
    VMs, more information can be found here:
    http://docs.opennebula.org/5.4/integration/system_interfaces/api.html#one-vmpool-info
    """

    args = get_args()
    one_auth = ConfigParser.SafeConfigParser()
    one_auth.read(args.config)
    one_host = args.host
    one_xmlrpc = 'http://' + one_host + ':2633/RPC2'
    one_user = one_auth.get('one backups', 'user')
    one_password = one_auth.get('one backups', 'password')
    one_session = (one_user + ':' + one_password)
    one = pyone.OneServer(one_xmlrpc, session=one_session)
    vmlist = one.vmpool.info(-2, 0, -1, 3).VM
    return vmlist
Ejemplo n.º 17
0
 def delete_proj_user(self, user_id):
     """
     Deletes user and project
     """
     conn = pyone.OneServer(self.auth_url,
                            session="{0}:{1}".format(
                                self.username, self.password))
     try:
         user = conn.user.info(user_id)
         group = user.get_GROUPS().ID[0]
         # delete group
         conn.group.delete(group)
         # delete user
         return conn.user.delete(user.get_ID())
     except pyone.OneNoExistsException as e:
         logger.exception("Failed. User trying to delete, doesn't exist: ",
                          user_id)
     except Exception as e:
         logger.exception(
             "Failed. User trying to delete, group doesn't exist: ",
             user_id)
Ejemplo n.º 18
0
def get_one_info(one_user, one_password, one_endpoint) -> dict:
    """
    Return data of virtual machines from OpenNebula.
    """
    one = pyone.OneServer(one_endpoint,
                          session="{}:{}".format(one_user, one_password))

    vm_pool = one.vmpool.info(
        -3,  # only own vm
        -1,  # When the next parameter is >= -1 this is the Range start ID.
        # Can be -1. For smaller values this is the offset used for
        # pagination.
        -1,  # For values >= -1 this is the Range end ID. Can be -1 to get
        # until the last ID. For values < -1 this is the page size used
        # for pagination.
        3  # vm stat - active
    )

    vms = dict()
    for vm in vm_pool.get_VM():
        vms[vm.get_NAME()] = vm.get_TEMPLATE()["NIC"]["IP"]
    return vms
Ejemplo n.º 19
0
 def _new_one_connection(self):
     return pyone.OneServer(self.url, session=self.user + ':' + self.passwd)
import pyone

one = pyone.OneServer("http://5.254.20.106:2633/RPC2", session="oneadmin:BFGDETio2020")

#Get the name and id of all templates available
vm_template = one.templatepool.info(-1,-1,-1).VMTEMPLATE[0]
id = vm_template.get_ID()
name = vm_template.get_NAME()
print(id, name)

#Function test of initialising pyone server
def test(first, second):
    first = "http://5.254.20.106:2633/RPC2"
    second = "oneadmin:BFGDETio2020"
    one = pyone.OneServer(first, session=second)
    templateinfo = one.template.info(5, True)

#test("http://5.254.20.106:2633/RPC2", "oneadmin:BFGDETio2020")

#Get template information
templateinfo = one.template.info(5, True)
print (templateinfo.NAME, templateinfo.ID)
my_vm = one.vmpool.info(-1,-1,-1,-1).VM[0]
id = my_vm.get_ID()
name = my_vm.get_NAME()
template = my_vm.get_TEMPLATE()
print(id, name, template)

#Starting and suspending vm actions
one.vm.action('resume', 7)
one.vm.action('suspend', 2)
Ejemplo n.º 21
0
class OpenNebulaClient:
    """
    OpenNebula vCenter Automation API client.
    See also: http://docs.opennebula.io/5.8/integration/system_interfaces/api.html#actions-for-virtual-machine-management
    """
    one = pyone.OneServer("http://5.254.20.106:2633/RPC2",
                          session="oneadmin:BFGDETio2020")

    #allocate vm, deploy vm on host, action on vm, migrate vm to target host, attach disk to vm, detach disk from vm, attach nic to vm, detach nic from vm, rename vm,
    #create vm snapshot, revert vm to snapshot, delete vm snapshot, info on vm, monitoring vm,

    def start_vm(vm_id):
        """
        Power on given virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return one.vm.action('resume', vm_id)

    def stop_vm(vm_id):
        """
        Power off given virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return one.vm.action('suspend', vm_id)

    def list_clusters(self):
        return self._get('vcenter/cluster')

    def get_cluster(self, cluster_id):
        return self._get('vcenter/cluster/{0}'.format(cluster_id))

    def list_datacenters(self):
        return self._get('vcenter/datacenter')

    def list_datastores(self):
        return self._get('vcenter/datastore')

    def list_resource_pools(self):
        return self._get('vcenter/resource-pool')

    def list_networks(self):
        return self._get('vcenter/network')

    def list_folders(self, folder_type=None):
        """
        Returns information about folders in vCenter.
        :param folder_type: Type (DATACENTER, DATASTORE, HOST, NETWORK, VIRTUAL_MACHINE) of the vCenter Server folder.
        :rtype: List[Dict]
        """
        params = {}
        if folder_type:
            params['filter.type'] = folder_type
        return self._get('vcenter/folder', params=params)

    def list_vms(self):
        """
        Get all the VMs from vCenter inventory.
        """
        return self._get('vcenter/vm')

    def get_vm(self, vm_id):
        """
        Returns information about a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._get('vcenter/vm/{}'.format(vm_id))

    def create_vm(self, spec):
        """
        Creates a virtual machine.

        :param spec: new virtual machine specification
        :type spec: dict
        :return: Virtual machine identifier
        :rtype: string
        """
        return self._post('vcenter/vm', json=spec)

    def delete_vm(self, vm_id):
        """
        Deletes a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._delete('vcenter/vm/{}'.format(vm_id))

    def reset_vm(self, vm_id):
        """
        Resets a powered-on virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._post('vcenter/vm/{}/power/reset'.format(vm_id))

    def suspend_vm(self, vm_id):
        """
        Suspends a powered-on virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._post('vcenter/vm/{}/power/suspend'.format(vm_id))

    def get_guest_power(self, vm_id):
        """
        Returns information about the guest operating system power state.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._get('vcenter/vm/{}/guest/power'.format(vm_id))

    def shutdown_guest(self, vm_id):
        """
        Issues a request to the guest operating system asking
        it to perform a clean shutdown of all services.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._post(
            'vcenter/vm/{}/guest/power?action=shutdown'.format(vm_id))

    def reboot_guest(self, vm_id):
        """
        Issues a request to the guest operating system asking it to perform a reboot.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._post(
            'vcenter/vm/{}/guest/power?action=reboot'.format(vm_id))

    def get_cpu(self, vm_id):
        """
        Returns the CPU-related settings of a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._get('vcenter/vm/{}/hardware/cpu'.format(vm_id))

    def update_cpu(self, vm_id, spec):
        """
        Updates the CPU-related settings of a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        :param spec: CPU specification
        :type spec: dict
        """
        return self._patch('vcenter/vm/{}/hardware/cpu'.format(vm_id),
                           json=spec)

    def get_memory(self, vm_id):
        """
        Returns the memory-related settings of a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        """
        return self._get('vcenter/vm/{}/hardware/memory'.format(vm_id))

    def update_memory(self, vm_id, spec):
        """
        Updates the memory-related settings of a virtual machine.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        :param spec: CPU specification
        :type spec: dict
        """
        return self._patch('vcenter/vm/{}/hardware/memory'.format(vm_id),
                           json=spec)

    def create_disk(self, vm_id, spec):
        """
        Adds a virtual disk to the virtual machine

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        :param spec: new virtual disk specification
        :type spec: dict
        """
        return self._post('vcenter/vm/{}/hardware/disk'.format(vm_id),
                          json=spec)

    def get_disk(self, vm_id, disk_id):
        """
        Returns information about a virtual disk.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param disk_id: Virtual disk identifier.
        :type disk_id: string
        """
        return self._get('vcenter/vm/{}/hardware/disk/{}'.format(
            vm_id, disk_id))

    def delete_disk(self, vm_id, disk_id):
        """
        Removes a virtual disk from the virtual machine.
        This operation does not destroy the VMDK file that backs the virtual disk.
        It only detaches the VMDK file from the virtual machine.
        Once detached, the VMDK file will not be destroyed when the virtual machine
        to which it was associated is deleted.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param disk_id: Virtual disk identifier.
        :type disk_id: string
        """
        return self._delete('vcenter/vm/{}/hardware/disk/{}'.format(
            vm_id, disk_id))

    def connect_cdrom(self, vm_id, cdrom_id):
        """
        Connects a virtual CD-ROM device of a powered-on virtual machine to its backing.

        :param vm_id: Virtual machine identifier
        :type vm_id: string
        :param cdrom_id: Virtual CD-ROM device identifier.
        :type cdrom_id: string
        """
        return self._post('vcenter/vm/{}/hardware/cdrom/{}/connect'.format(
            vm_id, cdrom_id))

    def disconnect_cdrom(self, vm_id, cdrom_id):
        """
        Disconnects a virtual CD-ROM device of a powered-on virtual machine from its backing.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param cdrom_id: Virtual CD-ROM device identifier.
        :type cdrom_id: string
        """
        return self._post('vcenter/vm/{}/hardware/cdrom/{}/disconnect'.format(
            vm_id, cdrom_id))

    def create_nic(self, vm_id, network_id):
        """
        Adds a virtual Ethernet adapter to the virtual machine.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param network_id: Identifier of the network that backs the virtual Ethernet adapter.
        :type network_id: string
        """
        spec = {
            'backing': {
                'network': network_id,
                'type': 'DISTRIBUTED_PORTGROUP',
            },
            'start_connected': True,
        }
        return self._post('vcenter/vm/{}/hardware/ethernet'.format(vm_id),
                          json=spec)

    def delete_nic(self, vm_id, nic_id):
        """
        Removes a virtual Ethernet adapter from the virtual machine.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param nic_id: Virtual Ethernet adapter identifier.
        :type nic_id: string
        """
        return self._delete('vcenter/vm/{}/hardware/ethernet/{}'.format(
            vm_id, nic_id))

    def list_nics(self, vm_id):
        """
        Returns list of Ethernet adapters by virtual machine ID.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :rtype: List[Dict]
        """
        result = []
        for nic in self.list_nic_ids(vm_id):
            nic_payload = self.get_nic(vm_id, nic['nic'])
            nic_payload['nic'] = nic['nic']
            result.append(nic_payload)
        return result

    def list_nic_ids(self, vm_id):
        """
        Returns list of Ethernet adapter IDs by virtual machine ID.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        """
        return self._get('vcenter/vm/{}/hardware/ethernet'.format(vm_id))

    def get_nic(self, vm_id, nic_id):
        """
        Returns information about a virtual Ethernet adapter.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param nic_id: Virtual Ethernet adapter identifier.
        :type nic_id: string
        """
        return self._get('vcenter/vm/{}/hardware/ethernet/{}'.format(
            vm_id, nic_id))

    def connect_nic(self, vm_id, nic_id):
        """
        Connects a virtual Ethernet adapter of a powered-on virtual machine to its backing.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param nic_id: Virtual Ethernet adapter identifier.
        :type nic_id: string
        """
        return self._post('vcenter/vm/{}/hardware/ethernet/{}/connect'.format(
            vm_id, nic_id))

    def disconnect_nic(self, vm_id, nic_id):
        """
        Disconnects a virtual Ethernet adapter of a powered-on virtual machine from its backing.

        :param vm_id: Virtual machine identifier.
        :type vm_id: string
        :param nic_id: Virtual Ethernet adapter identifier.
        :type nic_id: string
        """
        return self._post(
            'vcenter/vm/{}/hardware/ethernet/{}/disconnect'.format(
                vm_id, nic_id))

    def list_libraries(self):
        return self._get('com/opennebula/content/library')

    def list_library_items(self, library_id):
        params = {'library_id': library_id}
        return self._get('com/opennebula/content/library/item', params=params)

    def get_library_item(self, library_item_id):
        return self._get('com/opennebula/content/library/item/id:{}'.format(
            library_item_id))

    def get_template_library_item(self, library_item_id):
        return self._get(
            'vcenter/vm-template/library-items/{}'.format(library_item_id))

    def list_all_templates(self):
        items = []
        for library_id in self.list_libraries():
            for library_item_id in self.list_library_items(library_id):
                library_item = self.get_library_item(library_item_id)
                if library_item['type'] == 'vm-template':
                    template = self.get_template_library_item(library_item_id)
                    items.append({
                        'library_item': library_item,
                        'template': template,
                    })
        return items

    def deploy_vm_from_template(self, library_item_id, spec):
        """
        Deploys a virtual machine as a copy of the source virtual machine
        template contained in the library item specified by library_item_id.

        :param library_item_id: identifier of the content library item containing the source virtual machine template to be deployed.
        :param spec: deployment specification
        :return: Identifier of the deployed virtual machine.
        :rtype: str
        """
        url = 'vcenter/vm-template/library-items/{}?action=deploy'.format(
            library_item_id)
        return self._post(url, json=spec)
Ejemplo n.º 22
0
 def test_auth_error(self):
     with self.assertRaises(pyone.OneAuthenticationException):
         xone = pyone.OneServer(testEndpoint, session="oneadmin:invalidpass", context=ssl._create_unverified_context())
         xone.hostpool.info()
def test(first, second):
    first = "http://5.254.20.106:2633/RPC2"
    second = "oneadmin:BFGDETio2020"
    one = pyone.OneServer(first, session=second)
    templateinfo = one.template.info(5, True)
Ejemplo n.º 24
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.pub_key = get_pub_key()
     self.one = pyone.OneServer(
         settings.ONE_API_ENDPOINT,
         session="%s:%s" % (settings.ONE_USERNAME, settings.ONE_PASSWORD))
Ejemplo n.º 25
0
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
import ssl
import pyone

testSession = "oneadmin:onepass"
testEndpoint = 'https://192.168.121.55/RPC2'
one = pyone.OneServer(testEndpoint, session=testSession, context=ssl._create_unverified_context())

class IntegrationTests(unittest.TestCase):

    def test_pool_info(self):
        hostpool = one.hostpool.info()
        self.assertGreater(len(hostpool.HOST), 0)
        host0 = hostpool.HOST[0]
        self.assertEqual(host0.ID, 0)

    def test_auth_error(self):
        with self.assertRaises(pyone.OneAuthenticationException):
            xone = pyone.OneServer(testEndpoint, session="oneadmin:invalidpass", context=ssl._create_unverified_context())
            xone.hostpool.info()

    def test_market_info(self):
Ejemplo n.º 26
0
         config_file_name))
     print(Error)
     exit(-1)
 except Exception as Error:
     print(Error)
     exit(-1)
 try:
     nb = pynetbox.api(**cfg['netbox'])
 except KeyError as Error:
     print('Netbox configuration not found.')
     exit(-1)
 except Exception as Error:
     print('PyNetbox: ', Error)
     exit(-1)
 try:
     one = pyone.OneServer(cfg['one']['endpoint'],
                           session=cfg['one']['credentials'])
     one_vms = one.vmpool.info(-2, -1, -1, -1).VM
     one_tmp_pool = one.templatepool.info(-2, -1, -1).VMTEMPLATE
     template_dict = dict(
         tuple(map(lambda tmp: (tmp.ID, tmp.NAME), one_tmp_pool)))
     cluster_name = cfg['cluster_name']
     cluster_id = cfg['cluster_id']
     vm_role_id = cfg['vm_role_id']
 except KeyError as Error:
     print('OpenNebula configuration not found.')
     exit(-1)
 except Exception as Error:
     print('OpenNebula: ', Error)
     exit(-1)
 netbox_vms = nb.virtualization.virtual_machines.filter(
     cluster_id=cluster_id)
Ejemplo n.º 27
0
 def __init__(self, ip, user, password):
     self.one = pyone.OneServer(ip, session=user + ":" + password)
     self.user = user
     self.password = password
Ejemplo n.º 28
0
 def server(self):
     if self._server is None:
         self._server = pyone.OneServer(
             self._endpoint, ':'.join([self._username, self._password]))
     return self._server
Ejemplo n.º 29
0
def main():
    fields = {
        "api_url": {
            "required": False,
            "type": "str"
        },
        "api_username": {
            "required": False,
            "type": "str"
        },
        "api_password": {
            "required": False,
            "type": "str",
            "no_log": True
        },
        "id": {
            "required": False,
            "type": "int"
        },
        "name": {
            "required": False,
            "type": "str"
        },
        "state": {
            "default": "present",
            "choices": ['present', 'absent', 'cloned', 'renamed'],
            "type": "str"
        },
        "enabled": {
            "required": False,
            "type": "bool"
        },
        "new_name": {
            "required": False,
            "type": "str"
        },
    }

    module = AnsibleModule(argument_spec=fields,
                           mutually_exclusive=[['id', 'name']],
                           supports_check_mode=True)

    if not HAS_PYONE:
        module.fail_json(msg='This module requires pyone to work!')

    auth = get_connection_info(module)
    params = module.params
    id = params.get('id')
    name = params.get('name')
    state = params.get('state')
    enabled = params.get('enabled')
    new_name = params.get('new_name')
    client = pyone.OneServer(auth.url,
                             session=auth.username + ':' + auth.password)

    result = {}

    if not id and state == 'renamed':
        module.fail_json(
            msg="Option 'id' is required when the state is 'renamed'")

    image = get_image_instance(module, client, id, name)
    if not image and state != 'absent':
        if id:
            module.fail_json(msg="There is no image with id=" + str(id))
        else:
            module.fail_json(msg="There is no image with name=" + name)

    if state == 'absent':
        result = delete_image(module, client, image)
    else:
        result = get_image_info(image)
        changed = False
        result['changed'] = False

        if enabled is not None:
            result = enable_image(module, client, image, enabled)
        if state == "cloned":
            result = clone_image(module, client, image, new_name)
        elif state == "renamed":
            result = rename_image(module, client, image, new_name)

        changed = changed or result['changed']
        result['changed'] = changed

    module.exit_json(**result)
Ejemplo n.º 30
0
    def create_one_client(self):
        """
        Creates an XMLPRC client to OpenNebula.
        Dependign on environment variables it will implement a test client.

        Returns: the new xmlrpc client.

        """

        test_fixture = (environ.get("ONE_TEST_FIXTURE", "False").lower()
                        in ["1", "yes", "true"])
        test_fixture_file = environ.get("ONE_TEST_FIXTURE_FILE", "undefined")
        test_fixture_replay = (environ.get("ONE_TEST_FIXTURE_REPLAY",
                                           "True").lower()
                               in ["1", "yes", "true"])
        test_fixture_unit = environ.get("ONE_TEST_FIXTURE_UNIT", "init")

        # context required for not validating SSL, old python versions won't validate anyway.
        if hasattr(ssl, '_create_unverified_context'):
            no_ssl_validation_context = ssl._create_unverified_context()
        else:
            no_ssl_validation_context = None

        # Check if the module can run
        if not HAS_PYONE:
            self.fail("pyone is required for this module")

        if 'api_url' in self.module.params:
            url = self.module.params.get("api_url",
                                         environ.get("ONE_URL", False))
        else:
            self.fail(
                "Either api_url or the environment variable ONE_URL must be provided"
            )

        if 'api_username' in self.module.params:
            username = self.module.params.get(
                "api_username", environ.get("ONE_USERNAME", False))
        else:
            self.fail(
                "Either api_username or the environment vairable ONE_USERNAME must be provided"
            )

        if 'api_password' in self.module.params:
            password = self.module.params.get(
                "api_password", environ.get("ONE_PASSWORD", False))
        else:
            self.fail(
                "Either api_password or the environment vairable ONE_PASSWORD must be provided"
            )

        session = "%s:%s" % (username, password)

        if not test_fixture:
            if not self.module.params.get(
                    "validate_certs") and "PYTHONHTTPSVERIFY" not in environ:
                return pyone.OneServer(url,
                                       session=session,
                                       context=no_ssl_validation_context)
            else:
                return pyone.OneServer(url, session)
        else:
            if not self.module.params.get(
                    "validate_certs") and "PYTHONHTTPSVERIFY" not in environ:
                one = OneServerTester(url,
                                      fixture_file=test_fixture_file,
                                      fixture_replay=test_fixture_replay,
                                      session=session,
                                      context=no_ssl_validation_context)
            else:
                one = OneServerTester(url,
                                      fixture_file=test_fixture_file,
                                      fixture_replay=test_fixture_replay,
                                      session=session)
            one.set_fixture_unit_test(test_fixture_unit)
            return one