-
Notifications
You must be signed in to change notification settings - Fork 207
/
v2.go
582 lines (498 loc) · 14.6 KB
/
v2.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package sdl
import (
"errors"
"fmt"
"path"
"regexp"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
manifest "github.com/akash-network/akash-api/go/manifest/v2beta2"
dtypes "github.com/akash-network/akash-api/go/node/deployment/v1beta3"
types "github.com/akash-network/akash-api/go/node/types/v1beta3"
)
const (
nextCaseError = "error"
nextCaseTimeout = "timeout"
nextCase500 = "500"
nextCase502 = "502"
nextCase503 = "503"
nextCase504 = "504"
nextCase403 = "403"
nextCase404 = "404"
nextCase400 = "429"
nextCaseOff = "off"
defaultMaxBodySize = uint32(1048576)
upperLimitBodySize = uint32(104857600)
defaultReadTimeout = uint32(60000)
upperLimitReadTimeout = defaultReadTimeout
defaultSendTimeout = uint32(60000)
upperLimitSendTimeout = defaultSendTimeout
defaultNextTries = uint32(3)
endpointKindIP = "ip"
)
var (
defaultNextCases = []string{nextCaseError, nextCaseTimeout}
errCannotSpecifyOffAndOtherCases = errors.New("if 'off' is specified, no other cases may be specified")
errUnknownNextCase = errors.New("next case is unknown")
errHTTPOptionNotAllowed = errors.New("http option not allowed")
errSDLInvalid = errors.New("SDL invalid")
errCredentialNoHost = errors.New("Service Credentials missing Host")
errCredentialNoUsername = errors.New("Service Credentials missing Username")
errCredentialNoPassword = errors.New("Service Credentials missing Password")
)
var endpointNameValidationRegex = regexp.MustCompile(`^[[:lower:]]+[[:lower:]-_\d]+$`)
var _ SDL = (*v2)(nil)
type v2 struct {
Include []string `yaml:",omitempty"`
Services map[string]v2Service `yaml:"services,omitempty"`
Profiles v2profiles `yaml:"profiles,omitempty"`
Deployments v2Deployments `yaml:"deployment"`
Endpoints map[string]v2Endpoint `yaml:"endpoints"`
result struct {
dgroups dtypes.GroupSpecs
mgroups manifest.Groups
}
}
type v2Deployments map[string]v2Deployment
type v2Endpoint struct {
Kind string `yaml:"kind"`
}
type v2ExposeTo struct {
Service string `yaml:"service,omitempty"`
Global bool `yaml:"global,omitempty"`
HTTPOptions v2HTTPOptions `yaml:"http_options"`
IP string `yaml:"ip"`
}
type v2HTTPOptions struct {
MaxBodySize uint32 `yaml:"max_body_size"`
ReadTimeout uint32 `yaml:"read_timeout"`
SendTimeout uint32 `yaml:"send_timeout"`
NextTries uint32 `yaml:"next_tries"`
NextTimeout uint32 `yaml:"next_timeout"`
NextCases []string `yaml:"next_cases"`
}
func (ho v2HTTPOptions) asManifest() (manifest.ServiceExposeHTTPOptions, error) {
maxBodySize := ho.MaxBodySize
if maxBodySize == 0 {
maxBodySize = defaultMaxBodySize
} else if maxBodySize > upperLimitBodySize {
return manifest.ServiceExposeHTTPOptions{}, fmt.Errorf("%w: body size cannot be greater than %d bytes", errHTTPOptionNotAllowed, upperLimitBodySize)
}
readTimeout := ho.ReadTimeout
if readTimeout == 0 {
readTimeout = defaultReadTimeout
} else if readTimeout > upperLimitReadTimeout {
return manifest.ServiceExposeHTTPOptions{}, fmt.Errorf("%w: read timeout cannot be greater than %d ms", errHTTPOptionNotAllowed, upperLimitReadTimeout)
}
sendTimeout := ho.SendTimeout
if sendTimeout == 0 {
sendTimeout = defaultSendTimeout
} else if sendTimeout > upperLimitSendTimeout {
return manifest.ServiceExposeHTTPOptions{}, fmt.Errorf("%w: send timeout cannot be greater than %d ms", errHTTPOptionNotAllowed, upperLimitSendTimeout)
}
nextTries := ho.NextTries
if nextTries == 0 {
nextTries = defaultNextTries
}
nextCases := ho.NextCases
if len(nextCases) == 0 {
nextCases = defaultNextCases
} else {
for _, nextCase := range nextCases {
switch nextCase {
case nextCaseOff:
if len(nextCases) != 1 {
return manifest.ServiceExposeHTTPOptions{}, errCannotSpecifyOffAndOtherCases
}
case nextCaseError:
case nextCaseTimeout:
case nextCase500:
case nextCase502:
case nextCase503:
case nextCase504:
case nextCase403:
case nextCase404:
case nextCase400:
default:
return manifest.ServiceExposeHTTPOptions{}, fmt.Errorf("%w: %q", errUnknownNextCase, nextCase)
}
}
}
return manifest.ServiceExposeHTTPOptions{
MaxBodySize: maxBodySize,
ReadTimeout: readTimeout,
SendTimeout: sendTimeout,
NextTries: nextTries,
NextTimeout: ho.NextTimeout,
NextCases: nextCases,
}, nil
}
type v2Expose struct {
Port uint32
As uint32
Proto string `yaml:"proto,omitempty"`
To []v2ExposeTo `yaml:"to,omitempty"`
Accept v2Accept `yaml:"accept"`
HTTPOptions v2HTTPOptions `yaml:"http_options"`
}
type v2Exposes []v2Expose
type v2Dependency struct {
Service string `yaml:"service"`
}
type v2ServiceParams struct {
Storage map[string]v2ServiceStorageParams `yaml:"storage,omitempty"`
}
type v2Service struct {
Image string
Command []string `yaml:",omitempty"`
Args []string `yaml:",omitempty"`
Env []string `yaml:",omitempty"`
Expose v2Exposes `yaml:",omitempty"`
Dependencies []v2Dependency `yaml:",omitempty"`
Params *v2ServiceParams `yaml:",omitempty"`
Credentials *v2ServiceCredentials `yaml:",omitempty"`
}
type v2ServiceCredentials struct {
Host string `yaml:",omitempty"`
Email string `yaml:",omitempty"`
Username string `yaml:",omitempty"`
Password string `yaml:",omitempty"`
}
func (c v2ServiceCredentials) validate() error {
if strings.TrimSpace(c.Host) == "" {
return errCredentialNoHost
}
if strings.TrimSpace(c.Username) == "" {
return errCredentialNoUsername
}
if strings.TrimSpace(c.Password) == "" {
return errCredentialNoPassword
}
return nil
}
type v2ServiceDeployment struct {
// Compute profile name
Profile string
// Number of instances
Count uint32
}
// placement-profile -> { compute-profile, count }
type v2Deployment map[string]v2ServiceDeployment
type v2ProfileCompute struct {
Resources *v2ComputeResources `yaml:"resources,omitempty"`
}
type v2ProfilePlacement struct {
Attributes v2PlacementAttributes `yaml:"attributes"`
SignedBy types.SignedBy `yaml:"signedBy"`
Pricing v2PlacementPricing `yaml:"pricing"`
}
type v2profiles struct {
Compute map[string]v2ProfileCompute `yaml:"compute"`
Placement map[string]v2ProfilePlacement `yaml:"placement"`
}
func (sdl *v2) DeploymentGroups() (dtypes.GroupSpecs, error) {
return sdl.result.dgroups, nil
}
func (sdl *v2) Manifest() (manifest.Manifest, error) {
return manifest.Manifest(sdl.result.mgroups), nil
}
// Version creates the deterministic Deployment Version hash from the SDL.
func (sdl *v2) Version() ([]byte, error) {
return manifest.Manifest(sdl.result.mgroups).Version()
}
func (sdl *v2) UnmarshalYAML(node *yaml.Node) error {
result := v2{}
loop:
for i := 0; i < len(node.Content); i += 2 {
var val interface{}
switch node.Content[i].Value {
case "include":
val = &result.Include
case "services":
val = &result.Services
case "profiles":
val = &result.Profiles
case "deployment":
val = &result.Deployments
case "endpoints":
val = &result.Endpoints
case sdlVersionField:
// version is already verified
continue loop
default:
return fmt.Errorf("sdl: unexpected field %s", node.Content[i].Value)
}
if err := node.Content[i+1].Decode(val); err != nil {
return err
}
}
if err := result.buildGroups(); err != nil {
return err
}
*sdl = result
return nil
}
func (sdl *v2) validate() error {
for endpointName, endpoint := range sdl.Endpoints {
if !endpointNameValidationRegex.MatchString(endpointName) {
return fmt.Errorf(
"%w: endpoint named %q is not a valid name",
errSDLInvalid,
endpointName,
)
}
if len(endpoint.Kind) == 0 {
return fmt.Errorf("%w: endpoint named %q has no kind", errSDLInvalid, endpointName)
}
// Validate endpoint kind, there is only one allowed value for now
if endpoint.Kind != endpointKindIP {
return fmt.Errorf(
"%w: endpoint named %q, unknown kind %q",
errSDLInvalid,
endpointName,
endpoint.Kind,
)
}
}
endpointsUsed := make(map[string]struct{})
portsUsed := make(map[string]string)
for _, svcName := range sdl.Deployments.svcNames() {
depl := sdl.Deployments[svcName]
for _, placementName := range v2DeploymentPlacementNames(depl) {
svcdepl := depl[placementName]
compute, ok := sdl.Profiles.Compute[svcdepl.Profile]
if !ok {
return fmt.Errorf(
"%w: %v.%v: no compute profile named %v",
errSDLInvalid,
svcName,
placementName,
svcdepl.Profile,
)
}
infra, ok := sdl.Profiles.Placement[placementName]
if !ok {
return fmt.Errorf(
"%w: %v.%v: no placement profile named %v",
errSDLInvalid,
svcName,
placementName,
placementName,
)
}
if _, ok := infra.Pricing[svcdepl.Profile]; !ok {
return fmt.Errorf(
"%w: %v.%v: no pricing for profile %v",
errSDLInvalid,
svcName,
placementName,
svcdepl.Profile,
)
}
svc, ok := sdl.Services[svcName]
if !ok {
return fmt.Errorf(
"%w: %v.%v: no service profile named %v",
errSDLInvalid,
svcName,
placementName,
svcName,
)
}
if svc.Credentials != nil {
if err := svc.Credentials.validate(); err != nil {
return fmt.Errorf(
"%w: %v.%v: %v",
errSDLInvalid,
svcName,
placementName,
err,
)
}
}
for _, serviceExpose := range svc.Expose {
for _, to := range serviceExpose.To {
// Check to see if an IP endpoint is also specified
if len(to.IP) != 0 {
if !to.Global {
return fmt.Errorf(
"%w: error on %q if an IP is declared the directive must be declared as global",
errSDLInvalid,
svcName,
)
}
endpoint, endpointExists := sdl.Endpoints[to.IP]
if !endpointExists {
return fmt.Errorf(
"%w: error on service %q no endpoint named %q exists",
errSDLInvalid,
svcName,
to.IP,
)
}
if endpoint.Kind != endpointKindIP {
return fmt.Errorf(
"%w: error on service %q endpoint %q has type %q, should be %q",
errSDLInvalid,
svcName,
to.IP,
endpoint.Kind,
endpointKindIP,
)
}
endpointsUsed[to.IP] = struct{}{}
// Endpoint exists. Now check for port collisions across a single endpoint, port, & protocol
portKey := fmt.Sprintf(
"%s-%d-%s",
to.IP,
serviceExpose.As,
serviceExpose.Proto,
)
otherServiceName, inUse := portsUsed[portKey]
if inUse {
return fmt.Errorf(
"%w: IP endpoint %q port: %d protocol: %s specified by service %q already in use by %q",
errSDLInvalid,
to.IP,
serviceExpose.Port,
serviceExpose.Proto,
svcName,
otherServiceName,
)
}
portsUsed[portKey] = svcName
}
}
}
// validate storage's attributes and parameters
volumes := make(map[string]v2ResourceStorage)
for _, volume := range compute.Resources.Storage {
// making deepcopy here as we gonna merge compute attributes and service parameters for validation below
attr := make(v2StorageAttributes, len(volume.Attributes))
copy(attr, volume.Attributes)
volumes[volume.Name] = v2ResourceStorage{
Name: volume.Name,
Quantity: volume.Quantity,
Attributes: attr,
}
}
attr := make(map[string]string)
mounts := make(map[string]string)
if svc.Params != nil {
for name, params := range svc.Params.Storage {
if _, exists := volumes[name]; !exists {
return fmt.Errorf(
"%w: service \"%s\" references to no-existing compute volume named \"%s\"",
errSDLInvalid,
svcName,
name,
)
}
if !path.IsAbs(params.Mount) {
return fmt.Errorf(
"%w: invalid value for \"service.%s.params.%s.mount\" parameter. expected absolute path",
errSDLInvalid,
svcName,
name,
)
}
attr[StorageAttributeMount] = params.Mount
attr[StorageAttributeReadOnly] = strconv.FormatBool(params.ReadOnly)
mount := attr[StorageAttributeMount]
if vlname, exists := mounts[mount]; exists {
if mount == "" {
return errStorageMultipleRootEphemeral
}
return fmt.Errorf(
"%w: mount %q already in use by volume %q",
errStorageDupMountPoint,
mount,
vlname,
)
}
mounts[mount] = name
}
}
for name, volume := range volumes {
for _, nd := range types.Attributes(volume.Attributes) {
attr[nd.Key] = nd.Value
}
persistent, _ := strconv.ParseBool(attr[StorageAttributePersistent])
if persistent && attr[StorageAttributeMount] == "" {
return fmt.Errorf(
"%w: compute.storage.%s has persistent=true which requires service.%s.params.storage.%s to have mount",
errSDLInvalid,
name,
svcName,
name,
)
}
}
}
}
for endpointName := range sdl.Endpoints {
_, inUse := endpointsUsed[endpointName]
if !inUse {
return fmt.Errorf(
"%w: endpoint %q declared but never used",
errSDLInvalid,
endpointName,
)
}
}
return nil
}
func (sdl *v2) computeEndpointSequenceNumbers() map[string]uint32 {
var endpointNames []string
res := make(map[string]uint32)
for _, serviceName := range sdl.Deployments.svcNames() {
for _, expose := range sdl.Services[serviceName].Expose {
for _, to := range expose.To {
if to.Global && len(to.IP) == 0 {
continue
}
endpointNames = append(endpointNames, to.IP)
}
}
}
if len(endpointNames) == 0 {
return res
}
// Make the assignment stable
sort.Strings(endpointNames)
// Start at zero, so the first assigned one is 1
endpointSeqNumber := uint32(0)
for _, name := range endpointNames {
endpointSeqNumber++
seqNo := endpointSeqNumber
res[name] = seqNo
}
return res
}
func (sdl v2Deployments) svcNames() []string {
names := make([]string, 0, len(sdl))
for name := range sdl {
names = append(names, name)
}
sort.Strings(names)
return names
}
// placementNames stable ordered placement names
func (sdl v2Deployment) placementNames() []string {
names := make([]string, 0, len(sdl))
for name := range sdl {
names = append(names, name)
}
sort.Strings(names)
return names
}
func v2DeploymentPlacementNames(m v2Deployment) []string {
names := make([]string, 0, len(m))
for name := range m {
names = append(names, name)
}
sort.Strings(names)
return names
}