Skip to content
This repository was archived by the owner on Jun 11, 2025. It is now read-only.

Conversation

@nxtcoder17
Copy link
Member

@nxtcoder17 nxtcoder17 commented Nov 16, 2024

Summary by Sourcery

Introduce a new ServiceIntercept feature with a custom resource definition and controller to manage service intercepts in Kubernetes. Update kustomization and build configurations to support the new feature.

New Features:

  • Introduce a new ServiceIntercept custom resource definition (CRD) to manage service intercepts within the Kubernetes cluster.
  • Add a new controller for handling ServiceIntercept resources, including reconciliation logic and webhook setup for pod mutation.

Enhancements:

  • Enhance the kustomization configuration to include the new ServiceIntercept CRD and related resources.

Build:

  • Add Dockerfile and Taskfile for building and running the service-intercept component.

@sourcery-ai
Copy link

sourcery-ai bot commented Nov 16, 2024

Reviewer's Guide by Sourcery

This PR implements a new ServiceIntercept CRD and controller that enables service interception functionality in Kubernetes clusters. The implementation includes a mutating webhook for pod interception, TLS certificate generation utilities, and the necessary controller logic to manage service intercepts.

Class diagram for ServiceIntercept CRD

classDiagram
    class ServiceIntercept {
        +TypeMeta
        +ObjectMeta
        +ServiceInterceptSpec Spec
        +ServiceInterceptStatus Status
        +EnsureGVK()
        +GetStatus() rApi.Status
        +GetEnsuredLabels() map[string]string
        +GetEnsuredAnnotations() map[string]string
    }
    class ServiceInterceptSpec {
        +string ToAddr
        +SvcInterceptPortMappings[] PortMappings
    }
    class ServiceInterceptStatus {
        +rApi.Status
        +map[string]string Selector
    }
    class SvcInterceptPortMappings {
        +uint16 ContainerPort
        +uint16 ServicePort
    }
    ServiceIntercept --> ServiceInterceptSpec
    ServiceIntercept --> ServiceInterceptStatus
    ServiceInterceptSpec --> SvcInterceptPortMappings
Loading

File-Level Changes

Change Details Files
Implements new ServiceIntercept CRD and types
  • Adds ServiceIntercept CRD with spec for port mappings and target address
  • Implements DeepCopy functions for ServiceIntercept types
  • Adds status fields for tracking service selector and reconciliation state
apis/crds/v1/zz_generated.deepcopy.go
apis/crds/v1/serviceintercept_types.go
config/crd/bases/crds.kloudlite.io_serviceintercepts.yaml
Creates service intercept controller and webhook implementation
  • Implements mutating webhook for intercepting pod creation
  • Adds controller logic for managing service intercepts
  • Creates templates for service intercept resources
  • Implements TLS certificate generation for webhook security
operators/service-intercept/internal/controllers/svci/controller.go
operators/service-intercept/internal/cmd/webhook/main.go
operators/service-intercept/internal/templates/svc-intercept.yml.tpl
operators/service-intercept/internal/templates/webhook.yml.tpl
pkg/tls_utils/cert-gen.go
Integrates service intercept functionality into operator framework
  • Registers service intercept controller in agent and platform operators
  • Adds RBAC roles for ServiceIntercept resources
  • Updates kustomization to include new CRD
cmd/agent-operator/main.go
cmd/platform-operator/main.go
config/rbac/crds_serviceintercept_editor_role.yaml
config/rbac/crds_serviceintercept_viewer_role.yaml
config/crd/kustomization.yaml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@nxtcoder17 nxtcoder17 changed the title Feat/svc intercept @sourcery-ai title Nov 16, 2024
@sourcery-ai sourcery-ai bot changed the title @sourcery-ai title feat: add ServiceIntercept CRD and controller for Kubernetes Nov 16, 2024
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @nxtcoder17 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • There's a commented out error return in the TLS cert generation code (networking/internal/gateway/generate-tls-certs.go). This should either be removed or properly handled to avoid masking certificate generation failures.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -42,7 +42,7 @@ func GenTLSCert(dnsNames []string) (caBundle []byte, tlsCert []byte, tlsKey []by
caCertPEM := new(bytes.Buffer)
err = pem.Encode(caCertPEM, &pem.Block{Type: "CERTIFICATE", Bytes: caCertBytes})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Error from PEM encoding should be properly handled rather than commented out

Ignoring PEM encoding errors could mask serious issues. The error should be propagated to the caller.

return check.Failed(err)
}

for _, p := range podList.Items {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Pod deletion handling needs to be more robust against edge cases

The pod deletion logic should handle cases where pods can't be deleted immediately due to network issues or other failures. Consider adding retry logic with timeouts.

return check.Completed()
}

func (r *Reconciler) createSvcIntercept(req *rApi.Request[*crdsv1.ServiceIntercept]) stepResult.Result {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting pod creation logic and flattening nested control flow in service intercept methods

The createSvcIntercept and trackInterceptSvc methods could be simplified without losing functionality. Consider:

  1. Extract pod creation logic into a helper function:
func (r *Reconciler) buildInterceptPod(obj *crdsv1.ServiceIntercept, svc *corev1.Service) (*corev1.Pod, error) {
    portMappings := make(map[uint16]uint16, len(obj.Spec.PortMappings))
    for _, pm := range obj.Spec.PortMappings {
        portMappings[pm.ContainerPort] = pm.ServicePort
    }

    if obj.Spec.ToAddr == "" {
        return nil, fmt.Errorf("no address configured on service intercept")
    }

    return templates.ParsePodSpec(r.svcInterceptTemplate, map[string]any{
        "name":      obj.Name + "-intercept",
        "namespace": obj.Namespace,
        "labels": fn.MapMerge(
            map[string]string{
                svciGenerationLabel: fmt.Sprintf("%d", obj.Generation),
                CreatedForLabel:     "intercept",
            },
            svc.Spec.Selector,
        ),
        "owner-references": []metav1.OwnerReference{fn.AsOwner(obj, true)},
        "device-host":      obj.Spec.ToAddr,
        "port-mappings":    portMappings,
    })
}
  1. Flatten trackInterceptSvc with early returns:
func (r *Reconciler) trackInterceptSvc(req *rApi.Request[*crdsv1.ServiceIntercept]) stepResult.Result {
    ctx, obj := req.Context(), req.Object
    check := rApi.NewRunningCheck(TrackInterceptedSvc, req)

    svc, err := rApi.Get(ctx, r.Client, fn.NN(obj.Namespace, obj.Name), &corev1.Service{})
    if err != nil {
        return check.Failed(err)
    }

    if !fn.IsOwner(obj, fn.AsOwner(svc, true)) {
        obj.SetOwnerReferences(append(obj.GetOwnerReferences(), fn.AsOwner(svc, true)))
        if err := r.Update(ctx, obj); err != nil {
            return check.Failed(err)
        }
        return check.StillRunning(fmt.Errorf("waiting for reconciliation")).RequeueAfter(1 * time.Second)
    }

    if err := r.updateSelectorStatus(ctx, obj, svc); err != nil {
        return check.StillRunning(err).RequeueAfter(1 * time.Second)
    }

    return r.cleanupNonInterceptPods(ctx, check, obj, svc)
}

These changes improve readability by:

  • Separating pod creation logic from state management
  • Reducing nesting through early returns
  • Breaking complex methods into focused helper functions

@nxtcoder17 nxtcoder17 merged commit 289ea4d into release-v1.1.3 Nov 16, 2024
@nxtcoder17 nxtcoder17 deleted the feat/svc-intercept branch November 16, 2024 09:45
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants