...
1
16
17 package envvars
18
19 import (
20 "fmt"
21 "net"
22 "strconv"
23 "strings"
24
25 "k8s.io/api/core/v1"
26 v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
27 )
28
29
30
31
32 func FromServices(services []*v1.Service) []v1.EnvVar {
33 var result []v1.EnvVar
34 for i := range services {
35 service := services[i]
36
37
38
39
40 if !v1helper.IsServiceIPSet(service) {
41 continue
42 }
43
44
45 name := makeEnvVariableName(service.Name) + "_SERVICE_HOST"
46 result = append(result, v1.EnvVar{Name: name, Value: service.Spec.ClusterIP})
47
48 name = makeEnvVariableName(service.Name) + "_SERVICE_PORT"
49 result = append(result, v1.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))})
50
51 for i := range service.Spec.Ports {
52 sp := &service.Spec.Ports[i]
53 if sp.Name != "" {
54 pn := name + "_" + makeEnvVariableName(sp.Name)
55 result = append(result, v1.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))})
56 }
57 }
58
59 result = append(result, makeLinkVariables(service)...)
60 }
61 return result
62 }
63
64 func makeEnvVariableName(str string) string {
65
66
67
68
69 return strings.ToUpper(strings.Replace(str, "-", "_", -1))
70 }
71
72 func makeLinkVariables(service *v1.Service) []v1.EnvVar {
73 prefix := makeEnvVariableName(service.Name)
74 all := []v1.EnvVar{}
75 for i := range service.Spec.Ports {
76 sp := &service.Spec.Ports[i]
77
78 protocol := string(v1.ProtocolTCP)
79 if sp.Protocol != "" {
80 protocol = string(sp.Protocol)
81 }
82
83 hostPort := net.JoinHostPort(service.Spec.ClusterIP, strconv.Itoa(int(sp.Port)))
84
85 if i == 0 {
86
87 all = append(all, v1.EnvVar{
88 Name: prefix + "_PORT",
89 Value: fmt.Sprintf("%s://%s", strings.ToLower(protocol), hostPort),
90 })
91 }
92 portPrefix := fmt.Sprintf("%s_PORT_%d_%s", prefix, sp.Port, strings.ToUpper(protocol))
93 all = append(all, []v1.EnvVar{
94 {
95 Name: portPrefix,
96 Value: fmt.Sprintf("%s://%s", strings.ToLower(protocol), hostPort),
97 },
98 {
99 Name: portPrefix + "_PROTO",
100 Value: strings.ToLower(protocol),
101 },
102 {
103 Name: portPrefix + "_PORT",
104 Value: strconv.Itoa(int(sp.Port)),
105 },
106 {
107 Name: portPrefix + "_ADDR",
108 Value: service.Spec.ClusterIP,
109 },
110 }...)
111 }
112 return all
113 }
114
View as plain text