From 3e9fe97ba38ad3bd6567ff6c347f386bca17a339 Mon Sep 17 00:00:00 2001 From: Gallardot Date: Thu, 6 Oct 2022 17:58:38 +0800 Subject: [PATCH] [apisix] Implement router interface and observer interface Signed-off-by: Gallardot --- artifacts/flagger/account.yaml | 12 + artifacts/flagger/crd.yaml | 13 + charts/flagger/crds/crd.yaml | 13 + charts/flagger/templates/rbac.yaml | 12 + hack/update-codegen.sh | 2 +- kustomize/base/flagger/crd.yaml | 13 + pkg/apis/apisix/register.go | 21 + pkg/apis/apisix/v2/doc.go | 21 + pkg/apis/apisix/v2/register.go | 52 +++ pkg/apis/apisix/v2/types.go | 245 ++++++++++ pkg/apis/apisix/v2/zz_generated.deepcopy.go | 434 ++++++++++++++++++ pkg/apis/flagger/v1beta1/canary.go | 4 + pkg/apis/flagger/v1beta1/provider.go | 1 + .../flagger/v1beta1/zz_generated.deepcopy.go | 5 + pkg/client/clientset/versioned/clientset.go | 13 + .../versioned/fake/clientset_generated.go | 7 + .../clientset/versioned/fake/register.go | 2 + .../clientset/versioned/scheme/register.go | 2 + .../typed/apisix/v2/apisix_client.go | 107 +++++ .../versioned/typed/apisix/v2/apisixroute.go | 195 ++++++++ .../versioned/typed/apisix/v2/doc.go | 20 + .../versioned/typed/apisix/v2/fake/doc.go | 20 + .../apisix/v2/fake/fake_apisix_client.go | 40 ++ .../typed/apisix/v2/fake/fake_apisixroute.go | 142 ++++++ .../typed/apisix/v2/generated_expansion.go | 21 + .../externalversions/apisix/interface.go | 46 ++ .../externalversions/apisix/v2/apisixroute.go | 90 ++++ .../externalversions/apisix/v2/interface.go | 45 ++ .../informers/externalversions/factory.go | 6 + .../informers/externalversions/generic.go | 7 +- pkg/client/listers/apisix/v2/apisixroute.go | 99 ++++ .../listers/apisix/v2/expansion_generated.go | 27 ++ pkg/metrics/observers/apisix.go | 90 ++++ pkg/metrics/observers/apisix_test.go | 117 +++++ pkg/metrics/observers/factory.go | 4 + pkg/router/apisix.go | 184 ++++++++ pkg/router/apisix_test.go | 33 ++ pkg/router/factory.go | 6 + pkg/router/router_test.go | 1 + 39 files changed, 2170 insertions(+), 2 deletions(-) create mode 100644 pkg/apis/apisix/register.go create mode 100644 pkg/apis/apisix/v2/doc.go create mode 100644 pkg/apis/apisix/v2/register.go create mode 100644 pkg/apis/apisix/v2/types.go create mode 100644 pkg/apis/apisix/v2/zz_generated.deepcopy.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/apisix_client.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/apisixroute.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/doc.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/fake/doc.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisix_client.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisixroute.go create mode 100644 pkg/client/clientset/versioned/typed/apisix/v2/generated_expansion.go create mode 100644 pkg/client/informers/externalversions/apisix/interface.go create mode 100644 pkg/client/informers/externalversions/apisix/v2/apisixroute.go create mode 100644 pkg/client/informers/externalversions/apisix/v2/interface.go create mode 100644 pkg/client/listers/apisix/v2/apisixroute.go create mode 100644 pkg/client/listers/apisix/v2/expansion_generated.go create mode 100644 pkg/metrics/observers/apisix.go create mode 100644 pkg/metrics/observers/apisix_test.go create mode 100644 pkg/router/apisix.go create mode 100644 pkg/router/apisix_test.go diff --git a/artifacts/flagger/account.yaml b/artifacts/flagger/account.yaml index 67b22ee5..ae07a7f8 100644 --- a/artifacts/flagger/account.yaml +++ b/artifacts/flagger/account.yaml @@ -239,6 +239,18 @@ rules: - update - patch - delete + - apiGroups: + - apisix.apache.org + resources: + - apisixroutes + verbs: + - get + - list + - watch + - create + - update + - patch + - delete - nonResourceURLs: - /version verbs: diff --git a/artifacts/flagger/crd.yaml b/artifacts/flagger/crd.yaml index 6cfba256..13e0bd00 100644 --- a/artifacts/flagger/crd.yaml +++ b/artifacts/flagger/crd.yaml @@ -134,6 +134,19 @@ spec: - Ingress name: type: string + routeRef: + description: APISIX route selector + type: object + required: [ "apiVersion", "kind", "name" ] + properties: + apiVersion: + type: string + kind: + type: string + enum: + - ApisixRoute + name: + type: string upstreamRef: description: Gloo Upstream selector type: object diff --git a/charts/flagger/crds/crd.yaml b/charts/flagger/crds/crd.yaml index 6cfba256..13e0bd00 100644 --- a/charts/flagger/crds/crd.yaml +++ b/charts/flagger/crds/crd.yaml @@ -134,6 +134,19 @@ spec: - Ingress name: type: string + routeRef: + description: APISIX route selector + type: object + required: [ "apiVersion", "kind", "name" ] + properties: + apiVersion: + type: string + kind: + type: string + enum: + - ApisixRoute + name: + type: string upstreamRef: description: Gloo Upstream selector type: object diff --git a/charts/flagger/templates/rbac.yaml b/charts/flagger/templates/rbac.yaml index 6689a65f..c1dfc841 100644 --- a/charts/flagger/templates/rbac.yaml +++ b/charts/flagger/templates/rbac.yaml @@ -247,6 +247,18 @@ rules: - update - patch - delete + - apiGroups: + - apisix.apache.org + resources: + - apisixroutes + verbs: + - get + - list + - watch + - create + - update + - patch + - delete - nonResourceURLs: - /version verbs: diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index f8bf775a..001255b4 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -30,7 +30,7 @@ chmod +x ${CODEGEN_PKG}/generate-groups.sh ${CODEGEN_PKG}/generate-groups.sh all \ github.com/fluxcd/flagger/pkg/client github.com/fluxcd/flagger/pkg/apis \ - "flagger:v1beta1 appmesh:v1beta2 appmesh:v1beta1 istio:v1alpha3 smi:v1alpha1 smi:v1alpha2 smi:v1alpha3 gloo/gloo:v1 gloo/gateway:v1 projectcontour:v1 traefik:v1alpha1 kuma:v1alpha1 gatewayapi:v1alpha2 gatewayapi:v1beta1 keda:v1alpha1" \ + "flagger:v1beta1 appmesh:v1beta2 appmesh:v1beta1 istio:v1alpha3 smi:v1alpha1 smi:v1alpha2 smi:v1alpha3 gloo/gloo:v1 gloo/gateway:v1 projectcontour:v1 traefik:v1alpha1 kuma:v1alpha1 gatewayapi:v1alpha2 gatewayapi:v1beta1 keda:v1alpha1 apisix:v2" \ --output-base "${TEMP_DIR}" \ --go-header-file ${SCRIPT_ROOT}/hack/boilerplate.go.txt diff --git a/kustomize/base/flagger/crd.yaml b/kustomize/base/flagger/crd.yaml index 6cfba256..13e0bd00 100644 --- a/kustomize/base/flagger/crd.yaml +++ b/kustomize/base/flagger/crd.yaml @@ -134,6 +134,19 @@ spec: - Ingress name: type: string + routeRef: + description: APISIX route selector + type: object + required: [ "apiVersion", "kind", "name" ] + properties: + apiVersion: + type: string + kind: + type: string + enum: + - ApisixRoute + name: + type: string upstreamRef: description: Gloo Upstream selector type: object diff --git a/pkg/apis/apisix/register.go b/pkg/apis/apisix/register.go new file mode 100644 index 00000000..b0ae2cdf --- /dev/null +++ b/pkg/apis/apisix/register.go @@ -0,0 +1,21 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package apisix + +const ( + GroupName = "apisix.apache.org" +) diff --git a/pkg/apis/apisix/v2/doc.go b/pkg/apis/apisix/v2/doc.go new file mode 100644 index 00000000..8f197a95 --- /dev/null +++ b/pkg/apis/apisix/v2/doc.go @@ -0,0 +1,21 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// +k8s:deepcopy-gen=package + +// Package v2 is the v2 version of the API. +// +groupName=apisix.apache.org +package v2 diff --git a/pkg/apis/apisix/v2/register.go b/pkg/apis/apisix/v2/register.go new file mode 100644 index 00000000..6cc9b640 --- /dev/null +++ b/pkg/apis/apisix/v2/register.go @@ -0,0 +1,52 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v2 + +import ( + "github.com/fluxcd/flagger/pkg/apis/apisix" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: apisix.GroupName, Version: "v2"} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) schema.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &ApisixRoute{}, + &ApisixRouteList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/pkg/apis/apisix/v2/types.go b/pkg/apis/apisix/v2/types.go new file mode 100644 index 00000000..cbd33e2f --- /dev/null +++ b/pkg/apis/apisix/v2/types.go @@ -0,0 +1,245 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v2 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:subresource:status +// ApisixRoute is used to define the route rules and upstreams for Apache APISIX. +type ApisixRoute struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"` + Spec ApisixRouteSpec `json:"spec,omitempty" yaml:"spec,omitempty"` + Status ApisixStatus `json:"status,omitempty" yaml:"status,omitempty"` +} + +// ApisixStatus is the status report for Apisix ingress Resources +type ApisixStatus struct { + Conditions []metav1.Condition `json:"conditions,omitempty" yaml:"conditions,omitempty"` +} + +// ApisixRouteSpec is the spec definition for ApisixRouteSpec. +type ApisixRouteSpec struct { + HTTP []ApisixRouteHTTP `json:"http,omitempty" yaml:"http,omitempty"` + Stream []ApisixRouteStream `json:"stream,omitempty" yaml:"stream,omitempty"` +} + +// ApisixRouteHTTP represents a single route in for HTTP traffic. +type ApisixRouteHTTP struct { + // The rule name, cannot be empty. + Name string `json:"name" yaml:"name"` + // Route priority, when multiple routes contains + // same URI path (for path matching), route with + // higher priority will take effect. + Priority int `json:"priority,omitempty" yaml:"priority,omitempty"` + Timeout *UpstreamTimeout `json:"timeout,omitempty" yaml:"timeout,omitempty"` + Match ApisixRouteHTTPMatch `json:"match,omitempty" yaml:"match,omitempty"` + // Backends represents potential backends to proxy after the route + // rule matched. When number of backends are more than one, traffic-split + // plugin in APISIX will be used to split traffic based on the backend weight. + Backends []ApisixRouteHTTPBackend `json:"backends,omitempty" yaml:"backends,omitempty"` + Websocket bool `json:"websocket" yaml:"websocket"` + PluginConfigName string `json:"plugin_config_name,omitempty" yaml:"plugin_config_name,omitempty"` + Plugins []ApisixRoutePlugin `json:"plugins,omitempty" yaml:"plugins,omitempty"` + Authentication *ApisixRouteAuthentication `json:"authentication,omitempty" yaml:"authentication,omitempty"` +} + +// UpstreamTimeout is settings for the read, send and connect to the upstream. +type UpstreamTimeout struct { + Connect metav1.Duration `json:"connect,omitempty" yaml:"connect,omitempty"` + Send metav1.Duration `json:"send,omitempty" yaml:"send,omitempty"` + Read metav1.Duration `json:"read,omitempty" yaml:"read,omitempty"` +} + +// ApisixRouteHTTPBackend represents a HTTP backend (a Kuberentes Service). +type ApisixRouteHTTPBackend struct { + // The name (short) of the service, note cross namespace is forbidden, + // so be sure the ApisixRoute and Service are in the same namespace. + ServiceName string `json:"serviceName" yaml:"serviceName"` + // The service port, could be the name or the port number. + ServicePort intstr.IntOrString `json:"servicePort" yaml:"servicePort"` + // The resolve granularity, can be "endpoints" or "service", + // when set to "endpoints", the pod ips will be used; other + // wise, the service ClusterIP or ExternalIP will be used, + // default is endpoints. + ResolveGranularity string `json:"resolveGranularity,omitempty" yaml:"resolveGranularity,omitempty"` + // Weight of this backend. + Weight *int `json:"weight" yaml:"weight"` + // Subset specifies a subset for the target Service. The subset should be pre-defined + // in ApisixUpstream about this service. + Subset string `json:"subset,omitempty" yaml:"subset,omitempty"` +} + +// ApisixRouteHTTPMatch represents the match condition for hitting this route. +type ApisixRouteHTTPMatch struct { + // URI path predicates, at least one path should be + // configured, path could be exact or prefix, for prefix path, + // append "*" after it, for instance, "/foo*". + Paths []string `json:"paths" yaml:"paths"` + // HTTP request method predicates. + Methods []string `json:"methods,omitempty" yaml:"methods,omitempty"` + // HTTP Host predicates, host can be a wildcard domain or + // an exact domain. For wildcard domain, only one generic + // level is allowed, for instance, "*.foo.com" is valid but + // "*.*.foo.com" is not. + Hosts []string `json:"hosts,omitempty" yaml:"hosts,omitempty"` + // Remote address predicates, items can be valid IPv4 address + // or IPv6 address or CIDR. + RemoteAddrs []string `json:"remoteAddrs,omitempty" yaml:"remoteAddrs,omitempty"` + // NginxVars represents generic match predicates, + // it uses Nginx variable systems, so any predicate + // like headers, querystring and etc can be leveraged + // here to match the route. + // For instance, it can be: + // nginxVars: + // - subject: "$remote_addr" + // op: in + // value: + // - "127.0.0.1" + // - "10.0.5.11" + NginxVars []ApisixRouteHTTPMatchExpr `json:"exprs,omitempty" yaml:"exprs,omitempty"` +} + +// ApisixRouteHTTPMatchExpr represents a binary route match expression . +type ApisixRouteHTTPMatchExpr struct { + // Subject is the expression subject, it can + // be any string composed by literals and nginx + // vars. + Subject ApisixRouteHTTPMatchExprSubject `json:"subject" yaml:"subject"` + // Op is the operator. + Op string `json:"op" yaml:"op"` + // Set is an array type object of the expression. + // It should be used when the Op is "in" or "not_in"; + Set []string `json:"set" yaml:"set"` + // Value is the normal type object for the expression, + // it should be used when the Op is not "in" and "not_in". + // Set and Value are exclusive so only of them can be set + // in the same time. + Value *string `json:"value" yaml:"value"` +} + +// ApisixRouteHTTPMatchExprSubject describes the route match expression subject. +type ApisixRouteHTTPMatchExprSubject struct { + // The subject scope, can be: + // ScopeQuery, ScopeHeader, ScopePath + // when subject is ScopePath, Name field + // will be ignored. + Scope string `json:"scope" yaml:"scope"` + // The name of subject. + Name string `json:"name" yaml:"name"` +} + +// ApisixRoutePlugin represents an APISIX plugin. +type ApisixRoutePlugin struct { + // The plugin name. + Name string `json:"name" yaml:"name"` + // Whether this plugin is in use, default is true. + Enable bool `json:"enable" yaml:"enable"` + // Plugin configuration. + Config ApisixRoutePluginConfig `json:"config" yaml:"config"` +} + +// ApisixRoutePluginConfig is the configuration for +// any plugins. +type ApisixRoutePluginConfig map[string]interface{} + +// ApisixRouteAuthentication is the authentication-related +// configuration in ApisixRoute. +type ApisixRouteAuthentication struct { + Enable bool `json:"enable" yaml:"enable"` + Type string `json:"type" yaml:"type"` + KeyAuth ApisixRouteAuthenticationKeyAuth `json:"keyAuth,omitempty" yaml:"keyAuth,omitempty"` + JwtAuth ApisixRouteAuthenticationJwtAuth `json:"jwtAuth,omitempty" yaml:"jwtAuth,omitempty"` +} + +// ApisixRouteAuthenticationKeyAuth is the keyAuth-related +// configuration in ApisixRouteAuthentication. +type ApisixRouteAuthenticationKeyAuth struct { + Header string `json:"header,omitempty" yaml:"header,omitempty"` +} + +// ApisixRouteAuthenticationJwtAuth is the jwt auth related +// configuration in ApisixRouteAuthentication. +type ApisixRouteAuthenticationJwtAuth struct { + Header string `json:"header,omitempty" yaml:"header,omitempty"` + Query string `json:"query,omitempty" yaml:"query,omitempty"` + Cookie string `json:"cookie,omitempty" yaml:"cookie,omitempty"` +} + +func (p ApisixRoutePluginConfig) DeepCopyInto(out *ApisixRoutePluginConfig) { + b, _ := json.Marshal(&p) + _ = json.Unmarshal(b, out) +} + +func (p *ApisixRoutePluginConfig) DeepCopy() *ApisixRoutePluginConfig { + if p == nil { + return nil + } + out := new(ApisixRoutePluginConfig) + p.DeepCopyInto(out) + return out +} + +// ApisixRouteStream is the configuration for level 4 route +type ApisixRouteStream struct { + // The rule name, cannot be empty. + Name string `json:"name" yaml:"name"` + Protocol string `json:"protocol" yaml:"protocol"` + Match ApisixRouteStreamMatch `json:"match" yaml:"match"` + Backend ApisixRouteStreamBackend `json:"backend" yaml:"backend"` + Plugins []ApisixRoutePlugin `json:"plugins,omitempty" yaml:"plugins,omitempty"` +} + +// ApisixRouteStreamMatch represents the match conditions of stream route. +type ApisixRouteStreamMatch struct { + // IngressPort represents the port listening on the Ingress proxy server. + // It should be pre-defined as APISIX doesn't support dynamic listening. + IngressPort int32 `json:"ingressPort" yaml:"ingressPort"` +} + +// ApisixRouteStreamBackend represents a TCP backend (a Kubernetes Service). +type ApisixRouteStreamBackend struct { + // The name (short) of the service, note cross namespace is forbidden, + // so be sure the ApisixRoute and Service are in the same namespace. + ServiceName string `json:"serviceName" yaml:"serviceName"` + // The service port, could be the name or the port number. + ServicePort intstr.IntOrString `json:"servicePort" yaml:"servicePort"` + // The resolve granularity, can be "endpoints" or "service", + // when set to "endpoints", the pod ips will be used; other + // wise, the service ClusterIP or ExternalIP will be used, + // default is endpoints. + ResolveGranularity string `json:"resolveGranularity,omitempty" yaml:"resolveGranularity,omitempty"` + // Subset specifies a subset for the target Service. The subset should be pre-defined + // in ApisixUpstream about this service. + Subset string `json:"subset,omitempty" yaml:"subset,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ApisixRouteList contains a list of ApisixRoute. +type ApisixRouteList struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ListMeta `json:"metadata" yaml:"metadata"` + Items []ApisixRoute `json:"items,omitempty" yaml:"items,omitempty"` +} diff --git a/pkg/apis/apisix/v2/zz_generated.deepcopy.go b/pkg/apis/apisix/v2/zz_generated.deepcopy.go new file mode 100644 index 00000000..90e5e238 --- /dev/null +++ b/pkg/apis/apisix/v2/zz_generated.deepcopy.go @@ -0,0 +1,434 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v2 + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRoute) DeepCopyInto(out *ApisixRoute) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRoute. +func (in *ApisixRoute) DeepCopy() *ApisixRoute { + if in == nil { + return nil + } + out := new(ApisixRoute) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ApisixRoute) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteAuthentication) DeepCopyInto(out *ApisixRouteAuthentication) { + *out = *in + out.KeyAuth = in.KeyAuth + out.JwtAuth = in.JwtAuth + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteAuthentication. +func (in *ApisixRouteAuthentication) DeepCopy() *ApisixRouteAuthentication { + if in == nil { + return nil + } + out := new(ApisixRouteAuthentication) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteAuthenticationJwtAuth) DeepCopyInto(out *ApisixRouteAuthenticationJwtAuth) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteAuthenticationJwtAuth. +func (in *ApisixRouteAuthenticationJwtAuth) DeepCopy() *ApisixRouteAuthenticationJwtAuth { + if in == nil { + return nil + } + out := new(ApisixRouteAuthenticationJwtAuth) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteAuthenticationKeyAuth) DeepCopyInto(out *ApisixRouteAuthenticationKeyAuth) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteAuthenticationKeyAuth. +func (in *ApisixRouteAuthenticationKeyAuth) DeepCopy() *ApisixRouteAuthenticationKeyAuth { + if in == nil { + return nil + } + out := new(ApisixRouteAuthenticationKeyAuth) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteHTTP) DeepCopyInto(out *ApisixRouteHTTP) { + *out = *in + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(UpstreamTimeout) + **out = **in + } + in.Match.DeepCopyInto(&out.Match) + if in.Backends != nil { + in, out := &in.Backends, &out.Backends + *out = make([]ApisixRouteHTTPBackend, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Plugins != nil { + in, out := &in.Plugins, &out.Plugins + *out = make([]ApisixRoutePlugin, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Authentication != nil { + in, out := &in.Authentication, &out.Authentication + *out = new(ApisixRouteAuthentication) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteHTTP. +func (in *ApisixRouteHTTP) DeepCopy() *ApisixRouteHTTP { + if in == nil { + return nil + } + out := new(ApisixRouteHTTP) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteHTTPBackend) DeepCopyInto(out *ApisixRouteHTTPBackend) { + *out = *in + out.ServicePort = in.ServicePort + if in.Weight != nil { + in, out := &in.Weight, &out.Weight + *out = new(int) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteHTTPBackend. +func (in *ApisixRouteHTTPBackend) DeepCopy() *ApisixRouteHTTPBackend { + if in == nil { + return nil + } + out := new(ApisixRouteHTTPBackend) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteHTTPMatch) DeepCopyInto(out *ApisixRouteHTTPMatch) { + *out = *in + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Methods != nil { + in, out := &in.Methods, &out.Methods + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Hosts != nil { + in, out := &in.Hosts, &out.Hosts + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.RemoteAddrs != nil { + in, out := &in.RemoteAddrs, &out.RemoteAddrs + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.NginxVars != nil { + in, out := &in.NginxVars, &out.NginxVars + *out = make([]ApisixRouteHTTPMatchExpr, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteHTTPMatch. +func (in *ApisixRouteHTTPMatch) DeepCopy() *ApisixRouteHTTPMatch { + if in == nil { + return nil + } + out := new(ApisixRouteHTTPMatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteHTTPMatchExpr) DeepCopyInto(out *ApisixRouteHTTPMatchExpr) { + *out = *in + out.Subject = in.Subject + if in.Set != nil { + in, out := &in.Set, &out.Set + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteHTTPMatchExpr. +func (in *ApisixRouteHTTPMatchExpr) DeepCopy() *ApisixRouteHTTPMatchExpr { + if in == nil { + return nil + } + out := new(ApisixRouteHTTPMatchExpr) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteHTTPMatchExprSubject) DeepCopyInto(out *ApisixRouteHTTPMatchExprSubject) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteHTTPMatchExprSubject. +func (in *ApisixRouteHTTPMatchExprSubject) DeepCopy() *ApisixRouteHTTPMatchExprSubject { + if in == nil { + return nil + } + out := new(ApisixRouteHTTPMatchExprSubject) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteList) DeepCopyInto(out *ApisixRouteList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ApisixRoute, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteList. +func (in *ApisixRouteList) DeepCopy() *ApisixRouteList { + if in == nil { + return nil + } + out := new(ApisixRouteList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ApisixRouteList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRoutePlugin) DeepCopyInto(out *ApisixRoutePlugin) { + *out = *in + in.Config.DeepCopyInto(&out.Config) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRoutePlugin. +func (in *ApisixRoutePlugin) DeepCopy() *ApisixRoutePlugin { + if in == nil { + return nil + } + out := new(ApisixRoutePlugin) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteSpec) DeepCopyInto(out *ApisixRouteSpec) { + *out = *in + if in.HTTP != nil { + in, out := &in.HTTP, &out.HTTP + *out = make([]ApisixRouteHTTP, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Stream != nil { + in, out := &in.Stream, &out.Stream + *out = make([]ApisixRouteStream, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteSpec. +func (in *ApisixRouteSpec) DeepCopy() *ApisixRouteSpec { + if in == nil { + return nil + } + out := new(ApisixRouteSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteStream) DeepCopyInto(out *ApisixRouteStream) { + *out = *in + out.Match = in.Match + out.Backend = in.Backend + if in.Plugins != nil { + in, out := &in.Plugins, &out.Plugins + *out = make([]ApisixRoutePlugin, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteStream. +func (in *ApisixRouteStream) DeepCopy() *ApisixRouteStream { + if in == nil { + return nil + } + out := new(ApisixRouteStream) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteStreamBackend) DeepCopyInto(out *ApisixRouteStreamBackend) { + *out = *in + out.ServicePort = in.ServicePort + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteStreamBackend. +func (in *ApisixRouteStreamBackend) DeepCopy() *ApisixRouteStreamBackend { + if in == nil { + return nil + } + out := new(ApisixRouteStreamBackend) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixRouteStreamMatch) DeepCopyInto(out *ApisixRouteStreamMatch) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixRouteStreamMatch. +func (in *ApisixRouteStreamMatch) DeepCopy() *ApisixRouteStreamMatch { + if in == nil { + return nil + } + out := new(ApisixRouteStreamMatch) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApisixStatus) DeepCopyInto(out *ApisixStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApisixStatus. +func (in *ApisixStatus) DeepCopy() *ApisixStatus { + if in == nil { + return nil + } + out := new(ApisixStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *UpstreamTimeout) DeepCopyInto(out *UpstreamTimeout) { + *out = *in + out.Connect = in.Connect + out.Send = in.Send + out.Read = in.Read + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UpstreamTimeout. +func (in *UpstreamTimeout) DeepCopy() *UpstreamTimeout { + if in == nil { + return nil + } + out := new(UpstreamTimeout) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/apis/flagger/v1beta1/canary.go b/pkg/apis/flagger/v1beta1/canary.go index d1077cd6..fe77e497 100644 --- a/pkg/apis/flagger/v1beta1/canary.go +++ b/pkg/apis/flagger/v1beta1/canary.go @@ -80,6 +80,10 @@ type CanarySpec struct { // +optional IngressRef *LocalObjectReference `json:"ingressRef,omitempty"` + // Reference to APISIX route resource + // +optional + RouteRef *LocalObjectReference `json:"routeRef,omitempty"` + // Reference to Gloo Upstream resource. Upstream config is copied from // the referenced upstream to the upstreams generated by flagger. // +optional diff --git a/pkg/apis/flagger/v1beta1/provider.go b/pkg/apis/flagger/v1beta1/provider.go index 64f7a1c4..bc93c6de 100644 --- a/pkg/apis/flagger/v1beta1/provider.go +++ b/pkg/apis/flagger/v1beta1/provider.go @@ -1,6 +1,7 @@ package v1beta1 const ( + ApisixProvider string = "apisix" AppMeshProvider string = "appmesh" LinkerdProvider string = "linkerd" IstioProvider string = "istio" diff --git a/pkg/apis/flagger/v1beta1/zz_generated.deepcopy.go b/pkg/apis/flagger/v1beta1/zz_generated.deepcopy.go index 7f98b59d..a34b8e4c 100644 --- a/pkg/apis/flagger/v1beta1/zz_generated.deepcopy.go +++ b/pkg/apis/flagger/v1beta1/zz_generated.deepcopy.go @@ -458,6 +458,11 @@ func (in *CanarySpec) DeepCopyInto(out *CanarySpec) { *out = new(LocalObjectReference) **out = **in } + if in.RouteRef != nil { + in, out := &in.RouteRef, &out.RouteRef + *out = new(LocalObjectReference) + **out = **in + } if in.UpstreamRef != nil { in, out := &in.UpstreamRef, &out.UpstreamRef *out = new(CrossNamespaceObjectReference) diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index 22b70bde..9a3eb61d 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -22,6 +22,7 @@ import ( "fmt" "net/http" + apisixv2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/apisix/v2" appmeshv1beta1 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/appmesh/v1beta1" appmeshv1beta2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/appmesh/v1beta2" flaggerv1beta1 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/flagger/v1beta1" @@ -44,6 +45,7 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface + ApisixV2() apisixv2.ApisixV2Interface AppmeshV1beta2() appmeshv1beta2.AppmeshV1beta2Interface AppmeshV1beta1() appmeshv1beta1.AppmeshV1beta1Interface FlaggerV1beta1() flaggerv1beta1.FlaggerV1beta1Interface @@ -65,6 +67,7 @@ type Interface interface { // version included in a Clientset. type Clientset struct { *discovery.DiscoveryClient + apisixV2 *apisixv2.ApisixV2Client appmeshV1beta2 *appmeshv1beta2.AppmeshV1beta2Client appmeshV1beta1 *appmeshv1beta1.AppmeshV1beta1Client flaggerV1beta1 *flaggerv1beta1.FlaggerV1beta1Client @@ -82,6 +85,11 @@ type Clientset struct { traefikV1alpha1 *traefikv1alpha1.TraefikV1alpha1Client } +// ApisixV2 retrieves the ApisixV2Client +func (c *Clientset) ApisixV2() apisixv2.ApisixV2Interface { + return c.apisixV2 +} + // AppmeshV1beta2 retrieves the AppmeshV1beta2Client func (c *Clientset) AppmeshV1beta2() appmeshv1beta2.AppmeshV1beta2Interface { return c.appmeshV1beta2 @@ -201,6 +209,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, var cs Clientset var err error + cs.apisixV2, err = apisixv2.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.appmeshV1beta2, err = appmeshv1beta2.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err @@ -282,6 +294,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { // New creates a new Clientset for the given RESTClient. func New(c rest.Interface) *Clientset { var cs Clientset + cs.apisixV2 = apisixv2.New(c) cs.appmeshV1beta2 = appmeshv1beta2.New(c) cs.appmeshV1beta1 = appmeshv1beta1.New(c) cs.flaggerV1beta1 = flaggerv1beta1.New(c) diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 6c359fc9..e0f760b2 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -20,6 +20,8 @@ package fake import ( clientset "github.com/fluxcd/flagger/pkg/client/clientset/versioned" + apisixv2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/apisix/v2" + fakeapisixv2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/apisix/v2/fake" appmeshv1beta1 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/appmesh/v1beta1" fakeappmeshv1beta1 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/appmesh/v1beta1/fake" appmeshv1beta2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/appmesh/v1beta2" @@ -107,6 +109,11 @@ var ( _ testing.FakeClient = &Clientset{} ) +// ApisixV2 retrieves the ApisixV2Client +func (c *Clientset) ApisixV2() apisixv2.ApisixV2Interface { + return &fakeapisixv2.FakeApisixV2{Fake: &c.Fake} +} + // AppmeshV1beta2 retrieves the AppmeshV1beta2Client func (c *Clientset) AppmeshV1beta2() appmeshv1beta2.AppmeshV1beta2Interface { return &fakeappmeshv1beta2.FakeAppmeshV1beta2{Fake: &c.Fake} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 5e222e0a..83f13e2d 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -19,6 +19,7 @@ limitations under the License. package fake import ( + apisixv2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" appmeshv1beta1 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta1" appmeshv1beta2 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta2" flaggerv1beta1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" @@ -45,6 +46,7 @@ var scheme = runtime.NewScheme() var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ + apisixv2.AddToScheme, appmeshv1beta2.AddToScheme, appmeshv1beta1.AddToScheme, flaggerv1beta1.AddToScheme, diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index aa44edb5..d31f39e9 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -19,6 +19,7 @@ limitations under the License. package scheme import ( + apisixv2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" appmeshv1beta1 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta1" appmeshv1beta2 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta2" flaggerv1beta1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" @@ -45,6 +46,7 @@ var Scheme = runtime.NewScheme() var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ + apisixv2.AddToScheme, appmeshv1beta2.AddToScheme, appmeshv1beta1.AddToScheme, flaggerv1beta1.AddToScheme, diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/apisix_client.go b/pkg/client/clientset/versioned/typed/apisix/v2/apisix_client.go new file mode 100644 index 00000000..7f3dbe9c --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/apisix_client.go @@ -0,0 +1,107 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v2 + +import ( + "net/http" + + v2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + "github.com/fluxcd/flagger/pkg/client/clientset/versioned/scheme" + rest "k8s.io/client-go/rest" +) + +type ApisixV2Interface interface { + RESTClient() rest.Interface + ApisixRoutesGetter +} + +// ApisixV2Client is used to interact with features provided by the apisix.apache.org group. +type ApisixV2Client struct { + restClient rest.Interface +} + +func (c *ApisixV2Client) ApisixRoutes(namespace string) ApisixRouteInterface { + return newApisixRoutes(c, namespace) +} + +// NewForConfig creates a new ApisixV2Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*ApisixV2Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new ApisixV2Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ApisixV2Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &ApisixV2Client{client}, nil +} + +// NewForConfigOrDie creates a new ApisixV2Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *ApisixV2Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new ApisixV2Client for the given RESTClient. +func New(c rest.Interface) *ApisixV2Client { + return &ApisixV2Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v2.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *ApisixV2Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/apisixroute.go b/pkg/client/clientset/versioned/typed/apisix/v2/apisixroute.go new file mode 100644 index 00000000..bc463592 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/apisixroute.go @@ -0,0 +1,195 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v2 + +import ( + "context" + "time" + + v2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + scheme "github.com/fluxcd/flagger/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ApisixRoutesGetter has a method to return a ApisixRouteInterface. +// A group's client should implement this interface. +type ApisixRoutesGetter interface { + ApisixRoutes(namespace string) ApisixRouteInterface +} + +// ApisixRouteInterface has methods to work with ApisixRoute resources. +type ApisixRouteInterface interface { + Create(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.CreateOptions) (*v2.ApisixRoute, error) + Update(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (*v2.ApisixRoute, error) + UpdateStatus(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (*v2.ApisixRoute, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v2.ApisixRoute, error) + List(ctx context.Context, opts v1.ListOptions) (*v2.ApisixRouteList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.ApisixRoute, err error) + ApisixRouteExpansion +} + +// apisixRoutes implements ApisixRouteInterface +type apisixRoutes struct { + client rest.Interface + ns string +} + +// newApisixRoutes returns a ApisixRoutes +func newApisixRoutes(c *ApisixV2Client, namespace string) *apisixRoutes { + return &apisixRoutes{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the apisixRoute, and returns the corresponding apisixRoute object, and an error if there is any. +func (c *apisixRoutes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2.ApisixRoute, err error) { + result = &v2.ApisixRoute{} + err = c.client.Get(). + Namespace(c.ns). + Resource("apisixroutes"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ApisixRoutes that match those selectors. +func (c *apisixRoutes) List(ctx context.Context, opts v1.ListOptions) (result *v2.ApisixRouteList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v2.ApisixRouteList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("apisixroutes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested apisixRoutes. +func (c *apisixRoutes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("apisixroutes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a apisixRoute and creates it. Returns the server's representation of the apisixRoute, and an error, if there is any. +func (c *apisixRoutes) Create(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.CreateOptions) (result *v2.ApisixRoute, err error) { + result = &v2.ApisixRoute{} + err = c.client.Post(). + Namespace(c.ns). + Resource("apisixroutes"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(apisixRoute). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a apisixRoute and updates it. Returns the server's representation of the apisixRoute, and an error, if there is any. +func (c *apisixRoutes) Update(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (result *v2.ApisixRoute, err error) { + result = &v2.ApisixRoute{} + err = c.client.Put(). + Namespace(c.ns). + Resource("apisixroutes"). + Name(apisixRoute.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(apisixRoute). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *apisixRoutes) UpdateStatus(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (result *v2.ApisixRoute, err error) { + result = &v2.ApisixRoute{} + err = c.client.Put(). + Namespace(c.ns). + Resource("apisixroutes"). + Name(apisixRoute.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(apisixRoute). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the apisixRoute and deletes it. Returns an error if one occurs. +func (c *apisixRoutes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("apisixroutes"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *apisixRoutes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("apisixroutes"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched apisixRoute. +func (c *apisixRoutes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.ApisixRoute, err error) { + result = &v2.ApisixRoute{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("apisixroutes"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/doc.go b/pkg/client/clientset/versioned/typed/apisix/v2/doc.go new file mode 100644 index 00000000..3c471d4a --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v2 diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/fake/doc.go b/pkg/client/clientset/versioned/typed/apisix/v2/fake/doc.go new file mode 100644 index 00000000..1ccd9119 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/fake/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisix_client.go b/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisix_client.go new file mode 100644 index 00000000..a8f624c3 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisix_client.go @@ -0,0 +1,40 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v2 "github.com/fluxcd/flagger/pkg/client/clientset/versioned/typed/apisix/v2" + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" +) + +type FakeApisixV2 struct { + *testing.Fake +} + +func (c *FakeApisixV2) ApisixRoutes(namespace string) v2.ApisixRouteInterface { + return &FakeApisixRoutes{c, namespace} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeApisixV2) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisixroute.go b/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisixroute.go new file mode 100644 index 00000000..ba55e7b3 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/fake/fake_apisixroute.go @@ -0,0 +1,142 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeApisixRoutes implements ApisixRouteInterface +type FakeApisixRoutes struct { + Fake *FakeApisixV2 + ns string +} + +var apisixroutesResource = schema.GroupVersionResource{Group: "apisix.apache.org", Version: "v2", Resource: "apisixroutes"} + +var apisixroutesKind = schema.GroupVersionKind{Group: "apisix.apache.org", Version: "v2", Kind: "ApisixRoute"} + +// Get takes name of the apisixRoute, and returns the corresponding apisixRoute object, and an error if there is any. +func (c *FakeApisixRoutes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2.ApisixRoute, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(apisixroutesResource, c.ns, name), &v2.ApisixRoute{}) + + if obj == nil { + return nil, err + } + return obj.(*v2.ApisixRoute), err +} + +// List takes label and field selectors, and returns the list of ApisixRoutes that match those selectors. +func (c *FakeApisixRoutes) List(ctx context.Context, opts v1.ListOptions) (result *v2.ApisixRouteList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(apisixroutesResource, apisixroutesKind, c.ns, opts), &v2.ApisixRouteList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v2.ApisixRouteList{ListMeta: obj.(*v2.ApisixRouteList).ListMeta} + for _, item := range obj.(*v2.ApisixRouteList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested apisixRoutes. +func (c *FakeApisixRoutes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(apisixroutesResource, c.ns, opts)) + +} + +// Create takes the representation of a apisixRoute and creates it. Returns the server's representation of the apisixRoute, and an error, if there is any. +func (c *FakeApisixRoutes) Create(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.CreateOptions) (result *v2.ApisixRoute, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(apisixroutesResource, c.ns, apisixRoute), &v2.ApisixRoute{}) + + if obj == nil { + return nil, err + } + return obj.(*v2.ApisixRoute), err +} + +// Update takes the representation of a apisixRoute and updates it. Returns the server's representation of the apisixRoute, and an error, if there is any. +func (c *FakeApisixRoutes) Update(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (result *v2.ApisixRoute, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(apisixroutesResource, c.ns, apisixRoute), &v2.ApisixRoute{}) + + if obj == nil { + return nil, err + } + return obj.(*v2.ApisixRoute), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeApisixRoutes) UpdateStatus(ctx context.Context, apisixRoute *v2.ApisixRoute, opts v1.UpdateOptions) (*v2.ApisixRoute, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(apisixroutesResource, "status", c.ns, apisixRoute), &v2.ApisixRoute{}) + + if obj == nil { + return nil, err + } + return obj.(*v2.ApisixRoute), err +} + +// Delete takes name of the apisixRoute and deletes it. Returns an error if one occurs. +func (c *FakeApisixRoutes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteActionWithOptions(apisixroutesResource, c.ns, name, opts), &v2.ApisixRoute{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeApisixRoutes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(apisixroutesResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &v2.ApisixRouteList{}) + return err +} + +// Patch applies the patch and returns the patched apisixRoute. +func (c *FakeApisixRoutes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.ApisixRoute, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(apisixroutesResource, c.ns, name, pt, data, subresources...), &v2.ApisixRoute{}) + + if obj == nil { + return nil, err + } + return obj.(*v2.ApisixRoute), err +} diff --git a/pkg/client/clientset/versioned/typed/apisix/v2/generated_expansion.go b/pkg/client/clientset/versioned/typed/apisix/v2/generated_expansion.go new file mode 100644 index 00000000..e136dfb6 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/apisix/v2/generated_expansion.go @@ -0,0 +1,21 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v2 + +type ApisixRouteExpansion interface{} diff --git a/pkg/client/informers/externalversions/apisix/interface.go b/pkg/client/informers/externalversions/apisix/interface.go new file mode 100644 index 00000000..e2402af5 --- /dev/null +++ b/pkg/client/informers/externalversions/apisix/interface.go @@ -0,0 +1,46 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package apisix + +import ( + v2 "github.com/fluxcd/flagger/pkg/client/informers/externalversions/apisix/v2" + internalinterfaces "github.com/fluxcd/flagger/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to each of this group's versions. +type Interface interface { + // V2 provides access to shared informers for resources in V2. + V2() v2.Interface +} + +type group struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// V2 returns a new v2.Interface. +func (g *group) V2() v2.Interface { + return v2.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/pkg/client/informers/externalversions/apisix/v2/apisixroute.go b/pkg/client/informers/externalversions/apisix/v2/apisixroute.go new file mode 100644 index 00000000..e26e8b1a --- /dev/null +++ b/pkg/client/informers/externalversions/apisix/v2/apisixroute.go @@ -0,0 +1,90 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v2 + +import ( + "context" + time "time" + + apisixv2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + versioned "github.com/fluxcd/flagger/pkg/client/clientset/versioned" + internalinterfaces "github.com/fluxcd/flagger/pkg/client/informers/externalversions/internalinterfaces" + v2 "github.com/fluxcd/flagger/pkg/client/listers/apisix/v2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// ApisixRouteInformer provides access to a shared informer and lister for +// ApisixRoutes. +type ApisixRouteInformer interface { + Informer() cache.SharedIndexInformer + Lister() v2.ApisixRouteLister +} + +type apisixRouteInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewApisixRouteInformer constructs a new informer for ApisixRoute type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewApisixRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredApisixRouteInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredApisixRouteInformer constructs a new informer for ApisixRoute type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredApisixRouteInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ApisixV2().ApisixRoutes(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ApisixV2().ApisixRoutes(namespace).Watch(context.TODO(), options) + }, + }, + &apisixv2.ApisixRoute{}, + resyncPeriod, + indexers, + ) +} + +func (f *apisixRouteInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredApisixRouteInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *apisixRouteInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apisixv2.ApisixRoute{}, f.defaultInformer) +} + +func (f *apisixRouteInformer) Lister() v2.ApisixRouteLister { + return v2.NewApisixRouteLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/apisix/v2/interface.go b/pkg/client/informers/externalversions/apisix/v2/interface.go new file mode 100644 index 00000000..b322ea86 --- /dev/null +++ b/pkg/client/informers/externalversions/apisix/v2/interface.go @@ -0,0 +1,45 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v2 + +import ( + internalinterfaces "github.com/fluxcd/flagger/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // ApisixRoutes returns a ApisixRouteInformer. + ApisixRoutes() ApisixRouteInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// ApisixRoutes returns a ApisixRouteInformer. +func (v *version) ApisixRoutes() ApisixRouteInformer { + return &apisixRouteInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/pkg/client/informers/externalversions/factory.go b/pkg/client/informers/externalversions/factory.go index 19eed677..eb4172e7 100644 --- a/pkg/client/informers/externalversions/factory.go +++ b/pkg/client/informers/externalversions/factory.go @@ -24,6 +24,7 @@ import ( time "time" versioned "github.com/fluxcd/flagger/pkg/client/clientset/versioned" + apisix "github.com/fluxcd/flagger/pkg/client/informers/externalversions/apisix" appmesh "github.com/fluxcd/flagger/pkg/client/informers/externalversions/appmesh" flagger "github.com/fluxcd/flagger/pkg/client/informers/externalversions/flagger" gateway "github.com/fluxcd/flagger/pkg/client/informers/externalversions/gateway" @@ -182,6 +183,7 @@ type SharedInformerFactory interface { ForResource(resource schema.GroupVersionResource) (GenericInformer, error) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool + Apisix() apisix.Interface Appmesh() appmesh.Interface Flagger() flagger.Interface Gateway() gateway.Interface @@ -195,6 +197,10 @@ type SharedInformerFactory interface { Traefik() traefik.Interface } +func (f *sharedInformerFactory) Apisix() apisix.Interface { + return apisix.New(f, f.namespace, f.tweakListOptions) +} + func (f *sharedInformerFactory) Appmesh() appmesh.Interface { return appmesh.New(f, f.namespace, f.tweakListOptions) } diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index c6ca5a17..8264c3f3 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -21,6 +21,7 @@ package externalversions import ( "fmt" + v2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" v1beta1 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta1" v1beta2 "github.com/fluxcd/flagger/pkg/apis/appmesh/v1beta2" flaggerv1beta1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" @@ -66,7 +67,11 @@ func (f *genericInformer) Lister() cache.GenericLister { // TODO extend this to unknown resources with a client pool func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { - // Group=appmesh.k8s.aws, Version=v1beta1 + // Group=apisix.apache.org, Version=v2 + case v2.SchemeGroupVersion.WithResource("apisixroutes"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Apisix().V2().ApisixRoutes().Informer()}, nil + + // Group=appmesh.k8s.aws, Version=v1beta1 case v1beta1.SchemeGroupVersion.WithResource("meshes"): return &genericInformer{resource: resource.GroupResource(), informer: f.Appmesh().V1beta1().Meshes().Informer()}, nil case v1beta1.SchemeGroupVersion.WithResource("virtualnodes"): diff --git a/pkg/client/listers/apisix/v2/apisixroute.go b/pkg/client/listers/apisix/v2/apisixroute.go new file mode 100644 index 00000000..a3e6183f --- /dev/null +++ b/pkg/client/listers/apisix/v2/apisixroute.go @@ -0,0 +1,99 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v2 + +import ( + v2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// ApisixRouteLister helps list ApisixRoutes. +// All objects returned here must be treated as read-only. +type ApisixRouteLister interface { + // List lists all ApisixRoutes in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v2.ApisixRoute, err error) + // ApisixRoutes returns an object that can list and get ApisixRoutes. + ApisixRoutes(namespace string) ApisixRouteNamespaceLister + ApisixRouteListerExpansion +} + +// apisixRouteLister implements the ApisixRouteLister interface. +type apisixRouteLister struct { + indexer cache.Indexer +} + +// NewApisixRouteLister returns a new ApisixRouteLister. +func NewApisixRouteLister(indexer cache.Indexer) ApisixRouteLister { + return &apisixRouteLister{indexer: indexer} +} + +// List lists all ApisixRoutes in the indexer. +func (s *apisixRouteLister) List(selector labels.Selector) (ret []*v2.ApisixRoute, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v2.ApisixRoute)) + }) + return ret, err +} + +// ApisixRoutes returns an object that can list and get ApisixRoutes. +func (s *apisixRouteLister) ApisixRoutes(namespace string) ApisixRouteNamespaceLister { + return apisixRouteNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// ApisixRouteNamespaceLister helps list and get ApisixRoutes. +// All objects returned here must be treated as read-only. +type ApisixRouteNamespaceLister interface { + // List lists all ApisixRoutes in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v2.ApisixRoute, err error) + // Get retrieves the ApisixRoute from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v2.ApisixRoute, error) + ApisixRouteNamespaceListerExpansion +} + +// apisixRouteNamespaceLister implements the ApisixRouteNamespaceLister +// interface. +type apisixRouteNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all ApisixRoutes in the indexer for a given namespace. +func (s apisixRouteNamespaceLister) List(selector labels.Selector) (ret []*v2.ApisixRoute, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v2.ApisixRoute)) + }) + return ret, err +} + +// Get retrieves the ApisixRoute from the indexer for a given namespace and name. +func (s apisixRouteNamespaceLister) Get(name string) (*v2.ApisixRoute, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v2.Resource("apisixroute"), name) + } + return obj.(*v2.ApisixRoute), nil +} diff --git a/pkg/client/listers/apisix/v2/expansion_generated.go b/pkg/client/listers/apisix/v2/expansion_generated.go new file mode 100644 index 00000000..fc2b058b --- /dev/null +++ b/pkg/client/listers/apisix/v2/expansion_generated.go @@ -0,0 +1,27 @@ +/* +Copyright 2020 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v2 + +// ApisixRouteListerExpansion allows custom methods to be added to +// ApisixRouteLister. +type ApisixRouteListerExpansion interface{} + +// ApisixRouteNamespaceListerExpansion allows custom methods to be added to +// ApisixRouteNamespaceLister. +type ApisixRouteNamespaceListerExpansion interface{} diff --git a/pkg/metrics/observers/apisix.go b/pkg/metrics/observers/apisix.go new file mode 100644 index 00000000..80050310 --- /dev/null +++ b/pkg/metrics/observers/apisix.go @@ -0,0 +1,90 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package observers + +import ( + "fmt" + "time" + + flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" + "github.com/fluxcd/flagger/pkg/metrics/providers" +) + +var apisixQueries = map[string]string{ + "request-success-rate": ` + sum( + rate( + apisix_http_status{ + route=~"{{ namespace }}_{{ target }}-canary_.+", + code!~"5.." + }[{{ interval }}] + ) + ) + / + sum( + rate( + apisix_http_status{ + route=~"{{ namespace }}_{{ target }}-canary_.+" + }[{{ interval }}] + ) + ) * 100`, + "request-duration": ` + histogram_quantile( + 0.99, + sum( + rate( + apisix_http_latency_bucket{ + type=~"request", + route=~"{{ namespace }}_{{ target }}-canary_.+" + }[{{ interval }}] + ) + ) by (le) + )`, +} + +type ApisixObserver struct { + client providers.Interface +} + +func (ob *ApisixObserver) GetRequestSuccessRate(model flaggerv1.MetricTemplateModel) (float64, error) { + + query, err := RenderQuery(apisixQueries["request-success-rate"], model) + if err != nil { + return 0, fmt.Errorf("rendering query failed: %w", err) + } + value, err := ob.client.RunQuery(query) + if err != nil { + return 0, fmt.Errorf("running query failed: %w", err) + } + + return value, nil +} + +func (ob *ApisixObserver) GetRequestDuration(model flaggerv1.MetricTemplateModel) (time.Duration, error) { + query, err := RenderQuery(apisixQueries["request-duration"], model) + if err != nil { + return 0, fmt.Errorf("rendering query failed: %w", err) + } + + value, err := ob.client.RunQuery(query) + if err != nil { + return 0, fmt.Errorf("running query failed: %w", err) + } + + ms := time.Duration(int64(value)) * time.Millisecond + return ms, nil +} diff --git a/pkg/metrics/observers/apisix_test.go b/pkg/metrics/observers/apisix_test.go new file mode 100644 index 00000000..1e09c6f4 --- /dev/null +++ b/pkg/metrics/observers/apisix_test.go @@ -0,0 +1,117 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package observers + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" + "github.com/fluxcd/flagger/pkg/metrics/providers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestApisixObserver_GetRequestSuccessRate(t *testing.T) { + t.Run("ok", func(t *testing.T) { + expected := ` sum( rate( apisix_http_status{ route=~"default_podinfo-canary_.+", code!~"5.." }[1m] ) ) / sum( rate( apisix_http_status{ route=~"default_podinfo-canary_.+" }[1m] ) ) * 100` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + promql := r.URL.Query()["query"][0] + assert.Equal(t, expected, promql) + + json := `{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1,"100"]}]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &ApisixObserver{client: client} + + val, err := observer.GetRequestSuccessRate(flaggerv1.MetricTemplateModel{ + Name: "podinfo", + Namespace: "default", + Target: "podinfo", + Service: "podinfo", + Interval: "1m", + }) + require.NoError(t, err) + + assert.Equal(t, float64(100), val) + }) + + t.Run("no values", func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json := `{"status":"success","data":{"resultType":"vector","result":[]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &ApisixObserver{client: client} + _, err = observer.GetRequestSuccessRate(flaggerv1.MetricTemplateModel{}) + require.True(t, errors.Is(err, providers.ErrNoValuesFound)) + }) +} + +func TestApisixObserver_GetRequestDuration(t *testing.T) { + expected := ` histogram_quantile( 0.99, sum( rate( apisix_http_latency_bucket{ type=~"request", route=~"default_podinfo-canary_.+" }[1m] ) ) by (le) )` + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + promql := r.URL.Query()["query"][0] + assert.Equal(t, expected, promql) + + json := `{"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1,"100"]}]}}` + w.Write([]byte(json)) + })) + defer ts.Close() + + client, err := providers.NewPrometheusProvider(flaggerv1.MetricTemplateProvider{ + Type: "prometheus", + Address: ts.URL, + SecretRef: nil, + }, nil) + require.NoError(t, err) + + observer := &ApisixObserver{client: client} + + val, err := observer.GetRequestDuration(flaggerv1.MetricTemplateModel{ + Name: "podinfo", + Namespace: "default", + Target: "podinfo", + Service: "podinfo", + Interval: "1m", + }) + require.NoError(t, err) + + assert.Equal(t, 100*time.Millisecond, val) +} diff --git a/pkg/metrics/observers/factory.go b/pkg/metrics/observers/factory.go index 917bc9ab..044f68f5 100644 --- a/pkg/metrics/observers/factory.go +++ b/pkg/metrics/observers/factory.go @@ -88,6 +88,10 @@ func (factory Factory) Observer(provider string) Interface { return &KumaObserver{ client: factory.Client, } + case provider == flaggerv1.ApisixProvider: + return &ApisixObserver{ + client: factory.Client, + } default: return &IstioObserver{ client: factory.Client, diff --git a/pkg/router/apisix.go b/pkg/router/apisix.go new file mode 100644 index 00000000..ddc0b69e --- /dev/null +++ b/pkg/router/apisix.go @@ -0,0 +1,184 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package router + +import ( + "context" + "fmt" + + apisixv2 "github.com/fluxcd/flagger/pkg/apis/apisix/v2" + flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" + clientset "github.com/fluxcd/flagger/pkg/client/clientset/versioned" + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// ApisixRouter is managing Apisix Route +type ApisixRouter struct { + apisixClient clientset.Interface + logger *zap.SugaredLogger + setOwnerRefs bool +} + +const maxPriority = 10000 + +// Reconcile creates or updates the Apisix Route +func (ar *ApisixRouter) Reconcile(canary *flaggerv1.Canary) error { + if canary.Spec.RouteRef == nil || canary.Spec.RouteRef.Name == "" { + return fmt.Errorf("apisix route selector is empty") + } + + apisixRoute, err := ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Get(context.TODO(), canary.Spec.RouteRef.Name, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("apisix route %s.%s get query error: %w", canary.Spec.RouteRef.Name, canary.Namespace, err) + } + + apisixRouteClone := apisixRoute.DeepCopy() + if len(apisixRouteClone.Spec.HTTP) != 1 && len(apisixRouteClone.Spec.HTTP[0].Backends) != 1 { + return fmt.Errorf("apisix route %s.%s only one http backend is supported", canary.Spec.RouteRef.Name, canary.Namespace) + } + + httpBackend := apisixRouteClone.Spec.HTTP[0] + httpBackend.Priority = maxPriority + + _, primaryName, canaryName := canary.GetServiceNames() + + primaryBackend := httpBackend.Backends[0] + primaryBackend.ServiceName = primaryName + primaryWeight := 100 + primaryBackend.Weight = &primaryWeight + httpBackend.Backends[0] = primaryBackend + + canaryWeight := 0 + canaryBackend := apisixv2.ApisixRouteHTTPBackend{ + ServiceName: canaryName, + ServicePort: primaryBackend.ServicePort, + ResolveGranularity: primaryBackend.ResolveGranularity, + Weight: &canaryWeight, + Subset: primaryBackend.Subset, + } + httpBackend.Backends = append(httpBackend.Backends, canaryBackend) + + apisixRouteClone.Spec.HTTP[0] = httpBackend + canaryApisixRouteName := fmt.Sprintf("%s-canary", canary.Spec.RouteRef.Name) + _, err = ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Get(context.TODO(), canaryApisixRouteName, metav1.GetOptions{}) + + if errors.IsNotFound(err) { + route := &apisixv2.ApisixRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: canaryApisixRouteName, + Namespace: canary.Namespace, + Annotations: apisixRouteClone.Annotations, + Labels: apisixRouteClone.Labels, + }, + Spec: apisixRouteClone.Spec, + } + + if ar.setOwnerRefs { + route.OwnerReferences = []metav1.OwnerReference{ + *metav1.NewControllerRef(canary, schema.GroupVersionKind{ + Group: flaggerv1.SchemeGroupVersion.Group, + Version: flaggerv1.SchemeGroupVersion.Version, + Kind: flaggerv1.CanaryKind, + }), + } + } + + _, err := ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Create(context.TODO(), route, metav1.CreateOptions{}) + if err != nil { + return fmt.Errorf("apisix route %s.%s create error: %w", route.Name, route.Namespace, err) + } + + ar.logger.With("canary", fmt.Sprintf("%s.%s", canary.Name, canary.Namespace)). + Infof("apisix route %s.%s created", route.GetName(), canary.Namespace) + return nil + } else if err != nil { + return fmt.Errorf("apisix route %s.%s query error: %w", canaryApisixRouteName, canary.Namespace, err) + } + + //TODO diff + + return nil +} + +// GetRoutes returns the destinations weight for primary and canary +func (ar *ApisixRouter) GetRoutes(canary *flaggerv1.Canary) ( + primaryWeight int, + canaryWeight int, + mirrored bool, + err error, +) { + canaryApisixRouteName := fmt.Sprintf("%s-canary", canary.Spec.RouteRef.Name) + apisixRoute, err := ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Get(context.TODO(), canaryApisixRouteName, metav1.GetOptions{}) + if err != nil { + err = fmt.Errorf("apisix route %s.%s query error: %w", canaryApisixRouteName, canary.Namespace, err) + return + } + _, primaryName, _ := canary.GetServiceNames() + + for _, backend := range apisixRoute.Spec.HTTP[0].Backends { + if backend.ServiceName == primaryName { + primaryWeight = *backend.Weight + canaryWeight = 100 - primaryWeight + return + } + } + + return +} + +// SetRoutes updates the destinations weight for primary and canary +func (ar *ApisixRouter) SetRoutes( + canary *flaggerv1.Canary, + primaryWeight int, + canaryWeight int, + _ bool, +) error { + apexName, primaryName, canaryName := canary.GetServiceNames() + + if primaryWeight == 0 && canaryWeight == 0 { + return fmt.Errorf("RoutingRule %s.%s update failed: no valid weights", apexName, canary.Namespace) + } + + canaryApisixRouteName := fmt.Sprintf("%s-canary", canary.Spec.RouteRef.Name) + apisixRoute, err := ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Get(context.TODO(), canaryApisixRouteName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("apisix route %s.%s query error: %w", canaryApisixRouteName, canary.Namespace, err) + } + + backends := apisixRoute.Spec.HTTP[0].Backends + for i, backend := range backends { + if backend.ServiceName == primaryName { + backends[i].Weight = &primaryWeight + } else if backend.ServiceName == canaryName { + backends[i].Weight = &canaryWeight + } + } + apisixRoute.Spec.HTTP[0].Backends = backends + + _, err = ar.apisixClient.ApisixV2().ApisixRoutes(canary.Namespace).Update(context.TODO(), apisixRoute, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("apisix route %s.%s update error: %w", apexName, canary.Namespace, err) + } + return nil +} + +func (ar *ApisixRouter) Finalize(_ *flaggerv1.Canary) error { + return nil +} diff --git a/pkg/router/apisix_test.go b/pkg/router/apisix_test.go new file mode 100644 index 00000000..a405062b --- /dev/null +++ b/pkg/router/apisix_test.go @@ -0,0 +1,33 @@ +/* +Copyright 2022 The Flux authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package router + +import ( + "testing" +) + +func TestApisixRouter_Reconcile(t *testing.T) { + // TODO +} + +func TestApisixRouter_SetRoutes(t *testing.T) { + // TODO +} + +func TestApisixRouter_GetRoutes(t *testing.T) { + // TODO +} diff --git a/pkg/router/factory.go b/pkg/router/factory.go index ab64d5e0..e4f1a8b6 100644 --- a/pkg/router/factory.go +++ b/pkg/router/factory.go @@ -177,6 +177,12 @@ func (factory *Factory) MeshRouter(provider string, labelSelector string) Interf traefikClient: factory.meshClient, setOwnerRefs: factory.setOwnerRefs, } + case provider == flaggerv1.ApisixProvider: + return &ApisixRouter{ + logger: factory.logger, + apisixClient: factory.meshClient, + setOwnerRefs: factory.setOwnerRefs, + } case provider == flaggerv1.OsmProvider: return &Smiv1alpha2Router{ logger: factory.logger, diff --git a/pkg/router/router_test.go b/pkg/router/router_test.go index 90b669a6..e81eaba9 100644 --- a/pkg/router/router_test.go +++ b/pkg/router/router_test.go @@ -41,6 +41,7 @@ type fixture struct { abtest *flaggerv1.Canary appmeshCanary *flaggerv1.Canary ingressCanary *flaggerv1.Canary + apisixCanary *flaggerv1.Canary kubeClient kubernetes.Interface meshClient clientset.Interface flaggerClient clientset.Interface