Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/sdk/query/op.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ type ListOp struct {
metaListOptions *metav1.ListOptions
}

func NewListOp() *ListOp {
op := &ListOp{}
op.setDefaults()
return op
}

// ListOption configures ListOp.
type ListOption func(*ListOp)

Expand Down
25 changes: 25 additions & 0 deletions pkg/sdk/query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,28 @@ func Get(into sdkTypes.Object, opts ...GetOption) error {
}
return nil
}

// List retrieves the specified object list and unmarshals the retrieved data into the "into" object.
// "namespace" indicates which kubernetes namespace to look for the list of kubernetes objects.
// "into" is a sdkType.Object that must have
// "Kind" and "APIVersion" specified in its "TypeMeta" field
// Those are used to construct the underlying resource client.
// "opts" configures the List operation.
func List(namespace string, into sdkTypes.Object, opts ...ListOption) error {
gvk := into.GetObjectKind().GroupVersionKind()
apiVersion, kind := gvk.ToAPIVersionAndKind()
resourceClient, _, err := k8sclient.GetResourceClient(apiVersion, kind, namespace)
if err != nil {
return fmt.Errorf("failed to get resource client for (apiVersion:%s, kind:%s, ns:%s): %v", apiVersion, kind, namespace, err)
}
o := NewListOp()
o.applyOpts(opts)
l, err := resourceClient.List(*o.metaListOptions)
if err != nil {
return err
}
if err := k8sutil.RuntimeObjectIntoRuntimeObject(l, into); err != nil {
return fmt.Errorf("failed to unmarshal the retrieved data: %v", err)
}
return nil
}
15 changes: 15 additions & 0 deletions pkg/util/k8sutil/k8sutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,21 @@ func UnstructuredIntoRuntimeObject(u *unstructured.Unstructured, into runtime.Ob
return nil
}

// RuntimeObjectIntoRuntimeObject unmarshalls an runtime.Object into a given runtime object
func RuntimeObjectIntoRuntimeObject(from runtime.Object, into runtime.Object) error {
b, err := json.Marshal(from)
if err != nil {
return err
}
gvk := from.GetObjectKind().GroupVersionKind()
decoder := decoder(gvk.GroupVersion())
_, _, err = decoder.Decode(b, &gvk, into)
if err != nil {
return fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
}
return nil
}

// GetNameAndNamespace extracts the name and namespace from the given runtime.Object
// and returns a error if any of those is missing.
func GetNameAndNamespace(object runtime.Object) (string, string, error) {
Expand Down