// ShouldContainerBeRestarted checks whether a container needs to be restarted.
// TODO(yifan): Think about how to refactor this.
171073
func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus *PodStatus) bool {
	// Get latest container status.
	status := podStatus.FindContainerStatusByName(container.Name)
	// If the container was never started before, we should start it.
	// NOTE(random-liu): If all historical containers were GC'd, we'll also return true here.
	if status == nil {
		return true
	}
	// Check whether container is running
	if status.State == ContainerStateRunning {
		return false
	}
	// Always restart container in the unknown, or in the created state.
	if status.State == ContainerStateUnknown || status.State == ContainerStateCreated {
		return true
	}
	// Check RestartPolicy for dead container
	if pod.Spec.RestartPolicy == v1.RestartPolicyNever {
		klog.V(4).Infof("Already ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
		return false
	}
	if pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure {
		// Check the exit code.
		if status.ExitCode == 0 {
			klog.V(4).Infof("Already successfully ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
			return false
		}
	}
	return true
}
244152
func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
	return daemon.Mount(container)
}
897346
func (ss *FileSubStore) shouldCompact() bool {
	// Gobal switch
	if !ss.opts.CompactEnabled {
		return false
	}
	// Check that if minimum file size is set, the client file
	// is at least at the minimum.
	if ss.opts.CompactMinFileSize > 0 && ss.fileSize < ss.opts.CompactMinFileSize {
		return false
	}
	// Check fragmentation
	frag := 0
	if ss.numRecs == 0 {
		frag = 100
	} else {
		frag = ss.delRecs * 100 / ss.numRecs
	}
	if frag < ss.opts.CompactFragmentation {
		return false
	}
	// Check that we don't compact too often
	if time.Since(ss.compactTS) < ss.compactItvl {
		return false
	}
	return true
}
933607
func (n PidMode) IsContainer() bool {
	parts := strings.SplitN(string(n), ":", 2)
	return len(parts) > 1 && parts[0] == "container"
}
855952
func (m *activeDeadlineHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse {
	if !m.pastActiveDeadline(pod) {
		return lifecycle.ShouldEvictResponse{Evict: false}
	}
	m.recorder.Eventf(pod, v1.EventTypeNormal, reason, message)
	return lifecycle.ShouldEvictResponse{Evict: true, Reason: reason, Message: message}
}
909435
func (m *podManager) shouldSyncHostports(newPod *kubehostport.PodPortMapping) []*kubehostport.PodPortMapping {
	if m.hostportSyncer == nil {
		return nil
	}

	newActiveHostports := false
	mappings := make([]*kubehostport.PodPortMapping, 0)
	for _, runningPod := range m.runningPods {
		mappings = append(mappings, runningPod.podPortMapping)
		if !newActiveHostports && hasHostPorts(runningPod.podPortMapping) {
			newActiveHostports = true
		}
	}
	if newPod != nil && hasHostPorts(newPod) {
		newActiveHostports = true
	}

	// Sync the first time a pod is started (to clear out stale mappings
	// if kubelet crashed), or when there are any/will be active hostports.
	// Otherwise don't bother.
	if !m.hostportsSynced || m.activeHostports || newActiveHostports {
		m.hostportsSynced = true
		m.activeHostports = newActiveHostports
		return mappings
	}

	return nil
}
430542
func (c *ContainerServer) HasContainer(id string) bool {
	return c.state.containers.Get(id) != nil
}
58846
func (c CgroupSpec) IsContainer() bool {
	parts := strings.SplitN(string(c), ":", 2)
	return len(parts) > 1 && parts[0] == "container"
}
389573
func shouldHealObjectOnDisk(xlErr, dataErr error, meta xlMetaV1, quorumModTime time.Time) bool {
	switch xlErr {
	case errFileNotFound:
		return true
	case errCorruptedFormat:
		return true
	}
	if xlErr == nil {
		// If xl.json was read fine but there is some problem with the part.N files.
		if dataErr == errFileNotFound {
			return true
		}
		if _, ok := dataErr.(hashMismatchError); ok {
			return true
		}
		if quorumModTime != meta.Stat.ModTime {
			return true
		}
	}
	return false
}
1316496
func (a *HostAgent) RestartContainer(cancel <-chan interface{}, serviceID string, instanceID int) error {
	logger := plog.WithFields(log.Fields{
		"serviceid":  serviceID,
		"instanceid": instanceID,
	})

	// look up the container to get the image
	ctrName := fmt.Sprintf("%s-%d", serviceID, instanceID)
	ctr, err := docker.FindContainer(ctrName)
	if err == docker.ErrNoSuchContainer {
		// container has been deleted so we will pull when the container starts
		// again.
		logger.Debug("Container not found")
		return nil
	} else if err != nil {
		logger.WithError(err).Debug("Could not look up container")
		return err
	}

	if !ctr.IsRunning() {
		// container has stopped, so we will pull when the container starts
		// again; the event monitor will handle the stopped container
		logger.Debug("Container stopped")
		return nil
	}

	go func() {
		a.setInstanceState(serviceID, instanceID, service.StatePulling)
		for {
			// relentlessly try to pull the image
			_, _, err := a.pullImage(logger, cancel, ctr.Config.Image)
			if err != nil {
				logger.WithError(err).Debug("Could not pull the service image")
				// wait 5 seconds and try again
				select {
				case <-time.After(5 * time.Second):
				case <-cancel:
					logger.Info("Cancelled image pull")
					return
				}
				continue
			}
			logger.Debug("Pulled image")
			break
		}

		a.setInstanceState(serviceID, instanceID, service.StateStopping)
		// set the container to stop; ctr.Stop() stops the container by
		// container id and not name, so if the container was stopped or
		// deleted before the pull is successful, then this will just be a
		// no-op.  The restart of the container is handled by the delegate once
		// it is notified that the container has stopped.
		if err := ctr.Stop(45 * time.Second); err != nil {
			logger.WithError(err).Debug("Could not stop container")
		}
	}()

	return nil
}
1357035
func TerminatePodWithContainerID(c KubernetesClientInterface, containerID string, sig syscall.Signal) error {
	pod, container, err := c.GetContainerStatus(containerID)
	if err != nil {
		return err
	}
	if container.State.Terminated != nil {
		log.Infof("Container %s is already terminated: %v", container.ContainerID, container.State.Terminated.String())
		return nil
	}
	if pod.Spec.HostPID {
		return fmt.Errorf("cannot terminate a hostPID Pod %s", pod.Name)
	}
	if pod.Spec.RestartPolicy != "Never" {
		return fmt.Errorf("cannot terminate pod with a %q restart policy", pod.Spec.RestartPolicy)
	}
	return c.KillContainer(pod, container, sig)
}
435248
func PodContainerRunning(containerName string) watchtools.ConditionFunc {
	return func(event watch.Event) (bool, error) {
		switch event.Type {
		case watch.Deleted:
			return false, errors.NewNotFound(schema.GroupResource{Resource: "pods"}, "")
		}
		switch t := event.Object.(type) {
		case *corev1.Pod:
			switch t.Status.Phase {
			case corev1.PodRunning, corev1.PodPending:
			case corev1.PodFailed, corev1.PodSucceeded:
				return false, kubectl.ErrPodCompleted
			default:
				return false, nil
			}
			for _, s := range t.Status.ContainerStatuses {
				if s.Name != containerName {
					continue
				}
				if s.State.Terminated != nil {
					return false, ErrContainerTerminated
				}
				return s.State.Running != nil, nil
			}
			for _, s := range t.Status.InitContainerStatuses {
				if s.Name != containerName {
					continue
				}
				if s.State.Terminated != nil {
					return false, ErrContainerTerminated
				}
				return s.State.Running != nil, nil
			}
			return false, nil
		}
		return false, nil
	}
}
146536
func (p *nfsProvisioner) ShouldProvision(claim *v1.PersistentVolumeClaim) bool {
	// As long as the export limit has not been reached we're ok to provision
	ok := p.checkExportLimit()
	if !ok {
		glog.Infof("export limit reached. skipping claim %s/%s", claim.Namespace, claim.Name)
	}
	return ok
}
559244
func (pi *pinentryInstance) shouldStoreSecret(info pinentrySecretStoreInfo) bool {
	if len(info) == 0 {
		return false
	}

	// We just want to know when the user did check the "Save in
	// Keychain" checkbox, so remove whatever pinentry put into
	// the keychain, and infer the state of the checkbox from the
	// error (since there will be no error if an entry was found
	// and deleted).
	//
	// This is a bit of a hack -- this may cause a dialog to pop
	// up saying that the client wants to access the user's
	// keychain. But this will do for now until we write our own
	// pinentry.
	query := keychain.NewItem()
	query.SetSecClass(keychain.SecClassGenericPassword)
	query.SetService(pinentryServiceName)
	query.SetAccount(string(info))
	query.SetMatchLimit(keychain.MatchLimitOne)

	// We need to query and delete by item reference because the
	// OSX keychain API only allows us to delete unowned items
	// this way.
	query.SetReturnRef(true)
	ref, err := keychain.QueryItemRef(query)
	if err != nil {
		// Default to false if there was an error.
		return false
	}
	if ref == 0 {
		// If not found, return false.
		return false
	}

	defer keychain.Release(ref)

	err = keychain.DeleteItemRef(ref)
	if err != nil {
		// Default to false if there was an error deleting.
		return false
	}

	// Entry was found and deleted.
	return true
}
656323
func (l *retryLoop) ShouldRetry(err error) bool {
	if err == zk.ErrSessionExpired || err == zk.ErrSessionMoved {
		return true
	}

	if netErr, ok := err.(net.Error); ok {
		return netErr.Timeout() || netErr.Temporary()
	}

	return false
}
431442
func isPodManagedContainer(cinfo *cadvisorapiv2.ContainerInfo) bool {
	podName := kubetypes.GetPodName(cinfo.Spec.Labels)
	podNamespace := kubetypes.GetPodNamespace(cinfo.Spec.Labels)
	managed := podName != "" && podNamespace != ""
	if !managed && podName != podNamespace {
		klog.Warningf(
			"Expect container to have either both podName (%s) and podNamespace (%s) labels, or neither.",
			podName, podNamespace)
	}
	return managed
}
636326
func isValidExecContainerAction(action *kops.ExecContainerAction) error {
	action.Image = strings.TrimSpace(action.Image)
	if action.Image == "" {
		return errors.New("the image for the hook exec action not set")
	}

	return nil
}