Mohammadreza Khani 9f36dca7c9 fix: prevent concurrent jobs map writes by adding synchronization
This fix prevents undefined behavior and runtime crashes in multithreaded
use cases.
2024-12-13 20:11:58 +03:30

63 lines
1.3 KiB
Go

package crd
import (
"context"
"encoding/json"
"fmt"
"flink-kube-operator/pkg"
"go.uber.org/zap"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
func (crd *Crd) Patch(jobUid types.UID, patchData map[string]interface{}) error {
job := GetJob(jobUid)
patchBytes, err := json.Marshal(patchData)
if err != nil {
return fmt.Errorf("error marshaling patch data: %w", err)
}
// Patch the status sub-resource
unstructuredJob, err := crd.client.
Namespace(job.GetNamespace()).
Patch(
context.Background(),
job.GetName(),
types.MergePatchType, // Use MergePatchType for JSON Merge Patch
patchBytes,
metaV1.PatchOptions{},
)
if err != nil {
pkg.Logger.Error(
"[crd] [status] error patching custom resource status",
zap.String("namespace", job.GetNamespace()),
zap.Error(err),
)
return err
}
newJob, err := convertFromUnstructured(unstructuredJob)
if err != nil {
pkg.Logger.Error("[crd] [status] error in structure unstructured patched", zap.Error(err))
}
jobs.Store(jobUid, newJob)
if err != nil {
pkg.Logger.Error("[crd] [status] ", zap.Error(err))
return err
}
return nil
}
func (crd Crd) PatchAll(patchData map[string]interface{}) error {
keys := GetAllJobKeys()
for _, key := range keys {
err := crd.Patch(key, patchData)
if err != nil {
return err
}
}
return nil
}