Kuadrant / policy-machinery

Machinery for implementing Gateway API policies
Apache License 2.0
9 stars 2 forks source link

Go package: Gateway API Controller #5

Closed guicassolato closed 4 months ago

guicassolato commented 4 months ago

Adds github.com/kuadrant/policy-machinery/controller for implementing custom controllers with a built-in Gateway API topology.

The controller watches for events related to any kind of object for which an informer is specified; typically Gateway API resources and custom policy kinds. It then keeps an in-memory Gateway API topology up to date.

A callback function can be specified to act on the events of interest.

Example:

import (
  "k8s.io/apimachinery/pkg/runtime/schema"
  "k8s.io/client-go/dynamic"
  "k8s.io/client-go/tools/clientcmd"

  gwapiv1 "sigs.k8s.io/gateway-api/apis/v1"
  "./mypolicy"

  "github.com/kuadrant/policy-machinery/controller"
    "github.com/kuadrant/policy-machinery/machinery"
)

func main() {
    // load kubeconfig
    kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
    config, err := kubeconfig.ClientConfig()
    if err != nil {
        log.Fatalf("Error loading kubeconfig: %v", err)
    }

    // create a client
    client, err := dynamic.NewForConfig(config)
    if err != nil {
        log.Fatalf("Error creating client: %v", err)
    }

    // create a controller with a built-in gateway api topology
    controller := controller.NewController(
        controller.WithClient(client),
        controller.WithInformer("gateway", controller.For[*gwapiv1.Gateway](gwapiv1.SchemeGroupVersion.WithResource("gateways"), metav1.NamespaceAll)),
        controller.WithInformer("httproute", controller.For[*gwapiv1.HTTPRoute](gwapiv1.SchemeGroupVersion.WithResource("httproutes"), metav1.NamespaceAll)),
        controller.WithInformer("mypolicy", controller.For[*mypolicy.MyPolicy](mypolicy.SchemeGroupVersion.WithResource("mypolicies"), metav1.NamespaceAll)),
        controller.WithPolicyKinds(schema.GroupKind{Group: mypolicy.SchemeGroupVersion.Group, Kind: "MyPolicy"}),
        controller.WithCallback(reconcile),
    )

    controller.Start()
}

func reconcile(eventType controller.EventType, oldObj, newObj controller.RuntimeObject, topology *machinery.Topology) {
  // TODO
}

This PR will be followed by another one with a full example of using the package to implement a custom controller.