Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor namespace reconciliation to ensure openshift rbac requisites #2468

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
9 changes: 9 additions & 0 deletions pkg/reconciler/common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,12 @@ func StructToMap(in, out interface{}) error {
}
return json.Unmarshal(data, out)
}

// Helper function to serialize labels map to JSON string
func SerializeLabelsToJSON(labels map[string]string) (string, error) {
bytes, err := json.Marshal(labels)
if err != nil {
return "", fmt.Errorf("failed to serialize labels to JSON: %v", err)
}
return string(bytes), nil
}
62 changes: 62 additions & 0 deletions pkg/reconciler/common/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,65 @@ func TestStructMapError(t *testing.T) {
err := StructToMap(&in, actualOut)
assert.Error(t, err, "json: Unmarshal(non-pointer map[string]interface {})")
}

func TestSerializeLabelsToJSON(t *testing.T) {
// Test cases with different inputs
tests := []struct {
name string
labels map[string]string
expectedOutput string
expectError bool
}{
{
name: "Valid input with multiple labels",
labels: map[string]string{
"app": "my-app",
"env": "production",
"owner": "dev-team",
},
expectedOutput: `{"app":"my-app","env":"production","owner":"dev-team"}`,
expectError: false,
},
{
name: "Empty input",
labels: map[string]string{},
expectedOutput: `{}`,
expectError: false,
},
{
name: "Single label",
labels: map[string]string{
"key": "value",
},
expectedOutput: `{"key":"value"}`,
expectError: false,
},
{
name: "Special characters in keys and values",
labels: map[string]string{
"foo@bar": "bazqux",
"key#1": "value$%",
"space key": "with space",
},
expectedOutput: `{"foo@bar":"bazqux","key#1":"value$%","space key":"with space"}`,
expectError: false,
},
}

// Loop over each test case
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Call the function with the test labels
actual, err := SerializeLabelsToJSON(tt.labels)

// Check if we expect an error
if tt.expectError {
// Assert that an error was returned
assert.Error(t, err, "Expected error, but got none")
} else {
// Check if the output matches the expected result
assert.Equal(t, tt.expectedOutput, actual)
}
})
}
}
28 changes: 26 additions & 2 deletions pkg/reconciler/openshift/tektonconfig/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"github.com/tektoncd/operator/pkg/reconciler/common"
"github.com/tektoncd/operator/pkg/reconciler/openshift/tektonconfig/extension"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
nsV1 "k8s.io/client-go/informers/core/v1"
rbacV1 "k8s.io/client-go/informers/rbac/v1"
"k8s.io/client-go/kubernetes"
Expand Down Expand Up @@ -109,15 +110,38 @@ func (oe openshiftExtension) PreReconcile(ctx context.Context, tc v1alpha1.Tekto

// below code helps to retain state of pre-existing SA at the time of upgrade
if existingSAWithOwnerRef(r.tektonConfig) {
logger := logging.FromContext(ctx)
logger.Infof("Found pre-existing ServiceAccount. Changing owner reference during upgrade.")

if err := changeOwnerRefOfPreExistingSA(ctx, r.kubeClientSet, *config); err != nil {
logger.Errorf("Failed to change owner reference for pre-existing SA: %v", err)
return err
}

// Get current labels to retain any existing labels
tcLabels := config.GetLabels()
if tcLabels == nil {
tcLabels = map[string]string{}
}

// Add or update the serviceAccountCreationLabel without removing other labels
tcLabels[serviceAccountCreationLabel] = "true"
config.SetLabels(tcLabels)
if _, err := oe.operatorClientSet.OperatorV1alpha1().TektonConfigs().Update(ctx, config, metav1.UpdateOptions{}); err != nil {

// Prepare the patch to update only the labels, keeping the existing ones
jsonLabels, err := common.SerializeLabelsToJSON(tcLabels)
if err != nil {
logger.Error(err)
return err
anithapriyanatarajan marked this conversation as resolved.
Show resolved Hide resolved
}
patchData := []byte(fmt.Sprintf(`{"metadata":{"labels":%s}}`, jsonLabels))

// Apply the patch to the TektonConfig
if _, err := oe.operatorClientSet.OperatorV1alpha1().TektonConfigs().Patch(ctx, config.Name, types.MergePatchType, patchData, metav1.PatchOptions{}); err != nil {
logger.Errorf("Failed to patch TektonConfig with new label: %v", err)
return err
}

logger.Infof("Successfully patched TektonConfig with serviceAccountCreationLabel set to true")
}

createRBACResource := true
Expand Down
Loading
Loading