github.com/dkerwin/nomad@v0.3.3-0.20160525181927-74554135514b/scheduler/context.go (about)

     1  package scheduler
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  
     8  	"github.com/hashicorp/go-version"
     9  	"github.com/hashicorp/nomad/nomad/structs"
    10  )
    11  
    12  // Context is used to track contextual information used for placement
    13  type Context interface {
    14  	// State is used to inspect the current global state
    15  	State() State
    16  
    17  	// Plan returns the current plan
    18  	Plan() *structs.Plan
    19  
    20  	// Logger provides a way to log
    21  	Logger() *log.Logger
    22  
    23  	// Metrics returns the current metrics
    24  	Metrics() *structs.AllocMetric
    25  
    26  	// Reset is invoked after making a placement
    27  	Reset()
    28  
    29  	// ProposedAllocs returns the proposed allocations for a node
    30  	// which is the existing allocations, removing evictions, and
    31  	// adding any planned placements.
    32  	ProposedAllocs(nodeID string) ([]*structs.Allocation, error)
    33  
    34  	// RegexpCache is a cache of regular expressions
    35  	RegexpCache() map[string]*regexp.Regexp
    36  
    37  	// ConstraintCache is a cache of version constraints
    38  	ConstraintCache() map[string]version.Constraints
    39  
    40  	// Eligibility returns a tracker for node eligibility in the context of the
    41  	// eval.
    42  	Eligibility() *EvalEligibility
    43  }
    44  
    45  // EvalCache is used to cache certain things during an evaluation
    46  type EvalCache struct {
    47  	reCache         map[string]*regexp.Regexp
    48  	constraintCache map[string]version.Constraints
    49  }
    50  
    51  func (e *EvalCache) RegexpCache() map[string]*regexp.Regexp {
    52  	if e.reCache == nil {
    53  		e.reCache = make(map[string]*regexp.Regexp)
    54  	}
    55  	return e.reCache
    56  }
    57  func (e *EvalCache) ConstraintCache() map[string]version.Constraints {
    58  	if e.constraintCache == nil {
    59  		e.constraintCache = make(map[string]version.Constraints)
    60  	}
    61  	return e.constraintCache
    62  }
    63  
    64  // EvalContext is a Context used during an Evaluation
    65  type EvalContext struct {
    66  	EvalCache
    67  	state       State
    68  	plan        *structs.Plan
    69  	logger      *log.Logger
    70  	metrics     *structs.AllocMetric
    71  	eligibility *EvalEligibility
    72  }
    73  
    74  // NewEvalContext constructs a new EvalContext
    75  func NewEvalContext(s State, p *structs.Plan, log *log.Logger) *EvalContext {
    76  	ctx := &EvalContext{
    77  		state:   s,
    78  		plan:    p,
    79  		logger:  log,
    80  		metrics: new(structs.AllocMetric),
    81  	}
    82  	return ctx
    83  }
    84  
    85  func (e *EvalContext) State() State {
    86  	return e.state
    87  }
    88  
    89  func (e *EvalContext) Plan() *structs.Plan {
    90  	return e.plan
    91  }
    92  
    93  func (e *EvalContext) Logger() *log.Logger {
    94  	return e.logger
    95  }
    96  
    97  func (e *EvalContext) Metrics() *structs.AllocMetric {
    98  	return e.metrics
    99  }
   100  
   101  func (e *EvalContext) SetState(s State) {
   102  	e.state = s
   103  }
   104  
   105  func (e *EvalContext) Reset() {
   106  	e.metrics = new(structs.AllocMetric)
   107  }
   108  
   109  func (e *EvalContext) ProposedAllocs(nodeID string) ([]*structs.Allocation, error) {
   110  	// Get the existing allocations that are non-terminal
   111  	existingAlloc, err := e.state.AllocsByNodeTerminal(nodeID, false)
   112  	if err != nil {
   113  		return nil, err
   114  	}
   115  
   116  	// Determine the proposed allocation by first removing allocations
   117  	// that are planned evictions and adding the new allocations.
   118  	proposed := existingAlloc
   119  	if update := e.plan.NodeUpdate[nodeID]; len(update) > 0 {
   120  		proposed = structs.RemoveAllocs(existingAlloc, update)
   121  	}
   122  
   123  	// We create an index of the existing allocations so that if an inplace
   124  	// update occurs, we do not double count and we override the old allocation.
   125  	proposedIDs := make(map[string]*structs.Allocation, len(proposed))
   126  	for _, alloc := range proposed {
   127  		proposedIDs[alloc.ID] = alloc
   128  	}
   129  	for _, alloc := range e.plan.NodeAllocation[nodeID] {
   130  		proposedIDs[alloc.ID] = alloc
   131  	}
   132  
   133  	// Materialize the proposed slice
   134  	proposed = make([]*structs.Allocation, 0, len(proposedIDs))
   135  	for _, alloc := range proposedIDs {
   136  		proposed = append(proposed, alloc)
   137  	}
   138  
   139  	return proposed, nil
   140  }
   141  
   142  func (e *EvalContext) Eligibility() *EvalEligibility {
   143  	if e.eligibility == nil {
   144  		e.eligibility = NewEvalEligibility()
   145  	}
   146  
   147  	return e.eligibility
   148  }
   149  
   150  type ComputedClassFeasibility byte
   151  
   152  const (
   153  	// EvalComputedClassUnknown is the initial state until the eligibility has
   154  	// been explicitly marked to eligible/ineligible or escaped.
   155  	EvalComputedClassUnknown ComputedClassFeasibility = iota
   156  
   157  	// EvalComputedClassIneligible is used to mark the computed class as
   158  	// ineligible for the evaluation.
   159  	EvalComputedClassIneligible
   160  
   161  	// EvalComputedClassIneligible is used to mark the computed class as
   162  	// eligible for the evaluation.
   163  	EvalComputedClassEligible
   164  
   165  	// EvalComputedClassEscaped signals that computed class can not determine
   166  	// eligibility because a constraint exists that is not captured by computed
   167  	// node classes.
   168  	EvalComputedClassEscaped
   169  )
   170  
   171  // EvalEligibility tracks eligibility of nodes by computed node class over the
   172  // course of an evaluation.
   173  type EvalEligibility struct {
   174  	// job tracks the eligibility at the job level per computed node class.
   175  	job map[string]ComputedClassFeasibility
   176  
   177  	// jobEscaped marks whether constraints have escaped at the job level.
   178  	jobEscaped bool
   179  
   180  	// taskGroups tracks the eligibility at the task group level per computed
   181  	// node class.
   182  	taskGroups map[string]map[string]ComputedClassFeasibility
   183  
   184  	// tgEscapedConstraints is a map of task groups to whether constraints have
   185  	// escaped.
   186  	tgEscapedConstraints map[string]bool
   187  }
   188  
   189  // NewEvalEligibility returns an eligibility tracker for the context of an evaluation.
   190  func NewEvalEligibility() *EvalEligibility {
   191  	return &EvalEligibility{
   192  		job:                  make(map[string]ComputedClassFeasibility),
   193  		taskGroups:           make(map[string]map[string]ComputedClassFeasibility),
   194  		tgEscapedConstraints: make(map[string]bool),
   195  	}
   196  }
   197  
   198  // SetJob takes the job being evaluated and calculates the escaped constraints
   199  // at the job and task group level.
   200  func (e *EvalEligibility) SetJob(job *structs.Job) {
   201  	// Determine whether the job has escaped constraints.
   202  	e.jobEscaped = len(structs.EscapedConstraints(job.Constraints)) != 0
   203  
   204  	// Determine the escaped constraints per task group.
   205  	for _, tg := range job.TaskGroups {
   206  		constraints := tg.Constraints
   207  		for _, task := range tg.Tasks {
   208  			constraints = append(constraints, task.Constraints...)
   209  		}
   210  
   211  		e.tgEscapedConstraints[tg.Name] = len(structs.EscapedConstraints(constraints)) != 0
   212  	}
   213  }
   214  
   215  // HasEscaped returns whether any of the constraints in the passed job have
   216  // escaped computed node classes.
   217  func (e *EvalEligibility) HasEscaped() bool {
   218  	if e.jobEscaped {
   219  		return true
   220  	}
   221  
   222  	for _, escaped := range e.tgEscapedConstraints {
   223  		if escaped {
   224  			return true
   225  		}
   226  	}
   227  
   228  	return false
   229  }
   230  
   231  // GetClasses returns the tracked classes to their eligibility, across the job
   232  // and task groups.
   233  func (e *EvalEligibility) GetClasses() map[string]bool {
   234  	elig := make(map[string]bool)
   235  
   236  	// Go through the job.
   237  	for class, feas := range e.job {
   238  		switch feas {
   239  		case EvalComputedClassEligible:
   240  			elig[class] = true
   241  		case EvalComputedClassIneligible:
   242  			elig[class] = false
   243  		}
   244  	}
   245  
   246  	// Go through the task groups.
   247  	for _, classes := range e.taskGroups {
   248  		for class, feas := range classes {
   249  			switch feas {
   250  			case EvalComputedClassEligible:
   251  				elig[class] = true
   252  			case EvalComputedClassIneligible:
   253  				// Only mark as ineligible if it hasn't been marked before. This
   254  				// prevents one task group marking a class as ineligible when it
   255  				// is eligible on another task group.
   256  				if _, ok := elig[class]; !ok {
   257  					elig[class] = false
   258  				}
   259  			}
   260  		}
   261  	}
   262  
   263  	return elig
   264  }
   265  
   266  // JobStatus returns the eligibility status of the job.
   267  func (e *EvalEligibility) JobStatus(class string) ComputedClassFeasibility {
   268  	// COMPAT: Computed node class was introduced in 0.3. Clients running < 0.3
   269  	// will not have a computed class. The safest value to return is the escaped
   270  	// case, since it disables any optimization.
   271  	if e.jobEscaped || class == "" {
   272  		fmt.Println(e.jobEscaped, class)
   273  		return EvalComputedClassEscaped
   274  	}
   275  
   276  	if status, ok := e.job[class]; ok {
   277  		return status
   278  	}
   279  	return EvalComputedClassUnknown
   280  }
   281  
   282  // SetJobEligibility sets the eligibility status of the job for the computed
   283  // node class.
   284  func (e *EvalEligibility) SetJobEligibility(eligible bool, class string) {
   285  	if eligible {
   286  		e.job[class] = EvalComputedClassEligible
   287  	} else {
   288  		e.job[class] = EvalComputedClassIneligible
   289  	}
   290  }
   291  
   292  // TaskGroupStatus returns the eligibility status of the task group.
   293  func (e *EvalEligibility) TaskGroupStatus(tg, class string) ComputedClassFeasibility {
   294  	// COMPAT: Computed node class was introduced in 0.3. Clients running < 0.3
   295  	// will not have a computed class. The safest value to return is the escaped
   296  	// case, since it disables any optimization.
   297  	if class == "" {
   298  		return EvalComputedClassEscaped
   299  	}
   300  
   301  	if escaped, ok := e.tgEscapedConstraints[tg]; ok {
   302  		if escaped {
   303  			return EvalComputedClassEscaped
   304  		}
   305  	}
   306  
   307  	if classes, ok := e.taskGroups[tg]; ok {
   308  		if status, ok := classes[class]; ok {
   309  			return status
   310  		}
   311  	}
   312  	return EvalComputedClassUnknown
   313  }
   314  
   315  // SetTaskGroupEligibility sets the eligibility status of the task group for the
   316  // computed node class.
   317  func (e *EvalEligibility) SetTaskGroupEligibility(eligible bool, tg, class string) {
   318  	var eligibility ComputedClassFeasibility
   319  	if eligible {
   320  		eligibility = EvalComputedClassEligible
   321  	} else {
   322  		eligibility = EvalComputedClassIneligible
   323  	}
   324  
   325  	if classes, ok := e.taskGroups[tg]; ok {
   326  		classes[class] = eligibility
   327  	} else {
   328  		e.taskGroups[tg] = map[string]ComputedClassFeasibility{class: eligibility}
   329  	}
   330  }