Skip to content

Commit

Permalink
create a constants package and move annotations to it
Browse files Browse the repository at this point in the history
  • Loading branch information
ishustava committed Nov 9, 2022
1 parent 7f2e5c7 commit d5e5ebd
Show file tree
Hide file tree
Showing 22 changed files with 592 additions and 584 deletions.
7 changes: 4 additions & 3 deletions control-plane/connect-inject/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strconv"
"strings"

"github.com/hashicorp/consul-k8s/control-plane/connect-inject/constants"
corev1 "k8s.io/api/core/v1"
)

Expand All @@ -30,11 +31,11 @@ func PortValue(pod corev1.Pod, value string) (int32, error) {
// to read the pod's namespace label when it exists.
func TransparentProxyEnabled(namespace corev1.Namespace, pod corev1.Pod, globalEnabled bool) (bool, error) {
// First check to see if the pod annotation exists to override the namespace or global settings.
if raw, ok := pod.Annotations[KeyTransparentProxy]; ok {
if raw, ok := pod.Annotations[constants.KeyTransparentProxy]; ok {
return strconv.ParseBool(raw)
}
// Next see if the namespace has been defaulted.
if raw, ok := namespace.Labels[KeyTransparentProxy]; ok {
if raw, ok := namespace.Labels[constants.KeyTransparentProxy]; ok {
return strconv.ParseBool(raw)
}
// Else fall back to the global default.
Expand All @@ -44,7 +45,7 @@ func TransparentProxyEnabled(namespace corev1.Namespace, pod corev1.Pod, globalE
// ShouldOverwriteProbes returns true if we need to overwrite readiness/liveness probes for this pod.
// It returns an error when the annotation value cannot be parsed by strconv.ParseBool.
func ShouldOverwriteProbes(pod corev1.Pod, globalOverwrite bool) (bool, error) {
if raw, ok := pod.Annotations[AnnotationTransparentProxyOverwriteProbes]; ok {
if raw, ok := pod.Annotations[constants.AnnotationTransparentProxyOverwriteProbes]; ok {
return strconv.ParseBool(raw)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package common
package constants

const (
// KeyInjectStatus is the key of the annotation that is added to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
mapset "github.com/deckarep/golang-set"
"github.com/go-logr/logr"
"github.com/hashicorp/consul-k8s/control-plane/connect-inject/common"
"github.com/hashicorp/consul-k8s/control-plane/connect-inject/constants"
"github.com/hashicorp/consul-k8s/control-plane/connect-inject/metrics"
"github.com/hashicorp/consul-k8s/control-plane/consul"
"github.com/hashicorp/consul-k8s/control-plane/helper/parsetags"
Expand Down Expand Up @@ -198,7 +199,7 @@ func (r *Controller) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
continue
}

svcName, ok := pod.Annotations[common.AnnotationKubernetesService]
svcName, ok := pod.Annotations[constants.AnnotationKubernetesService]
if ok && serviceEndpoints.Name != svcName {
r.Log.Info("ignoring endpoint because it doesn't match explicit service annotation", "name", serviceEndpoints.Name, "ns", serviceEndpoints.Namespace)
// deregistration for service instances that don't match the annotation happens
Expand Down Expand Up @@ -252,7 +253,7 @@ func (r *Controller) registerServicesAndHealthCheck(apiClient *api.Client, pod c
endpointAddressMap[pod.Status.PodIP] = true

var managedByEndpointsController bool
if raw, ok := pod.Labels[common.KeyManagedBy]; ok && raw == common.ManagedByValue {
if raw, ok := pod.Labels[constants.KeyManagedBy]; ok && raw == constants.ManagedByValue {
managedByEndpointsController = true
}
// For pods managed by this controller, create and register the service instance.
Expand Down Expand Up @@ -291,7 +292,7 @@ func (r *Controller) registerGateway(apiClient *api.Client, pod corev1.Pod, serv
endpointAddressMap[pod.Status.PodIP] = true

var managedByEndpointsController bool
if raw, ok := pod.Labels[common.KeyManagedBy]; ok && raw == common.ManagedByValue {
if raw, ok := pod.Labels[constants.KeyManagedBy]; ok && raw == constants.ManagedByValue {
managedByEndpointsController = true
}
// For pods managed by this controller, create and register the service instance.
Expand Down Expand Up @@ -330,7 +331,7 @@ func (r *Controller) registerGateway(apiClient *api.Client, pod corev1.Pod, serv
func serviceName(pod corev1.Pod, serviceEndpoints corev1.Endpoints) string {
svcName := serviceEndpoints.Name
// If the annotation has a comma, it is a multi port Pod. In that case we always use the name of the endpoint.
if serviceNameFromAnnotation, ok := pod.Annotations[common.AnnotationService]; ok && serviceNameFromAnnotation != "" && !strings.Contains(serviceNameFromAnnotation, ",") {
if serviceNameFromAnnotation, ok := pod.Annotations[constants.AnnotationService]; ok && serviceNameFromAnnotation != "" && !strings.Contains(serviceNameFromAnnotation, ",") {
svcName = serviceNameFromAnnotation
}
return svcName
Expand All @@ -357,7 +358,7 @@ func (r *Controller) createServiceRegistrations(apiClient *api.Client, pod corev
// and register that port for the host service.
// The meshWebhook will always set the port annotation if one is not provided on the pod.
var consulServicePort int
if raw, ok := pod.Annotations[common.AnnotationPort]; ok && raw != "" {
if raw, ok := pod.Annotations[constants.AnnotationPort]; ok && raw != "" {
if multiPort := strings.Split(raw, ","); len(multiPort) > 1 {
// Figure out which index of the ports annotation to use by
// finding the index of the service names annotation.
Expand All @@ -383,15 +384,15 @@ func (r *Controller) createServiceRegistrations(apiClient *api.Client, pod corev
MetaKeyPodName: pod.Name,
MetaKeyKubeServiceName: serviceEndpoints.Name,
MetaKeyKubeNS: serviceEndpoints.Namespace,
MetaKeyManagedBy: common.ManagedByValue,
MetaKeyManagedBy: constants.ManagedByValue,
MetaKeySyntheticNode: "true",
}
for k, v := range pod.Annotations {
if strings.HasPrefix(k, common.AnnotationMeta) && strings.TrimPrefix(k, common.AnnotationMeta) != "" {
if strings.HasPrefix(k, constants.AnnotationMeta) && strings.TrimPrefix(k, constants.AnnotationMeta) != "" {
if v == "$POD_NAME" {
meta[strings.TrimPrefix(k, common.AnnotationMeta)] = pod.Name
meta[strings.TrimPrefix(k, constants.AnnotationMeta)] = pod.Name
} else {
meta[strings.TrimPrefix(k, common.AnnotationMeta)] = v
meta[strings.TrimPrefix(k, constants.AnnotationMeta)] = v
}
}
}
Expand Down Expand Up @@ -548,7 +549,7 @@ func (r *Controller) createServiceRegistrations(apiClient *api.Client, pod corev
}
if overwriteProbes {
var originalPod corev1.Pod
err = json.Unmarshal([]byte(pod.Annotations[common.AnnotationOriginalPod]), &originalPod)
err = json.Unmarshal([]byte(pod.Annotations[constants.AnnotationOriginalPod]), &originalPod)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -623,7 +624,7 @@ func (r *Controller) createGatewayRegistrations(pod corev1.Pod, serviceEndpoints
MetaKeyPodName: pod.Name,
MetaKeyKubeServiceName: serviceEndpoints.Name,
MetaKeyKubeNS: serviceEndpoints.Namespace,
MetaKeyManagedBy: common.ManagedByValue,
MetaKeyManagedBy: constants.ManagedByValue,
MetaKeySyntheticNode: "true",
}

Expand All @@ -633,24 +634,24 @@ func (r *Controller) createGatewayRegistrations(pod corev1.Pod, serviceEndpoints
Meta: meta,
}

gatewayServiceName, ok := pod.Annotations[common.AnnotationGatewayConsulServiceName]
gatewayServiceName, ok := pod.Annotations[constants.AnnotationGatewayConsulServiceName]
if !ok {
return nil, fmt.Errorf("failed to read annontation %s from pod %s/%s", common.AnnotationGatewayConsulServiceName, pod.Namespace, pod.Name)
return nil, fmt.Errorf("failed to read annontation %s from pod %s/%s", constants.AnnotationGatewayConsulServiceName, pod.Namespace, pod.Name)
}
service.Service = gatewayServiceName

var consulNS string

// Set the service values.
switch pod.Annotations[common.AnnotationGatewayKind] {
switch pod.Annotations[constants.AnnotationGatewayKind] {
case MeshGateway:
service.Kind = api.ServiceKindMeshGateway
if r.EnableConsulNamespaces {
service.Namespace = defaultNS
consulNS = defaultNS
}

port, err := strconv.Atoi(pod.Annotations[common.AnnotationMeshGatewayContainerPort])
port, err := strconv.Atoi(pod.Annotations[constants.AnnotationMeshGatewayContainerPort])
if err != nil {
return nil, err
}
Expand All @@ -677,13 +678,13 @@ func (r *Controller) createGatewayRegistrations(pod corev1.Pod, serviceEndpoints
case TerminatingGateway:
service.Kind = api.ServiceKindTerminatingGateway
service.Port = 8443
if ns, ok := pod.Annotations[common.AnnotationGatewayNamespace]; ok && r.EnableConsulNamespaces {
if ns, ok := pod.Annotations[constants.AnnotationGatewayNamespace]; ok && r.EnableConsulNamespaces {
service.Namespace = ns
consulNS = ns
}
case IngressGateway:
service.Kind = api.ServiceKindIngressGateway
if ns, ok := pod.Annotations[common.AnnotationGatewayNamespace]; ok && r.EnableConsulNamespaces {
if ns, ok := pod.Annotations[constants.AnnotationGatewayNamespace]; ok && r.EnableConsulNamespaces {
service.Namespace = ns
consulNS = ns
}
Expand Down Expand Up @@ -715,11 +716,11 @@ func (r *Controller) createGatewayRegistrations(pod corev1.Pod, serviceEndpoints
}

default:
return nil, fmt.Errorf("%s must be one of %s, %s, or %s", common.AnnotationGatewayKind, MeshGateway, TerminatingGateway, IngressGateway)
return nil, fmt.Errorf("%s must be one of %s, %s, or %s", constants.AnnotationGatewayKind, MeshGateway, TerminatingGateway, IngressGateway)
}

if r.MetricsConfig.DefaultEnableMetrics && r.MetricsConfig.EnableGatewayMetrics {
if pod.Annotations[common.AnnotationGatewayKind] == IngressGateway {
if pod.Annotations[constants.AnnotationGatewayKind] == IngressGateway {
service.Proxy.Config["envoy_prometheus_bind_addr"] = fmt.Sprintf("%s:20200", pod.Status.PodIP)
} else {
service.Proxy = &api.AgentServiceConnectProxyConfig{
Expand Down Expand Up @@ -754,17 +755,17 @@ func (r *Controller) createGatewayRegistrations(pod corev1.Pod, serviceEndpoints

func (r *Controller) getWanData(pod corev1.Pod, endpoints corev1.Endpoints) (string, int, error) {
var wanAddr string
source, ok := pod.Annotations[common.AnnotationGatewayWANSource]
source, ok := pod.Annotations[constants.AnnotationGatewayWANSource]
if !ok {
return "", 0, fmt.Errorf("failed to read annotation %s", common.AnnotationGatewayWANSource)
return "", 0, fmt.Errorf("failed to read annotation %s", constants.AnnotationGatewayWANSource)
}
switch source {
case "NodeName":
wanAddr = pod.Spec.NodeName
case "NodeIP":
wanAddr = pod.Status.HostIP
case "Static":
wanAddr = pod.Annotations[common.AnnotationGatewayWANAddress]
wanAddr = pod.Annotations[constants.AnnotationGatewayWANAddress]
case "Service":
svc, err := r.getService(endpoints)
if err != nil {
Expand All @@ -791,9 +792,9 @@ func (r *Controller) getWanData(pod corev1.Pod, endpoints corev1.Endpoints) (str
}
}

wanPort, err := strconv.Atoi(pod.Annotations[common.AnnotationGatewayWANPort])
wanPort, err := strconv.Atoi(pod.Annotations[constants.AnnotationGatewayWANPort])
if err != nil {
return "", 0, fmt.Errorf("failed to parse WAN port from value %s", pod.Annotations[common.AnnotationGatewayWANPort])
return "", 0, fmt.Errorf("failed to parse WAN port from value %s", pod.Annotations[constants.AnnotationGatewayWANPort])
}
return wanAddr, wanPort, nil
}
Expand Down Expand Up @@ -954,7 +955,7 @@ func (r *Controller) processUpstreams(pod corev1.Pod, endpoints corev1.Endpoints
}

var upstreams []api.Upstream
if raw, ok := pod.Annotations[common.AnnotationUpstreams]; ok && raw != "" {
if raw, ok := pod.Annotations[constants.AnnotationUpstreams]; ok && raw != "" {
for _, raw := range strings.Split(raw, ",") {
var upstream api.Upstream

Expand Down Expand Up @@ -1026,7 +1027,7 @@ func (r *Controller) serviceInstancesForK8SServiceNameAndNamespace(apiClient *ap
err error
)
filter := fmt.Sprintf(`Meta[%q] == %q and Meta[%q] == %q and Meta[%q] == %q`,
MetaKeyKubeServiceName, k8sServiceName, MetaKeyKubeNS, k8sServiceNamespace, MetaKeyManagedBy, common.ManagedByValue)
MetaKeyKubeServiceName, k8sServiceName, MetaKeyKubeNS, k8sServiceNamespace, MetaKeyManagedBy, constants.ManagedByValue)
if r.EnableConsulNamespaces {
serviceList, _, err = apiClient.Catalog().NodeServiceList(ConsulNodeName, &api.QueryOptions{Filter: filter, Namespace: namespaces.WildcardNamespace})
} else {
Expand Down Expand Up @@ -1210,15 +1211,15 @@ func (r *Controller) consulNamespace(namespace string) string {

// hasBeenInjected checks the value of the status annotation and returns true if the Pod has been injected.
func hasBeenInjected(pod corev1.Pod) bool {
if anno, ok := pod.Annotations[common.KeyInjectStatus]; ok && anno == common.Injected {
if anno, ok := pod.Annotations[constants.KeyInjectStatus]; ok && anno == constants.Injected {
return true
}
return false
}

// isGateway checks the value of the gateway annotation and returns true if the Pod represents a Gateway.
func isGateway(pod corev1.Pod) bool {
anno, ok := pod.Annotations[common.AnnotationGatewayKind]
anno, ok := pod.Annotations[constants.AnnotationGatewayKind]
return ok && anno != ""
}

Expand All @@ -1239,7 +1240,7 @@ func mapAddresses(addresses corev1.EndpointSubset) map[corev1.EndpointAddress]st
// isLabeledIgnore checks the value of the label `consul.hashicorp.com/service-ignore` and returns true if the
// label exists and is "truthy". Otherwise, it returns false.
func isLabeledIgnore(labels map[string]string) bool {
value, labelExists := labels[common.LabelServiceIgnore]
value, labelExists := labels[constants.LabelServiceIgnore]
shouldIgnore, err := strconv.ParseBool(value)

return shouldIgnore && labelExists && err == nil
Expand All @@ -1248,7 +1249,7 @@ func isLabeledIgnore(labels map[string]string) bool {
// consulTags returns tags that should be added to the Consul service and proxy registrations.
func consulTags(pod corev1.Pod) []string {
var tags []string
if raw, ok := pod.Annotations[common.AnnotationTags]; ok && raw != "" {
if raw, ok := pod.Annotations[constants.AnnotationTags]; ok && raw != "" {
tags = append(tags, parsetags.ParseTags(raw)...)
}

Expand All @@ -1268,7 +1269,7 @@ func consulTags(pod corev1.Pod) []string {
}

func getMultiPortIdx(pod corev1.Pod, serviceEndpoints corev1.Endpoints) int {
for i, name := range strings.Split(pod.Annotations[common.AnnotationService], ",") {
for i, name := range strings.Split(pod.Annotations[constants.AnnotationService], ",") {
if name == serviceName(pod, serviceEndpoints) {
return i
}
Expand Down
Loading

0 comments on commit d5e5ebd

Please sign in to comment.