diff --git a/controllers/gateway_controller.go b/controllers/gateway_controller.go index 69909554..6fb60a18 100644 --- a/controllers/gateway_controller.go +++ b/controllers/gateway_controller.go @@ -19,15 +19,14 @@ package controllers import ( "context" "fmt" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" - "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/deploy" "github.com/aws/aws-application-networking-k8s/pkg/gateway" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" lattice_runtime "github.com/aws/aws-application-networking-k8s/pkg/runtime" "github.com/aws/aws-application-networking-k8s/pkg/utils" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" @@ -41,7 +40,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/source" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/aws/aws-application-networking-k8s/controllers/eventhandlers" ) @@ -51,8 +50,7 @@ const ( defaultNameSpace = "default" ) -// GatewayReconciler reconciles a Gateway object -type GatewayReconciler struct { +type gatewayReconciler struct { log gwlog.Logger client client.Client scheme *runtime.Scheme @@ -78,7 +76,7 @@ func RegisterGatewayController( stackDeployer := deploy.NewServiceNetworkStackDeployer(log, cloud, mgrClient) stackMarshaller := deploy.NewDefaultStackMarshaller() - r := &GatewayReconciler{ + r := &gatewayReconciler{ log: log, client: mgrClient, scheme: scheme, @@ -93,16 +91,16 @@ func RegisterGatewayController( gwClassEventHandler := eventhandlers.NewEnqueueRequestsForGatewayClassEvent(log, mgrClient) vpcAssociationPolicyEventHandler := eventhandlers.NewVpcAssociationPolicyEventHandler(log, mgrClient) builder := ctrl.NewControllerManagedBy(mgr). - For(&gateway_api.Gateway{}) - builder.Watches(&source.Kind{Type: &gateway_api.GatewayClass{}}, gwClassEventHandler) + For(&gwv1beta1.Gateway{}) + builder.Watches(&source.Kind{Type: &gwv1beta1.GatewayClass{}}, gwClassEventHandler) //Watch VpcAssociationPolicy CRD if it is installed - ok, err := k8s.IsGVKSupported(mgr, v1alpha1.GroupVersion.String(), v1alpha1.VpcAssociationPolicyKind) + ok, err := k8s.IsGVKSupported(mgr, anv1alpha1.GroupVersion.String(), anv1alpha1.VpcAssociationPolicyKind) if err != nil { return err } if ok { - builder.Watches(&source.Kind{Type: &v1alpha1.VpcAssociationPolicy{}}, vpcAssociationPolicyEventHandler.MapToGateway()) + builder.Watches(&source.Kind{Type: &anv1alpha1.VpcAssociationPolicy{}}, vpcAssociationPolicyEventHandler.MapToGateway()) } else { log.Infof("VpcAssociationPolicy CRD is not installed, skipping watch") } @@ -113,16 +111,7 @@ func RegisterGatewayController( //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gateways/status,verbs=get;update;patch //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gateways/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the Gateway object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile -func (r *GatewayReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { +func (r *gatewayReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { r.log.Infow("reconcile", "name", req.Name) recErr := r.reconcile(ctx, req) res, retryErr := lattice_runtime.HandleReconcileError(recErr) @@ -136,18 +125,18 @@ func (r *GatewayReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct return res, retryErr } -func (r *GatewayReconciler) isDefaultNameSpace(n string) bool { +func (r *gatewayReconciler) isDefaultNameSpace(n string) bool { return n == defaultNameSpace } -func (r *GatewayReconciler) reconcile(ctx context.Context, req ctrl.Request) error { +func (r *gatewayReconciler) reconcile(ctx context.Context, req ctrl.Request) error { - gw := &gateway_api.Gateway{} + gw := &gwv1beta1.Gateway{} if err := r.client.Get(ctx, req.NamespacedName, gw); err != nil { return client.IgnoreNotFound(err) } - gwClass := &gateway_api.GatewayClass{} + gwClass := &gwv1beta1.GatewayClass{} gwClassName := types.NamespacedName{ Namespace: defaultNameSpace, Name: string(gw.Spec.GatewayClassName), @@ -158,82 +147,60 @@ func (r *GatewayReconciler) reconcile(ctx context.Context, req ctrl.Request) err return client.IgnoreNotFound(err) } - if gwClass.Spec.ControllerName == config.LatticeGatewayControllerName { - if !gw.DeletionTimestamp.IsZero() { - routes, err := core.ListAllRoutes(context.TODO(), r.client) - if err != nil { - return err - } - - for _, route := range routes { - if len(route.Spec().ParentRefs()) <= 0 { - continue - } - gwNamespace := route.Namespace() - if route.Spec().ParentRefs()[0].Namespace != nil { - gwNamespace = string(*route.Spec().ParentRefs()[0].Namespace) - } - gwName := types.NamespacedName{ - Namespace: gwNamespace, - Name: string(route.Spec().ParentRefs()[0].Name), - } + if gwClass.Spec.ControllerName != config.LatticeGatewayControllerName { + r.log.Infow("ignore non aws gateways", "name", req.Name, "gwClass controller name", gwClass.Spec.ControllerName) + return nil + } - httpGw := &gateway_api.Gateway{} - if err := r.client.Get(context.TODO(), gwName, httpGw); err != nil { - continue - } + if !gw.DeletionTimestamp.IsZero() { + return r.reconcileDelete(ctx, gw) + } else { + return r.reconcileUpsert(ctx, gw) + } +} - if httpGw.Name == gw.Name && httpGw.Namespace == gw.Namespace { - return fmt.Errorf("cannot delete gw, there is reference to httpGw, gw: %s, httpGw: %s", gw.Name, httpGw.Name) - } - } +func (r *gatewayReconciler) reconcileDelete(ctx context.Context, gw *gwv1beta1.Gateway) error { + routes, err := core.ListAllRoutes(ctx, r.client) + if err != nil { + return err + } - if err := r.cleanupGatewayResources(ctx, gw); err != nil { - return errors.Wrapf(err, "failed to cleanup gw: %s", gw.Name) - } + for _, route := range routes { + if len(route.Spec().ParentRefs()) <= 0 { + continue + } + gwNamespace := route.Namespace() + if route.Spec().ParentRefs()[0].Namespace != nil { + gwNamespace = string(*route.Spec().ParentRefs()[0].Namespace) + } + gwName := types.NamespacedName{ + Namespace: gwNamespace, + Name: string(route.Spec().ParentRefs()[0].Name), + } - err = r.finalizerManager.RemoveFinalizers(ctx, gw, gatewayFinalizer) - if err != nil { - return err - } + httpGw := &gwv1beta1.Gateway{} + if err := r.client.Get(ctx, gwName, httpGw); err != nil { + continue + } - return nil + if httpGw.Name == gw.Name && httpGw.Namespace == gw.Namespace { + return fmt.Errorf("cannot delete gw, there is reference to httpGw, gw: %s, httpGw: %s", gw.Name, httpGw.Name) } - return r.reconcileGatewayResources(ctx, gw) - } else { - r.log.Infow("ignore non aws gateways", "name", req.Name, "gwClass controller name", gwClass.Spec.ControllerName) } - return nil -} -func (r *GatewayReconciler) buildAndDeployModel(ctx context.Context, gw *gateway_api.Gateway) (core.Stack, *latticemodel.ServiceNetwork, error) { - stack, serviceNetwork, err := r.modelBuilder.Build(ctx, gw) - if err != nil { - r.eventRecorder.Event(gw, corev1.EventTypeWarning, - k8s.GatewayEventReasonFailedBuildModel, - fmt.Sprintf("failed build model: %s", err)) - return nil, nil, err - } - jsonStack, err := r.stackMarshaller.Marshal(stack) - if err != nil { - return nil, nil, err + if err := r.buildAndDeployModel(ctx, gw); err != nil { + return errors.Wrapf(err, "failed to cleanup gw: %s", gw.Name) } - r.log.Debugw("successfully built model", "stack", jsonStack) - if err := r.stackDeployer.Deploy(ctx, stack); err != nil { - /* - r.eventRecorder.Event(gw, corev1.EventTypeWarning, - k8s.GatewayEventReasonFailedDeployModel, fmt.Sprintf("Failed deploy model due to %v", err)) - */ - return nil, nil, err + err = r.finalizerManager.RemoveFinalizers(ctx, gw, gatewayFinalizer) + if err != nil { + return err } - r.log.Debugw("successfully deployed model", - "stack", stack.StackID().Name+":"+stack.StackID().Namespace, - ) - return stack, serviceNetwork, err + return nil } -func (r *GatewayReconciler) reconcileGatewayResources(ctx context.Context, gw *gateway_api.Gateway) error { + +func (r *gatewayReconciler) reconcileUpsert(ctx context.Context, gw *gwv1beta1.Gateway) error { if err := r.finalizerManager.AddFinalizers(ctx, gw, gatewayFinalizer); err != nil { r.eventRecorder.Event(gw, corev1.EventTypeWarning, k8s.GatewayEventReasonFailedAddFinalizer, fmt.Sprintf("failed add finalizer: %s", err)) @@ -253,8 +220,7 @@ func (r *GatewayReconciler) reconcileGatewayResources(ctx context.Context, gw *g return err } - _, _, err = r.buildAndDeployModel(ctx, gw) - if err != nil { + if err = r.buildAndDeployModel(ctx, gw); err != nil { return err } @@ -270,23 +236,46 @@ func (r *GatewayReconciler) reconcileGatewayResources(ctx context.Context, gw *g return nil } -func (r *GatewayReconciler) cleanupGatewayResources(ctx context.Context, gw *gateway_api.Gateway) error { - _, _, err := r.buildAndDeployModel(ctx, gw) +func (r *gatewayReconciler) buildAndDeployModel(ctx context.Context, gw *gwv1beta1.Gateway) error { + stack, _, err := r.modelBuilder.Build(ctx, gw) + if err != nil { + r.eventRecorder.Event(gw, corev1.EventTypeWarning, + k8s.GatewayEventReasonFailedBuildModel, + fmt.Sprintf("failed build model: %s", err)) + return err + } + jsonStack, err := r.stackMarshaller.Marshal(stack) + if err != nil { + return err + } + r.log.Debugw("successfully built model", "stack", jsonStack) + + if err := r.stackDeployer.Deploy(ctx, stack); err != nil { + /* + r.eventRecorder.Event(gw, corev1.EventTypeWarning, + k8s.GatewayEventReasonFailedDeployModel, fmt.Sprintf("Failed deploy model due to %v", err)) + */ + return err + } + r.log.Debugw("successfully deployed model", + "stack", stack.StackID().Name+":"+stack.StackID().Namespace, + ) + return err } -func (r *GatewayReconciler) updateGatewayStatus( +func (r *gatewayReconciler) updateGatewayStatus( ctx context.Context, snArn string, - gw *gateway_api.Gateway, + gw *gwv1beta1.Gateway, ) error { gwOld := gw.DeepCopy() gw.Status.Conditions = utils.GetNewConditions(gw.Status.Conditions, metav1.Condition{ - Type: string(gateway_api.GatewayConditionProgrammed), + Type: string(gwv1beta1.GatewayConditionProgrammed), Status: metav1.ConditionTrue, ObservedGeneration: gw.Generation, - Reason: string(gateway_api.GatewayReasonProgrammed), + Reason: string(gwv1beta1.GatewayReasonProgrammed), Message: fmt.Sprintf("aws-gateway-arn: %s", snArn), }) @@ -296,25 +285,25 @@ func (r *GatewayReconciler) updateGatewayStatus( return nil } -func (r *GatewayReconciler) updateGatewayAcceptStatus(ctx context.Context, gw *gateway_api.Gateway, accepted bool) error { +func (r *gatewayReconciler) updateGatewayAcceptStatus(ctx context.Context, gw *gwv1beta1.Gateway, accepted bool) error { gwOld := gw.DeepCopy() var cond metav1.Condition if accepted { cond = metav1.Condition{ - Type: string(gateway_api.GatewayConditionAccepted), + Type: string(gwv1beta1.GatewayConditionAccepted), ObservedGeneration: gw.Generation, Message: config.LatticeGatewayControllerName, Status: metav1.ConditionTrue, - Reason: string(gateway_api.GatewayReasonAccepted), + Reason: string(gwv1beta1.GatewayReasonAccepted), } } else { cond = metav1.Condition{ - Type: string(gateway_api.GatewayConditionAccepted), + Type: string(gwv1beta1.GatewayConditionAccepted), ObservedGeneration: gw.Generation, Message: config.LatticeGatewayControllerName, Status: metav1.ConditionFalse, - Reason: string(gateway_api.GatewayReasonInvalid), + Reason: string(gwv1beta1.GatewayReasonInvalid), } } gw.Status.Conditions = utils.GetNewConditions(gw.Status.Conditions, cond) @@ -326,7 +315,7 @@ func (r *GatewayReconciler) updateGatewayAcceptStatus(ctx context.Context, gw *g return nil } -func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *gateway_api.Gateway) error { +func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *gwv1beta1.Gateway) error { hasValidListener := false gwOld := gw.DeepCopy() @@ -339,12 +328,12 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga // Add one of lattice domains as GW address. This can represent incorrect value in some cases (e.g. cross-account) // TODO: support multiple endpoint addresses across services. if len(routes) > 0 { - gw.Status.Addresses = []gateway_api.GatewayAddress{} - addressType := gateway_api.HostnameAddressType + gw.Status.Addresses = []gwv1beta1.GatewayAddress{} + addressType := gwv1beta1.HostnameAddressType for _, route := range routes { if route.DeletionTimestamp().IsZero() && len(route.K8sObject().GetAnnotations()) > 0 { if domain, exists := route.K8sObject().GetAnnotations()[LatticeAssignedDomainName]; exists { - gw.Status.Addresses = append(gw.Status.Addresses, gateway_api.GatewayAddress{ + gw.Status.Addresses = append(gw.Status.Addresses, gwv1beta1.GatewayAddress{ Type: &addressType, Value: domain, }) @@ -361,7 +350,7 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga // go through each section of gw for _, listener := range gw.Spec.Listeners { - listenerStatus := gateway_api.ListenerStatus{ + listenerStatus := gwv1beta1.ListenerStatus{ Name: listener.Name, } @@ -372,9 +361,9 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga validListener, supportedKinds := listenerRouteGroupKindSupported(listener) if !validListener { condition := metav1.Condition{ - Type: string(gateway_api.ListenerConditionResolvedRefs), + Type: string(gwv1beta1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, - Reason: string(gateway_api.ListenerReasonInvalidRouteKinds), + Reason: string(gwv1beta1.ListenerReasonInvalidRouteKinds), ObservedGeneration: gw.Generation, LastTransitionTime: metav1.Now(), } @@ -384,9 +373,9 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga hasValidListener = true condition := metav1.Condition{ - Type: string(gateway_api.ListenerConditionAccepted), + Type: string(gwv1beta1.ListenerConditionAccepted), Status: metav1.ConditionTrue, - Reason: string(gateway_api.ListenerReasonAccepted), + Reason: string(gwv1beta1.ListenerReasonAccepted), ObservedGeneration: gw.Generation, LastTransitionTime: metav1.Now(), } @@ -398,12 +387,12 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga } for _, parentRef := range route.Spec().ParentRefs() { - if parentRef.Name != gateway_api.ObjectName(gw.Name) { + if parentRef.Name != gwv1beta1.ObjectName(gw.Name) { continue } if parentRef.Namespace != nil && - *parentRef.Namespace != gateway_api.Namespace(gw.Namespace) { + *parentRef.Namespace != gwv1beta1.Namespace(gw.Namespace) { continue } @@ -426,13 +415,13 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga } } - if listener.Protocol == gateway_api.HTTPSProtocolType { - listenerStatus.SupportedKinds = append(listenerStatus.SupportedKinds, gateway_api.RouteGroupKind{ + if listener.Protocol == gwv1beta1.HTTPSProtocolType { + listenerStatus.SupportedKinds = append(listenerStatus.SupportedKinds, gwv1beta1.RouteGroupKind{ Kind: "GRPCRoute", }) } - listenerStatus.SupportedKinds = append(listenerStatus.SupportedKinds, gateway_api.RouteGroupKind{ + listenerStatus.SupportedKinds = append(listenerStatus.SupportedKinds, gwv1beta1.RouteGroupKind{ Kind: "HTTPRoute", }) listenerStatus.Conditions = append(listenerStatus.Conditions, condition) @@ -464,18 +453,18 @@ func UpdateGWListenerStatus(ctx context.Context, k8sClient client.Client, gw *ga } } -func listenerRouteGroupKindSupported(listener gateway_api.Listener) (bool, []gateway_api.RouteGroupKind) { +func listenerRouteGroupKindSupported(listener gwv1beta1.Listener) (bool, []gwv1beta1.RouteGroupKind) { validRoute := true - supportedKinds := make([]gateway_api.RouteGroupKind, 0) + supportedKinds := make([]gwv1beta1.RouteGroupKind, 0) for _, routeGroupKind := range listener.AllowedRoutes.Kinds { if routeGroupKind.Kind == "HTTPRoute" { - supportedKinds = append(supportedKinds, gateway_api.RouteGroupKind{ + supportedKinds = append(supportedKinds, gwv1beta1.RouteGroupKind{ Kind: "HTTPRoute", }) } else if routeGroupKind.Kind == "GRPCRoute" { - if listener.Protocol == gateway_api.HTTPSProtocolType { - supportedKinds = append(supportedKinds, gateway_api.RouteGroupKind{ + if listener.Protocol == gwv1beta1.HTTPSProtocolType { + supportedKinds = append(supportedKinds, gwv1beta1.RouteGroupKind{ Kind: "GRPCRoute", }) } else { diff --git a/controllers/gatewayclass_controller.go b/controllers/gatewayclass_controller.go index 315ac66b..1c41ef81 100644 --- a/controllers/gatewayclass_controller.go +++ b/controllers/gatewayclass_controller.go @@ -28,11 +28,10 @@ import ( "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) -// GatewayClassReconciler reconciles a GatewayClass object -type GatewayClassReconciler struct { +type gatewayClassReconciler struct { log gwlog.Logger client client.Client scheme *runtime.Scheme @@ -40,14 +39,14 @@ type GatewayClassReconciler struct { } func RegisterGatewayClassController(log gwlog.Logger, mgr ctrl.Manager) error { - r := &GatewayClassReconciler{ + r := &gatewayClassReconciler{ log: log, client: mgr.GetClient(), scheme: mgr.GetScheme(), latticeControllerEnabled: false, } return ctrl.NewControllerManagedBy(mgr). - For(&gateway_api.GatewayClass{}). + For(&gwv1beta1.GatewayClass{}). Complete(r) } @@ -55,19 +54,10 @@ func RegisterGatewayClassController(log gwlog.Logger, mgr ctrl.Manager) error { //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gatewayclasses/status,verbs=get;update;patch //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gatewayclasses/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the GatewayClass object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile -func (r *GatewayClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { +func (r *gatewayClassReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { r.log.Infow("reconcile", "name", req.Name) - gwClass := &gateway_api.GatewayClass{} + gwClass := &gwv1beta1.GatewayClass{} if err := r.client.Get(ctx, req.NamespacedName, gwClass); err != nil { r.log.Debugw("gateway not found", "name", req.Name) return ctrl.Result{}, nil @@ -88,8 +78,8 @@ func (r *GatewayClassReconciler) Reconcile(ctx context.Context, req ctrl.Request gwClass.Status.Conditions[0].LastTransitionTime = metav1.NewTime(time.Now()) gwClass.Status.Conditions[0].ObservedGeneration = gwClass.Generation gwClass.Status.Conditions[0].Status = "True" - gwClass.Status.Conditions[0].Message = string(gateway_api.GatewayClassReasonAccepted) - gwClass.Status.Conditions[0].Reason = string(gateway_api.GatewayClassReasonAccepted) + gwClass.Status.Conditions[0].Message = string(gwv1beta1.GatewayClassReasonAccepted) + gwClass.Status.Conditions[0].Reason = string(gwv1beta1.GatewayClassReasonAccepted) if err := r.client.Status().Patch(ctx, gwClass, client.MergeFrom(gwClassOld)); err != nil { return ctrl.Result{}, errors.Wrapf(err, "failed to update gatewayclass status") diff --git a/controllers/pod_controller.go b/controllers/pod_controller.go index d9484231..f7cd1894 100644 --- a/controllers/pod_controller.go +++ b/controllers/pod_controller.go @@ -26,7 +26,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -// podReconciler reconciles a Pod object type podReconciler struct { log gwlog.Logger client client.Client @@ -49,15 +48,6 @@ func RegisterPodController(log gwlog.Logger, mgr ctrl.Manager) error { //+kubebuilder:rbac:groups=core,resources=pods/status,verbs=get;update;patch //+kubebuilder:rbac:groups=core,resources=pods/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the Pod object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile func (r *podReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { pod := &corev1.Pod{} if err := r.client.Get(ctx, req.NamespacedName, pod); err != nil { diff --git a/controllers/route_controller.go b/controllers/route_controller.go index 0cec919f..d8917117 100644 --- a/controllers/route_controller.go +++ b/controllers/route_controller.go @@ -35,10 +35,9 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/source" - gateway_api_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" - gateway_api_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" - mcs_api "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" "sigs.k8s.io/external-dns/endpoint" @@ -52,7 +51,7 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" lattice_runtime "github.com/aws/aws-application-networking-k8s/pkg/runtime" ) @@ -61,8 +60,7 @@ var routeTypeToFinalizer = map[core.RouteType]string{ core.GrpcRouteType: "grpcroute.k8s.aws/resources", } -// RouteReconciler reconciles a HTTPRoute and GRPCRoute objects -type RouteReconciler struct { +type routeReconciler struct { routeType core.RouteType log gwlog.Logger client client.Client @@ -103,12 +101,12 @@ func RegisterAllRouteControllers( routeType core.RouteType gatewayApiType client.Object }{ - {core.HttpRouteType, &gateway_api_v1beta1.HTTPRoute{}}, - {core.GrpcRouteType, &gateway_api_v1alpha2.GRPCRoute{}}, + {core.HttpRouteType, &gwv1beta1.HTTPRoute{}}, + {core.GrpcRouteType, &gwv1alpha2.GRPCRoute{}}, } for _, routeInfo := range routeInfos { - reconciler := RouteReconciler{ + reconciler := routeReconciler{ routeType: routeInfo.routeType, log: log, client: mgrClient, @@ -126,9 +124,9 @@ func RegisterAllRouteControllers( builder := ctrl.NewControllerManagedBy(mgr). For(routeInfo.gatewayApiType). - Watches(&source.Kind{Type: &gateway_api_v1beta1.Gateway{}}, gwEventHandler). + Watches(&source.Kind{Type: &gwv1beta1.Gateway{}}, gwEventHandler). Watches(&source.Kind{Type: &corev1.Service{}}, svcEventHandler.MapToRoute(routeInfo.routeType)). - Watches(&source.Kind{Type: &mcs_api.ServiceImport{}}, svcImportEventHandler.MapToRoute(routeInfo.routeType)). + Watches(&source.Kind{Type: &mcsv1alpha1.ServiceImport{}}, svcImportEventHandler.MapToRoute(routeInfo.routeType)). Watches(&source.Kind{Type: &corev1.Endpoints{}}, svcEventHandler.MapToRoute(routeInfo.routeType)) if ok, err := k8s.IsGVKSupported(mgr, v1alpha1.GroupVersion.String(), v1alpha1.TargetGroupPolicyKind); ok { @@ -162,20 +160,11 @@ func RegisterAllRouteControllers( //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=grpcroutes/status;httproutes/status,verbs=get;update;patch //+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=grpcroutes/finalizers;httproutes/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the Route object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile -func (r *RouteReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { +func (r *routeReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { return lattice_runtime.HandleReconcileError(r.reconcile(ctx, req)) } -func (r *RouteReconciler) reconcile(ctx context.Context, req ctrl.Request) error { +func (r *routeReconciler) reconcile(ctx context.Context, req ctrl.Request) error { r.log.Infow("reconcile", "name", req.Name) route, err := r.getRoute(ctx, req) @@ -192,35 +181,30 @@ func (r *RouteReconciler) reconcile(ctx context.Context, req ctrl.Request) error } if !route.DeletionTimestamp().IsZero() { - r.log.Infow("reconcile, deleting", "name", req.Name) - r.eventRecorder.Event(route.K8sObject(), corev1.EventTypeNormal, - k8s.RouteEventReasonReconcile, "Deleting Reconcile") - if err := r.cleanupRouteResources(ctx, route); err != nil { - return fmt.Errorf("failed to cleanup GRPCRoute %s, %s: %w", route.Name(), route.Namespace(), err) - } - err = updateRouteListenerStatus(ctx, r.client, route) - if err != nil { - return err - } - err = r.finalizerManager.RemoveFinalizers(ctx, route.K8sObject(), routeTypeToFinalizer[r.routeType]) - if err != nil { - return err - } - - // TODO delete metrics - r.log.Infow("reconciled", "name", req.Name) - return nil + return r.reconcileDelete(ctx, req, route) } else { - r.log.Infow("reconcile, adding or updating", "name", req.Name) - r.eventRecorder.Event(route.K8sObject(), corev1.EventTypeNormal, - k8s.RouteEventReasonReconcile, "Adding/Updating Reconcile") - err := r.reconcileRouteResource(ctx, route) - // TODO add/update metrics + return r.reconcileUpsert(ctx, req, route) + } +} + +func (r *routeReconciler) reconcileDelete(ctx context.Context, req ctrl.Request, route core.Route) error { + r.log.Infow("reconcile, deleting", "name", req.Name) + r.eventRecorder.Event(route.K8sObject(), corev1.EventTypeNormal, + k8s.RouteEventReasonReconcile, "Deleting Reconcile") + + if err := r.cleanupRouteResources(ctx, route); err != nil { + return fmt.Errorf("failed to cleanup GRPCRoute %s, %s: %w", route.Name(), route.Namespace(), err) + } + + if err := updateRouteListenerStatus(ctx, r.client, route); err != nil { return err } + + r.log.Infow("reconciled", "name", req.Name) + return r.finalizerManager.RemoveFinalizers(ctx, route.K8sObject(), routeTypeToFinalizer[r.routeType]) } -func (r *RouteReconciler) getRoute(ctx context.Context, req ctrl.Request) (core.Route, error) { +func (r *routeReconciler) getRoute(ctx context.Context, req ctrl.Request) (core.Route, error) { switch r.routeType { case core.HttpRouteType: return core.GetHTTPRoute(ctx, r.client, req.NamespacedName) @@ -232,7 +216,7 @@ func (r *RouteReconciler) getRoute(ctx context.Context, req ctrl.Request) (core. } func updateRouteListenerStatus(ctx context.Context, k8sClient client.Client, route core.Route) error { - gw := &gateway_api_v1beta1.Gateway{} + gw := &gwv1beta1.Gateway{} gwNamespace := route.Namespace() if route.Spec().ParentRefs()[0].Namespace != nil { @@ -251,18 +235,18 @@ func updateRouteListenerStatus(ctx context.Context, k8sClient client.Client, rou return UpdateGWListenerStatus(ctx, k8sClient, gw) } -func (r *RouteReconciler) cleanupRouteResources(ctx context.Context, route core.Route) error { +func (r *routeReconciler) cleanupRouteResources(ctx context.Context, route core.Route) error { _, _, err := r.buildAndDeployModel(ctx, route) return err } -func (r *RouteReconciler) isRouteRelevant(ctx context.Context, route core.Route) bool { +func (r *routeReconciler) isRouteRelevant(ctx context.Context, route core.Route) bool { if len(route.Spec().ParentRefs()) == 0 { r.log.Infof("Ignore Route which has no ParentRefs gateway %s ", route.Name()) return false } - gw := &gateway_api_v1beta1.Gateway{} + gw := &gwv1beta1.Gateway{} gwNamespace := route.Namespace() if route.Spec().ParentRefs()[0].Namespace != nil { @@ -280,7 +264,7 @@ func (r *RouteReconciler) isRouteRelevant(ctx context.Context, route core.Route) } // make sure gateway is an aws-vpc-lattice - gwClass := &gateway_api_v1beta1.GatewayClass{} + gwClass := &gwv1beta1.GatewayClass{} gwClassName := types.NamespacedName{ Namespace: defaultNameSpace, Name: string(gw.Spec.GatewayClassName), @@ -300,10 +284,10 @@ func (r *RouteReconciler) isRouteRelevant(ctx context.Context, route core.Route) return false } -func (r *RouteReconciler) buildAndDeployModel( +func (r *routeReconciler) buildAndDeployModel( ctx context.Context, route core.Route, -) (core.Stack, *latticemodel.Service, error) { +) (core.Stack, *model.Service, error) { stack, latticeService, err := r.modelBuilder.Build(ctx, route) if err != nil { @@ -335,7 +319,11 @@ func (r *RouteReconciler) buildAndDeployModel( return stack, latticeService, err } -func (r *RouteReconciler) reconcileRouteResource(ctx context.Context, route core.Route) error { +func (r *routeReconciler) reconcileUpsert(ctx context.Context, req ctrl.Request, route core.Route) error { + r.log.Infow("reconcile, adding or updating", "name", req.Name) + r.eventRecorder.Event(route.K8sObject(), corev1.EventTypeNormal, + k8s.RouteEventReasonReconcile, "Adding/Updating Reconcile") + if err := r.finalizerManager.AddFinalizers(ctx, route.K8sObject(), routeTypeToFinalizer[r.routeType]); err != nil { r.eventRecorder.Event(route.K8sObject(), corev1.EventTypeWarning, k8s.RouteEventReasonFailedAddFinalizer, fmt.Sprintf("Failed add finalizer due to %s", err)) } @@ -348,10 +336,10 @@ func (r *RouteReconciler) reconcileRouteResource(ctx context.Context, route core route.Status().UpdateParentRefs(route.Spec().ParentRefs()[0], config.LatticeGatewayControllerName) route.Status().UpdateRouteCondition(metav1.Condition{ - Type: string(gateway_api.RouteConditionAccepted), + Type: string(gwv1beta1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.K8sObject().GetGeneration(), - Reason: string(gateway_api.RouteReasonUnsupportedValue), + Reason: string(gwv1beta1.RouteReasonUnsupportedValue), Message: fmt.Sprintf("Dual stack Service is not supported"), }) @@ -382,10 +370,11 @@ func (r *RouteReconciler) reconcileRouteResource(ctx context.Context, route core return err } + r.log.Infow("reconciled", "name", req.Name) return nil } -func (r *RouteReconciler) updateRouteStatus(ctx context.Context, dns string, route core.Route) error { +func (r *routeReconciler) updateRouteStatus(ctx context.Context, dns string, route core.Route) error { r.log.Debugf("Updating route %s-%s with DNS %s", route.Name(), route.Namespace(), dns) routeOld := route.DeepCopy() @@ -404,25 +393,25 @@ func (r *RouteReconciler) updateRouteStatus(ctx context.Context, dns string, rou // Update listener Status if err := updateRouteListenerStatus(ctx, r.client, route); err != nil { route.Status().UpdateRouteCondition(metav1.Condition{ - Type: string(gateway_api_v1beta1.RouteConditionAccepted), + Type: string(gwv1beta1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.K8sObject().GetGeneration(), - Reason: string(gateway_api_v1beta1.RouteReasonNoMatchingParent), + Reason: string(gwv1beta1.RouteReasonNoMatchingParent), Message: fmt.Sprintf("Could not match gateway %s: %s", route.Spec().ParentRefs()[0].Name, err), }) } else { route.Status().UpdateRouteCondition(metav1.Condition{ - Type: string(gateway_api_v1beta1.RouteConditionAccepted), + Type: string(gwv1beta1.RouteConditionAccepted), Status: metav1.ConditionTrue, ObservedGeneration: route.K8sObject().GetGeneration(), - Reason: string(gateway_api_v1beta1.RouteReasonAccepted), + Reason: string(gwv1beta1.RouteReasonAccepted), Message: fmt.Sprintf("DNS Name: %s", dns), }) route.Status().UpdateRouteCondition(metav1.Condition{ - Type: string(gateway_api_v1beta1.RouteConditionResolvedRefs), + Type: string(gwv1beta1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: route.K8sObject().GetGeneration(), - Reason: string(gateway_api_v1beta1.RouteReasonResolvedRefs), + Reason: string(gwv1beta1.RouteReasonResolvedRefs), Message: fmt.Sprintf("DNS Name: %s", dns), }) } @@ -435,7 +424,7 @@ func (r *RouteReconciler) updateRouteStatus(ctx context.Context, dns string, rou return nil } -func (r *RouteReconciler) validateBackendRefsIpFamilies(ctx context.Context, route core.Route) error { +func (r *routeReconciler) validateBackendRefsIpFamilies(ctx context.Context, route core.Route) error { rules := route.Spec().Rules() for _, rule := range rules { @@ -447,19 +436,8 @@ func (r *RouteReconciler) validateBackendRefsIpFamilies(ctx context.Context, rou continue } - svc := &corev1.Service{} - - key := types.NamespacedName{ - Name: string(backendRef.Name()), - } - - if backendRef.Namespace() != nil { - key.Namespace = string(*backendRef.Namespace()) - } else { - key.Namespace = route.Namespace() - } - - if err := r.client.Get(ctx, key, svc); err != nil { + svc, err := gateway.GetServiceForBackendRef(ctx, r.client, route, backendRef) + if err != nil { // Ignore error since Service might not be created yet continue } diff --git a/controllers/service_controller.go b/controllers/service_controller.go index c2a670aa..ec5602bd 100644 --- a/controllers/service_controller.go +++ b/controllers/service_controller.go @@ -32,24 +32,22 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" lattice_runtime "github.com/aws/aws-application-networking-k8s/pkg/runtime" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) const ( - // Typo serviceFinalizer = "service.ki8s.aws/resources" ) -// serviceReconciler reconciles a Service object type serviceReconciler struct { log gwlog.Logger client client.Client scheme *runtime.Scheme finalizerManager k8s.FinalizerManager eventRecorder record.EventRecorder - modelBuilder gateway.LatticeTargetsBuilder + targetsBuilder gateway.LatticeTargetsBuilder stackDeployer deploy.StackDeployer datastore *latticestore.LatticeDataStore stackMashaller deploy.StackMarshaller @@ -65,16 +63,16 @@ func RegisterServiceController( client := mgr.GetClient() scheme := mgr.GetScheme() evtRec := mgr.GetEventRecorderFor("service") - modelBuild := gateway.NewTargetsBuilder(log, client, cloud, datastore) - stackDeploy := deploy.NewTargetsStackDeploy(log, cloud, client, datastore) + modelBuilder := gateway.NewTargetsBuilder(log, client, cloud, datastore) + stackDeployer := deploy.NewTargetsStackDeployer(log, cloud, client, datastore) stackMarshaller := deploy.NewDefaultStackMarshaller() sr := &serviceReconciler{ log: log, client: client, scheme: scheme, finalizerManager: finalizerManager, - modelBuilder: modelBuild, - stackDeployer: stackDeploy, + targetsBuilder: modelBuilder, + stackDeployer: stackDeployer, eventRecorder: evtRec, datastore: datastore, stackMashaller: stackMarshaller, @@ -92,15 +90,6 @@ func RegisterServiceController( //+kubebuilder:rbac:groups=core,resources=endpoints/status,verbs=get;update;patch //+kubebuilder:rbac:groups=core,resources=configmaps, verbs=create;delete;patch;update;get;list;watch -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the Service object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile func (r *serviceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { return lattice_runtime.HandleReconcileError(r.reconcile(ctx, req)) } @@ -117,7 +106,7 @@ func (r *serviceReconciler) reconcile(ctx context.Context, req ctrl.Request) err tgs := r.datastore.GetTargetGroupsByName(tgName) for _, tg := range tgs { r.log.Debugf("deletion request for tgName: %s: at timestamp: %s", tg.TargetGroupKey.Name, svc.DeletionTimestamp) - if err := r.reconcileTargetsResource(ctx, svc, tg.TargetGroupKey.RouteName); err != nil { + if _, _, err := r.buildAndDeployModel(ctx, svc, tg.TargetGroupKey.RouteName); err != nil { return err } } @@ -132,15 +121,8 @@ func (r *serviceReconciler) reconcile(ctx context.Context, req ctrl.Request) err return nil } -func (r *serviceReconciler) reconcileTargetsResource(ctx context.Context, svc *corev1.Service, routename string) error { - if _, _, err := r.buildAndDeployModel(ctx, svc, routename); err != nil { - return err - } - return nil -} - -func (r *serviceReconciler) buildAndDeployModel(ctx context.Context, svc *corev1.Service, routename string) (core.Stack, *latticemodel.Targets, error) { - stack, latticeTargets, err := r.modelBuilder.Build(ctx, svc, routename) +func (r *serviceReconciler) buildAndDeployModel(ctx context.Context, svc *corev1.Service, routename string) (core.Stack, *model.Targets, error) { + stack, latticeTargets, err := r.targetsBuilder.Build(ctx, svc, routename) if err != nil { r.eventRecorder.Event(svc, corev1.EventTypeWarning, k8s.ServiceEventReasonFailedBuildModel, fmt.Sprintf("failed build model: %s", err)) diff --git a/controllers/serviceexport_controller.go b/controllers/serviceexport_controller.go index 1b17b3a5..406f42c1 100644 --- a/controllers/serviceexport_controller.go +++ b/controllers/serviceexport_controller.go @@ -27,30 +27,27 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/source" - mcs_api "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" "github.com/aws/aws-application-networking-k8s/controllers/eventhandlers" - "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/deploy" "github.com/aws/aws-application-networking-k8s/pkg/gateway" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" lattice_runtime "github.com/aws/aws-application-networking-k8s/pkg/runtime" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) -// ServiceExportReconciler reconciles a ServiceExport object -type ServiceExportReconciler struct { +type serviceExportReconciler struct { log gwlog.Logger client client.Client Scheme *runtime.Scheme finalizerManager k8s.FinalizerManager eventRecorder record.EventRecorder - modelBuilder gateway.TargetGroupModelBuilder + modelBuilder gateway.SvcExportTargetGroupModelBuilder stackDeployer deploy.StackDeployer latticeDataStore *latticestore.LatticeDataStore stackMarshaller deploy.StackMarshaller @@ -71,11 +68,11 @@ func RegisterServiceExportController( scheme := mgr.GetScheme() eventRecorder := mgr.GetEventRecorderFor("serviceExport") - modelBuilder := gateway.NewTargetGroupBuilder(log, mgrClient, latticeDataStore, cloud) + modelBuilder := gateway.NewSvcExportTargetGroupBuilder(log, mgrClient, latticeDataStore, cloud) stackDeploy := deploy.NewTargetGroupStackDeploy(log, cloud, mgrClient, latticeDataStore) stackMarshaller := deploy.NewDefaultStackMarshaller() - r := &ServiceExportReconciler{ + r := &serviceExportReconciler{ log: log, client: mgrClient, Scheme: scheme, @@ -90,11 +87,11 @@ func RegisterServiceExportController( svcEventHandler := eventhandlers.NewServiceEventHandler(log, r.client) builder := ctrl.NewControllerManagedBy(mgr). - For(&mcs_api.ServiceExport{}). + For(&mcsv1alpha1.ServiceExport{}). Watches(&source.Kind{Type: &corev1.Service{}}, svcEventHandler.MapToServiceExport()) - if ok, err := k8s.IsGVKSupported(mgr, v1alpha1.GroupVersion.String(), v1alpha1.TargetGroupPolicyKind); ok { - builder.Watches(&source.Kind{Type: &v1alpha1.TargetGroupPolicy{}}, svcEventHandler.MapToServiceExport()) + if ok, err := k8s.IsGVKSupported(mgr, anv1alpha1.GroupVersion.String(), anv1alpha1.TargetGroupPolicyKind); ok { + builder.Watches(&source.Kind{Type: &anv1alpha1.TargetGroupPolicy{}}, svcEventHandler.MapToServiceExport()) } else { if err != nil { return err @@ -109,67 +106,48 @@ func RegisterServiceExportController( //+kubebuilder:rbac:groups=multicluster.x-k8s.io,resources=serviceexports/status,verbs=get;update;patch //+kubebuilder:rbac:groups=multicluster.x-k8s.io,resources=serviceexports/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the ServiceExport object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile -func (r *ServiceExportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { +func (r *serviceExportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { return lattice_runtime.HandleReconcileError(r.reconcile(ctx, req)) } -func (r *ServiceExportReconciler) reconcile(ctx context.Context, req ctrl.Request) error { - srvExport := &mcs_api.ServiceExport{} +func (r *serviceExportReconciler) reconcile(ctx context.Context, req ctrl.Request) error { + srvExport := &mcsv1alpha1.ServiceExport{} if err := r.client.Get(ctx, req.NamespacedName, srvExport); err != nil { return client.IgnoreNotFound(err) } - if srvExport.ObjectMeta.Annotations["multicluster.x-k8s.io/federation"] == "amazon-vpc-lattice" { - r.log.Debugf("Found matching service export %s-%s", srvExport.Name, srvExport.Namespace) - - if !srvExport.DeletionTimestamp.IsZero() { - if err := r.cleanupServiceExportResources(ctx, srvExport); err != nil { - return err - } - err := r.finalizerManager.RemoveFinalizers(ctx, srvExport, serviceExportFinalizer) - if err != nil { - r.log.Errorf("Failed to remove finalizers for service export %s-%s due to %s", - srvExport.Name, srvExport.Namespace, err) - } - return nil - } - - return r.reconcileServiceExportResources(ctx, srvExport) + if srvExport.ObjectMeta.Annotations["multicluster.x-k8s.io/federation"] != "amazon-vpc-lattice" { + return nil } + r.log.Debugf("Found matching service export %s-%s", srvExport.Name, srvExport.Namespace) - return nil -} - -func (r *ServiceExportReconciler) cleanupServiceExportResources(ctx context.Context, srvExport *mcs_api.ServiceExport) error { - _, _, err := r.buildAndDeployModel(ctx, srvExport) - return err -} + if !srvExport.DeletionTimestamp.IsZero() { + if err := r.buildAndDeployModel(ctx, srvExport); err != nil { + return err + } + err := r.finalizerManager.RemoveFinalizers(ctx, srvExport, serviceExportFinalizer) + if err != nil { + r.log.Errorf("Failed to remove finalizers for service export %s-%s due to %s", + srvExport.Name, srvExport.Namespace, err) + } + return nil + } else { + if err := r.finalizerManager.AddFinalizers(ctx, srvExport, serviceExportFinalizer); err != nil { + r.eventRecorder.Event(srvExport, corev1.EventTypeWarning, k8s.GatewayEventReasonFailedAddFinalizer, fmt.Sprintf("Failed add finalizer due to %v", err)) + return errors.New("TODO") + } -func (r *ServiceExportReconciler) reconcileServiceExportResources(ctx context.Context, srvExport *mcs_api.ServiceExport) error { - if err := r.finalizerManager.AddFinalizers(ctx, srvExport, serviceExportFinalizer); err != nil { - r.eventRecorder.Event(srvExport, corev1.EventTypeWarning, k8s.GatewayEventReasonFailedAddFinalizer, fmt.Sprintf("Failed add finalizer due to %s", err)) - return errors.New("TODO") + err := r.buildAndDeployModel(ctx, srvExport) + return err } - - _, _, err := r.buildAndDeployModel(ctx, srvExport) - return err } -func (r *ServiceExportReconciler) buildAndDeployModel( +func (r *serviceExportReconciler) buildAndDeployModel( ctx context.Context, - srvExport *mcs_api.ServiceExport, -) (core.Stack, *latticemodel.TargetGroup, error) { - stack, targetGroup, err := r.modelBuilder.Build(ctx, srvExport) + srvExport *mcsv1alpha1.ServiceExport, +) error { + stack, _, err := r.modelBuilder.Build(ctx, srvExport) if err != nil { r.log.Debugf("Failed to buildAndDeployModel for service export %s-%s due to %s", @@ -193,9 +171,9 @@ func (r *ServiceExportReconciler) buildAndDeployModel( if err := r.stackDeployer.Deploy(ctx, stack); err != nil { r.eventRecorder.Event(srvExport, corev1.EventTypeWarning, k8s.ServiceExportEventReasonFailedDeployModel, fmt.Sprintf("Failed deploy model due to %s", err)) - return nil, nil, err + return err } r.log.Debugf("Successfully deployed model for service export %s-%s", srvExport.Name, srvExport.Namespace) - return stack, targetGroup, err + return err } diff --git a/controllers/serviceimport_controller.go b/controllers/serviceimport_controller.go index 7903f94b..132fe9fa 100644 --- a/controllers/serviceimport_controller.go +++ b/controllers/serviceimport_controller.go @@ -34,8 +34,7 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/latticestore" ) -// ServiceImportReconciler reconciles a ServiceImport object -type ServiceImportReconciler struct { +type serviceImportReconciler struct { log gwlog.Logger client client.Client Scheme *runtime.Scheme @@ -58,7 +57,7 @@ func RegisterServiceImportController( scheme := mgr.GetScheme() eventRecorder := mgr.GetEventRecorderFor("ServiceImport") - r := &ServiceImportReconciler{ + r := &serviceImportReconciler{ log: log, client: mgrClient, Scheme: scheme, @@ -76,20 +75,10 @@ func RegisterServiceImportController( //+kubebuilder:rbac:groups=multicluster.x-k8s.io,resources=serviceimports/status,verbs=get;update;patch //+kubebuilder:rbac:groups=multicluster.x-k8s.io,resources=serviceimports/finalizers,verbs=update -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -// TODO(user): Modify the Reconcile function to compare the state specified by -// the ServiceImport object against the actual cluster state, and then -// perform operations to make the cluster state reflect the state specified by -// the user. -// -// For more details, check Reconcile and its Result here: -// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile -func (r *ServiceImportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { +func (r *serviceImportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { reconcileLog := log.FromContext(ctx) - // TODO(user): your logic here - reconcileLog.Info("ServiceImportReconciler") + reconcileLog.Info("serviceImportReconciler") serviceImport := &mcs_api.ServiceImport{} @@ -102,15 +91,13 @@ func (r *ServiceImportReconciler) Reconcile(ctx context.Context, req ctrl.Reques reconcileLog.Info("Deleting") r.finalizerManager.RemoveFinalizers(ctx, serviceImport, serviceImportFinalizer) return ctrl.Result{}, nil - } + } else { + if err := r.finalizerManager.AddFinalizers(ctx, serviceImport, serviceImportFinalizer); err != nil { + r.eventRecorder.Event(serviceImport, corev1.EventTypeWarning, k8s.ServiceImportEventReasonFailedAddFinalizer, fmt.Sprintf("Failed add finalizer due to %v", err)) + return ctrl.Result{}, nil + } + reconcileLog.Info("Adding/Updating") - // Handle add - if err := r.finalizerManager.AddFinalizers(ctx, serviceImport, serviceImportFinalizer); err != nil { - r.eventRecorder.Event(serviceImport, corev1.EventTypeWarning, k8s.ServiceImportEventReasonFailedAddFinalizer, fmt.Sprintf("Failed add finalizer due to %s", err)) return ctrl.Result{}, nil } - - reconcileLog.Info("Adding/Updating") - - return ctrl.Result{}, nil } diff --git a/docs/developer-cheat-sheet.md b/docs/developer-cheat-sheet.md new file mode 100644 index 00000000..ef56b9a5 --- /dev/null +++ b/docs/developer-cheat-sheet.md @@ -0,0 +1,61 @@ +# Developer Cheat Sheet + +## Startup +The program flow is roughly as follows. On startup, ```cmd/aws-application-networking-k8s/main.go#main()``` runs. This initializes all the key components and registers various controllers (in ```controllers/```) with the Kubernetes control plane. These controllers include event handlers (in ```controllers/eventhandlers/```) whose basic function is to convert object notifications to more specific types and enqueue them for processing by the various controllers. + +## Build and Deploy +Processing takes place in a controller's ```Reconcile()``` method, which will check if the object has been changed/created or deleted. Sometimes this invokes different paths, but most involve a ```buildAndDeployModel()``` step. + +### Build +In the "build" step, the controller invokes a "model builder" with the changed Kubernetes object. Model builders (in ```pkg/gateway/```) convert the Kubernetes object state into an intermediate VPC Lattice object called a "model type". These model types (in ```pkg/model/lattice```) are basic structs which contain the important information about the source Kubernetes object and fields containing Lattice-related values. These models are built only using information from Kubernetes and are intended to contain all details needed to make updates against the VPC Lattice API. Once created, model ojbects are stored in a "stack" (```/pkg/model/core/stack.go```). The stack contains basic methods for storing and retrieving objects based on model type. + +### Deploy +Once the "stack" is populated, it is serialized for logging then passed to the "deploy" step. Here, a "deployer" (```/pkg/deployer/stack_deployer.go```) will invoke a number of "synthesizers" (in ```/pkg/deploy/lattice/```) to read model objects from the stack and convert these to VPC Lattice API calls (via ```Synthesize()```). Most synthesizer interaction with the Lattice APIs is deferred to various "managers" (also ```/pkg/deploy/lattice```). These managers each have their own interface definition with CRUD methods that bridge model types and Lattice API types. Managers, in turn, use ```/pkg/aws/services/vpclattice.go``` for convenience methods against the Lattice API only using Lattice API types. + +### Other notes + +*Model Status Structs* +On each model type is a ```Status``` struct which contains information about the object from the Lattice API, such as ARNs or IDs. These are populated either on creation against the Lattice API or in cases where the API object already exists but needs updating via the model. + +*Resource Cleanup* +A typical part of model synthesis (though it is also present in ) is checking all resources in the VPC Lattice API to see if they belong to deleted or missing Kubernetes resources. This is to help ensure Lattice resources are not leaked due to bugs in the reconciliation process. + +## Code Consistency + +To help reduce cognitive load while working through the code, it is critical to be consistent. For now, this applies most directly to imports and variable naming. + +### Imports +Common imports should all use the same alias (or lack of alias) so that when we see ```aws.``` or ```vpclattice.``` or ```sdk.``` in the code we know what they refer to without having to double-check. Here are the conventions: + +```go +import ( + "github.com/aws/aws-sdk-go/service/vpclattice" // no alias + "github.com/aws/aws-sdk-go/aws" // no alias + + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + corev1 "k8s.io/api/core/v1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + ctrl "sigs.k8s.io/controller-runtime" + + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" +) +``` + +### Service, Service, or Service? +Similarly, because there is overlap between the Gateway API spec, model types, and Lattice API nouns, it is important to use differentiating names between the types in components where the name could be ambiguous. The safest approach is to use a prefix: + +* ```k8s``` refers to a kubernetes object +* ```model``` refers to an intermediate model object +* ```lattice``` refers to an object from the Lattice API + +An example in practice would be + +```go + var k8sSvc *corev1.Service + var modelSvc *model.Service + var latticeSvc *vpclattice.ServiceSummary +``` + +There are some objects which interact unambiguously with an underlying type, for example in ```vpclattice.go``` the types are always VPC Lattice API types, so disambiguating is less important there. diff --git a/pkg/deploy/lattice/listener_manager.go b/pkg/deploy/lattice/listener_manager.go index c58541bb..ab5cc72f 100644 --- a/pkg/deploy/lattice/listener_manager.go +++ b/pkg/deploy/lattice/listener_manager.go @@ -14,27 +14,27 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/utils" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) type ListenerManager interface { - Cloud() lattice_aws.Cloud - Create(ctx context.Context, service *latticemodel.Listener) (latticemodel.ListenerStatus, error) + Cloud() pkg_aws.Cloud + Create(ctx context.Context, service *model.Listener) (model.ListenerStatus, error) Delete(ctx context.Context, listenerID string, serviceID string) error List(ctx context.Context, serviceID string) ([]*vpclattice.ListenerSummary, error) } type defaultListenerManager struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud latticeDataStore *latticestore.LatticeDataStore } func NewListenerManager( log gwlog.Logger, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, latticeDataStore *latticestore.LatticeDataStore, ) *defaultListenerManager { return &defaultListenerManager{ @@ -44,12 +44,12 @@ func NewListenerManager( } } -func (d *defaultListenerManager) Cloud() lattice_aws.Cloud { +func (d *defaultListenerManager) Cloud() pkg_aws.Cloud { return d.cloud } type ListenerLSNProvider struct { - l *latticemodel.Listener + l *model.Listener } func (r *ListenerLSNProvider) LatticeServiceName() string { @@ -58,8 +58,8 @@ func (r *ListenerLSNProvider) LatticeServiceName() string { func (d *defaultListenerManager) Create( ctx context.Context, - listener *latticemodel.Listener, -) (latticemodel.ListenerStatus, error) { + listener *model.Listener, +) (model.ListenerStatus, error) { listenerSpec := listener.Spec d.log.Infof("Creating listener %s-%s", listenerSpec.Name, listenerSpec.Namespace) @@ -68,9 +68,9 @@ func (d *defaultListenerManager) Create( if services.IsNotFoundError(err1) { errMsg := fmt.Sprintf("Service not found during creation of Listener %s-%s", listenerSpec.Name, listenerSpec.Namespace) - return latticemodel.ListenerStatus{}, fmt.Errorf(errMsg) + return model.ListenerStatus{}, fmt.Errorf(errMsg) } else { - return latticemodel.ListenerStatus{}, err1 + return model.ListenerStatus{}, err1 } } @@ -78,7 +78,7 @@ func (d *defaultListenerManager) Create( if err2 == nil { // update Listener k8sName, k8sNamespace := latticeName2k8s(aws.StringValue(lis.Name)) - return latticemodel.ListenerStatus{ + return model.ListenerStatus{ Name: k8sName, Namespace: k8sNamespace, Port: aws.Int64Value(lis.Port), @@ -109,10 +109,10 @@ func (d *defaultListenerManager) Create( resp, err := d.cloud.Lattice().CreateListener(&listenerInput) if err != nil { - return latticemodel.ListenerStatus{}, err + return model.ListenerStatus{}, err } - return latticemodel.ListenerStatus{ + return model.ListenerStatus{ Name: listener.Spec.Name, Namespace: listener.Spec.Namespace, ListenerARN: aws.StringValue(resp.Arn), diff --git a/pkg/deploy/lattice/listener_manager_test.go b/pkg/deploy/lattice/listener_manager_test.go index e77de96f..d425a109 100644 --- a/pkg/deploy/lattice/listener_manager_test.go +++ b/pkg/deploy/lattice/listener_manager_test.go @@ -121,7 +121,6 @@ func Test_AddListener(t *testing.T) { stack := core.NewDefaultStack(core.StackID(namespaceName)) action := latticemodel.DefaultAction{ - Is_Import: false, BackendServiceName: "tg-test", BackendServiceNamespace: "tg-default", } diff --git a/pkg/deploy/lattice/listener_synthesizer.go b/pkg/deploy/lattice/listener_synthesizer.go index 87e6bf03..d660daba 100644 --- a/pkg/deploy/lattice/listener_synthesizer.go +++ b/pkg/deploy/lattice/listener_synthesizer.go @@ -5,13 +5,11 @@ import ( "errors" "fmt" - //"string" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) @@ -37,7 +35,7 @@ func NewListenerSynthesizer( } func (l *listenerSynthesizer) Synthesize(ctx context.Context) error { - var resListener []*latticemodel.Listener + var resListener []*model.Listener err := l.stack.ListResources(&resListener) if err != nil { @@ -85,21 +83,21 @@ func (l *listenerSynthesizer) Synthesize(ctx context.Context) error { func (l *listenerSynthesizer) findMatchListener( ctx context.Context, - sdkListener *latticemodel.ListenerStatus, - resListener []*latticemodel.Listener, -) (latticemodel.Listener, error) { + sdkListener *model.ListenerStatus, + resListener []*model.Listener, +) (model.Listener, error) { for _, moduleListener := range resListener { if moduleListener.Spec.Port == sdkListener.Port && moduleListener.Spec.Protocol == sdkListener.Protocol { return *moduleListener, nil } } - return latticemodel.Listener{}, errors.New("failed to find matching listener in model") + return model.Listener{}, errors.New("failed to find matching listener in model") } -func (l *listenerSynthesizer) getSDKListeners(ctx context.Context) ([]*latticemodel.ListenerStatus, error) { - var sdkListeners []*latticemodel.ListenerStatus +func (l *listenerSynthesizer) getSDKListeners(ctx context.Context) ([]*model.ListenerStatus, error) { + var sdkListeners []*model.ListenerStatus - var resService []*latticemodel.Service + var resService []*model.Service err := l.stack.ListResources(&resService) if err != nil { @@ -116,7 +114,7 @@ func (l *listenerSynthesizer) getSDKListeners(ctx context.Context) ([]*latticemo listenerSummaries, err := l.listenerMgr.List(ctx, aws.StringValue(latticeService.Id)) for _, listenerSummary := range listenerSummaries { - sdkListeners = append(sdkListeners, &latticemodel.ListenerStatus{ + sdkListeners = append(sdkListeners, &model.ListenerStatus{ Name: aws.StringValue(listenerSummary.Name), ListenerARN: aws.StringValue(listenerSummary.Arn), ListenerID: aws.StringValue(listenerSummary.Id), diff --git a/pkg/deploy/lattice/listener_synthesizer_test.go b/pkg/deploy/lattice/listener_synthesizer_test.go index 51be7087..46d5fa0f 100644 --- a/pkg/deploy/lattice/listener_synthesizer_test.go +++ b/pkg/deploy/lattice/listener_synthesizer_test.go @@ -132,7 +132,6 @@ func Test_SynthesizeListener(t *testing.T) { } action := latticemodel.DefaultAction{ - Is_Import: false, BackendServiceName: "test", BackendServiceNamespace: "default", } diff --git a/pkg/deploy/lattice/rule_manager.go b/pkg/deploy/lattice/rule_manager.go index 84cbe082..10bbfbbe 100644 --- a/pkg/deploy/lattice/rule_manager.go +++ b/pkg/deploy/lattice/rule_manager.go @@ -14,30 +14,30 @@ import ( "github.com/aws/aws-sdk-go/service/vpclattice" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) type RuleManager interface { - Cloud() lattice_aws.Cloud - Create(ctx context.Context, rule *latticemodel.Rule) (latticemodel.RuleStatus, error) + Cloud() pkg_aws.Cloud + Create(ctx context.Context, rule *model.Rule) (model.RuleStatus, error) Delete(ctx context.Context, ruleId string, listenerId string, serviceId string) error - Update(ctx context.Context, rules []*latticemodel.Rule) error - List(ctx context.Context, serviceId string, listenerId string) ([]*latticemodel.RuleStatus, error) + Update(ctx context.Context, rules []*model.Rule) error + List(ctx context.Context, serviceId string, listenerId string) ([]*model.RuleStatus, error) Get(ctx context.Context, serviceId string, listenerId string, ruleId string) (*vpclattice.GetRuleOutput, error) } type defaultRuleManager struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud latticeDataStore *latticestore.LatticeDataStore } func NewRuleManager( log gwlog.Logger, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, store *latticestore.LatticeDataStore, ) *defaultRuleManager { return &defaultRuleManager{ @@ -47,12 +47,12 @@ func NewRuleManager( } } -func (r *defaultRuleManager) Cloud() lattice_aws.Cloud { +func (r *defaultRuleManager) Cloud() pkg_aws.Cloud { return r.cloud } type RuleLSNProvider struct { - rule *latticemodel.Rule + rule *model.Rule } func (r *RuleLSNProvider) LatticeServiceName() string { @@ -71,8 +71,8 @@ func (r *defaultRuleManager) Get(ctx context.Context, serviceId string, listener } // find out all rules in SDK lattice under a single service -func (r *defaultRuleManager) List(ctx context.Context, service string, listener string) ([]*latticemodel.RuleStatus, error) { - var sdkRules []*latticemodel.RuleStatus = nil +func (r *defaultRuleManager) List(ctx context.Context, service string, listener string) ([]*model.RuleStatus, error) { + var sdkRules []*model.RuleStatus = nil ruleListInput := vpclattice.ListRulesInput{ ListenerIdentifier: aws.String(listener), @@ -87,7 +87,7 @@ func (r *defaultRuleManager) List(ctx context.Context, service string, listener for _, ruleSum := range resp.Items { if !aws.BoolValue(ruleSum.IsDefault) { - sdkRules = append(sdkRules, &latticemodel.RuleStatus{ + sdkRules = append(sdkRules, &model.RuleStatus{ RuleID: aws.StringValue(ruleSum.Id), ServiceID: service, ListenerID: listener, @@ -99,7 +99,7 @@ func (r *defaultRuleManager) List(ctx context.Context, service string, listener } // today, it only batch update the priority -func (r *defaultRuleManager) Update(ctx context.Context, rules []*latticemodel.Rule) error { +func (r *defaultRuleManager) Update(ctx context.Context, rules []*model.Rule) error { firstRuleSpec := rules[0].Spec var ruleUpdateList []*vpclattice.RuleUpdate @@ -138,25 +138,25 @@ func (r *defaultRuleManager) Update(ctx context.Context, rules []*latticemodel.R return err } -func (r *defaultRuleManager) Create(ctx context.Context, rule *latticemodel.Rule) (latticemodel.RuleStatus, error) { +func (r *defaultRuleManager) Create(ctx context.Context, rule *model.Rule) (model.RuleStatus, error) { r.log.Debugf("Creating rule %s for service %s-%s and listener port %d and protocol %s", rule.Spec.RuleID, rule.Spec.ServiceName, rule.Spec.ServiceNamespace, rule.Spec.ListenerPort, rule.Spec.ListenerProtocol) latticeService, err := r.cloud.Lattice().FindService(ctx, &RuleLSNProvider{rule}) if err != nil { - return latticemodel.RuleStatus{}, err + return model.RuleStatus{}, err } listener, err := r.latticeDataStore.GetlListener(rule.Spec.ServiceName, rule.Spec.ServiceNamespace, rule.Spec.ListenerPort, rule.Spec.ListenerProtocol) if err != nil { - return latticemodel.RuleStatus{}, err + return model.RuleStatus{}, err } priority, err := ruleID2Priority(rule.Spec.RuleID) if err != nil { - return latticemodel.RuleStatus{}, fmt.Errorf("failed to create rule due to invalid ruleId, err: %s", err) + return model.RuleStatus{}, fmt.Errorf("failed to create rule due to invalid ruleId, err: %s", err) } r.log.Debugf("Converted rule id %s to priority %d", rule.Spec.RuleID, priority) @@ -178,7 +178,7 @@ func (r *defaultRuleManager) Create(ctx context.Context, rule *latticemodel.Rule tg, err := r.latticeDataStore.GetTargetGroup(tgName, tgRule.RouteName, tgRule.IsServiceImport) if err != nil { - return latticemodel.RuleStatus{}, err + return model.RuleStatus{}, err } latticeTG := vpclattice.WeightedTargetGroup{ @@ -216,7 +216,7 @@ func (r *defaultRuleManager) Create(ctx context.Context, rule *latticemodel.Rule r.log.Errorf("Error updating rule, %s", err) } - return latticemodel.RuleStatus{ + return model.RuleStatus{ RuleID: aws.StringValue(resp.Id), UpdatePriorityNeeded: ruleStatus.UpdatePriorityNeeded, ServiceID: aws.StringValue(latticeService.Id), @@ -246,10 +246,10 @@ func (r *defaultRuleManager) Create(ctx context.Context, rule *latticemodel.Rule resp, err := r.cloud.Lattice().CreateRule(&ruleInput) if err != nil { - return latticemodel.RuleStatus{}, err + return model.RuleStatus{}, err } - return latticemodel.RuleStatus{ + return model.RuleStatus{ RuleID: *resp.Id, ListenerID: listener.ID, ServiceID: aws.StringValue(latticeService.Id), @@ -258,7 +258,7 @@ func (r *defaultRuleManager) Create(ctx context.Context, rule *latticemodel.Rule }, nil } -func updateSDKhttpMatch(httpMatch *vpclattice.HttpMatch, rule *latticemodel.Rule) { +func updateSDKhttpMatch(httpMatch *vpclattice.HttpMatch, rule *model.Rule) { // setup path based if rule.Spec.PathMatchExact || rule.Spec.PathMatchPrefix { matchType := vpclattice.PathMatchType{} @@ -287,7 +287,7 @@ func updateSDKhttpMatch(httpMatch *vpclattice.HttpMatch, rule *latticemodel.Rule } } -func isRulesSame(log gwlog.Logger, modelRule *latticemodel.Rule, sdkRuleDetail *vpclattice.GetRuleOutput) bool { +func isRulesSame(log gwlog.Logger, modelRule *model.Rule, sdkRuleDetail *vpclattice.GetRuleOutput) bool { // Exact Path Match if modelRule.Spec.PathMatchExact { if sdkRuleDetail.Match.HttpMatch.PathMatch == nil || @@ -384,10 +384,10 @@ func isRulesSame(log gwlog.Logger, modelRule *latticemodel.Rule, sdkRuleDetail * // If rule spec is same, then determine if there is any changes on target groups func (r *defaultRuleManager) findMatchingRule( ctx context.Context, - rule *latticemodel.Rule, + rule *model.Rule, serviceId string, listenerId string, -) (latticemodel.RuleStatus, error) { +) (model.RuleStatus, error) { var priorityMap [100]bool for i := 1; i < 100; i++ { @@ -403,7 +403,7 @@ func (r *defaultRuleManager) findMatchingRule( var resp *vpclattice.ListRulesOutput resp, err := r.cloud.Lattice().ListRules(&ruleListInput) if err != nil { - return latticemodel.RuleStatus{}, err + return model.RuleStatus{}, err } var matchRule *vpclattice.GetRuleOutput = nil @@ -493,7 +493,7 @@ func (r *defaultRuleManager) findMatchingRule( UpdatePriority = true } - return latticemodel.RuleStatus{ + return model.RuleStatus{ RuleARN: aws.StringValue(matchRule.Arn), RuleID: aws.StringValue(matchRule.Id), Priority: aws.Int64Value(matchRule.Priority), @@ -510,7 +510,7 @@ func (r *defaultRuleManager) findMatchingRule( } } - return latticemodel.RuleStatus{Priority: nextPriority}, errors.New("rule not found") + return model.RuleStatus{Priority: nextPriority}, errors.New("rule not found") } } diff --git a/pkg/deploy/lattice/rule_synthesizer.go b/pkg/deploy/lattice/rule_synthesizer.go index 2e96c225..8a522d81 100644 --- a/pkg/deploy/lattice/rule_synthesizer.go +++ b/pkg/deploy/lattice/rule_synthesizer.go @@ -9,7 +9,7 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) @@ -35,7 +35,7 @@ func NewRuleSynthesizer( } func (r *ruleSynthesizer) Synthesize(ctx context.Context) error { - var resRule []*latticemodel.Rule + var resRule []*model.Rule err := r.stack.ListResources(&resRule) if err != nil { @@ -92,9 +92,9 @@ func (r *ruleSynthesizer) findMatchedRule( sdkRuleId string, listener string, service string, - resRule []*latticemodel.Rule, -) (*latticemodel.Rule, error) { - var modelRule *latticemodel.Rule = nil + resRule []*model.Rule, +) (*model.Rule, error) { + var modelRule *model.Rule = nil sdkRuleDetail, err := r.rule.Get(ctx, service, listener, sdkRuleId) if err != nil { return modelRule, err @@ -115,11 +115,11 @@ func (r *ruleSynthesizer) findMatchedRule( return modelRule, fmt.Errorf("failed to find matching rule in model for rule %s", sdkRuleId) } -func (r *ruleSynthesizer) getSDKRules(ctx context.Context) ([]*latticemodel.RuleStatus, error) { - var sdkRules []*latticemodel.RuleStatus - var resService []*latticemodel.Service - var resListener []*latticemodel.Listener - var resRule []*latticemodel.Rule +func (r *ruleSynthesizer) getSDKRules(ctx context.Context) ([]*model.RuleStatus, error) { + var sdkRules []*model.RuleStatus + var resService []*model.Service + var resListener []*model.Listener + var resRule []*model.Rule err := r.stack.ListResources(&resService) if err != nil { diff --git a/pkg/deploy/lattice/service_manager.go b/pkg/deploy/lattice/service_manager.go index 202305ba..a9ac43fe 100644 --- a/pkg/deploy/lattice/service_manager.go +++ b/pkg/deploy/lattice/service_manager.go @@ -8,15 +8,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/vpclattice" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) //go:generate mockgen -destination service_manager_mock.go -package lattice github.com/aws/aws-application-networking-k8s/pkg/deploy/lattice ServiceManager -type Service = latticemodel.Service -type ServiceInfo = latticemodel.ServiceStatus +type Service = model.Service +type ServiceInfo = model.ServiceStatus type CreateSvcReq = vpclattice.CreateServiceInput type CreateSvcResp = vpclattice.CreateServiceOutput type UpdateSvcReq = vpclattice.UpdateServiceInput @@ -31,16 +31,16 @@ type ListSnSvcAssocsReq = vpclattice.ListServiceNetworkServiceAssociationsInput type SnSvcAssocSummary = vpclattice.ServiceNetworkServiceAssociationSummary type ServiceManager interface { - Create(ctx context.Context, service *latticemodel.Service) (latticemodel.ServiceStatus, error) - Delete(ctx context.Context, service *latticemodel.Service) error + Create(ctx context.Context, service *model.Service) (model.ServiceStatus, error) + Delete(ctx context.Context, service *model.Service) error } type defaultServiceManager struct { - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud datastore *latticestore.LatticeDataStore } -func NewServiceManager(cloud lattice_aws.Cloud, latticeDataStore *latticestore.LatticeDataStore) *defaultServiceManager { +func NewServiceManager(cloud pkg_aws.Cloud, latticeDataStore *latticestore.LatticeDataStore) *defaultServiceManager { return &defaultServiceManager{ cloud: cloud, datastore: latticeDataStore, diff --git a/pkg/deploy/lattice/service_network_manager.go b/pkg/deploy/lattice/service_network_manager.go index 2c7d5305..b3b5c7a7 100644 --- a/pkg/deploy/lattice/service_network_manager.go +++ b/pkg/deploy/lattice/service_network_manager.go @@ -13,16 +13,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/vpclattice" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/config" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils" ) //go:generate mockgen -destination service_network_manager_mock.go -package lattice github.com/aws/aws-application-networking-k8s/pkg/deploy/lattice ServiceNetworkManager type ServiceNetworkManager interface { - CreateOrUpdate(ctx context.Context, serviceNetwork *latticemodel.ServiceNetwork) (latticemodel.ServiceNetworkStatus, error) + CreateOrUpdate(ctx context.Context, serviceNetwork *model.ServiceNetwork) (model.ServiceNetworkStatus, error) List(ctx context.Context) ([]string, error) Delete(ctx context.Context, serviceNetwork string) error } @@ -32,7 +32,7 @@ type serviceNetworkOutput struct { snTags *vpclattice.ListTagsForResourceOutput } -func NewDefaultServiceNetworkManager(log gwlog.Logger, cloud lattice_aws.Cloud) *defaultServiceNetworkManager { +func NewDefaultServiceNetworkManager(log gwlog.Logger, cloud pkg_aws.Cloud) *defaultServiceNetworkManager { return &defaultServiceNetworkManager{ log: log, cloud: cloud, @@ -41,7 +41,7 @@ func NewDefaultServiceNetworkManager(log gwlog.Logger, cloud lattice_aws.Cloud) type defaultServiceNetworkManager struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } // CreateOrUpdate will try to create a service_network and associate the service_network with vpc. @@ -60,11 +60,11 @@ type defaultServiceNetworkManager struct { // // CreateServiceNetworkVpcAssociationInput returns ServiceNetworkVpcAssociationStatusFailed/ServiceNetworkVpcAssociationStatusCreateInProgress/MeshVpcAssociationStatusDeleteInProgress -func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, serviceNetwork *latticemodel.ServiceNetwork) (latticemodel.ServiceNetworkStatus, error) { +func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, serviceNetwork *model.ServiceNetwork) (model.ServiceNetworkStatus, error) { // check if exists foundSnSummary, err := m.cloud.Lattice().FindServiceNetwork(ctx, serviceNetwork.Spec.Name, "") if err != nil && !services.IsNotFoundError(err) { - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err } // pre declaration @@ -82,12 +82,12 @@ func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, servi Name: &serviceNetwork.Spec.Name, Tags: make(map[string]*string), } - serviceNetworkInput.Tags[latticemodel.K8SServiceNetworkOwnedByVPC] = &config.VpcID + serviceNetworkInput.Tags[model.K8SServiceNetworkOwnedByVPC] = &config.VpcID m.log.Debugf("Creating ServiceNetwork %+v", serviceNetworkInput) resp, err := vpcLatticeSess.CreateServiceNetworkWithContext(ctx, &serviceNetworkInput) if err != nil { - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err } serviceNetworkId = aws.StringValue(resp.Id) @@ -98,7 +98,7 @@ func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, servi serviceNetworkArn = aws.StringValue(foundSnSummary.SvcNetwork.Arn) isSnAlreadyAssociatedWithCurrentVpc, snvaAssociatedWithCurrentVPC, _, err = m.isServiceNetworkAlreadyAssociatedWithVPC(ctx, serviceNetworkId) if err != nil { - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err } if serviceNetwork.Spec.AssociateToVPC == true && isSnAlreadyAssociatedWithCurrentVpc == true && snvaAssociatedWithCurrentVPC.Status != nil && aws.StringValue(snvaAssociatedWithCurrentVPC.Status) == vpclattice.ServiceNetworkVpcAssociationStatusActive { @@ -118,21 +118,21 @@ func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, servi m.log.Debugf("Creating association between ServiceNetwork %s and VPC %s", serviceNetworkId, config.VpcID) resp, err := vpcLatticeSess.CreateServiceNetworkVpcAssociationWithContext(ctx, &createServiceNetworkVpcAssociationInput) if err != nil { - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err } serviceNetworkVpcAssociationStatus := aws.StringValue(resp.Status) switch serviceNetworkVpcAssociationStatus { case vpclattice.ServiceNetworkVpcAssociationStatusCreateInProgress: - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) case vpclattice.ServiceNetworkVpcAssociationStatusActive: - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil + return model.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil case vpclattice.ServiceNetworkVpcAssociationStatusCreateFailed: - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) case vpclattice.ServiceNetworkVpcAssociationStatusDeleteFailed: - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) case vpclattice.ServiceNetworkVpcAssociationStatusDeleteInProgress: - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) } } } else { @@ -151,11 +151,11 @@ func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, servi } // return retry and check later if disassociation workflow finishes - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) + return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, errors.New(LATTICE_RETRY) } m.log.Debugf("Created ServiceNetwork %s without VPC association", serviceNetwork.Spec.Name) } - return latticemodel.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil + return model.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil } // return all service_networkes associated with VPC @@ -209,7 +209,7 @@ func (m *defaultServiceNetworkManager) Delete(ctx context.Context, snName string // check if this VPC is the one created the service network needToDelete := false if serviceNetworkSummary.Tags != nil { - vpcOwner, ok := serviceNetworkSummary.Tags[latticemodel.K8SServiceNetworkOwnedByVPC] + vpcOwner, ok := serviceNetworkSummary.Tags[model.K8SServiceNetworkOwnedByVPC] if ok && *vpcOwner == config.VpcID { needToDelete = true } else { @@ -287,17 +287,17 @@ func (m *defaultServiceNetworkManager) isServiceNetworkAlreadyAssociatedWithVPC( return false, nil, resp, err } -func (m *defaultServiceNetworkManager) UpdateServiceNetworkVpcAssociation(ctx context.Context, existingSN *vpclattice.ServiceNetworkSummary, desiredSN *latticemodel.ServiceNetwork, existingSnvaId *string) (latticemodel.ServiceNetworkStatus, error) { +func (m *defaultServiceNetworkManager) UpdateServiceNetworkVpcAssociation(ctx context.Context, existingSN *vpclattice.ServiceNetworkSummary, desiredSN *model.ServiceNetwork, existingSnvaId *string) (model.ServiceNetworkStatus, error) { retrievedSnva, err := m.cloud.Lattice().GetServiceNetworkVpcAssociationWithContext(ctx, &vpclattice.GetServiceNetworkVpcAssociationInput{ ServiceNetworkVpcAssociationIdentifier: existingSnvaId, }) if err != nil { - return latticemodel.ServiceNetworkStatus{}, err + return model.ServiceNetworkStatus{}, err } sgIdsEqual := securityGroupIdsEqual(desiredSN.Spec.SecurityGroupIds, retrievedSnva.SecurityGroupIds) if sgIdsEqual { // desiredSN's security group ids are same with retrievedSnva's security group ids, don't need to update - return latticemodel.ServiceNetworkStatus{ + return model.ServiceNetworkStatus{ ServiceNetworkID: *existingSN.Id, ServiceNetworkARN: *existingSN.Arn, SnvaSecurityGroupIds: retrievedSnva.SecurityGroupIds, @@ -308,16 +308,16 @@ func (m *defaultServiceNetworkManager) UpdateServiceNetworkVpcAssociation(ctx co SecurityGroupIds: desiredSN.Spec.SecurityGroupIds, }) if err != nil { - return latticemodel.ServiceNetworkStatus{}, err + return model.ServiceNetworkStatus{}, err } if *updateSnvaResp.Status == vpclattice.ServiceNetworkVpcAssociationStatusActive { - return latticemodel.ServiceNetworkStatus{ + return model.ServiceNetworkStatus{ ServiceNetworkID: *existingSN.Id, ServiceNetworkARN: *existingSN.Arn, SnvaSecurityGroupIds: updateSnvaResp.SecurityGroupIds, }, nil } else { - return latticemodel.ServiceNetworkStatus{}, fmt.Errorf("%w, update svna status: %s", RetryErr, *updateSnvaResp.Status) + return model.ServiceNetworkStatus{}, fmt.Errorf("%w, update svna status: %s", RetryErr, *updateSnvaResp.Status) } } diff --git a/pkg/deploy/lattice/service_network_synthesizer.go b/pkg/deploy/lattice/service_network_synthesizer.go index 0b8a95bd..873b67dd 100644 --- a/pkg/deploy/lattice/service_network_synthesizer.go +++ b/pkg/deploy/lattice/service_network_synthesizer.go @@ -5,10 +5,10 @@ import ( "errors" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) @@ -54,7 +54,7 @@ func (s *serviceNetworkSynthesizer) Synthesize(ctx context.Context) error { } func (s *serviceNetworkSynthesizer) synthesizeTriggeredGateways(ctx context.Context) error { - var serviceNetworks []*latticemodel.ServiceNetwork + var serviceNetworks []*model.ServiceNetwork var ret = "" // only tracks the last error encountered, others are in the logs s.stack.ListResources(&serviceNetworks) @@ -87,11 +87,11 @@ func (s *serviceNetworkSynthesizer) synthesizeTriggeredGateways(ctx context.Cont } } -func (s *serviceNetworkSynthesizer) deleteServiceNetwork(ctx context.Context, resServiceNetwork *latticemodel.ServiceNetwork) string { +func (s *serviceNetworkSynthesizer) deleteServiceNetwork(ctx context.Context, resServiceNetwork *model.ServiceNetwork) string { s.log.Debugf("Synthesizing Gateway deletion for service network %s", resServiceNetwork.Spec.Name) // TODO need to check if service network is referenced by gateway in other namespace - gwList := &gateway_api.GatewayList{} + gwList := &gwv1beta1.GatewayList{} s.client.List(ctx, gwList) snUsedByGateway := false for _, gw := range gwList.Items { @@ -128,7 +128,7 @@ func (s *serviceNetworkSynthesizer) synthesizeSDKServiceNetworks(ctx context.Con // handling delete those gateway in lattice DB, but not in K8S DB // check local K8S cache - gwList := &gateway_api.GatewayList{} + gwList := &gwv1beta1.GatewayList{} s.client.List(context.TODO(), gwList) for _, sdkServiceNetwork := range sdkServiceNetworks { @@ -168,8 +168,8 @@ func (s *serviceNetworkSynthesizer) synthesizeSDKServiceNetworks(ctx context.Con } } -func mapResServiceNetworkByResourceID(resServiceNetworks []*latticemodel.ServiceNetwork) map[string]*latticemodel.ServiceNetwork { - resServiceNetworkByID := make(map[string]*latticemodel.ServiceNetwork, len(resServiceNetworks)) +func mapResServiceNetworkByResourceID(resServiceNetworks []*model.ServiceNetwork) map[string]*model.ServiceNetwork { + resServiceNetworkByID := make(map[string]*model.ServiceNetwork, len(resServiceNetworks)) for _, resServiceNetwork := range resServiceNetworks { resServiceNetworkByID[resServiceNetwork.ID()] = resServiceNetwork } diff --git a/pkg/deploy/lattice/service_synthesizer.go b/pkg/deploy/lattice/service_synthesizer.go index 671e7515..1cd83a10 100644 --- a/pkg/deploy/lattice/service_synthesizer.go +++ b/pkg/deploy/lattice/service_synthesizer.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/deploy/externaldns" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) @@ -35,7 +35,7 @@ type serviceSynthesizer struct { } func (s *serviceSynthesizer) Synthesize(ctx context.Context) error { - var resServices []*latticemodel.Service + var resServices []*model.Service s.stack.ListResources(&resServices) for _, resService := range resServices { diff --git a/pkg/deploy/lattice/target_group_manager.go b/pkg/deploy/lattice/target_group_manager.go index 7213c8ce..67291a8b 100644 --- a/pkg/deploy/lattice/target_group_manager.go +++ b/pkg/deploy/lattice/target_group_manager.go @@ -11,26 +11,26 @@ import ( "fmt" "strings" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) type TargetGroupManager interface { - Create(ctx context.Context, targetGroup *latticemodel.TargetGroup) (latticemodel.TargetGroupStatus, error) - Delete(ctx context.Context, targetGroup *latticemodel.TargetGroup) error + Create(ctx context.Context, targetGroup *model.TargetGroup) (model.TargetGroupStatus, error) + Delete(ctx context.Context, targetGroup *model.TargetGroup) error List(ctx context.Context) ([]targetGroupOutput, error) - Get(tx context.Context, targetGroup *latticemodel.TargetGroup) (latticemodel.TargetGroupStatus, error) + Get(tx context.Context, targetGroup *model.TargetGroup) (model.TargetGroupStatus, error) } type defaultTargetGroupManager struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } -func NewTargetGroupManager(log gwlog.Logger, cloud lattice_aws.Cloud) *defaultTargetGroupManager { +func NewTargetGroupManager(log gwlog.Logger, cloud pkg_aws.Cloud) *defaultTargetGroupManager { return &defaultTargetGroupManager{ log: log, cloud: cloud, @@ -38,7 +38,7 @@ func NewTargetGroupManager(log gwlog.Logger, cloud lattice_aws.Cloud) *defaultTa } // Determines the "actual" target group name used in VPC Lattice. -func getLatticeTGName(targetGroup *latticemodel.TargetGroup) string { +func getLatticeTGName(targetGroup *model.TargetGroup) string { var ( namePrefix = targetGroup.Spec.Name protocol = strings.ToLower(targetGroup.Spec.Config.Protocol) @@ -70,8 +70,8 @@ func getLatticeTGName(targetGroup *latticemodel.TargetGroup) string { // TG is TargetGroupStatusActive func (s *defaultTargetGroupManager) Create( ctx context.Context, - targetGroup *latticemodel.TargetGroup, -) (latticemodel.TargetGroupStatus, error) { + targetGroup *model.TargetGroup, +) (model.TargetGroupStatus, error) { s.log.Debugf("Creating VPC Lattice Target Group %s", targetGroup.Spec.Name) latticeTGName := getLatticeTGName(targetGroup) @@ -79,7 +79,7 @@ func (s *defaultTargetGroupManager) Create( tgSummary, err := s.findTargetGroup(ctx, targetGroup) if err != nil { - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err } vpcLatticeSess := s.cloud.Lattice() @@ -114,62 +114,62 @@ func (s *defaultTargetGroupManager) Create( Type: &targetGroupType, Tags: make(map[string]*string), } - createTargetGroupInput.Tags[latticemodel.K8SServiceNameKey] = &targetGroup.Spec.Config.K8SServiceName - createTargetGroupInput.Tags[latticemodel.K8SServiceNamespaceKey] = &targetGroup.Spec.Config.K8SServiceNamespace + createTargetGroupInput.Tags[model.K8SServiceNameKey] = &targetGroup.Spec.Config.K8SServiceName + createTargetGroupInput.Tags[model.K8SServiceNamespaceKey] = &targetGroup.Spec.Config.K8SServiceNamespace if targetGroup.Spec.Config.IsServiceExport { - value := latticemodel.K8SServiceExportType - createTargetGroupInput.Tags[latticemodel.K8SParentRefTypeKey] = &value + value := model.K8SServiceExportType + createTargetGroupInput.Tags[model.K8SParentRefTypeKey] = &value } else { - value := latticemodel.K8SHTTPRouteType - createTargetGroupInput.Tags[latticemodel.K8SParentRefTypeKey] = &value - createTargetGroupInput.Tags[latticemodel.K8SHTTPRouteNameKey] = &targetGroup.Spec.Config.K8SHTTPRouteName - createTargetGroupInput.Tags[latticemodel.K8SHTTPRouteNamespaceKey] = &targetGroup.Spec.Config.K8SHTTPRouteNamespace + value := model.K8SHTTPRouteType + createTargetGroupInput.Tags[model.K8SParentRefTypeKey] = &value + createTargetGroupInput.Tags[model.K8SHTTPRouteNameKey] = &targetGroup.Spec.Config.K8SHTTPRouteName + createTargetGroupInput.Tags[model.K8SHTTPRouteNamespaceKey] = &targetGroup.Spec.Config.K8SHTTPRouteNamespace } resp, err := vpcLatticeSess.CreateTargetGroupWithContext(ctx, &createTargetGroupInput) if err != nil { - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err } else { tgArn := aws.StringValue(resp.Arn) tgId := aws.StringValue(resp.Id) tgStatus := aws.StringValue(resp.Status) switch tgStatus { case vpclattice.TargetGroupStatusCreateInProgress: - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) case vpclattice.TargetGroupStatusActive: - return latticemodel.TargetGroupStatus{TargetGroupARN: tgArn, TargetGroupID: tgId}, nil + return model.TargetGroupStatus{TargetGroupARN: tgArn, TargetGroupID: tgId}, nil case vpclattice.TargetGroupStatusCreateFailed: - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) case vpclattice.TargetGroupStatusDeleteFailed: - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) case vpclattice.TargetGroupStatusDeleteInProgress: - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New(LATTICE_RETRY) } } - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, nil + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, nil } -func (s *defaultTargetGroupManager) Get(ctx context.Context, targetGroup *latticemodel.TargetGroup) (latticemodel.TargetGroupStatus, error) { +func (s *defaultTargetGroupManager) Get(ctx context.Context, targetGroup *model.TargetGroup) (model.TargetGroupStatus, error) { s.log.Debugf("Getting VPC Lattice Target Group %s", targetGroup.Spec.Name) // check if exists tgSummary, err := s.findTargetGroup(ctx, targetGroup) if err != nil { - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, err } if tgSummary != nil { - return latticemodel.TargetGroupStatus{TargetGroupARN: aws.StringValue(tgSummary.Arn), TargetGroupID: aws.StringValue(tgSummary.Id)}, err + return model.TargetGroupStatus{TargetGroupARN: aws.StringValue(tgSummary.Arn), TargetGroupID: aws.StringValue(tgSummary.Id)}, err } - return latticemodel.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New("Non existing Target Group") + return model.TargetGroupStatus{TargetGroupARN: "", TargetGroupID: ""}, errors.New("Non existing Target Group") } -func (s *defaultTargetGroupManager) update(ctx context.Context, targetGroup *latticemodel.TargetGroup, tgSummary *vpclattice.TargetGroupSummary) (latticemodel.TargetGroupStatus, error) { +func (s *defaultTargetGroupManager) update(ctx context.Context, targetGroup *model.TargetGroup, tgSummary *vpclattice.TargetGroupSummary) (model.TargetGroupStatus, error) { s.log.Debugf("Updating VPC Lattice Target Group %s", targetGroup.Spec.Name) vpcLatticeSess := s.cloud.Lattice() healthCheckConfig := targetGroup.Spec.Config.HealthCheckConfig - targetGroupStatus := latticemodel.TargetGroupStatus{ + targetGroupStatus := model.TargetGroupStatus{ TargetGroupARN: aws.StringValue(tgSummary.Arn), TargetGroupID: aws.StringValue(tgSummary.Id), } @@ -186,13 +186,13 @@ func (s *defaultTargetGroupManager) update(ctx context.Context, targetGroup *lat }) if err != nil { - return latticemodel.TargetGroupStatus{}, err + return model.TargetGroupStatus{}, err } return targetGroupStatus, nil } -func (s *defaultTargetGroupManager) Delete(ctx context.Context, targetGroup *latticemodel.TargetGroup) error { +func (s *defaultTargetGroupManager) Delete(ctx context.Context, targetGroup *model.TargetGroup) error { s.log.Debugf("Deleting VPC Lattice Target Group %s", targetGroup.Spec.Name) if targetGroup.Spec.LatticeID == "" { @@ -319,7 +319,7 @@ func (s *defaultTargetGroupManager) List(ctx context.Context) ([]targetGroupOutp return tgList, err } -func isNameOfTargetGroup(targetGroup *latticemodel.TargetGroup, name string) bool { +func isNameOfTargetGroup(targetGroup *model.TargetGroup, name string) bool { if targetGroup.Spec.Config.IsServiceImport { // We are missing protocol info for ServiceImport, but we do know the RouteType. // Relying on the assumption that we have one TG per (RouteType, Service), @@ -338,10 +338,10 @@ func isNameOfTargetGroup(targetGroup *latticemodel.TargetGroup, name string) boo for _, p := range validProtocols { for _, pv := range validProtocolVersions { - candidate := &latticemodel.TargetGroup{ - Spec: latticemodel.TargetGroupSpec{ + candidate := &model.TargetGroup{ + Spec: model.TargetGroupSpec{ Name: targetGroup.Spec.Name, - Config: latticemodel.TargetGroupConfig{ + Config: model.TargetGroupConfig{ Protocol: p, ProtocolVersion: pv, }, @@ -360,7 +360,7 @@ func isNameOfTargetGroup(targetGroup *latticemodel.TargetGroup, name string) boo func (s *defaultTargetGroupManager) findTargetGroup( ctx context.Context, - targetGroup *latticemodel.TargetGroup, + targetGroup *model.TargetGroup, ) (*vpclattice.TargetGroupSummary, error) { vpcLatticeSess := s.cloud.Lattice() targetGroupListInput := vpclattice.ListTargetGroupsInput{} diff --git a/pkg/deploy/lattice/target_group_synthesizer.go b/pkg/deploy/lattice/target_group_synthesizer.go index d0986daf..0ee0bcd5 100644 --- a/pkg/deploy/lattice/target_group_synthesizer.go +++ b/pkg/deploy/lattice/target_group_synthesizer.go @@ -11,18 +11,18 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - mcs_api "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) func NewTargetGroupSynthesizer( log gwlog.Logger, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, client client.Client, tgManager TargetGroupManager, stack core.Stack, @@ -40,7 +40,7 @@ func NewTargetGroupSynthesizer( type TargetGroupSynthesizer struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud client client.Client targetGroupManager TargetGroupManager stack core.Stack @@ -75,7 +75,7 @@ func (t *TargetGroupSynthesizer) Synthesize(ctx context.Context) error { } func (t *TargetGroupSynthesizer) SynthesizeTriggeredTargetGroup(ctx context.Context) error { - var resTargetGroups []*latticemodel.TargetGroup + var resTargetGroups []*model.TargetGroup var returnErr = false t.stack.ListResources(&resTargetGroups) @@ -165,8 +165,7 @@ func (t *TargetGroupSynthesizer) SynthesizeTriggeredTargetGroup(ctx context.Cont } func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) error { - var staleSDKTGs []latticemodel.TargetGroup - + var staleSDKTGs []model.TargetGroup sdkTGs, err := t.targetGroupManager.List(ctx) if err != nil { t.log.Errorf("Error listing target groups: %s", err) @@ -190,21 +189,23 @@ func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) continue } - parentRef, ok := tgTags.Tags[latticemodel.K8SParentRefTypeKey] + parentRef, ok := tgTags.Tags[model.K8SParentRefTypeKey] if !ok || parentRef == nil { t.log.Debugf("Ignoring target group %s (%s) because it has no K8S parentRef tag", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) continue } - srvName, ok := tgTags.Tags[latticemodel.K8SServiceNameKey] + srvName, ok := tgTags.Tags[model.K8SServiceNameKey] + if !ok || srvName == nil { t.log.Debugf("Ignoring target group %s (%s) because it has no servicename tag", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) continue } - srvNamespace, ok := tgTags.Tags[latticemodel.K8SServiceNamespaceKey] + srvNamespace, ok := tgTags.Tags[model.K8SServiceNamespaceKey] + if !ok || srvNamespace == nil { t.log.Infof("Ignoring target group %s (%s) because it has no serviceNamespace tag", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) @@ -213,16 +214,15 @@ func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) // if its parentref is service export, check the parent service export exist // Ignore if service export exists - if *parentRef == latticemodel.K8SServiceExportType { - t.log.Debugf("TargetGroup %s (%s) is referenced by ServiceExport", + if *parentRef == model.K8SServiceExportType { + t.log.Infof("TargetGroup %s (%s) is referenced by ServiceExport", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) srvExportName := types.NamespacedName{ Namespace: *srvNamespace, Name: *srvName, } - - srvExport := &mcs_api.ServiceExport{} + srvExport := &mcsv1alpha1.ServiceExport{} if err := t.client.Get(ctx, srvExportName, srvExport); err == nil { t.log.Debugf("Ignoring target group %s (%s), which was triggered by serviceexport, since serviceexport object is found", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) @@ -232,11 +232,11 @@ func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) // if its parentRef is a route, check that the parent route exists // Ignore if route does not exist - if *parentRef == latticemodel.K8SHTTPRouteType { - t.log.Debugf("Target group %s (%s) is referenced by a route", + if *parentRef == model.K8SHTTPRouteType { + t.log.Infof("Target group %s (%s) is referenced by a route", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) - routeNameValue, ok := tgTags.Tags[latticemodel.K8SHTTPRouteNameKey] + routeNameValue, ok := tgTags.Tags[model.K8SHTTPRouteNameKey] tgRouteName = *routeNameValue if !ok || routeNameValue == nil { t.log.Infof("Ignoring target group %s (%s), which was triggered by a route, because it has no route name tag", @@ -244,7 +244,8 @@ func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) continue } - routeNamespaceValue, ok := tgTags.Tags[latticemodel.K8SHTTPRouteNamespaceKey] + routeNamespaceValue, ok := tgTags.Tags[model.K8SHTTPRouteNamespaceKey] + if !ok || routeNamespaceValue == nil { t.log.Infof("Ignoring target group %s (%s), which was triggered by a route, because it has no route namespace tag", *sdkTG.getTargetGroupOutput.Arn, *sdkTG.getTargetGroupOutput.Name) @@ -293,10 +294,10 @@ func (t *TargetGroupSynthesizer) SynthesizeSDKTargetGroups(ctx context.Context) t.log.Debugf("Appending stale target group to stale list. Name: %s, routename: %s, ARN: %s", *sdkTG.getTargetGroupOutput.Name, tgRouteName, *sdkTG.getTargetGroupOutput.Id) - staleSDKTGs = append(staleSDKTGs, latticemodel.TargetGroup{ - Spec: latticemodel.TargetGroupSpec{ + staleSDKTGs = append(staleSDKTGs, model.TargetGroup{ + Spec: model.TargetGroupSpec{ Name: *sdkTG.getTargetGroupOutput.Name, - Config: latticemodel.TargetGroupConfig{ + Config: model.TargetGroupConfig{ K8SHTTPRouteName: tgRouteName, }, LatticeID: *sdkTG.getTargetGroupOutput.Id, @@ -350,7 +351,7 @@ func (t *TargetGroupSynthesizer) PostSynthesize(ctx context.Context) error { } func (t *TargetGroupSynthesizer) SynthesizeTriggeredTargetGroupsCreation(ctx context.Context) error { - var resTargetGroups []*latticemodel.TargetGroup + var resTargetGroups []*model.TargetGroup var returnErr = false err := t.stack.ListResources(&resTargetGroups) if err != nil { @@ -404,7 +405,7 @@ func (t *TargetGroupSynthesizer) SynthesizeTriggeredTargetGroupsCreation(ctx con } func (t *TargetGroupSynthesizer) SynthesizeTriggeredTargetGroupsDeletion(ctx context.Context) error { - var resTargetGroups []*latticemodel.TargetGroup + var resTargetGroups []*model.TargetGroup var returnErr = false err := t.stack.ListResources(&resTargetGroups) if err != nil { diff --git a/pkg/deploy/lattice/target_group_synthesizer_test.go b/pkg/deploy/lattice/target_group_synthesizer_test.go index 8243fd18..4a1ad778 100644 --- a/pkg/deploy/lattice/target_group_synthesizer_test.go +++ b/pkg/deploy/lattice/target_group_synthesizer_test.go @@ -130,7 +130,7 @@ func Test_SynthesizeTriggeredServiceExport(t *testing.T) { ds.AddTargetGroup(tgName, "vpc-123456789", "123456789", "tg-123", false, "") } - builder := gateway.NewTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) + builder := gateway.NewSvcExportTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) stack, tg, err := builder.Build(ctx, tt.svcExport) assert.Nil(t, err) @@ -877,7 +877,7 @@ func Test_SynthesizeTriggeredTargetGroupsCreation_TriggeredByServiceExport(t *te tgName := latticestore.TargetGroupName(tt.svcExport.Name, tt.svcExport.Namespace) ds.AddTargetGroup(tgName, "vpc-123456789", "arn123", "4567", false, "") } - builder := gateway.NewTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) + builder := gateway.NewSvcExportTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) stack, tg, err := builder.Build(ctx, tt.svcExport) assert.Nil(t, err) diff --git a/pkg/deploy/lattice/targets_manager.go b/pkg/deploy/lattice/targets_manager.go index a77a32a5..8dddf07e 100644 --- a/pkg/deploy/lattice/targets_manager.go +++ b/pkg/deploy/lattice/targets_manager.go @@ -7,25 +7,25 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/vpclattice" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) type TargetsManager interface { - Create(ctx context.Context, targets *latticemodel.Targets) error + Create(ctx context.Context, targets *model.Targets) error } type defaultTargetsManager struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud datastore *latticestore.LatticeDataStore } func NewTargetsManager( log gwlog.Logger, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, datastore *latticestore.LatticeDataStore, ) *defaultTargetsManager { return &defaultTargetsManager{ @@ -42,7 +42,7 @@ func NewTargetsManager( // nonempty unsuccessfully registered targets list // otherwise: // nil -func (s *defaultTargetsManager) Create(ctx context.Context, targets *latticemodel.Targets) error { +func (s *defaultTargetsManager) Create(ctx context.Context, targets *model.Targets) error { s.log.Debugf("Creating targets for target group %s-%s", targets.Spec.Name, targets.Spec.Namespace) // Need to find TargetGroup ID from datastore diff --git a/pkg/deploy/lattice/targets_synthesizer.go b/pkg/deploy/lattice/targets_synthesizer.go index 869469f5..b81782ac 100644 --- a/pkg/deploy/lattice/targets_synthesizer.go +++ b/pkg/deploy/lattice/targets_synthesizer.go @@ -4,16 +4,16 @@ import ( "context" "fmt" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) func NewTargetsSynthesizer( log gwlog.Logger, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, tgManager TargetsManager, stack core.Stack, latticeDataStore *latticestore.LatticeDataStore, @@ -29,14 +29,14 @@ func NewTargetsSynthesizer( type targetsSynthesizer struct { log gwlog.Logger - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud targetsManager TargetsManager stack core.Stack latticeDataStore *latticestore.LatticeDataStore } func (t *targetsSynthesizer) Synthesize(ctx context.Context) error { - var resTargets []*latticemodel.Targets + var resTargets []*model.Targets err := t.stack.ListResources(&resTargets) if err != nil { t.log.Errorf("Failed to list targets due to %s", err) @@ -44,7 +44,7 @@ func (t *targetsSynthesizer) Synthesize(ctx context.Context) error { return t.SynthesizeTargets(ctx, resTargets) } -func (t *targetsSynthesizer) SynthesizeTargets(ctx context.Context, resTargets []*latticemodel.Targets) error { +func (t *targetsSynthesizer) SynthesizeTargets(ctx context.Context, resTargets []*model.Targets) error { for _, targets := range resTargets { err := t.targetsManager.Create(ctx, targets) if err != nil { diff --git a/pkg/deploy/stack_deployer.go b/pkg/deploy/stack_deployer.go index 9719e8be..71910c9d 100644 --- a/pkg/deploy/stack_deployer.go +++ b/pkg/deploy/stack_deployer.go @@ -7,12 +7,12 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/deploy/externaldns" "github.com/aws/aws-application-networking-k8s/pkg/deploy/lattice" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) // StackDeployer will deploy a resource stack into AWS and K8S. @@ -27,7 +27,7 @@ type StackDeployer interface { // dedicated stack for serviceNetwork/service/targetgroup type serviceNetworkStackDeployer struct { log gwlog.Logger - cloud aws.Cloud + cloud pkg_aws.Cloud k8sClient client.Client latticeServiceNetworkManager lattice.ServiceNetworkManager } @@ -37,7 +37,7 @@ type ResourceSynthesizer interface { PostSynthesize(ctx context.Context) error } -func NewServiceNetworkStackDeployer(log gwlog.Logger, cloud aws.Cloud, k8sClient client.Client) *serviceNetworkStackDeployer { +func NewServiceNetworkStackDeployer(log gwlog.Logger, cloud pkg_aws.Cloud, k8sClient client.Client) *serviceNetworkStackDeployer { return &serviceNetworkStackDeployer{ log: log, cloud: cloud, @@ -73,7 +73,7 @@ func (d *serviceNetworkStackDeployer) Deploy(ctx context.Context, stack core.Sta type LatticeServiceStackDeployer struct { log gwlog.Logger - cloud aws.Cloud + cloud pkg_aws.Cloud k8sClient client.Client latticeServiceManager lattice.ServiceManager targetGroupManager lattice.TargetGroupManager @@ -86,7 +86,7 @@ type LatticeServiceStackDeployer struct { func NewLatticeServiceStackDeploy( log gwlog.Logger, - cloud aws.Cloud, + cloud pkg_aws.Cloud, k8sClient client.Client, latticeDataStore *latticestore.LatticeDataStore, ) *LatticeServiceStackDeployer { @@ -152,7 +152,7 @@ func (d *LatticeServiceStackDeployer) Deploy(ctx context.Context, stack core.Sta type LatticeTargetGroupStackDeployer struct { log gwlog.Logger - cloud aws.Cloud + cloud pkg_aws.Cloud k8sclient client.Client targetGroupManager lattice.TargetGroupManager latticeDatastore *latticestore.LatticeDataStore @@ -161,7 +161,7 @@ type LatticeTargetGroupStackDeployer struct { // triggered by service export func NewTargetGroupStackDeploy( log gwlog.Logger, - cloud aws.Cloud, + cloud pkg_aws.Cloud, k8sClient client.Client, latticeDataStore *latticestore.LatticeDataStore, ) *LatticeTargetGroupStackDeployer { @@ -182,7 +182,7 @@ func (d *LatticeTargetGroupStackDeployer) Deploy(ctx context.Context, stack core return deploy(ctx, stack, synthesizers) } -type latticeTargetsStackDeploy struct { +type latticeTargetsStackDeployer struct { log gwlog.Logger k8sClient client.Client stack core.Stack @@ -190,21 +190,21 @@ type latticeTargetsStackDeploy struct { latticeDataStore *latticestore.LatticeDataStore } -func NewTargetsStackDeploy( +func NewTargetsStackDeployer( log gwlog.Logger, - cloud aws.Cloud, + cloud pkg_aws.Cloud, k8sClient client.Client, latticeDataStore *latticestore.LatticeDataStore, -) *latticeTargetsStackDeploy { - return &latticeTargetsStackDeploy{ +) *latticeTargetsStackDeployer { + return &latticeTargetsStackDeployer{ k8sClient: k8sClient, targetsManager: lattice.NewTargetsManager(log, cloud, latticeDataStore), latticeDataStore: latticeDataStore, } } -func (d *latticeTargetsStackDeploy) Deploy(ctx context.Context, stack core.Stack) error { - var resTargets []*latticemodel.Targets +func (d *latticeTargetsStackDeployer) Deploy(ctx context.Context, stack core.Stack) error { + var resTargets []*model.Targets d.stack = stack diff --git a/pkg/gateway/model_build_lattice_service.go b/pkg/gateway/model_build_lattice_service.go index ddd5f80c..6ff4f16e 100644 --- a/pkg/gateway/model_build_lattice_service.go +++ b/pkg/gateway/model_build_lattice_service.go @@ -12,18 +12,14 @@ import ( "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" ) -const ( - resourceIDLatticeService = "LatticeService" -) - type LatticeServiceBuilder interface { - Build(ctx context.Context, httpRoute core.Route) (core.Stack, *latticemodel.Service, error) + Build(ctx context.Context, httpRoute core.Route) (core.Stack, *model.Service, error) } type LatticeServiceModelBuilder struct { @@ -31,14 +27,14 @@ type LatticeServiceModelBuilder struct { client client.Client defaultTags map[string]string datastore *latticestore.LatticeDataStore - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } func NewLatticeServiceBuilder( log gwlog.Logger, client client.Client, datastore *latticestore.LatticeDataStore, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, ) *LatticeServiceModelBuilder { return &LatticeServiceModelBuilder{ log: log, @@ -51,7 +47,7 @@ func NewLatticeServiceBuilder( func (b *LatticeServiceModelBuilder) Build( ctx context.Context, route core.Route, -) (core.Stack, *latticemodel.Service, error) { +) (core.Stack, *model.Service, error) { stack := core.NewDefaultStack(core.StackID(k8s.NamespacedName(route.K8sObject()))) task := &latticeServiceModelBuildTask{ @@ -59,7 +55,7 @@ func (b *LatticeServiceModelBuilder) Build( route: route, stack: stack, client: b.client, - tgByResID: make(map[string]*latticemodel.TargetGroup), + tgByResID: make(map[string]*model.TargetGroup), datastore: b.datastore, } @@ -76,13 +72,11 @@ func (t *latticeServiceModelBuildTask) run(ctx context.Context) error { } func (t *latticeServiceModelBuildTask) buildModel(ctx context.Context) error { - err := t.buildLatticeService(ctx) - if err != nil { + if err := t.buildLatticeService(ctx); err != nil { return fmt.Errorf("failed to build lattice service due to %w", err) } - _, err = t.buildTargetGroup(ctx, t.client) - if err != nil { + if err := t.buildTargetGroupsForRoute(ctx, t.client); err != nil { return fmt.Errorf("failed to build target group due to %w", err) } @@ -91,19 +85,15 @@ func (t *latticeServiceModelBuildTask) buildModel(ctx context.Context) error { return nil } - err = t.buildTargets(ctx) - if err != nil { + if err := t.buildTargetsForRoute(ctx); err != nil { t.log.Debugf("failed to build targets due to %s", err) } - // only build listener when it is NOT delete case - err = t.buildListener(ctx) - if err != nil { + if err := t.buildListeners(ctx); err != nil { return fmt.Errorf("failed to build listener due to %w", err) } - err = t.buildRules(ctx) - if err != nil { + if err := t.buildRules(ctx); err != nil { return fmt.Errorf("failed to build rule due to %w", err) } @@ -116,11 +106,10 @@ func (t *latticeServiceModelBuildTask) buildLatticeService(ctx context.Context) routeType = core.GrpcRouteType } - spec := latticemodel.ServiceSpec{ + spec := model.ServiceSpec{ Name: t.route.Name(), Namespace: t.route.Namespace(), RouteType: routeType, - //ServiceNetworkNames: string(t.route.Spec().ParentRefs()[0].Name), } for _, parentRef := range t.route.Spec().ParentRefs() { @@ -151,7 +140,7 @@ func (t *latticeServiceModelBuildTask) buildLatticeService(ctx context.Context) serviceResourceName := fmt.Sprintf("%s-%s", t.route.Name(), t.route.Namespace()) - t.latticeService = latticemodel.NewLatticeService(t.stack, serviceResourceName, spec) + t.latticeService = model.NewLatticeService(t.stack, serviceResourceName, spec) return nil } @@ -160,11 +149,11 @@ type latticeServiceModelBuildTask struct { log gwlog.Logger route core.Route client client.Client - latticeService *latticemodel.Service - tgByResID map[string]*latticemodel.TargetGroup - listenerByResID map[string]*latticemodel.Listener - rulesByResID map[string]*latticemodel.Rule + latticeService *model.Service + tgByResID map[string]*model.TargetGroup + listenerByResID map[string]*model.Listener + rulesByResID map[string]*model.Rule stack core.Stack datastore *latticestore.LatticeDataStore - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } diff --git a/pkg/gateway/model_build_listener.go b/pkg/gateway/model_build_listener.go index ed6c8291..40a780b1 100644 --- a/pkg/gateway/model_build_listener.go +++ b/pkg/gateway/model_build_listener.go @@ -5,23 +5,21 @@ import ( "errors" "fmt" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "k8s.io/apimachinery/pkg/types" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) const ( - resourceIDListenerConfig = "ListenerConfig" - awsCustomCertARN = "application-networking.k8s.aws/certificate-arn" ) func (t *latticeServiceModelBuildTask) extractListenerInfo( ctx context.Context, - parentRef gateway_api.ParentReference, + parentRef gwv1beta1.ParentReference, ) (int64, string, string, error) { - protocol := gateway_api.HTTPProtocolType + protocol := gwv1beta1.HTTPProtocolType if parentRef.SectionName != nil { t.log.Debugf("Listener parentRef SectionName is %s", *parentRef.SectionName) } @@ -33,7 +31,7 @@ func (t *latticeServiceModelBuildTask) extractListenerInfo( } var listenerPort = 0 - gw := &gateway_api.Gateway{} + gw := &gwv1beta1.Gateway{} gwName := types.NamespacedName{ Namespace: gwNamespace, Name: string(t.route.Spec().ParentRefs()[0].Name), @@ -54,7 +52,7 @@ func (t *latticeServiceModelBuildTask) extractListenerInfo( found = true if section.TLS != nil { - if section.TLS.Mode != nil && *section.TLS.Mode == gateway_api.TLSModeTerminate { + if section.TLS.Mode != nil && *section.TLS.Mode == gwv1beta1.TLSModeTerminate { curCertARN, ok := section.TLS.Options[awsCustomCertARN] if ok { t.log.Debugf("Found certification %s under section %s", curCertARN, section.Name) @@ -81,7 +79,7 @@ func (t *latticeServiceModelBuildTask) extractListenerInfo( } -func (t *latticeServiceModelBuildTask) buildListener(ctx context.Context) error { +func (t *latticeServiceModelBuildTask) buildListeners(ctx context.Context) error { for _, parentRef := range t.route.Spec().ParentRefs() { if parentRef.Name != t.route.Spec().ParentRefs()[0].Name { // when a service is associate to multiple service network(s), all listener config MUST be same @@ -114,36 +112,21 @@ func (t *latticeServiceModelBuildTask) buildListener(ctx context.Context) error } backendRef := rule.BackendRefs()[0] + targetGroupName := string(backendRef.Name()) - var isImport = false - var targetGroupName = "" var targetGroupNamespace = t.route.Namespace() - - if string(*backendRef.Kind()) == "Service" { - if backendRef.Namespace() != nil { - targetGroupNamespace = string(*backendRef.Namespace()) - } - targetGroupName = string(backendRef.Name()) - isImport = false - } - - if string(*backendRef.Kind()) == "ServiceImport" { - isImport = true - if backendRef.Namespace() != nil { - targetGroupNamespace = string(*backendRef.Namespace()) - } - targetGroupName = string(backendRef.Name()) + if backendRef.Namespace() != nil { + targetGroupNamespace = string(*backendRef.Namespace()) } - action := latticemodel.DefaultAction{ - Is_Import: isImport, + action := model.DefaultAction{ BackendServiceName: targetGroupName, BackendServiceNamespace: targetGroupNamespace, } listenerResourceName := fmt.Sprintf("%s-%s-%d-%s", t.route.Name(), t.route.Namespace(), port, protocol) t.log.Infof("Creating new listener with name %s", listenerResourceName) - latticemodel.NewListener(t.stack, listenerResourceName, port, protocol, t.route.Name(), t.route.Namespace(), action) + model.NewListener(t.stack, listenerResourceName, port, protocol, t.route.Name(), t.route.Namespace(), action) } return nil diff --git a/pkg/gateway/model_build_listener_test.go b/pkg/gateway/model_build_listener_test.go index 9cf54544..7de03ab1 100644 --- a/pkg/gateway/model_build_listener_test.go +++ b/pkg/gateway/model_build_listener_test.go @@ -390,15 +390,15 @@ func Test_ListenerModelBuild(t *testing.T) { service := latticemodel.Service{} task.latticeService = &service - err := task.buildListener(ctx) + err := task.buildListeners(ctx) - fmt.Printf("task.buildListener err: %v \n", err) + fmt.Printf("task.buildListeners err: %v \n", err) if !tt.wantErrIsNil { // TODO why following is failing???? //assert.Equal(t, err!=nil, true) //assert.Error(t, err) - fmt.Printf("task.buildListener tt : %v err: %v %v\n", tt.name, err, err != nil) + fmt.Printf("task.buildListeners tt : %v err: %v %v\n", tt.name, err, err != nil) continue } else { assert.NoError(t, err) @@ -424,12 +424,6 @@ func Test_ListenerModelBuild(t *testing.T) { assert.Equal(t, resListener[0].Spec.DefaultAction.BackendServiceNamespace, tt.route.Namespace()) } - if *tt.route.Spec().Rules()[0].BackendRefs()[0].Kind() == "Service" { - assert.Equal(t, resListener[0].Spec.DefaultAction.Is_Import, false) - } else { - assert.Equal(t, resListener[0].Spec.DefaultAction.Is_Import, true) - } - if tt.tlsTerminate && !tt.noTLSOption && !tt.wrongTLSOption { assert.Equal(t, task.latticeService.Spec.CustomerCertARN, tt.certARN) } else { diff --git a/pkg/gateway/model_build_rule.go b/pkg/gateway/model_build_rule.go index 204e2a9b..7e055a52 100644 --- a/pkg/gateway/model_build_rule.go +++ b/pkg/gateway/model_build_rule.go @@ -9,28 +9,21 @@ import ( "github.com/aws/aws-sdk-go/aws" - gateway_api_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - gateway_api_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/aws/aws-sdk-go/service/vpclattice" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) const ( - resourceIDRuleConfig = "RuleConfig" - // error code LATTICE_NO_SUPPORT_FOR_MULTIPLE_MATCHES = "LATTICE_NO_SUPPORT_FOR_MULTIPLE_MATCHES" - - LATTICE_EXCEED_MAX_HEADER_MATCHES = "LATTICE_EXCEED_MAX_HEADER_MATCHES" - - LATTICE_UNSUPPORTED_MATCH_TYPE = "LATTICE_UNSUPPORTED_MATCH_TYPE" - - LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE = "LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE" - - LATTICE_UNSUPPORTED_PATH_MATCH_TYPE = "LATTICE_UNSUPPORTED_PATH_MATCH_TYPE" - - LATTICE_MAX_HEADER_MATCHES = 5 + LATTICE_EXCEED_MAX_HEADER_MATCHES = "LATTICE_EXCEED_MAX_HEADER_MATCHES" + LATTICE_UNSUPPORTED_MATCH_TYPE = "LATTICE_UNSUPPORTED_MATCH_TYPE" + LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE = "LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE" + LATTICE_UNSUPPORTED_PATH_MATCH_TYPE = "LATTICE_UNSUPPORTED_PATH_MATCH_TYPE" + LATTICE_MAX_HEADER_MATCHES = 5 ) func (t *latticeServiceModelBuildTask) buildRules(ctx context.Context) error { @@ -49,7 +42,7 @@ func (t *latticeServiceModelBuildTask) buildRules(ctx context.Context) error { } for _, rule := range t.route.Spec().Rules() { - var ruleSpec latticemodel.RuleSpec + var ruleSpec model.RuleSpec if len(rule.Matches()) > 1 { // only support 1 match today @@ -66,152 +59,28 @@ func (t *latticeServiceModelBuildTask) buildRules(ctx context.Context) error { switch m := match.(type) { case *core.HTTPRouteMatch: - if m.Path() != nil && m.Path().Type != nil { - t.log.Debugf("Examining pathmatch type %s value %s for for httproute %s-%s ", - *m.Path().Type, *m.Path().Value, t.route.Name(), t.route.Namespace()) - - switch *m.Path().Type { - case gateway_api_v1beta1.PathMatchExact: - t.log.Debugf("Using PathMatchExact for httproute %s-%s ", - t.route.Name(), t.route.Namespace()) - ruleSpec.PathMatchExact = true - - case gateway_api_v1beta1.PathMatchPathPrefix: - t.log.Debugf("Using PathMatchPathPrefix for httproute %s-%s ", - t.route.Name(), t.route.Namespace()) - ruleSpec.PathMatchPrefix = true - default: - t.log.Debugf("Unsupported path match type %s for httproute %s-%s", - *m.Path().Type, t.route.Name(), t.route.Namespace()) - return errors.New(LATTICE_UNSUPPORTED_PATH_MATCH_TYPE) - } - ruleSpec.PathMatchValue = *m.Path().Value - } - - // method based match - if m.Method() != nil { - t.log.Infof("Examining http method %s for httproute %s-%s", - *m.Method(), t.route.Name(), t.route.Namespace()) - - ruleSpec.Method = string(*m.Method()) - } - - // controller does not support query matcher type today - if m.QueryParams() != nil { - t.log.Infof("Unsupported match type for httproute %s, namespace %s", - t.route.Name(), t.route.Namespace()) - return errors.New(LATTICE_UNSUPPORTED_MATCH_TYPE) + if err := t.updateRuleSpecForHttpRoute(m, &ruleSpec); err != nil { + return err } case *core.GRPCRouteMatch: - t.log.Debugf("Building rule with GRPCRouteMatch, %+v", *m) - ruleSpec.Method = string(gateway_api_v1beta1.HTTPMethodPost) - method := m.Method() - // VPC Lattice doesn't support suffix/regex matching, so we can't support method match without service - if method.Service == nil && method.Method != nil { - return fmt.Errorf("cannot create GRPCRouteMatch for nil service and non-nil method") - } - switch *method.Type { - case gateway_api_v1alpha2.GRPCMethodMatchExact: - if method.Service == nil { - t.log.Debugf("Match all paths due to nil service and nil method") - ruleSpec.PathMatchPrefix = true - ruleSpec.PathMatchValue = "/" - } else if method.Method == nil { - t.log.Debugf("Match by specific gRPC service %s, regardless of method", *method.Service) - ruleSpec.PathMatchPrefix = true - ruleSpec.PathMatchValue = fmt.Sprintf("/%s/", *method.Service) - } else { - t.log.Debugf("Match by specific gRPC service %s and method %s", *method.Service, *method.Method) - ruleSpec.PathMatchExact = true - ruleSpec.PathMatchValue = fmt.Sprintf("/%s/%s", *method.Service, *method.Method) - } - default: - return fmt.Errorf("unsupported gRPC method match type %s", *method.Type) + if err := t.updateRuleSpecForGrpcRoute(m, &ruleSpec); err != nil { + return err } default: return fmt.Errorf("unsupported rule match: %T", m) } - // header based match - // today, only support EXACT match - if match.Headers() != nil { - if len(match.Headers()) > LATTICE_MAX_HEADER_MATCHES { - return errors.New(LATTICE_EXCEED_MAX_HEADER_MATCHES) - } - - ruleSpec.NumOfHeaderMatches = len(match.Headers()) - - t.log.Debugf("Examining match.Headers for route %s-%s", t.route.Name(), t.route.Namespace()) - - for i, header := range match.Headers() { - t.log.Debugf("Examining match.Header: i = %d header.Type %s", i, *header.Type()) - if header.Type() != nil && *header.Type() != gateway_api_v1beta1.HeaderMatchExact { - t.log.Debugf("Unsupported header matchtype %s for httproute %s-%s", - *header.Type(), t.route.Name(), t.route.Namespace()) - return errors.New(LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE) - } - - matchType := vpclattice.HeaderMatchType{ - Exact: aws.String(header.Value()), - } - ruleSpec.MatchedHeaders[i].Match = &matchType - headerName := header.Name() - ruleSpec.MatchedHeaders[i].Name = &headerName - } + if err := t.updateRuleSpecWithHeaderMatches(match, &ruleSpec); err != nil { + return err } - var tgList []*latticemodel.RuleTargetGroup - - for _, backendRef := range rule.BackendRefs() { - ruleTG := latticemodel.RuleTargetGroup{} - if string(*backendRef.Kind()) == "Service" { - namespace := t.route.Namespace() - if backendRef.Namespace() != nil { - namespace = string(*backendRef.Namespace()) - } - ruleTG.Name = string(backendRef.Name()) - ruleTG.Namespace = namespace - ruleTG.RouteName = t.route.Name() - ruleTG.IsServiceImport = false - if backendRef.Weight() != nil { - ruleTG.Weight = int64(*backendRef.Weight()) - } - } - - if string(*backendRef.Kind()) == "ServiceImport" { - // TODO - /* I think this need to be done at policy manager API call - tg, err := t.datastore.GetTargetGroup(string(backendRef.Name()), - "default", true) // isServiceImport==true - if err != nil { - t.log.Infof("ServiceImport %s Not found, continue \n", - string(backendRef.Name())) - continue - - } - */ - ruleTG.Name = string(backendRef.Name()) - ruleTG.Namespace = t.route.Namespace() - if backendRef.Namespace() != nil { - ruleTG.Namespace = string(*backendRef.Namespace()) - } - // the routeName for serviceimport is always "" - ruleTG.RouteName = "" - ruleTG.IsServiceImport = true - - if backendRef.Weight() != nil { - ruleTG.Weight = int64(*backendRef.Weight()) - } - } - - tgList = append(tgList, &ruleTG) - } + tgList := t.getTargetGroupsForRuleAction(rule) ruleIDName := fmt.Sprintf("rule-%d", ruleID) - ruleAction := latticemodel.RuleAction{ + ruleAction := model.RuleAction{ TargetGroups: tgList, } - latticemodel.NewRule(t.stack, ruleIDName, t.route.Name(), t.route.Namespace(), port, + model.NewRule(t.stack, ruleIDName, t.route.Name(), t.route.Namespace(), port, protocol, ruleAction, ruleSpec) ruleID++ } @@ -219,3 +88,142 @@ func (t *latticeServiceModelBuildTask) buildRules(ctx context.Context) error { return nil } + +func (t *latticeServiceModelBuildTask) updateRuleSpecForHttpRoute(m *core.HTTPRouteMatch, ruleSpec *model.RuleSpec) error { + if m.Path() != nil && m.Path().Type != nil { + t.log.Debugf("Examining pathmatch type %s value %s for for httproute %s-%s ", + *m.Path().Type, *m.Path().Value, t.route.Name(), t.route.Namespace()) + + switch *m.Path().Type { + case gwv1beta1.PathMatchExact: + t.log.Debugf("Using PathMatchExact for httproute %s-%s ", + t.route.Name(), t.route.Namespace()) + ruleSpec.PathMatchExact = true + + case gwv1beta1.PathMatchPathPrefix: + t.log.Debugf("Using PathMatchPathPrefix for httproute %s-%s ", + t.route.Name(), t.route.Namespace()) + ruleSpec.PathMatchPrefix = true + default: + t.log.Debugf("Unsupported path match type %s for httproute %s-%s", + *m.Path().Type, t.route.Name(), t.route.Namespace()) + return errors.New(LATTICE_UNSUPPORTED_PATH_MATCH_TYPE) + } + ruleSpec.PathMatchValue = *m.Path().Value + } + + // method based match + if m.Method() != nil { + t.log.Infof("Examining http method %s for httproute %s-%s", + *m.Method(), t.route.Name(), t.route.Namespace()) + + ruleSpec.Method = string(*m.Method()) + } + + // controller does not support query matcher type today + if m.QueryParams() != nil { + t.log.Infof("Unsupported match type for httproute %s, namespace %s", + t.route.Name(), t.route.Namespace()) + return errors.New(LATTICE_UNSUPPORTED_MATCH_TYPE) + } + return nil +} + +func (t *latticeServiceModelBuildTask) updateRuleSpecForGrpcRoute(m *core.GRPCRouteMatch, ruleSpec *model.RuleSpec) error { + t.log.Debugf("Building rule with GRPCRouteMatch, %+v", *m) + ruleSpec.Method = string(gwv1beta1.HTTPMethodPost) + method := m.Method() + // VPC Lattice doesn't support suffix/regex matching, so we can't support method match without service + if method.Service == nil && method.Method != nil { + return fmt.Errorf("cannot create GRPCRouteMatch for nil service and non-nil method") + } + switch *method.Type { + case gwv1alpha2.GRPCMethodMatchExact: + if method.Service == nil { + t.log.Debugf("Match all paths due to nil service and nil method") + ruleSpec.PathMatchPrefix = true + ruleSpec.PathMatchValue = "/" + } else if method.Method == nil { + t.log.Debugf("Match by specific gRPC service %s, regardless of method", *method.Service) + ruleSpec.PathMatchPrefix = true + ruleSpec.PathMatchValue = fmt.Sprintf("/%s/", *method.Service) + } else { + t.log.Debugf("Match by specific gRPC service %s and method %s", *method.Service, *method.Method) + ruleSpec.PathMatchExact = true + ruleSpec.PathMatchValue = fmt.Sprintf("/%s/%s", *method.Service, *method.Method) + } + default: + return fmt.Errorf("unsupported gRPC method match type %s", *method.Type) + } + return nil +} + +func (t *latticeServiceModelBuildTask) updateRuleSpecWithHeaderMatches(match core.RouteMatch, ruleSpec *model.RuleSpec) error { + if match.Headers() == nil { + return nil + } + + if len(match.Headers()) > LATTICE_MAX_HEADER_MATCHES { + return errors.New(LATTICE_EXCEED_MAX_HEADER_MATCHES) + } + + ruleSpec.NumOfHeaderMatches = len(match.Headers()) + + t.log.Debugf("Examining match headers for route %s-%s", t.route.Name(), t.route.Namespace()) + + for i, header := range match.Headers() { + t.log.Debugf("Examining match.Header: i = %d header.Type %s", i, *header.Type()) + if header.Type() != nil && *header.Type() != gwv1beta1.HeaderMatchExact { + t.log.Debugf("Unsupported header matchtype %s for httproute %s-%s", + *header.Type(), t.route.Name(), t.route.Namespace()) + return errors.New(LATTICE_UNSUPPORTED_HEADER_MATCH_TYPE) + } + + matchType := vpclattice.HeaderMatchType{ + Exact: aws.String(header.Value()), + } + ruleSpec.MatchedHeaders[i].Match = &matchType + headerName := header.Name() + ruleSpec.MatchedHeaders[i].Name = &headerName + } + return nil +} + +func (t *latticeServiceModelBuildTask) getTargetGroupsForRuleAction(rule core.RouteRule) []*model.RuleTargetGroup { + var tgList []*model.RuleTargetGroup + + for _, backendRef := range rule.BackendRefs() { + ruleTG := model.RuleTargetGroup{} + if string(*backendRef.Kind()) == "Service" { + namespace := t.route.Namespace() + if backendRef.Namespace() != nil { + namespace = string(*backendRef.Namespace()) + } + ruleTG.Name = string(backendRef.Name()) + ruleTG.Namespace = namespace + ruleTG.RouteName = t.route.Name() + ruleTG.IsServiceImport = false + if backendRef.Weight() != nil { + ruleTG.Weight = int64(*backendRef.Weight()) + } + } + + if string(*backendRef.Kind()) == "ServiceImport" { + ruleTG.Name = string(backendRef.Name()) + ruleTG.Namespace = t.route.Namespace() + if backendRef.Namespace() != nil { + ruleTG.Namespace = string(*backendRef.Namespace()) + } + // the routeName for serviceimport is always "" + ruleTG.RouteName = "" + ruleTG.IsServiceImport = true + + if backendRef.Weight() != nil { + ruleTG.Weight = int64(*backendRef.Weight()) + } + } + + tgList = append(tgList, &ruleTG) + } + return tgList +} diff --git a/pkg/gateway/model_build_servicenetwork.go b/pkg/gateway/model_build_servicenetwork.go index 242201ea..cc18ed3e 100644 --- a/pkg/gateway/model_build_servicenetwork.go +++ b/pkg/gateway/model_build_servicenetwork.go @@ -7,23 +7,20 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" - "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) const ( ResourceIDServiceNetwork = "ServiceNetwork" LatticeVPCAssociationAnnotation = "application-networking.k8s.aws/lattice-vpc-association" - ModelBuiltError = "Failed to build model" ) -// ModelBuilder builds the model stack for the mesh resource. type ServiceNetworkModelBuilder interface { - // Build model stack for service - Build(ctx context.Context, gw *gateway_api.Gateway) (core.Stack, *latticemodel.ServiceNetwork, error) + Build(ctx context.Context, gw *gateway_api.Gateway) (core.Stack, *model.ServiceNetwork, error) } type serviceNetworkModelBuilder struct { @@ -34,9 +31,9 @@ type serviceNetworkModelBuilder struct { func NewServiceNetworkModelBuilder(client client.Client) *serviceNetworkModelBuilder { return &serviceNetworkModelBuilder{client: client} } -func (b *serviceNetworkModelBuilder) Build(ctx context.Context, gw *gateway_api.Gateway) (core.Stack, *latticemodel.ServiceNetwork, error) { +func (b *serviceNetworkModelBuilder) Build(ctx context.Context, gw *gateway_api.Gateway) (core.Stack, *model.ServiceNetwork, error) { stack := core.NewDefaultStack(core.StackID(k8s.NamespacedName(gw))) - vpcAssociationPolicy, err := GetAttachedPolicy(ctx, b.client, k8s.NamespacedName(gw), &v1alpha1.VpcAssociationPolicy{}) + vpcAssociationPolicy, err := GetAttachedPolicy(ctx, b.client, k8s.NamespacedName(gw), &anv1alpha1.VpcAssociationPolicy{}) if err != nil { return nil, nil, err } @@ -69,7 +66,7 @@ func (t *serviceNetworkModelBuildTask) buildModel(ctx context.Context) error { } func (t *serviceNetworkModelBuildTask) buildServiceNetwork(ctx context.Context) error { - spec := latticemodel.ServiceNetworkSpec{ + spec := model.ServiceNetworkSpec{ Name: t.gateway.Name, Namespace: t.gateway.Namespace, Account: config.AccountID, @@ -101,20 +98,20 @@ func (t *serviceNetworkModelBuildTask) buildServiceNetwork(ctx context.Context) spec.IsDeleted = false } - t.serviceNetwork = latticemodel.NewServiceNetwork(t.stack, ResourceIDServiceNetwork, spec) + t.serviceNetwork = model.NewServiceNetwork(t.stack, ResourceIDServiceNetwork, spec) return nil } type serviceNetworkModelBuildTask struct { gateway *gateway_api.Gateway - vpcAssociationPolicy *v1alpha1.VpcAssociationPolicy - serviceNetwork *latticemodel.ServiceNetwork + vpcAssociationPolicy *anv1alpha1.VpcAssociationPolicy + serviceNetwork *model.ServiceNetwork stack core.Stack } -func securityGroupIdsToStringPointersSlice(sgIds []v1alpha1.SecurityGroupId) []*string { +func securityGroupIdsToStringPointersSlice(sgIds []anv1alpha1.SecurityGroupId) []*string { ret := make([]*string, 0) for _, sgId := range sgIds { sgIdStr := string(sgId) diff --git a/pkg/gateway/model_build_targetgroup.go b/pkg/gateway/model_build_targetgroup.go index 399cb544..154f3636 100644 --- a/pkg/gateway/model_build_targetgroup.go +++ b/pkg/gateway/model_build_targetgroup.go @@ -11,44 +11,39 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - mcs_api "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" "github.com/aws/aws-sdk-go/service/vpclattice" - "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/config" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" ) -const ( - resourceIDTargetGroup = "TargetGroup" -) - -type TargetGroupModelBuilder interface { - Build(ctx context.Context, srvExport *mcs_api.ServiceExport) (core.Stack, *latticemodel.TargetGroup, error) +type SvcExportTargetGroupModelBuilder interface { + Build(ctx context.Context, srvExport *mcsv1alpha1.ServiceExport) (core.Stack, *model.TargetGroup, error) } -type TargetGroupBuilder struct { +type SvcExportTargetGroupBuilder struct { log gwlog.Logger client client.Client - serviceExport *mcs_api.ServiceExport + serviceExport *mcsv1alpha1.ServiceExport datastore *latticestore.LatticeDataStore - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud defaultTags map[string]string } -// triggered from serviceexport -func NewTargetGroupBuilder( +func NewSvcExportTargetGroupBuilder( log gwlog.Logger, client client.Client, datastore *latticestore.LatticeDataStore, - cloud lattice_aws.Cloud, -) *TargetGroupBuilder { - return &TargetGroupBuilder{ + cloud pkg_aws.Cloud, +) *SvcExportTargetGroupBuilder { + return &SvcExportTargetGroupBuilder{ log: log, client: client, datastore: datastore, @@ -56,29 +51,28 @@ func NewTargetGroupBuilder( } } -type targetGroupModelBuildTask struct { +type svcExportTargetGroupModelBuildTask struct { log gwlog.Logger client client.Client - serviceExport *mcs_api.ServiceExport - targetGroup *latticemodel.TargetGroup - tgByResID map[string]*latticemodel.TargetGroup + serviceExport *mcsv1alpha1.ServiceExport + targetGroup *model.TargetGroup + tgByResID map[string]*model.TargetGroup stack core.Stack datastore *latticestore.LatticeDataStore - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } -// for serviceexport -func (b *TargetGroupBuilder) Build( +func (b *SvcExportTargetGroupBuilder) Build( ctx context.Context, - srvExport *mcs_api.ServiceExport, -) (core.Stack, *latticemodel.TargetGroup, error) { + srvExport *mcsv1alpha1.ServiceExport, +) (core.Stack, *model.TargetGroup, error) { stack := core.NewDefaultStack(core.StackID(k8s.NamespacedName(srvExport))) - task := &targetGroupModelBuildTask{ + task := &svcExportTargetGroupModelBuildTask{ log: b.log, serviceExport: srvExport, stack: stack, - tgByResID: make(map[string]*latticemodel.TargetGroup), + tgByResID: make(map[string]*model.TargetGroup), datastore: b.datastore, cloud: b.cloud, client: b.client, @@ -91,22 +85,7 @@ func (b *TargetGroupBuilder) Build( return task.stack, task.targetGroup, nil } -// for serviceexport -func (t *targetGroupModelBuildTask) run(ctx context.Context) error { - /* - if !t.serviceExport.DeletionTimestamp.IsZero() { - // TODO handle delete - return nil - } - */ - - err := t.buildModel(ctx) - - return err -} - -// for serviceexport -func (t *targetGroupModelBuildTask) buildModel(ctx context.Context) error { +func (t *svcExportTargetGroupModelBuildTask) run(ctx context.Context) error { err := t.BuildTargetGroupForServiceExport(ctx) if err != nil { return fmt.Errorf("failed to build target group for service export %s-%s due to %w", @@ -122,8 +101,7 @@ func (t *targetGroupModelBuildTask) buildModel(ctx context.Context) error { return nil } -// triggered from service exports/targetgroups -func (t *targetGroupModelBuildTask) BuildTargets(ctx context.Context) error { +func (t *svcExportTargetGroupModelBuildTask) BuildTargets(ctx context.Context) error { targetTask := &latticeTargetsModelBuildTask{ log: t.log, client: t.client, @@ -141,48 +119,9 @@ func (t *targetGroupModelBuildTask) BuildTargets(ctx context.Context) error { return nil } -// Triggered from route/service/targetgroup -func (t *latticeServiceModelBuildTask) buildTargets(ctx context.Context) error { - for _, rule := range t.route.Spec().Rules() { - for _, backendRef := range rule.BackendRefs() { - if string(*backendRef.Kind()) == "ServiceImport" { - continue - } - - backendNamespace := t.route.Namespace() - if backendRef.Namespace() != nil { - backendNamespace = string(*backendRef.Namespace()) - } - - var port int32 - if backendRef.Port() != nil { - port = int32(*backendRef.Port()) - } - - targetTask := &latticeTargetsModelBuildTask{ - log: t.log, - client: t.client, - tgName: string(backendRef.Name()), - tgNamespace: backendNamespace, - routeName: t.route.Name(), - backendRefPort: port, - stack: t.stack, - datastore: t.datastore, - route: t.route, - } - - err := targetTask.buildLatticeTargets(ctx) - if err != nil { - return err - } - } - } - return nil -} - -func (t *targetGroupModelBuildTask) BuildTargetGroupForServiceExport(ctx context.Context) error { +func (t *svcExportTargetGroupModelBuildTask) BuildTargetGroupForServiceExport(ctx context.Context) error { tgName := latticestore.TargetGroupName(t.serviceExport.Name, t.serviceExport.Namespace) - var tg *latticemodel.TargetGroup + var tg *model.TargetGroup var err error if t.serviceExport.DeletionTimestamp.IsZero() { tg, err = t.buildTargetGroupForServiceExportCreation(ctx, tgName) @@ -199,7 +138,7 @@ func (t *targetGroupModelBuildTask) BuildTargetGroupForServiceExport(ctx context return nil } -func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportCreation(ctx context.Context, targetGroupName string) (*latticemodel.TargetGroup, error) { +func (t *svcExportTargetGroupModelBuildTask) buildTargetGroupForServiceExportCreation(ctx context.Context, targetGroupName string) (*model.TargetGroup, error) { svc := &corev1.Service{} if err := t.client.Get(ctx, k8s.NamespacedName(t.serviceExport), svc); err != nil { t.datastore.SetTargetGroupByServiceExport(targetGroupName, false, false) @@ -211,7 +150,7 @@ func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportCreation(ctx return nil, err } - tgp, err := GetAttachedPolicy(ctx, t.client, k8s.NamespacedName(t.serviceExport), &v1alpha1.TargetGroupPolicy{}) + tgp, err := GetAttachedPolicy(ctx, t.client, k8s.NamespacedName(t.serviceExport), &anv1alpha1.TargetGroupPolicy{}) if err != nil { return nil, err } @@ -229,10 +168,10 @@ func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportCreation(ctx healthCheckConfig = parseHealthCheckConfig(tgp) } - stackTG := latticemodel.NewTargetGroup(t.stack, targetGroupName, latticemodel.TargetGroupSpec{ + stackTG := model.NewTargetGroup(t.stack, targetGroupName, model.TargetGroupSpec{ Name: targetGroupName, - Type: latticemodel.TargetGroupTypeIP, - Config: latticemodel.TargetGroupConfig{ + Type: model.TargetGroupTypeIP, + Config: model.TargetGroupConfig{ VpcID: config.VpcID, // Fill in default HTTP port as we are using target port anyway. Port: 80, @@ -262,8 +201,8 @@ func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportCreation(ctx return stackTG, nil } -func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportDeletion(ctx context.Context, targetGroupName string) (*latticemodel.TargetGroup, error) { - stackTG := latticemodel.NewTargetGroup(t.stack, targetGroupName, latticemodel.TargetGroupSpec{ +func (t *svcExportTargetGroupModelBuildTask) buildTargetGroupForServiceExportDeletion(ctx context.Context, targetGroupName string) (*model.TargetGroup, error) { + stackTG := model.NewTargetGroup(t.stack, targetGroupName, model.TargetGroupSpec{ Name: targetGroupName, LatticeID: "", IsDeleted: true, @@ -286,16 +225,16 @@ func (t *targetGroupModelBuildTask) buildTargetGroupForServiceExportDeletion(ctx } // Build target group for backend service ref used in Route -func (t *latticeServiceModelBuildTask) buildTargetGroup( +func (t *latticeServiceModelBuildTask) buildTargetGroupsForRoute( ctx context.Context, client client.Client, -) (*latticemodel.TargetGroup, error) { +) error { for _, rule := range t.route.Spec().Rules() { for _, backendRef := range rule.BackendRefs() { tgName := t.buildTargetGroupName(ctx, backendRef) tgSpec, err := t.buildTargetGroupSpec(ctx, client, backendRef) if err != nil { - return nil, fmt.Errorf("buildTargetGroupSpec err %w", err) + return fmt.Errorf("buildTargetGroupSpec err %w", err) } // add targetgroup to localcache for service reconcile to reference @@ -307,21 +246,58 @@ func (t *latticeServiceModelBuildTask) buildTargetGroup( } if t.route.DeletionTimestamp().IsZero() { - // to add t.datastore.SetTargetGroupByBackendRef(tgName, t.route.Name(), tgSpec.Config.IsServiceImport, true) } else { - // to delete t.datastore.SetTargetGroupByBackendRef(tgName, t.route.Name(), tgSpec.Config.IsServiceImport, false) dsTG, _ := t.datastore.GetTargetGroup(tgName, t.route.Name(), tgSpec.Config.IsServiceImport) tgSpec.IsDeleted = true tgSpec.LatticeID = dsTG.ID } - tg := latticemodel.NewTargetGroup(t.stack, tgName, tgSpec) + tg := model.NewTargetGroup(t.stack, tgName, tgSpec) t.tgByResID[tgName] = tg } } - return nil, nil + return nil +} + +// Triggered from route/service/targetgroup +func (t *latticeServiceModelBuildTask) buildTargetsForRoute(ctx context.Context) error { + for _, rule := range t.route.Spec().Rules() { + for _, backendRef := range rule.BackendRefs() { + if string(*backendRef.Kind()) == "ServiceImport" { + continue + } + + backendNamespace := t.route.Namespace() + if backendRef.Namespace() != nil { + backendNamespace = string(*backendRef.Namespace()) + } + + var port int32 + if backendRef.Port() != nil { + port = int32(*backendRef.Port()) + } + + targetTask := &latticeTargetsModelBuildTask{ + log: t.log, + client: t.client, + tgName: string(backendRef.Name()), + tgNamespace: backendNamespace, + routeName: t.route.Name(), + backendRefPort: port, + stack: t.stack, + datastore: t.datastore, + route: t.route, + } + + err := targetTask.buildLatticeTargets(ctx) + if err != nil { + return err + } + } + } + return nil } // Now, Only k8sService and serviceImport creation deletion use this function to build TargetGroupSpec, serviceExport does not use this function to create TargetGroupSpec @@ -329,7 +305,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( ctx context.Context, client client.Client, backendRef core.BackendRef, -) (latticemodel.TargetGroupSpec, error) { +) (model.TargetGroupSpec, error) { var namespace string if backendRef.Namespace() != nil { @@ -360,7 +336,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( Namespace: namespace, Name: string(backendRef.Name()), } - serviceImport := &mcs_api.ServiceImport{} + serviceImport := &mcsv1alpha1.ServiceImport{} if err := client.Get(context.TODO(), namespaceName, serviceImport); err == nil { t.log.Debugf("Building target group spec using service import %s", namespaceName) @@ -372,7 +348,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( //Return error for creation request only. //For ServiceImport deletion request, we should go ahead to build TargetGroupSpec model, //although the targetGroupSynthesizer could skip TargetGroup deletion triggered by ServiceImport deletion - return latticemodel.TargetGroupSpec{}, err + return model.TargetGroupSpec{}, err } } @@ -394,7 +370,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( if !isDeleted { //Return error for creation request only, //For k8sService deletion request, we should go ahead to build TargetGroupSpec model - return latticemodel.TargetGroupSpec{}, err + return model.TargetGroupSpec{}, err } } @@ -404,7 +380,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( // Ignore error for creation request if !isDeleted && err != nil { - return latticemodel.TargetGroupSpec{}, err + return model.TargetGroupSpec{}, err } } @@ -414,10 +390,10 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( Namespace: namespace, Name: string(backendRef.Name()), } - tgp, err := GetAttachedPolicy(ctx, t.client, refObjNamespacedName, &v1alpha1.TargetGroupPolicy{}) + tgp, err := GetAttachedPolicy(ctx, t.client, refObjNamespacedName, &anv1alpha1.TargetGroupPolicy{}) if err != nil { - return latticemodel.TargetGroupSpec{}, err + return model.TargetGroupSpec{}, err } protocol := "HTTP" protocolVersion := vpclattice.TargetGroupProtocolVersionHttp1 @@ -438,10 +414,10 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupSpec( protocolVersion = vpclattice.TargetGroupProtocolVersionGrpc } - return latticemodel.TargetGroupSpec{ + return model.TargetGroupSpec{ Name: tgName, - Type: latticemodel.TargetGroupTypeIP, - Config: latticemodel.TargetGroupConfig{ + Type: model.TargetGroupTypeIP, + Config: model.TargetGroupConfig{ VpcID: vpc, EKSClusterName: eksCluster, IsServiceImport: isServiceImport, @@ -469,7 +445,7 @@ func (t *latticeServiceModelBuildTask) buildTargetGroupName(_ context.Context, b } } -func parseHealthCheckConfig(tgp *v1alpha1.TargetGroupPolicy) *vpclattice.HealthCheckConfig { +func parseHealthCheckConfig(tgp *anv1alpha1.TargetGroupPolicy) *vpclattice.HealthCheckConfig { hc := tgp.Spec.HealthCheck if hc == nil { return nil @@ -511,3 +487,22 @@ func buildTargetGroupIpAdressType(svc *corev1.Service) (string, error) { return "", fmt.Errorf("unknown ipFamily: %s", ipFamily) } } + +func GetServiceForBackendRef(ctx context.Context, client client.Client, route core.Route, backendRef core.BackendRef) (*corev1.Service, error) { + svc := &corev1.Service{} + key := types.NamespacedName{ + Name: string(backendRef.Name()), + } + + if backendRef.Namespace() != nil { + key.Namespace = string(*backendRef.Namespace()) + } else { + key.Namespace = route.Namespace() + } + + if err := client.Get(ctx, key, svc); err != nil { + return nil, err + } + + return svc, nil +} diff --git a/pkg/gateway/model_build_targetgroup_test.go b/pkg/gateway/model_build_targetgroup_test.go index d627453f..1b4ecca5 100644 --- a/pkg/gateway/model_build_targetgroup_test.go +++ b/pkg/gateway/model_build_targetgroup_test.go @@ -230,7 +230,7 @@ func Test_TGModelByServicexportBuild(t *testing.T) { tgName := latticestore.TargetGroupName(tt.svcExport.Name, tt.svcExport.Namespace) ds.AddTargetGroup(tgName, "vpc-123456789", "123456789", "tg-123", false, "") } - builder := NewTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) + builder := NewSvcExportTargetGroupBuilder(gwlog.FallbackLogger, k8sClient, ds, nil) stack, tg, err := builder.Build(ctx, tt.svcExport) @@ -538,7 +538,7 @@ func Test_TGModelByHTTPRouteBuild(t *testing.T) { } } - _, err := task.buildTargetGroup(ctx, k8sClient) + err := task.buildTargetGroupsForRoute(ctx, k8sClient) if !tt.wantErrIsNil { assert.NotNil(t, err) @@ -769,7 +769,7 @@ func Test_TGModelByHTTPRouteImportBuild(t *testing.T) { } k8sClient.EXPECT().List(ctx, gomock.Any(), gomock.Any()).Return(nil) - _, err := task.buildTargetGroup(ctx, k8sClient) + err := task.buildTargetGroupsForRoute(ctx, k8sClient) fmt.Printf("err %v\n", err) diff --git a/pkg/gateway/model_build_targets.go b/pkg/gateway/model_build_targets.go index a1dacb8b..4cd5cd3e 100644 --- a/pkg/gateway/model_build_targets.go +++ b/pkg/gateway/model_build_targets.go @@ -10,24 +10,23 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - mcs_api "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" + mcsv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1" - lattice_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" + pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws" "github.com/aws/aws-application-networking-k8s/pkg/k8s" "github.com/aws/aws-application-networking-k8s/pkg/latticestore" "github.com/aws/aws-application-networking-k8s/pkg/model/core" - latticemodel "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" + model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice" "github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog" ) const ( - resourceIDLatticeTargets = "LatticeTargets" - portAnnotationsKey = "multicluster.x-k8s.io/port" - undefinedPort = int32(0) + portAnnotationsKey = "multicluster.x-k8s.io/port" + undefinedPort = int32(0) ) type LatticeTargetsBuilder interface { - Build(ctx context.Context, service *corev1.Service, routeName string) (core.Stack, *latticemodel.Targets, error) + Build(ctx context.Context, service *corev1.Service, routeName string) (core.Stack, *model.Targets, error) } type LatticeTargetsModelBuilder struct { @@ -35,13 +34,13 @@ type LatticeTargetsModelBuilder struct { client client.Client defaultTags map[string]string datastore *latticestore.LatticeDataStore - cloud lattice_aws.Cloud + cloud pkg_aws.Cloud } func NewTargetsBuilder( log gwlog.Logger, client client.Client, - cloud lattice_aws.Cloud, + cloud pkg_aws.Cloud, datastore *latticestore.LatticeDataStore, ) *LatticeTargetsModelBuilder { return &LatticeTargetsModelBuilder{ @@ -52,7 +51,7 @@ func NewTargetsBuilder( } } -func (b *LatticeTargetsModelBuilder) Build(ctx context.Context, service *corev1.Service, routeName string) (core.Stack, *latticemodel.Targets, error) { +func (b *LatticeTargetsModelBuilder) Build(ctx context.Context, service *corev1.Service, routeName string) (core.Stack, *model.Targets, error) { stack := core.NewDefaultStack(core.StackID(k8s.NamespacedName(service))) task := &latticeTargetsModelBuildTask{ @@ -73,16 +72,7 @@ func (b *LatticeTargetsModelBuilder) Build(ctx context.Context, service *corev1. } func (t *latticeTargetsModelBuildTask) run(ctx context.Context) error { - err := t.buildModel(ctx) - return err -} - -func (t *latticeTargetsModelBuildTask) buildModel(ctx context.Context) error { - err := t.buildLatticeTargets(ctx) - if err != nil { - return err - } - return nil + return t.buildLatticeTargets(ctx) } func (t *latticeTargetsModelBuildTask) buildLatticeTargets(ctx context.Context) error { @@ -113,7 +103,7 @@ func (t *latticeTargetsModelBuildTask) buildLatticeTargets(ctx context.Context) definedPorts := make(map[int32]struct{}) if tg.ByServiceExport { - serviceExport := &mcs_api.ServiceExport{} + serviceExport := &mcsv1alpha1.ServiceExport{} err = t.client.Get(ctx, namespacedName, serviceExport) if err != nil { t.log.Errorf("Failed to find service export %s-%s in datastore due to %s", t.tgName, t.tgNamespace, err) @@ -160,7 +150,7 @@ func (t *latticeTargetsModelBuildTask) buildLatticeTargets(ctx context.Context) skipMatch = true } - var targetList []latticemodel.Target + var targetList []model.Target endpoints := &corev1.Endpoints{} if svc.DeletionTimestamp.IsZero() { @@ -171,7 +161,7 @@ func (t *latticeTargetsModelBuildTask) buildLatticeTargets(ctx context.Context) for _, endPoint := range endpoints.Subsets { for _, address := range endPoint.Addresses { for _, port := range endPoint.Ports { - target := latticemodel.Target{ + target := model.Target{ TargetIP: address.IP, Port: int64(port.Port), } @@ -185,14 +175,14 @@ func (t *latticeTargetsModelBuildTask) buildLatticeTargets(ctx context.Context) } } - spec := latticemodel.TargetsSpec{ + spec := model.TargetsSpec{ Name: t.tgName, Namespace: t.tgNamespace, RouteName: t.routeName, TargetIPList: targetList, } - t.latticeTargets = latticemodel.NewTargets(t.stack, tgName, spec) + t.latticeTargets = model.NewTargets(t.stack, tgName, spec) return nil } @@ -204,7 +194,7 @@ type latticeTargetsModelBuildTask struct { tgNamespace string routeName string backendRefPort int32 - latticeTargets *latticemodel.Targets + latticeTargets *model.Targets stack core.Stack datastore *latticestore.LatticeDataStore route core.Route diff --git a/pkg/gateway/utils.go b/pkg/gateway/utils.go index a2fa90d4..c9a10173 100644 --- a/pkg/gateway/utils.go +++ b/pkg/gateway/utils.go @@ -8,9 +8,9 @@ import ( "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" - "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" + anv1alpha1 "github.com/aws/aws-application-networking-k8s/pkg/apis/applicationnetworking/v1alpha1" "github.com/aws/aws-application-networking-k8s/pkg/model/core" ) @@ -51,12 +51,12 @@ func GetAttachedPolicy[T core.Policy](ctx context.Context, k8sClient client.Clie return null, nil } -func policyTypeToPolicyListAndTargetRefGroupKind(policyType core.Policy) (core.PolicyList, gateway_api.Group, gateway_api.Kind, error) { +func policyTypeToPolicyListAndTargetRefGroupKind(policyType core.Policy) (core.PolicyList, gwv1beta1.Group, gwv1beta1.Kind, error) { switch policyType.(type) { - case *v1alpha1.VpcAssociationPolicy: - return &v1alpha1.VpcAssociationPolicyList{}, gateway_api.GroupName, "Gateway", nil - case *v1alpha1.TargetGroupPolicy: - return &v1alpha1.TargetGroupPolicyList{}, corev1.GroupName, "Service", nil + case *anv1alpha1.VpcAssociationPolicy: + return &anv1alpha1.VpcAssociationPolicyList{}, gwv1beta1.GroupName, "Gateway", nil + case *anv1alpha1.TargetGroupPolicy: + return &anv1alpha1.TargetGroupPolicyList{}, corev1.GroupName, "Service", nil default: return nil, "", "", fmt.Errorf("unsupported policy type %T", policyType) } diff --git a/pkg/model/core/grpcroute.go b/pkg/model/core/grpcroute.go index 906608dd..9b33fb79 100644 --- a/pkg/model/core/grpcroute.go +++ b/pkg/model/core/grpcroute.go @@ -4,11 +4,11 @@ import ( "context" "reflect" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - gateway_api_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/aws/aws-application-networking-k8s/pkg/utils" ) @@ -18,15 +18,15 @@ const ( ) type GRPCRoute struct { - r gateway_api_v1alpha2.GRPCRoute + r gwv1alpha2.GRPCRoute } -func NewGRPCRoute(route gateway_api_v1alpha2.GRPCRoute) *GRPCRoute { +func NewGRPCRoute(route gwv1alpha2.GRPCRoute) *GRPCRoute { return &GRPCRoute{r: route} } func GetGRPCRoute(ctx context.Context, client client.Client, routeNamespacedName types.NamespacedName) (Route, error) { - grpcRoute := &gateway_api_v1alpha2.GRPCRoute{} + grpcRoute := &gwv1alpha2.GRPCRoute{} err := client.Get(ctx, routeNamespacedName, grpcRoute) if err != nil { return nil, err @@ -35,7 +35,7 @@ func GetGRPCRoute(ctx context.Context, client client.Client, routeNamespacedName } func ListGRPCRoutes(context context.Context, client client.Client) ([]Route, error) { - routeList := &gateway_api_v1alpha2.GRPCRouteList{} + routeList := &gwv1alpha2.GRPCRouteList{} if err := client.List(context, routeList); err != nil { return nil, err } @@ -63,7 +63,7 @@ func (r *GRPCRoute) Namespace() string { return r.r.Namespace } -func (r *GRPCRoute) DeletionTimestamp() *v1.Time { +func (r *GRPCRoute) DeletionTimestamp() *metav1.Time { return r.r.DeletionTimestamp } @@ -75,19 +75,19 @@ func (r *GRPCRoute) K8sObject() client.Object { return &r.r } -func (r *GRPCRoute) Inner() *gateway_api_v1alpha2.GRPCRoute { +func (r *GRPCRoute) Inner() *gwv1alpha2.GRPCRoute { return &r.r } type GRPCRouteSpec struct { - s gateway_api_v1alpha2.GRPCRouteSpec + s gwv1alpha2.GRPCRouteSpec } -func (s *GRPCRouteSpec) ParentRefs() []gateway_api_v1beta1.ParentReference { +func (s *GRPCRouteSpec) ParentRefs() []gwv1beta1.ParentReference { return s.s.ParentRefs } -func (s *GRPCRouteSpec) Hostnames() []gateway_api_v1beta1.Hostname { +func (s *GRPCRouteSpec) Hostnames() []gwv1beta1.Hostname { return s.s.Hostnames } @@ -128,32 +128,32 @@ func (s *GRPCRouteSpec) Equals(routeSpec RouteSpec) bool { } type GRPCRouteStatus struct { - s *gateway_api_v1alpha2.GRPCRouteStatus + s *gwv1alpha2.GRPCRouteStatus } -func (s *GRPCRouteStatus) Parents() []gateway_api_v1beta1.RouteParentStatus { +func (s *GRPCRouteStatus) Parents() []gwv1beta1.RouteParentStatus { return s.s.Parents } -func (s *GRPCRouteStatus) SetParents(parents []gateway_api_v1beta1.RouteParentStatus) { +func (s *GRPCRouteStatus) SetParents(parents []gwv1beta1.RouteParentStatus) { s.s.Parents = parents } -func (s *GRPCRouteStatus) UpdateParentRefs(parent gateway_api_v1beta1.ParentReference, controllerName gateway_api_v1beta1.GatewayController) { +func (s *GRPCRouteStatus) UpdateParentRefs(parent gwv1beta1.ParentReference, controllerName gwv1beta1.GatewayController) { if len(s.Parents()) == 0 { - s.SetParents(make([]gateway_api_v1beta1.RouteParentStatus, 1)) + s.SetParents(make([]gwv1beta1.RouteParentStatus, 1)) } s.Parents()[0].ParentRef = parent s.Parents()[0].ControllerName = controllerName } -func (s *GRPCRouteStatus) UpdateRouteCondition(condition v1.Condition) { +func (s *GRPCRouteStatus) UpdateRouteCondition(condition metav1.Condition) { s.Parents()[0].Conditions = utils.GetNewConditions(s.Parents()[0].Conditions, condition) } type GRPCRouteRule struct { - r gateway_api_v1alpha2.GRPCRouteRule + r gwv1alpha2.GRPCRouteRule } func (r *GRPCRouteRule) BackendRefs() []BackendRef { @@ -202,30 +202,30 @@ func (r *GRPCRouteRule) Equals(routeRule RouteRule) bool { } type GRPCBackendRef struct { - r gateway_api_v1alpha2.GRPCBackendRef + r gwv1alpha2.GRPCBackendRef } func (r *GRPCBackendRef) Weight() *int32 { return r.r.Weight } -func (r *GRPCBackendRef) Group() *gateway_api_v1beta1.Group { +func (r *GRPCBackendRef) Group() *gwv1beta1.Group { return r.r.Group } -func (r *GRPCBackendRef) Kind() *gateway_api_v1beta1.Kind { +func (r *GRPCBackendRef) Kind() *gwv1beta1.Kind { return r.r.Kind } -func (r *GRPCBackendRef) Name() gateway_api_v1beta1.ObjectName { +func (r *GRPCBackendRef) Name() gwv1beta1.ObjectName { return r.r.Name } -func (r *GRPCBackendRef) Namespace() *gateway_api_v1beta1.Namespace { +func (r *GRPCBackendRef) Namespace() *gwv1beta1.Namespace { return r.r.Namespace } -func (r *GRPCBackendRef) Port() *gateway_api_v1beta1.PortNumber { +func (r *GRPCBackendRef) Port() *gwv1beta1.PortNumber { return r.r.Port } @@ -255,7 +255,7 @@ func (r *GRPCBackendRef) Equals(backendRef BackendRef) bool { } type GRPCRouteMatch struct { - m gateway_api_v1alpha2.GRPCRouteMatch + m gwv1alpha2.GRPCRouteMatch } func (m *GRPCRouteMatch) Headers() []HeaderMatch { @@ -266,7 +266,7 @@ func (m *GRPCRouteMatch) Headers() []HeaderMatch { return headerMatches } -func (m *GRPCRouteMatch) Method() *gateway_api_v1alpha2.GRPCMethodMatch { +func (m *GRPCRouteMatch) Method() *gwv1alpha2.GRPCMethodMatch { return m.m.Method } @@ -294,10 +294,10 @@ func (m *GRPCRouteMatch) Equals(routeMatch RouteMatch) bool { } type GRPCHeaderMatch struct { - m gateway_api_v1alpha2.GRPCHeaderMatch + m gwv1alpha2.GRPCHeaderMatch } -func (m *GRPCHeaderMatch) Type() *gateway_api_v1beta1.HeaderMatchType { +func (m *GRPCHeaderMatch) Type() *gwv1beta1.HeaderMatchType { return m.m.Type } diff --git a/pkg/model/core/httproute.go b/pkg/model/core/httproute.go index 90548c71..13c71a39 100644 --- a/pkg/model/core/httproute.go +++ b/pkg/model/core/httproute.go @@ -4,10 +4,10 @@ import ( "context" "reflect" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/aws/aws-application-networking-k8s/pkg/utils" ) @@ -17,15 +17,15 @@ const ( ) type HTTPRoute struct { - r gateway_api_v1beta1.HTTPRoute + r gwv1beta1.HTTPRoute } -func NewHTTPRoute(route gateway_api_v1beta1.HTTPRoute) *HTTPRoute { +func NewHTTPRoute(route gwv1beta1.HTTPRoute) *HTTPRoute { return &HTTPRoute{r: route} } func GetHTTPRoute(ctx context.Context, client client.Client, routeNamespacedName types.NamespacedName) (Route, error) { - httpRoute := &gateway_api_v1beta1.HTTPRoute{} + httpRoute := &gwv1beta1.HTTPRoute{} err := client.Get(ctx, routeNamespacedName, httpRoute) if err != nil { return nil, err @@ -34,7 +34,7 @@ func GetHTTPRoute(ctx context.Context, client client.Client, routeNamespacedName } func ListHTTPRoutes(context context.Context, client client.Client) ([]Route, error) { - routeList := &gateway_api_v1beta1.HTTPRouteList{} + routeList := &gwv1beta1.HTTPRouteList{} if err := client.List(context, routeList); err != nil { return nil, err } @@ -62,7 +62,7 @@ func (r *HTTPRoute) Namespace() string { return r.r.Namespace } -func (r *HTTPRoute) DeletionTimestamp() *v1.Time { +func (r *HTTPRoute) DeletionTimestamp() *metav1.Time { return r.r.DeletionTimestamp } @@ -74,19 +74,19 @@ func (r *HTTPRoute) K8sObject() client.Object { return &r.r } -func (r *HTTPRoute) Inner() *gateway_api_v1beta1.HTTPRoute { +func (r *HTTPRoute) Inner() *gwv1beta1.HTTPRoute { return &r.r } type HTTPRouteSpec struct { - s gateway_api_v1beta1.HTTPRouteSpec + s gwv1beta1.HTTPRouteSpec } -func (s *HTTPRouteSpec) ParentRefs() []gateway_api_v1beta1.ParentReference { +func (s *HTTPRouteSpec) ParentRefs() []gwv1beta1.ParentReference { return s.s.ParentRefs } -func (s *HTTPRouteSpec) Hostnames() []gateway_api_v1beta1.Hostname { +func (s *HTTPRouteSpec) Hostnames() []gwv1beta1.Hostname { return s.s.Hostnames } @@ -127,32 +127,32 @@ func (s *HTTPRouteSpec) Equals(routeSpec RouteSpec) bool { } type HTTPRouteStatus struct { - s *gateway_api_v1beta1.HTTPRouteStatus + s *gwv1beta1.HTTPRouteStatus } -func (s *HTTPRouteStatus) Parents() []gateway_api_v1beta1.RouteParentStatus { +func (s *HTTPRouteStatus) Parents() []gwv1beta1.RouteParentStatus { return s.s.Parents } -func (s *HTTPRouteStatus) SetParents(parents []gateway_api_v1beta1.RouteParentStatus) { +func (s *HTTPRouteStatus) SetParents(parents []gwv1beta1.RouteParentStatus) { s.s.Parents = parents } -func (s *HTTPRouteStatus) UpdateParentRefs(parent gateway_api_v1beta1.ParentReference, controllerName gateway_api_v1beta1.GatewayController) { +func (s *HTTPRouteStatus) UpdateParentRefs(parent gwv1beta1.ParentReference, controllerName gwv1beta1.GatewayController) { if len(s.Parents()) == 0 { - s.SetParents(make([]gateway_api_v1beta1.RouteParentStatus, 1)) + s.SetParents(make([]gwv1beta1.RouteParentStatus, 1)) } s.Parents()[0].ParentRef = parent s.Parents()[0].ControllerName = controllerName } -func (s *HTTPRouteStatus) UpdateRouteCondition(condition v1.Condition) { +func (s *HTTPRouteStatus) UpdateRouteCondition(condition metav1.Condition) { s.Parents()[0].Conditions = utils.GetNewConditions(s.Parents()[0].Conditions, condition) } type HTTPRouteRule struct { - r gateway_api_v1beta1.HTTPRouteRule + r gwv1beta1.HTTPRouteRule } func (r *HTTPRouteRule) BackendRefs() []BackendRef { @@ -201,30 +201,30 @@ func (r *HTTPRouteRule) Equals(routeRule RouteRule) bool { } type HTTPBackendRef struct { - r gateway_api_v1beta1.HTTPBackendRef + r gwv1beta1.HTTPBackendRef } func (r *HTTPBackendRef) Weight() *int32 { return r.r.Weight } -func (r *HTTPBackendRef) Group() *gateway_api_v1beta1.Group { +func (r *HTTPBackendRef) Group() *gwv1beta1.Group { return r.r.Group } -func (r *HTTPBackendRef) Kind() *gateway_api_v1beta1.Kind { +func (r *HTTPBackendRef) Kind() *gwv1beta1.Kind { return r.r.Kind } -func (r *HTTPBackendRef) Name() gateway_api_v1beta1.ObjectName { +func (r *HTTPBackendRef) Name() gwv1beta1.ObjectName { return r.r.Name } -func (r *HTTPBackendRef) Namespace() *gateway_api_v1beta1.Namespace { +func (r *HTTPBackendRef) Namespace() *gwv1beta1.Namespace { return r.r.Namespace } -func (r *HTTPBackendRef) Port() *gateway_api_v1beta1.PortNumber { +func (r *HTTPBackendRef) Port() *gwv1beta1.PortNumber { return r.r.Port } @@ -254,7 +254,7 @@ func (r *HTTPBackendRef) Equals(backendRef BackendRef) bool { } type HTTPRouteMatch struct { - m gateway_api_v1beta1.HTTPRouteMatch + m gwv1beta1.HTTPRouteMatch } func (m *HTTPRouteMatch) Headers() []HeaderMatch { @@ -265,15 +265,15 @@ func (m *HTTPRouteMatch) Headers() []HeaderMatch { return headerMatches } -func (m *HTTPRouteMatch) Path() *gateway_api_v1beta1.HTTPPathMatch { +func (m *HTTPRouteMatch) Path() *gwv1beta1.HTTPPathMatch { return m.m.Path } -func (m *HTTPRouteMatch) QueryParams() []gateway_api_v1beta1.HTTPQueryParamMatch { +func (m *HTTPRouteMatch) QueryParams() []gwv1beta1.HTTPQueryParamMatch { return m.m.QueryParams } -func (m *HTTPRouteMatch) Method() *gateway_api_v1beta1.HTTPMethod { +func (m *HTTPRouteMatch) Method() *gwv1beta1.HTTPMethod { return m.m.Method } @@ -309,10 +309,10 @@ func (m *HTTPRouteMatch) Equals(routeMatch RouteMatch) bool { } type HTTPHeaderMatch struct { - m gateway_api_v1beta1.HTTPHeaderMatch + m gwv1beta1.HTTPHeaderMatch } -func (m *HTTPHeaderMatch) Type() *gateway_api_v1beta1.HeaderMatchType { +func (m *HTTPHeaderMatch) Type() *gwv1beta1.HeaderMatchType { return m.m.Type } diff --git a/pkg/model/core/policy.go b/pkg/model/core/policy.go index 17508313..d25c57fe 100644 --- a/pkg/model/core/policy.go +++ b/pkg/model/core/policy.go @@ -2,12 +2,12 @@ package core import ( "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/gateway-api/apis/v1alpha2" + gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" ) type Policy interface { GetNamespacedName() types.NamespacedName - GetTargetRef() *v1alpha2.PolicyTargetReference + GetTargetRef() *gwv1alpha2.PolicyTargetReference } type PolicyList interface { diff --git a/pkg/model/core/route.go b/pkg/model/core/route.go index 761cdc16..c04af44d 100644 --- a/pkg/model/core/route.go +++ b/pkg/model/core/route.go @@ -4,11 +4,11 @@ import ( "context" "fmt" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" - gateway_api_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - gateway_api_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" + gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gwv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) type RouteType string @@ -18,16 +18,16 @@ type Route interface { Status() RouteStatus Name() string Namespace() string - DeletionTimestamp() *v1.Time + DeletionTimestamp() *metav1.Time DeepCopy() Route K8sObject() client.Object } func NewRoute(object client.Object) (Route, error) { switch obj := object.(type) { - case *gateway_api_v1beta1.HTTPRoute: + case *gwv1beta1.HTTPRoute: return NewHTTPRoute(*obj), nil - case *gateway_api_v1alpha2.GRPCRoute: + case *gwv1alpha2.GRPCRoute: return NewGRPCRoute(*obj), nil default: return nil, fmt.Errorf("unexpected route type for object %+v", object) @@ -57,17 +57,17 @@ func ListAllRoutes(context context.Context, client client.Client) ([]Route, erro } type RouteSpec interface { - ParentRefs() []gateway_api_v1beta1.ParentReference - Hostnames() []gateway_api_v1beta1.Hostname + ParentRefs() []gwv1beta1.ParentReference + Hostnames() []gwv1beta1.Hostname Rules() []RouteRule Equals(routeSpec RouteSpec) bool } type RouteStatus interface { - Parents() []gateway_api_v1beta1.RouteParentStatus - SetParents(parents []gateway_api_v1beta1.RouteParentStatus) - UpdateParentRefs(parent gateway_api_v1beta1.ParentReference, controllerName gateway_api_v1beta1.GatewayController) - UpdateRouteCondition(condition v1.Condition) + Parents() []gwv1beta1.RouteParentStatus + SetParents(parents []gwv1beta1.RouteParentStatus) + UpdateParentRefs(parent gwv1beta1.ParentReference, controllerName gwv1beta1.GatewayController) + UpdateRouteCondition(condition metav1.Condition) } type RouteRule interface { @@ -78,11 +78,11 @@ type RouteRule interface { type BackendRef interface { Weight() *int32 - Group() *gateway_api_v1beta1.Group - Kind() *gateway_api_v1beta1.Kind - Name() gateway_api_v1beta1.ObjectName - Namespace() *gateway_api_v1beta1.Namespace - Port() *gateway_api_v1beta1.PortNumber + Group() *gwv1beta1.Group + Kind() *gwv1beta1.Kind + Name() gwv1beta1.ObjectName + Namespace() *gwv1beta1.Namespace + Port() *gwv1beta1.PortNumber Equals(backendRef BackendRef) bool } @@ -92,7 +92,7 @@ type RouteMatch interface { } type HeaderMatch interface { - Type() *gateway_api_v1beta1.HeaderMatchType + Type() *gwv1beta1.HeaderMatchType Name() string Value() string Equals(headerMatch HeaderMatch) bool diff --git a/pkg/model/lattice/listener.go b/pkg/model/lattice/listener.go index daecd54c..f2ea3ffb 100644 --- a/pkg/model/lattice/listener.go +++ b/pkg/model/lattice/listener.go @@ -19,7 +19,6 @@ type ListenerSpec struct { } type DefaultAction struct { - Is_Import bool `json:"isimport"` BackendServiceName string `json:"backendservicename"` BackendServiceNamespace string `json:"backendservicenamespace"` } diff --git a/pkg/model/lattice/rule.go b/pkg/model/lattice/rule.go index c9f89027..b7bd75ef 100644 --- a/pkg/model/lattice/rule.go +++ b/pkg/model/lattice/rule.go @@ -15,11 +15,6 @@ type Rule struct { } const ( - // K8S HTTPRouteMatch - MatchByPath = "HTTPRouteMatch" - // K8S HTTPRouteFilter - MatchByFilter = "HTTPRouteFilter" - MAX_NUM_OF_MATCHED_HEADERS = 5 ) diff --git a/pkg/model/lattice/service.go b/pkg/model/lattice/service.go index 2c143e87..4c299c18 100644 --- a/pkg/model/lattice/service.go +++ b/pkg/model/lattice/service.go @@ -7,10 +7,8 @@ import ( type Service struct { core.ResourceMeta `json:"-"` - - Spec ServiceSpec `json:"spec"` - - Status *ServiceStatus `json:"status,omitempty"` + Spec ServiceSpec `json:"spec"` + Status *ServiceStatus `json:"status,omitempty"` } type ServiceSpec struct { diff --git a/pkg/model/lattice/servicenetwork.go b/pkg/model/lattice/servicenetwork.go index 1d8b09ed..63cf93d6 100644 --- a/pkg/model/lattice/servicenetwork.go +++ b/pkg/model/lattice/servicenetwork.go @@ -11,12 +11,8 @@ const ( type ServiceNetwork struct { core.ResourceMeta `json:"-"` - - // desired state of ServiceNetwork - Spec ServiceNetworkSpec `json:"spec"` - - // observed state of ServiceNetwork - Status *ServiceNetworkStatus `json:"status,omitempty"` + Spec ServiceNetworkSpec `json:"spec"` + Status *ServiceNetworkStatus `json:"status,omitempty"` } type ServiceNetworkSpec struct {