1/*
2Copyright 2021 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package managedfields
18
19import (
20	"bytes"
21	"fmt"
22
23	"sigs.k8s.io/structured-merge-diff/v4/fieldpath"
24	"sigs.k8s.io/structured-merge-diff/v4/typed"
25
26	"k8s.io/apimachinery/pkg/api/meta"
27	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
29	"k8s.io/apimachinery/pkg/runtime"
30)
31
32// ExtractInto extracts the applied configuration state from object for fieldManager
33// into applyConfiguration. If no managed fields are found for the given fieldManager,
34// no error is returned, but applyConfiguration is left unpopulated. It is possible
35// that no managed fields were found for the fieldManager because other field managers
36// have taken ownership of all the fields previously owned by the fieldManager. It is
37// also possible the fieldManager never owned fields.
38func ExtractInto(object runtime.Object, objectType typed.ParseableType, fieldManager string, applyConfiguration interface{}) error {
39	typedObj, err := toTyped(object, objectType)
40	if err != nil {
41		return fmt.Errorf("error converting obj to typed: %w", err)
42	}
43
44	accessor, err := meta.Accessor(object)
45	if err != nil {
46		return fmt.Errorf("error accessing metadata: %w", err)
47	}
48	fieldsEntry, ok := findManagedFields(accessor, fieldManager)
49	if !ok {
50		return nil
51	}
52	fieldset := &fieldpath.Set{}
53	err = fieldset.FromJSON(bytes.NewReader(fieldsEntry.FieldsV1.Raw))
54	if err != nil {
55		return fmt.Errorf("error marshalling FieldsV1 to JSON: %w", err)
56	}
57
58	u := typedObj.ExtractItems(fieldset.Leaves()).AsValue().Unstructured()
59	m, ok := u.(map[string]interface{})
60	if !ok {
61		return fmt.Errorf("unable to convert managed fields for %s to unstructured, expected map, got %T", fieldManager, u)
62	}
63	if err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, applyConfiguration); err != nil {
64		return fmt.Errorf("error extracting into obj from unstructured: %w", err)
65	}
66	return nil
67}
68
69func findManagedFields(accessor metav1.Object, fieldManager string) (metav1.ManagedFieldsEntry, bool) {
70	objManagedFields := accessor.GetManagedFields()
71	for _, mf := range objManagedFields {
72		if mf.Manager == fieldManager && mf.Operation == metav1.ManagedFieldsOperationApply {
73			return mf, true
74		}
75	}
76	return metav1.ManagedFieldsEntry{}, false
77}
78
79func toTyped(obj runtime.Object, objectType typed.ParseableType) (*typed.TypedValue, error) {
80	switch o := obj.(type) {
81	case *unstructured.Unstructured:
82		return objectType.FromUnstructured(o.Object)
83	default:
84		return objectType.FromStructured(o)
85	}
86}
87