github.com/andy2046/gopie@v0.7.0/pkg/drf/types.go (about)

     1  package drf
     2  
     3  import (
     4  	"container/heap"
     5  	"fmt"
     6  	"sync"
     7  )
     8  
     9  type (
    10  	// Typ represents resource type.
    11  	Typ string
    12  
    13  	// Node represents a Cluster Node.
    14  	Node struct {
    15  		index     int
    16  		allocated map[Typ]float64
    17  		demand    map[Typ]float64
    18  		dShare    float64 // Dominant Share
    19  		mu        sync.RWMutex
    20  	}
    21  
    22  	// A nodeQueue implements heap.Interface and holds Nodes.
    23  	nodeQueue []*Node
    24  
    25  	// DRF represents a DRF Cluster.
    26  	DRF struct {
    27  		clusterResource  map[Typ]float64
    28  		consumedResource map[Typ]float64
    29  		nodes            nodeQueue
    30  		mu               *sync.RWMutex
    31  	}
    32  )
    33  
    34  const (
    35  	// CPU resource.
    36  	CPU = Typ("CPU")
    37  
    38  	// MEMORY resource.
    39  	MEMORY = Typ("MEMORY")
    40  )
    41  
    42  var (
    43  	// ErrResourceSaturated when there is not enough resource to run next task.
    44  	ErrResourceSaturated = fmt.Errorf("Fatal: resource has been saturated")
    45  
    46  	// ErrEmptyResource when cluster resource is empty.
    47  	ErrEmptyResource = fmt.Errorf("Fatal: empty cluster resource")
    48  
    49  	// ErrEmptyNodes when cluster nodes is empty.
    50  	ErrEmptyNodes = fmt.Errorf("Fatal: empty cluster nodes")
    51  
    52  	// EmptyDRF is empty DRF.
    53  	EmptyDRF = DRF{}
    54  )
    55  
    56  func (nq nodeQueue) Len() int { return len(nq) }
    57  
    58  func (nq nodeQueue) Less(i, j int) bool {
    59  	// Pop the lowest dShare
    60  	return nq[i].dShare < nq[j].dShare
    61  }
    62  
    63  func (nq nodeQueue) Swap(i, j int) {
    64  	nq[i], nq[j] = nq[j], nq[i]
    65  	nq[i].index = i
    66  	nq[j].index = j
    67  }
    68  
    69  func (nq *nodeQueue) Push(x interface{}) {
    70  	n := len(*nq)
    71  	item := x.(*Node)
    72  	item.index = n
    73  	*nq = append(*nq, item)
    74  }
    75  
    76  func (nq *nodeQueue) Pop() interface{} {
    77  	old := *nq
    78  	n := len(old)
    79  	item := old[n-1]
    80  	item.index = -1 // for safety
    81  	*nq = old[0 : n-1]
    82  	return item
    83  }
    84  
    85  // update modifies an Node in the queue.
    86  func (nq *nodeQueue) update(item *Node, dShare float64) {
    87  	item.dShare = dShare
    88  	heap.Fix(nq, item.index)
    89  }