// EnsureImageComponentLayerNode adds a graph node for the image layer if it does not already exist.
324557
func EnsureImageComponentManifestNode(g osgraph.MutableUniqueGraph, name string) graph.Node {
	return ensureImageComponentNode(g, name, ImageComponentTypeManifest)
}
994208
func (i *Image) LayerURLs(id string) []string {
	var urls []string
	for _, ep := range i.endpoints {
		urls = append(urls, fmt.Sprintf("%s://%s/v1/images/%s/layer", i.scheme, ep, id))
	}
	return urls
}
1315882
func (a *Agent) EnableNodeMaintenance(reason, token string) {
	// Ensure node maintenance is not already enabled
	if _, ok := a.State.Checks()[structs.NodeMaint]; ok {
		return
	}

	// Use a default notes value
	if reason == "" {
		reason = defaultNodeMaintReason
	}

	// Create and register the node maintenance check
	check := &structs.HealthCheck{
		Node:    a.config.NodeName,
		CheckID: structs.NodeMaint,
		Name:    "Node Maintenance Mode",
		Notes:   reason,
		Status:  api.HealthCritical,
	}
	a.AddCheck(check, nil, true, token, ConfigSourceLocal)
	a.logger.Printf("[INFO] agent: Node entered maintenance mode")
}
879780
func Convert_v1_ImageLayerData_To_image_ImageLayerData(in *v1.ImageLayerData, out *image.ImageLayerData, s conversion.Scope) error {
	return autoConvert_v1_ImageLayerData_To_image_ImageLayerData(in, out, s)
}
579177
func EnsureDaemonSetNode(g osgraph.MutableUniqueGraph, ds *kappsv1.DaemonSet) *DaemonSetNode {
	dsName := DaemonSetNodeName(ds)
	dsNode := osgraph.EnsureUnique(
		g,
		dsName,
		func(node osgraph.Node) graph.Node {
			return &DaemonSetNode{Node: node, DaemonSet: ds, IsFound: true}
		},
	).(*DaemonSetNode)

	podTemplateSpecNode := EnsurePodTemplateSpecNode(g, &ds.Spec.Template, ds.Namespace, dsName)
	g.AddEdge(dsNode, podTemplateSpecNode, osgraph.ContainsEdgeKind)

	return dsNode
}
393847
func EnsureJobNode(g osgraph.MutableUniqueGraph, job *batchv1.Job) *JobNode {
	jobNodeName := JobNodeName(job)
	jobNode := osgraph.EnsureUnique(g,
		jobNodeName,
		func(node osgraph.Node) graph.Node {
			return &JobNode{node, job, true}
		},
	).(*JobNode)

	jobSpecNode := EnsureJobSpecNode(g, &job.Spec, job.Namespace, jobNodeName)
	g.AddEdge(jobNode, jobSpecNode, osgraph.ContainsEdgeKind)

	return jobNode
}
295114
func GetTopLevelContainerNode(g Graph, containedNode graph.Node) graph.Node {
	// my kingdom for a LinkedHashSet
	visited := map[int]bool{}
	prevContainingNode := containedNode

	for {
		visited[prevContainingNode.ID()] = true
		currContainingNode := GetContainingNode(g, prevContainingNode)

		if currContainingNode == nil {
			return prevContainingNode
		}
		if _, alreadyVisited := visited[currContainingNode.ID()]; alreadyVisited {
			panic(fmt.Sprintf("contains cycle in %v", visited))
		}

		prevContainingNode = currContainingNode
	}
}
1106023
func shouldIncludeNode(eCtx *executionContext, directives []*ast.Directive) bool {
	var (
		skipAST, includeAST *ast.Directive
		argValues           map[string]interface{}
	)
	for _, directive := range directives {
		if directive == nil || directive.Name == nil {
			continue
		}
		switch directive.Name.Value {
		case SkipDirective.Name:
			skipAST = directive
		case IncludeDirective.Name:
			includeAST = directive
		}
	}
	// precedence: skipAST > includeAST
	if skipAST != nil {
		argValues = getArgumentValues(SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues)
		if skipIf, ok := argValues["if"].(bool); ok && skipIf {
			return false // excluded selectionSet's fields
		}
	}
	if includeAST != nil {
		argValues = getArgumentValues(IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues)
		if includeIf, ok := argValues["if"].(bool); ok && !includeIf {
			return false // excluded selectionSet's fields
		}
	}
	return true
}
1082451
func addComponentReferencingStreams(
	g genericgraph.Graph,
	components ComponentRetentions,
	referencingImages map[*imagegraph.ImageNode]struct{},
	referencingStreams map[*imagegraph.ImageStreamNode]struct{},
	processedImages map[*imagegraph.ImageNode]*Job,
	comp *imagegraph.ImageComponentNode,
) (blocked bool) {
streamLoop:
	for stream := range referencingStreams {
		refCounter := 0
		markedForDeletionCounter := 0

		for image := range referencingImages {
			edge := g.Edge(stream, image)
			if edge == nil {
				continue
			}
			kinds := g.EdgeKinds(edge)
			// tagged not prunable image -> keep the component in the stream
			if kinds.Has(ReferencedImageEdgeKind) {
				components.AddReferencingStreams(comp, false, stream)
				continue streamLoop
			}
			if !kinds.Has(WeakReferencedImageEdgeKind) {
				continue
			}

			refCounter++
			if _, processed := processedImages[image]; processed {
				markedForDeletionCounter++
			}

			if refCounter-markedForDeletionCounter > 1 {
				components.AddReferencingStreams(comp, false, stream)
				continue streamLoop
			}
		}

		switch {
		// there's just one remaining strong reference from the stream -> unlink
		case refCounter < 2:
			components.AddReferencingStreams(comp, true, stream)
		// there's just one remaining strong reference and at least one another reference now being
		// dereferenced in a running job -> wait until it completes
		case refCounter-markedForDeletionCounter < 2:
			return true
		// not yet prunable
		default:
			components.AddReferencingStreams(comp, false, stream)
		}
	}

	return false
}
865513
func (i *ImageService) CreateLayer(container *container.Container, initFunc layer.MountInit) (layer.RWLayer, error) {
	var layerID layer.ChainID
	if container.ImageID != "" {
		img, err := i.imageStore.Get(container.ImageID)
		if err != nil {
			return nil, err
		}
		layerID = img.RootFS.ChainID()
	}

	rwLayerOpts := &layer.CreateRWLayerOpts{
		MountLabel: container.MountLabel,
		InitFunc:   initFunc,
		StorageOpt: container.HostConfig.StorageOpt,
	}

	// Indexing by OS is safe here as validation of OS has already been performed in create() (the only
	// caller), and guaranteed non-nil
	return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts)
}
1353329
func EnsureReplicationControllerNode(g osgraph.MutableUniqueGraph, rc *corev1.ReplicationController) *ReplicationControllerNode {
	rcNodeName := ReplicationControllerNodeName(rc)
	rcNode := osgraph.EnsureUnique(g,
		rcNodeName,
		func(node osgraph.Node) graph.Node {
			return &ReplicationControllerNode{node, rc, true}
		},
	).(*ReplicationControllerNode)

	rcSpecNode := EnsureReplicationControllerSpecNode(g, &rc.Spec, rc.Namespace, rcNodeName)
	g.AddEdge(rcNode, rcSpecNode, osgraph.ContainsEdgeKind)

	return rcNode
}
1157851
func (s *Store) ensureServiceTxn(tx *memdb.Txn, idx uint64, node string, svc *structs.NodeService) error {
	// Check for existing service
	existing, err := tx.First("services", "id", node, svc.ID)
	if err != nil {
		return fmt.Errorf("failed service lookup: %s", err)
	}

	if err = structs.ValidateMetadata(svc.Meta, false); err != nil {
		return fmt.Errorf("Invalid Service Meta for node %s and serviceID %s: %v", node, svc.ID, err)
	}
	// Create the service node entry and populate the indexes. Note that
	// conversion doesn't populate any of the node-specific information.
	// That's always populated when we read from the state store.
	entry := svc.ToServiceNode(node)
	// Get the node
	n, err := tx.First("nodes", "id", node)
	if err != nil {
		return fmt.Errorf("failed node lookup: %s", err)
	}
	if n == nil {
		return ErrMissingNode
	}
	if existing != nil {
		serviceNode := existing.(*structs.ServiceNode)
		entry.CreateIndex = serviceNode.CreateIndex
		entry.ModifyIndex = serviceNode.ModifyIndex
		// We cannot return here because: we want to keep existing behavior (ex: failed node lookup -> ErrMissingNode)
		// It might be modified in future, but it requires changing many unit tests
		// Enforcing saving the entry also ensures that if we add default values in .ToServiceNode()
		// those values will be saved even if node is not really modified for a while.
		if entry.IsSameService(serviceNode) {
			return nil
		}
	} else {
		entry.CreateIndex = idx
	}
	entry.ModifyIndex = idx

	// Insert the service and update the index
	if err := tx.Insert("services", entry); err != nil {
		return fmt.Errorf("failed inserting service: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"services", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{serviceIndexName(svc.Service), idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}
1045280
func ValidComponent(el ClusterComponent, components []ClusterComponent) bool {
	for _, v := range components {
		if el == v {
			return true
		}
	}
	return false
}
708029
func ValidateNode(node *api.Node) field.ErrorList {
	allErrs := ValidateObjectMeta(&node.ObjectMeta, false, ValidateNodeName, field.NewPath("metadata"))

	// Only validate spec. All status fields are optional and can be updated later.

	// external ID is required.
	if len(node.Spec.ExternalID) == 0 {
		allErrs = append(allErrs, field.Required(field.NewPath("spec", "externalID"), ""))
	}

	// TODO(rjnagal): Ignore PodCIDR till its completely implemented.
	return allErrs
}
833616
func (d *Driver) getLayerChain(id string) ([]string, error) {
	jPath := filepath.Join(d.dir(id), "layerchain.json")
	content, err := ioutil.ReadFile(jPath)
	if os.IsNotExist(err) {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("Unable to read layerchain file - %s", err)
	}

	var layerChain []string
	err = json.Unmarshal(content, &layerChain)
	if err != nil {
		return nil, fmt.Errorf("Failed to unmarshall layerchain json - %s", err)
	}

	return layerChain, nil
}
56815
func (c *ImageComponent) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		Type            FlexComponentType        `json:"type"`
		URL             string                   `json:"url"`
		Flex            *int                     `json:"flex,omitempty"`
		Margin          FlexComponentMarginType  `json:"margin,omitempty"`
		Align           FlexComponentAlignType   `json:"align,omitempty"`
		Gravity         FlexComponentGravityType `json:"gravity,omitempty"`
		Size            FlexImageSizeType        `json:"size,omitempty"`
		AspectRatio     FlexImageAspectRatioType `json:"aspectRatio,omitempty"`
		AspectMode      FlexImageAspectModeType  `json:"aspectMode,omitempty"`
		BackgroundColor string                   `json:"backgroundColor,omitempty"`
		Action          TemplateAction           `json:"action,omitempty"`
	}{
		Type:            FlexComponentTypeImage,
		URL:             c.URL,
		Flex:            c.Flex,
		Margin:          c.Margin,
		Align:           c.Align,
		Gravity:         c.Gravity,
		Size:            c.Size,
		AspectRatio:     c.AspectRatio,
		AspectMode:      c.AspectMode,
		BackgroundColor: c.BackgroundColor,
		Action:          c.Action,
	})
}
738214
func (r ComponentReferences) ImageComponentRefs() (refs ComponentReferences) {
	return r.filter(func(ref ComponentReference) bool {
		if ref.Input().ScratchImage {
			return true
		}
		return ref.Input() != nil && ref.Input().ResolvedMatch != nil && ref.Input().ResolvedMatch.IsImage()
	})
}