-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeployment.go
More file actions
619 lines (527 loc) · 19.7 KB
/
deployment.go
File metadata and controls
619 lines (527 loc) · 19.7 KB
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package api
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"github.com/moonrhythm/validator"
)
type Deployment interface {
Deploy(ctx context.Context, m *DeploymentDeploy) (*Empty, error)
List(ctx context.Context, m *DeploymentList) (*DeploymentListResult, error)
Get(ctx context.Context, m *DeploymentGet) (*DeploymentItem, error)
Revisions(ctx context.Context, m *DeploymentRevisions) (*DeploymentRevisionsResult, error)
Resume(ctx context.Context, m *DeploymentResume) (*Empty, error)
Pause(ctx context.Context, m *DeploymentPause) (*Empty, error)
Rollback(ctx context.Context, m *DeploymentRollback) (*Empty, error)
Delete(ctx context.Context, m *DeploymentDelete) (*Empty, error)
Metrics(ctx context.Context, m *DeploymentMetrics) (*DeploymentMetricsResult, error)
}
type DeploymentType int
const (
_ DeploymentType = iota
DeploymentTypeWebService
DeploymentTypeWorker
DeploymentTypeCronJob
DeploymentTypeTCPService
DeploymentTypeInternalTCPService
)
var allDeploymentTypes = []DeploymentType{
DeploymentTypeWebService,
DeploymentTypeWorker,
DeploymentTypeCronJob,
DeploymentTypeTCPService,
DeploymentTypeInternalTCPService,
}
var validDeploymentType = func() map[DeploymentType]bool {
m := map[DeploymentType]bool{}
for _, t := range allDeploymentTypes {
m[t] = true
}
return m
}()
func ParseDeploymentTypeString(s string) DeploymentType {
for _, t := range allDeploymentTypes {
if t.String() == s {
return t
}
}
return 0
}
func (t DeploymentType) String() string {
switch t {
case DeploymentTypeWebService:
return "WebService"
case DeploymentTypeWorker:
return "Worker"
case DeploymentTypeCronJob:
return "CronJob"
case DeploymentTypeTCPService:
return "TCPService"
case DeploymentTypeInternalTCPService:
return "InternalTCPService"
default:
return ""
}
}
func (t DeploymentType) Text() string {
switch t {
case DeploymentTypeWebService:
return "Web Service"
case DeploymentTypeWorker:
return "Worker"
case DeploymentTypeCronJob:
return "CronJob"
case DeploymentTypeTCPService:
return "TCP Service"
case DeploymentTypeInternalTCPService:
return "Internal TCP Service"
default:
return ""
}
}
func (t DeploymentType) Int() int {
return int(t)
}
func (t DeploymentType) IsZero() bool {
return t == 0
}
func (t DeploymentType) Valid() bool {
// zero value is valid
if t == 0 {
return true
}
return validDeploymentType[t]
}
func (t *DeploymentType) parseString(s string) error {
if s == "" {
*t = 0
return nil
}
*t = ParseDeploymentTypeString(s)
if t.IsZero() {
return fmt.Errorf("invalid deployment type")
}
return nil
}
func (t DeploymentType) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
func (t *DeploymentType) UnmarshalJSON(b []byte) error {
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
return t.parseString(s)
}
func (t DeploymentType) MarshalYAML() (any, error) {
return t.String(), nil
}
func (t *DeploymentType) UnmarshalYAML(unmarshal func(any) error) error {
var s string
err := unmarshal(&s)
if err != nil {
return err
}
return t.parseString(s)
}
func (t DeploymentType) HasExternalTCPAddress() bool {
switch t {
default:
return false
case DeploymentTypeTCPService:
return true
}
}
func (t DeploymentType) HasInternalTCPAddress() bool {
switch t {
default:
return false
case DeploymentTypeWebService:
return true
case DeploymentTypeTCPService:
return true
case DeploymentTypeInternalTCPService:
return true
}
}
type DeploymentProtocol string
const (
DeploymentProtocolHTTP = "http"
DeploymentProtocolHTTPS = "https"
DeploymentProtocolH2C = "h2c"
)
var allDeploymentProtocol = []DeploymentProtocol{
DeploymentProtocolHTTP,
DeploymentProtocolHTTPS,
DeploymentProtocolH2C,
}
var validDeploymentProtocol = func() map[DeploymentProtocol]bool {
m := map[DeploymentProtocol]bool{}
for _, t := range allDeploymentProtocol {
m[t] = true
}
return m
}()
type ResourceItem struct {
CPU string `json:"cpu" yaml:"cpu"`
Memory string `json:"memory" yaml:"memory"`
}
type DeploymentResource struct {
Requests ResourceItem `json:"requests" yaml:"requests"`
Limits ResourceItem `json:"limits" yaml:"limits"`
}
type DeploymentDeploy struct {
Project string `json:"project" yaml:"project"`
Location string `json:"location" yaml:"location"`
Name string `json:"name" yaml:"name"`
Image string `json:"image" yaml:"image"`
MinReplicas *int `json:"minReplicas" yaml:"minReplicas"`
MaxReplicas *int `json:"maxReplicas" yaml:"maxReplicas"`
Type DeploymentType `json:"type" yaml:"type"`
Port *int `json:"port" yaml:"port"`
Protocol *DeploymentProtocol `json:"protocol" yaml:"protocol"` // protocol for WebService
Internal *bool `json:"internal" yaml:"internal"` // run WebService as internal service
Env map[string]string `json:"env" yaml:"env"` // override all env
AddEnv map[string]string `json:"addEnv" yaml:"addEnv"` // add env to old revision env
RemoveEnv []string `json:"removeEnv" yaml:"removeEnv"` // remove env from old revision env
Command []string `json:"command" yaml:"command"`
Args []string `json:"args" yaml:"args"`
WorkloadIdentity *string `json:"workloadIdentity" yaml:"workloadIdentity"` // workload identity name
PullSecret *string `json:"pullSecret" yaml:"pullSecret"` // pull secret name
Disk *DeploymentDisk `json:"disk" yaml:"disk"` // type=Stateful
Schedule *string `json:"schedule" yaml:"schedule"` // type=CronJob
Resources *DeploymentResource `json:"resources" yaml:"resources"`
MountData map[string]string `json:"mountData" yaml:"mountData"`
Sidecars []*Sidecar `json:"sidecars" yaml:"sidecars"`
}
type DeploymentDisk struct {
Name string `json:"name" yaml:"name"`
MountPath string `json:"mountPath" yaml:"mountPath"`
SubPath string `json:"subPath" yaml:"subPath"`
}
func (m *DeploymentDeploy) Valid() error {
m.Name = strings.TrimSpace(m.Name)
m.Image = strings.ReplaceAll(m.Image, " ", "") // remove all space in image
m.Image = strings.ReplaceAll(m.Image, "\t", "") // remove all tab character
// TODO: autofill location until all user migrate
if m.Location == "" {
m.Location = "gke.cluster-rcf2"
}
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
{
cnt := utf8.RuneCountInString(m.Name)
v.Mustf(cnt >= MinNameLength && cnt <= MaxNameLength, "name must have length between %d-%d characters", MinNameLength, MaxNameLength)
}
if v.Must(m.Image != "", "image required") {
v.Must(validImage(m.Image), "invalid image")
}
// validate replicas if provided
if m.MinReplicas != nil {
v.Mustf(*m.MinReplicas >= 0 && *m.MinReplicas <= DeploymentMaxReplicas, "min replicas value must be in range [%d, %d]", 0, DeploymentMaxReplicas)
}
if m.MaxReplicas != nil {
v.Mustf(*m.MaxReplicas >= 0 && *m.MaxReplicas <= DeploymentMaxReplicas, "max replicas value must be in range [%d, %d]", 0, DeploymentMaxReplicas)
}
if m.MinReplicas != nil && m.MaxReplicas != nil {
v.Must(*m.MinReplicas <= *m.MaxReplicas, "max replicas must higher or equal min replicas")
}
// feature not support autoscaling
if m.MinReplicas != nil && m.MaxReplicas != nil && *m.MinReplicas != *m.MaxReplicas {
if m.Disk != nil {
v.Mustf(m.Disk.Name == "", "using disk not support auto-scaling")
}
}
// validate disk
if m.Disk != nil && m.Disk.Name != "" {
v.Mustf(m.Disk.MountPath != "", "disk mount path required")
if m.Disk.SubPath != "" {
v.Mustf(!filepath.IsAbs(m.Disk.SubPath), "disk sub path must be absolute path")
}
}
// validate mount data
var totalDataSize int
for path, data := range m.MountData {
l := len(data)
v.Must(strings.HasPrefix(path, "/"), "mountData must be absolute path")
v.Must(l < 10*1024, "mountData value must less than 10KiB")
totalDataSize += l
}
v.Must(totalDataSize < 500*1024, "mountData all values must less than 500KiB")
// validate type
if !m.Type.IsZero() {
v.Must(m.Type.Valid(), "invalid type")
switch m.Type {
case DeploymentTypeWebService:
if v.Must(m.Port != nil, "port required") {
v.Must(*m.Port > 0, "invalid port")
}
if m.Protocol != nil {
v.Must(validDeploymentProtocol[*m.Protocol], "invalid protocol")
}
case DeploymentTypeWorker:
v.Must(m.Protocol == nil || *m.Protocol == "", "Worker not support custom protocol")
case DeploymentTypeCronJob:
v.Must(m.Protocol == nil || *m.Protocol == "", "CronJob not support custom protocol")
if m.Schedule != nil {
if v.Must(*m.Schedule != "", "schedule required") {
v.Must(ReValidSchedule.MatchString(*m.Schedule), "schedule invalid")
}
}
case DeploymentTypeTCPService:
v.Must(m.Protocol == nil || *m.Protocol == "", "TCPService not support custom protocol")
if v.Must(m.Port != nil, "port required") {
v.Must(*m.Port > 0, "invalid port")
}
case DeploymentTypeInternalTCPService:
v.Must(m.Protocol == nil || *m.Protocol == "", "InternalTCPService not support custom protocol")
if v.Must(m.Port != nil, "port required") {
v.Must(*m.Port > 0, "invalid port")
}
}
}
v.Must(validEnvName(m.Env), "invalid env name")
v.Must(validEnvName(m.AddEnv), "invalid env name")
v.Must(len(m.Sidecars) <= 2, "sidecars must less than 2")
for _, s := range m.Sidecars {
v.Must(s.Valid(), "invalid sidecar")
}
return WrapValidate(v)
}
type DeploymentList struct {
Location string `json:"location" yaml:"location"` // optional
Project string `json:"project" yaml:"project"`
}
func (m *DeploymentList) Valid() error {
v := validator.New()
v.Must(m.Project != "", "project required")
return WrapValidate(v)
}
type DeploymentListResult struct {
Items []*DeploymentItem `json:"items" yaml:"items"`
}
func (m *DeploymentListResult) Table() [][]string {
table := [][]string{
{"NAME", "TYPE", "STATUS", "AGE"},
}
for _, x := range m.Items {
table = append(table, []string{
x.Name,
x.Type.String(),
x.Status.Text(),
age(x.CreatedAt),
})
}
return table
}
type DeploymentItem struct {
Project string `json:"project" yaml:"project"`
Location string `json:"location" yaml:"location"`
Name string `json:"name" yaml:"name"`
Type DeploymentType `json:"type" yaml:"type"`
Revision int64 `json:"revision" yaml:"revision"`
Image string `json:"image" yaml:"image"`
Env map[string]string `json:"env" yaml:"env"`
Command []string `json:"command" yaml:"command"`
Args []string `json:"args" yaml:"args"`
WorkloadIdentity string `json:"workloadIdentity" yaml:"workloadIdentity"`
PullSecret string `json:"pullSecret" yaml:"pullSecret"`
Disk *DeploymentDisk `json:"disk" yaml:"disk"`
MountData map[string]string `json:"mountData" yaml:"mountData"`
MinReplicas int `json:"minReplicas" yaml:"minReplicas"`
MaxReplicas int `json:"maxReplicas" yaml:"maxReplicas"`
Schedule string `json:"schedule" yaml:"schedule"`
Port int `json:"port" yaml:"port"`
Protocol DeploymentProtocol `json:"protocol" yaml:"protocol"`
Internal bool `json:"internal" yaml:"internal"`
NodePort int `json:"nodePort" yaml:"nodePort"`
Annotations map[string]string `json:"annotations" yaml:"annotations"`
Resources DeploymentResource `json:"resources" yaml:"resources"`
Sidecars []*Sidecar `json:"sidecars" yaml:"sidecars"`
URL string `json:"url" yaml:"url"`
InternalURL string `json:"internalUrl" yaml:"internalUrl"`
LogURL string `json:"logUrl" yaml:"logUrl"`
EventURL string `json:"eventUrl" yaml:"eventUrl"`
PodsURL string `json:"podsUrl" yaml:"podsUrl"`
StatusURL string `json:"statusUrl" yaml:"statusUrl"`
Address string `json:"address" yaml:"address"`
InternalAddress string `json:"internalAddress" yaml:"internalAddress"`
Status Status `json:"status" yaml:"status"`
Action DeploymentAction `json:"action" yaml:"action"`
AllocatedPrice float64 `json:"allocatedPrice" yaml:"allocatedPrice"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
CreatedBy string `json:"createdBy" yaml:"createdBy"`
SuccessAt time.Time `json:"successAt" yaml:"successAt"`
}
type DeploymentGet struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
Revision int `json:"revision" yaml:"revision"` // 0 = latest
}
func (m *DeploymentGet) Valid() error {
m.Name = strings.TrimSpace(m.Name)
// TODO: autofill location until all user migrate
if m.Location == "" {
m.Location = "gke.cluster-rcf2"
}
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
v.Must(m.Revision >= 0, "invalid revision")
return WrapValidate(v)
}
type DeploymentRevisions struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
}
func (m *DeploymentRevisions) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
return WrapValidate(v)
}
type DeploymentRevisionsResult struct {
Items []*DeploymentItem `json:"items" yaml:"items"`
}
type DeploymentResume struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
}
func (m *DeploymentResume) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
return WrapValidate(v)
}
type DeploymentPause struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
}
func (m *DeploymentPause) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
return WrapValidate(v)
}
type DeploymentRollback struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
Revision int `json:"revision" yaml:"revision"`
}
func (m *DeploymentRollback) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
v.Must(m.Revision >= 1, "invalid revision")
return WrapValidate(v)
}
type DeploymentDelete struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
}
func (m *DeploymentDelete) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(m.Project != "", "project required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
return WrapValidate(v)
}
type DeploymentMetricsTimeRange string
const (
DeploymentMetricsTimeRange1h = "1h"
DeploymentMetricsTimeRange6h = "6h"
DeploymentMetricsTimeRange12h = "12h"
DeploymentMetricsTimeRange1d = "1d"
DeploymentMetricsTimeRange1hagg = "1hagg"
DeploymentMetricsTimeRange6hagg = "6hagg"
DeploymentMetricsTimeRange12hagg = "12hagg"
DeploymentMetricsTimeRange1dagg = "1dagg"
DeploymentMetricsTimeRange2dagg = "2dagg"
DeploymentMetricsTimeRange7dagg = "7dagg"
DeploymentMetricsTimeRange30dagg = "30dagg"
)
var allDeploymentMetricsTimeRange = []DeploymentMetricsTimeRange{
DeploymentMetricsTimeRange1h,
DeploymentMetricsTimeRange6h,
DeploymentMetricsTimeRange12h,
DeploymentMetricsTimeRange1d,
DeploymentMetricsTimeRange1hagg,
DeploymentMetricsTimeRange6hagg,
DeploymentMetricsTimeRange12hagg,
DeploymentMetricsTimeRange1dagg,
DeploymentMetricsTimeRange2dagg,
DeploymentMetricsTimeRange7dagg,
DeploymentMetricsTimeRange30dagg,
}
var validDeploymentMetricsTimeRange = func() map[DeploymentMetricsTimeRange]bool {
m := map[DeploymentMetricsTimeRange]bool{}
for _, t := range allDeploymentMetricsTimeRange {
m[t] = true
}
return m
}()
type DeploymentMetrics struct {
Location string `json:"location" yaml:"location"`
Project string `json:"project" yaml:"project"`
Name string `json:"name" yaml:"name"`
TimeRange DeploymentMetricsTimeRange `json:"timeRange" yaml:"timeRange"`
}
func (m *DeploymentMetrics) Valid() error {
m.Name = strings.TrimSpace(m.Name)
v := validator.New()
v.Must(m.Location != "", "location required")
v.Must(ReValidName.MatchString(m.Name), "name invalid "+ReValidNameStr)
// allow old spec long name
v.Mustf(utf8.RuneCountInString(m.Name) <= MaxNameLength*2, "name must have length less then %d characters", MaxNameLength*2)
v.Must(m.Project != "", "project required")
v.Must(validDeploymentMetricsTimeRange[m.TimeRange], "timeRange invalid")
return WrapValidate(v)
}
type DeploymentMetricsResult struct {
CPUUsage []*DeploymentMetricsLine `json:"cpuUsage" yaml:"cpuUsage"`
CPULimit []*DeploymentMetricsLine `json:"cpuLimit" yaml:"cpuLimit"`
MemoryUsage []*DeploymentMetricsLine `json:"memoryUsage" yaml:"memoryUsage"`
Memory []*DeploymentMetricsLine `json:"memory" yaml:"memory"`
MemoryLimit []*DeploymentMetricsLine `json:"memoryLimit" yaml:"memoryLimit"`
Requests []*DeploymentMetricsLine `json:"requests" yaml:"requests"`
Egress []*DeploymentMetricsLine `json:"egress" yaml:"egress"`
}
type DeploymentMetricsLine struct {
Name string `json:"name" yaml:"name"`
Points [][2]float64 `json:"points" yaml:"points"`
}