コード例 #1
0
 def tearDown(self):
     print("teardown")
     vns = oca.VirtualNetworkPool(self.c)
     vns.info()
     for vn in vns:
         if vn.name.startswith('inttest'):
             vn.delete()
コード例 #2
0
 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
                    availability_zone_index=None, availability_zone_list=None):
     """Adds a VM instance to VIM
     Params:
         start: indicates if VM must start or boot in pause mode. Ignored
         image_id,flavor_id: image and flavor uuid
         net_list: list of interfaces, each one is a dictionary with:
             name:
             net_id: network uuid to connect
             vpci: virtual vcpi to assign
             model: interface model, virtio, e2000, ...
             mac_address:
             use: 'data', 'bridge',  'mgmt'
             type: 'virtual', 'PF', 'VF', 'VFnotShared'
             vim_id: filled/added by this function
             #TODO ip, security groups
     Returns the instance identifier
     """
     self.logger.debug(
         "new_vminstance input: image='{}' flavor='{}' nics='{}'".format(image_id, flavor_id, str(net_list)))
     try:
         client = oca.Client(self.user + ':' + self.passwd, self.url)
         listaTemplate = oca.VmTemplatePool(client)
         listaTemplate.info()
         for template in listaTemplate:
             if str(template.id) == str(flavor_id):
                 cpu = ' CPU = "{}"'.format(template.template.cpu)
                 memory = ' MEMORY = "{}"'.format(template.template.memory)
                 context = ' CONTEXT = [NETWORK = "YES",SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ]'
                 graphics = ' GRAPHICS = [ LISTEN = "0.0.0.0", TYPE = "VNC" ]'
                 disk = ' DISK = [ IMAGE_ID = {}]'.format(image_id)
                 sched_requeriments = ' SCHED_REQUIREMENTS = "CLUSTER_ID={}"'.format(self.config["cluster"]["id"])
                 template_updated = cpu + memory + context + graphics + disk + sched_requeriments
                 networkListVim = oca.VirtualNetworkPool(client)
                 networkListVim.info()
                 network = ""
                 for net in net_list:
                     network_found = False
                     for network_existingInVim in networkListVim:
                         if str(net["net_id"]) == str(network_existingInVim.id):
                             net["vim_id"] = network_existingInVim["id"]
                             network = 'NIC = [NETWORK = "{}",NETWORK_UNAME = "{}" ]'.format(
                                 network_existingInVim.name, network_existingInVim.uname)
                             network_found = True
                             break
                     if not network_found:
                         raise vimconn.vimconnNotFoundException("Network {} not found".format(net["net_id"]))
                     template_updated += network
                 oca.VmTemplate.update(template, template_updated)
                 self.logger.info(
                     "Instanciating in OpenNebula a new VM name:{} id:{}".format(template.name, template.id))
                 vminstance_id = template.instantiate(name=name)
                 return str(vminstance_id), None
         raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id))
     except Exception as e:
         self.logger.error("Create new vm instance error: " + str(e))
         raise vimconn.vimconnException(e)
コード例 #3
0
 def pool(self):
     try:
         p = oca.VirtualNetworkPool(self.client, preload_info=True)
         # Filter flag possible values:
         # -3: Connected user's resources
         # -2: All resources
         # -1: Connected user's and his group's resources
         p.info(filter=-2, range_start=-1, range_end=-1)
         return p
     except ProtocolError:
         raise OpenNebulaError('Could not retrieve info from OpenNebula')
コード例 #4
0
 def get_network(self, net_id):
     """Obtain network details of network id"""
     try:
         client = oca.Client(self.user + ':' + self.passwd, self.url)
         networkList = oca.VirtualNetworkPool(client)
         networkList.info()
         net = {}
         for network in networkList:
             if str(network.id) == str(net_id):
                 net['id'] = net_id
                 net['name'] = network.name
                 net['status'] = "ACTIVE"
                 break
         if net:
             return net
         else:
             raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
     except Exception as e:
             self.logger.error("Get network " + str(net_id) + " error): " + str(e))
             raise vimconn.vimconnException(e)
コード例 #5
0
 def delete_network(self, net_id):
     """Deletes a tenant network from VIM
         Returns the network identifier
     """
     try:
         # self.delete_bridge_host()
         client = oca.Client(self.user + ':' + self.passwd, self.url)
         networkList = oca.VirtualNetworkPool(client)
         networkList.info()
         network_deleted = False
         for network in networkList:
             if str(network.id) == str(net_id):
                 oca.VirtualNetwork.delete(network)
                 network_deleted = True
         if network_deleted:
             return net_id
         else:
             raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
     except Exception as e:
             self.logger.error("Delete network " + str(net_id) + "error: " + str(e))
             raise vimconn.vimconnException(e)
コード例 #6
0
 def get_network_list(self, filter_dict={}):
     """Obtain tenant networks of VIM
     Filter_dict can be:
         name: network name
         id: network uuid
         public: boolean
         tenant_id: tenant
         admin_state_up: boolean
         status: 'ACTIVE'
     Returns the network list of dictionaries
     """
     try:
         client = oca.Client(self.user + ':' + self.passwd, self.url)
         networkList = oca.VirtualNetworkPool(client)
         networkList.info()
         response = []
         if "name" in filter_dict.keys():
             network_name_filter = filter_dict["name"]
         else:
             network_name_filter = None
         if "id" in filter_dict.keys():
             network_id_filter = filter_dict["id"]
         else:
             network_id_filter = None
         for network in networkList:
             match = False
             if network.name == network_name_filter and str(network.id) == str(network_id_filter):
                 match = True
             if network_name_filter is None and str(network.id) == str(network_id_filter):
                 match = True
             if network_id_filter is None and network.name == network_name_filter:
                 match = True
             if match:
                 net_dict = {"name": network.name, "id": str(network.id)}
                 response.append(net_dict)
         return response
     except Exception as e:
         self.logger.error("Get network list error: " + str(e))
         raise vimconn.vimconnException(e)
コード例 #7
0
def clean_opennebula(hours, network, user, pwd, endpoint):
    now = datetime.datetime.utcnow()
    delta = datetime.timedelta(hours=hours)
    client = oca.Client('{user}:{pwd}'.format(user=user, pwd=pwd),
                        'https://{host}:2633/RPC2'.format(host=endpoint))
    vms = oca.VirtualMachinePool(client)
    vms.info()
    vns = oca.VirtualNetworkPool(client)
    vns.info()
    net = vns.get_by_name(network)
    net.info()
    to_delete = []
    print("{uid:<6} {name:10} {started}".format(uid="#",
                                                name="Name",
                                                started="Started"))
    for vm in vms:
        text = "{uid:<6} {name:10} {started!s:10}".format(
            uid=vm.id,
            name=vm.name,
            started=datetime.datetime.fromtimestamp(vm.stime))
        print(text)
        if now - datetime.datetime.fromtimestamp(vm.stime) > delta:
            to_delete.append(vm)

    for vm in to_delete:
        # Release cluster IP on hold, if any
        if getattr(vm.user_template, 'reserved_ips', None):
            ips = vm.user_template.reserved_ips.split(',')
            for ip in ips:
                text = "{} IP on hold - released".format(ip)
                print(text)
                client.call('vn.release', net.id, 'LEASES=[IP={}]'.format(ip))
        # Delete VM
        text = "{uid:<6} {name:10} {started!s:10} - deleted".format(
            uid=vm.id,
            name=vm.name,
            started=datetime.datetime.fromtimestamp(vm.stime))
        print(text)
        vm.delete()
コード例 #8
0
 def test_info(self):
     self.client.call = Mock(return_value=self.xml)
     pool = oca.VirtualNetworkPool(self.client)
     pool.info()
     assert len(list(pool)) == 2