-
Notifications
You must be signed in to change notification settings - Fork 33
/
policy-server-service.go
86 lines (78 loc) · 2.52 KB
/
policy-server-service.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
package admission
import (
"context"
"errors"
"fmt"
"os"
"strconv"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
policiesv1 "github.com/kubewarden/kubewarden-controller/api/policies/v1"
"github.com/kubewarden/kubewarden-controller/internal/constants"
)
// This is the port where the Policy Server service will be exposing metrics. Can be overridden
// by an environment variable KUBEWARDEN_POLICY_SERVER_SERVICES_METRICS_PORT
var metricsPort = constants.PolicyServerMetricsPort
func init() {
envMetricsPort := os.Getenv(constants.PolicyServerMetricsPortEnvVar)
if envMetricsPort != "" {
var err error
metricsPortInt32, err := strconv.ParseInt(envMetricsPort, 10, 32)
if err != nil {
fmt.Fprintf(os.Stderr, "port %s provided in %s envvar cannot be parsed as integer: %v. Aborting.\n", envMetricsPort, constants.PolicyServerMetricsPortEnvVar, err)
os.Exit(1)
}
metricsPort = int(metricsPortInt32)
}
}
func (r *Reconciler) reconcilePolicyServerService(ctx context.Context, policyServer *policiesv1.PolicyServer) error {
svc := corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: policyServer.NameWithPrefix(),
Namespace: r.DeploymentsNamespace,
},
}
_, err := controllerutil.CreateOrPatch(ctx, r.Client, &svc, func() error {
return r.updateService(&svc, policyServer)
})
if err != nil {
return fmt.Errorf("cannot reconcile policy-server service: %w", err)
}
return nil
}
func (r *Reconciler) updateService(svc *corev1.Service, policyServer *policiesv1.PolicyServer) error {
svc.Name = policyServer.NameWithPrefix()
svc.Namespace = r.DeploymentsNamespace
svc.Labels = map[string]string{
constants.AppLabelKey: policyServer.AppLabel(),
}
svc.Spec = corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "policy-server",
Port: constants.PolicyServerPort,
TargetPort: intstr.FromInt(constants.PolicyServerPort),
Protocol: corev1.ProtocolTCP,
},
},
Selector: map[string]string{
constants.AppLabelKey: policyServer.AppLabel(),
},
}
if r.MetricsEnabled {
svc.Spec.Ports = append(
svc.Spec.Ports,
corev1.ServicePort{
Name: "metrics",
Port: int32(metricsPort),
Protocol: corev1.ProtocolTCP,
},
)
}
if err := controllerutil.SetOwnerReference(policyServer, svc, r.Client.Scheme()); err != nil {
return errors.Join(errors.New("failed to set policy server service owner reference"), err)
}
return nil
}