Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions internal/adc/translator/annotations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 translator

import (
"errors"
"fmt"

"github.com/imdario/mergo"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations/plugins"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations/upstream"
)

// Structure extracted by Ingress Resource
type IngressConfig struct {
Upstream upstream.Upstream
Plugins adctypes.Plugins
}

var ingressAnnotationParsers = map[string]annotations.IngressAnnotationsParser{
"upstream": upstream.NewParser(),
"plugins": plugins.NewParser(),
}

func (t *Translator) TranslateIngressAnnotations(anno map[string]string) *IngressConfig {
if len(anno) == 0 {
return nil
}
ing := &IngressConfig{}
if err := translateAnnotations(anno, ing); err != nil {
t.Log.Error(err, "failed to translate ingress annotations", "annotations", anno)
}
return ing
}

func translateAnnotations(anno map[string]string, dst any) error {
extractor := annotations.NewExtractor(anno)
data := make(map[string]any)
var errs []error

for name, parser := range ingressAnnotationParsers {
out, err := parser.Parse(extractor)
if err != nil {
errs = append(errs, fmt.Errorf("parse %s: %w", name, err))
continue
}
if out != nil {
data[name] = out
}
}

if err := mergo.MapWithOverwrite(dst, data); err != nil {
errs = append(errs, fmt.Errorf("merge: %w", err))
}
return errors.Join(errs...)
}
65 changes: 65 additions & 0 deletions internal/adc/translator/annotations/plugins/plugins.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 plugins

import (
logf "sigs.k8s.io/controller-runtime/pkg/log"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
)

// Handler abstracts the behavior so that the apisix-ingress-controller knows
// how to parse some annotations and convert them to APISIX plugins.
type PluginAnnotationsHandler interface {
// Handle parses the target annotation and converts it to the type-agnostic structure.
// The return value might be nil since some features have an explicit switch, users should
// judge whether Handle is failed by the second error value.
Handle(annotations.Extractor) (any, error)
// PluginName returns a string which indicates the target plugin name in APISIX.
PluginName() string
}

var (
log = logf.Log.WithName("annotations").WithName("plugins").WithName("parser")

handlers = []PluginAnnotationsHandler{
NewRedirectHandler(),
}
)

type plugins struct{}

func NewParser() annotations.IngressAnnotationsParser {
return &plugins{}
}

func (p *plugins) Parse(e annotations.Extractor) (any, error) {
plugins := make(adctypes.Plugins)
for _, handler := range handlers {
out, err := handler.Handle(e)
if err != nil {
log.Error(err, "Failed to handle annotation", "handler", handler.PluginName())
continue
}
if out != nil {
plugins[handler.PluginName()] = out
}
}
if len(plugins) > 0 {
return plugins, nil
}
return nil, nil
}
55 changes: 55 additions & 0 deletions internal/adc/translator/annotations/plugins/redirect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 plugins

import (
"net/http"
"strconv"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
)

type redirect struct{}

// NewRedirectHandler creates a handler to convert
// annotations about redirect control to APISIX redirect plugin.
func NewRedirectHandler() PluginAnnotationsHandler {
return &redirect{}
}

func (r *redirect) PluginName() string {
return "redirect"
}

func (r *redirect) Handle(e annotations.Extractor) (any, error) {
var plugin adctypes.RedirectConfig
plugin.HttpToHttps = e.GetBoolAnnotation(annotations.AnnotationsHttpToHttps)
// To avoid empty redirect plugin config, adding the check about the redirect.
if plugin.HttpToHttps {
return &plugin, nil
}
if uri := e.GetStringAnnotation(annotations.AnnotationsHttpRedirect); uri != "" {
// Transformation fail defaults to 0.
plugin.RetCode, _ = strconv.Atoi(e.GetStringAnnotation(annotations.AnnotationsHttpRedirectCode))
plugin.URI = uri
// Default is http.StatusMovedPermanently, the allowed value is between http.StatusMultipleChoices and http.StatusPermanentRedirect.
if plugin.RetCode < http.StatusMovedPermanently || plugin.RetCode > http.StatusPermanentRedirect {
plugin.RetCode = http.StatusMovedPermanently
}
return &plugin, nil
}
return nil, nil
}
203 changes: 203 additions & 0 deletions internal/adc/translator/annotations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 translator

import (
"errors"
"testing"

"github.com/stretchr/testify/assert"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations/upstream"
)

type mockParser struct {
output any
err error
}

func (m *mockParser) Parse(extractor annotations.Extractor) (any, error) {
return m.output, m.err
}

func TestTranslateAnnotations(t *testing.T) {
tests := []struct {
name string
anno map[string]string
parsers map[string]annotations.IngressAnnotationsParser
expected any
expectErr bool
}{
{
name: "successful parsing",
anno: map[string]string{"key1": "value1"},
parsers: map[string]annotations.IngressAnnotationsParser{
"key1": &mockParser{output: "parsedValue1", err: nil},
},
expected: map[string]any{"key1": "parsedValue1"},
expectErr: false,
},
{
name: "parsing with error",
anno: map[string]string{"key1": "value1"},
parsers: map[string]annotations.IngressAnnotationsParser{
"key1": &mockParser{output: nil, err: errors.New("parse error")},
},
expected: map[string]any{},
expectErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orig := ingressAnnotationParsers
defer func() { ingressAnnotationParsers = orig }()

ingressAnnotationParsers = make(map[string]annotations.IngressAnnotationsParser)
for key, parser := range tt.parsers {
ingressAnnotationParsers[key] = parser
}

dst := make(map[string]any)
err := translateAnnotations(tt.anno, &dst)

if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.expected, dst)
})
}
}

func TestTranslateIngressAnnotations(t *testing.T) {
tests := []struct {
name string
anno map[string]string
expected *IngressConfig
}{
{
name: "no matching annotations",
anno: map[string]string{"upstream": "value1"},
expected: &IngressConfig{},
},
{
name: "invalid scheme",
anno: map[string]string{annotations.AnnotationsUpstreamScheme: "invalid"},
expected: &IngressConfig{},
},
{
name: "http scheme",
anno: map[string]string{annotations.AnnotationsUpstreamScheme: "https"},
expected: &IngressConfig{
Upstream: upstream.Upstream{
Scheme: "https",
},
},
},
{
name: "retries",
anno: map[string]string{annotations.AnnotationsUpstreamRetry: "3"},
expected: &IngressConfig{
Upstream: upstream.Upstream{
Retries: 3,
},
},
},
{
name: "read timeout",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
},
},
},
{
name: "timeouts",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
annotations.AnnotationsUpstreamTimeoutSend: "6s",
annotations.AnnotationsUpstreamTimeoutConnect: "7s",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
TimeoutSend: 6,
TimeoutConnect: 7,
},
},
},
{
name: "timeout/scheme/retries",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
annotations.AnnotationsUpstreamScheme: "http",
annotations.AnnotationsUpstreamRetry: "2",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
Scheme: "http",
Retries: 2,
},
},
},
{
name: "redirect to https",
anno: map[string]string{
annotations.AnnotationsHttpToHttps: "true",
},
expected: &IngressConfig{
Plugins: adctypes.Plugins{
"redirect": &adctypes.RedirectConfig{
HttpToHttps: true,
},
},
},
},
{
name: "redirect to specific uri",
anno: map[string]string{
annotations.AnnotationsHttpRedirect: "/newpath",
annotations.AnnotationsHttpRedirectCode: "301",
},
expected: &IngressConfig{
Plugins: adctypes.Plugins{
"redirect": &adctypes.RedirectConfig{
URI: "/newpath",
RetCode: 301,
},
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
translator := &Translator{}
result := translator.TranslateIngressAnnotations(tt.anno)

assert.NotNil(t, result)
assert.Equal(t, tt.expected, result)
})
}
}
Loading