Skip to content

Commit

Permalink
Merge pull request #15 from snapp-incubator/create-svc
Browse files Browse the repository at this point in the history
adding service creation for deployments
  • Loading branch information
sinamna committed Dec 11, 2023
2 parents e34c8c2 + 9dd1af9 commit b8a4207
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 8 deletions.
4 changes: 4 additions & 0 deletions api/v1alpha1/basicauthenticator_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ type BasicAuthenticatorSpec struct {
// +kubebuilder:validation:Optional
Selector metav1.LabelSelector `json:"selector,omitempty"`

// +kubebuilder:validation:Optional
// +kubebuilder:default=ClusterIP
ServiceType string `json:"serviceType"`

// +kubebuilder:validation:Required
AppPort int `json:"appPort"`

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ spec:
type: object
type: object
x-kubernetes-map-type: atomic
serviceType:
default: ClusterIP
type: string
type:
description: Type is used to determine that nginx should be sidercar
or deployment
Expand Down
12 changes: 12 additions & 0 deletions config/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,15 @@ rules:
- patch
- update
- watch
- apiGroups:
- ""
resources:
- services
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/snapp-incubator/simple-authenticator/internal/config"
appv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
Expand All @@ -41,6 +42,7 @@ type BasicAuthenticatorReconciler struct {
configMapName string
credentialName string
basicAuthenticatorNamespace string
deploymentLabel *v1.LabelSelector
logger logr.Logger
}

Expand Down Expand Up @@ -72,6 +74,7 @@ func (r *BasicAuthenticatorReconciler) SetupWithManager(mgr ctrl.Manager) error
Owns(&appv1.Deployment{}).
Owns(&corev1.ConfigMap{}).
Owns(&corev1.Secret{}).
Owns(&corev1.Service{}).
Watches(
&source.Kind{Type: &appv1.Deployment{}},
handler.EnqueueRequestsFromMapFunc(r.findExternallyManagedDeployments),
Expand Down
47 changes: 42 additions & 5 deletions internal/controller/basic_authenticator/provision.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func (r *BasicAuthenticatorReconciler) Provision(ctx context.Context, req ctrl.R
r.ensureSecret,
r.ensureConfigmap,
r.ensureDeployment,
r.ensureService,
}
for _, provisioner := range subProvisioner {
result, err := provisioner(ctx, req)
Expand Down Expand Up @@ -177,7 +178,45 @@ func (r *BasicAuthenticatorReconciler) ensureDeployment(ctx context.Context, req
return r.createDeploymentAuthenticator(ctx, req, basicAuthenticator, r.configMapName, r.credentialName)
}
}
func (r *BasicAuthenticatorReconciler) ensureService(ctx context.Context, req ctrl.Request) (*ctrl.Result, error) {
basicAuthenticator := &v1alpha1.BasicAuthenticator{}

if r, err := r.getLatestBasicAuthenticator(ctx, req, basicAuthenticator); subreconciler.ShouldHaltOrRequeue(r, err) {
return r, err
}
if r.deploymentLabel == nil {
return subreconciler.ContinueReconciling()
}
newService := createNginxService(ctx, basicAuthenticator, r.deploymentLabel)
foundService := corev1.Service{}
err := r.Get(ctx, types.NamespacedName{Name: newService.Name, Namespace: newService.Namespace}, &foundService)
if errors.IsNotFound(err) {
if err := ctrl.SetControllerReference(basicAuthenticator, newService, r.Scheme); err != nil {
r.logger.Error(err, "failed to set service owner")
return subreconciler.RequeueWithError(err)
}
err := r.Create(ctx, newService)
if err != nil {
r.logger.Error(err, "failed to create new service")
return subreconciler.RequeueWithError(err)
}

} else if err != nil {
r.logger.Error(err, "failed to fetch service")
return subreconciler.RequeueWithError(err)
} else {
if !reflect.DeepEqual(newService.Spec, foundService.Spec) {
r.logger.Info("updating service")
foundService.Spec = newService.Spec
err := r.Update(ctx, &foundService)
if err != nil {
r.logger.Error(err, "failed to update service")
return subreconciler.RequeueWithError(err)
}
}
}
return subreconciler.ContinueReconciling()
}
func (r *BasicAuthenticatorReconciler) createDeploymentAuthenticator(ctx context.Context, req ctrl.Request, basicAuthenticator *v1alpha1.BasicAuthenticator, authenticatorConfigName, secretName string) (*ctrl.Result, error) {

newDeployment := createNginxDeployment(basicAuthenticator, authenticatorConfigName, secretName, r.CustomConfig)
Expand All @@ -203,12 +242,10 @@ func (r *BasicAuthenticatorReconciler) createDeploymentAuthenticator(ctx context
return subreconciler.RequeueWithError(err)
}
r.logger.Info("created deployment")

r.deploymentLabel = newDeployment.Spec.Selector
} else if err != nil {
if err != nil {
r.logger.Error(err, "failed to fetch deployment")
return subreconciler.RequeueWithError(err)
}
r.logger.Error(err, "failed to fetch deployment")
return subreconciler.RequeueWithError(err)
} else {
//update deployment
targetReplica := newDeployment.Spec.Replicas
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
"strings"
)
Expand Down Expand Up @@ -90,7 +91,6 @@ func createNginxDeployment(basicAuthenticator *v1alpha1.BasicAuthenticator, conf
},
},
}

return deploy
}

Expand Down Expand Up @@ -153,7 +153,29 @@ func createCredentials(basicAuthenticator *v1alpha1.BasicAuthenticator) (*corev1
}
return secret, nil
}

func createNginxService(ctx context.Context, basicAuthenticator *v1alpha1.BasicAuthenticator, selector *metav1.LabelSelector) *corev1.Service {
serviceName := fmt.Sprintf("%s-svc", basicAuthenticator.Name)
serviceType := getServiceType(basicAuthenticator.Spec.ServiceType)
targetPort := intstr.IntOrString{Type: intstr.Int, IntVal: int32(basicAuthenticator.Spec.AuthenticatorPort)}
svc := corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: serviceName,
Namespace: basicAuthenticator.Namespace,
},
Spec: corev1.ServiceSpec{
Selector: selector.MatchLabels,
Type: serviceType,
Ports: []corev1.ServicePort{
{
Port: int32(basicAuthenticator.Spec.AuthenticatorPort),
TargetPort: targetPort,
Name: "authenticator",
},
},
},
}
return &svc
}
func injector(ctx context.Context, basicAuthenticator *v1alpha1.BasicAuthenticator, configMapName string, credentialName string, customConfig *config.CustomConfig, k8Client client.Client) ([]*appsv1.Deployment, error) {
nginxImageAddress := getNginxContainerImage(customConfig)
nginxContainerName := getNginxContainerName(customConfig)
Expand Down Expand Up @@ -236,3 +258,14 @@ func fillTemplate(template string, secretPath string, authenticator *v1alpha1.Ba
result = strings.Replace(result, "APP_PORT", fmt.Sprintf("%d", authenticator.Spec.AppPort), 1)
return result
}

func getServiceType(serviceType string) corev1.ServiceType {
switch serviceType {
case "NodePort":
return corev1.ServiceTypeNodePort
case "LoadBalancer":
return corev1.ServiceTypeLoadBalancer
default:
return corev1.ServiceTypeClusterIP
}
}
2 changes: 1 addition & 1 deletion tests/e2e/deployment/00-install.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ spec:
appPort: 8081
appService: google.com
adaptiveScale: false
authenticatorPort: 8080
authenticatorPort: 8082
4 changes: 4 additions & 0 deletions tests/e2e/deployment/02-assert.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
apiVersion: v1
kind: Service
metadata:
name: basicauthenticator-sample-svc

0 comments on commit b8a4207

Please sign in to comment.