def set_disks(self, provision_config : Sequence[SetDisksEntry]): ''' Generates a provision XML, does provision, sets appropriate access rights to current user :param provision_config: :return: ''' from xenadapter.vbd import VBD from xenadapter.disk import VDIorISO from xenadapter.disk import VDI i = 0 specs = provision.ProvisionSpec() for entry in provision_config: size = str(1048576 * int(entry.size)) specs.disks.append(provision.Disk(f'{i}', size, entry.SR.uuid, True)) i += 1 try: provision.setProvisionSpec(self.auth.xen.session, self.ref, specs) except Exception as e: try: raise e except XenAPI.Failure as f: msg = f'Failed to assign provision specification: {f.details}' self.insert_log_entry(state='failed-provision-spec', message=f.details) raise XenAdapterAPIError(self.log, msg) finally: pass #self.destroy_vm(vm_uuid, force=True) else: self.log.debug(f"provision spec set {provision_config}") try: self.provision() except Exception as e: try: raise e except XenAPI.Failure as f: self.insert_log_entry(state='failed-provision', message=f.details) raise XenAdapterAPIError(self.log, f"Failed to provision: {f.details}") finally: pass #self.destroy_vm(vm_uuid, force=True) else: self.insert_log_entry(state='provisioned',message=str(specs)) for item in self.get_VBDs(): vbd = VBD(auth=self.auth, ref=item) vdi = VDIorISO(self.auth, ref=vbd.get_VDI()) if isinstance(vdi, VDI): vdi.set_name_description(f"Created by VMEmperor for VM {self.uuid}") # After provision. manage disks actions if not self.auth.is_admin(): vdi.manage_actions('all', user=self.auth.get_id())
def create_vm(session,template,net,name,cpu=None,ram=None,min_ram=None,max_ram=None): vm = session.xenapi.VM.clone(template,name) create_vif(session,vm,net) session.xenapi.VM.set_PV_args(vm, "noninteractive") pool = session.xenapi.pool.get_all()[0] default_sr = session.xenapi.pool.get_default_SR(pool) default_sr = session.xenapi.SR.get_record(default_sr) spec = provision.getProvisionSpec(session, vm) spec.setSR(default_sr['uuid']) provision.setProvisionSpec(session, vm, spec) session.xenapi.VM.provision(vm) return vm
def create_vm(session, template, net, name, cpu=None, ram=None, min_ram=None, max_ram=None): vm = session.xenapi.VM.clone(template, name) create_vif(session, vm, net) session.xenapi.VM.set_PV_args(vm, "noninteractive") pool = session.xenapi.pool.get_all()[0] default_sr = session.xenapi.pool.get_default_SR(pool) default_sr = session.xenapi.SR.get_record(default_sr) spec = provision.getProvisionSpec(session, vm) spec.setSR(default_sr['uuid']) provision.setProvisionSpec(session, vm, spec) session.xenapi.VM.provision(vm) return vm
def main(session): # Choose the PIF with the alphabetically lowest device # (we assume that plugging the debian VIF into the same network will allow # it to get an IP address by DHCP) pifs = session.xenapi.PIF.get_all_records() lowest = None for pifRef in pifs.keys(): if (lowest is None) or (pifs[pifRef]['device'] < pifs[lowest]['device']): lowest = pifRef print "Choosing PIF with device: ", pifs[lowest]['device'] network = session.xenapi.PIF.get_network(lowest) print "Chosen PIF is connected to network: ", session.xenapi.network.get_name_label(network) # List all the VM objects vms = session.xenapi.VM.get_all_records() print "Server has %d VM objects (this includes templates):" % (len(vms)) templates = [] for vm in vms: record = vms[vm] ty = "VM" if record["is_a_template"]: ty = "Template" # Look for a debian template if record["name_label"].startswith("Debian"): templates.append(vm) print " Found %8s with name_label = %s" % (ty, record["name_label"]) print "Choosing a Debian template to clone" if not templates: print "Could not find any Debian templates. Exiting." sys.exit(1) template = templates[0] print " Selected template: ", session.xenapi.VM.get_name_label(template) print "Installing new VM from the template" vm = session.xenapi.VM.clone(template, "new") print " New VM has name: new" print "Creating VIF" vif = { 'device': '0', 'network': network, 'VM': vm, 'MAC': "", 'MTU': "1500", "qos_algorithm_type": "", "qos_algorithm_params": {}, "other_config": {} } session.xenapi.VIF.create(vif) print "Adding non-interactive to the kernel commandline" session.xenapi.VM.set_PV_args(vm, "non-interactive") print "Choosing an SR to instantiate the VM's disks" pool = session.xenapi.pool.get_all()[0] default_sr = session.xenapi.pool.get_default_SR(pool) default_sr = session.xenapi.SR.get_record(default_sr) print "Choosing SR: %s (uuid %s)" % (default_sr['name_label'], default_sr['uuid']) print "Rewriting the disk provisioning XML" spec = provision.getProvisionSpec(session, vm) spec.setSR(default_sr['uuid']) provision.setProvisionSpec(session, vm, spec) print "Asking server to provision storage from the template specification" session.xenapi.VM.provision(vm) print "Starting VM" session.xenapi.VM.start(vm, False, True) print " VM is booting" print "Waiting for the installation to complete" # Here we poll because we don't generate events for metrics objects currently def read_os_name(a_vm): vgm = session.xenapi.VM.get_guest_metrics(a_vm) try: os = session.xenapi.VM_guest_metrics.get_os_version(vgm) if "name" in os.keys(): return os["name"] return None except: return None def read_ip_address(a_vm): vgm = session.xenapi.VM.get_guest_metrics(a_vm) try: os = session.xenapi.VM_guest_metrics.get_networks(vgm) if "0/ip" in os.keys(): return os["0/ip"] return None except: return None while read_os_name(vm) is None: time.sleep(1) print "Reported OS name: ", read_os_name(vm) while read_ip_address(vm) is None: time.sleep(1) print "Reported IP: ", read_ip_address(vm)
def main(session): # Choose the PIF with the alphabetically lowest device # (we assume that plugging the debian VIF into the same network will allow # it to get an IP address by DHCP) pifs = session.xenapi.PIF.get_all_records() lowest = None for pifRef in pifs.keys(): if (lowest is None) or (pifs[pifRef]['device'] < pifs[lowest]['device']): lowest = pifRef print "Choosing PIF with device: ", pifs[lowest]['device'] network = session.xenapi.PIF.get_network(lowest) print "Chosen PIF is connected to network: ", session.xenapi.network.get_name_label( network) # List all the VM objects vms = session.xenapi.VM.get_all_records() print "Server has %d VM objects (this includes templates):" % (len(vms)) templates = [] for vm in vms: record = vms[vm] ty = "VM" if record["is_a_template"]: ty = "Template" # Look for a debian template if record["name_label"].startswith("Debian"): templates.append(vm) print " Found %8s with name_label = %s" % (ty, record["name_label"]) print "Choosing a template to clone" if templates == []: print "Could not find any Debian templates. Exitting" sys.exit(1) template = templates[0] print " Selected template: ", session.xenapi.VM.get_name_label(template) print "Installing new VM from the template" vm = session.xenapi.VM.clone(template, "new") print " New VM has name: new" print "Creating VIF" vif = { 'device': '0', 'network': network, 'VM': vm, 'MAC': "", 'MTU': "1500", "qos_algorithm_type": "", "qos_algorithm_params": {}, "other_config": {} } session.xenapi.VIF.create(vif) print "Adding noniteractive to the kernel commandline" session.xenapi.VM.set_PV_args(vm, "noninteractive") print "Choosing an SR to instaniate the VM's disks" pool = session.xenapi.pool.get_all()[0] default_sr = session.xenapi.pool.get_default_SR(pool) default_sr = session.xenapi.SR.get_record(default_sr) print "Choosing SR: %s (uuid %s)" % (default_sr['name_label'], default_sr['uuid']) print "Rewriting the disk provisioning XML" spec = provision.getProvisionSpec(session, vm) spec.setSR(default_sr['uuid']) provision.setProvisionSpec(session, vm, spec) print "Asking server to provision storage from the template specification" session.xenapi.VM.provision(vm) print "Starting VM" session.xenapi.VM.start(vm, False, True) print " VM is booting" print "Waiting for the installation to complete" # Here we poll because we don't generate events for metrics objects currently def read_os_name(vm): vgm = session.xenapi.VM.get_guest_metrics(vm) try: os = session.xenapi.VM_guest_metrics.get_os_version(vgm) if "name" in os.keys(): return os["name"] return None except: return None def read_ip_address(vm): vgm = session.xenapi.VM.get_guest_metrics(vm) try: os = session.xenapi.VM_guest_metrics.get_networks(vgm) if "0/ip" in os.keys(): return os["0/ip"] return None except: return None while read_os_name(vm) == None: time.sleep(1) print "Reported OS name: ", read_os_name(vm) while read_ip_address(vm) == None: time.sleep(1) print "Reported IP: ", read_ip_address(vm) session.xenapi.session.logout()
print "We pick the first one:" first_pool=pool_list[0] print "name:", sx.pool.get_name_label(first_pool) print "description: ", sx.pool.get_name_description(first_pool) default_SR=sx.pool.get_default_SR(first_pool) print "The default SR is: " print "Name:", sx.SR.get_name_label(default_SR) print "Description:", sx.SR.get_name_description(default_SR) #set the new copy to have its disks in the default SR #this is a debian template specific hack which allows us to create Debian VMs easily spec=provision.getProvisionSpec(session, clone) spec.setSR(sx.SR.get_uuid(default_SR)) provision.setProvisionSpec(session, clone, spec) #now 'provision' it, which causes the disks to actually be created. print "provisioning...." sx.VM.provision(clone) print "provisioned" #now find out which network to attach the new machine to #by finding out what the pool master host is connected to. pool_master=sx.pool.get_master(first_pool) master_PIFs=sx.host.get_PIFs(pool_master) primary_PIF=master_PIFs[0] master_network=sx.PIF.get_network(primary_PIF) #attach new VM to default SR and master network print "Creating VIF..."
def vm_template_copy(self,vm_template,vm_name): pifs = self.session.xenapi.PIF.get_all_records() lowest = None for pifRef in pifs.keys(): if (lowest is None) or (pifs[pifRef]['device'] < pifs[lowest]['device']): lowest = pifRef print "Choosing PIF with device: ", pifs[lowest]['device'] network = self.session.xenapi.PIF.get_network(lowest) print "Chosen PIF is connected to network: ", self.session.xenapi.network.get_name_label(network) # List all the VM objects vms = self.session.xenapi.VM.get_all_records() templates = [] for vm in vms: record = vms[vm] ty = "VM" if record["is_a_template"]: ty = "Template" if record["name_label"] == vm_template: templates.append(vm) print "Choosing a template to clone" if templates == []: print "Could not find any templates. Exitting" sys.exit(1) template = templates[0] print "Installing new VM from the template" vm = self.session.xenapi.VM.clone(template, vm_name) #print vm vm_uuid = self.get_uuid(vm) print " New VM has name: "+vm_name print "Creating VIF" vif = { 'device': '0', 'network': network, 'VM': vm, 'MAC': "", 'MTU': "1500", "qos_algorithm_type": "", "qos_algorithm_params": {}, "other_config": {} } self.session.xenapi.VIF.create(vif) self.session.xenapi.VM.set_PV_args(vm, "noninteractive") print "Choosing an SR to instaniate the VM's disks" pool = self.session.xenapi.pool.get_all()[0] default_sr = self.session.xenapi.pool.get_default_SR(pool) default_sr = self.session.xenapi.SR.get_record(default_sr) print "Choosing SR: %s (uuid %s)" % (default_sr['name_label'], default_sr['uuid']) print "Rewriting the disk provisioning XML" ps = provision.ProvisionSpec() provision.setProvisionSpec(self.session,vm,ps) spec = provision.getProvisionSpec(self.session, vm) spec.setSR(default_sr['uuid']) #print spec provision.setProvisionSpec(self.session, vm, spec) print "Asking server to provision storage from the template specification" self.session.xenapi.VM.provision(vm) return vm_uuid,vm print "Starting VM" self.session.xenapi.VM.start(vm, False, True) print " VM is booting" print "Waiting for the installation to complete" # Here we poll because we don't generate events for metrics objects currently def read_os_name(vm): vgm = self.session.xenapi.VM.get_guest_metrics(vm) try: os = self.session.xenapi.VM_guest_metrics.get_os_version(vgm) if "name" in os.keys(): return os["name"] return None except: return None def read_ip_address(vm): vgm = self.session.xenapi.VM.get_guest_metrics(vm) try: os = self.session.xenapi.VM_guest_metrics.get_networks(vgm) if "0/ip" in os.keys(): return os["0/ip"] return None except: return None while read_os_name(vm) == None: time.sleep(1) print "Reported OS name: ", read_os_name(vm) while read_ip_address(vm) == None: time.sleep(1) print "Reported IP: ", read_ip_address(vm) self.session.xenapi.session.logout()
def build_vm(ctx,cpus,ram,template,name,sr,networkdevice): """ Build VM Out passing VM's projected specifications. This will take in vCPU(s), RAM, HardDrive space, Template name, Network Device Name, and the SR to pull the Template from. An example of doing this is: bsdxenvmbuilder build_vm --template "CentOS 7" --ram 2 --cpus 2 --name "Test" --sr "NFS VM disks" --networkdevice bond0 This will essentially connect to the Xen Server configured and build out a CentOS VM named Test. """ logging.info("Collecting Info on the VM Specs.....") try: session = xen_session() click.echo("Checking for template: " + template) vms = session.xenapi.VM.get_all_records() print ("Server has %d VM objects (this includes templates):" % (len(vms))) templates = [] for vm in vms: record = vms[vm] ty = "VM" if record["is_a_template"]: ty = "Template" if record["name_label"].startswith(template): templates.append(vm) print("Found: " + vm + " " + record["name_label"]) if not templates: print("Could not find any templates. Exiting.") sys.exit(1) template = templates[0] logger.info("Selected template: ", session.xenapi.VM.get_name_label(template)) logger.info("Installing new VM from the template") vm = session.xenapi.VM.clone(template, name) logger.info("Adding non-interactive to the kernel commandline") session.xenapi.VM.set_PV_args(vm, "non-interactive") logger.info("Choosing an SR to instantiate the VM's disks") sr_pool = session.xenapi.pool.get_all()[0] default_sr = session.xenapi.pool.get_default_SR(sr_pool) default_sr = session.xenapi.SR.get_record(default_sr) print("Choosing SR: %s (uuid %s)" % (default_sr['name_label'], default_sr['uuid'])) print("Rewriting the disk provisioning XML") spec = provision.getProvisionSpec(session, vm) spec.setSR(default_sr['uuid']) provision.setProvisionSpec(session, vm, spec) create = session.xenapi.VM.provision(vm) sr_dvd=session.xenapi.SR.get_by_name_label("ISO_IMAGES_LOCAL") record_dvd=session.xenapi.SR.get_record(sr_dvd[0]) VDI_dvd=record_dvd["VDIs"] vm_uid=session.xenapi.VM.get_uuid(vm) vm_get=session.xenapi.VM.get_by_uuid(vm_uid) # Configuring Boot disk vbdconnectcd={'VDI':VDI_dvd[0], 'VM':vm_get, 'userdevice':"1", 'mode':"RO", 'type':"cd", 'bootable':True, 'unpluggable':True, 'empty':False, 'other_config':{}, 'qos_algorithm_type':'', 'qos_algorithm_params':{}} vbdref=session.xenapi.VBD.create(vbdconnectcd) session.xenapi.VBD.set_bootable(vbdref, True) # Configuring Network pifs = session.xenapi.PIF.get_all_records() for pifRef in pifs.keys(): if (pifs[pifRef]['device'] == networkdevice): networkdevice = pifRef logger.info("Choosing PIF with device: ", networkdevice) network = session.xenapi.PIF.get_network(str(networkdevice)) logger.info("Chosen PIF is connected to network: ", session.xenapi.network.get_name_label(network)) vif = { 'device': '0', 'network': network, 'VM': vm, 'MAC': "", 'MTU': "1500", "qos_algorithm_type": "", "qos_algorithm_params": {}, "other_config": {} } vif_object = session.xenapi.VIF.create(vif) # Need Byte Conversion bytes = str(long(ram) * 1024L * 1024L * 1024L) session.xenapi.VM.set_memory_limits(vm,bytes,bytes,bytes,bytes) session.xenapi.VM.set_VCPUs_max(vm,cpus) session.xenapi.VM.set_VCPUs_at_startup(vm,cpus) session.xenapi.VM.start(vm,False, True) except: logging.error("ERROR: Unexpected Error - ", sys.exc_info()[0]) raise