Skip to content
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
21 changes: 16 additions & 5 deletions controllers/resource_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
package controllers

import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"

Expand All @@ -29,11 +29,13 @@ import (
nodev1 "k8s.io/api/node/v1"
rbacv1 "k8s.io/api/rbac/v1"
schedv1 "k8s.io/api/scheduling/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

secv1 "github.com/openshift/api/security/v1"

"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/yaml"
)

const (
Expand Down Expand Up @@ -99,6 +101,17 @@ func getAssetsFrom(n *ClusterPolicyController, path string, openshiftVersion str
return manifests
}

func manifestKind(manifest []byte) (string, error) {
typeMeta := metav1.TypeMeta{}
if err := yaml.Unmarshal(manifest, &typeMeta); err != nil {
return "", fmt.Errorf("failed to decode manifest metadata: %w", err)
}
if typeMeta.Kind == "" {
return "", fmt.Errorf("manifest is missing kind")
}
return typeMeta.Kind, nil
}

func addResourcesControls(n *ClusterPolicyController, path string) (Resources, controlFunc) {
res := Resources{}
ctrl := controlFunc{}
Expand All @@ -108,12 +121,10 @@ func addResourcesControls(n *ClusterPolicyController, path string) (Resources, c

s := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme.Scheme,
scheme.Scheme, json.SerializerOptions{Yaml: true, Pretty: false, Strict: false})
reg := regexp.MustCompile(`\b(\w*kind:\w*)\B.*\b`)

for _, m := range manifests {
kind := reg.FindString(string(m))
slce := strings.Split(kind, ":")
kind = strings.TrimSpace(slce[1])
kind, err := manifestKind(m)
panicIfError(err)

n.logger.V(1).Info("Looking for ", "Kind", kind, "in path:", path)

Expand Down
109 changes: 109 additions & 0 deletions controllers/resource_manager_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
# Copyright (c) NVIDIA CORPORATION. All rights reserved.
#
# 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 controllers

import (
"io/fs"
"os"
"testing"

"github.com/stretchr/testify/require"
)

func TestManifestKind(t *testing.T) {
tests := []struct {
name string
manifest string
expectedKind string
errorMessage string
}{
{
name: "YAML",
manifest: `apiVersion: v1
kind: ServiceAccount
metadata:
name: test
`,
expectedKind: "ServiceAccount",
},
{
name: "JSON",
manifest: `{"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"test"}}`,
expectedKind: "ConfigMap",
},
{
name: "kind-like text in another field",
manifest: `apiVersion: v1
metadata:
annotations:
example.com/value: "kind: WrongKind"
name: test
kind: Service
`,
expectedKind: "Service",
},
{
name: "missing kind",
manifest: `apiVersion: v1
metadata:
name: test
`,
errorMessage: "manifest is missing kind",
},
{
name: "malformed YAML",
manifest: "kind: [",
errorMessage: "failed to decode manifest metadata",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
kind, err := manifestKind([]byte(tc.manifest))
if tc.errorMessage != "" {
require.ErrorContains(t, err, tc.errorMessage)
require.Empty(t, kind)
return
}
require.NoError(t, err)
require.Equal(t, tc.expectedKind, kind)
})
}
}

func TestAllAssetsHaveManifestKind(t *testing.T) {
root, err := os.OpenRoot("../assets")
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, root.Close())
})

err = fs.WalkDir(root.FS(), ".", func(path string, entry fs.DirEntry, walkErr error) error {
require.NoError(t, walkErr)
if entry.IsDir() {
return nil
}

manifest, err := root.ReadFile(path)
require.NoError(t, err)
kind, err := manifestKind(manifest)
require.NoErrorf(t, err, "failed to read kind from %s", path)
require.NotEmptyf(t, kind, "empty kind in %s", path)
return nil
})
require.NoError(t, err)
}
Loading