/
deployment.go
102 lines (85 loc) · 2.45 KB
/
deployment.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
package kube
import (
"encoding/json"
"time"
appsv1 "k8s.io/api/apps/v1"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type Deployment struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Labels map[string]string `json:"labels,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Replicas int `json:"replicas"`
Containers []Container `json:"containers"`
NodeSelectors map[string]string `json:"node_selectors,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
func (d *Deployment) ToJSON() string {
response, _ := json.Marshal(d)
return string(response)
}
func (d *Deployment) Marshal() (appsv1.Deployment, error) {
var kubeContainers []apiv1.Container
for _, container := range d.Containers {
kubeContainers = append(kubeContainers, container.Marshal())
}
var replicas int32 = int32(d.Replicas)
if replicas == 0 {
replicas = 1
}
deployment := appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: d.Name,
Namespace: d.Namespace,
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": d.Name,
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": d.Name,
},
Annotations: d.Annotations,
},
Spec: apiv1.PodSpec{
Containers: kubeContainers,
},
},
},
}
if d.NodeSelectors != nil {
deployment.Spec.Template.Spec.NodeSelector = d.NodeSelectors
}
return deployment, nil
}
func (d *Deployment) Unmarshal(deployment *appsv1.Deployment) error {
d.Name = deployment.GetName()
d.Namespace = deployment.GetNamespace()
d.CreatedAt = deployment.GetCreationTimestamp().Time
d.Replicas = int(*deployment.Spec.Replicas)
d.Labels = make(map[string]string)
if labels := deployment.GetLabels(); labels != nil {
d.Labels = labels
}
d.Annotations = make(map[string]string)
if annotations := deployment.GetAnnotations(); annotations != nil {
d.Annotations = annotations
}
for _, c := range deployment.Spec.Template.Spec.Containers {
container := Container{}
container.Unmarshal(c)
d.Containers = append(d.Containers, container)
}
d.NodeSelectors = make(map[string]string)
if nodeSelectors := deployment.Spec.Template.Spec.NodeSelector; nodeSelectors != nil {
d.NodeSelectors = nodeSelectors
}
return nil
}