Fix the VM uuid in the case of linked clone
546585
def _patch_vm_uuid(self):
        
        if os.path.exists(self._linked_vbox_file()):
            try:
                tree = ET.parse(self._linked_vbox_file())
            except ET.ParseError:
                raise VirtualBoxError("Cannot modify VirtualBox linked nodes file. "
                                      "File {} is corrupted.".format(self._linked_vbox_file()))

            machine = tree.getroot().find("{http://www.virtualbox.org/}Machine")
            if machine is not None and machine.get("uuid") != "{" + self.id + "}":

                for image in tree.getroot().findall("{http://www.virtualbox.org/}Image"):
                    currentSnapshot = machine.get("currentSnapshot")
                    if currentSnapshot:
                        newSnapshot = re.sub("\{.*\}", "{" + str(uuid.uuid4()) + "}", currentSnapshot)
                    shutil.move(os.path.join(self.working_dir, self._vmname, "Snapshots", currentSnapshot) + ".vdi",
                                os.path.join(self.working_dir, self._vmname, "Snapshots", newSnapshot) + ".vdi")
                    image.set("uuid", newSnapshot)

                machine.set("uuid", "{" + self.id + "}")
                tree.write(self._linked_vbox_file())
761154
def thin_clone(self, name, io_limit_policy=None, description=None):
        
        if self.is_member_snap():
            raise UnityCGMemberActionNotSupportError()

        if self.lun and not self.lun.is_thin_enabled:
            raise UnityThinCloneNotAllowedError()

        return TCHelper.thin_clone(self._cli, self, name, io_limit_policy,
                                   description)
275130
def shutdown(self, uuid):
        
        args = {
            'uuid': uuid,
        }
        self._domain_action_chk.check(args)

        self._client.sync('kvm.shutdown', args)
168975
private synchronized VirtualMachine getAttachedVirtualMachine() throws VirtualMachineException {
        if (PID == null) {
            // Java Attach requires a PID.
            return null;
        }

        if (vm == null) {
            vm = createVirtualMachine();
        }
        return vm.isAttached() ? vm : null;
    }
265159
function cloneRelayHandleSourceField(
  handleField: NormalizationLinkedHandle,
  selections: $ReadOnlyArray<NormalizationSelection>,
  variables: Variables,
): NormalizationLinkedField {
  const sourceField = selections.find(
    source =>
      source.kind === LINKED_FIELD &&
      source.name === handleField.name &&
      source.alias === handleField.alias &&
      areEqual(source.args, handleField.args),
  );
  invariant(
    sourceField && sourceField.kind === LINKED_FIELD,
    'cloneRelayHandleSourceField: Expected a corresponding source field for ' +
      'handle `%s`.',
    handleField.handle,
  );
  const handleKey = getHandleStorageKey(handleField, variables);
  const clonedField = {
    ...sourceField,
    args: null,
    name: handleKey,
    storageKey: handleKey,
  };
  return clonedField;
}
439777
def get_vm_obj(self):
        
        uuid = VcenterInterfaces.get_vcenter_vm_uuid_by_name(self.host, self.user, self.password, self.name)
        # connect to vc

        # Getting VM data
        vm_obj = self.vcenter_conn.content.searchIndex.FindByUuid(None, uuid, True, True)
        # VM does exist
        if not vm_obj:
            print 'VM {} does not exist'.format(uuid)
            sys.exit(1)

        # VM must be powered off to export
        if not vm_obj.runtime.powerState == \
                vim.VirtualMachine.PowerState.poweredOff:
            print 'VM {} must be powered off'.format(vm_obj.name)
            sys.exit(1)

        return vm_obj
1306019
def unregister_vm(vm_ref):
    '''
    
    '''
    vm_name = get_managed_object_name(vm_ref)
    log.trace('Destroying vm \'%s\'', vm_name)
    try:
        vm_ref.UnregisterVM()
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(
            'Not enough permissions. Required privilege: '
            '{}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        raise salt.exceptions.VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        raise salt.exceptions.VMwareRuntimeError(exc.msg)
993091
public ManagedEntity findByUuid(Datacenter datacenter, String uuid, boolean vmOnly) throws RuntimeFault, RemoteException {
        return findByUuid(datacenter, uuid, vmOnly, null);
    }
852510
def get_vcenter_vm_uuid_by_name(host, user, password, vm_name):
    
    vc = VcenterInterface(host, user, password)
    vmi = VmInterface(vc, vm_name)
    return vmi.get_instance_uuid()
255431
function bind (vm, key, source) {
  var asObject = false
  var cancelCallback = null
  var readyCallback = null
  // check { source, asArray, cancelCallback } syntax
  if (isObject(source) && source.hasOwnProperty('source')) {
    asObject = source.asObject
    cancelCallback = source.cancelCallback
    readyCallback = source.readyCallback
    source = source.source
  }
  if (!isObject(source)) {
    throw new Error('VueWild: invalid Wilddog binding source.')
  }
  var ref = _getRef(source)
  vm.$wilddogRefs[key] = ref
  vm._wilddogSources[key] = source
  if (cancelCallback) {
    cancelCallback = cancelCallback.bind(vm)
  }
  // bind based on initial value type
  if (asObject) {
    bindAsObject(vm, key, source, cancelCallback)
  } else {
    bindAsArray(vm, key, source, cancelCallback)
  }
  if (readyCallback) {
    source.once('value', readyCallback.bind(vm))
  }
}
547066
def resume(self, uuid):
        
        args = {
            'uuid': uuid,
        }
        self._domain_action_chk.check(args)

        self._client.sync('kvm.resume', args)
1127958
def vcpu_pin(vm_, vcpu, cpus):
    '''
    
    '''
    with _get_xapi_session() as xapi:

        vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
        if vm_uuid is False:
            return False

        # from xm's main
        def cpu_make_map(cpulist):
            cpus = []
            for c in cpulist.split(','):
                if c == '':
                    continue
                if '-' in c:
                    (x, y) = c.split('-')
                    for i in range(int(x), int(y) + 1):
                        cpus.append(int(i))
                else:
                    # remove this element from the list
                    if c[0] == '^':
                        cpus = [x for x in cpus if x != int(c[1:])]
                    else:
                        cpus.append(int(c))
            cpus.sort()
            return ','.join(map(str, cpus))

        if cpus == 'all':
            cpumap = cpu_make_map('0-63')
        else:
            cpumap = cpu_make_map('{0}'.format(cpus))

        try:
            xapi.VM.add_to_VCPUs_params_live(vm_uuid,
                                             'cpumap{0}'.format(vcpu), cpumap)
            return True
        # VM.add_to_VCPUs_params_live() implementation in xend 4.1+ has
        # a bug which makes the client call fail.
        # That code is accurate for all others XenAPI implementations, but
        # for that particular one, fallback to xm / xl instead.
        except Exception:
            return __salt__['cmd.run'](
                    '{0} vcpu-pin {1} {2} {3}'.format(_get_xtool(), vm_, vcpu, cpus),
                    python_shell=False)
1334880
def _deploy_a_clone(self, si, logger, app_name, template_name, other_params, vcenter_data_model, reservation_id,
                        cancellation_context,
                        snapshot=''):
        
        # generate unique name
        vm_name = self.name_generator(app_name, reservation_id)

        VCenterDetailsFactory.set_deplyment_vcenter_params(
            vcenter_resource_model=vcenter_data_model, deploy_params=other_params)

        template_name = VMLocation.combine([other_params.default_datacenter,
                                            template_name])

        params = self.pv_service.CloneVmParameters(si=si,
                                                   template_name=template_name,
                                                   vm_name=vm_name,
                                                   vm_folder=other_params.vm_location,
                                                   datastore_name=other_params.vm_storage,
                                                   cluster_name=other_params.vm_cluster,
                                                   resource_pool=other_params.vm_resource_pool,
                                                   power_on=False,
                                                   snapshot=snapshot)

        if cancellation_context.is_cancelled:
            raise Exception("Action 'Clone VM' was cancelled.")

        clone_vm_result = self.pv_service.clone_vm(clone_params=params, logger=logger,
                                                   cancellation_context=cancellation_context)
        if clone_vm_result.error:
            raise Exception(clone_vm_result.error)

        # remove a new created vm due to cancellation
        if cancellation_context.is_cancelled:
            self.pv_service.destroy_vm(vm=clone_vm_result.vm, logger=logger)
            raise Exception("Action 'Clone VM' was cancelled.")

        vm_details_data = self._safely_get_vm_details(clone_vm_result.vm, vm_name, vcenter_data_model, other_params,
                                                      logger)

        return DeployAppResult(vmName=vm_name,
                               vmUuid=clone_vm_result.vm.summary.config.uuid,
                               vmDetailsData=vm_details_data,
                               deployedAppAdditionalData={'ip_regex': other_params.ip_regex,
                                                          'refresh_ip_timeout': other_params.refresh_ip_timeout,
                                                          'auto_power_off': convert_to_bool(other_params.auto_power_off),
                                                          'auto_delete': convert_to_bool(other_params.auto_delete)})
448272
function reprovisionInstance(uuid, image_uuid, callback) {
    assert.string(uuid, 'uuid');
    assert.string(image_uuid, 'image_uuid');

    var opts = {};
    opts.image_uuid = image_uuid;

    return (this.put(sprintf('/instances/%s/upgrade', uuid), opts, callback));
}
460258
function clone(url, target, ref, key, log, fn) {
  var urlObj = parseurl(url);
  urlObj.auth = key + ':x-oauth-basic';
  var authurl = formaturl(urlObj) + '.git';

  var dir = target + '/.git';

  log('creating dir ' + dir);
  mkdirp(dir, function(err) {
    if (err) return fn(err);

    var remote = git.remote(authurl);
    var repo = git.repo(dir);
    var opts = {};
    opts.want = ref;
    log('fetching ' + url);
    repo.fetch(remote, opts, function(err) {
      if (err) return fn(err);
      log('checking out ' + ref);
      repo.resolveHashish(ref, function(err, hash) {
        if (err) return fn(err);
        log('updating head to ' + hash);
        repo.updateHead(hash, function(err) {
          if (err) return fn(err);
          exec('git checkout ' + hash, {cwd: target}, function(err, stdout, stderr) {
            fn(err);
          });
        });
      });
    });
  });
}
378978
def reset(vm_):
    '''
    
    '''
    with _get_xapi_session() as xapi:
        vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
        if vm_uuid is False:
            return False
        try:
            xapi.VM.hard_reboot(vm_uuid)
            return True
        except Exception:
            return False
1205397
def vcpu=(count)
      fail(CloudError,
           "Invalid virtual CPU count #{count}") if count <= 0

      Config
        .logger
        .info "Changing the virtual CPU count to #{count}."

      payload = entity_xml
      payload.change_cpu_count(count)

      task = connection.post(payload.reconfigure_link.href,
                             payload,
                             Xml::MEDIA_TYPE[:VM])
      monitor_task(task)
      self
    end