// BuildPredicate returns a Predicate which will evaluate a machine,
// service, or unit against the given patterns.
979392
func BuildPredicateFor(patterns []string) Predicate {

	or := func(predicates ...closurePredicate) (bool, error) {
		// Differentiate between a valid format that eliminated all
		// elements, and an invalid query.
		oneValidFmt := false
		for _, p := range predicates {
			if matches, ok, err := p(); err != nil {
				return false, err
			} else if ok {
				oneValidFmt = true
				if matches {
					return true, nil
				}
			}
		}

		if !oneValidFmt && len(predicates) > 0 {
			return false, InvalidFormatErr
		}

		return false, nil
	}

	return func(i interface{}) (bool, error) {
		switch i.(type) {
		default:
			panic(errors.Errorf("expected a machine or an applications or a unit, got %T", i))
		case *state.Machine:
			shims, err := buildMachineMatcherShims(i.(*state.Machine), patterns)
			if err != nil {
				return false, err
			}
			return or(shims...)
		case *state.Unit:
			return or(buildUnitMatcherShims(i.(*state.Unit), patterns)...)
		case *state.Application:
			shims, err := buildApplicationMatcherShims(i.(*state.Application), patterns...)
			if err != nil {
				return false, err
			}
			return or(shims...)
		}
	}
}
734692
func (p *LogicalUnionAll) PredicatePushDown(predicates []expression.Expression) (ret []expression.Expression, retPlan LogicalPlan) {
	for i, proj := range p.children {
		newExprs := make([]expression.Expression, 0, len(predicates))
		newExprs = append(newExprs, predicates...)
		retCond, newChild := proj.PredicatePushDown(newExprs)
		addSelection(p, newChild, retCond, i)
	}
	return nil, p
}
1253164
func (cb *CreateDatabaseBuilder) Build() string {
	q := fmt.Sprintf("CREATE DATABASE %s;", cb.name)
	if cb.useIt {
		q = fmt.Sprintf("%s\nUSE %s;\n", q, cb.name)
	}
	return q
}
345555
func (b *Builder) Prune(ctx context.Context, opts types.BuildCachePruneOptions) (int64, []string, error) {
	ch := make(chan *controlapi.UsageRecord)

	eg, ctx := errgroup.WithContext(ctx)

	validFilters := make(map[string]bool, 1+len(cacheFields))
	validFilters["unused-for"] = true
	validFilters["until"] = true
	validFilters["label"] = true  // TODO(tiborvass): handle label
	validFilters["label!"] = true // TODO(tiborvass): handle label!
	for k, v := range cacheFields {
		validFilters[k] = v
	}
	if err := opts.Filters.Validate(validFilters); err != nil {
		return 0, nil, err
	}

	pi, err := toBuildkitPruneInfo(opts)
	if err != nil {
		return 0, nil, err
	}

	eg.Go(func() error {
		defer close(ch)
		return b.controller.Prune(&controlapi.PruneRequest{
			All:          pi.All,
			KeepDuration: int64(pi.KeepDuration),
			KeepBytes:    pi.KeepBytes,
			Filter:       pi.Filter,
		}, &pruneProxy{
			streamProxy: streamProxy{ctx: ctx},
			ch:          ch,
		})
	})

	var size int64
	var cacheIDs []string
	eg.Go(func() error {
		for r := range ch {
			size += r.Size_
			cacheIDs = append(cacheIDs, r.ID)
		}
		return nil
	})

	if err := eg.Wait(); err != nil {
		return 0, nil, err
	}

	return size, cacheIDs, nil
}
554518
func (b *UpdateServiceBuilder) Build(c *fi.ModelBuilderContext) error {
	if b.Cluster.Spec.UpdatePolicy == nil || *b.Cluster.Spec.UpdatePolicy != kops.UpdatePolicyExternal {
		glog.Infof("UpdatePolicy not set in Cluster Spec; skipping creation of %s", ServiceName)
		return nil
	}

	for _, spec := range [][]kops.HookSpec{b.InstanceGroup.Spec.Hooks, b.Cluster.Spec.Hooks} {
		for _, hook := range spec {
			if hook.Name == ServiceName || hook.Name == ServiceName+".service" {
				glog.Infof("Detected kops Hook for '%s'; skipping creation", ServiceName)
				return nil
			}
		}
	}

	if b.Distribution == distros.DistributionCoreOS {
		glog.Infof("Detected OS %s; building %s service to disable update scheduler", ServiceName, b.Distribution)
		c.AddTask(b.buildCoreOSSystemdService())
	}

	return nil
}
904640
func (b *PlanBuilder) buildProjectionForWindow(p LogicalPlan, expr *ast.WindowFuncExpr, aggMap map[*ast.AggregateFuncExpr]int) (LogicalPlan, []property.Item, []property.Item, []expression.Expression, error) {
	b.optFlag |= flagEliminateProjection

	var items []*ast.ByItem
	if expr.Spec.Name.L != "" {
		ref, ok := b.windowSpecs[expr.Spec.Name.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(expr.Spec.Name.O)
		}
		expr.Spec = ref
	}
	spec := expr.Spec
	if spec.Ref.L != "" {
		ref, ok := b.windowSpecs[spec.Ref.L]
		if !ok {
			return nil, nil, nil, nil, ErrWindowNoSuchWindow.GenWithStackByArgs(spec.Ref.O)
		}
		err := mergeWindowSpec(&spec, &ref)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	}

	lenPartition := 0
	if spec.PartitionBy != nil {
		items = append(items, spec.PartitionBy.Items...)
		lenPartition = len(spec.PartitionBy.Items)
	}
	if spec.OrderBy != nil {
		items = append(items, spec.OrderBy.Items...)
	}
	projLen := len(p.Schema().Columns) + len(items) + len(expr.Args)
	proj := LogicalProjection{Exprs: make([]expression.Expression, 0, projLen)}.Init(b.ctx)
	schema := expression.NewSchema(make([]*expression.Column, 0, projLen)...)
	for _, col := range p.Schema().Columns {
		proj.Exprs = append(proj.Exprs, col)
		schema.Append(col)
	}

	transformer := &itemTransformer{}
	propertyItems := make([]property.Item, 0, len(items))
	for _, item := range items {
		newExpr, _ := item.Expr.Accept(transformer)
		item.Expr = newExpr.(ast.ExprNode)
		it, np, err := b.rewrite(item.Expr, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		if col, ok := it.(*expression.Column); ok {
			propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
			continue
		}
		proj.Exprs = append(proj.Exprs, it)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  it.GetType(),
		}
		schema.Append(col)
		propertyItems = append(propertyItems, property.Item{Col: col, Desc: item.Desc})
	}

	newArgList := make([]expression.Expression, 0, len(expr.Args))
	for _, arg := range expr.Args {
		newArg, np, err := b.rewrite(arg, p, aggMap, true)
		if err != nil {
			return nil, nil, nil, nil, err
		}
		p = np
		switch newArg.(type) {
		case *expression.Column, *expression.Constant:
			newArgList = append(newArgList, newArg)
			continue
		}
		proj.Exprs = append(proj.Exprs, newArg)
		col := &expression.Column{
			ColName:  model.NewCIStr(fmt.Sprintf("%d_proj_window_%d", p.ID(), schema.Len())),
			UniqueID: b.ctx.GetSessionVars().AllocPlanColumnID(),
			RetType:  newArg.GetType(),
		}
		schema.Append(col)
		newArgList = append(newArgList, col)
	}

	proj.SetSchema(schema)
	proj.SetChildren(p)
	return proj, propertyItems[:lenPartition], propertyItems[lenPartition:], newArgList, nil
}
983214
func (s *TriggerUpdate) SetPredicate(v *Predicate) *TriggerUpdate {
	s.Predicate = v
	return s
}
838811
func (p *LogicalProjection) buildSchemaByExprs() *expression.Schema {
	schema := expression.NewSchema(make([]*expression.Column, 0, p.schema.Len())...)
	for _, expr := range p.Exprs {
		if col, isCol := expr.(*expression.Column); isCol {
			schema.Append(col)
		} else {
			// If the expression is not a column, we add a column to occupy the position.
			schema.Append(&expression.Column{
				UniqueID: p.ctx.GetSessionVars().AllocPlanColumnID(),
				RetType:  expr.GetType(),
			})
		}
	}
	return schema
}
620051
func (_m *APIClient) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) {
	ret := _m.Called(ctx, opts)

	var r0 *types.BuildCachePruneReport
	if rf, ok := ret.Get(0).(func(context.Context, types.BuildCachePruneOptions) *types.BuildCachePruneReport); ok {
		r0 = rf(ctx, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*types.BuildCachePruneReport)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, types.BuildCachePruneOptions) error); ok {
		r1 = rf(ctx, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
779322
func (s *IndicesExistsTemplateService) buildURL() (string, url.Values, error) {
	// Build URL
	path, err := uritemplates.Expand("/_template/{name}", map[string]string{
		"name": s.name,
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "true")
	}
	if s.local != nil {
		params.Set("local", fmt.Sprintf("%v", *s.local))
	}
	return path, params, nil
}
885046
func (h HostPrefixBuilder) Build(r *request.Request) {
	if aws.BoolValue(r.Config.DisableEndpointHostPrefix) {
		return
	}

	var labels map[string]string
	if h.LabelsFn != nil {
		labels = h.LabelsFn()
	}

	prefix := h.Prefix
	for name, value := range labels {
		prefix = strings.Replace(prefix, "{"+name+"}", value, -1)
	}

	r.HTTPRequest.URL.Host = prefix + r.HTTPRequest.URL.Host
	if len(r.HTTPRequest.Host) > 0 {
		r.HTTPRequest.Host = prefix + r.HTTPRequest.Host
	}
}
142846
func (s *RuleUpdate) SetPredicate(v *Predicate) *RuleUpdate {
	s.Predicate = v
	return s
}
388627
func (s *Trigger) SetPredicate(v *Predicate) *Trigger {
	s.Predicate = v
	return s
}
1265394
func (p *Union) PredicatePushDown(predicates []expression.Expression) (ret []expression.Expression, retPlan LogicalPlan, err error) {
	retPlan = p
	for _, proj := range p.children {
		newExprs := make([]expression.Expression, 0, len(predicates))
		for _, cond := range predicates {
			newCond := expression.ColumnSubstitute(cond, p.GetSchema(), expression.Column2Exprs(proj.GetSchema().Columns))
			newExprs = append(newExprs, newCond)
		}
		retCond, _, err := proj.(LogicalPlan).PredicatePushDown(newExprs)
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		if len(retCond) != 0 {
			addSelection(p, proj.(LogicalPlan), retCond, p.allocator)
		}
	}
	return
}
1321137
func NewServiceAffinityPredicate(podLister algorithm.PodLister, serviceLister algorithm.ServiceLister, nodeInfo NodeInfo, labels []string) (FitPredicate, predicateMetadataProducer) {
	affinity := &ServiceAffinity{
		podLister:     podLister,
		serviceLister: serviceLister,
		nodeInfo:      nodeInfo,
		labels:        labels,
	}
	return affinity.checkServiceAffinity, affinity.serviceAffinityMetadataProducer
}
31814
func (p *pruner) buildGraph(options PrunerOptions) kerrors.Aggregate {
	p.g = genericgraph.New()

	var errs []error

	errs = append(errs, p.addImagesToGraph(options.Images)...)
	errs = append(errs, p.addImageStreamsToGraph(options.Streams, options.LimitRanges)...)
	errs = append(errs, p.addPodsToGraph(options.Pods)...)
	errs = append(errs, p.addReplicationControllersToGraph(options.RCs)...)
	errs = append(errs, p.addBuildConfigsToGraph(options.BCs)...)
	errs = append(errs, p.addBuildsToGraph(options.Builds)...)
	errs = append(errs, p.addDaemonSetsToGraph(options.DSs)...)
	errs = append(errs, p.addDeploymentsToGraph(options.Deployments)...)
	errs = append(errs, p.addDeploymentConfigsToGraph(options.DCs)...)
	errs = append(errs, p.addReplicaSetsToGraph(options.RSs)...)

	return kerrors.NewAggregate(errs)
}
982148
func (service *Service) EvaluatePrereqsTemplate(gs GetService, fc FindChildService, instanceID int) (err error) {
	log.WithFields(log.Fields{
		"servicename": service.Name,
		"serviceid": service.ID,
		"instanceid": instanceID,
	}).Debug("Evaluating Prereq scripts")

	for i, prereq := range service.Prereqs {
		err, result := service.evaluateTemplate(gs, fc, instanceID, prereq.Script)
		if err != nil {
			return err
		}
		if result != "" {
			prereq.Script = result
			service.Prereqs[i] = prereq
		}
	}
	return
}