Skip to content

Commit

Permalink
Updates tektonPipeline to make it independent of tektonConfig
Browse files Browse the repository at this point in the history
  - With the addition of operator version config map getting created
    in tektonConfig, the targetNamespace was getting created in
    tektonConfig reconciler, but if tektonConfig is not installed
    and tektonPipeline is supposed to installed alone then it won't
    be installed as it would miss the targetNamespace. So this patch
    checks for the targetNamespace in tektonPipeline reconciler, if
    it is not present then it creates the targetNamespace and also
    the operator version config map i.e. makes tektonPipeline
    independent of tektonConfig

Signed-off-by: Puneet Punamiya <[email protected]>
  • Loading branch information
PuneetPunamiya committed Feb 21, 2022
1 parent a0cd67e commit cd2b281
Show file tree
Hide file tree
Showing 5 changed files with 241 additions and 39 deletions.
59 changes: 59 additions & 0 deletions pkg/reconciler/common/targetnamespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package common

import (
"context"
"os"
"path/filepath"

mf "github.com/manifestival/manifestival"
"github.com/tektoncd/operator/pkg/apis/operator/v1alpha1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)

func CreateTargetNamespace(labels map[string]string, obj v1alpha1.TektonComponent, kubeClientSet kubernetes.Interface) error {
namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: obj.GetSpec().GetTargetNamespace(),
Labels: map[string]string{
"operator.tekton.dev/targetNamespace": "true",
},
},
}

if len(labels) > 0 {
for key, value := range labels {
namespace.Labels[key] = value
}
}

if _, err := kubeClientSet.CoreV1().Namespaces().Create(context.TODO(), namespace, metav1.CreateOptions{}); err != nil {
return err
}
return nil
}

func CreateOperatorVersionConfigMap(manifest mf.Manifest, obj v1alpha1.TektonComponent) error {
koDataDir := os.Getenv(KoEnvKey)
operatorDir := filepath.Join(koDataDir, "info")

if err := AppendManifest(&manifest, operatorDir); err != nil {
return err
}

manifest, err := manifest.Transform(
mf.InjectNamespace(obj.GetSpec().GetTargetNamespace()),
mf.InjectOwner(obj),
)

if err != nil {
return err
}

if err = manifest.Apply(); err != nil {
return err
}

return nil
}
142 changes: 142 additions & 0 deletions pkg/reconciler/common/targetnamespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
Copyright 2022 The Tekton 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 common

import (
"context"
"fmt"
"os"
"testing"

"github.com/google/go-cmp/cmp"
mf "github.com/manifestival/manifestival"
"github.com/tektoncd/operator/pkg/apis/operator/v1alpha1"
"gotest.tools/v3/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/kubernetes/fake"
)

type fakeClient struct {
err error
getErr error
createErr error
resourcesExist bool
creates []unstructured.Unstructured
deletes []unstructured.Unstructured
}

var configMap = namespacedResource("v1", "ConfigMap", "test-ns", "operators-info")

func (f *fakeClient) Get(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) {
var resource *unstructured.Unstructured
if f.resourcesExist {
resource = &unstructured.Unstructured{}
}
return resource, f.getErr
}

func (f *fakeClient) Create(obj *unstructured.Unstructured, options ...mf.ApplyOption) error {
obj.SetAnnotations(nil) // Deleting the extra annotation. Irrelevant for the test.
f.creates = append(f.creates, *obj)
return f.createErr
}

func (f *fakeClient) Delete(obj *unstructured.Unstructured, options ...mf.DeleteOption) error {
f.deletes = append(f.deletes, *obj)
return f.err
}

func (f *fakeClient) Update(obj *unstructured.Unstructured, options ...mf.ApplyOption) error {
return f.err
}

func TestCreateTargetNamespace(t *testing.T) {
targetNamespace := "test-ns"
component := &v1alpha1.TektonPipeline{
ObjectMeta: metav1.ObjectMeta{
Name: "test-name",
},
Spec: v1alpha1.TektonPipelineSpec{
CommonSpec: v1alpha1.CommonSpec{
TargetNamespace: targetNamespace,
},
},
}
fakeClientset := fake.NewSimpleClientset()

err := CreateTargetNamespace(nil, component, fakeClientset)
assert.Equal(t, err, nil)

ns, err := fakeClientset.CoreV1().Namespaces().Get(context.TODO(), targetNamespace, metav1.GetOptions{})
assert.Equal(t, err, nil)
assert.Equal(t, ns.ObjectMeta.Name, targetNamespace)
}

func TestTargetNamespaceNotFound(t *testing.T) {
component := &v1alpha1.TektonPipeline{
ObjectMeta: metav1.ObjectMeta{
Name: "test-name",
},
Spec: v1alpha1.TektonPipelineSpec{
CommonSpec: v1alpha1.CommonSpec{},
},
}
fakeClientset := fake.NewSimpleClientset()

err := CreateTargetNamespace(nil, component, fakeClientset)
assert.Equal(t, err, nil)

_, err = fakeClientset.CoreV1().Namespaces().Get(context.TODO(), "foo", metav1.GetOptions{})
assert.Equal(t, err.Error(), `namespaces "foo" not found`)
}

func TestOperatorVersionCreateConfigMap(t *testing.T) {
os.Setenv(KoEnvKey, "testdata/kodata")
defer os.Unsetenv(KoEnvKey)

targetNamespace := "test-ns"
component := &v1alpha1.TektonPipeline{
ObjectMeta: metav1.ObjectMeta{
Name: "test-name",
},
Spec: v1alpha1.TektonPipelineSpec{
CommonSpec: v1alpha1.CommonSpec{
TargetNamespace: targetNamespace,
},
},
}
fakeClientset := fake.NewSimpleClientset()

err := CreateTargetNamespace(nil, component, fakeClientset)
assert.Equal(t, err, nil)

var manifest mf.Manifest

client := &fakeClient{}
manifest, err = mf.ManifestFrom(mf.Slice(manifest.Resources()), mf.UseClient(client))
assert.Equal(t, err, nil)

err = CreateOperatorVersionConfigMap(manifest, component)
assert.Equal(t, err, nil)

want := []unstructured.Unstructured{configMap}

if len(want) != len(client.creates) {
t.Fatalf("Unexpected creates: %s", fmt.Sprintf("(-got, +want): %s", cmp.Diff(client.creates, want)))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright 2022 The Tekton 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
#
# https://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.

apiVersion: v1
kind: ConfigMap
metadata:
name: operators-info
labels:
app.kubernetes.io/instance: default
data:
# Contains operator version which can be queried by external
# tools such as CLI.
version: 'devel'
9 changes: 9 additions & 0 deletions pkg/reconciler/kubernetes/tektonpipeline/tektonpipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,17 @@ func (r *Reconciler) targetNamespaceCheck(ctx context.Context, tp *v1alpha1.Tekt
ns, err := r.kubeClientSet.CoreV1().Namespaces().Get(ctx, tp.GetSpec().GetTargetNamespace(), metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
if err := common.CreateTargetNamespace(labels, tp, r.kubeClientSet); err != nil {
return err
}
if err := common.CreateOperatorVersionConfigMap(r.manifest, tp); err != nil {
return err
}
return nil
} else {
return err
}

}
for key, value := range labels {
ns.Labels[key] = value
Expand Down
46 changes: 7 additions & 39 deletions pkg/reconciler/shared/tektonconfig/tektonconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@ package tektonconfig
import (
"context"
"fmt"
"os"
"path/filepath"
"time"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"

mf "github.com/manifestival/manifestival"
Expand Down Expand Up @@ -108,7 +105,7 @@ func (r *Reconciler) ReconcileKind(ctx context.Context, tc *v1alpha1.TektonConfi
return err
}

if err := r.createOperatorVersionConfigMap(tc); err != nil {
if err := common.CreateOperatorVersionConfigMap(r.manifest, tc); err != nil {
return err
}

Expand Down Expand Up @@ -172,29 +169,6 @@ func (r *Reconciler) ReconcileKind(ctx context.Context, tc *v1alpha1.TektonConfi
return nil
}

func (r *Reconciler) createOperatorVersionConfigMap(tc *v1alpha1.TektonConfig) error {
koDataDir := os.Getenv(common.KoEnvKey)
operatorDir := filepath.Join(koDataDir, "info")

if err := common.AppendManifest(&r.manifest, operatorDir); err != nil {
return err
}

manifest, err := r.manifest.Transform(
mf.InjectNamespace(tc.GetSpec().GetTargetNamespace()),
mf.InjectOwner(tc),
)
if err != nil {
return err
}

if err = manifest.Apply(); err != nil {
return err
}

return nil
}

func (r *Reconciler) ensureTargetNamespaceExists(ctx context.Context, tc *v1alpha1.TektonConfig) error {

ns, err := r.kubeClientSet.CoreV1().Namespaces().List(ctx, metav1.ListOptions{
Expand All @@ -219,20 +193,14 @@ func (r *Reconciler) ensureTargetNamespaceExists(ctx context.Context, tc *v1alph
}
}
} else {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: tc.GetSpec().GetTargetNamespace(),
Labels: map[string]string{
"operator.tekton.dev/targetNamespace": "true",
},
},
}
if _, err = r.kubeClientSet.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}); err != nil {
if errors.IsAlreadyExists(err) {
return r.addTargetNamespaceLabel(ctx, tc.GetSpec().GetTargetNamespace())
}
if err := common.CreateTargetNamespace(nil, tc, r.kubeClientSet); err != nil {
return err
}
if errors.IsAlreadyExists(err) {
return r.addTargetNamespaceLabel(ctx, tc.GetSpec().GetTargetNamespace())
}
return err

}
return nil
}
Expand Down

0 comments on commit cd2b281

Please sign in to comment.