GetReference returns an ObjectReference which refers to the given object, or an error if the object doesn't follow the conventions that would allow this. TODO: should take a meta.Interface see http://issue.k8s.io/7127
(scheme *runtime.Scheme, obj runtime.Object)
| 39 | // that would allow this. |
| 40 | // TODO: should take a meta.Interface see http://issue.k8s.io/7127 |
| 41 | func GetReference(scheme *runtime.Scheme, obj runtime.Object) (*v1.ObjectReference, error) { |
| 42 | if obj == nil { |
| 43 | return nil, ErrNilObject |
| 44 | } |
| 45 | if ref, ok := obj.(*v1.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 metav1.Common |
| 66 | objectMeta, err := meta.Accessor(obj) |
| 67 | if err != nil { |
| 68 | listMeta, err = meta.CommonAccessor(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) < 4 { |
| 90 | return nil, fmt.Errorf("unexpected self link format: '%v'; got version '%v'", selfLink, version) |
| 91 | } |
| 92 | if parts[1] == "api" { |
| 93 | version = parts[2] |
| 94 | } else { |
| 95 | version = parts[2] + "/" + parts[3] |
| 96 | } |
| 97 | } |
| 98 |