// Recovers a virtual machine.
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
}
439624
func DetachVhd(path string) error {
	handle, err := OpenVirtualDisk(path, VirtualDiskAccessDetach, OpenVirtualDiskFlagNone)
	if err != nil {
		return err
	}
	defer syscall.CloseHandle(handle)
	return detachVirtualDisk(handle, 0, 0)
}
91239
func recoverUnmarshal(v interface{}, data *C.pn_data_t) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if uerr, ok := r.(*UnmarshalError); ok {
				err = uerr
			} else {
				panic(r)
			}
		}
	}()
	unmarshal(v, data)
	return nil
}
925328
func (s *SQLStore) Recover() (*RecoveredState, error) {
	s.Lock()
	defer s.Unlock()
	var (
		clusterID string
		data      []byte
		version   int
		err       error
	)
	r := s.db.QueryRow(sqlStmts[sqlRecoverServerInfo])
	if err := r.Scan(&clusterID, &data, &version); err != nil {
		// If there is no row, that means nothing to recover. Return nil for the
		// state and no error.
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, sqlStmtError(sqlRecoverServerInfo, err)
	}
	if version != sqlVersion {
		return nil, fmt.Errorf("sql: unsupported version: %v (supports [1..%v])", version, sqlVersion)
	}
	info := &spb.ServerInfo{}
	if err := info.Unmarshal(data); err != nil {
		return nil, err
	}
	if info.ClusterID != clusterID {
		return nil, fmt.Errorf("sql: id %q in column does not match cluster ID in data %q", clusterID, info.ClusterID)
	}

	// Create recovered state structure and fill it with server info.
	rs := &RecoveredState{
		Info: info,
	}

	var clients []*Client
	cliRows, err := s.db.Query(sqlStmts[sqlRecoverClients])
	if err != nil && err != sql.ErrNoRows {
		return nil, sqlStmtError(sqlRecoverClients, err)
	}
	defer cliRows.Close()
	for cliRows.Next() {
		var (
			clientID string
			hbInbox  string
			proto    []byte
		)
		if err := cliRows.Scan(&clientID, &hbInbox, &proto); err != nil {
			return nil, err
		}
		var client *Client
		if len(proto) == 0 {
			client = &Client{spb.ClientInfo{ID: clientID, HbInbox: hbInbox}}
		} else {
			info := spb.ClientInfo{}
			info.Unmarshal(proto)
			client = &Client{info}
		}
		clients = append(clients, client)
	}
	cliRows.Close()
	// Set clients into recovered state.
	rs.Clients = clients

	// Get the maxChannelID
	r = s.db.QueryRow(sqlStmts[sqlRecoverMaxChannelID])
	err = r.Scan(&s.maxChannelID)
	if err != nil && err != sql.ErrNoRows {
		return nil, sqlStmtError(sqlRecoverMaxChannelID, err)
	}
	// If there was no channel recovered, we are done
	if s.maxChannelID == 0 {
		return rs, nil
	}
	// Get the maxSubID
	r = s.db.QueryRow(sqlStmts[sqlRecoverMaxSubID])
	if err := r.Scan(&s.maxSubID); err != nil && err != sql.ErrNoRows {
		return nil, sqlStmtError(sqlRecoverMaxSubID, err)
	}

	// Recover individual channels
	var channels map[string]*RecoveredChannel
	channelRows, err := s.db.Query(sqlStmts[sqlRecoverChannelsList])
	if err != nil && err != sql.ErrNoRows {
		return nil, sqlStmtError(sqlRecoverChannelsList, err)
	}
	defer channelRows.Close()
	for channelRows.Next() {
		var (
			channelID int64
			name      string
			maxseq    uint64 // We get that from the Channels table.
			mmseq     uint64 // This is the max seq found in the Messages table for given channel.
		)
		if err := channelRows.Scan(&channelID, &name, &maxseq); err != nil {
			return nil, err
		}

		channelLimits := s.genericStore.getChannelLimits(name)

		msgStore := s.newSQLMsgStore(name, channelID, &channelLimits.MsgStoreLimits)

		// We need to get the last seq from messages table before possibly expiring messages.
		r = s.preparedStmts[sqlGetLastSeq].QueryRow(channelID)
		if err := r.Scan(&mmseq); err != nil {
			return nil, sqlStmtError(sqlGetLastSeq, err)
		}
		// If it is more than the one that was updated in the Channel row, then use this one.
		if mmseq > maxseq {
			maxseq = mmseq
		}

		if err := s.applyLimitsOnRecovery(msgStore); err != nil {
			return nil, err
		}

		r = s.preparedStmts[sqlRecoverChannelMsgs].QueryRow(channelID)
		var (
			totalCount    int
			first         uint64
			last          uint64
			totalBytes    uint64
			lastTimestamp int64
		)
		if err := r.Scan(&totalCount, &first, &last, &totalBytes, &lastTimestamp); err != nil && err != sql.ErrNoRows {
			return nil, sqlStmtError(sqlRecoverChannelMsgs, err)
		}
		msgStore.first = first
		msgStore.last = last
		msgStore.totalCount = totalCount
		msgStore.totalBytes = totalBytes
		// Since messages may have been removed due to limits, update first/last
		// based on known max sequence.
		if maxseq > msgStore.last {
			msgStore.first = maxseq + 1
			msgStore.last = maxseq
		}

		subStore := s.newSQLSubStore(channelID, &channelLimits.SubStoreLimits)
		// Prevent scheduling to flusher while we are recovering
		if !s.opts.NoCaching {
			// By setting this to true, we prevent scheduling since
			// scheduling would occur only if needsFlush is false.
			subStore.cache.needsFlush = true
		}

		var subscriptions []*RecoveredSubscription

		subRows, err := s.preparedStmts[sqlRecoverChannelSubs].Query(channelID)
		if err != nil {
			return nil, sqlStmtError(sqlRecoverChannelSubs, err)
		}
		defer subRows.Close()
		for subRows.Next() {
			var (
				lastSent   uint64
				protoBytes []byte
				ap         *sqlSubAcksPending
			)
			if err := subRows.Scan(&lastSent, &protoBytes); err != nil && err != sql.ErrNoRows {
				return nil, err
			}
			if protoBytes != nil {
				sub := &spb.SubState{}
				if err := sub.Unmarshal(protoBytes); err != nil {
					return nil, err
				}
				// We need to use the max of lastSent column or the one in the proto
				if lastSent > sub.LastSent {
					sub.LastSent = lastSent
				}
				if s.opts.NoCaching {
					// We can remove entries for sequence that are below the smallest
					// sequence that was found in Messages.
					if _, err := s.preparedStmts[sqlRecoverDoPurgeSubsPending].Exec(sub.ID, msgStore.first); err != nil {
						return nil, sqlStmtError(sqlRecoverDoPurgeSubsPending, err)
					}
				} else {
					ap = subStore.getOrCreateAcksPending(sub.ID, 0)
				}
				rows, err := s.preparedStmts[sqlRecoverSubPending].Query(sub.ID)
				if err != nil {
					return nil, sqlStmtError(sqlRecoverSubPending, err)
				}
				defer rows.Close()
				pendingAcks := make(PendingAcks)
				var gcedRows map[uint64]struct{}
				if !s.opts.NoCaching {
					gcedRows = make(map[uint64]struct{})
				}
				for rows.Next() {
					if err := subStore.recoverPendingRow(rows, sub, ap, pendingAcks, gcedRows); err != nil {
						return nil, err
					}
				}
				rows.Close()

				if s.opts.NoCaching {
					// Update the in-memory map tracking last sent
					subStore.subLastSent[sub.ID] = sub.LastSent
				} else {
					// Go over garbage collected rows and delete them
					for rowID := range gcedRows {
						if err := subStore.deleteSubPendingRow(sub.ID, rowID); err != nil {
							return nil, err
						}
					}
				}

				// Add to the recovered subscriptions
				subscriptions = append(subscriptions, &RecoveredSubscription{Sub: sub, Pending: pendingAcks})
			}
		}
		subRows.Close()

		if !s.opts.NoCaching {
			// Clear but also allow scheduling now that the recovery is complete.
			subStore.cache.needsFlush = false
		}

		rc := &RecoveredChannel{
			Channel: &Channel{
				Msgs: msgStore,
				Subs: subStore,
			},
			Subscriptions: subscriptions,
		}
		if channels == nil {
			channels = make(map[string]*RecoveredChannel)
		}
		channels[name] = rc
		s.channels[name] = rc.Channel
	}
	channelRows.Close()

	// Set channels into recovered state
	rs.Channels = channels

	return rs, nil
}
230845
func Recovery() macaron.Handler {
	return func(c *macaron.Context) {
		defer func() {
			if err := recover(); err != nil {
				stack := stack(3)

				panicLogger := log.Root
				// try to get request logger
				if ctx, ok := c.Data["ctx"]; ok {
					ctxTyped := ctx.(*m.ReqContext)
					panicLogger = ctxTyped.Logger
				}

				panicLogger.Error("Request error", "error", err, "stack", string(stack))

				c.Data["Title"] = "Server Error"
				c.Data["AppSubUrl"] = setting.AppSubUrl
				c.Data["Theme"] = setting.DefaultTheme

				if setting.Env == setting.DEV {
					if theErr, ok := err.(error); ok {
						c.Data["Title"] = theErr.Error()
					}

					c.Data["ErrorMsg"] = string(stack)
				}

				ctx, ok := c.Data["ctx"].(*m.ReqContext)

				if ok && ctx.IsApiRequest() {
					resp := make(map[string]interface{})
					resp["message"] = "Internal Server Error - Check the Grafana server logs for the detailed error message."

					if c.Data["ErrorMsg"] != nil {
						resp["error"] = fmt.Sprintf("%v - %v", c.Data["Title"], c.Data["ErrorMsg"])
					} else {
						resp["error"] = c.Data["Title"]
					}

					c.JSON(500, resp)
				} else {
					c.HTML(500, setting.ERR_TEMPLATE_NAME)
				}
			}
		}()

		c.Next()
	}
}
737703
func (c *Client) ResetPasswordForVirtualMachine(p *ResetPasswordForVirtualMachineParameter) (*VirtualMachine, error) {
	obj, err := c.Request("resetPasswordForVirtualMachine", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
271032
func (c *Client) RestoreVirtualMachine(p *RestoreVirtualMachineParameter) (*VirtualMachine, error) {
	obj, err := c.Request("restoreVirtualMachine", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
773306
func (c *Client) MigrateVirtualMachineWithVolume(p *MigrateVirtualMachineWithVolumeParameter) (*VirtualMachine, error) {
	obj, err := c.Request("migrateVirtualMachineWithVolume", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
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
}
63976
func (_class VMClass) GetSRsRequiredForRecovery(sessionID SessionRef, self VMRef, sessionTo SessionRef) (_retval []SRRef, _err error) {
	_method := "VM.get_SRs_required_for_recovery"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVMRefToXen(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
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg, _sessionToArg)
	if _err != nil {
		return
	}
	_retval, _err = convertSRRefSetToGo(_method + " -> ", _result.Value)
	return
}
300541
func (r *PortAllocator) Restore(pr net.PortRange, data []byte) error {
	if pr.String() != r.portRange.String() {
		return ErrMismatchedNetwork
	}
	snapshottable, ok := r.alloc.(allocator.Snapshottable)
	if !ok {
		return fmt.Errorf("not a snapshottable allocator")
	}
	return snapshottable.Restore(pr.String(), data)
}
32810
func (limiters *RateLimiters) Recover(host string) {
	limiters.mu.Lock()
	defer limiters.mu.Unlock()
	if limiters.perHost == nil {
		return
	}
	if limiter, ok := limiters.perHost[host]; ok {
		oldLimit := float64(limiter.Limit())
		newLimit := limiters.clip(oldLimit * recoverBy)
		if newLimit != oldLimit && limiters.Logger != nil {
			limiters.Logger.Log("info", "increasing rate limit", "host", host, "limit", strconv.FormatFloat(newLimit, 'f', 2, 64))
		}
		limiter.SetLimit(rate.Limit(newLimit))
	}
}
65207
func (s *VirtualMachineService) NewRestoreVirtualMachineParams(virtualmachineid string) *RestoreVirtualMachineParams {
	p := &RestoreVirtualMachineParams{}
	p.p = make(map[string]interface{})
	p.p["virtualmachineid"] = virtualmachineid
	return p
}
1330029
func Recover() goa.Middleware {
	return func(h goa.Handler) goa.Handler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) {
			defer func() {
				if r := recover(); r != nil {
					var msg string
					switch x := r.(type) {
					case string:
						msg = fmt.Sprintf("panic: %s", x)
					case error:
						msg = fmt.Sprintf("panic: %s", x)
					default:
						msg = "unknown panic"
					}
					const size = 64 << 10 // 64KB
					buf := make([]byte, size)
					buf = buf[:runtime.Stack(buf, false)]
					lines := strings.Split(string(buf), "\n")
					stack := lines[3:]
					err = fmt.Errorf("%s\n%s", msg, strings.Join(stack, "\n"))
				}
			}()
			return h(ctx, rw, req)
		}
	}
}
643466
func (_class PoolClass) RecoverSlaves(sessionID SessionRef) (_retval []HostRef, _err error) {
	_method := "pool.recover_slaves"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostRefSetToGo(_method + " -> ", _result.Value)
	return
}
52678
func (s *CloudBackupServer) Restore(
	ctx context.Context,
	req *api.SdkCloudBackupRestoreRequest,
) (*api.SdkCloudBackupRestoreResponse, error) {
	if s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}
	credId := req.GetCredentialId()
	var err error
	if len(req.GetBackupId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must provide backup id")
	} else if len(req.GetCredentialId()) == 0 {
		credId, err = s.defaultCloudBackupCreds(ctx)
		if err != nil {
			return nil, err
		}
	}

	if len(req.GetCredentialId()) != 0 {
		if err := s.checkAccessToCredential(ctx, req.GetCredentialId()); err != nil {
			return nil, err
		}
	}

	r, err := s.driver(ctx).CloudBackupRestore(&api.CloudBackupRestoreRequest{
		ID:                req.GetBackupId(),
		RestoreVolumeName: req.GetRestoreVolumeName(),
		CredentialUUID:    credId,
		NodeID:            req.GetNodeId(),
		Name:              req.GetTaskId(),
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Failed to restore backup: %v", err)
	}

	return &api.SdkCloudBackupRestoreResponse{
		RestoreVolumeId: r.RestoreVolumeID,
		TaskId:          r.Name,
	}, nil

}
377804
func (s *VirtualMachineService) CleanVMReservations(p *CleanVMReservationsParams) (*CleanVMReservationsResponse, error) {
	resp, err := s.cs.newRequest("cleanVMReservations", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CleanVMReservationsResponse
	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
}