// Recover the VM appliance
//
// Errors:
//  VM_REQUIRES_SR - You attempted to run a VM on a host which doesn't have access to an SR needed by the VM. The VM has at least one VBD attached to a VDI in the SR.
512479
func (_class VMApplianceClass) Recover(sessionID SessionRef, self VMApplianceRef, sessionTo SessionRef, force bool) (_err error) {
	_method := "VM_appliance.recover"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVMApplianceRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_sessionToArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_to"), sessionTo)
	if _err != nil {
		return
	}
	_forceArg, _err := convertBoolToXen(fmt.Sprintf("%s(%s)", _method, "force"), force)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg, _sessionToArg, _forceArg)
	return
}
983515
func (vm *VirtualMachine) GetVirtualDiskPath(ctx context.Context) (string, error) {
	vmDevices, err := vm.Device(ctx)
	if err != nil {
		klog.Errorf("Failed to get the devices for VM: %q. err: %+v", vm.InventoryPath, err)
		return "", err
	}
	// filter vm devices to retrieve device for the given vmdk file identified by disk path
	for _, device := range vmDevices {
		if vmDevices.TypeName(device) == "VirtualDisk" {
			virtualDevice := device.GetVirtualDevice()
			if backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {
				return backing.FileName, nil
			}
		}
	}
	return "", nil
}
1017828
func (vm *VirtualMachine) RenewVM(client *vim25.Client) VirtualMachine {
	dc := Datacenter{Datacenter: object.NewDatacenter(client, vm.Datacenter.Reference())}
	newVM := object.NewVirtualMachine(client, vm.VirtualMachine.Reference())
	return VirtualMachine{VirtualMachine: newVM, Datacenter: &dc}
}
926261
func (f *Facade) RepairRegistry(ctx datastore.Context) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.RepairRegistry"))
	if err := f.DFSLock(ctx).LockWithTimeout("reset registry", userLockTimeout); err != nil {
		plog.WithError(err).Debug("Cannot reset registry")
		return err
	}
	defer f.DFSLock(ctx).Unlock()

	tenantIDs, err := f.GetTenantIDs(ctx)
	if err != nil {
		return err
	}
	for _, tenantID := range tenantIDs {
		svcs, err := f.GetServiceDetailsByTenantID(ctx, tenantID)
		if err != nil {
			return err
		}
		var imagesMap = make(map[string]struct{})
		for _, svc := range svcs {
			if _, ok := imagesMap[svc.ImageID]; !ok {
				if _, err := f.dfs.Download(svc.ImageID, tenantID, true); err != nil {
					plog.WithField("imageid", svc.ImageID).WithError(err).Debug("Could not download image from registry")
					return err
				}
				imagesMap[svc.ImageID] = struct{}{}
			}
		}
	}
	return nil
}
925938
func (r Virtual_Host) GetHardware() (resp datatypes.Hardware_Server, err error) {
	err = r.Session.DoRequest("SoftLayer_Virtual_Host", "getHardware", nil, &r.Options, &resp)
	return
}
761447
func (s *VirtualMachineService) RecoverVirtualMachine(p *RecoverVirtualMachineParams) (*RecoverVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("recoverVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r RecoverVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
750906
func (s *VirtualMachineService) ExpungeVirtualMachine(p *ExpungeVirtualMachineParams) (*ExpungeVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("expungeVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ExpungeVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
375006
func deleteVM(c context.Context, id, hostname string) error {
	vm := &model.VM{
		ID: id,
	}
	return datastore.RunInTransaction(c, func(c context.Context) error {
		switch err := datastore.Get(c, vm); {
		case err == datastore.ErrNoSuchEntity:
			return nil
		case err != nil:
			return errors.Annotate(err, "failed to fetch VM").Err()
		case vm.Hostname != hostname:
			logging.Debugf(c, "VM %q does not exist", hostname)
			return nil
		}
		if err := datastore.Delete(c, vm); err != nil {
			return errors.Annotate(err, "failed to delete VM").Err()
		}
		return nil
	}, nil)
}
986424
func (_class VMSSClass) GetVMs(sessionID SessionRef, self VMSSRef) (_retval []VMRef, _err error) {
	_method := "VMSS.get_VMs"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVMSSRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVMRefSetToGo(_method + " -> ", _result.Value)
	return
}
383915
func (s *RaftStore) Recover() (*RecoveredState, error) {
	s.Lock()
	defer s.Unlock()
	state, err := s.Store.Recover()
	if err != nil {
		return nil, err
	}
	if state != nil {
		for channel, rc := range state.Channels {
			// Note that this is when recovering the underlying sub store
			// that would be the case for a RaftSubStore prior to 0.14.1
			var maxSubID uint64
			for _, rs := range rc.Subscriptions {
				if rs.Sub.ID > maxSubID {
					maxSubID = rs.Sub.ID
				}
			}
			rc.Channel.Subs = s.replaceSubStore(channel, rc.Channel.Subs, maxSubID)
			rc.Subscriptions = nil
		}
		state.Clients = nil
	}
	return state, nil
}
577571
func (orig OptionsConfiguration) RequiresRestartOnly() OptionsConfiguration {
	copy := orig
	blank := OptionsConfiguration{}
	util.CopyMatchingTag(&blank, &copy, "restart", func(v string) bool {
		if len(v) > 0 && v != "true" {
			panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "true"`, v))
		}
		return v != "true"
	})
	return copy
}
1037259
func (s *VirtualMachineService) NewRecoverVirtualMachineParams(id string) *RecoverVirtualMachineParams {
	p := &RecoverVirtualMachineParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
1169612
func (ctrl *PersistentVolumeController) reclaimVolume(volume *v1.PersistentVolume) error {
	switch volume.Spec.PersistentVolumeReclaimPolicy {
	case v1.PersistentVolumeReclaimRetain:
		klog.V(4).Infof("reclaimVolume[%s]: policy is Retain, nothing to do", volume.Name)

	case v1.PersistentVolumeReclaimRecycle:
		klog.V(4).Infof("reclaimVolume[%s]: policy is Recycle", volume.Name)
		opName := fmt.Sprintf("recycle-%s[%s]", volume.Name, string(volume.UID))
		ctrl.scheduleOperation(opName, func() error {
			ctrl.recycleVolumeOperation(volume)
			return nil
		})

	case v1.PersistentVolumeReclaimDelete:
		klog.V(4).Infof("reclaimVolume[%s]: policy is Delete", volume.Name)
		opName := fmt.Sprintf("delete-%s[%s]", volume.Name, string(volume.UID))
		startTime := time.Now()
		ctrl.scheduleOperation(opName, func() error {
			pluginName, err := ctrl.deleteVolumeOperation(volume)
			timeTaken := time.Since(startTime).Seconds()
			metrics.RecordVolumeOperationMetric(pluginName, "delete", timeTaken, err)
			return err
		})

	default:
		// Unknown PersistentVolumeReclaimPolicy
		if _, err := ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, "VolumeUnknownReclaimPolicy", "Volume has unrecognized PersistentVolumeReclaimPolicy"); err != nil {
			return err
		}
	}
	return nil
}
1024272
func (vm *VM) Halt() error {

	if vm.ID == "" {
		return fmt.Errorf("Need an ID to stop the virtual machine")
	}

	params := url.Values{}
	params.Set("id", vm.ID)

	client := vm.getExoClient()
	resp, err := client.Request("stopVirtualMachine", params)
	if err != nil {
		return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err)
	}

	stop := &egoscale.StopVirtualMachineResponse{}
	if err := json.Unmarshal(resp, stop); err != nil {
		return fmt.Errorf("Stopping virtual machine %q: %s", vm.ID, err)
	}

	vm.JobID = stop.JobID

	return nil

}
932628
func (_class VIFClass) GetVM(sessionID SessionRef, self VIFRef) (_retval VMRef, _err error) {
	_method := "VIF.get_VM"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVIFRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVMRefToGo(_method + " -> ", _result.Value)
	return
}
1091716
func (vm *VM) Provision() error {
	src := vm.Src
	dst := vm.Dst

	if src == "" {
		return lvm.ErrSourceNotSpecified
	}

	if dst == "" {
		return lvm.ErrDestNotSpecified
	}

	srcPath, _ := filepath.Abs(filepath.Dir(src))
	srcPath += "/"

	// Check if the path exists, if not try to create it.
	if _, err := os.Stat(dst); err != nil {
		if os.IsNotExist(err) {
			dir := os.Mkdir(dst, 0777)

			if dir != nil {
				return dir
			}
		} else {
			return err
		}
	} else {
		return lvm.ErrCreatingVM
	}

	// Copy over the source path to the destination.
	err := copyDir(srcPath, dst)
	if err != nil {
		return err
	}

	_, vmxFileName := filepath.Split(src)
	vm.VmxFilePath = fmt.Sprintf("%s/%s", dst, vmxFileName)

	err = vm.configure()
	if err != nil {
		return err
	}

	_, _, err = runVMware()
	if err != nil {
		return err
	}

	return vm.waitUntilReady()
}
1228129
func (s *VirtualMachineService) RestoreVirtualMachine(p *RestoreVirtualMachineParams) (*RestoreVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("restoreVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r RestoreVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}