Skip to content
This repository has been archived by the owner on Jul 11, 2023. It is now read-only.

Commit

Permalink
injector: Adding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
draychev committed Oct 1, 2020
1 parent 5096fe9 commit f656d18
Show file tree
Hide file tree
Showing 12 changed files with 564 additions and 79 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ require (
github.com/golang/protobuf v1.4.2
github.com/golangci/golangci-lint v1.30.0
github.com/google/go-cmp v0.5.0
github.com/google/uuid v1.1.1
github.com/google/uuid v1.1.2
github.com/gorilla/mux v1.7.3
github.com/hashicorp/vault/api v1.0.4
github.com/jetstack/cert-manager v0.16.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,8 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
Expand Down
3 changes: 2 additions & 1 deletion pkg/catalog/mock_catalog.go

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

7 changes: 4 additions & 3 deletions pkg/debugger/mock_debugger.go

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

65 changes: 51 additions & 14 deletions pkg/injector/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@ import (
"encoding/base64"
"fmt"

corev1 "k8s.io/api/core/v1"

"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

"github.com/golang/mock/gomock"
"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"

"github.com/openservicemesh/osm/pkg/certificate/providers/tresor"
"github.com/openservicemesh/osm/pkg/configurator"
"github.com/openservicemesh/osm/pkg/constants"
k8s "github.com/openservicemesh/osm/pkg/kubernetes"
)

var _ = Describe("Test Envoy configuration creation", func() {
Expand Down Expand Up @@ -106,28 +110,61 @@ static_resources:
Expect(string(actual)).To(Equal(expectedEnvoyConfig),
fmt.Sprintf("Expected:\n%s\nActual:\n%s\n", expectedEnvoyConfig, string(actual)))
})

It("Creates bootstrap config for the Envoy proxy", func() {
wh := &webhook{
kubeClient: fake.NewSimpleClientset(),
kubeController: k8s.NewMockController(gomock.NewController(GinkgoT())),
}
name := uuid.New().String()
namespace := "a"
osmNamespace := "b"

secret, err := wh.createEnvoyBootstrapConfig(name, namespace, osmNamespace, cert)
Expect(err).ToNot(HaveOccurred())

expected := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Data: map[string][]byte{
envoyBootstrapConfigFile: []byte(expectedEnvoyConfig),
},
}

// Contains only the "bootstrap.yaml" key
Expect(len(secret.Data)).To(Equal(1))

Expect(secret.Data[envoyBootstrapConfigFile]).To(Equal(expected.Data[envoyBootstrapConfigFile]),
fmt.Sprintf("Expected YAML: %s;\nActual YAML: %s\n", expected.Data, secret.Data))

// Now check the entire struct
Expect(*secret).To(Equal(expected))
})
})
})

var _ = Describe("Test Envoy sidecar", func() {
var (
mockCtrl *gomock.Controller
mockConfigurator *configurator.MockConfigurator
const (
containerName = "-container-name-"
envoyImage = "-envoy-image-"
nodeID = "-node-id-"
clusterID = "-cluster-id-"
)

mockCtrl = gomock.NewController(GinkgoT())
mockConfigurator = configurator.NewMockConfigurator(mockCtrl)
mockCtrl := gomock.NewController(GinkgoT())
mockConfigurator := configurator.NewMockConfigurator(mockCtrl)

Context("create Envoy sidecar", func() {
It("creates correct Envoy sidecar spec", func() {
mockConfigurator.EXPECT().GetEnvoyLogLevel().Return("debug").Times(1)

actual := getEnvoySidecarContainerSpec("a", "b", "c", "d", mockConfigurator)
actual := getEnvoySidecarContainerSpec(containerName, envoyImage, nodeID, clusterID, mockConfigurator)
Expect(len(actual)).To(Equal(1))

expected := corev1.Container{
Name: "a",
Image: "b",
Name: containerName,
Image: envoyImage,
ImagePullPolicy: corev1.PullAlways,
SecurityContext: &corev1.SecurityContext{
RunAsUser: func() *int64 {
Expand Down Expand Up @@ -162,8 +199,8 @@ var _ = Describe("Test Envoy sidecar", func() {
Args: []string{
"--log-level", "debug",
"--config-path", "/etc/envoy/bootstrap.yaml",
"--service-node", "c",
"--service-cluster", "d",
"--service-node", nodeID,
"--service-cluster", clusterID,
"--bootstrap-version 3",
},
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/injector/init-container.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"github.com/openservicemesh/osm/pkg/constants"
)

func getInitContainerSpec(data *InitContainer) (corev1.Container, error) {
func getInitContainerSpec(initContainer *InitContainer) (corev1.Container, error) {
return corev1.Container{
Name: data.Name,
Image: data.Image,
Name: initContainer.Name,
Image: initContainer.Image,
SecurityContext: &corev1.SecurityContext{
Capabilities: &corev1.Capabilities{
Add: []corev1.Capability{
Expand Down
94 changes: 58 additions & 36 deletions pkg/injector/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"strconv"
"strings"

"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"

"github.com/openservicemesh/osm/pkg/catalog"
Expand All @@ -20,10 +19,7 @@ const (
labelsPath = "/metadata/labels"
)

func (wh *webhook) createPatch(pod *corev1.Pod, namespace string) ([]byte, error) {
// This string uniquely identifies the pod. Ideally this would be the pod.UID, but this is not available at this point.
proxyUUID := uuid.New().String()

func (wh *webhook) createPatch(pod *corev1.Pod, namespace, proxyUUID string) ([]byte, error) {
// Start patching the spec
var patches []JSONPatchOperation

Expand Down Expand Up @@ -110,16 +106,16 @@ func addVolume(target, add []corev1.Volume, basePath string) (patch []JSONPatchO
var value interface{}
for _, volume := range add {
value = volume
path := basePath
volumePath := basePath
if isFirst {
isFirst = false
value = []corev1.Volume{volume}
} else {
path += "/-"
volumePath += "/-"
}
patch = append(patch, JSONPatchOperation{
Op: "add",
Path: path,
Op: addOperation.String(),
Path: volumePath,
Value: value,
})
}
Expand All @@ -139,41 +135,67 @@ func addContainer(target, add []corev1.Container, basePath string) (patch []JSON
path += "/-"
}
patch = append(patch, JSONPatchOperation{
Op: "add",
Op: addOperation.String(),
Path: path,
Value: value,
})
}
return patch
}

func updateAnnotation(target, add map[string]string, basePath string) (patch []JSONPatchOperation) {
type operation string

func (o operation) String() string {
return string(o)
}

const (
addOperation operation = "add"
replaceOperation operation = "replace"
)

func getOpAndPath(target map[string]string, key, basePath string) (patchOperation operation, patchPath string) {
if target == nil {
// This is an addition
return addOperation, basePath
}

if target[key] != "" {
// This is a replacement
return replaceOperation, path.Join(basePath, escapeJSONPointerValue(key))
}

// Target exists, but the key is new.
return addOperation, basePath // path.Join(basePath, escapeJSONPointerValue(key))
}

func updateAnnotation(target, add map[string]string, basePath string) []JSONPatchOperation {
var patches []JSONPatchOperation

for key, value := range add {
if target == nil {
// First one will be a Create
target = map[string]string{}
patch = append(patch, JSONPatchOperation{
Op: "add",
Path: basePath,
Value: map[string]string{
patchOperation, patchPath := getOpAndPath(target, key, basePath)

patchValue := map[operation]func() interface{}{

addOperation: func() interface{} {
return map[string]string{
key: value,
},
})
} else {
// Update
op := "add"
if target[key] != "" {
op = "replace"
}
patch = append(patch, JSONPatchOperation{
Op: op,
Path: path.Join(basePath, escapeJSONPointerValue(key)),
Value: value,
})
}
}
},

replaceOperation: func() interface{} {
return value
},
}[patchOperation]()

patches = append(patches, JSONPatchOperation{
Op: patchOperation.String(),
Path: patchPath,
Value: patchValue,
})
}

return patch
return patches
}

// This function will append a label to the pod, which points to the unique Envoy ID used in the
Expand All @@ -182,17 +204,17 @@ func updateAnnotation(target, add map[string]string, basePath string) (patch []J
func updateLabels(pod *corev1.Pod, envoyUID string) *JSONPatchOperation {
if len(pod.Labels) == 0 {
return &JSONPatchOperation{
Op: "add",
Op: addOperation.String(),
Path: labelsPath,
Value: map[string]string{constants.EnvoyUniqueIDLabelName: envoyUID},
}
}

getOp := func() string {
if _, exists := pod.Labels[constants.EnvoyUniqueIDLabelName]; exists {
return "replace"
return replaceOperation.String()
}
return "add"
return addOperation.String()
}

return &JSONPatchOperation{
Expand Down
Loading

0 comments on commit f656d18

Please sign in to comment.