def GetHints(hints): """ Get hints suitable for CLI Info """ paramHints = None if hints: if isinstance(hints, dict): paramHints = Vim.KeyValue.Array() for key, value in six.iteritems(hints): paramHints.append(Vim.KeyValue(key=key, value=value)) else: paramHints = hints return paramHints
def runTest(numPair=1, sameVmName=False): try: failoverPair = [] vmName = ("vm-%s" % random.randint(1, 1000)) for i in range(numPair): if not sameVmName: vmName = ("vm-%s" % random.randint(1, 1000)) Log("\nCreating VM pair #%d, vm %s\n" % (i + 1, vmName)) srcMap = getObjMapping(vmName, "Source") global dstMap dstMap = getObjMapping(vmName, "Target") pair = Vim.Datastore.VVolContainerFailoverPair() pair.srcContainer = vvolId pair.tgtContainer = vvolId pair.vvolMapping = [] for key in srcMap.keys(): oneMapping = Vim.KeyValue() oneMapping.key = srcMap[key] oneMapping.value = dstMap[key] pair.vvolMapping.append(oneMapping) failoverPair.append(pair) Log("\nGenerating failoverPair = %s\n" % failoverPair) Log("\nCalling updateVVolVirtualMachineFiles\n") task = InvokeAndTrackWithTask(vvolDs.UpdateVVolVirtualMachineFiles, failoverPair) checkTaskResult(task) except Exception as e: cleanup() raise e
def AddArgument(key, value, args): arg = Vim.KeyValue() arg.key = key arg.value = str(value) args.append(arg)
def runTest(): try: vmName = ("vm-%s" % random.randint(1, 1000)) Log("\nCreating VM pair -- vm %s\n" % (vmName)) srcMaps, srcVms = getObjMapping(vmName, "Source") dstMaps, dstVms = getObjMapping(vmName, "Target", True) # src mapping of vmName.vmx is the true source VM # tgt mapping of vmName.vmx is the faked failover VM # We need to copy files into the fake VM for name in srcVms: if (name + '.vmx' in srcMaps[0]): srcPath = os.path.join('/vmfs/volumes', vvolDsName, srcMaps[0][name + '.vmx']) tgtPath = os.path.join('/vmfs/volumes', vvolDsName, dstMaps[0][name + '.vmx']) else: srcPath = os.path.join('/vmfs/volumes', vvolDsName, srcMaps[1][name + '.vmx']) tgtPath = os.path.join('/vmfs/volumes', vvolDsName, dstMaps[1][name + '.vmx']) for fn in glob.glob(os.path.join(srcPath, '*.*')): shutil.copy(fn, tgtPath) for fn in glob.glob(os.path.join(srcPath, '.rfc*')): shutil.copy(fn, tgtPath) Log('VM {0} duplicated to failover target: {1}'.format( name, tgtPath)) # Make a copy to compare after the failover Log('Removing previous backup...') shutil.rmtree(os.path.join('/vmfs/volumes/datastore1', vvolDsName), ignore_errors=True) Log('Backing up datastore...') shutil.copytree(os.path.join('/vmfs/volumes', vvolDsName), os.path.join('/vmfs/volumes/datastore1', vvolDsName), ignore=shutil.ignore_patterns('*.vmsn', 'rfc4122.*')) for idx in xrange(len(srcMaps)): pair = Vim.Datastore.VVolContainerFailoverPair() pair.srcContainer = vvolId pair.tgtContainer = vvolId pair.vvolMapping = [] for key in srcMaps[idx].keys(): oneMapping = Vim.KeyValue() oneMapping.key = srcMaps[idx][key] oneMapping.value = dstMaps[idx][key] pair.vvolMapping.append(oneMapping) Log("\nGenerating failoverPair = %s\n" % pair) Log("\nCalling updateVVolVirtualMachineFiles\n") task = InvokeAndTrackWithTask(vvolDs.UpdateVVolVirtualMachineFiles, [pair]) checkTaskResult(task, dstMaps[idx]) except Exception: cleanup() raise
def Deploy(self, powerOn=True): context = ssl._create_unverified_context() if os.path.exists(self.ovfUrl): with open(self.ovfUrl) as f: data = f.read() else: response = urllib.request.urlopen(self.ovfUrl, context=context) data = response.read() self.params.propertyMapping = [ Vim.KeyValue(key=key, value=value) for key, value in self.properties.iteritems() ] resourcePool = self.hostd.GetHostComputeResources().GetResourcePool() spec = self.hostd.GetOvfManager().CreateImportSpec( ovfDescriptor=data, resourcePool=resourcePool, datastore=self.datastore, cisp=self.params) importSpec = spec.GetImportSpec() baseDir = os.path.dirname(self.ovfUrl) vm = None with GetLease(resourcePool, importSpec) as lease: uploadUrlMap = {} for deviceUrl in lease.info.deviceUrl: uploadUrlMap[deviceUrl.importKey] = (deviceUrl.key, deviceUrl.url) totalSize = 1 for fileItem in spec.fileItem: totalSize += fileItem.size counter = 0 chunk = 32 * 1024 * 1024 # 32MB progressMark = max(totalSize // 10 // chunk, 1) for fileItem in spec.fileItem: key, url = uploadUrlMap[fileItem.deviceId] srcDiskPath = os.path.join(baseDir, fileItem.path) parsedUrl = urllib.parse.urlparse(url) if parsedUrl.scheme == 'https': HttpConnection = lambda host: http_client.HTTPSConnection( host, context=context) else: HttpConnection = http_client.HTTPConnection host = parsedUrl.netloc if host == '*': host = self.hostd.Hostname() logger.info('Connecting to {}'.format(host)) httpConn = HttpConnection(host) source = urllib.request.urlopen(srcDiskPath, context=context) with contextlib.closing(source) as srcDisk, \ contextlib.closing(httpConn) as httpConn: diskSize = int(srcDisk.headers.get('Content-Length')) requestType = 'PUT' if fileItem.create else 'POST' logger.info('{} {} => {}'.format(requestType, srcDiskPath, parsedUrl.path)) httpConn.putrequest(requestType, parsedUrl.path) httpConn.putheader('Content-Length', diskSize) httpConn.endheaders() while True: start = time.time() data = srcDisk.read(chunk) end = time.time() logger.debug( 'Read {} bytes in {} (speed = {} MB/s)'.format( chunk, end - start, chunk / 1024 / 1024 / (end - start))) if len(data) == 0: break if lease.GetState() != Vim.HttpNfcLease.State.ready: raise RuntimeError('Lease expired') start = time.time() httpConn.send(data) end = time.time() logger.debug( 'Wrote {} bytes in {} (speed = {} MB/s)'.format( chunk, end - start, chunk / 1024 / 1024 / (end - start))) counter += 1 if counter % progressMark == 0: progress = int( min(99, counter * chunk * 100 // totalSize)) logger.info('Progress at {}%'.format(progress)) lease.Progress(progress) if lease.state == Vim.HttpNfcLease.State.error: raise lease.error elif lease.state not in [ Vim.HttpNfcLease.State.ready, Vim.HttpNfcLease.State.done ]: raise RuntimeError( 'Upload aborted, lease state {}'.format( lease.state)) logger.debug('HTTP response from server {}'.format( httpConn.getresponse().read())) vm = lease.info.entity lease.Progress(100) lease.Complete() self._InjectOvfEnv(vm) if powerOn: task = vm.PowerOn() self.hostd.WaitForTask(task) return vm