Skip to content

Commit acf910d

Browse files
adracusMadVikingGod
authored andcommitted
✨ Implement delete collection via delete options
implement `CollectionOptions` in `DeleteOptions` that allow to issue a `DeleteCollection` call under the hood add tests + examples Co-Authored-By: Aaron Clawson <[email protected]>
1 parent 0216acb commit acf910d

File tree

7 files changed

+222
-6
lines changed

7 files changed

+222
-6
lines changed

pkg/client/client_test.go

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ var _ = Describe("Client", func() {
7070
BeforeEach(func(done Done) {
7171
atomic.AddUint64(&count, 1)
7272
dep = &appsv1.Deployment{
73-
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("deployment-name-%v", count), Namespace: ns},
73+
ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("deployment-name-%v", count), Namespace: ns, Labels: map[string]string{"app": fmt.Sprintf("bar-%v", count)}},
7474
Spec: appsv1.DeploymentSpec{
7575
Replicas: &replicaCount,
7676
Selector: &metav1.LabelSelector{
@@ -898,6 +898,37 @@ var _ = Describe("Client", func() {
898898
PIt("should fail if the GVK cannot be mapped to a Resource", func() {
899899

900900
})
901+
902+
It("should delete a collection of object", func(done Done) {
903+
cl, err := client.New(cfg, client.Options{})
904+
Expect(err).NotTo(HaveOccurred())
905+
Expect(cl).NotTo(BeNil())
906+
907+
By("initially creating two Deployments")
908+
909+
dep2 := dep.DeepCopy()
910+
dep2.Name = dep2.Name + "-2"
911+
912+
dep, err = clientset.AppsV1().Deployments(ns).Create(dep)
913+
Expect(err).NotTo(HaveOccurred())
914+
dep2, err = clientset.AppsV1().Deployments(ns).Create(dep2)
915+
Expect(err).NotTo(HaveOccurred())
916+
917+
depName := dep.Name
918+
dep2Name := dep2.Name
919+
920+
By("deleting Deployments")
921+
err = cl.Delete(context.TODO(), dep, client.All(client.InNamespace(ns), client.MatchingLabels(dep.ObjectMeta.Labels)))
922+
Expect(err).NotTo(HaveOccurred())
923+
924+
By("validating the Deployment no longer exists")
925+
_, err = clientset.AppsV1().Deployments(ns).Get(depName, metav1.GetOptions{})
926+
Expect(err).To(HaveOccurred())
927+
_, err = clientset.AppsV1().Deployments(ns).Get(dep2Name, metav1.GetOptions{})
928+
Expect(err).To(HaveOccurred())
929+
930+
close(done)
931+
})
901932
})
902933
Context("with unstructured objects", func() {
903934
It("should delete an existing object from a go struct", func(done Done) {
@@ -974,6 +1005,44 @@ var _ = Describe("Client", func() {
9741005

9751006
close(done)
9761007
})
1008+
1009+
It("should delete a collection of object", func(done Done) {
1010+
cl, err := client.New(cfg, client.Options{})
1011+
Expect(err).NotTo(HaveOccurred())
1012+
Expect(cl).NotTo(BeNil())
1013+
1014+
By("initially creating two Deployments")
1015+
1016+
dep2 := dep.DeepCopy()
1017+
dep2.Name = dep2.Name + "-2"
1018+
1019+
dep, err = clientset.AppsV1().Deployments(ns).Create(dep)
1020+
Expect(err).NotTo(HaveOccurred())
1021+
dep2, err = clientset.AppsV1().Deployments(ns).Create(dep2)
1022+
Expect(err).NotTo(HaveOccurred())
1023+
1024+
depName := dep.Name
1025+
dep2Name := dep2.Name
1026+
1027+
By("deleting Deployments")
1028+
u := &unstructured.Unstructured{}
1029+
Expect(scheme.Convert(dep, u, nil)).To(Succeed())
1030+
u.SetGroupVersionKind(schema.GroupVersionKind{
1031+
Group: "apps",
1032+
Kind: "Deployment",
1033+
Version: "v1",
1034+
})
1035+
err = cl.Delete(context.TODO(), u, client.All(client.InNamespace(ns), client.MatchingLabels(dep.ObjectMeta.Labels)))
1036+
Expect(err).NotTo(HaveOccurred())
1037+
1038+
By("validating the Deployment no longer exists")
1039+
_, err = clientset.AppsV1().Deployments(ns).Get(depName, metav1.GetOptions{})
1040+
Expect(err).To(HaveOccurred())
1041+
_, err = clientset.AppsV1().Deployments(ns).Get(dep2Name, metav1.GetOptions{})
1042+
Expect(err).To(HaveOccurred())
1043+
1044+
close(done)
1045+
})
9771046
})
9781047
})
9791048

@@ -1994,6 +2063,10 @@ var _ = Describe("Client", func() {
19942063
PIt("should fail if the object doesn't have meta", func() {
19952064

19962065
})
2066+
2067+
PIt("should filter results by namespace selector", func() {
2068+
2069+
})
19972070
})
19982071
})
19992072

@@ -2056,6 +2129,12 @@ var _ = Describe("Client", func() {
20562129
Expect(do.AsDeleteOptions()).To(Equal(&metav1.DeleteOptions{}))
20572130
})
20582131

2132+
It("should producte nil CollectionOptions if not present", func() {
2133+
do := &client.DeleteOptions{}
2134+
do.AsDeleteOptions()
2135+
Expect(do.CollectionOptions).To(BeNil())
2136+
})
2137+
20592138
It("should merge multiple options together", func() {
20602139
gp := int64(1)
20612140
pc := metav1.NewUIDPreconditions("uid")
@@ -2065,10 +2144,13 @@ var _ = Describe("Client", func() {
20652144
client.GracePeriodSeconds(gp),
20662145
client.Preconditions(*pc),
20672146
client.PropagationPolicy(dp),
2147+
client.All(client.InNamespace("test")),
20682148
})
20692149
Expect(do.GracePeriodSeconds).To(Equal(&gp))
20702150
Expect(do.Preconditions).To(Equal(pc))
20712151
Expect(do.PropagationPolicy).To(Equal(&dp))
2152+
Expect(do.CollectionOptions).NotTo(BeNil())
2153+
Expect(do.CollectionOptions.Namespace).To(Equal("test"))
20722154
})
20732155
})
20742156

@@ -2105,6 +2187,13 @@ var _ = Describe("Client", func() {
21052187
Expect(lo).NotTo(BeNil())
21062188
Expect(lo.Namespace).To(Equal("test"))
21072189
})
2190+
2191+
It("should produce empty metav1.ListOptions if nil", func() {
2192+
var do *client.ListOptions
2193+
Expect(do.AsListOptions()).To(Equal(&metav1.ListOptions{}))
2194+
do = &client.ListOptions{}
2195+
Expect(do.AsListOptions()).To(Equal(&metav1.ListOptions{}))
2196+
})
21082197
})
21092198

21102199
Describe("UpdateOptions", func() {

pkg/client/example_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,22 @@ func ExampleClient_delete() {
199199
_ = c.Delete(context.Background(), u)
200200
}
201201

202+
// This example shows how to use the client with typed and unstrucurted objects to delete collections of objects.
203+
func ExampleClient_deleteCollection() {
204+
// Using a typed object.
205+
// c is a created client.
206+
_ = c.Delete(context.Background(), &corev1.Pod{}, client.All(client.InNamespace("foo"), client.MatchingLabels{"app": "foo"}))
207+
208+
// Using an unstructured Object
209+
u := &unstructured.UnstructuredList{}
210+
u.SetGroupVersionKind(schema.GroupVersionKind{
211+
Group: "apps",
212+
Kind: "Deployment",
213+
Version: "v1",
214+
})
215+
_ = c.Delete(context.Background(), u, client.All(client.InNamespace("foo"), client.MatchingLabels{"app": "foo"}))
216+
}
217+
202218
// This example shows how to set up and consume a field selector over a pod's volumes' secretName field.
203219
func ExampleFieldIndexer_secretName() {
204220
// someIndexer is a FieldIndexer over a Cache

pkg/client/fake/client.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,49 @@ func (c *fakeClient) Delete(ctx context.Context, obj runtime.Object, opts ...cli
161161
if err != nil {
162162
return err
163163
}
164+
delOptions := client.DeleteOptions{}
165+
delOptions.ApplyOptions(opts)
166+
if delOptions.CollectionOptions != nil {
167+
return c.deleteCollection(obj, delOptions)
168+
}
169+
164170
//TODO: implement propagation
165171
return c.tracker.Delete(gvr, accessor.GetNamespace(), accessor.GetName())
166172
}
167173

174+
func (c *fakeClient) deleteCollection(obj runtime.Object, dcOptions client.DeleteOptions) error {
175+
gvk, err := apiutil.GVKForObject(obj, scheme.Scheme)
176+
if err != nil {
177+
return err
178+
}
179+
180+
gvr, _ := meta.UnsafeGuessKindToResource(gvk)
181+
o, err := c.tracker.List(gvr, gvk, dcOptions.CollectionOptions.Namespace)
182+
if err != nil {
183+
return err
184+
}
185+
186+
objs, err := meta.ExtractList(o)
187+
if err != nil {
188+
return err
189+
}
190+
filteredObjs, err := objectutil.FilterWithLabels(objs, dcOptions.CollectionOptions.LabelSelector)
191+
if err != nil {
192+
return err
193+
}
194+
for _, o := range filteredObjs {
195+
accessor, err := meta.Accessor(o)
196+
if err != nil {
197+
return err
198+
}
199+
err = c.tracker.Delete(gvr, accessor.GetNamespace(), accessor.GetName())
200+
if err != nil {
201+
return err
202+
}
203+
}
204+
return nil
205+
}
206+
168207
func (c *fakeClient) Update(ctx context.Context, obj runtime.Object, opts ...client.UpdateOption) error {
169208
updateOptions := &client.UpdateOptions{}
170209
updateOptions.ApplyOptions(opts)

pkg/client/fake/client_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,18 @@ var _ = Describe("Fake client", func() {
158158
Expect(list.Items).To(ConsistOf(*dep2))
159159
})
160160

161+
It("should be able to Delete a Collection", func() {
162+
By("Deleting a deploymentList")
163+
err := cl.Delete(nil, &appsv1.Deployment{}, client.All(client.InNamespace("ns1")))
164+
Expect(err).To(BeNil())
165+
166+
By("Listing all deployments in the namespace")
167+
list := &appsv1.DeploymentList{}
168+
err = cl.List(nil, list, client.InNamespace("ns1"))
169+
Expect(err).To(BeNil())
170+
Expect(list.Items).To(BeEmpty())
171+
})
172+
161173
Context("with the DryRun option", func() {
162174
It("should not create a new object", func() {
163175
By("Creating a new configmap with DryRun")

pkg/client/options.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,10 @@ type DeleteOptions struct {
168168
// foreground.
169169
PropagationPolicy *metav1.DeletionPropagation
170170

171+
// CollectionOptions is used by the DeleteCollection to determine the objects
172+
// to be deleted.
173+
CollectionOptions *ListOptions
174+
171175
// Raw represents raw DeleteOptions, as passed to the API server.
172176
Raw *metav1.DeleteOptions
173177

@@ -228,6 +232,28 @@ func (p PropagationPolicy) ApplyToDelete(opts *DeleteOptions) {
228232
opts.PropagationPolicy = &policy
229233
}
230234

235+
// NB(directxman12): there's two ways to spell this because the variadic
236+
// parameters are often more ergonomic, but we want a public type.
237+
238+
// All indicates that this delete operation should affect all objects,
239+
// matching any list options passed to the delete operation, instead of
240+
// a single object.
241+
func All(opts ...ListOption) Everything {
242+
return Everything(opts)
243+
}
244+
245+
// Everything indicates that this delete operation should affect all objects,
246+
// matching any list options passed to the delete operation, instead of
247+
// a single object.
248+
type Everything []ListOption
249+
250+
func (e Everything) ApplyToDelete(opts *DeleteOptions) {
251+
if opts.CollectionOptions == nil {
252+
opts.CollectionOptions = &ListOptions{}
253+
}
254+
opts.CollectionOptions.ApplyOptions([]ListOption(e))
255+
}
256+
231257
// }}}
232258

233259
// {{{ List Options
@@ -282,7 +308,7 @@ func (o *ListOptions) ApplyOptions(opts []ListOption) *ListOptions {
282308
return o
283309
}
284310

285-
// MatchingLabels filters the list operation on the given set of labels.
311+
// MatchingLabels filters the list/delete operation on the given set of labels.
286312
type MatchingLabels map[string]string
287313

288314
func (m MatchingLabels) ApplyToList(opts *ListOptions) {
@@ -299,7 +325,7 @@ func MatchingField(name, val string) MatchingFields {
299325
return MatchingFields{name: val}
300326
}
301327

302-
// MatchingField filters the list operation on the given field selector
328+
// MatchingField filters the list/delete operation on the given field selector
303329
// (or index in the case of cached lists).
304330
type MatchingFields fields.Set
305331

@@ -309,7 +335,7 @@ func (m MatchingFields) ApplyToList(opts *ListOptions) {
309335
opts.FieldSelector = sel
310336
}
311337

312-
// InNamespace restricts the given operation to the given namespace.
338+
// InNamespace restricts the list/delete operation to the given namespace.
313339
type InNamespace string
314340

315341
func (n InNamespace) ApplyToList(opts *ListOptions) {

pkg/client/typed_client.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,29 @@ func (c *typedClient) Delete(ctx context.Context, obj runtime.Object, opts ...De
7676
}
7777

7878
deleteOpts := DeleteOptions{}
79+
deleteOpts.ApplyOptions(opts)
80+
81+
if deleteOpts.CollectionOptions != nil {
82+
return c.deleteCollection(ctx, o, deleteOpts)
83+
}
84+
7985
return o.Delete().
8086
NamespaceIfScoped(o.GetNamespace(), o.isNamespaced()).
8187
Resource(o.resource()).
8288
Name(o.GetName()).
83-
Body(deleteOpts.ApplyOptions(opts).AsDeleteOptions()).
89+
Body(deleteOpts.AsDeleteOptions()).
90+
Context(ctx).
91+
Do().
92+
Error()
93+
}
94+
95+
// DeleteCollection implements client.Client
96+
func (c *typedClient) deleteCollection(ctx context.Context, o *objMeta, deleteOpts DeleteOptions) error {
97+
return o.Delete().
98+
NamespaceIfScoped(deleteOpts.CollectionOptions.Namespace, o.isNamespaced()).
99+
Resource(o.resource()).
100+
VersionedParams(deleteOpts.CollectionOptions.AsListOptions(), c.paramCodec).
101+
Body(deleteOpts.AsDeleteOptions()).
84102
Context(ctx).
85103
Do().
86104
Error()

pkg/client/unstructured_client.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,23 @@ func (uc *unstructuredClient) Delete(_ context.Context, obj runtime.Object, opts
8787
return err
8888
}
8989
deleteOpts := DeleteOptions{}
90-
err = r.Delete(u.GetName(), deleteOpts.ApplyOptions(opts).AsDeleteOptions())
90+
deleteOpts.ApplyOptions(opts)
91+
if deleteOpts.CollectionOptions != nil {
92+
return uc.deleteCollection(u, deleteOpts)
93+
}
94+
err = r.Delete(u.GetName(), deleteOpts.AsDeleteOptions())
95+
return err
96+
}
97+
98+
func (uc *unstructuredClient) deleteCollection(u *unstructured.Unstructured, dcOpts DeleteOptions) error {
99+
gvk := u.GroupVersionKind()
100+
101+
r, err := uc.getResourceInterface(gvk, dcOpts.CollectionOptions.Namespace)
102+
if err != nil {
103+
return err
104+
}
105+
106+
err = r.DeleteCollection(dcOpts.AsDeleteOptions(), *dcOpts.CollectionOptions.AsListOptions())
91107
return err
92108
}
93109

0 commit comments

Comments
 (0)