-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
68 lines (62 loc) · 1.52 KB
/
service.go
File metadata and controls
68 lines (62 loc) · 1.52 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
package resources
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// ServiceOpts configures Service generation.
type ServiceOpts struct {
Name string
Namespace string
Labels map[string]string
Annotations map[string]string
Ports []ServicePort
Type corev1.ServiceType
}
// ServicePort maps a service port to a target port.
type ServicePort struct {
Name string
Port int32
TargetPort int32
Protocol corev1.Protocol
}
// NewService builds a Kubernetes Service.
func NewService(opts ServiceOpts) *corev1.Service {
if opts.Labels == nil {
opts.Labels = map[string]string{
"app": opts.Name,
}
}
if opts.Type == "" {
opts.Type = corev1.ServiceTypeClusterIP
}
var ports []corev1.ServicePort
for _, p := range opts.Ports {
protocol := p.Protocol
if protocol == "" {
protocol = corev1.ProtocolTCP
}
targetPort := p.TargetPort
if targetPort == 0 {
targetPort = p.Port
}
ports = append(ports, corev1.ServicePort{
Name: p.Name,
Port: p.Port,
TargetPort: intstr.FromInt32(targetPort),
Protocol: protocol,
})
}
return &corev1.Service{
TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Service"},
ObjectMeta: metav1.ObjectMeta{
Name: opts.Name, Namespace: opts.Namespace,
Labels: opts.Labels, Annotations: opts.Annotations,
},
Spec: corev1.ServiceSpec{
Type: opts.Type,
Selector: map[string]string{"app": opts.Name},
Ports: ports,
},
}
}