1/*
2Copyright 2014 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 v1
18
19import (
20	"errors"
21	"fmt"
22	"net/url"
23	"strings"
24
25	"k8s.io/apimachinery/pkg/runtime/schema"
26
27	"k8s.io/apimachinery/pkg/api/meta"
28	"k8s.io/apimachinery/pkg/runtime"
29)
30
31var (
32	// Errors that could be returned by GetReference.
33	ErrNilObject  = errors.New("can't reference a nil object")
34	ErrNoSelfLink = errors.New("selfLink was empty, can't make reference")
35)
36
37// GetReference returns an ObjectReference which refers to the given
38// object, or an error if the object doesn't follow the conventions
39// that would allow this.
40// TODO: should take a meta.Interface see http://issue.k8s.io/7127
41func GetReference(scheme *runtime.Scheme, obj runtime.Object) (*ObjectReference, error) {
42	if obj == nil {
43		return nil, ErrNilObject
44	}
45	if ref, ok := obj.(*ObjectReference); ok {
46		// Don't make a reference to a reference.
47		return ref, nil
48	}
49
50	gvk := obj.GetObjectKind().GroupVersionKind()
51
52	// if the object referenced is actually persisted, we can just get kind from meta
53	// if we are building an object reference to something not yet persisted, we should fallback to scheme
54	kind := gvk.Kind
55	if len(kind) == 0 {
56		// TODO: this is wrong
57		gvks, _, err := scheme.ObjectKinds(obj)
58		if err != nil {
59			return nil, err
60		}
61		kind = gvks[0].Kind
62	}
63
64	// An object that implements only List has enough metadata to build a reference
65	var listMeta meta.List
66	objectMeta, err := meta.Accessor(obj)
67	if err != nil {
68		listMeta, err = meta.ListAccessor(obj)
69		if err != nil {
70			return nil, err
71		}
72	} else {
73		listMeta = objectMeta
74	}
75
76	// if the object referenced is actually persisted, we can also get version from meta
77	version := gvk.GroupVersion().String()
78	if len(version) == 0 {
79		selfLink := listMeta.GetSelfLink()
80		if len(selfLink) == 0 {
81			return nil, ErrNoSelfLink
82		}
83		selfLinkUrl, err := url.Parse(selfLink)
84		if err != nil {
85			return nil, err
86		}
87		// example paths: /<prefix>/<version>/*
88		parts := strings.Split(selfLinkUrl.Path, "/")
89		if len(parts) < 3 {
90			return nil, fmt.Errorf("unexpected self link format: '%v'; got version '%v'", selfLink, version)
91		}
92		version = parts[2]
93	}
94
95	// only has list metadata
96	if objectMeta == nil {
97		return &ObjectReference{
98			Kind:            kind,
99			APIVersion:      version,
100			ResourceVersion: listMeta.GetResourceVersion(),
101		}, nil
102	}
103
104	return &ObjectReference{
105		Kind:            kind,
106		APIVersion:      version,
107		Name:            objectMeta.GetName(),
108		Namespace:       objectMeta.GetNamespace(),
109		UID:             objectMeta.GetUID(),
110		ResourceVersion: objectMeta.GetResourceVersion(),
111	}, nil
112}
113
114// GetPartialReference is exactly like GetReference, but allows you to set the FieldPath.
115func GetPartialReference(scheme *runtime.Scheme, obj runtime.Object, fieldPath string) (*ObjectReference, error) {
116	ref, err := GetReference(scheme, obj)
117	if err != nil {
118		return nil, err
119	}
120	ref.FieldPath = fieldPath
121	return ref, nil
122}
123
124// IsAnAPIObject allows clients to preemptively get a reference to an API object and pass it to places that
125// intend only to get a reference to that object. This simplifies the event recording interface.
126func (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind) {
127	obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()
128}
129func (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind {
130	return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
131}
132
133func (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }
134