Exemplo n.º 1
0
 def __init__(self, url, username, password):
     self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
     if(url.startswith('http://') or url.startswith('https://')):
         server = urllib2.Request(url).get_host()
     else:
         server = url
     self.client = Client(server=server, username=username, password=password)
Exemplo n.º 2
0
def main(options):
    """A simple connection test to login and print the server time."""
        
    client = Client(server=options.server, username=options.username, password=options.password)
    print('Successfully connected to %s' % client.server)
    print(client.si.CurrentTime())
    
    client.logout()
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
Exemplo n.º 4
0
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
Exemplo n.º 5
0
def main(options):
    """A simple connection test to login and print the server time."""

    client = Client(server=options.server,
                    username=options.username,
                    password=options.password)
    print('Successfully connected to %s' % client.server)
    print(client.si.CurrentTime())

    client.logout()
Exemplo n.º 6
0
def main(options):
    """Obtains supported features from the license manager"""
    client = Client(server=options.server, username=options.username,
                    password=options.password)
    print('Successfully connected to %s' % client.server)
    lm_info = client.sc.licenseManager.QuerySupportedFeatures()
    for feature in lm_info:
        print('%s: %s' % (feature.featureName, feature.state))

    client.logout()
Exemplo n.º 7
0
def main(name, options):
    """The main method for this script.

    :param name: The name of the VM to create.
    :type name: str
    :param template_name: The name of the template to use for creating \
            the VM.
    :type template_name: str

    """
    server = config._config_value("general", "server", options.server)
    if server is None:
        raise ValueError("server must be supplied on command line"
                         " or in configuration file.")
    username = config._config_value("general", "username", options.username)
    if username is None:
        raise ValueError("username must be supplied on command line"
                         " or in configuration file.")
    password = config._config_value("general", "password", options.password)
    if password is None:
        raise ValueError("password must be supplied on command line"
                         " or in configuration file.")

    vm_template = None
    if options.template is not None:
        try:
            vm_template = template.load_template(options.template)
        except TemplateNotFoundError:
            print("ERROR: Template \"%s\" could not be found." % options.template)
            sys.exit(1)

    expected_opts = ["compute_resource", "datastore", "disksize", "nics",
                     "memory", "num_cpus", "guest_id", "host"]

    vm_opts = {}
    for opt in expected_opts:
        vm_opts[opt] = getattr(options, opt)
        if vm_opts[opt] is None:
            if vm_template is None:
                raise ValueError("%s not specified on the command line and"
                                 " you have not specified any template to"
                                 " inherit the value from." % opt)
            try:
                vm_opts[opt] = vm_template[opt]
            except AttributeError:
                raise ValueError("%s not specified on the command line and"
                                 " no value is provided in the specified"
                                 " template." % opt)

    client = Client(server=server, username=username, password=password)
    create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"],
              vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"],
              vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"])
    client.logout()
Exemplo n.º 8
0
def main(name, options):
    """The main method for this script.

    :param name: The name of the VM to create.
    :type name: str
    :param template_name: The name of the template to use for creating \
            the VM.
    :type template_name: str

    """
    server = config._config_value("general", "server", options.server)
    if server is None:
        raise ValueError("server must be supplied on command line"
                         " or in configuration file.")
    username = config._config_value("general", "username", options.username)
    if username is None:
        raise ValueError("username must be supplied on command line"
                         " or in configuration file.")
    password = config._config_value("general", "password", options.password)
    if password is None:
        raise ValueError("password must be supplied on command line"
                         " or in configuration file.")

    vm_template = None
    if options.template is not None:
        try:
            vm_template = template.load_template(options.template)
        except TemplateNotFoundError:
            print("ERROR: Template \"%s\" could not be found." % options.template)
            sys.exit(1)

    expected_opts = ["compute_resource", "datastore", "disksize", "nics",
                     "memory", "num_cpus", "guest_id", "host"]

    vm_opts = {}
    for opt in expected_opts:
        vm_opts[opt] = getattr(options, opt)
        if vm_opts[opt] is None:
            if vm_template is None:
                raise ValueError("%s not specified on the command line and"
                                 " you have not specified any template to"
                                 " inherit the value from." % opt)
            try:
                vm_opts[opt] = vm_template[opt]
            except AttributeError:
                raise ValueError("%s not specified on the command line and"
                                 " no value is provided in the specified"
                                 " template." % opt)

    client = Client(server=server, username=username, password=password)
    create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"],
              vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"],
              vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"])
    client.logout()
Exemplo n.º 9
0
class Vmops:
 client=None
 def connect(self):
     configuration=Config()
     server = configuration._config_value("general", "server")
     if server is None:
         raise ValueError("server must be supplied on command line"+"or in configuration file.")
     username = configuration._config_value("general", "username")
     if username is None:
         raise ValueError("username must be supplied on command line"
                      " or in configuration file.")
     password = configuration._config_value("general", "password")
     if password is None:
         raise ValueError("password must be supplied on command line"
                      " or in configuration file.")

     self.client=Client(server,username,password)


 def findVM(self,vmName):
     vm = self.client.find_entity_view("VirtualMachine",filter={"name": vmName})
     return vm


 def changevmConfig(self,vm_name,cpuCount):
    try:
     new_config = self.client.create("VirtualMachineConfigSpec")
     new_config.numCPUs = cpuCount
     new_config.cpuHotAddEnabled=True
     vm = VirtualMachine.get(self.client, name=vm_name)
     print("Reconfiguring %s" % vm_name)
     if vm.config.hardware.numCPU == cpuCount:
        print("Not reconfiguring %s as it already has 2 CPUs" % vm_name)
        sys.exit()
     task = vm.ReconfigVM_Task(spec=new_config)
     while task.info.state in ["queued", "running"]:
      print("Waiting 5 more seconds for VM creation")
      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()
    except ObjectNotFoundError:
     print("ERROR: No VM found with name %s" % vm_name)
Exemplo n.º 10
0
 def __init__(self, vsphere_server, vsphere_username, vsphere_password):
     self.server = vsphere_server
     self.username = vsphere_username
     self.password = vsphere_password
     try:
         log._info("Attempting to connect to vCenter server: %s" %
                   (self.server))
         self.client = Client(self.server, self.username, self.password)
         log._info("CONNECTED to vCenter server: %s" % (self.server))
     except VimFault as e:
         log._warn("Failed to connect to vCenter: %s" % (e.fault_name))
         return False
Exemplo n.º 11
0
def run(**kwargs):
    provider = cfme_data['management_systems'][kwargs.get('provider')]
    creds = credentials[provider['credentials']]

    hostname = provider['hostname']
    username = creds['username']
    password = creds['password']

    client = Client(server=hostname, username=username, password=password)

    kwargs = update_params_api(client, **kwargs)

    name = kwargs.get('template_name', None)
    if name is None:
        name = cfme_data['basic_info']['appliance_template']

    print "VSPHERE: Template Name: %s" % name

    check_kwargs(**kwargs)

    url = kwargs.get('image_url')

    if not check_template_exists(hostname, username, password, name):
        if kwargs.get('upload'):
            # Wrapper for ovftool - sometimes it just won't work
            for i in range(0, NUM_OF_TRIES_OVFTOOL):
                print "VSPHERE: Trying ovftool %s..." % i
                ova_ret, ova_out = upload_ova(hostname,
                                              username,
                                              password,
                                              name,
                                              kwargs.get('datastore'),
                                              kwargs.get('cluster'),
                                              kwargs.get('datacenter'),
                                              url,
                                              kwargs.get('host'),
                                              kwargs.get('proxy'))
                if ova_ret is 0:
                    break
            if ova_ret is -1:
                print "VSPHERE: Ovftool failed to upload file."
                print ova_out
                sys.exit(127)

        if kwargs.get('disk'):
            add_disk(client, name)
        if kwargs.get('template'):
            make_template(client, name, hostname, username, password)
        client.logout()
    print "VSPHERE: Completed successfully"
Exemplo n.º 12
0
    def __init__(self, guests_only=None):
        self.config = ConfigParser.SafeConfigParser()
        if os.environ.get('VMWARE_INI', ''):
            config_files = [os.environ['VMWARE_INI']]
        else:
            config_files =  [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini']
        for config_file in config_files:
            if os.path.exists(config_file):
                self.config.read(config_file)
                break

        # Retrieve only guest VMs, or include host systems?
        if guests_only is not None:
            self.guests_only = guests_only
        elif self.config.has_option('defaults', 'guests_only'):
            self.guests_only = self.config.getboolean('defaults', 'guests_only')
        else:
            self.guests_only = True

        # Read authentication information from VMware environment variables
        # (if set), otherwise from INI file.
        auth_host = os.environ.get('VMWARE_HOST')
        if not auth_host and self.config.has_option('auth', 'host'):
            auth_host = self.config.get('auth', 'host')
        auth_user = os.environ.get('VMWARE_USER')
        if not auth_user and self.config.has_option('auth', 'user'):
            auth_user = self.config.get('auth', 'user')
        auth_password = os.environ.get('VMWARE_PASSWORD')
        if not auth_password and self.config.has_option('auth', 'password'):
            auth_password = self.config.get('auth', 'password')

        # Create the VMware client connection.
        self.client = Client(auth_host, auth_user, auth_password)
Exemplo n.º 13
0
 def run(self):
     logging.info('connecting to %s', self.server)
     self.client = Client()
     self.identify_datacenter()
     self.identify_datastore()
     self.list_files()
     self.client.logout()
Exemplo n.º 14
0
def main():

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.verify_mode = ssl.CERT_NONE 

    # real vcenter
    kwargs = {'host': '192.168.1.39', 'user': '******', 'pwd': 'vmware', 'port': 443, 'sslContext': context}

    # fake vcenter
    kwargs = {'host': 'localhost', 'user': '******', 'pwd': 'test', 'port': 443, 'sslContext': context }


    print('# PYVMOMI ...')
    try:
        si = SmartConnect(**kwargs)
        content = si.RetrieveContent()
        virtual_machines = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)

        for virtual_machine in virtual_machines.view:
            name = virtual_machine.name
            print('name: %s' % name)
            if virtual_machine.guest:
                for net in virtual_machine.guest.net:
                    print('mac: %s' % net.macAddress)
    except Exception as e:
        print e

    print('# PSPHERE ...')
    client = Client(kwargs['host'], kwargs['user'], kwargs['pwd']) 
    hosts = HostSystem.all(client)
    for host in hosts:
        print 'host:',host.name
        for vm in host.vm:
            print 'name: ',vm.name
Exemplo n.º 15
0
def main():

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.verify_mode = ssl.CERT_NONE

    # real vcenter
    kwargs = {
        'host': '192.168.1.39',
        'user': '******',
        'pwd': 'vmware',
        'port': 443,
        'sslContext': context
    }

    # fake vcenter
    kwargs = {
        'host': 'localhost',
        'user': '******',
        'pwd': 'test',
        'port': 443,
        'sslContext': context
    }

    print('# PYVMOMI ...')
    try:
        si = SmartConnect(**kwargs)
        content = si.RetrieveContent()
    except Exception as e:
        print e

    print('# PSPHERE ...')
    client = Client(kwargs['host'], kwargs['user'], kwargs['pwd'])
Exemplo n.º 16
0
def run(**kwargs):
    provider = cfme_data['management_systems'][kwargs.get('provider')]
    creds = credentials[provider['credentials']]

    hostname = provider['hostname']
    username = creds['username']
    password = creds['password']

    client = Client(server=hostname, username=username, password=password)

    kwargs = update_params_api(client, **kwargs)

    name = kwargs.get('template_name', None)
    if name is None:
        name = cfme_data['basic_info']['appliance_template']

    print "VSPHERE: Template Name: %s" % name

    check_kwargs(**kwargs)

    url = kwargs.get('image_url')

    if not check_template_exists(hostname, username, password, name):
        if kwargs.get('upload'):
            # Wrapper for ovftool - sometimes it just won't work
            for i in range(0, NUM_OF_TRIES_OVFTOOL):
                print "VSPHERE: Trying ovftool %s..." % i
                ova_ret, ova_out = upload_ova(hostname, username, password,
                                              name, kwargs.get('datastore'),
                                              kwargs.get('cluster'),
                                              kwargs.get('datacenter'), url,
                                              kwargs.get('host'),
                                              kwargs.get('proxy'))
                if ova_ret is 0:
                    break
            if ova_ret is -1:
                print "VSPHERE: Ovftool failed to upload file."
                print ova_out
                sys.exit(127)

        if kwargs.get('disk'):
            add_disk(client, name)
        if kwargs.get('template'):
            make_template(client, name, hostname, username, password)
        client.logout()
    print "VSPHERE: Completed successfully"
Exemplo n.º 17
0
 def connect_server(self):
     try:
         client = Client(self.server_ip, self.username, self.password)
         print "connection established"
         return client
     except Exception, e:
         print "exception:", e
         sys.exit(1)
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://%s@%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:"******"'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:"******"\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])
Exemplo n.º 19
0
def main(options):
    client = Client(server=options.server, username=options.username,
                    password=options.password)

    print('Successfully connected to %s' % client.server)

    # Get a HostSystem object representing the host
    host = HostSystem.get(client, name=options.hostsystem)

    # Preload the name attribute of all items in the vm attribute. Read the
    # manual as this significantly speeds up queries for ManagedObject's
    host.preload("vm", properties=["name"])

    # Iterate over the items in host.vm and print their names
    for vm in sorted(host.vm):
        print(vm.name)

    # Close the connection
    client.logout()
Exemplo n.º 20
0
    def __init__(self, guests_only=None):
        self.config = configparser.SafeConfigParser()
        if os.environ.get('VMWARE_INI', ''):
            config_files = [os.environ['VMWARE_INI']]
        else:
            config_files = [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini']
        for config_file in config_files:
            if os.path.exists(config_file):
                self.config.read(config_file)
                break

        # Retrieve only guest VMs, or include host systems?
        if guests_only is not None:
            self.guests_only = guests_only
        elif self.config.has_option('defaults', 'guests_only'):
            self.guests_only = self.config.getboolean('defaults', 'guests_only')
        else:
            self.guests_only = True

        # Read authentication information from VMware environment variables
        # (if set), otherwise from INI file.
        auth_host = os.environ.get('VMWARE_HOST')
        if not auth_host and self.config.has_option('auth', 'host'):
            auth_host = self.config.get('auth', 'host')
        auth_user = os.environ.get('VMWARE_USER')
        if not auth_user and self.config.has_option('auth', 'user'):
            auth_user = self.config.get('auth', 'user')
        auth_password = os.environ.get('VMWARE_PASSWORD')
        if not auth_password and self.config.has_option('auth', 'password'):
            auth_password = self.config.get('auth', 'password')
        sslcheck = os.environ.get('VMWARE_SSLCHECK')
        if not sslcheck and self.config.has_option('auth', 'sslcheck'):
            sslcheck = self.config.get('auth', 'sslcheck')
        if not sslcheck:
            sslcheck = True
        else:
            if sslcheck.lower() in ['no', 'false']:
                sslcheck = False
            else:
                sslcheck = True

        # Limit the clusters being scanned
        self.filter_clusters = os.environ.get('VMWARE_CLUSTERS')
        if not self.filter_clusters and self.config.has_option('defaults', 'clusters'):
            self.filter_clusters = self.config.get('defaults', 'clusters')
        if self.filter_clusters:
            self.filter_clusters = [x.strip() for x in self.filter_clusters.split(',') if x.strip()]

        # Override certificate checks
        if not sslcheck:
            if hasattr(ssl, '_create_unverified_context'):
                ssl._create_default_https_context = ssl._create_unverified_context

        # Create the VMware client connection.
        self.client = Client(auth_host, auth_user, auth_password)
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
def main(options):
    client = Client(server=options.server,
                    username=options.username,
                    password=options.password)

    print('Successfully connected to %s' % client.server)

    # Get a HostSystem object representing the host
    host = HostSystem.get(client, name=options.hostsystem)

    # Preload the name attribute of all items in the vm attribute. Read the
    # manual as this significantly speeds up queries for ManagedObject's
    host.preload("vm", properties=["name"])

    # Iterate over the items in host.vm and print their names
    for vm in sorted(host.vm):
        print(vm.name)

    # Close the connection
    client.logout()
Exemplo n.º 23
0
def main(options):
    client = Client(server=options.server,
                    username=options.username,
                    password=options.password)

    print('Successfully connected to %s' % client.server)

    host = HostSystem.all(client)

    for h in host:
        # Preload the name attribute of all items in the vm attribute. Read the
        # manual as this significantly speeds up queries for ManagedObject's
        h.preload("vm", properties=["name", "guest"])

        # Iterate over the items in host.vm and print their names
        for vm in sorted(h.vm):
            print("%s: %s" % (vm.name, vm.guest.guestState))

    # Close the connection
    client.logout()
Exemplo n.º 24
0
 def connect(self):
     configuration=Config()
     server = configuration._config_value("general", "server")
     if server is None:
         raise ValueError("server must be supplied on command line"+"or in configuration file.")
     username = configuration._config_value("general", "username")
     if username is None:
         raise ValueError("username must be supplied on command line"
                      " or in configuration file.")
     password = configuration._config_value("general", "password")
     if password is None:
         raise ValueError("password must be supplied on command line"
                      " or in configuration file.")

     self.client=Client(server,username,password)
Exemplo n.º 25
0
e.g.
    reconfig_vm test

"""

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)
Exemplo n.º 26
0
from ssl import SSLContext, PROTOCOL_SSLv23, CERT_NONE
from psphere.client import Client

context = SSLContext(PROTOCOL_SSLv23)
context.verify_mode = CERT_NONE
test_client = Client("192.168.0.14", "root", "password", sslcontext=context)
print(test_client.si.CurrentTime())
test_client.logout()
Exemplo n.º 27
0
class VSphereHelper:
    def __init__(self, url, username, password):
        self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        if(url.startswith('http://') or url.startswith('https://')):
            server = urllib2.Request(url).get_host()
        else:
            server = url
        self.client = Client(server=server, username=username, password=password)

    def curl_progress(self, download_t, download_d, upload_t, upload_d):
        curtime=time()
        # TODO: Make poke frequency variable
        # 5 seconds isn't too much and it makes the status bar in the vSphere GUI look nice :-)
        if  (curtime - self.time_at_last_poke) >= 5:
            self.lease.HttpNfcLeaseProgress(percent = int(upload_d*100/upload_t))
            self.time_at_last_poke = time()

    def create_vm(self, imagefilename, name, compute_resource, datastore, disksize, nics,
                  memory, num_cpus, guest_id, host=None):
        """Create a virtual machine using the specified values.

        :param name: The name of the VM to create.
        :type name: str
        :param compute_resource: The name of a ComputeResource in which to \
                create the VM.
        :type compute_resource: str
        :param datastore: The name of the datastore on which to create the VM.
        :type datastore: str
        :param disksize: The size of the disk, specified in KB, MB or GB. e.g. \
                20971520KB, 20480MB, 20GB.
        :type disksize: str
        :param nics: The NICs to create, specified in a list of dict's which \
                contain a "network_name" and "type" key. e.g. \
                {"network_name": "VM Network", "type": "VirtualE1000"}
        :type nics: list of dict's
        :param memory: The amount of memory for the VM. Specified in KB, MB or \
                GB. e.g. 2097152KB, 2048MB, 2GB.
        :type memory: str
        :param num_cpus: The number of CPUs the VM will have.
        :type num_cpus: int
        :param guest_id: The vSphere string of the VM guest you are creating. \
                The list of VMs can be found at \
            http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/index.html
        :type guest_id: str
        :param host: The name of the host (default: None), if you want to \
                provision the VM on a \ specific host.
        :type host: str

        """
        # Convenience variable
        client = self.client

        self.log.debug("Creating VM %s" % name)
        # If the host is not set, use the ComputeResource as the target
        if host is None:
            target = client.find_entity_view("ComputeResource",
                                          filter={"name": compute_resource})
            resource_pool = target.resourcePool
        else:
            target = client.find_entity_view("HostSystem", filter={"name": host})
            resource_pool = target.parent.resourcePool

        disksize_pattern = re.compile("^\d+[KMG]B")
        if disksize_pattern.match(disksize) is None:
            raise Exception("Disk size %s is invalid. Try \"12G\" or similar" % disksize)

        if disksize.endswith("GB"):
            disksize_kb = int(disksize[:-2]) * 1024 * 1024
        elif disksize.endswith("MB"):
            disksize_kb = int(disksize[:-2]) * 1024
        elif disksize.endswith("KB"):
            disksize_kb = int(disksize[:-2])
        else:
            raise Exception("Disk size %s is invalid. Try \"12G\" or similar" % disksize)

        memory_pattern = re.compile("^\d+[KMG]B")
        if memory_pattern.match(memory) is None:
            raise Exception("Memory size %s is invalid. Try \"12G\" or similar" % memory)

        if memory.endswith("GB"):
            memory_mb = int(memory[:-2]) * 1024
        elif memory.endswith("MB"):
            memory_mb = int(memory[:-2])
        elif memory.endswith("KB"):
            memory_mb = int(memory[:-2]) / 1024
        else:
            raise Exception("Memory size %s is invalid. Try \"12G\" or similar" % memory)

        # A list of devices to be assigned to the VM
        vm_devices = []

        # Create a disk controller
        controller = self.create_controller("VirtualLsiLogicController")
        vm_devices.append(controller)

        ds_to_use = None
        for ds in target.datastore:
            if ds.name == datastore:
                ds_to_use = ds
                break

        if ds_to_use is None:
            raise Exception("Could not find datastore on %s with name %s" %
                  (target.name, datastore))

        # Ensure the datastore is accessible and has enough space
        if ds_to_use.summary.accessible is not True:
            raise Exception("Datastore (%s) exists, but is not accessible" %
                  ds_to_use.summary.name)
        if ds_to_use.summary.freeSpace < disksize_kb * 1024:
            raise Exception("Datastore (%s) exists, but does not have sufficient"
                  " free space." % ds_to_use.summary.name)

        disk = self.create_disk(datastore=ds_to_use, disksize_kb=disksize_kb)
        vm_devices.append(disk)

        cdrom = self.create_cdrom(datastore=ds_to_use)
        vm_devices.append(cdrom)
        
        for nic in nics:
            nic_spec = self.create_nic(target, nic)
            if nic_spec is None:
                raise Exception("Could not create spec for NIC")

            # Append the nic spec to the vm_devices list
            vm_devices.append(nic_spec)

        vmfi = client.create("VirtualMachineFileInfo")
        vmfi.vmPathName = "[%s]" % ds_to_use.summary.name
        vm_config_spec = client.create("VirtualMachineConfigSpec")
        vm_config_spec.name = name
        vm_config_spec.memoryMB = memory_mb
        vm_config_spec.files = vmfi
        vm_config_spec.annotation = "Auto-provisioned by psphere"
        vm_config_spec.numCPUs = num_cpus
        vm_config_spec.guestId = guest_id
        vm_config_spec.deviceChange = vm_devices

        # Find the datacenter of the target
        if target.__class__.__name__ == "HostSystem":
            datacenter = target.parent.parent.parent
        else:
            datacenter = target.parent.parent

        importspec = client.create('VirtualMachineImportSpec')

        importspec.configSpec = vm_config_spec
        importspec.resPoolEntity = None

        lease = resource_pool.ImportVApp(spec = importspec, folder = datacenter.vmFolder)
        self.lease = lease

        # Lease takes a bit of time to initialize
        for i in range(1000):
            #print lease.error
            if lease.state == "ready":
                break
            if lease.state == "error":
                raise Exception("Our HttpNFCLease failed to initialize")
            sleep(5)
            lease.update_view_data(properties=["state"])

        #print "For debug and general info, here is the lease info"
        #pprint(lease.info)

        upload_url = None
        for url_candidate in lease.info.deviceUrl:
            if url_candidate['disk']:
                upload_url = str(url_candidate['url'])

        if not upload_url:
            raise Exception("Unable to extract disk upload URL from HttpNfcLease")

        self.log.debug("Extracted image upload URL (%s) from lease" % (upload_url))

        lease_timeout = lease.info.leaseTimeout
        self.time_at_last_poke = time()

        image_file = open(imagefilename)

        # Upload the image itself
        image_size = os.path.getsize(imagefilename)
        curl = pycurl.Curl()
        curl.setopt(pycurl.URL, upload_url)
        curl.setopt(pycurl.SSL_VERIFYPEER, 0)
        curl.setopt(pycurl.POST, 1)
        curl.setopt(pycurl.POSTFIELDSIZE, image_size)
        curl.setopt(pycurl.READFUNCTION, image_file.read)
        curl.setopt(pycurl.HTTPHEADER, ["User-Agent: Load Tool (PyCURL Load Tool)", "Content-Type: application/octet-stream"])
        curl.setopt(pycurl.NOPROGRESS, 0)
        curl.setopt(pycurl.PROGRESSFUNCTION, self.curl_progress)
        curl.perform()
        curl.close()

        image_file.close()

        lease.HttpNfcLeaseComplete()

        vm = lease.info.entity

        vm.MarkAsTemplate()

    def create_nic(self, target, nic):
        # Convenience variable
        client = self.client
        """Return a NIC spec"""
        # Iterate through the networks and look for one matching
        # the requested name
        for network in target.network:
            if network.name == nic["network_name"]:
                net = network
                break
        else:
            return None

        # Success! Create a nic attached to this network
        backing = client.create("VirtualEthernetCardNetworkBackingInfo")
        backing.deviceName = nic["network_name"]
        backing.network = net

        connect_info = client.create("VirtualDeviceConnectInfo")
        connect_info.allowGuestControl = True
        connect_info.connected = False
        connect_info.startConnected = True

        new_nic = client.create(nic["type"]) 
        new_nic.backing = backing
        new_nic.key = 2
        # TODO: Work out a way to automatically increment this
        new_nic.unitNumber = 1
        new_nic.addressType = "generated"
        new_nic.connectable = connect_info

        nic_spec = client.create("VirtualDeviceConfigSpec")
        nic_spec.device = new_nic
        nic_spec.fileOperation = None
        operation = client.create("VirtualDeviceConfigSpecOperation")
        nic_spec.operation = (operation.add)

        return nic_spec

    def create_controller(self, controller_type):
        # Convenience variable
        client = self.client
        controller = client.create(controller_type)
        controller.key = 0
        controller.device = [0]
        controller.busNumber = 0,
        controller.sharedBus = client.create("VirtualSCSISharing").noSharing
        spec = client.create("VirtualDeviceConfigSpec")
        spec.device = controller
        spec.fileOperation = None
        spec.operation = client.create("VirtualDeviceConfigSpecOperation").add
        return spec

    def create_disk(self, datastore, disksize_kb):
        # Convenience variable
        client = self.client
        backing = client.create("VirtualDiskFlatVer2BackingInfo")
        backing.datastore = None
        backing.diskMode = "persistent"
        backing.fileName = "[%s]" % datastore.summary.name
        backing.thinProvisioned = True

        disk = client.create("VirtualDisk")
        disk.backing = backing
        disk.controllerKey = 0
        disk.key = 0
        disk.unitNumber = 0
        disk.capacityInKB = disksize_kb

        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

        return disk_spec

    def create_cdrom(self, datastore):
        # Convenience variable
        client = self.client
        # This creates what is essentially a virtual CDROM drive with no disk in it
        # Adding this greatly simplifies the process of adding a custom ISO via deltacloud
        connectable = client.create('VirtualDeviceConnectInfo')
        connectable.allowGuestControl = True
        connectable.connected = True
        connectable.startConnected = True
        #connectable.status = None

        backing = client.create('VirtualCdromIsoBackingInfo')
        backing.datastore = None
        backing.fileName = '[%s]' % datastore.summary.name

        cdrom = client.create('VirtualCdrom')
        cdrom.connectable = connectable
        cdrom.backing = backing
        # 201 is the second built in IDE controller
        cdrom.controllerKey = 201
        cdrom.key = 10
        cdrom.unitNumber = 0

        cdrom_spec = client.create('VirtualDeviceConfigSpec')
        cdrom_spec.fileOperation = None
        cdrom_spec.device = cdrom
        operation = client.create('VirtualDeviceConfigSpecOperation')
        cdrom_spec.operation = operation.add

        return cdrom_spec

    def delete_vm(self, name):
        vm = self.client.find_entity_view("VirtualMachine", filter={"name":name})
        if not vm:
            raise Exception("Cannot find VM with name (%s)" % (name))

        vmdestroy = vm.Destroy_Task()
        for i in range(300):
            if not (vmdestroy.info.state in ["queued", "running"]):
                break
            sleep(1)
            vmdestroy.update_view_data(properties=["info"])

        if vmdestroy.info.state != "success":
            # TODO: Return the reason - this is part of the rather complex Task object
            raise Exception("Failed to delete VM (%s) in timeout period" % (name))
Exemplo n.º 28
0
        if sys.argv[1] == "--host":
            hostname = sys.argv[2]

    # Read config
    config = ConfigParser.SafeConfigParser()
    me = os.path.abspath(sys.argv[0]).rstrip('.py')
    for configfilename in [me + '.ini', 'vmware.ini']:
        if os.path.exists(configfilename):
            config.read(configfilename)
            break

    mename = os.path.basename(me).upper()
    host =  os.getenv('VMWARE_' + mename + '_HOST',os.getenv('VMWARE_HOST', config.get('auth','host')))
    user = os.getenv('VMWARE_' + mename + '_USER', os.getenv('VMWARE_USER', config.get('auth','user')))
    password = os.getenv('VMWARE_' + mename + '_PASSWORD',os.getenv('VMWARE_PASSWORD', config.get('auth','password')))

    try:
        client =  Client( host,user,password )
    except Exception, e:
        client = None
        #print >> STDERR "Unable to login (only cache available): %s", str(e)

    # Actually do the work
    if hostname is None:
        inventory = get_inventory(client, config)
    else:
        inventory = get_single_host(client, config, hostname)

    # Return to ansible
    print inventory
Exemplo n.º 29
0
#!/bin/env python

import sys
from psphere.client import Client

argvs = sys.argv
target_host = argvs[1]  # 第1引数に指定したターゲットホスト名取得
target_vm = argvs[2]  # 第2引数に指定したターゲットVM名取得

client = Client("ホスト名/IPアドレス", "ログインユーザ名", "パスワード")

host = HostSystem.get(client, name=target_host)  #ターゲットホストシステム情報取得
for vm in host.vm:
    if vm.name == target_vm:
        vm.PowerOnVM_Task()  # ターゲットVMのPowerOn実行
Exemplo n.º 30
0
        if sys.argv[1] == "--host":
            hostname = sys.argv[2]

    # Read config
    config = ConfigParser.SafeConfigParser()
    for configfilename in [
            os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini'
    ]:
        if os.path.exists(configfilename):
            config.read(configfilename)
            break

    try:
        client = Client(
            config.get('auth', 'host'),
            config.get('auth', 'user'),
            config.get('auth', 'password'),
        )
    except Exception, e:
        client = None
        #print >> STDERR "Unable to login (only cache avilable): %s", str(e)

    # acitually do the work
    if hostname is None:
        inventory = get_inventory(client, config)
    else:
        inventory = get_single_host(client, config, hostname)

    # return to ansible
    print inventory
Exemplo n.º 31
0
        sys.exit(127)


if __name__ == "__main__":
    args = parse_cmd_line()

    provider = conf.cfme_data["management_systems"][args.provider]
    creds = conf.credentials[provider["credentials"]]

    hostname = provider["hostname"]
    username = creds["username"]
    password = creds["password"]
    datastore = args.datastore or provider["datastores"][0]
    cluster = args.cluster or provider["clusters"][0]
    datacenter = args.datacenter or provider["datacenters"][0]

    name = get_vm_name(args)
    url = args.url
    print "Template Name: %s" % name

    if args.upload:
        upload_ova(hostname, username, password, name, datastore, cluster, datacenter, url)

    client = Client(server=hostname, username=username, password=password)
    if args.disk:
        add_disk(client, name)
    if args.template:
        make_template(client, name)
    client.logout()
print "Completed successfully"
Exemplo n.º 32
0
#!/usr/bin/python

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
Exemplo n.º 33
0
#!/bin/env python

from psphere.client import Client
from psphere.managedobjects import HostSystem
esxi_host = sys.argv[1]  #HyperVisor hostname
username = sys.argv[2]  #HyperVisor login username
password = sys.argv[3]  #HyperVisor login password

client = Client(esxi_host, username, password)

hosts = HostSystem.all(client)
cpu_usage = hosts[0].summary.quickStats.overallCpuUsage
print cpu_usage
Exemplo n.º 34
0
#!/usr/bin/python
"""A script which generates DHCP configuration for hosts matching a regex.
Usage:
    find_vms_by_regex.py <regex> <compute_resource>
e.g.
    find_vms_by_regex.py 'ssi2+' 'Online Engineering'
"""

import re
import sys

from psphere.client import Client
from psphere.managedobjects import ComputeResource

client = Client()

vm_regex = sys.argv[1]
p = re.compile(vm_regex)
compute_resource = sys.argv[2]

cr = ComputeResource.get(client, name=compute_resource)

cr.resourcePool.preload("vm", properties=["name"])
for vm in sorted(cr.resourcePool.vm):
    if p.match(vm.name) is None:
        continue
    print(vm.name)

client.logout()
Exemplo n.º 35
0
def main():
    client = Client()
    dsf = DatastoreFiles(client)
    dsf.list_files()
    client.logout()
Exemplo n.º 36
0
"""A script which generates DHCP configuration for hosts matching a regex.
Usage:
    gen_dhcpconf.py <regex> <compute_resource>
e.g.
    gen_dhcpconf.py 'ssi2+' 'Online Engineering'
"""

from __future__ import absolute_import, division, print_function

import re
import sys

from psphere.client import Client

if __name__ == '__main__':
    client = Client()

    host_regex = sys.argv[1]
    p = re.compile(host_regex)
    compute_resource = sys.argv[2]

    cr = client.find_entity_view("ComputeResource",
                                 filter={"name": compute_resource})

    cr.resourcePool.preload("vm", properties=["name"])
    for vm in sorted(cr.resourcePool.vm):
        if p.match(vm.name) is None:
            continue

        print("host %s {" % vm.name)
        print("    option host-name \"%s\";" % vm.name)
Exemplo n.º 37
0
def main():
    client = Client()
    dsf = DatastoreFiles(client)
    dsf.list_files()
    client.logout()
Exemplo n.º 38
0
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)
Exemplo n.º 39
0
from __future__ import absolute_import, division, print_function

from ssl import CERT_NONE, PROTOCOL_SSLv23, SSLContext

from psphere.client import Client

if __name__ == '__main__':
    context = SSLContext(PROTOCOL_SSLv23)
    context.verify_mode = CERT_NONE
    test_client = Client('localhost:8989', 'user', 'pass', sslcontext=context)
    print(test_client.si.CurrentTime())
    test_client.logout()
Exemplo n.º 40
0
 def run(self):
     client = Client()
     hsev = client.find_entity_view('HostSystem', filter={'name': self.server})
     for network in hsev.network:
         print network.name
     client.logout()
Exemplo n.º 41
0
class VSphereHelper:
    def __init__(self, url, username, password):
        self.log = logging.getLogger('%s.%s' %
                                     (__name__, self.__class__.__name__))
        if (url.startswith('http://') or url.startswith('https://')):
            server = urllib2.Request(url).get_host()
        else:
            server = url
        self.client = Client(server=server,
                             username=username,
                             password=password)

    def curl_progress(self, download_t, download_d, upload_t, upload_d):
        curtime = time()
        # TODO: Make poke frequency variable
        # 5 seconds isn't too much and it makes the status bar in the vSphere GUI look nice :-)
        if (curtime - self.time_at_last_poke) >= 5:
            self.lease.HttpNfcLeaseProgress(percent=int(upload_d * 100 /
                                                        upload_t))
            self.time_at_last_poke = time()

    def create_vm(self,
                  imagefilename,
                  name,
                  compute_resource,
                  datastore,
                  disksize,
                  nics,
                  memory,
                  num_cpus,
                  guest_id,
                  host=None):
        """Create a virtual machine using the specified values.

        :param name: The name of the VM to create.
        :type name: str
        :param compute_resource: The name of a ComputeResource in which to \
                create the VM.
        :type compute_resource: str
        :param datastore: The name of the datastore on which to create the VM.
        :type datastore: str
        :param disksize: The size of the disk, specified in KB, MB or GB. e.g. \
                20971520KB, 20480MB, 20GB.
        :type disksize: str
        :param nics: The NICs to create, specified in a list of dict's which \
                contain a "network_name" and "type" key. e.g. \
                {"network_name": "VM Network", "type": "VirtualE1000"}
        :type nics: list of dict's
        :param memory: The amount of memory for the VM. Specified in KB, MB or \
                GB. e.g. 2097152KB, 2048MB, 2GB.
        :type memory: str
        :param num_cpus: The number of CPUs the VM will have.
        :type num_cpus: int
        :param guest_id: The vSphere string of the VM guest you are creating. \
                The list of VMs can be found at \
            http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/index.html
        :type guest_id: str
        :param host: The name of the host (default: None), if you want to \
                provision the VM on a \ specific host.
        :type host: str

        """
        # Convenience variable
        client = self.client

        self.log.debug("Creating VM %s" % name)
        # If the host is not set, use the ComputeResource as the target
        if host is None:
            target = client.find_entity_view("ComputeResource",
                                             filter={"name": compute_resource})
            resource_pool = target.resourcePool
        else:
            target = client.find_entity_view("HostSystem",
                                             filter={"name": host})
            resource_pool = target.parent.resourcePool

        disksize_pattern = re.compile("^\d+[KMG]B")
        if disksize_pattern.match(disksize) is None:
            raise Exception("Disk size %s is invalid. Try \"12G\" or similar" %
                            disksize)

        if disksize.endswith("GB"):
            disksize_kb = int(disksize[:-2]) * 1024 * 1024
        elif disksize.endswith("MB"):
            disksize_kb = int(disksize[:-2]) * 1024
        elif disksize.endswith("KB"):
            disksize_kb = int(disksize[:-2])
        else:
            raise Exception("Disk size %s is invalid. Try \"12G\" or similar" %
                            disksize)

        memory_pattern = re.compile("^\d+[KMG]B")
        if memory_pattern.match(memory) is None:
            raise Exception(
                "Memory size %s is invalid. Try \"12G\" or similar" % memory)

        if memory.endswith("GB"):
            memory_mb = int(memory[:-2]) * 1024
        elif memory.endswith("MB"):
            memory_mb = int(memory[:-2])
        elif memory.endswith("KB"):
            memory_mb = int(memory[:-2]) / 1024
        else:
            raise Exception(
                "Memory size %s is invalid. Try \"12G\" or similar" % memory)

        # A list of devices to be assigned to the VM
        vm_devices = []

        # Create a disk controller
        controller = self.create_controller("VirtualLsiLogicController")
        vm_devices.append(controller)

        ds_to_use = None
        for ds in target.datastore:
            if ds.name == datastore:
                ds_to_use = ds
                break

        if ds_to_use is None:
            raise Exception("Could not find datastore on %s with name %s" %
                            (target.name, datastore))

        # Ensure the datastore is accessible and has enough space
        if ds_to_use.summary.accessible is not True:
            raise Exception("Datastore (%s) exists, but is not accessible" %
                            ds_to_use.summary.name)
        if ds_to_use.summary.freeSpace < disksize_kb * 1024:
            raise Exception(
                "Datastore (%s) exists, but does not have sufficient"
                " free space." % ds_to_use.summary.name)

        disk = self.create_disk(datastore=ds_to_use, disksize_kb=disksize_kb)
        vm_devices.append(disk)

        cdrom = self.create_cdrom(datastore=ds_to_use)
        vm_devices.append(cdrom)

        for nic in nics:
            nic_spec = self.create_nic(target, nic)
            if nic_spec is None:
                raise Exception("Could not create spec for NIC")

            # Append the nic spec to the vm_devices list
            vm_devices.append(nic_spec)

        vmfi = client.create("VirtualMachineFileInfo")
        vmfi.vmPathName = "[%s]" % ds_to_use.summary.name
        vm_config_spec = client.create("VirtualMachineConfigSpec")
        vm_config_spec.name = name
        vm_config_spec.memoryMB = memory_mb
        vm_config_spec.files = vmfi
        vm_config_spec.annotation = "Auto-provisioned by psphere"
        vm_config_spec.numCPUs = num_cpus
        vm_config_spec.guestId = guest_id
        vm_config_spec.deviceChange = vm_devices

        # Find the datacenter of the target
        if target.__class__.__name__ == "HostSystem":
            datacenter = target.parent.parent.parent
        else:
            datacenter = target.parent.parent

        importspec = client.create('VirtualMachineImportSpec')

        importspec.configSpec = vm_config_spec
        importspec.resPoolEntity = None

        lease = resource_pool.ImportVApp(spec=importspec,
                                         folder=datacenter.vmFolder)
        self.lease = lease

        # Lease takes a bit of time to initialize
        for i in range(1000):
            #print lease.error
            if lease.state == "ready":
                break
            if lease.state == "error":
                raise Exception("Our HttpNFCLease failed to initialize")
            sleep(5)
            lease.update_view_data(properties=["state"])

        #print "For debug and general info, here is the lease info"
        #pprint(lease.info)

        url = None
        for url in lease.info.deviceUrl:
            if url['disk']:
                url = url['url']

        if not url:
            raise Exception(
                "Unable to extract disk upload URL from HttpNfcLease")

        self.log.debug("Extracted image upload URL (%s) from lease" % (url))

        lease_timeout = lease.info.leaseTimeout
        self.time_at_last_poke = time()

        image_file = open(imagefilename)

        # Upload the image itself
        image_size = os.path.getsize(imagefilename)
        curl = pycurl.Curl()
        curl.setopt(pycurl.URL, str(url))
        curl.setopt(pycurl.SSL_VERIFYPEER, 0)
        curl.setopt(pycurl.POST, 1)
        curl.setopt(pycurl.POSTFIELDSIZE, image_size)
        curl.setopt(pycurl.READFUNCTION, image_file.read)
        curl.setopt(pycurl.HTTPHEADER, [
            "User-Agent: Load Tool (PyCURL Load Tool)",
            "Content-Type: application/octet-stream"
        ])
        curl.setopt(pycurl.NOPROGRESS, 0)
        curl.setopt(pycurl.PROGRESSFUNCTION, self.curl_progress)
        curl.perform()
        curl.close()

        image_file.close()

        lease.HttpNfcLeaseComplete()

        vm = lease.info.entity

        vm.MarkAsTemplate()

    def create_nic(self, target, nic):
        # Convenience variable
        client = self.client
        """Return a NIC spec"""
        # Iterate through the networks and look for one matching
        # the requested name
        for network in target.network:
            if network.name == nic["network_name"]:
                net = network
                break
        else:
            return None

        # Success! Create a nic attached to this network
        backing = client.create("VirtualEthernetCardNetworkBackingInfo")
        backing.deviceName = nic["network_name"]
        backing.network = net

        connect_info = client.create("VirtualDeviceConnectInfo")
        connect_info.allowGuestControl = True
        connect_info.connected = False
        connect_info.startConnected = True

        new_nic = client.create(nic["type"])
        new_nic.backing = backing
        new_nic.key = 2
        # TODO: Work out a way to automatically increment this
        new_nic.unitNumber = 1
        new_nic.addressType = "generated"
        new_nic.connectable = connect_info

        nic_spec = client.create("VirtualDeviceConfigSpec")
        nic_spec.device = new_nic
        nic_spec.fileOperation = None
        operation = client.create("VirtualDeviceConfigSpecOperation")
        nic_spec.operation = (operation.add)

        return nic_spec

    def create_controller(self, controller_type):
        # Convenience variable
        client = self.client
        controller = client.create(controller_type)
        controller.key = 0
        controller.device = [0]
        controller.busNumber = 0,
        controller.sharedBus = client.create("VirtualSCSISharing").noSharing
        spec = client.create("VirtualDeviceConfigSpec")
        spec.device = controller
        spec.fileOperation = None
        spec.operation = client.create("VirtualDeviceConfigSpecOperation").add
        return spec

    def create_disk(self, datastore, disksize_kb):
        # Convenience variable
        client = self.client
        backing = client.create("VirtualDiskFlatVer2BackingInfo")
        backing.datastore = None
        backing.diskMode = "persistent"
        backing.fileName = "[%s]" % datastore.summary.name
        backing.thinProvisioned = True

        disk = client.create("VirtualDisk")
        disk.backing = backing
        disk.controllerKey = 0
        disk.key = 0
        disk.unitNumber = 0
        disk.capacityInKB = disksize_kb

        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

        return disk_spec

    def create_cdrom(self, datastore):
        # Convenience variable
        client = self.client
        # This creates what is essentially a virtual CDROM drive with no disk in it
        # Adding this greatly simplifies the process of adding a custom ISO via deltacloud
        connectable = client.create('VirtualDeviceConnectInfo')
        connectable.allowGuestControl = True
        connectable.connected = True
        connectable.startConnected = True
        #connectable.status = None

        backing = client.create('VirtualCdromIsoBackingInfo')
        backing.datastore = None
        backing.fileName = '[%s]' % datastore.summary.name

        cdrom = client.create('VirtualCdrom')
        cdrom.connectable = connectable
        cdrom.backing = backing
        # 201 is the second built in IDE controller
        cdrom.controllerKey = 201
        cdrom.key = 10
        cdrom.unitNumber = 0

        cdrom_spec = client.create('VirtualDeviceConfigSpec')
        cdrom_spec.fileOperation = None
        cdrom_spec.device = cdrom
        operation = client.create('VirtualDeviceConfigSpecOperation')
        cdrom_spec.operation = operation.add

        return cdrom_spec

    def delete_vm(self, name):
        vm = self.client.find_entity_view("VirtualMachine",
                                          filter={"name": name})
        if not vm:
            raise Exception("Cannot find VM with name (%s)" % (name))

        vmdestroy = vm.Destroy_Task()
        for i in range(300):
            if not (vmdestroy.info.state in ["queued", "running"]):
                break
            sleep(1)
            vmdestroy.update_view_data(properties=["info"])

        if vmdestroy.info.state != "success":
            # TODO: Return the reason - this is part of the rather complex Task object
            raise Exception("Failed to delete VM (%s) in timeout period" %
                            (name))
Exemplo n.º 42
0
 def __init__(self, key, secret=None, secure=True, host=None):
     self.key = key
     self.secret = secret
     self.host = host
     self.connection = Client(server=host, username=key, password=secret)
Exemplo n.º 43
0
class ListDatastoreContents:
    
    def __init__(self, args):
        self.dcname = args.datacenter
        self.dsname = args.datastore
        self.server = config._config_value('general', 'server', args.server)
        self.username = config._config_value('general', 'username', args.username)
        self.password = config._config_value('general', 'password', args.username)
        self.client = None
        self.datacenter = None
        self.datastore = None


    def validate(self):
        pass

    def identify_datacenter(self):
        dcs = Datacenter.all(self.client)
        if self.dcname is None:
            self.datacenter = dcs[0]
            logging.info('defaulting to data center %s' % (self.datacenter.name))
        else:
            for dc in dcs:
                if dc.name == self.dcname:
                    self.datacenter = dc
                    break
            if self.datacenter is None:
                raise ValueError('no data center named %s' % (self.dcname))

    def identify_datastore(self):
        dss = self.datacenter.datastore
        if self.dsname is None:
            self.datastore = dss[0]
            logging.info('defaulting to data store %s' % (self.datastore.info.name))
        else:
            for ds in dss:
                if ds.info.name == self.dsname:
                    self.datastore = ds
                    break
            if self.datastore is None:
                raise ValueError('no data store named %s' % (self.dsname))

    def list_files(self):
        browser = self.datastore.browser
        rootpath = '[%s] /' % (self.datastore.info.name) 
        task = browser.SearchDatastoreSubFolders_Task(datastorePath=rootpath)
        while task.info.state == 'running':
            print '.',
            time.sleep(3)
            task.update()
        print 'done'
        for resultlist in task.info.result:
            # first entry is a type descriptor, skip over it
            for result in resultlist[1:]:
                for r in result:
                    try:
                        for f in r.file:
                            print os.path.join(r.folderPath, f.path)
                    except AttributeError:
                        pass

    def run(self):
        logging.info('connecting to %s', self.server)
        self.client = Client()
        self.identify_datacenter()
        self.identify_datastore()
        self.list_files()
        self.client.logout()
Exemplo n.º 44
0
def main():
    client = Client()
    vd = Discovery(client)
    vd.discovery(sys.argv[1])
Exemplo n.º 45
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)
Exemplo n.º 46
0
class VSphere(object):
    """
    Class represents a vSphere client.

    Example usage:
        my_client = sut.VSphere('16.xx.xx.xx', 'user1', 'passwd1')
        my_vm = my_client.get_vm('user1_vm1')
        my_client.power_on_vm(my_vm)
        my_client.end_session()
    """
    def __init__(self, vsphere_server, vsphere_username, vsphere_password):
        self.server = vsphere_server
        self.username = vsphere_username
        self.password = vsphere_password
        try:
            log._info("Attempting to connect to vCenter server: %s" %
                      (self.server))
            self.client = Client(self.server, self.username, self.password)
            log._info("CONNECTED to vCenter server: %s" % (self.server))
        except VimFault as e:
            log._warn("Failed to connect to vCenter: %s" % (e.fault_name))
            return False

    def end_session(self):
        """
        Terminates session with vSphere client
        """
        self.client.logout()

    def get_vm(self, vm_name):
        try:
            vm = VirtualMachine.get(self.client, name=vm_name)
        except ObjectNotFoundError:
            log._warn("Error finding VM '%s', does not exist within client" %
                      (vm_name))
            return False
        return vm

    def power_on_vm(self, vm_name):
        """
        Powers on a VM defined in the Client

        Params:
            - vm_name:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        vm = self.get_vm(vm_name)
        if vm.runtime.powerState == "poweredOn":
            log._warn("ERROR: %s is already powered on." % vm.name)
        else:
            try:
                log._info("Powering on %s" % vm.name)
                task = vm.PowerOnVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to power on %s %s" % (vm.name, e))

    def power_off_vm(self, vm_name):
        """
        Powers off a VM defined in the Client

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        vm = self.get_vm(vm_name)
        if vm.runtime.powerState == "poweredOff":
            log._warn("ERROR: %s is already powered off." % vm.name)
        else:
            try:
                log._info("Powering off %s" % vm.name)
                task = vm.PowerOffVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to power off %s %s" % (vm.name, e))

    def suspend_vm(self, vm):
        """
        Powers off a VM defined in the Client

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        if vm.runtime.powerState in ["poweredOff", "suspended"]:
            log._warn(
                "ERROR: %s is powered off or suspended. Cannot suspend." %
                vm.name)
        else:
            try:
                log._info("Suspending %s" % vm.name)
                task = vm.SuspendVM_Task()
            except VimFault as e:
                log._warn("ERROR: Failed to suspend %s %s" % (vm.name, e))

    def reset_vm(self, vm):
        """
        Resets the virtual machine

        Params:
            - vm:  (str) The name of the virtual machine. (Ex. 'cosmos-jvm')
        """
        try:
            log._info("Restarting %s" % vm.name)
            task = vm.RestartVM_Task()
        except VimFault as e:
            log._warn("ERROR: Failed to restart %s %s" % (vm.name, e))

    def destroy_vm(self, vm_name):
        """
        Destroys VM*, deleting its contents and removing it from parent folder
        Params:
            - vm:  (str) The name of the virtual machine to be deleted.


        *Assumes proper permissions (VirtualMachine.Inventory.Delete)
        """
        vm = VirtualMachine.get(self.client, name=vm_name)

        try:
            log._info("Destroying %s" % vm.name)
            task = vm.Destroy_Task()
        except VimFault as e:
            log._warn("ERROR: Failed to destroy %s %s" % (vm.name, e))

    def clone_vm(self,
                 source_vm_name,
                 dest_vm_name,
                 power_on=False,
                 is_template=False):
        """
        Creates a clone of virtual machine 'vm'.  If the vm is a template,
        this method corresponds to deploying from a template

        Params:
            - (str)source_vm:     Name of Virtual machine (or template) to clone
            - (str)dest_vm_name:  Name of the new clone
        Optional:
            - power_on:     Option to power on the cloned vm after creation
            - is_template:  Option to mark cloned vm as a template


        * Assumes proper permissions.  The privilege required on the source
        virtual machine depends on the source and destination types:

        - source is virtual machine, destination is virtual machine - VirtualMachine.Provisioning.Clone
        - source is virtual machine, destination is template - VirtualMachine.Provisioning.CreateTemplateFromVM
        - source is template, destination is virtual machine - VirtualMachine.Provisioning.DeployTemplate
        - source is template, destination is template - VirtualMachine.Provisioning.CloneTemplate
        """
        # host_system = HostSystem.get(client, name=vm_host)

        # check to see if dest_vm already exists
        try:
            vm = VirtualMachine.get(self.client, name=dest_vm_name)
            if vm.name == dest_vm_name:
                log._warn("ERROR: Destination VM '%s' already exists." %
                          dest_vm_name)
                return False
        except ObjectNotFoundError:
            pass  # we want the object to not be found :)

        # also, check to see if the source vm exists
        try:
            source_vm = VirtualMachine.get(self.client, name=source_vm_name)
        except ObjectNotFoundError:
            log._warn("ERROR: No VM with name \"%s\" to clone" %
                      source_vm_name)
            return False

        vm_clone_spec = self.client.create("VirtualMachineCloneSpec")
        vm_reloc_spec = self.client.create("VirtualMachineRelocateSpec")
        vm_reloc_spec.datastore = source_vm.datastore  # [0]
        vm_reloc_spec.pool = source_vm.resourcePool
        vm_reloc_spec.host = None
        # vm_reloc_spec.disk = None #[]
        vm_reloc_spec.transform = None
        vm_clone_spec.powerOn = power_on
        vm_clone_spec.template = is_template
        vm_clone_spec.location = vm_reloc_spec
        vm_clone_spec.snapshot = None
        # Datacenter folder
        datacenter_folder = source_vm.parent.parent.vmFolder

        try:
            log._info("Attempting to clone %s" % source_vm.name)
            task = source_vm.CloneVM_Task(folder=datacenter_folder,
                                          name=dest_vm_name,
                                          spec=vm_clone_spec)
        except VimFault as e:
            log._warn("ERROR: Failed to clone '%s'" % e)
            return False
        while task.info.state in ["queued", "running"]:
            log._info("Waiting 5 more seconds for VM creation")
            time.sleep(5)
            task.update()

        if task.info.state == "success":
            elapsed_time = task.info.completeTime - task.info.startTime
            log._info(
                "Successfully cloned VM %s from %s. Server took %s seconds." %
                (dest_vm_name, source_vm_name, elapsed_time.seconds))
        elif task.info.state == "error":
            log._warn("ERROR: The task for cloning the VM has finished with"
                      " an error. If an error was reported it will follow.")
            try:
                log._warn("ERROR: %s" % task.info.error.localizedMessage)
            except AttributeError:
                log._warn("ERROR: There is no error message available.")
        else:
            log._warn("UNKNOWN: The task reports an unknown state %s" %
                      task.info.state)

    def deploy_from_ovf(self, ovf_path, vm_name):
        """
        Deploys a VM from an .ovf file
        """
        pass
        # def get_descriptor(ovf_path):
        # """
        # Opens .ovf file and returns descriptor
        # """
        # fh = open(ovf_path, "r")
        # ovf_descriptor = fh.read()
        # fh.close()
        # return ovf_descriptor

        # '''
        # https://groups.google.com/forum/#!topic/pysphere/NkTOy_GSaKw

        # def parse_descriptor(ovf_descriptor):
        # ovf_manager = s._do_service_content.OvfManager
        # request = VI.ParseDescriptorRequestMsg()
        # _this =request.new__this(ovf_manager)
        # _this.set_attribute_type(ovf_manager.get_attribute_type())
        # request.set_element__this(_this)
        # request.set_element_ovfDescriptor(ovf_descriptor)
        # pdp = request.new_pdp()
        # pdp.set_element_locale("")
        # pdp.set_element_deploymentOption("")
        # request.set_element_pdp(pdp)
        # return s._proxy.ParseDescriptor(request)._returnval
        # '''

        # def deploy(args):
        # """
        # """
        # ovfdesc = get_descriptor(ovf_path)

        # ovfmgr = self.client.sc.ovfManager

        # descriptor_info =  parse_descriptor(o)

        # descriptor_info = ovfmgr.ParseDescriptor(ovfdesc)
        # ovfimportresult = ovfmgr.CreateImportSpec(ovfDescriptor=ovfdesc, resourcePool=resourcepool, datastore=dstore, cisp=ocisp)

        # httpNfcLease = resourcepool.ImportVApp(spec=ovfimportresult.importSpec, folder=dl.vmFolder)

    def create_snapshot(self, vm_name, snapshot_name):
        """
        Creates a snapshot of 'vm' with name of 'snapshot_name'

        Both arguments are type 'str'
        """
        try:
            vm = VirtualMachine.get(self.client, vm_name)
        except ObjectNotFoundError:
            log._warn("ERROR: No VM with name \"%s\" to clone" %
                      source_vm_name)
            return False
        try:
            log._info("Creating snapshot for VM: %s" % vm.name)
            # task = vm.CreateSnapshot_Task(name=snapshot_name, memory=False, quiesce=False)
            task = vm.CreateSnapshot_Task(name=snapshot_name,
                                          memory=True,
                                          quiesce=True)
        except VimFault as e:
            log._warn("Failed to create snapshot %s: " % e)

        while task.info.state in ["queued", "running"]:
            log.info("Waiting 5 more seconds for VM snapshot to complete")
            time.sleep(5)
            task.update()

        if task.info.state == "success":
            elapsed_time = task.info.completeTime - task.info.startTime
            log._info(
                "Successfully create snapshot for VM %s. Processing took %s seconds."
                % (vm_name, elapsed_time.seconds))
        elif task.info.state == "error":
            log._warn(
                "ERROR: The task for creating the VM snapshot has finished with an error. If an error was reported it will follow."
            )
            try:
                log._warn("ERROR: %s" % task.info.error.localizedMessage)
            except AttributeError:
                log._warn("ERROR: There is no error message available.")
        else:
            log._warn("UNKNOWN: The task reports an unknown state %s" %
                      task.info.state)