Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce simplified parsers #2972

Merged
merged 7 commits into from
Jun 3, 2024
Merged
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
115 changes: 115 additions & 0 deletions internal/components/component.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright The OpenTelemetry 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 components

import (
"errors"
"regexp"
"strconv"
"strings"

"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)

var (
GrpcProtocol = "grpc"
HttpProtocol = "http"
UnsetPort int32 = 0
PortNotFoundErr = errors.New("port should not be empty")
)

type PortRetriever interface {
GetPortNum() (int32, error)
GetPortNumOrDefault(logr.Logger, int32) int32
}

type PortBuilderOption func(*corev1.ServicePort)

func WithTargetPort(targetPort int32) PortBuilderOption {
return func(servicePort *corev1.ServicePort) {
servicePort.TargetPort = intstr.FromInt32(targetPort)
}
}

func WithAppProtocol(proto *string) PortBuilderOption {
return func(servicePort *corev1.ServicePort) {
servicePort.AppProtocol = proto
}
}

func WithProtocol(proto corev1.Protocol) PortBuilderOption {
return func(servicePort *corev1.ServicePort) {
servicePort.Protocol = proto
}
}

// ComponentType returns the type for a given component name.
// components have a name like:
// - mycomponent/custom
// - mycomponent
// we extract the "mycomponent" part and see if we have a parser for the component.
func ComponentType(name string) string {
if strings.Contains(name, "/") {
return name[:strings.Index(name, "/")]
}
return name
}

func PortFromEndpoint(endpoint string) (int32, error) {
var err error
var port int64

r := regexp.MustCompile(":[0-9]+")

if r.MatchString(endpoint) {
portStr := r.FindString(endpoint)
cleanedPortStr := strings.Replace(portStr, ":", "", -1)
port, err = strconv.ParseInt(cleanedPortStr, 10, 32)
Copy link
Contributor

Choose a reason for hiding this comment

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

Port numbers are 16-bit integers, so this should really be 16 instead of 32. We should also check if the value isn't negative.

In general, is there a reason not to use https://pkg.go.dev/net#SplitHostPort for parsing here, instead of the regex?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this was copied over from the existing code, but i can swap it :)

Copy link
Contributor Author

@jaronoff97 jaronoff97 May 31, 2024

Choose a reason for hiding this comment

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

actually the problem with net.SplitHostPort is that it doesn't handle the case where it contains a scheme at the beginning (obv not a major issue) but that probably is why it wasn't used initially. The code ends up being the same here actually, so I think I may stick with this just changing to a 16 bit int... actually i think we need to use 32 bits here because otherwise we get an out of range error:

strconv.ParseInt: parsing "65535": value out of range

(ex)


if err != nil {
return 0, err
}
}

if port == 0 {
return 0, PortNotFoundErr
}

return int32(port), err
}

type ComponentPortParser interface {
// Ports returns the service ports parsed based on the exporter's configuration
Ports(logger logr.Logger, config interface{}) ([]corev1.ServicePort, error)

// ParserType returns the name of this parser
ParserType() string

// ParserName is an internal name for the parser
ParserName() string
}

func ConstructServicePort(current *corev1.ServicePort, port int32) corev1.ServicePort {
return corev1.ServicePort{
Name: current.Name,
Port: port,
TargetPort: current.TargetPort,
NodePort: current.NodePort,
AppProtocol: current.AppProtocol,
Protocol: current.Protocol,
}
}
67 changes: 67 additions & 0 deletions internal/components/component_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright The OpenTelemetry 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 components_test

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/open-telemetry/opentelemetry-operator/internal/components"
)

func TestComponentType(t *testing.T) {
for _, tt := range []struct {
desc string
name string
expected string
}{
{"regular case", "myreceiver", "myreceiver"},
{"named instance", "myreceiver/custom", "myreceiver"},
} {
t.Run(tt.desc, func(t *testing.T) {
// test and verify
assert.Equal(t, tt.expected, components.ComponentType(tt.name))
})
}
}

func TestReceiverParsePortFromEndpoint(t *testing.T) {
for _, tt := range []struct {
desc string
endpoint string
expected int
errorExpected bool
}{
{"regular case", "http://localhost:1234", 1234, false},
{"absolute with path", "http://localhost:1234/server-status?auto", 1234, false},
{"no protocol", "0.0.0.0:1234", 1234, false},
{"just port", ":1234", 1234, false},
{"no port at all", "http://localhost", 0, true},
{"overflow", "0.0.0.0:2147483648", 0, true},
} {
t.Run(tt.desc, func(t *testing.T) {
// test
val, err := components.PortFromEndpoint(tt.endpoint)
if tt.errorExpected {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}

assert.EqualValues(t, tt.expected, val, "wrong port from endpoint %s: %d", tt.endpoint, val)
})
}
}
96 changes: 96 additions & 0 deletions internal/components/multi_endpoint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright The OpenTelemetry 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 components

import (
"fmt"

"github.com/go-logr/logr"
"github.com/mitchellh/mapstructure"
corev1 "k8s.io/api/core/v1"

"github.com/open-telemetry/opentelemetry-operator/internal/naming"
)

var _ ComponentPortParser = &MultiPortReceiver{}

// MultiProtocolEndpointConfig represents the minimal struct for a given YAML configuration input containing a map to
// a struct with either endpoint or listen_address.
type MultiProtocolEndpointConfig struct {
Protocols map[string]*SingleEndpointConfig `mapstructure:"protocols"`
}

// MultiPortOption allows the setting of options for a MultiPortReceiver.
type MultiPortOption func(parser *MultiPortReceiver)

// MultiPortReceiver is a special parser for components with endpoints for each protocol.
type MultiPortReceiver struct {
name string

portMappings map[string]*corev1.ServicePort
}

func (m *MultiPortReceiver) Ports(logger logr.Logger, config interface{}) ([]corev1.ServicePort, error) {
multiProtoEndpointCfg := &MultiProtocolEndpointConfig{}
if err := mapstructure.Decode(config, multiProtoEndpointCfg); err != nil {
return nil, err
}
var ports []corev1.ServicePort
for protocol, ec := range multiProtoEndpointCfg.Protocols {
if defaultSvc, ok := m.portMappings[protocol]; ok {
port := defaultSvc.Port
if ec != nil {
port = ec.GetPortNumOrDefault(logger, port)
defaultSvc.Name = naming.PortName(fmt.Sprintf("%s-%s", m.name, protocol), port)
}
ports = append(ports, ConstructServicePort(defaultSvc, port))
} else {
return nil, fmt.Errorf("unknown protocol set: %s", protocol)
}
}
return ports, nil
}

func (m *MultiPortReceiver) ParserType() string {
return ComponentType(m.name)
}

func (m *MultiPortReceiver) ParserName() string {
return fmt.Sprintf("__%s", m.name)
swiatekm marked this conversation as resolved.
Show resolved Hide resolved
}

func NewMultiPortReceiver(name string, opts ...MultiPortOption) *MultiPortReceiver {
multiReceiver := &MultiPortReceiver{
name: name,
portMappings: map[string]*corev1.ServicePort{},
}
for _, opt := range opts {
opt(multiReceiver)
}
return multiReceiver
}

func WithPortMapping(name string, port int32, opts ...PortBuilderOption) MultiPortOption {
return func(parser *MultiPortReceiver) {
servicePort := &corev1.ServicePort{
Name: naming.PortName(fmt.Sprintf("%s-%s", parser.name, name), port),
Port: port,
}
for _, opt := range opts {
opt(servicePort)
}
parser.portMappings[name] = servicePort
}
}
Loading
Loading