// handle processes a deployment and either creates a deployer pod or responds
// to a terminal deployment status. Since this controller started using caches,
// the provided rc MUST be deep-copied beforehand (see work() in factory.go).
778787
func (c *DeploymentController) handle(deployment *corev1.ReplicationController, willBeDropped bool) error {
	// Copy all the annotations from the deployment.
	updatedAnnotations := make(map[string]string)
	for key, value := range deployment.Annotations {
		updatedAnnotations[key] = value
	}

	currentStatus := appsutil.DeploymentStatusFor(deployment)
	nextStatus := currentStatus

	deployerPodName := appsutil.DeployerPodNameForDeployment(deployment.Name)
	deployer, deployerErr := c.podLister.Pods(deployment.Namespace).Get(deployerPodName)
	if deployerErr == nil {
		nextStatus = c.nextStatus(deployer, deployment, updatedAnnotations)
	}

	switch currentStatus {
	case appsv1.DeploymentStatusNew:
		// If the deployment has been cancelled, don't create a deployer pod.
		// Instead try to delete any deployer pods found and transition the
		// deployment to Pending so that the deployment config controller
		// continues to see the deployment as in-flight. Eventually the deletion
		// of the deployer pod should cause a requeue of this deployment and
		// then it can be transitioned to Failed by this controller.
		if appsutil.IsDeploymentCancelled(deployment) {
			nextStatus = appsv1.DeploymentStatusPending
			if err := c.cleanupDeployerPods(deployment); err != nil {
				return err
			}
			break
		}
		// In case the deployment is stuck in "new" state because we fail to create
		// deployer pod (quota, etc..) we should respect the timeoutSeconds in the
		// config strategy and transition the rollout to failed instead of waiting for
		// the deployment pod forever.
		config, err := appsutil.DecodeDeploymentConfig(deployment)
		if err != nil {
			return err
		}
		if appsutil.RolloutExceededTimeoutSeconds(config, deployment) {
			nextStatus = appsv1.DeploymentStatusFailed
			updatedAnnotations[appsv1.DeploymentStatusReasonAnnotation] = appsutil.DeploymentFailedUnableToCreateDeployerPod
			c.emitDeploymentEvent(deployment, corev1.EventTypeWarning, "RolloutTimeout", fmt.Sprintf("Rollout for %q failed to create deployer pod (timeoutSeconds: %ds)", appsutil.LabelForDeployment(deployment), appsutil.GetTimeoutSecondsForStrategy(config)))
			klog.V(4).Infof("Failing deployment %s/%s as we reached timeout while waiting for the deployer pod to be created", deployment.Namespace, deployment.Name)
			break
		}

		switch {
		case kerrors.IsNotFound(deployerErr):
			if _, ok := deployment.Annotations[appsutil.DeploymentIgnorePodAnnotation]; ok {
				return nil
			}

			// Generate a deployer pod spec.
			deployerPod, err := c.makeDeployerPod(deployment)
			if err != nil {
				return fatalError(fmt.Sprintf("couldn't make deployer pod for %q: %v", appsutil.LabelForDeployment(deployment), err))
			}
			// Create the deployer pod.
			deploymentPod, err := c.pn.Pods(deployment.Namespace).Create(deployerPod)
			// Retry on error.
			if err != nil {
				// if we cannot create a deployment pod (i.e lack of quota), match normal replica set experience and
				// emit an event.
				c.emitDeploymentEvent(deployment, corev1.EventTypeWarning, "FailedCreate", fmt.Sprintf("Error creating deployer pod: %v", err))
				return actionableError(fmt.Sprintf("couldn't create deployer pod for %q: %v", appsutil.LabelForDeployment(deployment), err))
			}
			updatedAnnotations[appsv1.DeploymentPodAnnotation] = deploymentPod.Name
			updatedAnnotations[appsv1.DeployerPodCreatedAtAnnotation] = deploymentPod.CreationTimestamp.String()
			if deploymentPod.Status.StartTime != nil {
				updatedAnnotations[appsv1.DeployerPodStartedAtAnnotation] = deploymentPod.Status.StartTime.String()
			}
			nextStatus = appsv1.DeploymentStatusPending
			klog.V(4).Infof("Created deployer pod %q for %q", deploymentPod.Name, appsutil.LabelForDeployment(deployment))

		// Most likely dead code since we never get an error different from 404 back from the cache.
		case deployerErr != nil:
			// If the pod already exists, it's possible that a previous CreatePod
			// succeeded but the deployment state update failed and now we're re-
			// entering. Ensure that the pod is the one we created by verifying the
			// annotation on it, and throw a retryable error.
			return fmt.Errorf("couldn't fetch existing deployer pod for %s: %v", appsutil.LabelForDeployment(deployment), deployerErr)

		default: /* deployerErr == nil */
			// Do a stronger check to validate that the existing deployer pod is
			// actually for this deployment, and if not, fail this deployment.
			//
			// TODO: Investigate checking the container image of the running pod and
			// comparing with the intended deployer pod image. If we do so, we'll need
			// to ensure that changes to 'unrelated' pods don't result in updates to
			// the deployment. So, the image check will have to be done in other areas
			// of the code as well.
			if appsutil.DeploymentNameFor(deployer) != deployment.Name {
				nextStatus = appsv1.DeploymentStatusFailed
				updatedAnnotations[appsv1.DeploymentStatusReasonAnnotation] = appsutil.DeploymentFailedUnrelatedDeploymentExists
				c.emitDeploymentEvent(deployment, corev1.EventTypeWarning, "FailedCreate", fmt.Sprintf("Error creating deployer pod since another pod with the same name (%q) exists", deployer.Name))
			} else {
				// Update to pending or to the appropriate status relative to the existing validated deployer pod.
				updatedAnnotations[appsv1.DeploymentPodAnnotation] = deployer.Name
				updatedAnnotations[appsv1.DeployerPodCreatedAtAnnotation] = deployer.CreationTimestamp.String()
				if deployer.Status.StartTime != nil {
					updatedAnnotations[appsv1.DeployerPodStartedAtAnnotation] = deployer.Status.StartTime.String()
				}
				nextStatus = nextStatusComp(nextStatus, appsv1.DeploymentStatusPending)
			}
		}

	case appsv1.DeploymentStatusPending, appsv1.DeploymentStatusRunning:
		switch {
		case kerrors.IsNotFound(deployerErr):
			nextStatus = appsv1.DeploymentStatusFailed
			// If the deployment is cancelled here then we deleted the deployer in a previous
			// resync of the deployment.
			if !appsutil.IsDeploymentCancelled(deployment) {
				// Retry more before setting the deployment to Failed if it's Pending - the pod might not have
				// appeared in the cache yet.
				if !willBeDropped && currentStatus == appsv1.DeploymentStatusPending {
					return deployerErr
				}
				updatedAnnotations[appsv1.DeploymentStatusReasonAnnotation] = appsutil.DeploymentFailedDeployerPodNoLongerExists
				c.emitDeploymentEvent(deployment, corev1.EventTypeWarning, "Failed", fmt.Sprintf("Deployer pod %q has gone missing", deployerPodName))
				deployerErr = fmt.Errorf("failing rollout for %q because its deployer pod %q disappeared", appsutil.LabelForDeployment(deployment), deployerPodName)
				utilruntime.HandleError(deployerErr)
			}

		// Most likely dead code since we never get an error different from 404 back from the cache.
		case deployerErr != nil:
			// We'll try again later on resync. Continue to process cancellations.
			deployerErr = fmt.Errorf("error getting deployer pod %q for %q: %v", deployerPodName, appsutil.LabelForDeployment(deployment), deployerErr)
			utilruntime.HandleError(deployerErr)

		default: /* err == nil */
			// If the deployment has been cancelled, delete any deployer pods
			// found. Eventually the deletion of the deployer pod should cause
			// a requeue of this deployment and then it can be transitioned to
			// Failed.
			if appsutil.IsDeploymentCancelled(deployment) {
				if err := c.cleanupDeployerPods(deployment); err != nil {
					return err
				}
			} else {
				// Set an ownerRef for the deployment lifecycle pods so they are cleaned up when the
				// replication controller is deleted.
				if err := c.setDeployerPodsOwnerRef(deployment); err != nil {
					return err
				}
			}
		}

	case appsv1.DeploymentStatusFailed:
		// Try to cleanup once more a cancelled deployment in case hook pods
		// were created just after we issued the first cleanup request.
		if appsutil.IsDeploymentCancelled(deployment) {
			if err := c.cleanupDeployerPods(deployment); err != nil {
				return err
			}
		} else {
			// Set an ownerRef for the deployment lifecycle pods so they are cleaned up when the
			// replication controller is deleted.
			if err := c.setDeployerPodsOwnerRef(deployment); err != nil {
				return err
			}
		}

	case appsv1.DeploymentStatusComplete:
		// preserve deployer pods on completed deployments
	}

	deploymentCopy := deployment.DeepCopy()

	// Update only if we need to transition to a new phase.
	if appsutil.CanTransitionPhase(currentStatus, nextStatus) {
		updatedAnnotations[appsv1.DeploymentStatusAnnotation] = string(nextStatus)
		deploymentCopy.Annotations = updatedAnnotations

		// If we are going to transition to failed or complete and scale is non-zero, we'll check one more
		// time to see if we are a test deployment to guarantee that we maintain the test invariant.
		if *deploymentCopy.Spec.Replicas != 0 && appsutil.IsTerminatedDeployment(deploymentCopy) {
			if config, err := appsutil.DecodeDeploymentConfig(deploymentCopy); err == nil && config.Spec.Test {
				zero := int32(0)
				deploymentCopy.Spec.Replicas = &zero
			}
		}

		if _, err := c.rn.ReplicationControllers(deploymentCopy.Namespace).Update(deploymentCopy); err != nil {
			return fmt.Errorf("couldn't update rollout status for %q to %s: %v", appsutil.LabelForDeployment(deploymentCopy), nextStatus, err)
		}
		klog.V(4).Infof("Updated rollout status for %q from %s to %s (scale: %d)", appsutil.LabelForDeployment(deploymentCopy), currentStatus, nextStatus, *deploymentCopy.Spec.Replicas)

		if appsutil.IsDeploymentCancelled(deploymentCopy) && appsutil.IsFailedDeployment(deploymentCopy) {
			c.emitDeploymentEvent(deploymentCopy, corev1.EventTypeNormal, "RolloutCancelled", fmt.Sprintf("Rollout for %q cancelled", appsutil.LabelForDeployment(deploymentCopy)))
		}
	}
	return nil
}
1369535
func (hf HandlerFunc) Handle(ctx context.Context, command Command) (result interface{}, err error) {
	return hf(ctx, command)
}
1047902
func (handler *handler) Handle(_ <-chan struct{}, applications []string) error {
	return handler.config.Facade.Rescale(applications)
}
341152
func (s *Server) Handle(path string, controller interface{}, filters ...Filter) {
	//t := struct {
	//	Login  HandlerFunc `method:"get,post" path:"/login"`
	//	Logout HandlerFunc `path:"/logout"`
	//}{}
	v := reflect.Indirect(reflect.ValueOf(controller))
	if v.Kind() != reflect.Struct {
		panic("web > controller must be struct type")
	}

	t := v.Type()
	num := v.NumField()
	for i := 0; i < num; i++ {
		f := v.Field(i)
		h, ok := f.Interface().(HandlerFunc)
		if !ok {
			continue
		}

		sf := t.Field(i)
		if h == nil {
			panic(fmt.Sprintf("web > handler %s.%s isn't initialized", t.Name(), sf.Name))
		}

		s.handleField(path, t, &sf, h, filters...)
	}
}
1358470
func (f FuncReqHandler) Handle(req *http.Request, ctx *ProxyCtx) (*http.Request, *http.Response) {
	return f(req, ctx)
}
372113
func Handle(h Handler) {
	m := &manager{
		Reader:  os.Stdin,
		Writer:  os.Stdout,
		Handler: h,
	}

	m.Start()
}
946136
func (agent *Agent) handle(ctx context.Context, instruction *machine.ComponentsMachineProviderRpcMessagesPollResponse) error {
	if instruction.State == "" || instruction.State == "EXECUTED" {
		return nil
	}

	// The only type of instruction that exists is to connect to Swarming.
	if instruction.Instruction == nil || instruction.Instruction.SwarmingServer == "" {
		return nil
	}

	logging.Infof(ctx, "Received new instruction:\n%s", instruction)
	start := time.Now()
	if err := agent.configureSwarmingAutoStart(ctx, instruction.Instruction.SwarmingServer); err != nil {
		return err
	}
	if err := agent.mp.ack(ctx, agent.hostname, "GCE"); err != nil {
		return err
	}
	duration := float64(time.Since(start)) / float64(time.Second)
	instructionsAcked.Add(ctx, 1, agent.server, instruction.Instruction.SwarmingServer)
	instructionsAckedTime.Add(ctx, duration, agent.server, instruction.Instruction.SwarmingServer)
	return agent.reboot(ctx)
}
197396
func (hdr *Handler) Handle(im *imageserver.Image, params imageserver.Params) (*imageserver.Image, error) {
	enc, format, err := getEncoderFormat(im.Format, params)
	if err != nil {
		if _, ok := err.(*imageserver.ParamError); !ok {
			err = &imageserver.ImageError{Message: err.Error()}
		}
		return nil, err
	}
	if !hdr.change(im, format, enc, params) {
		return im, nil
	}
	nim, err := Decode(im)
	if err != nil {
		return nil, err
	}
	if hdr.Processor != nil {
		nim, err = hdr.Processor.Process(nim, params)
		if err != nil {
			return nil, err
		}
	}
	im, err = encode(nim, format, enc, params)
	if err != nil {
		return nil, err
	}
	return im, nil
}
254732
func (c *managedHandleImpl) Handle() (interface{}, error) {
	if atomic.LoadInt32(&c.isActive) == 0 {
		return c.handle, errors.New("Resource handle is no longer valid")
	}
	return c.handle, nil
}
1204292
func (eh guildCreateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*GuildCreate); ok {
		eh(s, t)
	}
}
926208
func (c *PairingController) Handle(cont util.Container) (util.Container, error) {
	method := PairMethodType(cont.GetByte(TagPairingMethod))
	perm := cont.GetByte(TagPermission)
	username := cont.GetString(TagUsername)
	publicKey := cont.GetBytes(TagPublicKey)

	log.Debug.Println("->     Method:", method)
	log.Debug.Println("-> Permission:", perm)
	log.Debug.Println("->   Username:", username)
	log.Debug.Println("->       LTPK:", publicKey)

	entity := db.NewEntity(username, publicKey, nil)

	out := util.NewTLV8Container()
	out.SetByte(TagSequence, 0x2)

	switch method {
	case PairingMethodDelete:
		log.Debug.Printf("Remove LTPK for client '%s'\n", username)
		c.database.DeleteEntity(entity)
	case PairingMethodAdd:
		err := c.database.SaveEntity(entity)
		if err != nil {
			log.Info.Panic(err)
			return nil, err
		}
	default:
		return nil, fmt.Errorf("Invalid pairing method type %v", method)
	}

	return out, nil
}
1327020
func (h *getStatusCache) Handle(params GetStatusParams) middleware.Responder {
	log.Debug("Handling request for /status")

	return NewGetStatusOK().WithPayload(h.GetStatusResponse())
}
331542
func (fn AddOneHandlerFunc) Handle(params AddOneParams, principal interface{}) middleware.Responder {
	return fn(params, principal)
}
1032389
func (r *PolicyReactionEvent) Handle(res chan interface{}) {
	r.d.ReactToRuleUpdates(r.wg, r.epsToBumpRevision, r.endpointsToRegen, r.newRev)
}
356886
func (fn CreateHandlerFunc) Handle(params CreateParams, principal *models.Principal) middleware.Responder {
	return fn(params, principal)
}
619898
func (fn InventoryGetHandlerFunc) Handle(params InventoryGetParams, principal interface{}) middleware.Responder {
	return fn(params, principal)
}
558769
func (c *Container) Handle(pattern string, handler http.Handler) {
	c.ServeMux.Handle(pattern, handler)
}