Skip to content

Commit

Permalink
Merge pull request #214 from rramkumar1/add-validation
Browse files Browse the repository at this point in the history
Code to setup removal of ServicePort logic out of translator
  • Loading branch information
nicksardo authored Apr 14, 2018
2 parents 4795047 + a4ea2b7 commit 69e9e55
Show file tree
Hide file tree
Showing 21 changed files with 1,779 additions and 2 deletions.
12 changes: 12 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions Gopkg.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,12 @@ ignored = ["k8s.io/kubernetes/pkg/api"]
branch = "master"
name = "k8s.io/kube-openapi"


[[constraint]]
branch = "master"
name = "github.com/hashicorp/go-multierror"


[prune]
go-tests = true
unused-packages = true


94 changes: 94 additions & 0 deletions pkg/backends/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
Copyright 2018 The Kubernetes 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 backends

import (
"fmt"

"github.com/golang/glog"
multierror "github.com/hashicorp/go-multierror"
"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/ingress-gce/pkg/annotations"
)

// ServicePorts converts an IngressBackend -> Service mapping
// to a IngressBackend -> ServicePort mapping
func ServicePorts(backendToService map[v1beta1.IngressBackend]v1.Service) (map[v1beta1.IngressBackend]ServicePort, error) {
backendToServicePort := make(map[v1beta1.IngressBackend]ServicePort)
var result *multierror.Error

for ib, svc := range backendToService {
svcPort, err := servicePort(ib, svc)
if err != nil {
result = multierror.Append(result, err)
}
backendToServicePort[ib] = svcPort
}
return backendToServicePort, result.ErrorOrNil()
}

// servicePort looks at the port specified in the IngressBackend and returns
// the correct ServicePort.
func servicePort(ib v1beta1.IngressBackend, svc v1.Service) (ServicePort, error) {
// If service is not of type NodePort, return an error.
if svc.Spec.Type != v1.ServiceTypeNodePort {
return ServicePort{}, fmt.Errorf("service %v is type %v, expected type NodePort", svc.Name, svc.Spec.Type)
}
appProtocols, err := annotations.FromService(&svc).ApplicationProtocols()
if err != nil {
return ServicePort{}, err
}

var port *v1.ServicePort
PortLoop:
for _, p := range svc.Spec.Ports {
np := p
switch ib.ServicePort.Type {
case intstr.Int:
if p.Port == ib.ServicePort.IntVal {
port = &np
break PortLoop
}
default:
if p.Name == ib.ServicePort.StrVal {
port = &np
break PortLoop
}
}
}

if port == nil {
return ServicePort{}, fmt.Errorf("could not find matching port for backend %+v and service %s/%s. Looking for port %+v in %v", ib, svc.Namespace, ib.ServiceName, ib.ServicePort, svc.Spec.Ports)
}

proto := annotations.ProtocolHTTP
if protoStr, exists := appProtocols[port.Name]; exists {
glog.V(2).Infof("service %s/%s, port %q: using protocol to %q", svc.Namespace, ib.ServiceName, port, protoStr)
proto = annotations.AppProtocol(protoStr)
}

p := ServicePort{
NodePort: int64(port.NodePort),
Protocol: proto,
SvcName: types.NamespacedName{Namespace: svc.Namespace, Name: ib.ServiceName},
SvcPort: ib.ServicePort,
}
return p, nil
}
76 changes: 76 additions & 0 deletions pkg/backends/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package backends

import (
"testing"

"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
)

func TestServicePort(t *testing.T) {

objMeta := meta_v1.ObjectMeta{
Namespace: "bar",
Annotations: map[string]string{"http": "HTTP"},
}

testCases := []struct {
ib v1beta1.IngressBackend
svc v1.Service
expectedSvcPort ServicePort
}{
{
v1beta1.IngressBackend{ServiceName: "foo", ServicePort: intstr.FromInt(80)},
v1.Service{
ObjectMeta: objMeta,
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeNodePort,
Ports: []v1.ServicePort{v1.ServicePort{Port: 80, NodePort: 30000}},
},
},
ServicePort{
SvcName: types.NamespacedName{Namespace: "bar", Name: "foo"},
SvcPort: intstr.FromInt(80),
NodePort: 30000,
Protocol: "HTTP",
},
},
{
v1beta1.IngressBackend{ServiceName: "foo", ServicePort: intstr.FromInt(80)},
v1.Service{
ObjectMeta: objMeta,
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeNodePort,
Ports: []v1.ServicePort{v1.ServicePort{Port: 443, NodePort: 30000, Protocol: "TCP"}, v1.ServicePort{Port: 80, NodePort: 30001}},
},
},
ServicePort{
SvcName: types.NamespacedName{Namespace: "bar", Name: "foo"},
SvcPort: intstr.FromInt(80),
NodePort: 30001,
Protocol: "HTTP",
},
},
{
v1beta1.IngressBackend{ServiceName: "foo", ServicePort: intstr.FromInt(80)},
v1.Service{
ObjectMeta: objMeta,
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeClusterIP,
Ports: []v1.ServicePort{v1.ServicePort{Port: 80, NodePort: 30000}},
},
},
ServicePort{},
},
}

for _, testCase := range testCases {
res, _ := servicePort(testCase.ib, testCase.svc)
if res != testCase.expectedSvcPort {
t.Errorf("Result ServicePort: %v does not match expected: %v", res, testCase.expectedSvcPort)
}
}
}
24 changes: 24 additions & 0 deletions pkg/controller/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,27 @@ func nodeStatusChanged(old, cur *api_v1.Node) bool {
}
return false
}

// Encapsulates an object that can get a service from a cluster.
type SvcGetter struct {
cache.Store
}

func (s *SvcGetter) Get(svcName, namespace string) (*api_v1.Service, error) {
obj, exists, err := s.Store.Get(
&api_v1.Service{
ObjectMeta: meta_v1.ObjectMeta{
Name: svcName,
Namespace: namespace,
},
},
)
if !exists {
return nil, fmt.Errorf("service %v/%v not found in store", namespace, svcName)
}
if err != nil {
return nil, err
}
svc := obj.(*api_v1.Service)
return svc, nil
}
37 changes: 37 additions & 0 deletions pkg/mapper/fakes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2018 Google Inc.
//
// 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.

// TODO(rramkumar): Add stuff here
package mapper

import (
"fmt"

"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
)

type fakeClusterServiceMapper struct {
// Whether the fake implementation of ClusterServiceMapper
// should return an error on purpose.
returnError bool
}

func NewFakeClusterServiceMapper(returnError bool) ClusterServiceMapper {
return &fakeClusterServiceMapper{returnError}
}

func (f *fakeClusterServiceMapper) Services(ing *v1beta1.Ingress) (map[v1beta1.IngressBackend]v1.Service, error) {
return nil, fmt.Errorf("fake error")
}
26 changes: 26 additions & 0 deletions pkg/mapper/interfaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2018 Google Inc.
//
// 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 mapper

import (
"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
)

// ClusterServiceMapper is an interface to intuitively map an Ingress to the
// Services it defines for a specific cluster,
type ClusterServiceMapper interface {
Services(ing *v1beta1.Ingress) (map[v1beta1.IngressBackend]v1.Service, error)
}
100 changes: 100 additions & 0 deletions pkg/mapper/mapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2018 Google Inc.
//
// 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 mapper

import (
"fmt"

multierror "github.com/hashicorp/go-multierror"
"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
)

// Implements ClusterServiceMapper
type clusterServiceMapper struct {
// Function to convert a (svcName, namespace) pair into a Service object.
svcGetter func(svcName string, namespace string) (*v1.Service, error)
// Services that are expected to exist in cluster.
expectedSvcs map[string]bool
}

var _ ClusterServiceMapper = &clusterServiceMapper{}

// NewClusterServiceMapper creates a new ClusterServiceMapper given:
// 1. a list of services expected to exist in the cluster. If empty, then all services are expected to exist.
// 2. a function that gets a Service object from a cluster given its name and namespace.
func NewClusterServiceMapper(
svcGetter func(svcName string, namespace string) (*v1.Service, error),
expectedSvcs []string) ClusterServiceMapper {
es := make(map[string]bool)
if expectedSvcs == nil {
return &clusterServiceMapper{svcGetter, es}
}
for _, expectedSvc := range expectedSvcs {
es[expectedSvc] = true
}
return &clusterServiceMapper{svcGetter, es}
}

// Services returns a mapping for a cluster of IngressBackend -> Service given an Ingress.
func (c *clusterServiceMapper) Services(ing *v1beta1.Ingress) (map[v1beta1.IngressBackend]v1.Service, error) {
backendToService := make(map[v1beta1.IngressBackend]v1.Service)
var result *multierror.Error

defaultBackend := ing.Spec.Backend
if defaultBackend != nil {
// We don't expect this service to exist
// so don't bother actually getting it.
if !c.expectedToExist(defaultBackend.ServiceName) {
goto Loop
}
svc, err := c.svcGetter(defaultBackend.ServiceName, ing.Namespace)
if err != nil {
result = multierror.Append(result, fmt.Errorf("error getting %v/%v: %v", defaultBackend.ServiceName, ing.Namespace, err))
} else {
backendToService[*defaultBackend] = *svc
}
}
Loop:
for _, rule := range ing.Spec.Rules {
if rule.HTTP == nil {
result = multierror.Append(result, fmt.Errorf("no HTTP rule specified in %v", rule))
continue
}
for _, path := range rule.HTTP.Paths {
svcName := path.Backend.ServiceName
if !c.expectedToExist(svcName) {
// We don't expect this service to exist
// so don't bother actually getting it.
continue
}
svc, err := c.svcGetter(path.Backend.ServiceName, ing.Namespace)
if err != nil {
result = multierror.Append(result, fmt.Errorf("error getting %v/%v", ing.Namespace, path.Backend.ServiceName))
continue
}
backendToService[path.Backend] = *svc
}
}
return backendToService, result.ErrorOrNil()
}

// expectedToExist returns true if the provided service name is expected to exist.
func (c *clusterServiceMapper) expectedToExist(svcName string) bool {
if _, ok := c.expectedSvcs[svcName]; !ok && len(c.expectedSvcs) > 0 {
return false
}
return true
}
Loading

0 comments on commit 69e9e55

Please sign in to comment.