/
func.go
242 lines (219 loc) · 7.43 KB
/
func.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
package beku
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"github.com/ghodss/yaml"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/api/core/v1"
apiresource "k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/intstr"
)
// ToYAML struct translate into yaml
func ToYAML(o interface{}) (byts []byte, err error) {
byts, err = yaml.Marshal(o)
return
}
// ToJSON struct translate into json
func ToJSON(v interface{}) (byts []byte, err error) {
byts, err = json.Marshal(v)
return
}
// JSONToYAML json data translate into yaml
func JSONToYAML(jbyts []byte) (ybyts []byte, err error) {
ybyts, err = yaml.JSONToYAML(jbyts)
return
}
// YAMLToJSON yaml data translate into json
func YAMLToJSON(ybyts []byte) (jbyts []byte, err error) {
jbyts, err = yaml.YAMLToJSON(ybyts)
return
}
// DeploymentToSvc Use the Deployment to generate the associated SVC
// autoRelease[0] if true,beku will auto Release Service On Kubernetes,default can't Release Service On Kubernetes
func DeploymentToSvc(dp *appsv1.Deployment, sty ServiceType, autoRelease ...bool) (*v1.Service, error) {
var ports []ServicePort
for _, data := range dp.Spec.Template.Spec.Containers {
ports = append(ports, ServicePort{
Name: data.Name,
Protocol: Protocol(data.Ports[0].Protocol),
Port: data.Ports[0].ContainerPort,
})
}
svc := NewSvc().SetNamespaceAndName(dp.GetNamespace(), dp.GetName()).SetSelector(dp.Spec.Template.GetLabels()).SetPorts(ports).SetServiceType(sty)
if len(autoRelease) > 0 && autoRelease[0] == true {
return svc.Release()
}
return svc.Finish()
}
// StatefulSetToSvc Use the StatefulSet to generate the associated SVC
// autoRelease[0] if true,beku will auto Release Service On Kubernetes,default can't Release Service On Kubernetes
func StatefulSetToSvc(sts *appsv1.StatefulSet, sty ServiceType, isHeadless bool, autoRelease ...bool) (*v1.Service, error) {
var ports []ServicePort
for _, data := range sts.Spec.Template.Spec.Containers {
ports = append(ports, ServicePort{
Name: data.Name,
Protocol: Protocol(data.Ports[0].Protocol),
Port: data.Ports[0].ContainerPort,
})
}
svc := NewSvc().SetNamespaceAndName(sts.GetNamespace(), sts.GetName()).SetSelector(sts.Spec.Template.GetLabels()).SetPorts(ports)
if isHeadless {
svc = svc.Headless()
} else {
svc = svc.SetServiceType(sty)
}
if len(autoRelease) > 0 && autoRelease[0] == true {
return svc.Release()
}
return svc.Finish()
}
// DaemonSetToSvc Use the Set to generate the associated SVC
// autoRelease[0] if true,beku will auto Release Service On Kubernetes,default can't Release Service On Kubernetes
func DaemonSetToSvc(ds *appsv1.DaemonSet, sty ServiceType, autoRelease ...bool) (*v1.Service, error) {
var ports []ServicePort
for _, data := range ds.Spec.Template.Spec.Containers {
ports = append(ports, ServicePort{
Name: data.Name,
Protocol: Protocol(data.Ports[0].Protocol),
Port: data.Ports[0].ContainerPort,
})
}
svc := NewSvc().SetNamespaceAndName(ds.GetNamespace(), ds.GetName()).SetSelector(ds.Spec.Template.GetLabels()).SetPorts(ports).SetServiceType(sty)
if len(autoRelease) > 0 && autoRelease[0] == true {
return svc.Release()
}
return svc.Finish()
}
// Base64Encode base64 encode
func Base64Encode(src []byte) string {
return base64.StdEncoding.EncodeToString(src)
}
// Base64Decode base64 decode
func Base64Decode(src string) ([]byte, error) {
return base64.StdEncoding.DecodeString(src)
}
// ResourceMapsToK8s to K8s resourceList
func ResourceMapsToK8s(maps map[ResourceName]string) (v1.ResourceList, error) {
data := make(v1.ResourceList, 0)
for k, v := range maps {
q, err := apiresource.ParseQuantity(v)
if err != nil {
return nil, err
}
reName := k.ToK8s()
if reName == "" {
return nil, errors.New("resource name not allow")
}
data[reName] = q
}
if len(data) < 1 {
return nil, errors.New("source cann't allow empty")
}
return data, nil
}
// FromInt creates an IntOrString object with an int32 value. It is
// your responsibility not to call this method with a value greater
// than int32.
// TODO: convert to (val int32)
func FromInt(val int) intstr.IntOrString {
return intstr.IntOrString{Type: intstr.Int, IntVal: int32(val)}
}
// FromString creates an IntOrString object with a string value.
func FromString(val string) intstr.IntOrString {
return intstr.IntOrString{Type: intstr.String, StrVal: val}
}
// Parse the given string and try to convert it to an integer before
// setting it as a string value.
func Parse(val string) intstr.IntOrString {
i, err := strconv.Atoi(val)
if err != nil {
return FromString(val)
}
return FromInt(i)
}
// httpProbe container health check readness and liveness http probe
func httpProbe(port int, path string, initDelaySec, timeoutSec, periodSec int32, headers ...map[string]string) *v1.Probe {
if initDelaySec <= 0 {
initDelaySec = 30
}
return &v1.Probe{
Handler: v1.Handler{HTTPGet: &v1.HTTPGetAction{Path: path, Port: FromInt(port), HTTPHeaders: mapsToHeaders(headers)}},
InitialDelaySeconds: initDelaySec,
TimeoutSeconds: timeoutSec,
PeriodSeconds: periodSec,
}
}
func mapsToHeaders(headers []map[string]string) []v1.HTTPHeader {
if len(headers) <= 0 {
return nil
}
return mapToHeaders(headers[0])
}
func mapToHeaders(header map[string]string) []v1.HTTPHeader {
var headers []v1.HTTPHeader
for key := range header {
headers = append(headers, v1.HTTPHeader{Name: key, Value: header[key]})
}
return headers
}
// cmdProbe container health check readness and liveness cmd probe
func cmdProbe(cmd []string, initDelaySec, timeoutSec, periodSec int32) *v1.Probe {
if initDelaySec <= 0 {
initDelaySec = 30
}
return &v1.Probe{
Handler: v1.Handler{Exec: &v1.ExecAction{Command: cmd}},
InitialDelaySeconds: initDelaySec,
TimeoutSeconds: timeoutSec,
PeriodSeconds: periodSec,
}
}
// tcpProbe container health check readness and liveness tcp probe
func tcpProbe(host string, port int, initDelaySec, timeoutSec, periodSec int32) *v1.Probe {
if initDelaySec <= 0 {
initDelaySec = 30
}
return &v1.Probe{
Handler: v1.Handler{TCPSocket: &v1.TCPSocketAction{Port: FromInt(port), Host: host}},
InitialDelaySeconds: initDelaySec,
TimeoutSeconds: timeoutSec,
PeriodSeconds: periodSec,
}
}
func verifyString(str string) bool { return !(str == "" || len(str) <= 0) }
func emptyString(str string) bool { return str == "" || len(str) <= 0 }
func verifyMap(maps map[string]string) bool { return len(maps) > 0 }
func mapToEnvs(envMap map[string]string) ([]v1.EnvVar, error) {
if len(envMap) <= 0 {
return nil, errors.New("SetEnvs error, envMap is not allowed to be empty")
}
var envs []v1.EnvVar
for k, v := range envMap {
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
if k == "" || v == "" {
return nil, fmt.Errorf("SetEnvs error, key or value is not allowed to be empty,data(%s:%s)", k, v)
}
envs = append(envs, v1.EnvVar{Name: k, Value: v})
}
if len(envs) <= 0 {
return nil, fmt.Errorf("SetEnvs error, envs is not allowed to be empty")
}
return envs, nil
}
func containerRepeated(containers []v1.Container) error {
if containers == nil {
return errors.New("Containers is not allowed to be empty")
}
containerNames := make(map[string]int8, 0)
for _, container := range containers {
containerNames[container.Name] = 1
}
if len(containerNames) < len(containers) {
return errors.New("Multiple container names cannot be repeated")
}
return nil
}