Merge pull request #56563 from nikhita/unstructured-error-handling

Automatic merge from submit-queue (batch tested with PRs 56390, 56334, 55572, 55598, 56563). If you want to cherry-pick this change to another branch, please follow the instructions <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/cherry-picks.md">here</a>.

apimachinery: improve error handling for unstructured helpers

Improve error handling for unstructured helpers to give more information - if the field is missing or a wrong type exists. (taken from https://github.com/kubernetes/kubernetes/pull/55168)

**Release note**:

```release-note
NONE
```

/assign sttts ash2k
pull/6/head
Kubernetes Submit Queue 2017-12-15 22:51:48 -08:00 committed by GitHub
commit 1073758485
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 112 additions and 95 deletions

View File

@ -31,147 +31,163 @@ import (
) )
// NestedFieldCopy returns a deep copy of the value of a nested field. // NestedFieldCopy returns a deep copy of the value of a nested field.
// false is returned if the value is missing. // Returns false if the value is missing.
// nil, true is returned for a nil field. // No error is returned for a nil field.
func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool) { func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return nil, false return nil, found, err
} }
return runtime.DeepCopyJSONValue(val), true return runtime.DeepCopyJSONValue(val), true, nil
} }
func nestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool) { func nestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {
var val interface{} = obj var val interface{} = obj
for _, field := range fields { for _, field := range fields {
if m, ok := val.(map[string]interface{}); ok { if m, ok := val.(map[string]interface{}); ok {
val, ok = m[field] val, ok = m[field]
if !ok { if !ok {
return nil, false return nil, false, nil
} }
} else { } else {
// Expected map[string]interface{}, got something else return nil, false, fmt.Errorf("%v is of the type %T, expected map[string]interface{}", val, val)
return nil, false
} }
} }
return val, true return val, true, nil
} }
// NestedString returns the string value of a nested field. // NestedString returns the string value of a nested field.
// Returns false if value is not found or is not a string. // Returns false if value is not found and an error if not a string.
func NestedString(obj map[string]interface{}, fields ...string) (string, bool) { func NestedString(obj map[string]interface{}, fields ...string) (string, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return "", false return "", found, err
} }
s, ok := val.(string) s, ok := val.(string)
return s, ok if !ok {
return "", false, fmt.Errorf("%v is of the type %T, expected string", val, val)
}
return s, true, nil
} }
// NestedBool returns the bool value of a nested field. // NestedBool returns the bool value of a nested field.
// Returns false if value is not found or is not a bool. // Returns false if value is not found and an error if not a bool.
func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool) { func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return false, false return false, found, err
} }
b, ok := val.(bool) b, ok := val.(bool)
return b, ok if !ok {
return false, false, fmt.Errorf("%v is of the type %T, expected bool", val, val)
}
return b, true, nil
} }
// NestedFloat64 returns the bool value of a nested field. // NestedFloat64 returns the float64 value of a nested field.
// Returns false if value is not found or is not a float64. // Returns false if value is not found and an error if not a float64.
func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool) { func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return 0, false return 0, found, err
} }
f, ok := val.(float64) f, ok := val.(float64)
return f, ok if !ok {
return 0, false, fmt.Errorf("%v is of the type %T, expected float64", val, val)
}
return f, true, nil
} }
// NestedInt64 returns the int64 value of a nested field. // NestedInt64 returns the int64 value of a nested field.
// Returns false if value is not found or is not an int64. // Returns false if value is not found and an error if not an int64.
func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool) { func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return 0, false return 0, found, err
} }
i, ok := val.(int64) i, ok := val.(int64)
return i, ok if !ok {
return 0, false, fmt.Errorf("%v is of the type %T, expected int64", val, val)
}
return i, true, nil
} }
// NestedStringSlice returns a copy of []string value of a nested field. // NestedStringSlice returns a copy of []string value of a nested field.
// Returns false if value is not found, is not a []interface{} or contains non-string items in the slice. // Returns false if value is not found and an error if not a []interface{} or contains non-string items in the slice.
func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool) { func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return nil, false return nil, found, err
}
m, ok := val.([]interface{})
if !ok {
return nil, false, fmt.Errorf("%v is of the type %T, expected []interface{}", val, val)
} }
if m, ok := val.([]interface{}); ok {
strSlice := make([]string, 0, len(m)) strSlice := make([]string, 0, len(m))
for _, v := range m { for _, v := range m {
if str, ok := v.(string); ok { if str, ok := v.(string); ok {
strSlice = append(strSlice, str) strSlice = append(strSlice, str)
} else { } else {
return nil, false return nil, false, fmt.Errorf("contains non-string key in the slice: %v is of the type %T, expected string", v, v)
} }
} }
return strSlice, true return strSlice, true, nil
}
return nil, false
} }
// NestedSlice returns a deep copy of []interface{} value of a nested field. // NestedSlice returns a deep copy of []interface{} value of a nested field.
// Returns false if value is not found or is not a []interface{}. // Returns false if value is not found and an error if not a []interface{}.
func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool) { func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !found || err != nil {
return nil, found, err
}
_, ok := val.([]interface{})
if !ok { if !ok {
return nil, false return nil, false, fmt.Errorf("%v is of the type %T, expected []interface{}", val, val)
} }
if _, ok := val.([]interface{}); ok { return runtime.DeepCopyJSONValue(val).([]interface{}), true, nil
return runtime.DeepCopyJSONValue(val).([]interface{}), true
}
return nil, false
} }
// NestedStringMap returns a copy of map[string]string value of a nested field. // NestedStringMap returns a copy of map[string]string value of a nested field.
// Returns false if value is not found, is not a map[string]interface{} or contains non-string values in the map. // Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map.
func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool) { func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {
m, ok := nestedMapNoCopy(obj, fields...) m, found, err := nestedMapNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return nil, false return nil, found, err
} }
strMap := make(map[string]string, len(m)) strMap := make(map[string]string, len(m))
for k, v := range m { for k, v := range m {
if str, ok := v.(string); ok { if str, ok := v.(string); ok {
strMap[k] = str strMap[k] = str
} else { } else {
return nil, false return nil, false, fmt.Errorf("contains non-string key in the map: %v is of the type %T, expected string", v, v)
} }
} }
return strMap, true return strMap, true, nil
} }
// NestedMap returns a deep copy of map[string]interface{} value of a nested field. // NestedMap returns a deep copy of map[string]interface{} value of a nested field.
// Returns false if value is not found or is not a map[string]interface{}. // Returns false if value is not found and an error if not a map[string]interface{}.
func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool) { func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
m, ok := nestedMapNoCopy(obj, fields...) m, found, err := nestedMapNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return nil, false return nil, found, err
} }
return runtime.DeepCopyJSON(m), true return runtime.DeepCopyJSON(m), true, nil
} }
// nestedMapNoCopy returns a map[string]interface{} value of a nested field. // nestedMapNoCopy returns a map[string]interface{} value of a nested field.
// Returns false if value is not found or is not a map[string]interface{}. // Returns false if value is not found and an error if not a map[string]interface{}.
func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool) { func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {
val, ok := nestedFieldNoCopy(obj, fields...) val, found, err := nestedFieldNoCopy(obj, fields...)
if !ok { if !found || err != nil {
return nil, false return nil, found, err
} }
m, ok := val.(map[string]interface{}) m, ok := val.(map[string]interface{})
return m, ok if !ok {
return nil, false, fmt.Errorf("%v is of the type %T, expected map[string]interface{}", val, val)
}
return m, true, nil
} }
// SetNestedField sets the value of a nested field to a deep copy of the value provided. // SetNestedField sets the value of a nested field to a deep copy of the value provided.
@ -245,8 +261,8 @@ func RemoveNestedField(obj map[string]interface{}, fields ...string) {
} }
func getNestedString(obj map[string]interface{}, fields ...string) string { func getNestedString(obj map[string]interface{}, fields ...string) string {
val, ok := NestedString(obj, fields...) val, found, err := NestedString(obj, fields...)
if !ok { if !found || err != nil {
return "" return ""
} }
return val return val
@ -256,11 +272,11 @@ func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference {
// though this field is a *bool, but when decoded from JSON, it's // though this field is a *bool, but when decoded from JSON, it's
// unmarshalled as bool. // unmarshalled as bool.
var controllerPtr *bool var controllerPtr *bool
if controller, ok := NestedBool(v, "controller"); ok { if controller, found, err := NestedBool(v, "controller"); err == nil && found {
controllerPtr = &controller controllerPtr = &controller
} }
var blockOwnerDeletionPtr *bool var blockOwnerDeletionPtr *bool
if blockOwnerDeletion, ok := NestedBool(v, "blockOwnerDeletion"); ok { if blockOwnerDeletion, found, err := NestedBool(v, "blockOwnerDeletion"); err == nil && found {
blockOwnerDeletionPtr = &blockOwnerDeletion blockOwnerDeletionPtr = &blockOwnerDeletion
} }
return metav1.OwnerReference{ return metav1.OwnerReference{

View File

@ -138,8 +138,8 @@ func (u *Unstructured) setNestedMap(value map[string]string, fields ...string) {
} }
func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference { func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference {
field, ok := nestedFieldNoCopy(u.Object, "metadata", "ownerReferences") field, found, err := nestedFieldNoCopy(u.Object, "metadata", "ownerReferences")
if !ok { if !found || err != nil {
return nil return nil
} }
original, ok := field.([]interface{}) original, ok := field.([]interface{})
@ -228,8 +228,8 @@ func (u *Unstructured) SetResourceVersion(version string) {
} }
func (u *Unstructured) GetGeneration() int64 { func (u *Unstructured) GetGeneration() int64 {
val, ok := NestedInt64(u.Object, "metadata", "generation") val, found, err := NestedInt64(u.Object, "metadata", "generation")
if !ok { if !found || err != nil {
return 0 return 0
} }
return val return val
@ -289,8 +289,8 @@ func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time) {
} }
func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64 { func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64 {
val, ok := NestedInt64(u.Object, "metadata", "deletionGracePeriodSeconds") val, found, err := NestedInt64(u.Object, "metadata", "deletionGracePeriodSeconds")
if !ok { if !found || err != nil {
return nil return nil
} }
return &val return &val
@ -305,7 +305,7 @@ func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds
} }
func (u *Unstructured) GetLabels() map[string]string { func (u *Unstructured) GetLabels() map[string]string {
m, _ := NestedStringMap(u.Object, "metadata", "labels") m, _, _ := NestedStringMap(u.Object, "metadata", "labels")
return m return m
} }
@ -314,7 +314,7 @@ func (u *Unstructured) SetLabels(labels map[string]string) {
} }
func (u *Unstructured) GetAnnotations() map[string]string { func (u *Unstructured) GetAnnotations() map[string]string {
m, _ := NestedStringMap(u.Object, "metadata", "annotations") m, _, _ := NestedStringMap(u.Object, "metadata", "annotations")
return m return m
} }
@ -337,8 +337,8 @@ func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind {
} }
func (u *Unstructured) GetInitializers() *metav1.Initializers { func (u *Unstructured) GetInitializers() *metav1.Initializers {
m, ok := nestedMapNoCopy(u.Object, "metadata", "initializers") m, found, err := nestedMapNoCopy(u.Object, "metadata", "initializers")
if !ok { if !found || err != nil {
return nil return nil
} }
out := &metav1.Initializers{} out := &metav1.Initializers{}
@ -362,7 +362,7 @@ func (u *Unstructured) SetInitializers(initializers *metav1.Initializers) {
} }
func (u *Unstructured) GetFinalizers() []string { func (u *Unstructured) GetFinalizers() []string {
val, _ := NestedStringSlice(u.Object, "metadata", "finalizers") val, _, _ := NestedStringSlice(u.Object, "metadata", "finalizers")
return val return val
} }

View File

@ -35,8 +35,9 @@ func TestUnstructuredList(t *testing.T) {
content := list.UnstructuredContent() content := list.UnstructuredContent()
items := content["items"].([]interface{}) items := content["items"].([]interface{})
require.Len(t, items, 1) require.Len(t, items, 1)
val, ok := NestedFieldCopy(items[0].(map[string]interface{}), "metadata", "name") val, found, err := NestedFieldCopy(items[0].(map[string]interface{}), "metadata", "name")
require.True(t, ok) require.True(t, found)
require.NoError(t, err)
assert.Equal(t, "test", val) assert.Equal(t, "test", val)
} }