Python pyVmomi.vim.Datastore() Examples
The following are 30
code examples of pyVmomi.vim.Datastore().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyVmomi.vim
, or try the search function
.
Example #1
Source File: list_dc_datastore_info.py From pyvmomi-community-samples with Apache License 2.0 | 7 votes |
def main(): args = get_args() # connect to vc si = SmartConnect( host=args.host, user=args.user, pwd=args.password, port=args.port) # disconnect vc atexit.register(Disconnect, si) content = si.RetrieveContent() # Get list of ds mo ds_obj_list = get_obj(content, [vim.Datastore], args.name) for ds in ds_obj_list: print_datastore_info(ds) # start
Example #2
Source File: datastore_file.py From vsphere-automation-sdk-python with MIT License | 7 votes |
def __init__(self, parent=None, path=None, ftype=None): self._file_manager = None if isinstance(parent, vim.Datastore): # Iteratively look for the Datacenter parent self._datacenter_mo = get_datacenter_for_datastore(parent) self._datastore_mo = parent self._ftype = FOLDER if path: self._path = path else: self._path = '' elif isinstance(parent, File): self._datacenter_mo = parent._datacenter_mo self._datastore_mo = parent.datastore_mo self._ftype = ftype if parent._path == '': self._path = path else: self._path = '{}/{}'.format(parent._path, path) else: raise Exception( "Invalid type '{}' for datastore_file".format(type(parent)))
Example #3
Source File: get_portgroup.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def get_obj(content, vimtype, name): """ Retrieves the managed object for the name and type specified Sample Usage: get_obj(content, [vim.Datastore], "Datastore Name") """ obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if c.name == name: # print(Item: + c.name) # for debugging obj = c break if not obj: raise RuntimeError("Managed Object " + name + " not found.") return obj
Example #4
Source File: disk.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def get_obj(content, vimtype, name): """ Retrieves the managed object for the name and type specified Sample Usage: get_obj(content, [vim.Datastore], "Datastore Name") """ obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if c.name == name: obj = c break if not obj: raise RuntimeError("Managed Object " + name + " not found.") return obj
Example #5
Source File: nsxt_vcenter_moids.py From ansible-module-chaperone with Apache License 2.0 | 6 votes |
def find_object_by_name(module,content, object_name): try: if(object_name == module.params['datacenter']): vmware_objects = get_all_objs(module,content,[vim.Datacenter]) elif (object_name == module.params['cluster']): vmware_objects = get_all_objs(module,content,[vim.ComputeResource]) elif (object_name == module.params['datastore']): vmware_objects = get_all_objs(module,content,[vim.Datastore]) elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ): vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network]) for object in vmware_objects: if object.name == object_name: logger.info('object: %s',object.name) return object return None except Exception as err: module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err)))
Example #6
Source File: vsphere_utils.py From ADLES with Apache License 2.0 | 6 votes |
def make_vsphere(filename=None): """ Creates a vSphere object using either a JSON file or by prompting the user. :param str filename: Name of JSON file with connection info :return: vSphere object :rtype: :class:`Vsphere` """ from adles.vsphere.vsphere_class import Vsphere if filename is not None: info = read_json(filename) if info is None: raise VsphereException("Failed to create vSphere object") return Vsphere(username=info.get("user"), password=info.get("pass"), hostname=info.get("host"), port=info.get("port", 443), datacenter=info.get("datacenter"), datastore=info.get("datastore")) else: logging.info("Enter information to connect to the vSphere environment") datacenter = input("Datacenter : ") datastore = input("Datastore : ") return Vsphere(datacenter=datacenter, datastore=datastore)
Example #7
Source File: virtualcenter.py From wrapanapi with MIT License | 6 votes |
def get_datastore(self, name): """Fetch the Datastore object(for a datastore) or StoragePod object (for a datastore cluster) from a provided name Args: name: The name of the datastore or datastore cluster Returns: A object of vim.Datastore or vim.StoragePod """ if name in self.list_datastore() and name not in self.list_datastore_cluster(): datastore = self.get_obj(vimtype=vim.Datastore, name=name) elif name in self.list_datastore_cluster(): datastore = self.get_obj(vimtype=vim.StoragePod, name=name) else: raise ValueError("{ds} was not found as a datastore on {p}".format( ds=name, p=self.hostname)) return datastore
Example #8
Source File: vsphere.py From ocs-ci with MIT License | 6 votes |
def find_datastore_by_name(self, datastore_name, datacenter_name): """ Fetches the Datastore Args: datastore_name (str): Name of the Datastore datacenter_name (str): Name of the Datacenter Returns: vim.Datastore: Datastore instance """ dc = self.find_datacenter_by_name(datacenter_name) folder = dc.datastoreFolder return self.find_object_by_name( self.get_content, datastore_name, [vim.Datastore], folder=folder )
Example #9
Source File: virtualcenter.py From wrapanapi with MIT License | 6 votes |
def pick_datastore(self, allowed_datastores): """ Pick a datastore based on free space. Args: allowed_datastores: A list of allowed datastore names that can be deployed on Returns: pyVmomi.vim.Datastore: The managed object of the datastore. """ possible_datastores = [ ds for ds in self.system.get_obj_list(vim.Datastore) if ds.name in allowed_datastores and ds.summary.accessible and ds.summary.multipleHostAccess and ds.overallStatus != "red"] if not possible_datastores: raise DatastoreNotFoundError(item_type='datastores') possible_datastores.sort( key=lambda ds: float(ds.summary.freeSpace) / float(ds.summary.capacity), reverse=True) return possible_datastores[0]
Example #10
Source File: vsphere.py From ocs-ci with MIT License | 6 votes |
def get_datastore_type_by_name(self, datastore_name, datacenter_name): """ Gets the Datastore Type Args: datastore_name (str): Name of the Datastore datacenter_name (str): Name of the Datacenter Returns: str: Datastore type. Either VMFS or vsan """ datastore = self.find_datastore_by_name( datastore_name, datacenter_name ) return self.get_datastore_type(datastore)
Example #11
Source File: relocate_vm.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def get_args(): """ Adds additional args for the vMotion """ parser = cli.build_arg_parser() parser.add_argument('-dd', '--datastore-dest', required=False, help=' Datastore of the destination') parser.add_argument('-t', '--target-esx-host', required=False, help="name of the destination esx host") parser.add_argument('-v', '--vm-name', required=True, help="name of the vm") my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #12
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def datastore_labels(self): def _collect(node, level=1, dc=None, storagePod=""): inventory = {} if isinstance(node, vim.Folder) and not isinstance(node, vim.StoragePod): logging.debug("[Folder ] {level} {name}".format(name=node.name, level=('-' * level).ljust(7))) for child in node.childEntity: inventory.update(_collect(child, level + 1, dc)) elif isinstance(node, vim.Datacenter): logging.debug("[Datacenter] {level} {name}".format(name=node.name, level=('-' * level).ljust(7))) inventory.update(_collect(node.datastoreFolder, level + 1, node.name)) elif isinstance(node, vim.Folder) and isinstance(node, vim.StoragePod): logging.debug("[StoragePod] {level} {name}".format(name=node.name, level=('-' * level).ljust(7))) for child in node.childEntity: inventory.update(_collect(child, level + 1, dc, node.name)) elif isinstance(node, vim.Datastore): logging.debug("[Datastore ] {level} {name}".format(name=node.name, level=('-' * level).ljust(7))) inventory[node.name] = [node.name, dc, storagePod] else: logging.debug("[? ] {level} {node}".format(node=node, level=('-' * level).ljust(7))) return inventory labels = {} dcs = yield self.datacenter_inventory for dc in dcs: result = yield threads.deferToThread(lambda: _collect(dc)) labels.update(result) return labels
Example #13
Source File: fcd_list_vdisk_snapshots.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def get_args(): """ Adds additional args for listing all snapshots of a fcd -d datastore -v vdisk """ parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name where disk is located') parser.add_argument('-v', '--vdisk', required=True, action='store', help='First Class Disk name to delete snapshot for') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #14
Source File: test_cache.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_infrastructure_cache(realtime_instance): cache = InfrastructureCache(float('inf')) config = VSphereConfig(realtime_instance, logger) mock_api = VSphereRestAPI(config, log=logger) mors = {MagicMock(spec=k, _moId="foo"): object() for k in ALL_RESOURCES_WITH_METRICS * 2} with cache.update(): for k, v in iteritems(mors): cache.set_mor_props(k, v) cache.set_all_tags(mock_api.get_resource_tags_for_mors(mors)) for r in ALL_RESOURCES_WITH_METRICS: assert len(list(cache.get_mors(r))) == 2 for k, v in iteritems(mors): assert cache.get_mor_props(k) == v vm_mor = vim.VirtualMachine(moId='VM4-4-1') vm2_mor = vim.VirtualMachine(moId='i-dont-have-tags') datastore = vim.Datastore(moId='NFS-Share-1') assert cache.get_mor_tags(vm_mor) == ['my_cat_name_1:my_tag_name_1', 'my_cat_name_2:my_tag_name_2'] assert cache.get_mor_tags(datastore) == ['my_cat_name_2:my_tag_name_2'] assert cache.get_mor_tags(vm2_mor) == []
Example #15
Source File: fcd_delete_vdisk_snapshot.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): """ Adds additional args for deleting a snapshot of a fcd -d datastore -v vdisk -n snapshot -y yes """ parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name where disk is located') parser.add_argument('-v', '--vdisk', required=False, action='store', help='First Class Disk name to delete snapshot for') # because -s is reserved for 'service', we use -n for snapshot name parser.add_argument('-n', '--snapshot', required=True, action='store', help='Snapshot name to be deleted') parser.add_argument('-y', '--yes', action='store_true', help='Confirm disk deletion.') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #16
Source File: list_dc_datastore_info.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): parser = cli.build_arg_parser() parser.add_argument('-n', '--name', required=False, help="Name of the Datastore.") my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #17
Source File: fcd_list_vdisk_snapshots.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def main(): """ Simple command-line program for listing all snapshots of a fcd """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # Retrieve Datastore Object datastore = disk.get_obj(content, [vim.Datastore], args.datastore) # Retrieve FCD Object vdisk = disk.retrieve_fcd(content, datastore, args.vdisk) # Retrieve all Snapshots list_fcd_snapshots(content, vdisk) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0 # Start program
Example #18
Source File: fcd_attach_vdisk_to_vm.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): """ Adds additional args for attaching a fcd to a vm -d datastore -v vdisk -n vm_name -i uuid """ parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name where disk is located') parser.add_argument('-v', '--vdisk', required=True, action='store', help='First Class Disk name to be attached') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-n', '--vm_name', action='store', help='Virtual Machine name where disk is attached') group.add_argument('-i', '--uuid', action='store', help='Virtual Machine UUID where disk is attached') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #19
Source File: fcd_create_vdisk_snapshot.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): """ Adds additional args for creating a snapshot of a fcd -d datastore -v vdisk -n snapshot """ parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name where disk is located') parser.add_argument('-v', '--vdisk', required=True, action='store', help='First Class Disk name to create snapshot for') # because -s is reserved for 'service', we use -n for snapshot name parser.add_argument('-n', '--snapshot', required=True, action='store', help='New snapshot name') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #20
Source File: fcd_delete_vdisk.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): """ Adds additional args for deleting a fcd -d datastore -v vdisk -y yes """ parser = cli.build_arg_parser() parser.add_argument('-d', '--datastore', required=True, action='store', help='Datastore name where disk is located') parser.add_argument('-v', '--vdisk', required=True, action='store', help='First Class Disk name to be deleted') parser.add_argument('-y', '--yes', action='store_true', help='Confirm disk deletion.') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #21
Source File: get_vcenter_id.py From ansible-module-chaperone with Apache License 2.0 | 5 votes |
def core(module): vim_type = module.params['vcenter_vim_type'] vcenter_object_name = module.params['vcenter_object_name'] vim_rec_type = { 'cluster': vim.ClusterComputeResource, 'datacenter': vim.Datacenter, 'datastore': vim.Datastore, 'vds': vim.DistributedVirtualSwitch, 'dvs-port': vim.Network, 'vm': vim.VirtualMachine } try: vimtype = vim_rec_type[vim_type] except KeyError: module.fail_json(msg="Please specify valid vim type: cluster, datacenter, datastore, vds, vm") si = si_connect(module) vcenter_id = get_id(module, si, [vimtype], vcenter_object_name, False, True) return False, vcenter_id
Example #22
Source File: vsphere.py From ocs-ci with MIT License | 5 votes |
def get_all_objs(self, content, vimtype, folder=None, recurse=True): """ Generate objects of type vimtype Args: content (vim.ServiceInstanceContent): Service Instance Content vimtype (vim.type): Type of vim (e.g: For VM's, type is vim.VirtualMachine For Hosts, type is vim.HostSystem) folder (str): Folder name recurse (bool): True for recursive search Returns: dict: Dictionary of objects and corresponding name e.g:{ 'vim.Datastore:datastore-12158': 'datastore1 (1)', 'vim.Datastore:datastore-12157': 'datastore1 (2)' } """ if not folder: folder = content.rootFolder obj = {} container = content.viewManager.CreateContainerView( folder, vimtype, recurse ) for managed_object_ref in container.view: obj.update({managed_object_ref: managed_object_ref.name}) container.Destroy() return obj
Example #23
Source File: vsphere.py From ocs-ci with MIT License | 5 votes |
def get_datastore_type(self, datastore): """ Gets the Datastore Type Args: datastore (vim.Datastore): Datastore instance Returns: str: Datastore type. Either VMFS or vsan """ return datastore.summary.type
Example #24
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def collect(self): """ collects metrics """ vsphere_host = self.host metrics = self._create_metric_containers() logging.info("Start collecting metrics from {vsphere_host}".format(vsphere_host=vsphere_host)) self._labels = {} collect_only = self.collect_only tasks = [] # Collect vm / snahpshot / vmguest metrics if collect_only['vmguests'] is True or collect_only['vms'] is True or collect_only['snapshots'] is True: tasks.append(self._vmware_get_vms(metrics)) if collect_only['vms'] is True: tasks.append(self._vmware_get_vm_perf_manager_metrics(metrics)) # Collect Datastore metrics if collect_only['datastores'] is True: tasks.append(self._vmware_get_datastores(metrics,)) if collect_only['hosts'] is True: tasks.append(self._vmware_get_hosts(metrics)) tasks.append(self._vmware_get_host_perf_manager_metrics(metrics)) yield parallelize(*tasks) yield self._vmware_disconnect() logging.info("Finished collecting metrics from {vsphere_host}".format(vsphere_host=vsphere_host)) return list(metrics.values()) # noqa: F705
Example #25
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def tags(self): """ tags are finally stored by category: vms, hosts, and datastores and linked to object moid """ logging.info("Fetching tags") start = datetime.datetime.utcnow() attachedObjs = yield self._attachedObjectsOnTags tagNames = yield self._tagNames tags = { 'vms': {}, 'hosts': {}, 'datastores': {}, 'others': {}, } sections = {'VirtualMachine': 'vms', 'Datastore': 'datastores', 'HostSystem': 'hosts'} for attachedObj in attachedObjs: tagName = tagNames.get(attachedObj.get('tag_id')) for obj in attachedObj.get('object_ids'): section = sections.get(obj.get('type'), 'others') if obj.get('id') not in tags[section]: tags[section][obj.get('id')] = [tagName] else: tags[section][obj.get('id')].append(tagName) fetch_time = datetime.datetime.utcnow() - start logging.info("Fetched tags ({fetch_time})".format(fetch_time=fetch_time)) return tags
Example #26
Source File: utils.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_parent_tags_recursively(mor, infrastructure_data): # type: (vim.ManagedEntity, InfrastructureData) -> List[str] """Go up the resources hierarchy from the given mor. Note that a host running a VM is not considered to be a parent of that VM. rootFolder(vim.Folder): - vm(vim.Folder): VM1-1 VM1-2 - host(vim.Folder): HOST1 HOST2 """ mor_props = infrastructure_data[mor] parent = mor_props.get('parent') if parent: tags = [] parent_props = infrastructure_data.get(parent, {}) parent_name = to_string(parent_props.get('name', 'unknown')) if isinstance(parent, vim.HostSystem): tags.append('vsphere_host:{}'.format(parent_name)) elif isinstance(parent, vim.Folder): tags.append('vsphere_folder:{}'.format(parent_name)) elif isinstance(parent, vim.ComputeResource): if isinstance(parent, vim.ClusterComputeResource): tags.append('vsphere_cluster:{}'.format(parent_name)) tags.append('vsphere_compute:{}'.format(parent_name)) elif isinstance(parent, vim.Datacenter): tags.append('vsphere_datacenter:{}'.format(parent_name)) elif isinstance(parent, vim.Datastore): tags.append('vsphere_datastore:{}'.format(parent_name)) parent_tags = get_parent_tags_recursively(parent, infrastructure_data) parent_tags.extend(tags) return parent_tags return []
Example #27
Source File: test_vsphere.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def migrated_event(): now = datetime.utcnow() vm = MockedMOR(spec='VirtualMachine', name='vm1') vm_arg = vim.event.VmEventArgument(vm=vm) host = MockedMOR(spec='HostSystem') host_arg = vim.event.HostEventArgument(host=host, name='host1') host_dest = MockedMOR(spec='HostSystem') host_dest_arg = vim.event.HostEventArgument(host=host_dest, name='host2') dc = MockedMOR(spec='Datacenter') dc_arg = vim.event.DatacenterEventArgument(datacenter=dc, name='dc1') dc_dest = MockedMOR(spec='Datacenter') dc_dest_arg = vim.event.DatacenterEventArgument(datacenter=dc_dest, name='dc2') ds = MockedMOR(spec='Datastore') ds_arg = vim.event.DatastoreEventArgument(datastore=ds, name='ds1') ds_dest = MockedMOR(spec='Datastore') ds_dest_arg = vim.event.DatastoreEventArgument(datastore=ds_dest, name='ds2') event = vim.event.VmBeingHotMigratedEvent( vm=vm_arg, userName='John', fullFormattedMessage='Some error', createdTime=now, host=host_arg, destHost=host_dest_arg, datacenter=dc_arg, destDatacenter=dc_dest_arg, ds=ds_arg, destDatastore=ds_dest_arg, ) return event
Example #28
Source File: test_api_rest.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get_resource_tags(realtime_instance): config = VSphereConfig(realtime_instance, logger) mock_api = VSphereRestAPI(config, log=logger) mock_mors = [MagicMock(spec=vim.VirtualMachine, _moId="foo")] resource_tags = mock_api.get_resource_tags_for_mors(mock_mors) expected_resource_tags = { vim.HostSystem: {'10.0.0.104-1': ['my_cat_name_2:my_tag_name_2']}, vim.VirtualMachine: {'VM4-4-1': ['my_cat_name_1:my_tag_name_1', 'my_cat_name_2:my_tag_name_2']}, vim.Datacenter: {}, vim.Datastore: {'NFS-Share-1': ['my_cat_name_2:my_tag_name_2']}, vim.ClusterComputeResource: {}, } assert expected_resource_tags == resource_tags
Example #29
Source File: __init__.py From kcli with Apache License 2.0 | 5 votes |
def _uploadimage(self, pool, origin, directory, verbose=False, temp=False): if verbose: common.pprint("Uploading %s to %s/%s" % (origin, pool, directory)) si = self.si rootFolder = self.rootFolder datastore = find(si, rootFolder, vim.Datastore, pool) if not datastore: return {'result': 'failure', 'reason': "Pool %s not found" % pool} destination = os.path.basename(origin) if temp: destination = "temp-%s" % destination url = "https://%s:443/folder/%s/%s?dcPath=%s&dsName=%s" % (self.vcip, directory, destination, self.dc.name, pool) client_cookie = si._stub.cookie cookie_name = client_cookie.split("=", 1)[0] cookie_value = client_cookie.split("=", 1)[1].split(";", 1)[0] cookie_path = client_cookie.split("=", 1)[1].split(";", 1)[1].split(";", 1)[0].lstrip() cookie_text = " " + cookie_value + "; $" + cookie_path cookie = {cookie_name: cookie_text} headers = {'Content-Type': 'application/octet-stream'} with open(origin, "rb") as f: if hasattr(requests.packages.urllib3, 'disable_warnings'): requests.packages.urllib3.disable_warnings() r = requests.put(url, data=f, headers=headers, cookies=cookie, verify=False) if verbose: if r.status_code not in [200, 201]: print(r.status_code, r.text) else: common.pprint("Successfull upload of %s to %s" % (origin, pool))
Example #30
Source File: vmware.py From skylight with GNU General Public License v3.0 | 5 votes |
def find_datastore_by_name(self, datastore_name): """ Function to get datastore managed object by name Args: datastore_name: Name of datastore Returns: datastore managed object if found else None """ return find_datastore_by_name(self.content, datastore_name=datastore_name) # Datastore cluster