~egtann/binp

binp/binp.go -rw-r--r-- 5.1 KiB
7746a19a — Evan Tann fix net name in test services file 5 months ago
                                                                                
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
package binp

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"sort"
)

type BoxName string
type ServiceName string

type BoxServices map[ServiceName]*Service

type Config struct {
	Services map[BoxName]BoxServices `json:"services"`
	Boxes    map[BoxName]*Box        `json:"boxes"`
}

type Service struct {
	CPU   int         `json:"cpu"`
	RAM   datasize    `json:"ram"`
	Disk  datasize    `json:"disk"`
	Net   network     `json:"net"`
	Count int         `json:"count"`
	Name  ServiceName `json:"-"`
}

type network struct {
	// Mbps required for the application, useful if the service is network
	// i/o bound. Note that this is megabits, not bytes.
	Mbps int `json:"mbps"`

	// Ports required by the service. Defining them for binp prevents
	// disparate services from binding the same port across apps.
	Ports []int `json:"ports"`
}

type Box struct {
	CPU        int                      `json:"cpu"`
	RAM        datasize                 `json:"ram"`
	Disk       datasize                 `json:"disk"`
	Net        network                  `json:"net"`
	Services   []*Service               `json:"-"`
	serviceMap map[ServiceName]struct{} `json:"-"`
	usedPorts  map[int]struct{}         `json:"-"`
}

func ParseConfig(filename string) (*Config, error) {
	fi, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("open: %w", err)
	}
	defer func() { _ = fi.Close() }()

	conf := &Config{}
	if err := json.NewDecoder(fi).Decode(conf); err != nil {
		return nil, fmt.Errorf("decode: %w", err)
	}

	return conf, nil
}

func (c *Config) packBox(
	boxName BoxName,
	boxServices map[ServiceName]*Service,
) ([]*Box, error) {
	if len(boxServices) == 0 {
		return nil, errors.New("no box services")
	}

	// Sort all services by their scores in descending order. Sort by
	// strings in the case of equal scores to ensure binp produces stable
	// output even in that scenario.
	var services []*Service
	for name, srv := range boxServices {
		srv.Name = name
		for i := 0; i < srv.Count; i++ {
			services = append(services, srv)
		}
	}
	sort.Slice(services, func(i, j int) bool {
		score1 := services[i].score()
		score2 := services[j].score()
		if score1 == score2 {
			return services[i].Name < services[j].Name
		}
		return score2 < score1
	})

	if _, ok := c.Boxes[boxName]; !ok {
		return nil, fmt.Errorf("no boxes for name: %s", boxName)
	}

	// Ensure no service is larger than any 1 box before we start packing
	newBox := func() *Box {
		b := c.Boxes[boxName]
		return &Box{
			CPU:        b.CPU,
			RAM:        b.RAM,
			Disk:       b.Disk,
			Net:        b.Net,
			serviceMap: map[ServiceName]struct{}{},
			usedPorts:  map[int]struct{}{},
		}
	}
	tmpBox := newBox()
	for _, srv := range services {
		if !srv.fitIn(tmpBox) {
			return nil, fmt.Errorf("%s does not fit", srv.Name)
		}
	}
	tmpBox = nil

	// Start with one box, and increase the number of boxes until counts
	// can be satisfied.
	for i := 1; ; i++ {
		boxes := make([]*Box, i)
		for j := 0; j < i; j++ {
			boxes[j] = newBox()
		}
		for _, srv := range services {
			boxIdx := 0
			box := boxes[boxIdx]
			for !srv.fitIn(box) {
				if boxIdx+1 >= len(boxes) {
					// Skip to the next iteration of the
					// outer loop
					goto next
				}
				boxIdx++
				box = boxes[boxIdx]
			}
			box = addService(box, srv)
		}
		return boxes, nil
	next:
	}
	msg := fmt.Sprintf("no number of boxes can fulfill the request for %s",
		boxName)
	panic(msg)
}

// Pack services into boxes.
func (c *Config) Pack() (map[BoxName][]*Box, error) {
	boxes := map[BoxName][]*Box{}
	for boxName, boxServices := range c.Services {
		bxs, err := c.packBox(boxName, boxServices)
		if err != nil {
			return nil, fmt.Errorf("pack box: %w", err)
		}
		boxes[boxName] = bxs
	}
	return boxes, nil
}

func (s *Service) score() int {
	cpu := s.CPU
	if cpu == 0 {
		cpu = 1
	}
	ram := int(s.RAM)
	if ram == 0 {
		ram = 1
	}
	mbps := s.Net.Mbps
	if mbps == 0 {
		mbps = 1
	}
	diskGB := int(s.Disk / 1024)
	if diskGB == 0 {
		diskGB = 1
	}
	return cpu * ram * diskGB * mbps
}

func (s *Service) fitIn(b *Box) bool {
	if s.CPU > b.CPU {
		return false
	}
	if s.RAM > b.RAM {
		return false
	}
	if s.Disk > b.Disk {
		return false
	}
	if s.Net.Mbps > b.Net.Mbps {
		return false
	}
	for _, p := range s.Net.Ports {
		if _, exist := b.usedPorts[p]; exist {
			return false
		}
	}
	if _, ok := b.serviceMap[s.Name]; ok {
		return false
	}
	return true
}

func addService(box *Box, srv *Service) *Box {
	box.CPU -= srv.CPU
	box.RAM -= srv.RAM
	box.Disk -= srv.Disk
	box.Net.Mbps -= srv.Net.Mbps
	box.Services = append(box.Services, srv)
	box.serviceMap[srv.Name] = struct{}{}
	for _, p := range srv.Net.Ports {
		box.usedPorts[p] = struct{}{}
	}
	return box
}

func MinBox(boxes []*Service) *Box {
	minBox := &Box{}
	for _, box := range boxes {
		if box.CPU > minBox.CPU {
			minBox.CPU = box.CPU
		}
		if box.RAM > minBox.RAM {
			minBox.RAM = box.RAM
		}
		if box.Disk > minBox.Disk {
			minBox.Disk = box.Disk
		}
		if box.Net.Mbps > minBox.Net.Mbps {
			minBox.Net.Mbps = box.Net.Mbps
		}
	}
	return minBox
}

func MaxBox(boxes []*Service) *Box {
	maxBox := &Box{}
	for _, box := range boxes {
		maxBox.CPU += box.CPU
		maxBox.RAM += box.RAM
		maxBox.Disk += box.Disk
		maxBox.Net.Mbps += box.Net.Mbps
	}
	return maxBox
}