Fix race conditions in kube.GetResourcesWithLabel and DeleteResourceWithLabel (issue #587) (#593)

This commit is contained in:
Jesse Suen 2018-09-13 13:58:47 -07:00 committed by GitHub
parent 15ce7ea880
commit fb17589af6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -330,12 +330,11 @@ func GetResourcesWithLabel(config *rest.Config, namespace string, labelName stri
var asyncErr error
var result []*unstructured.Unstructured
var wg sync.WaitGroup
var lock sync.Mutex
wg.Add(len(resourceInterfaces))
for i := range resourceInterfaces {
client := resourceInterfaces[i]
go func() {
for _, c := range resourceInterfaces {
go func(client dynamic.ResourceInterface) {
defer wg.Done()
list, err := client.List(metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s", labelName, labelValue),
@ -350,11 +349,13 @@ func GetResourcesWithLabel(config *rest.Config, namespace string, labelName stri
labels := item.GetLabels()
if labels != nil {
if value, ok := labels[labelName]; ok && value == labelValue {
lock.Lock()
result = append(result, &item)
lock.Unlock()
}
}
}
}()
}(c)
}
wg.Wait()
return result, asyncErr
@ -372,10 +373,11 @@ func DeleteResourceWithLabel(config *rest.Config, namespace string, labelName st
return err
}
var resourceInterfaces []struct {
type resClient struct {
dynamic.ResourceInterface
bool
deleteCollectionSupported bool
}
var resourceInterfaces []resClient
for _, apiResourcesList := range resources {
for i := range apiResourcesList.APIResources {
@ -395,10 +397,10 @@ func DeleteResourceWithLabel(config *rest.Config, namespace string, labelName st
}
if deleteCollectionSupported || deleteSupported {
resourceInterfaces = append(resourceInterfaces, struct {
dynamic.ResourceInterface
bool
}{dclient.Resource(&apiResource, namespace), deleteCollectionSupported})
resourceInterfaces = append(resourceInterfaces, resClient{
dclient.Resource(&apiResource, namespace),
deleteCollectionSupported,
})
}
}
}
@ -409,13 +411,10 @@ func DeleteResourceWithLabel(config *rest.Config, namespace string, labelName st
var wg sync.WaitGroup
wg.Add(len(resourceInterfaces))
for i := range resourceInterfaces {
client := resourceInterfaces[i].ResourceInterface
deleteCollectionSupported := resourceInterfaces[i].bool
go func() {
for _, c := range resourceInterfaces {
go func(client resClient) {
defer wg.Done()
if deleteCollectionSupported {
if client.deleteCollectionSupported {
err = client.DeleteCollection(&metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
}, metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", labelName, labelValue)})
@ -444,7 +443,7 @@ func DeleteResourceWithLabel(config *rest.Config, namespace string, labelName st
}
}
}
}()
}(c)
}
wg.Wait()
return asyncErr