diff --git a/apis/networking/v1beta1/gatewayclient_types.go b/apis/networking/v1beta1/gatewayclient_types.go index 6d683947d8..95474c48c2 100644 --- a/apis/networking/v1beta1/gatewayclient_types.go +++ b/apis/networking/v1beta1/gatewayclient_types.go @@ -43,6 +43,9 @@ type GatewayClientSpec struct { MTU int `json:"mtu,omitempty"` // Endpoint specifies the endpoint of the tunnel. Endpoint EndpointStatus `json:"endpoint,omitempty"` + // SecretRef specifies the reference to the secret containing the wireguard configuration. + // Leave it empty to let the operator create a new secret. + SecretRef corev1.LocalObjectReference `json:"secretRef,omitempty"` } // GatewayClientStatus defines the observed state of GatewayClient. diff --git a/apis/networking/v1beta1/gatewayserver_types.go b/apis/networking/v1beta1/gatewayserver_types.go index d06f488c9d..dffad698aa 100644 --- a/apis/networking/v1beta1/gatewayserver_types.go +++ b/apis/networking/v1beta1/gatewayserver_types.go @@ -60,6 +60,9 @@ type GatewayServerSpec struct { MTU int `json:"mtu,omitempty"` // Endpoint specifies the endpoint of the tunnel. Endpoint Endpoint `json:"endpoint,omitempty"` + // SecretRef specifies the reference to the secret containing the wireguard configuration. + // Leave it empty to let the operator create a new secret. + SecretRef corev1.LocalObjectReference `json:"secretRef,omitempty"` } // EndpointStatus defines the observed state of the endpoint. diff --git a/apis/networking/v1beta1/wggatewayclient_types.go b/apis/networking/v1beta1/wggatewayclient_types.go index 51bfc3981c..d35f431cc2 100644 --- a/apis/networking/v1beta1/wggatewayclient_types.go +++ b/apis/networking/v1beta1/wggatewayclient_types.go @@ -41,6 +41,9 @@ type WgGatewayClientSpec struct { Deployment DeploymentTemplate `json:"deployment"` // Metrics specifies the metrics configuration for the client. Metrics *Metrics `json:"metrics,omitempty"` + // SecretRef specifies the reference to the secret containing the wireguard configuration. + // Leave it empty to let the operator create a new secret. + SecretRef corev1.LocalObjectReference `json:"secretRef,omitempty"` } // WgGatewayClientStatus defines the observed state of WgGatewayClient. diff --git a/apis/networking/v1beta1/wggatewayserver_types.go b/apis/networking/v1beta1/wggatewayserver_types.go index 923d3900f3..63d49972bd 100644 --- a/apis/networking/v1beta1/wggatewayserver_types.go +++ b/apis/networking/v1beta1/wggatewayserver_types.go @@ -79,6 +79,9 @@ type WgGatewayServerSpec struct { Deployment DeploymentTemplate `json:"deployment"` // Metrics specifies the metrics configuration for the server. Metrics *Metrics `json:"metrics,omitempty"` + // SecretRef specifies the reference to the secret containing the wireguard configuration. + // Leave it empty to let the operator create a new secret. + SecretRef corev1.LocalObjectReference `json:"secretRef,omitempty"` } // WgGatewayServerStatus defines the observed state of WgGatewayServer. diff --git a/apis/networking/v1beta1/zz_generated.deepcopy.go b/apis/networking/v1beta1/zz_generated.deepcopy.go index 8b3d2bc6d1..633a3ed081 100644 --- a/apis/networking/v1beta1/zz_generated.deepcopy.go +++ b/apis/networking/v1beta1/zz_generated.deepcopy.go @@ -505,6 +505,7 @@ func (in *GatewayClientSpec) DeepCopyInto(out *GatewayClientSpec) { *out = *in out.ClientTemplateRef = in.ClientTemplateRef in.Endpoint.DeepCopyInto(&out.Endpoint) + out.SecretRef = in.SecretRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewayClientSpec. @@ -611,6 +612,7 @@ func (in *GatewayServerSpec) DeepCopyInto(out *GatewayServerSpec) { *out = *in out.ServerTemplateRef = in.ServerTemplateRef in.Endpoint.DeepCopyInto(&out.Endpoint) + out.SecretRef = in.SecretRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewayServerSpec. @@ -1502,6 +1504,7 @@ func (in *WgGatewayClientSpec) DeepCopyInto(out *WgGatewayClientSpec) { *out = new(Metrics) (*in).DeepCopyInto(*out) } + out.SecretRef = in.SecretRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WgGatewayClientSpec. @@ -1683,6 +1686,7 @@ func (in *WgGatewayServerSpec) DeepCopyInto(out *WgGatewayServerSpec) { *out = new(Metrics) (*in).DeepCopyInto(*out) } + out.SecretRef = in.SecretRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WgGatewayServerSpec. diff --git a/cmd/gateway/wireguard/main.go b/cmd/gateway/wireguard/main.go index cacd9e3fbf..95f753c5a3 100644 --- a/cmd/gateway/wireguard/main.go +++ b/cmd/gateway/wireguard/main.go @@ -28,7 +28,6 @@ import ( "k8s.io/klog/v2" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/log" @@ -90,15 +89,6 @@ func run(cmd *cobra.Command, _ []string) error { // Get the rest config. cfg := config.GetConfigOrDie() - // Create the client. This client should be used only outside the reconciler. - // This client don't need a cache. - cl, err := client.New(cfg, client.Options{ - Scheme: scheme, - }) - if err != nil { - return fmt.Errorf("unable to create client: %w", err) - } - // Create the manager. mgr, err := ctrl.NewManager(cfg, ctrl.Options{ MapperProvider: mapper.LiqoMapperProvider(scheme), @@ -155,9 +145,9 @@ func run(cmd *cobra.Command, _ []string) error { return fmt.Errorf("unable to setup public keys reconciler: %w", err) } - // Ensure presence of Secret with private and public keys. - if err = wireguard.EnsureKeysSecret(cmd.Context(), cl, options); err != nil { - return fmt.Errorf("unable to manage wireguard keys secret: %w", err) + // Load keys. + if err := wireguard.LoadKeys(options); err != nil { + return fmt.Errorf("unable to load keys: %w", err) } // Create the wg-liqo interface and init the wireguard configuration depending on the mode (client/server). diff --git a/cmd/liqo-controller-manager/modules/networking.go b/cmd/liqo-controller-manager/modules/networking.go index a236039035..38e0528cc1 100644 --- a/cmd/liqo-controller-manager/modules/networking.go +++ b/cmd/liqo-controller-manager/modules/networking.go @@ -95,14 +95,16 @@ func SetupNetworkingModule(ctx context.Context, mgr manager.Manager, opts *Netwo return err } - wgServerRec := wggatewaycontrollers.NewWgGatewayServerReconciler( - mgr.GetClient(), mgr.GetScheme(), opts.WgGatewayServerClusterRoleName) + wgServerRec := wggatewaycontrollers.NewWgGatewayServerReconciler(mgr.GetClient(), mgr.GetScheme(), + mgr.GetEventRecorderFor("wg-gateway-server-controller"), + opts.WgGatewayServerClusterRoleName) if err := wgServerRec.SetupWithManager(mgr); err != nil { klog.Errorf("Unable to start the wgGatewayServerReconciler: %v", err) return err } wgClientRec := wggatewaycontrollers.NewWgGatewayClientReconciler(mgr.GetClient(), mgr.GetScheme(), + mgr.GetEventRecorderFor("wg-gateway-client-controller"), opts.WgGatewayClientClusterRoleName) if err := wgClientRec.SetupWithManager(mgr); err != nil { klog.Errorf("Unable to start the wgGatewayClientReconciler: %v", err) @@ -110,14 +112,18 @@ func SetupNetworkingModule(ctx context.Context, mgr manager.Manager, opts *Netwo } serverReconciler := serveroperator.NewServerReconciler(mgr.GetClient(), - opts.DynClient, opts.Factory, mgr.GetScheme(), opts.GatewayServerResources) + opts.DynClient, opts.Factory, mgr.GetScheme(), + mgr.GetEventRecorderFor("server-controller"), + opts.GatewayServerResources) if err := serverReconciler.SetupWithManager(mgr); err != nil { klog.Errorf("Unable to start the serverReconciler: %v", err) return err } clientReconciler := clientoperator.NewClientReconciler(mgr.GetClient(), - opts.DynClient, opts.Factory, mgr.GetScheme(), opts.GatewayClientResources) + opts.DynClient, opts.Factory, mgr.GetScheme(), + mgr.GetEventRecorderFor("client-controller"), + opts.GatewayClientResources) if err := clientReconciler.SetupWithManager(mgr); err != nil { klog.Errorf("Unable to start the clientReconciler: %v", err) return err diff --git a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayclients.yaml b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayclients.yaml index 2aed5eeeb3..87116184b0 100644 --- a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayclients.yaml +++ b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayclients.yaml @@ -142,6 +142,24 @@ spec: mtu: description: MTU specifies the MTU of the tunnel. type: integer + secretRef: + description: |- + SecretRef specifies the reference to the secret containing the wireguard configuration. + Leave it empty to let the operator create a new secret. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + TODO: Add other useful fields. apiVersion, kind, uid? + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + TODO: Drop `kubebuilder:default` when controller-gen doesn't need it https://github.com/kubernetes-sigs/kubebuilder/issues/3896. + type: string + type: object + x-kubernetes-map-type: atomic type: object status: description: GatewayClientStatus defines the observed state of GatewayClient. diff --git a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayservers.yaml b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayservers.yaml index 91c13956d6..b1752490ec 100644 --- a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayservers.yaml +++ b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_gatewayservers.yaml @@ -104,6 +104,24 @@ spec: mtu: description: MTU specifies the MTU of the tunnel. type: integer + secretRef: + description: |- + SecretRef specifies the reference to the secret containing the wireguard configuration. + Leave it empty to let the operator create a new secret. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + TODO: Add other useful fields. apiVersion, kind, uid? + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + TODO: Drop `kubebuilder:default` when controller-gen doesn't need it https://github.com/kubernetes-sigs/kubebuilder/issues/3896. + type: string + type: object + x-kubernetes-map-type: atomic serverTemplateRef: description: ServerTemplateRef specifies the reference to the server template. diff --git a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayclients.yaml b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayclients.yaml index 453a974776..8f08b2ae54 100644 --- a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayclients.yaml +++ b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayclients.yaml @@ -9575,6 +9575,24 @@ spec: required: - enabled type: object + secretRef: + description: |- + SecretRef specifies the reference to the secret containing the wireguard configuration. + Leave it empty to let the operator create a new secret. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + TODO: Add other useful fields. apiVersion, kind, uid? + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + TODO: Drop `kubebuilder:default` when controller-gen doesn't need it https://github.com/kubernetes-sigs/kubebuilder/issues/3896. + type: string + type: object + x-kubernetes-map-type: atomic required: - deployment type: object diff --git a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayservers.yaml b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayservers.yaml index bf3b75b86a..147d3548c1 100644 --- a/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayservers.yaml +++ b/deployments/liqo/charts/liqo-crds/crds/networking.liqo.io_wggatewayservers.yaml @@ -9575,6 +9575,24 @@ spec: required: - enabled type: object + secretRef: + description: |- + SecretRef specifies the reference to the secret containing the wireguard configuration. + Leave it empty to let the operator create a new secret. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + TODO: Add other useful fields. apiVersion, kind, uid? + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + TODO: Drop `kubebuilder:default` when controller-gen doesn't need it https://github.com/kubernetes-sigs/kubebuilder/issues/3896. + type: string + type: object + x-kubernetes-map-type: atomic service: description: Service specifies the service template for the server. properties: diff --git a/deployments/liqo/files/liqo-gateway-ClusterRole.yaml b/deployments/liqo/files/liqo-gateway-ClusterRole.yaml index 82fdb1a8dc..642503f20e 100644 --- a/deployments/liqo/files/liqo-gateway-ClusterRole.yaml +++ b/deployments/liqo/files/liqo-gateway-ClusterRole.yaml @@ -20,16 +20,6 @@ rules: - patch - update - watch -- apiGroups: - - "" - resources: - - secrets - verbs: - - create - - delete - - get - - list - - update - apiGroups: - networking.liqo.io resources: diff --git a/deployments/liqo/templates/liqo-wireguard-gateway-client-template.yaml b/deployments/liqo/templates/liqo-wireguard-gateway-client-template.yaml index 724c1819fb..7672e9ff0d 100644 --- a/deployments/liqo/templates/liqo-wireguard-gateway-client-template.yaml +++ b/deployments/liqo/templates/liqo-wireguard-gateway-client-template.yaml @@ -19,6 +19,8 @@ spec: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 6 }} spec: + secretRef: + name: "{{"{{ .Spec.SecretRef.Name }}"}}" deployment: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 10 }} @@ -106,6 +108,9 @@ spec: {{ if .Values.networking.gatewayTemplates.wireguard.implementation | eq "userspace" }} privileged: true {{ end }} + volumeMounts: + - name: wireguard-config + mountPath: /etc/wireguard/keys - name: geneve image: {{ .Values.networking.gatewayTemplates.container.geneve.image.name }}{{ include "liqo.suffix" $geneveConfig }}:{{ include "liqo.version" $geneveConfig }} imagePullPolicy: {{ .Values.pullPolicy }} @@ -138,4 +143,8 @@ spec: - NET_RAW # Uncomment to set a priorityClassName # priorityClassName: "" + volumes: + - name: wireguard-config + secret: + secretName: "{{"{{ .SecretName }}"}}" {{- end }} diff --git a/deployments/liqo/templates/liqo-wireguard-gateway-server-template-eks.yaml b/deployments/liqo/templates/liqo-wireguard-gateway-server-template-eks.yaml index b26ca0f43a..9fc39ffa4d 100644 --- a/deployments/liqo/templates/liqo-wireguard-gateway-server-template-eks.yaml +++ b/deployments/liqo/templates/liqo-wireguard-gateway-server-template-eks.yaml @@ -19,6 +19,8 @@ spec: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 6 }} spec: + secretRef: + name: "{{"{{ .Spec.SecretRef.Name }}"}}" service: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 10 }} @@ -132,6 +134,9 @@ spec: {{ if .Values.networking.gatewayTemplates.wireguard.implementation | eq "userspace" }} privileged: true {{ end }} + volumeMounts: + - name: wireguard-config + mountPath: /etc/wireguard/keys - name: geneve image: {{ .Values.networking.gatewayTemplates.container.geneve.image.name }}{{ include "liqo.suffix" $geneveConfig }}:{{ include "liqo.version" $geneveConfig }} imagePullPolicy: {{ .Values.pullPolicy }} @@ -166,4 +171,8 @@ spec: image: nginx # Uncomment to set a priorityClassName # priorityClassName: "" + volumes: + - name: wireguard-config + secret: + secretName: "{{"{{ .SecretName }}"}}" {{- end }} diff --git a/deployments/liqo/templates/liqo-wireguard-gateway-server-template.yaml b/deployments/liqo/templates/liqo-wireguard-gateway-server-template.yaml index d3e71ae3a0..27bcc03b13 100644 --- a/deployments/liqo/templates/liqo-wireguard-gateway-server-template.yaml +++ b/deployments/liqo/templates/liqo-wireguard-gateway-server-template.yaml @@ -19,6 +19,8 @@ spec: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 6 }} spec: + secretRef: + name: "{{"{{ .Spec.SecretRef.Name }}"}}" service: metadata: {{- include "liqo.metadataTemplate" $templateConfig | nindent 10 }} @@ -123,6 +125,9 @@ spec: {{ if .Values.networking.gatewayTemplates.wireguard.implementation | eq "userspace" }} privileged: true {{ end }} + volumeMounts: + - name: wireguard-config + mountPath: /etc/wireguard/keys - name: geneve image: {{ .Values.networking.gatewayTemplates.container.geneve.image.name }}{{ include "liqo.suffix" $geneveConfig }}:{{ include "liqo.version" $geneveConfig }} imagePullPolicy: {{ .Values.pullPolicy }} @@ -155,4 +160,8 @@ spec: - NET_RAW # Uncomment to set a priorityClassName # priorityClassName: "" + volumes: + - name: wireguard-config + secret: + secretName: "{{"{{ .SecretName }}"}}" {{- end }} diff --git a/pkg/gateway/tunnel/wireguard/flags.go b/pkg/gateway/tunnel/wireguard/flags.go index de6272d105..0822e3d1f1 100644 --- a/pkg/gateway/tunnel/wireguard/flags.go +++ b/pkg/gateway/tunnel/wireguard/flags.go @@ -42,6 +42,8 @@ const ( FlagNameEndpointAddress FlagName = "endpoint-address" // FlagNameEndpointPort is the port of the endpoint for the wireguard interface. FlagNameEndpointPort FlagName = "endpoint-port" + // FlagNameKeysDir is the directory where the keys are stored. + FlagNameKeysDir FlagName = "keys-dir" // FlagNameDNSCheckInterval is the interval between two DNS checks. FlagNameDNSCheckInterval FlagName = "dns-check-interval" @@ -61,6 +63,7 @@ func InitFlags(flagset *pflag.FlagSet, opts *Options) { flagset.IntVar(&opts.ListenPort, FlagNameListenPort.String(), forge.DefaultGwServerPort, "Listen port (server only)") flagset.StringVar(&opts.EndpointAddress, FlagNameEndpointAddress.String(), "", "Endpoint address (client only)") flagset.IntVar(&opts.EndpointPort, FlagNameEndpointPort.String(), forge.DefaultGwServerPort, "Endpoint port (client only)") + flagset.StringVar(&opts.KeysDir, FlagNameKeysDir.String(), forge.DefaultKeysDir, "Directory where the keys are stored") flagset.DurationVar(&opts.DNSCheckInterval, FlagNameDNSCheckInterval.String(), 5*time.Minute, "Interval between two DNS checks") diff --git a/pkg/gateway/tunnel/wireguard/k8s.go b/pkg/gateway/tunnel/wireguard/k8s.go index a0ce795acd..f0c92b4cca 100644 --- a/pkg/gateway/tunnel/wireguard/k8s.go +++ b/pkg/gateway/tunnel/wireguard/k8s.go @@ -54,20 +54,20 @@ func CheckKeysSecret(ctx context.Context, cl client.Client, opts *Options) (wgty } // CreateKeysSecret creates the private and public keys for the Wireguard interface and save them inside a Secret resource. -func CreateKeysSecret(ctx context.Context, cl client.Client, opts *Options, pri, pub wgtypes.Key) error { +func CreateKeysSecret(ctx context.Context, cl client.Client, opts *gateway.Options, pri, pub wgtypes.Key) error { secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ - Name: forge.GatewayResourceName(opts.GwOptions.Name), - Namespace: opts.GwOptions.Namespace, + Name: forge.GatewayResourceName(opts.Name), + Namespace: opts.Namespace, }, } if _, err := controllerutil.CreateOrUpdate(ctx, cl, secret, func() error { secret.SetLabels(map[string]string{ - string(consts.RemoteClusterID): opts.GwOptions.RemoteClusterID, + string(consts.RemoteClusterID): opts.RemoteClusterID, string(consts.GatewayResourceLabel): string(consts.GatewayResourceLabelValue), }) - if err := gateway.SetOwnerReferenceWithMode(opts.GwOptions, secret, cl.Scheme()); err != nil { + if err := gateway.SetOwnerReferenceWithMode(opts, secret, cl.Scheme()); err != nil { return err } secret.Data = map[string][]byte{ diff --git a/pkg/gateway/tunnel/wireguard/keys.go b/pkg/gateway/tunnel/wireguard/keys.go index bca7a2fa55..b8bce22fc5 100644 --- a/pkg/gateway/tunnel/wireguard/keys.go +++ b/pkg/gateway/tunnel/wireguard/keys.go @@ -15,37 +15,39 @@ package wireguard import ( - "context" + "encoding/base64" + "io" + "os" + "path" + "path/filepath" "golang.zx2c4.com/wireguard/wgctrl/wgtypes" - kerrors "k8s.io/apimachinery/pkg/api/errors" - "sigs.k8s.io/controller-runtime/pkg/client" ) -// cluster-role -// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;create;delete;update - -// EnsureKeysSecret ensure the presence of the private and public keys for the Wireguard interface and save them inside a Secret resource and Options. -func EnsureKeysSecret(ctx context.Context, cl client.Client, opts *Options) error { - var pri, pub wgtypes.Key - var err error - pri, err = CheckKeysSecret(ctx, cl, opts) - - switch { - case kerrors.IsNotFound(err) || len(pri) == 0: - pri, err = wgtypes.GeneratePrivateKey() - if err != nil { - return err - } - pub = pri.PublicKey() - if err := CreateKeysSecret(ctx, cl, opts, pri, pub); err != nil { - return err - } - case err != nil: +// LoadKeys loads the keys from the specified directory. +func LoadKeys(options *Options) error { + // Load the keys + privKeyPath := path.Join(options.KeysDir, "privateKey") + + // read the private key from the file + privKeyFile, err := os.Open(filepath.Clean(privKeyPath)) + if err != nil { + return err + } + defer privKeyFile.Close() + + // base64 encoded private key + privKey, err := io.ReadAll(privKeyFile) + if err != nil { return err } - opts.PrivateKey = pri + base64PrivKey := base64.StdEncoding.EncodeToString(privKey) + wgtypesKey, err := wgtypes.ParseKey(base64PrivKey) + if err != nil { + return err + } + options.PrivateKey = wgtypesKey return nil } diff --git a/pkg/gateway/tunnel/wireguard/options.go b/pkg/gateway/tunnel/wireguard/options.go index 11ba8de229..89c7af8bd9 100644 --- a/pkg/gateway/tunnel/wireguard/options.go +++ b/pkg/gateway/tunnel/wireguard/options.go @@ -62,11 +62,13 @@ type Options struct { GwOptions *gateway.Options MTU int + SecretName string PrivateKey wgtypes.Key InterfaceIP string ListenPort int EndpointAddress string EndpointPort int + KeysDir string EndpointIP net.IP EndpointIPMutex *sync.Mutex diff --git a/pkg/liqo-controller-manager/networking/external-network/client-operator/client_controller.go b/pkg/liqo-controller-manager/networking/external-network/client-operator/client_controller.go index 7cda778f4b..ea3e71822a 100644 --- a/pkg/liqo-controller-manager/networking/external-network/client-operator/client_controller.go +++ b/pkg/liqo-controller-manager/networking/external-network/client-operator/client_controller.go @@ -26,6 +26,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/record" "k8s.io/klog/v2" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" @@ -44,6 +45,8 @@ type ClientReconciler struct { DynClient dynamic.Interface Factory *dynamicutils.RunnableFactory ClientResources []string + + eventRecorder record.EventRecorder } type templateData struct { @@ -52,11 +55,13 @@ type templateData struct { Namespace string GatewayUID string ClusterID string + SecretName string } // NewClientReconciler returns a new ClientReconciler. func NewClientReconciler(cl client.Client, dynClient dynamic.Interface, factory *dynamicutils.RunnableFactory, s *runtime.Scheme, + eventRecorder record.EventRecorder, clientResources []string) *ClientReconciler { return &ClientReconciler{ Client: cl, @@ -64,6 +69,8 @@ func NewClientReconciler(cl client.Client, dynClient dynamic.Interface, DynClient: dynClient, Factory: factory, ClientResources: clientResources, + + eventRecorder: eventRecorder, } } @@ -94,7 +101,10 @@ func (r *ClientReconciler) Reconcile(ctx context.Context, req ctrl.Request) (res } klog.Errorf("Unable to update the gateway client %q: %s", req.NamespacedName, newErr) err = newErr + return } + + r.eventRecorder.Eventf(gwClient, corev1.EventTypeNormal, "Reconciled", "Reconciled GatewayClient %q", gwClient.Name) }() if err = r.EnsureGatewayClient(ctx, gwClient); err != nil { @@ -168,6 +178,7 @@ func (r *ClientReconciler) EnsureGatewayClient(ctx context.Context, gwClient *ne Namespace: gwClient.Namespace, GatewayUID: string(gwClient.UID), ClusterID: remoteClusterID, + SecretName: gwClient.Spec.SecretRef.Name, } name, err := enutils.RenderTemplate(objectTemplateMetadata["name"], td, true) diff --git a/pkg/liqo-controller-manager/networking/external-network/server-operator/server_controller.go b/pkg/liqo-controller-manager/networking/external-network/server-operator/server_controller.go index f01dd37035..161d5c90bf 100644 --- a/pkg/liqo-controller-manager/networking/external-network/server-operator/server_controller.go +++ b/pkg/liqo-controller-manager/networking/external-network/server-operator/server_controller.go @@ -26,6 +26,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" + "k8s.io/client-go/tools/record" "k8s.io/klog/v2" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" @@ -44,6 +45,8 @@ type ServerReconciler struct { DynClient dynamic.Interface Factory *dynamicutils.RunnableFactory ServerResources []string + + eventRecorder record.EventRecorder } type templateData struct { @@ -52,11 +55,13 @@ type templateData struct { Namespace string GatewayUID string ClusterID string + SecretName string } // NewServerReconciler returns a new ServerReconciler. func NewServerReconciler(cl client.Client, dynClient dynamic.Interface, factory *dynamicutils.RunnableFactory, s *runtime.Scheme, + eventRecorder record.EventRecorder, serverResources []string) *ServerReconciler { return &ServerReconciler{ Client: cl, @@ -64,6 +69,8 @@ func NewServerReconciler(cl client.Client, dynClient dynamic.Interface, DynClient: dynClient, Factory: factory, ServerResources: serverResources, + + eventRecorder: eventRecorder, } } @@ -94,7 +101,10 @@ func (r *ServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (res } klog.Errorf("Unable to update the gateway server %q: %s", req.NamespacedName, newErr) err = newErr + return } + + r.eventRecorder.Eventf(gwServer, corev1.EventTypeNormal, "Reconciled", "Reconciled GatewayServer %q", gwServer.Name) }() if err = r.EnsureGatewayServer(ctx, gwServer); err != nil { @@ -168,6 +178,7 @@ func (r *ServerReconciler) EnsureGatewayServer(ctx context.Context, gwServer *ne Namespace: gwServer.Namespace, GatewayUID: string(gwServer.UID), ClusterID: remoteClusterID, + SecretName: gwServer.Spec.SecretRef.Name, } name, err := enutils.RenderTemplate(objectTemplateMetadata["name"], td, true) diff --git a/pkg/liqo-controller-manager/networking/external-network/wireguard/utils.go b/pkg/liqo-controller-manager/networking/external-network/wireguard/utils.go index a828717d78..563cfeac6d 100644 --- a/pkg/liqo-controller-manager/networking/external-network/wireguard/utils.go +++ b/pkg/liqo-controller-manager/networking/external-network/wireguard/utils.go @@ -19,8 +19,10 @@ import ( "fmt" "strconv" + "golang.zx2c4.com/wireguard/wgctrl/wgtypes" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" + kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -29,11 +31,18 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/predicate" + networkingv1beta1 "github.com/liqotech/liqo/apis/networking/v1beta1" "github.com/liqotech/liqo/pkg/consts" + "github.com/liqotech/liqo/pkg/gateway" "github.com/liqotech/liqo/pkg/gateway/forge" + "github.com/liqotech/liqo/pkg/gateway/tunnel/wireguard" liqolabels "github.com/liqotech/liqo/pkg/utils/labels" ) +const ( + wireguardVolumeName = "wireguard-config" +) + func filterWireGuardSecretsPredicate() predicate.Predicate { filterGatewayResources, err := predicate.LabelSelectorPredicate(liqolabels.GatewayResourceLabelSelector) utilruntime.Must(err) @@ -88,6 +97,52 @@ func clusterRoleBindingEnquerer(_ context.Context, obj client.Object) []ctrl.Req } } +// ensureKeysSecret ensure the presence of the private and public keys for the Wireguard interface and save them inside a Secret resource and Options. +func ensureKeysSecret(ctx context.Context, cl client.Client, wgObj metav1.Object, mode gateway.Mode) error { + var controllerRef metav1.OwnerReference + for _, ref := range wgObj.GetOwnerReferences() { + if ref.Controller != nil && *ref.Controller { + switch ref.Kind { + case networkingv1beta1.GatewayClientKind: + controllerRef = ref + case networkingv1beta1.GatewayServerKind: + controllerRef = ref + } + break + } + } + + opts := &gateway.Options{ + Name: controllerRef.Name, + Namespace: wgObj.GetNamespace(), + RemoteClusterID: wgObj.GetLabels()[consts.RemoteClusterID], + GatewayUID: string(controllerRef.UID), + Mode: mode, + } + + _, err := getWireGuardSecret(ctx, cl, wgObj) + switch { + case kerrors.IsNotFound(err): + pri, err := wgtypes.GeneratePrivateKey() + if err != nil { + klog.Error(err) + return err + } + pub := pri.PublicKey() + if err := wireguard.CreateKeysSecret(ctx, cl, opts, pri, pub); err != nil { + klog.Error(err) + return err + } + klog.Infof("Keys secret for WireGuard gateway %q correctly enforced", wgObj.GetName()) + return nil + case err != nil: + klog.Error(err) + return err + default: + return nil + } +} + func getWireGuardSecret(ctx context.Context, cl client.Client, wgObj metav1.Object) (*corev1.Secret, error) { wgObjNsName := types.NamespacedName{Name: wgObj.GetName(), Namespace: wgObj.GetNamespace()} @@ -111,8 +166,8 @@ func getWireGuardSecret(ctx context.Context, cl client.Client, wgObj metav1.Obje switch len(secrets.Items) { case 0: - klog.Warningf("Secret associated to WireGuard gateway %q not found", wgObjNsName) - return nil, nil + err = kerrors.NewNotFound(corev1.Resource("Secret"), wgObjNsName.Name) + return nil, err case 1: return &secrets.Items[0], nil default: diff --git a/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayclient_controller.go b/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayclient_controller.go index 5024662514..738f078ad9 100644 --- a/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayclient_controller.go +++ b/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayclient_controller.go @@ -24,10 +24,12 @@ import ( rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" + kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" "k8s.io/klog/v2" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" @@ -38,6 +40,7 @@ import ( networkingv1beta1 "github.com/liqotech/liqo/apis/networking/v1beta1" "github.com/liqotech/liqo/pkg/consts" + "github.com/liqotech/liqo/pkg/gateway" "github.com/liqotech/liqo/pkg/gateway/forge" enutils "github.com/liqotech/liqo/pkg/liqo-controller-manager/networking/external-network/utils" mapsutil "github.com/liqotech/liqo/pkg/utils/maps" @@ -48,15 +51,20 @@ type WgGatewayClientReconciler struct { client.Client Scheme *runtime.Scheme clusterRoleName string + + eventRecorder record.EventRecorder } // NewWgGatewayClientReconciler returns a new WgGatewayClientReconciler. func NewWgGatewayClientReconciler(cl client.Client, s *runtime.Scheme, + recorder record.EventRecorder, clusterRoleName string) *WgGatewayClientReconciler { return &WgGatewayClientReconciler{ Client: cl, Scheme: s, clusterRoleName: clusterRoleName, + + eventRecorder: recorder, } } @@ -64,7 +72,7 @@ func NewWgGatewayClientReconciler(cl client.Client, s *runtime.Scheme, // +kubebuilder:rbac:groups=networking.liqo.io,resources=wggatewayclients,verbs=get;list;watch;delete;create;update;patch // +kubebuilder:rbac:groups=networking.liqo.io,resources=wggatewayclients/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;delete;create;update;patch -// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch +// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;create;delete;update // +kubebuilder:rbac:groups=monitoring.coreos.com,resources=servicemonitors,verbs=get;list;watch;delete;create;update;patch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch;delete;create;update;patch // +kubectl:rbac:groups=core,resources=serviceaccounts,verbs=get;list;watch;delete;create;update;patch @@ -117,20 +125,19 @@ func (r *WgGatewayClientReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, nil } - // Ensure deployment (create or update) - var deploy *appsv1.Deployment deployNsName := types.NamespacedName{Namespace: wgClient.Namespace, Name: forge.GatewayResourceName(wgClient.Name)} - deploy, err = r.ensureDeployment(ctx, wgClient, deployNsName) - if err != nil { - return ctrl.Result{}, err - } - // Ensure Metrics (if set) - err = enutils.EnsureMetrics(ctx, - r.Client, r.Scheme, - wgClient.Spec.Metrics, wgClient) - if err != nil { + var deploy *appsv1.Deployment + var d appsv1.Deployment + err = r.Get(ctx, deployNsName, &d) + switch { + case kerrors.IsNotFound(err): + deploy = nil + case err != nil: + klog.Errorf("error while getting deployment %q: %v", deployNsName, err) return ctrl.Result{}, err + default: + deploy = &d } // Handle status @@ -142,7 +149,10 @@ func (r *WgGatewayClientReconciler) Reconcile(ctx context.Context, req ctrl.Requ } klog.Errorf("Unable to update the WireGuard gateway client status %q: %s", req.NamespacedName, newErr) err = newErr + return } + + r.eventRecorder.Event(wgClient, corev1.EventTypeNormal, "Reconciled", "WireGuard gateway client reconciled") }() if err := r.handleSecretRefStatus(ctx, wgClient); err != nil { @@ -153,6 +163,30 @@ func (r *WgGatewayClientReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, err } + if wgClient.Spec.SecretRef.Name == "" { + // Ensure WireGuard keys secret (create or update) + if err = ensureKeysSecret(ctx, r.Client, wgClient, gateway.ModeClient); err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgClient, corev1.EventTypeNormal, "KeysSecretEnforced", "Enforced keys secret") + } + + // Ensure deployment (create or update) + _, err = r.ensureDeployment(ctx, wgClient, deployNsName) + if err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgClient, corev1.EventTypeNormal, "DeploymentEnforced", "Enforced deployment") + + // Ensure Metrics (if set) + err = enutils.EnsureMetrics(ctx, + r.Client, r.Scheme, + wgClient.Spec.Metrics, wgClient) + if err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgClient, corev1.EventTypeNormal, "MetricsEnforced", "Enforced metrics") + return ctrl.Result{}, nil } @@ -197,32 +231,47 @@ func (r *WgGatewayClientReconciler) mutateFnWgClientDeployment(deployment *appsv // Forge spec deployment.Spec = wgClient.Spec.Deployment.Spec + if wgClient.Status.SecretRef != nil { + for i := range deployment.Spec.Template.Spec.Volumes { + if deployment.Spec.Template.Spec.Volumes[i].Name == wireguardVolumeName { + deployment.Spec.Template.Spec.Volumes[i].Secret = &corev1.SecretVolumeSource{ + SecretName: wgClient.Status.SecretRef.Name, + } + break + } + } + } else { + r.eventRecorder.Event(wgClient, corev1.EventTypeWarning, "MissingSecretRef", "WireGuard keys secret not found") + } + // Set WireGuard client as owner of the deployment return controllerutil.SetControllerReference(wgClient, deployment, r.Scheme) } func (r *WgGatewayClientReconciler) handleSecretRefStatus(ctx context.Context, wgClient *networkingv1beta1.WgGatewayClient) error { secret, err := getWireGuardSecret(ctx, r.Client, wgClient) - if err != nil { - return err - } - - // Put secret reference in WireGuard client status - if secret == nil { - // if the secret is not found, we cancel the reference as it could be not valid anymore + switch { + case kerrors.IsNotFound(err): wgClient.Status.SecretRef = nil - } else { + return nil + case err != nil: + return err + default: wgClient.Status.SecretRef = &corev1.ObjectReference{ Name: secret.Name, Namespace: secret.Namespace, } + return nil } - - return nil } func (r *WgGatewayClientReconciler) handleInternalEndpointStatus(ctx context.Context, wgClient *networkingv1beta1.WgGatewayClient, dep *appsv1.Deployment) error { + if dep == nil { + wgClient.Status.InternalEndpoint = nil + return nil + } + podsFromDepSelector := client.MatchingLabelsSelector{Selector: labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)} var podList corev1.PodList if err := r.List(ctx, &podList, client.InNamespace(dep.Namespace), podsFromDepSelector); err != nil { diff --git a/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayserver_controller.go b/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayserver_controller.go index 5f1d3476be..03145c1a87 100644 --- a/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayserver_controller.go +++ b/pkg/liqo-controller-manager/networking/external-network/wireguard/wggatewayserver_controller.go @@ -28,6 +28,7 @@ import ( "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" "k8s.io/klog/v2" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" @@ -38,6 +39,7 @@ import ( networkingv1beta1 "github.com/liqotech/liqo/apis/networking/v1beta1" "github.com/liqotech/liqo/pkg/consts" + "github.com/liqotech/liqo/pkg/gateway" "github.com/liqotech/liqo/pkg/gateway/forge" enutils "github.com/liqotech/liqo/pkg/liqo-controller-manager/networking/external-network/utils" "github.com/liqotech/liqo/pkg/utils" @@ -49,15 +51,20 @@ type WgGatewayServerReconciler struct { client.Client Scheme *runtime.Scheme clusterRoleName string + + eventRecorder record.EventRecorder } // NewWgGatewayServerReconciler returns a new WgGatewayServerReconciler. func NewWgGatewayServerReconciler(cl client.Client, s *runtime.Scheme, + recorder record.EventRecorder, clusterRoleName string) *WgGatewayServerReconciler { return &WgGatewayServerReconciler{ Client: cl, Scheme: s, clusterRoleName: clusterRoleName, + + eventRecorder: recorder, } } @@ -67,7 +74,7 @@ func NewWgGatewayServerReconciler(cl client.Client, s *runtime.Scheme, // +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch // +kubebuilder:rbac:groups=core,resources=nodes,verbs=get;list;watch // +kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;delete;create;update;patch -// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch +// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;create;delete;update // +kubebuilder:rbac:groups=monitoring.coreos.com,resources=servicemonitors,verbs=get;list;watch;delete;create;update;patch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch;delete;create;update;patch // +kubectl:rbac:groups=core,resources=serviceaccounts,verbs=get;list;watch;delete;create;update;patch @@ -120,26 +127,20 @@ func (r *WgGatewayServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, nil } - // Ensure deployment (create or update) deployNsName := types.NamespacedName{Namespace: wgServer.Namespace, Name: forge.GatewayResourceName(wgServer.Name)} - deploy, err := r.ensureDeployment(ctx, wgServer, deployNsName) - if err != nil { - return ctrl.Result{}, err - } - - // Ensure service (create or update) svcNsName := types.NamespacedName{Namespace: wgServer.Namespace, Name: forge.GatewayResourceName(wgServer.Name)} - _, err = r.ensureService(ctx, wgServer, svcNsName) - if err != nil { - return ctrl.Result{}, err - } - // Ensure Metrics (if set) - err = enutils.EnsureMetrics(ctx, - r.Client, r.Scheme, - wgServer.Spec.Metrics, wgServer) - if err != nil { + var deploy *appsv1.Deployment + var d appsv1.Deployment + err = r.Get(ctx, deployNsName, &d) + switch { + case apierrors.IsNotFound(err): + deploy = nil + case err != nil: + klog.Errorf("Unable to get the deployment %q: %v", deployNsName, err) return ctrl.Result{}, err + default: + deploy = &d } // Handle status @@ -151,7 +152,10 @@ func (r *WgGatewayServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ } klog.Errorf("Unable to update the WireGuard gateway server status %q: %s", req.NamespacedName, newErr) err = newErr + return } + + r.eventRecorder.Event(wgServer, corev1.EventTypeNormal, "Reconciled", "WireGuard gateway server reconciled") }() if err := r.handleEndpointStatus(ctx, wgServer, svcNsName, deploy); err != nil { @@ -166,6 +170,37 @@ func (r *WgGatewayServerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, err } + if wgServer.Spec.SecretRef.Name == "" { + // Ensure WireGuard keys secret (create or update) + if err = ensureKeysSecret(ctx, r.Client, wgServer, gateway.ModeServer); err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgServer, corev1.EventTypeNormal, "KeysSecretEnforced", "Enforced keys secret") + } + + // Ensure deployment (create or update) + _, err = r.ensureDeployment(ctx, wgServer, deployNsName) + if err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgServer, corev1.EventTypeNormal, "DeploymentEnforced", "Enforced deployment") + + // Ensure service (create or update) + _, err = r.ensureService(ctx, wgServer, svcNsName) + if err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgServer, corev1.EventTypeNormal, "ServiceEnforced", "Enforced service") + + // Ensure Metrics (if set) + err = enutils.EnsureMetrics(ctx, + r.Client, r.Scheme, + wgServer.Spec.Metrics, wgServer) + if err != nil { + return ctrl.Result{}, err + } + r.eventRecorder.Event(wgServer, corev1.EventTypeNormal, "MetricsEnforced", "Enforced metrics") + return ctrl.Result{}, nil } @@ -230,6 +265,19 @@ func (r *WgGatewayServerReconciler) mutateFnWgServerDeployment(deployment *appsv // Forge spec deployment.Spec = wgServer.Spec.Deployment.Spec + if wgServer.Status.SecretRef != nil { + for i := range deployment.Spec.Template.Spec.Volumes { + if deployment.Spec.Template.Spec.Volumes[i].Name == wireguardVolumeName { + deployment.Spec.Template.Spec.Volumes[i].Secret = &corev1.SecretVolumeSource{ + SecretName: wgServer.Status.SecretRef.Name, + } + break + } + } + } else { + r.eventRecorder.Event(wgServer, corev1.EventTypeWarning, "MissingSecretRef", "WireGuard keys secret not found") + } + // Set WireGuard server as owner of the deployment return controllerutil.SetControllerReference(wgServer, deployment, r.Scheme) } @@ -252,6 +300,11 @@ func (r *WgGatewayServerReconciler) mutateFnWgServerService(service *corev1.Serv func (r *WgGatewayServerReconciler) handleEndpointStatus(ctx context.Context, wgServer *networkingv1beta1.WgGatewayServer, svcNsName types.NamespacedName, dep *appsv1.Deployment) error { + if dep == nil { + wgServer.Status.Endpoint = nil + return nil + } + // Handle WireGuard server Service var service corev1.Service err := r.Get(ctx, svcNsName, &service) @@ -471,26 +524,28 @@ func (r *WgGatewayServerReconciler) forgeEndpointStatusLoadBalancer(service *cor func (r *WgGatewayServerReconciler) handleSecretRefStatus(ctx context.Context, wgServer *networkingv1beta1.WgGatewayServer) error { secret, err := getWireGuardSecret(ctx, r.Client, wgServer) - if err != nil { - return err - } - - // Put secret reference in WireGuard server status - if secret == nil { - // if the secret is not found, we cancel the reference as it could be not valid anymore + switch { + case apierrors.IsNotFound(err): wgServer.Status.SecretRef = nil - } else { + return nil + case err != nil: + return err + default: wgServer.Status.SecretRef = &corev1.ObjectReference{ Name: secret.Name, Namespace: secret.Namespace, } + return nil } - - return nil } func (r *WgGatewayServerReconciler) handleInternalEndpointStatus(ctx context.Context, wgServer *networkingv1beta1.WgGatewayServer, svcNsName types.NamespacedName, dep *appsv1.Deployment) error { + if dep == nil { + wgServer.Status.InternalEndpoint = nil + return nil + } + var service corev1.Service err := r.Get(ctx, svcNsName, &service) if err != nil { diff --git a/pkg/liqo-controller-manager/networking/forge/gatewayserver.go b/pkg/liqo-controller-manager/networking/forge/gatewayserver.go index 5562116f63..617f355129 100644 --- a/pkg/liqo-controller-manager/networking/forge/gatewayserver.go +++ b/pkg/liqo-controller-manager/networking/forge/gatewayserver.go @@ -31,6 +31,7 @@ const ( DefaultGwServerTemplateName = "wireguard-server" DefaultGwServerServiceType = corev1.ServiceTypeLoadBalancer DefaultGwServerPort = 51840 + DefaultKeysDir = "/etc/wireguard/keys" ) // DefaultGatewayServerName returns the default name for a GatewayServer.