-
Notifications
You must be signed in to change notification settings - Fork 37
/
resources.go
375 lines (315 loc) · 9.36 KB
/
resources.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package rep
import (
"errors"
"fmt"
"net/url"
"sort"
"strings"
"code.cloudfoundry.org/bbs/models"
"code.cloudfoundry.org/executor/containermetrics"
"code.cloudfoundry.org/routing-info/internalroutes"
)
var ErrorIncompatibleRootfs = errors.New("rootfs not found")
type CellState struct {
RepURL string `json:"rep_url"`
CellID string `json:"cell_id"`
CellIndex int `json:"cell_index"`
RootFSProviders RootFSProviders
AvailableResources Resources
TotalResources Resources
LRPs []LRP
Tasks []Task
StartingContainerCount int
Zone string
Evacuating bool
VolumeDrivers []string
PlacementTags []string
OptionalPlacementTags []string
ProxyMemoryAllocationMB int
}
func NewCellState(
cellID string,
cellIndex int,
repURL string,
root RootFSProviders,
avail Resources,
total Resources,
lrps []LRP,
tasks []Task,
zone string,
startingContainerCount int,
isEvac bool,
volumeDrivers []string,
placementTags []string,
optionalPlacementTags []string,
proxyMemoryAllocation int,
) CellState {
return CellState{
CellID: cellID,
CellIndex: cellIndex,
RepURL: repURL,
RootFSProviders: root,
AvailableResources: avail,
TotalResources: total,
LRPs: lrps,
Tasks: tasks,
Zone: zone,
StartingContainerCount: startingContainerCount,
Evacuating: isEvac,
VolumeDrivers: volumeDrivers,
PlacementTags: placementTags,
OptionalPlacementTags: optionalPlacementTags,
ProxyMemoryAllocationMB: proxyMemoryAllocation,
}
}
func (c *CellState) AddLRP(lrp *LRP) {
c.AvailableResources.Subtract(&lrp.Resource)
c.StartingContainerCount += 1
c.LRPs = append(c.LRPs, *lrp)
}
func (c *CellState) AddTask(task *Task) {
c.AvailableResources.Subtract(&task.Resource)
c.StartingContainerCount += 1
c.Tasks = append(c.Tasks, *task)
}
func (c *CellState) ResourceMatch(res *Resource) error {
problems := map[string]struct{}{}
if c.AvailableResources.DiskMB < res.DiskMB {
problems["disk"] = struct{}{}
}
if c.AvailableResources.MemoryMB < res.MemoryMB {
problems["memory"] = struct{}{}
}
if c.AvailableResources.Containers < 1 {
problems["containers"] = struct{}{}
}
if len(problems) == 0 {
return nil
}
return InsufficientResourcesError{Problems: problems}
}
type InsufficientResourcesError struct {
Problems map[string]struct{}
}
func (i InsufficientResourcesError) Error() string {
if len(i.Problems) == 0 {
return "insufficient resources"
}
keys := []string{}
for key := range i.Problems {
keys = append(keys, key)
}
sort.Strings(keys)
return fmt.Sprintf("insufficient resources: %s", strings.Join(keys, ", "))
}
func (c CellState) ComputeScore(res *Resource, startingContainerWeight float64) float64 {
remainingResources := c.AvailableResources.Copy()
remainingResources.Subtract(res)
startingContainerScore := float64(c.StartingContainerCount) * startingContainerWeight
return remainingResources.ComputeScore(&c.TotalResources) + startingContainerScore
}
func (c *CellState) MatchRootFS(rootfs string) bool {
rootFSURL, err := url.Parse(rootfs)
if err != nil {
return false
}
return c.RootFSProviders.Match(*rootFSURL)
}
func (c *CellState) MatchVolumeDrivers(volumeDrivers []string) bool {
for _, requestedDriver := range volumeDrivers {
found := false
for _, actualDriver := range c.VolumeDrivers {
if requestedDriver == actualDriver {
found = true
break
}
}
if !found {
return false
}
}
return true
}
func (c *CellState) MatchPlacementTags(desiredPlacementTags []string) bool {
desiredTags := toSet(desiredPlacementTags)
optionalTags := toSet(c.OptionalPlacementTags)
requiredTags := toSet(c.PlacementTags)
allTags := requiredTags.union(optionalTags)
return requiredTags.isSubset(desiredTags) && desiredTags.isSubset(allTags)
}
type placementTagSet map[string]struct{}
func (set placementTagSet) union(other placementTagSet) placementTagSet {
tags := placementTagSet{}
for k := range set {
tags[k] = struct{}{}
}
for k := range other {
tags[k] = struct{}{}
}
return tags
}
func (set placementTagSet) isSubset(other placementTagSet) bool {
for k := range set {
if _, ok := other[k]; !ok {
return false
}
}
return true
}
func toSet(slice []string) placementTagSet {
tags := placementTagSet{}
for _, k := range slice {
tags[k] = struct{}{}
}
return tags
}
type Resources struct {
MemoryMB int32
DiskMB int32
Containers int
}
func NewResources(memoryMb, diskMb int32, containerCount int) Resources {
return Resources{memoryMb, diskMb, containerCount}
}
func (r *Resources) Copy() Resources {
return *r
}
func (r *Resources) Subtract(res *Resource) {
r.MemoryMB -= res.MemoryMB
r.DiskMB -= res.DiskMB
r.Containers -= 1
}
func (r *Resources) ComputeScore(total *Resources) float64 {
fractionUsedMemory := 1.0 - float64(r.MemoryMB)/float64(total.MemoryMB)
fractionUsedDisk := 1.0 - float64(r.DiskMB)/float64(total.DiskMB)
fractionUsedContainers := 1.0 - float64(r.Containers)/float64(total.Containers)
return (fractionUsedMemory + fractionUsedDisk + fractionUsedContainers) / 3.0
}
type Resource struct {
MemoryMB int32
DiskMB int32
MaxPids int32
}
func NewResource(memoryMb, diskMb int32, maxPids int32) Resource {
return Resource{MemoryMB: memoryMb, DiskMB: diskMb, MaxPids: maxPids}
}
func (r *Resource) Valid() bool {
return r.DiskMB >= 0 && r.MemoryMB >= 0
}
func (r *Resource) Copy() Resource {
return NewResource(r.MemoryMB, r.DiskMB, r.MaxPids)
}
type PlacementConstraint struct {
PlacementTags []string
VolumeDrivers []string
RootFs string
}
func NewPlacementConstraint(rootFs string, placementTags, volumeDrivers []string) PlacementConstraint {
return PlacementConstraint{PlacementTags: placementTags, VolumeDrivers: volumeDrivers, RootFs: rootFs}
}
func (p *PlacementConstraint) Valid() bool {
return p.RootFs != ""
}
type LRP struct {
InstanceGUID string `json:"instance_guid"`
models.ActualLRPKey
PlacementConstraint
Resource
State string `json:"state"`
}
func NewLRP(instanceGUID string, key models.ActualLRPKey, res Resource, pc PlacementConstraint) LRP {
return LRP{instanceGUID, key, pc, res, ""}
}
func (lrp *LRP) Identifier() string {
return fmt.Sprintf("%s.%d", lrp.ProcessGuid, lrp.Index)
}
func (lrp *LRP) Copy() LRP {
return NewLRP(lrp.InstanceGUID, lrp.ActualLRPKey, lrp.Resource, lrp.PlacementConstraint)
}
type LRPUpdate struct {
InstanceGUID string `json:"instance_guid"`
models.ActualLRPKey
InternalRoutes internalroutes.InternalRoutes `json:"internal_routes"`
MetricTags map[string]string `json:"metric_tags"`
}
func NewLRPUpdate(instanceGUID string, key models.ActualLRPKey, internalRoutes internalroutes.InternalRoutes, metricTags map[string]string) LRPUpdate {
return LRPUpdate{
InstanceGUID: instanceGUID,
ActualLRPKey: key,
InternalRoutes: internalRoutes,
MetricTags: metricTags,
}
}
type Task struct {
TaskGuid string
Domain string
PlacementConstraint
Resource
State models.Task_State `json:"state"`
Failed bool `json:"failed"`
}
func NewTask(guid string, domain string, res Resource, pc PlacementConstraint) Task {
return Task{guid, domain, pc, res, models.Task_Invalid, false}
}
func (task *Task) Identifier() string {
return task.TaskGuid
}
func (task Task) Copy() Task {
return task
}
type Work struct {
LRPs []LRP
Tasks []Task
CellID string `json:"cell_id,omitempty"`
}
// StackPathMap maps aliases to rootFS paths on the system.
type StackPathMap map[string]string
// ErrPreloadedRootFSNotFound is returned when the given hostname of the
// rootFS could not be resolved if the scheme is the PreloadedRootFSScheme
// or the PreloadedOCIRootFSScheme. This isn't the error for when the actual
// path on the system could not be found.
var ErrPreloadedRootFSNotFound = errors.New("preloaded rootfs path not found")
// PathForRootFS resolves the hostname portion of the RootFS URL to the actual
// path to the preloaded rootFS on the system according to the StackPathMap
func (m StackPathMap) PathForRootFS(rootFS string) (string, error) {
if rootFS == "" {
return rootFS, nil
}
url, err := url.Parse(rootFS)
if err != nil {
return "", err
}
if url.Scheme == models.PreloadedRootFSScheme {
path, ok := m[url.Opaque]
if !ok {
return "", ErrPreloadedRootFSNotFound
}
return path, nil
} else if url.Scheme == models.PreloadedOCIRootFSScheme {
path, ok := m[url.Opaque]
if !ok {
return "", ErrPreloadedRootFSNotFound
}
return fmt.Sprintf("%s:%s?%s", url.Scheme, path, url.RawQuery), nil
}
return rootFS, nil
}
//go:generate counterfeiter -o auctioncellrep/auctioncellrepfakes/fake_container_metrics_provider.go . ContainerMetricsProvider
type ContainerMetricsProvider interface {
Metrics() map[string]*containermetrics.CachedContainerMetrics
}
type ContainerMetricsCollection struct {
CellID string `json:"cell_id"`
LRPs []LRPMetric `json:"lrps"`
Tasks []TaskMetric `json:"tasks"`
}
type LRPMetric struct {
InstanceGUID string `json:"instance_guid"`
ProcessGUID string `json:"process_guid"`
Index int32 `json:"index"`
containermetrics.CachedContainerMetrics
}
type TaskMetric struct {
TaskGUID string `json:"task_guid"`
containermetrics.CachedContainerMetrics
}