forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ingress_common.go
106 lines (97 loc) · 2.64 KB
/
ingress_common.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
package ingress
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"github.com/rancher/norman/types/convert"
util "github.com/rancher/rancher/pkg/controllers/user/workload"
"github.com/rancher/rancher/pkg/settings"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
const (
ingressStateAnnotation = "field.cattle.io/ingressState"
)
func GetStateKey(name, namespace, host string, path string, port string) string {
ipDomain := settings.IngressIPDomain.Get()
if ipDomain != "" && strings.HasSuffix(host, ipDomain) {
host = ipDomain
}
key := fmt.Sprintf("%s/%s/%s/%s/%s", name, namespace, host, path, port)
return base64.URLEncoding.EncodeToString([]byte(key))
}
func GetIngressState(obj *v1beta1.Ingress) map[string]string {
annotations := obj.Annotations
if annotations == nil {
return nil
}
if v, ok := annotations[ingressStateAnnotation]; ok {
state := make(map[string]string)
json.Unmarshal([]byte(convert.ToString(v)), &state)
return state
}
return nil
}
type ingressService struct {
serviceName string
servicePort int32
workloadIDs string
}
func generateIngressService(name string, port int32, workloadIDs string) (ingressService, error) {
rtn := ingressService{
serviceName: name,
servicePort: port,
}
if workloadIDs != "" {
b, err := json.Marshal(strings.Split(workloadIDs, "/"))
if err != nil {
logrus.WithError(err).Warnf("marshal workload ids %s string error", workloadIDs)
return rtn, err
}
rtn.workloadIDs = string(b)
}
return rtn, nil
}
func (i *ingressService) generateNewService(obj *v1beta1.Ingress, serviceType corev1.ServiceType) *corev1.Service {
controller := true
return &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: i.serviceName,
OwnerReferences: []metav1.OwnerReference{
{
Name: obj.Name,
APIVersion: "v1beta1/extensions",
UID: obj.UID,
Kind: "Ingress",
Controller: &controller,
},
},
Namespace: obj.Namespace,
Annotations: map[string]string{
util.WorkloadAnnotation: i.workloadIDs,
},
},
Spec: corev1.ServiceSpec{
Type: serviceType,
Ports: []corev1.ServicePort{
{
Port: i.servicePort,
TargetPort: intstr.FromInt(int(i.servicePort)),
Protocol: "TCP",
},
},
},
}
}
func IsServiceOwnedByIngress(ingress *v1beta1.Ingress, service *corev1.Service) bool {
for i, owners := 0, service.GetOwnerReferences(); owners != nil && i < len(owners); i++ {
if owners[i].UID == ingress.UID && owners[i].Kind == ingress.Kind {
return true
}
}
return false
}