// unwrapVcsErr will extract actual command output from a vcs err, if possible
//
// TODO this is really dumb, lossy, and needs proper handling
482320
func unwrapVcsErr(err error) error {
	switch verr := err.(type) {
	case *vcs.LocalError:
		return fmt.Errorf("%s: %s", verr.Error(), verr.Out())
	case *vcs.RemoteError:
		return fmt.Errorf("%s: %s", verr.Error(), verr.Out())
	default:
		return err
	}
}
1167664
func (b *BasicAuth) UnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	if err := b.doAuth(ctx); err != nil {
		return nil, err
	}
	return handler(ctx, req)
}
537661
func (_class VMApplianceClass) GetSRsRequiredForRecovery(sessionID SessionRef, self VMApplianceRef, sessionTo SessionRef) (_retval []SRRef, _err error) {
	_method := "VM_appliance.get_SRs_required_for_recovery"
	_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
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg, _sessionToArg)
	if _err != nil {
		return
	}
	_retval, _err = convertSRRefSetToGo(_method + " -> ", _result.Value)
	return
}
515560
func UnaryServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateServerOpt(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
		startTime := time.Now()
		newCtx := newLoggerForCall(ctx, entry, info.FullMethod, startTime)

		resp, err := handler(newCtx, req)

		if !o.shouldLog(info.FullMethod, err) {
			return resp, err
		}
		code := o.codeFunc(err)
		level := o.levelFunc(code)
		durField, durVal := o.durationFunc(time.Since(startTime))
		fields := logrus.Fields{
			"grpc.code": code.String(),
			durField:    durVal,
		}
		if err != nil {
			fields[logrus.ErrorKey] = err
		}

		levelLogf(
			ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder.
			level,
			"finished unary call with code "+code.String())

		return resp, err
	}
}
794158
func wrapErr(err error, ctx interface{}) error {
	if pc, ok := ctx.(pageContext); ok {
		return pc.wrapError(err)
	}
	return err
}
1355125
func unwrapValue(v interface{}) (token, interface{}) {
	switch tk := v.(type) {
	case token:
		return tk, tk.Value()
	default:
		return nil, v
	}
}
509979
func WrapRecoverable(msg string, err error) error {
	return &RecoverableError{Err: msg, Recoverable: IsRecoverable(err)}
}
1340550
func Recoverer(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rval := recover(); rval != nil {
				debug.PrintStack()
				rvalStr := fmt.Sprint(rval)
				var packet *Packet
				if err, ok := rval.(error); ok {
					packet = NewPacket(rvalStr, NewException(errors.New(rvalStr), GetOrNewStacktrace(err, 2, 3, nil)), NewHttp(r))
				} else {
					packet = NewPacket(rvalStr, NewException(errors.New(rvalStr), NewStacktrace(2, 3, nil)), NewHttp(r))
				}
				Capture(packet, nil)
				w.WriteHeader(http.StatusInternalServerError)
			}
		}()

		handler.ServeHTTP(w, r)
	})
}
58976
func UnwrapError(err error) (b2Err *Error, ok bool) {
	if e, ok := err.(*url.Error); ok {
		err = e.Err
	}
	if e, ok := err.(*Error); ok {
		return e, true
	}
	return nil, false
}
834785
func (s *RemoteEnforcer) Unenforce(req rpcwrapper.Request, resp *rpcwrapper.Response) error {

	if !s.rpcHandle.CheckValidity(&req, s.rpcSecret) {
		resp.Status = "unenforce message auth failed"
		return fmt.Errorf(resp.Status)
	}

	cmdLock.Lock()
	defer cmdLock.Unlock()

	s.statsClient.SendStats()

	payload, ok := req.Payload.(rpcwrapper.UnEnforcePayload)
	if !ok {
		resp.Status = "invalid unenforcer payload"
		return fmt.Errorf(resp.Status)
	}

	var err error

	// If any error happens, cleanup everything on exit so that we can recover
	// by launcing a new remote.
	defer func() {
		if err != nil {
			s.cleanup()
		}
	}()

	if err = s.supervisor.Unsupervise(payload.ContextID); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf("unable to clean supervisor: %s", err)
	}

	if err = s.enforcer.Unenforce(payload.ContextID); err != nil {
		resp.Status = err.Error()
		return fmt.Errorf("unable to stop enforcer: %s", err)
	}

	return nil
}
504788
func createOutputWrapper(uri string, classes []LogClass) (*loggerOutputWrapper, error) {
	// If the caller didn't give us any classes to configure then we do
	// nothing. This can be either an error or not, and since it is just as easy
	// either way we define this as being a no op rather than error condition.
	if len(classes) == 0 {
		return nil, nil
	}

	// Combine the output classes into just one
	class := NONE
	for _, c := range classes {
		class |= c
	}

	return createOutputWrapperForClass(uri, class)
}
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
}
887948
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
	o := evaluateOptions(opts)
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
		defer func() {
			if r := recover(); r != nil {
				err = recoverFrom(ctx, r, o.recoveryHandlerFunc)
			}
		}()

		return handler(ctx, req)
	}
}
529046
func encodeInvCursor(cur *internal.InvocationsCursor) (string, error) {
	if cur.LastScanned == 0 {
		return "", nil
	}

	blob, err := proto.Marshal(cur)
	if err != nil {
		return "", err // must never actually happen
	}

	return base64.RawURLEncoding.EncodeToString(blob), nil
}
843310
func unmarshalScraper(v []byte) (*influxdb.ScraperTarget, error) {
	s := &influxdb.ScraperTarget{}
	if err := json.Unmarshal(v, s); err != nil {
		return nil, CorruptScraperError(err)
	}
	return s, nil
}
328117
func (svc *Service) UnaryServerInterceptor(
	permissionMap map[string][]bakery.Op) grpc.UnaryServerInterceptor {

	return func(ctx context.Context, req interface{},
		info *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler) (interface{}, error) {

		if _, ok := permissionMap[info.FullMethod]; !ok {
			return nil, fmt.Errorf("%s: unknown permissions "+
				"required for method", info.FullMethod)
		}

		err := svc.ValidateMacaroon(ctx, permissionMap[info.FullMethod])
		if err != nil {
			return nil, err
		}

		return handler(ctx, req)
	}
}
1288033
func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
		w.Header().Set("Server", fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS))
		w.Header().Set("API-Version", v.defaultVersion)
		w.Header().Set("OSType", runtime.GOOS)

		apiVersion := vars["version"]
		if apiVersion == "" {
			apiVersion = v.defaultVersion
		}
		if versions.LessThan(apiVersion, v.minVersion) {
			return versionUnsupportedError{version: apiVersion, minVersion: v.minVersion}
		}
		if versions.GreaterThan(apiVersion, v.defaultVersion) {
			return versionUnsupportedError{version: apiVersion, maxVersion: v.defaultVersion}
		}
		ctx = context.WithValue(ctx, httputils.APIVersionKey{}, apiVersion)
		return handler(ctx, w, r, vars)
	}

}