Skip to content

Commit

Permalink
feat: add name utils and update reconcile utils (#35)
Browse files Browse the repository at this point in the history
* feat: add name utils

* feat: update reconcile utils

* feat: add function that escape `\t` to blank
  • Loading branch information
lwpk110 committed May 15, 2024
1 parent 5d6e112 commit 5a0eb18
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 16 deletions.
44 changes: 44 additions & 0 deletions pkg/util/code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package util

import (
"regexp"
"strings"
)

var reTab = regexp.MustCompile(`^\t+`)

func IndentTabToSpaces(code string, spaces int) string {
indentation := strings.Repeat(" ", spaces)
return reTab.ReplaceAllString(code, indentation)
}

func IndentTab4Spaces(code string) string {
return IndentTabToSpaces(code, 4)
}

func IndentTab2Spaces(code string) string {
return IndentTabToSpaces(code, 2)
}

var re2Spaces = regexp.MustCompile(`^` + strings.Repeat(" ", 2))
var re4Spaces = regexp.MustCompile(`^` + strings.Repeat(" ", 4))

func IndentSpacesToTab(code string, spaces int) string {
switch spaces {
case 2:
return re2Spaces.ReplaceAllString(code, "\t")
case 4:
return re4Spaces.ReplaceAllString(code, "\t")
default:
re := regexp.MustCompile(`^` + strings.Repeat(" ", spaces))
return re.ReplaceAllString(code, "\t")
}
}

func Indent4SpacesToTab(code string) string {
return IndentSpacesToTab(code, 4)
}

func Indent2SpacesToTab(code string) string {
return IndentSpacesToTab(code, 2)
}
44 changes: 44 additions & 0 deletions pkg/util/name_util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package util

type ResourceNameGenerator struct {
InstanceName string
RoleName string
GroupName string
}

// NewResourceNameGenerator new a ResourceNameGenerator
func NewResourceNameGenerator(instanceName, roleName, groupName string) *ResourceNameGenerator {
return &ResourceNameGenerator{
InstanceName: instanceName,
RoleName: roleName,
GroupName: groupName,
}
}

// NewResourceNameGeneratorOneRole new a ResourceNameGenerator without roleName
func NewResourceNameGeneratorOneRole(instanceName, groupName string) *ResourceNameGenerator {
return &ResourceNameGenerator{
InstanceName: instanceName,
GroupName: groupName,
}
}

// GenerateResourceName generate resource Name
func (r *ResourceNameGenerator) GenerateResourceName(extraSuffix string) string {
var res string
if r.InstanceName != "" {
res = r.InstanceName + "-"
}
if r.GroupName != "" {
res = res + r.GroupName + "-"
}
if r.RoleName != "" {
res = res + r.RoleName
} else {
res = res[:len(res)-1]
}
if extraSuffix != "" {
return res + "-" + extraSuffix
}
return res
}
47 changes: 31 additions & 16 deletions pkg/util/reconciler_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"

"github.com/cisco-open/k8s-objectmatcher/patch"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -19,22 +20,31 @@ var (
)

// CreateOrUpdate creates or updates the client.object
func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object) error {
func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object) (bool, error) {

key := client.ObjectKeyFromObject(obj)
namespace := obj.GetNamespace()

kinds, _, _ := scheme.Scheme.ObjectKinds(obj)

name := obj.GetName()

logger.V(5).Info("Creating or updating object", "Kind", kinds, "Namespace", namespace, "Name", name)

current := obj.DeepCopyObject().(client.Object)
// Check if the object exists, if not create a new one
err := c.Get(ctx, key, current)
var calculateOpt = []patch.CalculateOption{
patch.IgnoreStatusFields(),
}
if errors.IsNotFound(err) {
if err := patch.DefaultAnnotator.SetLastAppliedAnnotation(obj); err != nil {
return err
return false, err
}
logger.Info("Creating a new object", "Kind", kinds, "Namespace", namespace, "Name", name)
return c.Create(ctx, obj)

if err := c.Create(ctx, obj); err != nil {
return false, err
}
return true, nil
} else if err == nil {
switch obj.(type) {
case *corev1.Service:
Expand All @@ -54,40 +64,45 @@ func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object) err
svc.Spec.Ports[i].NodePort = currentSvc.Spec.Ports[i].NodePort
}
}
case *appsv1.StatefulSet:
calculateOpt = append(calculateOpt, patch.IgnoreVolumeClaimTemplateTypeMetaAndStatus())
}
result, err := patch.DefaultPatchMaker.Calculate(current, obj, patch.IgnoreStatusFields())
result, err := patch.DefaultPatchMaker.Calculate(current, obj, calculateOpt...)
if err != nil {
logger.Error(err, "failed to calculate patch to match objects, moving on to update")
// if there is an error with matching, we still want to update
resourceVersion := current.(metav1.ObjectMetaAccessor).GetObjectMeta().GetResourceVersion()
obj.(metav1.ObjectMetaAccessor).GetObjectMeta().SetResourceVersion(resourceVersion)

return c.Update(ctx, obj)
if err := c.Update(ctx, obj); err != nil {
return false, err
}
return true, nil
}

if !result.IsEmpty() {
logger.Info(fmt.Sprintf("Resource update for object %s:%s", kinds, obj.(metav1.ObjectMetaAccessor).GetObjectMeta().GetName()),
logger.Info(
fmt.Sprintf("Resource update for object %s:%s", kinds, obj.(metav1.ObjectMetaAccessor).GetObjectMeta().GetName()),
"patch", string(result.Patch),
// "original", string(result.Original),
// "modified", string(result.Modified),
// "current", string(result.Current),
)

err := patch.DefaultAnnotator.SetLastAppliedAnnotation(obj)
if err != nil {
if err := patch.DefaultAnnotator.SetLastAppliedAnnotation(obj); err != nil {
logger.Error(err, "failed to annotate modified object", "object", obj)
}

resourceVersion := current.(metav1.ObjectMetaAccessor).GetObjectMeta().GetResourceVersion()
obj.(metav1.ObjectMetaAccessor).GetObjectMeta().SetResourceVersion(resourceVersion)

return c.Update(ctx, obj)
if err = c.Update(ctx, obj); err != nil {
return false, err
}
return true, nil
}

logger.V(1).Info(fmt.Sprintf("Skipping update for object %s:%s", kinds, obj.(metav1.ObjectMetaAccessor).GetObjectMeta().GetName()))

}
return err
return false, err

}

// UpdateStatus updates the status of the Server resource
Expand Down

0 comments on commit 5a0eb18

Please sign in to comment.