From d2d5c72bb5454bcb09149e0ffe7e3d844aa98a2d Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Fri, 19 Feb 2021 16:05:23 +0300 Subject: [PATCH] fix: skip empty manifest YAML sub-documents If sub-doc contains a comment, it's not empty, but when loaded into JSON it yields `nil` which should be skipped, as `Unstructured` can't load from such object. E.g.: ``` --- # Some comment --- ``` Signed-off-by: Andrey Smirnov --- pkg/resources/k8s/manifest.go | 8 +++++ pkg/resources/k8s/manifest_test.go | 49 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 pkg/resources/k8s/manifest_test.go diff --git a/pkg/resources/k8s/manifest.go b/pkg/resources/k8s/manifest.go index a788e89bb..408a2b83b 100644 --- a/pkg/resources/k8s/manifest.go +++ b/pkg/resources/k8s/manifest.go @@ -10,6 +10,7 @@ import ( "encoding/json" "fmt" "io" + "log" "github.com/talos-systems/os-runtime/pkg/resource" "github.com/talos-systems/os-runtime/pkg/resource/core" @@ -116,6 +117,13 @@ func (r *Manifest) SetYAML(yamlBytes []byte) error { return fmt.Errorf("error converting manifest to JSON: %w", err) } + if bytes.Equal(jsonManifest, []byte("null")) || bytes.Equal(jsonManifest, []byte("{}")) { + // skip YAML docs which contain only comments + continue + } + + log.Printf("jsonManifest = %v", string(jsonManifest)) + obj := new(unstructured.Unstructured) if err = json.Unmarshal(jsonManifest, obj); err != nil { diff --git a/pkg/resources/k8s/manifest_test.go b/pkg/resources/k8s/manifest_test.go new file mode 100644 index 000000000..38e2c317b --- /dev/null +++ b/pkg/resources/k8s/manifest_test.go @@ -0,0 +1,49 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +package k8s_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/talos-systems/talos/pkg/resources/k8s" +) + +func TestManifestSetYAML(t *testing.T) { + manifest := k8s.NewManifest(k8s.ControlPlaneNamespaceName, "test") + + require.NoError(t, manifest.SetYAML([]byte(strings.TrimSpace(` +--- +apiVersion: audit.k8s.io/v1beta1 +kind: Policy +rules: +- level: Metadata +--- +`)))) + + assert.Len(t, manifest.Objects(), 1) + assert.Equal(t, manifest.Objects()[0].GetKind(), "Policy") +} + +func TestManifestSetYAMLEmptyComments(t *testing.T) { + manifest := k8s.NewManifest(k8s.ControlPlaneNamespaceName, "test") + + require.NoError(t, manifest.SetYAML([]byte(strings.TrimSpace(` +--- +apiVersion: audit.k8s.io/v1beta1 +kind: Policy +rules: +- level: Metadata +--- +# Left empty +--- +`)))) + + assert.Len(t, manifest.Objects(), 1) + assert.Equal(t, manifest.Objects()[0].GetKind(), "Policy") +}