Example #1
0
def vsphere_check_with_api(api, run_time, text):
    """Uses api to perform checking of vms on vsphere-type provider.

    Args:
        api: api endpoint to vsphere
        run_time: when this run time is exceeded for the VM, it will be deleted
        text: when this string is found in the name of VM, it may be deleted
    """
    vms = VirtualMachine.all(api.api)
    vms_to_delete = []
    templates_to_delete = []

    nightly_templates = [VirtualMachine.get(api.api, name=x)
                         for x in api.list_template() if "miq-nightly" in x]
    nightly_templates.sort(key=lambda x: datetime.datetime.strptime(x.name[-12:], "%Y%m%d%H%M"))

    if len(nightly_templates) > MRU_NIGHTLIES:
        for template in nightly_templates[:-MRU_NIGHTLIES]:
            templates_to_delete.append(template.name)

    for vm in vms:
        vm_name = vm.name
        running_for = vm.summary.quickStats.uptimeSeconds / SEC_IN_DAY
        if running_for >= run_time and is_affected(vm_name, text):
            print("To delete: {} with runtime: {}".format(vm_name, running_for))
            vms_to_delete.append(vm_name)
    return (vms_to_delete, templates_to_delete)
def check_template_exists(hostname, username, password, name):
    client = Client(server=hostname, username=username, password=password)
    try:
        VirtualMachine.get(client, name=name)
        print "VSPHERE: A Machine with that name already exists"
    except ObjectNotFoundError:
        return False
    client.logout()
    return True
Example #3
0
    def get_host(self, hostname):
        '''
        Read info about a specific host or VM from cache or VMware API.
        '''
        inv = self._get_cache(hostname, None)
        if inv is not None:
            return inv

        if not self.guests_only:
            try:
                host = HostSystem.get(self.client, name=hostname)
                inv = self._get_host_info(host)
            except ObjectNotFoundError:
                pass

        if inv is None:
            try:
                vm = VirtualMachine.get(self.client, name=hostname)
                inv = self._get_vm_info(vm)
            except ObjectNotFoundError:
                pass

        if inv is not None:
            self._put_cache(hostname, inv)
        return inv or {}
Example #4
0
 def changevmMemory(self,vm_name,memory):
     try:
         new_config = self.client.create("VirtualMachineConfigSpec")
         new_config.memoryMB = memory
         vm = VirtualMachine.get(self.client, name=vm_name)
         print("Reconfiguring %s" % vm_name)
         if vm.config.hardware.memoryMB== vm_name:
             print("Not reconfiguring %s as it already has %s memory" % (vm_name,memory))
             sys.exit()
         task = vm.ReconfigVM_Task(spec=new_config)
         while task.info.state in ["queued", "running"]:
             print("Waiting 5 more seconds for VM starting")
             time.sleep(5)
             task.update()

         if task.info.state == "success":
             elapsed_time = task.info.completeTime - task.info.startTime
             print("Successfully reconfigured VM %s. Server took %s seconds." %
                   (vm_name, elapsed_time.seconds))
         elif task.info.state == "error":
             print("ERROR: The task for reconfiguring the VM has finished with"
                   " an error. If an error was reported it will follow.")
             print("ERROR: %s" % task.info.error.localizedMessage)
     except VimFault, e:
         print("Failed to reconfigure %s: " % e)
         sys.exit()
def upload_ova(hostname, username, password, name, datastore,
               cluster, datacenter, url, host):
    client = Client(server=hostname, username=username, password=password)
    try:
        VirtualMachine.get(client, name=name)
        print "VSPHERE: A Machine with that name already exists"
        sys.exit(127)
    except ObjectNotFoundError:
        pass
    client.logout()

    cmd_args = ['ovftool']
    cmd_args.append("--datastore=%s" % datastore)
    cmd_args.append("--name=%s" % name)
    cmd_args.append("--vCloudTemplate=True")
    cmd_args.append(url)
    cmd_args.append("vi://%[email protected]%s/%s/host/%s" % (username, hostname, datacenter, cluster))

    print "VSPHERE: Running OVFTool..."

    proc = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    out_string = ""

    while "'yes' or 'no'" not in out_string and "Password:" not in out_string:
        out_string += proc.stdout.read(1)

    if "'yes' or 'no'" in out_string:
        proc.stdin.write("yes\n")
        proc.stdin.flush()
        print "VSPHERE: Added host to SSL hosts"
        out_string = ""
        while "Password:" not in out_string:
            out_string += proc.stdout.read(1)

    proc.stdin.write(password + "\n")
    output = proc.stdout.read()
    error = proc.stderr.read()

    if "successfully" in output:
        print " VSPHERE: Upload completed"
        return 0, output
    else:
        print "VSPHERE: Upload did not complete"
        return -1, "\n".join([output, error])
def make_template(client, name, provider):
    print("VSPHERE:{} Marking as Template".format(provider))
    vm = VirtualMachine.get(client.api, name=name)
    try:
        vm.MarkAsTemplate()
        print(" VSPHERE:{} Successfully templatized machine".format(provider))
    except:
        print(" VSPHERE:{} Failed to templatize machine".format(provider))
        sys.exit(127)
def make_template(client, name):
    print("VSPHERE: Marking as Template")
    vm = VirtualMachine.get(client.api, name=name)
    try:
        vm.MarkAsTemplate()
        print(" VSPHERE: Successfully templatized machine")
    except:
        print(" VSPHERE: Failed to templatize machine")
        sys.exit(127)
def make_template(client, name, hostname, username, password):
    print "VSPHERE: Marking as Template"
    client = Client(server=hostname, username=username, password=password)
    vm = VirtualMachine.get(client, name=name)

    try:
        vm.MarkAsTemplate()
        print " VSPHERE: Successfully templatized machine"
    except:
        print " VSPHERE: Failed to templatize machine"
        sys.exit(127)
Example #9
0
def vsphere_is_vm_down(api, vm_name):
    """Returns True if VM on vsphere is down.

    Args:
        api: api endpoint to vsphere
        vm_name: name og the vm
    """
    vm = VirtualMachine.get(api.api, name=vm_name)
    if vm.runtime.powerState == 'poweredOff':
        return True
    return False
Example #10
0
def vsphere_is_vm_up(api, vm_name):
    """Returns True if VM on vsphere is up.

    Args:
        api: api endpoint to vsphere
        vm_name: name of the vm
    """
    vm = VirtualMachine.get(api.api, name=vm_name)
    if vm.runtime.powerState == "poweredOn":
        return True
    return False
Example #11
0
 def stop(self, vmname):
     vm = VirtualMachine.get(self.client, name=vmname)
     print 'Attempting to shut down ' + vmname
     try:
         shutdown = vm.ShutdownGuest()
         self.task(vm, shutdown)
     except suds.WebFault as e:
         if self.force:
             print 'Attempting to forcefully power off ' + vmname
             pass
         else:
             raise e
     print 'Attempting to power off ' + vmname
     poweroff = vm.PowerOffVM_Task()
     self.task(vm, poweroff)
def add_disk(client, name):
    print "VSPHERE: Beginning disk add..."

    backing = client.create("VirtualDiskFlatVer2BackingInfo")
    backing.datastore = None
    backing.diskMode = "persistent"
    backing.thinProvisioned = True

    disk = client.create("VirtualDisk")
    disk.backing = backing
    disk.controllerKey = 1000
    disk.key = 3000
    disk.unitNumber = 1
    disk.capacityInKB = 8388608

    disk_spec = client.create("VirtualDeviceConfigSpec")
    disk_spec.device = disk
    file_op = client.create("VirtualDeviceConfigSpecFileOperation")
    disk_spec.fileOperation = file_op.create
    operation = client.create("VirtualDeviceConfigSpecOperation")
    disk_spec.operation = operation.add

    devices = []
    devices.append(disk_spec)

    nc = client.create("VirtualMachineConfigSpec")
    nc.deviceChange = devices

    vm = VirtualMachine.get(client, name=name)
    task = vm.ReconfigVM_Task(spec=nc)

    def check_task(task):
        task.update()
        return task.info.state

    wait_for(check_task, [task], fail_condition="running")

    if task.info.state == "success":
        print " VSPHERE: Successfully added new disk"
        client.logout()
    else:
        client.logout()
        print " VSPHERE: Failed to add disk"
        sys.exit(127)
Example #13
0
def vsphere_delete_vm(api, vm_name):
    """Deletes VM from vsphere-type provider.
    If needed, stops the VM first, then deletes it.

    Args:
        api: api endpoint to vsphere
        vm_name: name of the vm
    """
    vm = VirtualMachine.get(api.api, name=vm_name)
    vm_status = vsphere_vm_status(api, vm_name)
    if vm_status != "poweredOn" and vm_status != "poweredOff":
        # something is wrong, locked image etc
        exc_msg = "VM status: {}".format(vm_status)
        raise Exception(exc_msg)
    print("status: {}".format(vm_status))
    if vm_status == "poweredOn":
        print("Powering down: {}".format(vm.name))
        vm.PowerOffVM_Task()
        wait_for(vsphere_is_vm_down, [api, vm_name], fail_condition=False, delay=10, num_sec=120)
    print("Deleting: {}".format(vm_name))
    vm.Destroy_Task()
Example #14
0
    def clone(self,cursor,payload):
        ''' clone the template with our payload '''
   
        while payload:
            data = payload.pop(0)
            try:
                cluster = ClusterComputeResource.get(cursor, name=data['cluster'])
            except Exception, e:
                log.error("Unable to locate a cluster resource witht the name {}. Omitting build".format(data['cluster']))
            else:
                pool = cluster.resourcePool
                esxhost = choice(cluster.host)
                datastore = choice(cluster.datastore)
                log.info("Cloning virtual machine named {} into cluster {} from template {}".format(data['vm_name'],data['cluster'],data['template']))
                template = VirtualMachine.get(cursor, name=data['template'])
                folder = cluster.parent.parent.vmFolder

                _ip_spec = self._vm_ip_spec(cursor, domain = data['domain'],
                                            dns = data['dns'],
                                            gateway = data['gateway'],
                                            ip = data['ip'],
                                            netmask = data['netmask'])
                _adapter_spec = self._vm_adapter_spec(cursor,_ip_spec)
                _net_spec = self._vm_net_spec(cursor,cluster.network, vlan = data['vlan'])
                _custom_spec = self._vm_custom_spec(cursor, _adapter_spec, template = data['template'],
                                                    domain = data['domain'], name = data['vm_name'],
                                                    ip = data['ip'], gateway = data['gateway'],
                                                    netmask = data['netmask'], dns = data['dns'])
                _config_spec = self._vm_config_spec(cursor, _net_spec, memory = data['memory'], 
                                                    cpus = data['cpus'], cores = data['cores'],
                                                    name = data['vm_name'])
                _relo_spec = self._vm_relo_spec(cursor,esxhost,datastore,pool)
                _clone_spec = self._vm_clone_spec(cursor, _relo_spec, _config_spec, _custom_spec)

                try:
                    #self.wait_for_task(template.CloneVM_Task(folder = folder, name = data['vm_name'], spec=_clone_spec))
                    template.CloneVM_Task(folder = folder, name = data['vm_name'], spec=_clone_spec)
                except VimFault, e:
                    print e
Example #15
0
 def start(self, vmname):
     vm = VirtualMachine.get(self.client, name=vmname)
     print 'Attempting to power on %s' % (vmname)
     poweron = vm.PowerOnVM_Task()
     self.task(vm, poweron)
Example #16
0
def vsphere_vm_status(api, vm_name):
    vm = VirtualMachine.get(api.api, name=vm_name)
    return vm.runtime.powerState
def exportVM(serverIp, user, passwd, vmName, workingDir):
    try:
        print "Connecting to the server...."
        client = Client(serverIp, user, passwd)
    except WebFault:
        print "Can't connect to the server"
        sys.exit(1)
    print "Connected"
    validVms = {}
    if vmName <> 'all':
        try:
            vm = VirtualMachine.get(client, name=vmName)
            if vm.runtime.powerState <> 'poweredOff':
                print 'Skipping VM:' + vm.name + ' VM is not powered off'
                sys.exit(5)
            if len(vm.network) <> 1:
                print 'Skipping VM:' + vm.name + ' The number of network devices is not equal to 1'
                sys.exit(5)
            vmdkPath = getVMDKUri(serverIp, vm)
            if vmdkPath != None:
                validVms[vm.name] = vmdkPath
        except ObjectNotFoundError:
            print 'Invalid VM name'
            client.logout()
            sys.exit(2)
    else:
        # inspect all vms
        vms = VirtualMachine.all(client)
        for vm in vms:
            if vm.runtime.powerState <> 'poweredOff':
                print 'Skipping VM:' + vm.name + ' VM is not powered off'
                continue
            if len(vm.network) <> 1:
                print 'Skipping VM:' + vm.name + ' The number of network devices is not equal to 1'
                continue
            vmdkPath = getVMDKUri(serverIp, vm)
            if vmdkPath != None:
                validVms[vm.name] = vmdkPath
            else:
                continue

    client.logout()
    if len(validVms.keys()) == 0:
        print 'Nothing to export'
        sys.exit(2)

    # get vmdks for all valid vms
    for vmName in validVms.keys():
        directory = workingDir + '/' + vmName + '/'
        if not os.path.exists(directory):
            os.makedirs(directory)
        VmdkUri = validVms[vmName]
        downloadFile(VmdkUri, user, passwd, directory + vmName + '.vmdk')
        extends = parseVMDK(directory + vmName + '.vmdk')
        if extends == None:
            print 'No accessable extends'
            sys.exit(3)
        else:
            available = getAvalableDiskSpaceBytes(workingDir)
            for s in extends.values():
                available = available - s
            if available < 0:
                print 'There is not enough free disk space to download all extends for VM:' + vmName
                exit(4)
            for e in extends.keys():
                m = re.match('^(.+?)/folder/(.+?)/(.+?)\?(.+)$', VmdkUri)
                uri = m.group(1) + '/folder/' + m.group(2) + '/' + urllib2.quote(e) + '?' + m.group(4)
                downloadFile(uri, user, passwd, directory + e)

    sys.exit(0)
Example #18
0
import time
import sys

from psphere.client import Client
from psphere.managedobjects import VirtualMachine

scatter_secs = 8

nodes = sys.argv[1:]

client = Client()

print("Powering on %s VMs" % len(nodes))
print("Estimated run time with %s seconds sleep between each power on: %s" %
      (scatter_secs, scatter_secs*len(nodes)))

for node in nodes:
    try:
        vm = VirtualMachine.get(client, name=node, properties=["name", "runtime"])
    except ObjectNotFoundError:
        print("WARNING: Could not find VM with name %s" % node)
        pass

    print("Powering on %s" % vm.name)
    if vm.runtime.powerState == "poweredOn":
        print("%s is already powered on." % vm.name)
        continue

    task = vm.PowerOnVM_Task()
    time.sleep(scatter_secs)
Example #19
0
import sys
import time

from psphere.client import Client
from psphere.soap import VimFault
from psphere.managedobjects import VirtualMachine
from psphere.errors import ObjectNotFoundError

vm_name = sys.argv[1]

client = Client()
new_config = client.create("VirtualMachineConfigSpec")
new_config.numCPUs = 2

try:
    vm = VirtualMachine.get(client, name=vm_name)
except ObjectNotFoundError:
    print("ERROR: No VM found with name %s" % vm_name)

print("Reconfiguring %s" % vm_name)
if vm.config.hardware.numCPU == 2:
    print("Not reconfiguring %s as it already has 2 CPUs" % vm_name)
    sys.exit()

try:
    task = vm.ReconfigVM_Task(spec=new_config)
except VimFault, e:
    print("Failed to reconfigure %s: " % e)
    sys.exit()

while task.info.state in ["queued", "running"]:
Example #20
0
#!/usr/bin/python

import sys

from psphere.client import Client
from psphere.managedobjects import HostSystem, VirtualMachine

client = Client(sys.argv[1], sys.argv[2], sys.argv[3])
host_systems = HostSystem.all(client)
print("HostSystem.all(client) finds these hosts")
for host_system in host_systems:
    print(host_system.name)

vm = VirtualMachine.get(client, name="genesis", overallStatus="green")

print('VirtualMachine.get(client, name="genesis", overallStatus="green")'
      ' got the following host:')
print("Name: %s" % vm.name)
print("overallStatus: %s" % vm.overallStatus)