forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
services.go
300 lines (267 loc) · 8.24 KB
/
services.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
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
package kube
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
)
const (
ExposeAnnotation = "fabric8.io/expose"
ExposeURLAnnotation = "fabric8.io/exposeUrl"
ExposeGeneratedByAnnotation = "fabric8.io/generated-by"
JenkinsXSkipTLSAnnotation = "jenkins-x.io/skip.tls"
ExposeIngressAnnotation = "fabric8.io/ingress.annotations"
CertManagerAnnotation = "certmanager.k8s.io/issuer"
)
type ServiceURL struct {
Name string
URL string
}
func GetServices(client kubernetes.Interface, ns string) (map[string]*v1.Service, error) {
answer := map[string]*v1.Service{}
list, err := client.CoreV1().Services(ns).List(meta_v1.ListOptions{})
if err != nil {
return answer, fmt.Errorf("failed to load Services %s", err)
}
for _, r := range list.Items {
name := r.Name
copy := r
answer[name] = ©
}
return answer, nil
}
func GetServiceNames(client kubernetes.Interface, ns string, filter string) ([]string, error) {
names := []string{}
list, err := client.CoreV1().Services(ns).List(meta_v1.ListOptions{})
if err != nil {
return names, fmt.Errorf("failed to load Services %s", err)
}
for _, r := range list.Items {
name := r.Name
if filter == "" || strings.Contains(name, filter) {
names = append(names, name)
}
}
sort.Strings(names)
return names, nil
}
func GetServiceURLFromMap(services map[string]*v1.Service, name string) string {
return GetServiceURL(services[name])
}
func FindServiceURL(client kubernetes.Interface, namespace string, name string) (string, error) {
svc, err := client.CoreV1().Services(namespace).Get(name, meta_v1.GetOptions{})
if err != nil {
return "", err
}
answer := GetServiceURL(svc)
if answer != "" {
return answer, nil
}
// lets try find the service via Ingress
ing, err := client.ExtensionsV1beta1().Ingresses(namespace).Get(name, meta_v1.GetOptions{})
if ing != nil && err == nil {
if len(ing.Spec.Rules) > 0 {
rule := ing.Spec.Rules[0]
hostname := rule.Host
for _, tls := range ing.Spec.TLS {
for _, h := range tls.Hosts {
if h != "" {
return "https://" + h, nil
}
}
}
if hostname != "" {
return "http://" + hostname, nil
}
}
}
return "", nil
}
// FindService looks up a service by name across all namespaces
func FindService(client kubernetes.Interface, name string) (*v1.Service, error) {
nsl, err := client.CoreV1().Namespaces().List(meta_v1.ListOptions{})
if err != nil {
return nil, err
}
for _, ns := range nsl.Items {
svc, err := client.CoreV1().Services(ns.GetName()).Get(name, meta_v1.GetOptions{})
if err == nil {
return svc, nil
}
}
return nil, errors.New("Service not found!")
}
func GetServiceURL(svc *v1.Service) string {
url := ""
if svc != nil && svc.Annotations != nil {
url = svc.Annotations[ExposeURLAnnotation]
}
return url
}
func GetServiceURLFromName(c kubernetes.Interface, name, ns string) (string, error) {
svc, err := c.CoreV1().Services(ns).Get(name, meta_v1.GetOptions{})
if err != nil {
return "", err
}
return GetServiceURL(svc), nil
}
func FindServiceURLs(client kubernetes.Interface, namespace string) ([]ServiceURL, error) {
options := meta_v1.ListOptions{}
urls := []ServiceURL{}
svcs, err := client.CoreV1().Services(namespace).List(options)
if err != nil {
return urls, err
}
for _, svc := range svcs.Items {
url := GetServiceURL(&svc)
if len(url) > 0 {
urls = append(urls, ServiceURL{
Name: svc.Name,
URL: url,
})
}
}
return urls, nil
}
// waits for the pods of a deployment to become ready
func WaitForExternalIP(client kubernetes.Interface, name, namespace string, timeout time.Duration) error {
options := meta_v1.ListOptions{
FieldSelector: fields.OneTermEqualSelector("metadata.name", name).String(),
}
w, err := client.CoreV1().Services(namespace).Watch(options)
if err != nil {
return err
}
defer w.Stop()
condition := func(event watch.Event) (bool, error) {
svc := event.Object.(*v1.Service)
return HasExternalAddress(svc), nil
}
_, err = watch.Until(timeout, w, condition)
if err == wait.ErrWaitTimeout {
return fmt.Errorf("service %s never became ready", name)
}
return nil
}
func HasExternalAddress(svc *v1.Service) bool {
for _, v := range svc.Status.LoadBalancer.Ingress {
if v.IP != "" || v.Hostname != "" {
return true
}
}
return false
}
func CreateServiceLink(client kubernetes.Interface, currentNamespace, targetNamespace, serviceName, externalURL string) error {
annotations := make(map[string]string)
annotations[ExposeURLAnnotation] = externalURL
svc := v1.Service{
ObjectMeta: meta_v1.ObjectMeta{
Name: serviceName,
Namespace: currentNamespace,
Annotations: annotations,
},
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeExternalName,
ExternalName: fmt.Sprintf("%s.%s.svc.cluster.local", serviceName, targetNamespace),
},
}
_, err := client.CoreV1().Services(currentNamespace).Create(&svc)
if err != nil {
return err
}
return nil
}
func DeleteService(client *kubernetes.Clientset, namespace string, serviceName string) error {
return client.CoreV1().Services(namespace).Delete(serviceName, &meta_v1.DeleteOptions{})
}
func GetService(client kubernetes.Interface, currentNamespace, targetNamespace, serviceName string) error {
svc := v1.Service{
ObjectMeta: meta_v1.ObjectMeta{
Name: serviceName,
Namespace: currentNamespace,
},
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeExternalName,
ExternalName: fmt.Sprintf("%s.%s.svc.cluster.local", serviceName, targetNamespace),
},
}
_, err := client.CoreV1().Services(currentNamespace).Create(&svc)
if err != nil {
return err
}
return nil
}
func IsServicePresent(c kubernetes.Interface, name, ns string) (bool, error) {
svc, err := c.CoreV1().Services(ns).Get(name, meta_v1.GetOptions{})
if err != nil || svc == nil {
return false, err
}
return true, nil
}
func AnnotateNamespaceServicesWithCertManager(c kubernetes.Interface, ns, issuer string) error {
svcList, err := GetServices(c, ns)
if err != nil {
return err
}
for _, s := range svcList {
if s.Annotations[ExposeAnnotation] == "true" && s.Annotations[JenkinsXSkipTLSAnnotation] != "true" {
existingAnnotations, _ := s.Annotations[ExposeIngressAnnotation]
// if no existing `fabric8.io/ingress.annotations` initialise and add else update with ClusterIssuer
if len(existingAnnotations) > 0 {
s.Annotations[ExposeIngressAnnotation] = existingAnnotations + "\n" + CertManagerAnnotation + ": " + issuer
} else {
s.Annotations[ExposeIngressAnnotation] = CertManagerAnnotation + ": " + issuer
}
_, err = c.CoreV1().Services(ns).Update(s)
if err != nil {
return fmt.Errorf("failed to annotate and update service %s in namespace %s: %v", s.Name, ns, err)
}
}
}
return nil
}
func CleanServiceAnnotations(c kubernetes.Interface, ns string) error {
svcList, err := GetServices(c, ns)
if err != nil {
return err
}
for _, s := range svcList {
if s.Annotations[ExposeAnnotation] == "true" && s.Annotations[JenkinsXSkipTLSAnnotation] != "true" {
// if no existing `fabric8.io/ingress.annotations` initialise and add else update with ClusterIssuer
annotationsForIngress, _ := s.Annotations[ExposeIngressAnnotation]
if len(annotationsForIngress) > 0 {
var newAnnotations []string
annotations := strings.Split(annotationsForIngress, "\n")
for _, element := range annotations {
annotation := strings.SplitN(element, ":", 2)
key, _ := annotation[0], strings.TrimSpace(annotation[1])
if key != CertManagerAnnotation {
newAnnotations = append(newAnnotations, element)
}
}
annotationsForIngress = ""
for _, v := range newAnnotations {
if len(annotationsForIngress) > 0 {
annotationsForIngress = annotationsForIngress + "\n" + v
} else {
annotationsForIngress = v
}
}
s.Annotations[ExposeIngressAnnotation] = annotationsForIngress
}
delete(s.Annotations, ExposeURLAnnotation)
_, err = c.CoreV1().Services(ns).Update(s)
if err != nil {
return fmt.Errorf("failed to clean service %s annotations in namespace %s: %v", s.Name, ns, err)
}
}
}
return nil
}