package object import ( "errors" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" edgeunstructured "edge-infra.dev/pkg/k8s/unstructured" ) var ( ErrObservedGenerationNotFound = errors.New("observed generation not found") ErrRequeueIntervalNotFound = errors.New("requeue interval not found") ) // GetStatusObservedGeneration returns the status.observedGeneration of a given // runtime object. func GetStatusObservedGeneration(obj runtime.Object) (int64, error) { u, err := edgeunstructured.FromRuntime(obj) if err != nil { return 0, err } og, found, err := unstructured.NestedInt64(u.Object, "status", "observedGeneration") if err != nil { return 0, err } if !found { return 0, ErrObservedGenerationNotFound } return og, nil } // GetRequeueInterval returns the spec.interval of a given runtime object, if // present. func GetRequeueInterval(obj runtime.Object) (time.Duration, error) { period := time.Second u, err := edgeunstructured.FromRuntime(obj) if err != nil { return period, err } interval, found, err := unstructured.NestedString(u.Object, "spec", "interval") if err != nil { return period, err } if !found { return period, ErrRequeueIntervalNotFound } return time.ParseDuration(interval) } // GetConditions returns the list of conditions from an Unstructured object. // // NOTE: Due to the constraints of JSON-unmarshal, this operation is to be considered best effort. // In more details: // - Errors during JSON-unmarshal are ignored and a empty collection list is returned. // - It's not possible to detect if the object has an empty condition list or if it does not implement conditions; // in both cases the operation returns an empty slice. // - If the object doesn't implement status conditions as defined in GitOps Toolkit API, // JSON-unmarshal matches incoming object keys to the keys; this can lead to to conditions values partially set. func GetConditions(obj runtime.Object) []metav1.Condition { u, err := edgeunstructured.FromRuntime(obj) if err != nil { return nil } conditions := []metav1.Condition{} if err := edgeunstructured.UnmarshalField(u, &conditions, "status", "conditions"); err != nil { return nil } return conditions }