-
Notifications
You must be signed in to change notification settings - Fork 289
feat: allow list items to be processed in parallel #738
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shady-canva
wants to merge
1
commit into
argoproj:master
Choose a base branch
from
Canva:shady-parallel-list-item-processing
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -56,6 +56,8 @@ const ( | |
// Limit is required to avoid memory spikes during cache initialization. | ||
// The default limit of 50 is chosen based on experiments. | ||
defaultListSemaphoreWeight = 50 | ||
// defaultListItemSemaphoreWeight limits the amount of items to process in parallel for each k8s list. | ||
defaultListItemSemaphoreWeight = int64(1) | ||
// defaultEventProcessingInterval is the default interval for processing events | ||
defaultEventProcessingInterval = 100 * time.Millisecond | ||
) | ||
|
@@ -164,15 +166,16 @@ type ListRetryFunc func(err error) bool | |
func NewClusterCache(config *rest.Config, opts ...UpdateSettingsFunc) *clusterCache { | ||
log := textlogger.NewLogger(textlogger.NewConfig()) | ||
cache := &clusterCache{ | ||
settings: Settings{ResourceHealthOverride: &noopSettings{}, ResourcesFilter: &noopSettings{}}, | ||
apisMeta: make(map[schema.GroupKind]*apiMeta), | ||
eventMetaCh: nil, | ||
listPageSize: defaultListPageSize, | ||
listPageBufferSize: defaultListPageBufferSize, | ||
listSemaphore: semaphore.NewWeighted(defaultListSemaphoreWeight), | ||
resources: make(map[kube.ResourceKey]*Resource), | ||
nsIndex: make(map[string]map[kube.ResourceKey]*Resource), | ||
config: config, | ||
settings: Settings{ResourceHealthOverride: &noopSettings{}, ResourcesFilter: &noopSettings{}}, | ||
apisMeta: make(map[schema.GroupKind]*apiMeta), | ||
eventMetaCh: nil, | ||
listPageSize: defaultListPageSize, | ||
listPageBufferSize: defaultListPageBufferSize, | ||
listSemaphore: semaphore.NewWeighted(defaultListSemaphoreWeight), | ||
listItemSemaphoreWeight: defaultListItemSemaphoreWeight, | ||
resources: make(map[kube.ResourceKey]*Resource), | ||
nsIndex: make(map[string]map[kube.ResourceKey]*Resource), | ||
config: config, | ||
kubectl: &kube.KubectlCmd{ | ||
Log: log, | ||
Tracer: tracing.NopTracer{}, | ||
|
@@ -219,8 +222,9 @@ type clusterCache struct { | |
// size of a page for list operations pager. | ||
listPageSize int64 | ||
// number of pages to prefetch for list pager. | ||
listPageBufferSize int32 | ||
listSemaphore WeightedSemaphore | ||
listPageBufferSize int32 | ||
listSemaphore WeightedSemaphore | ||
listItemSemaphoreWeight int64 | ||
|
||
// retry options for list operations | ||
listRetryLimit int32 | ||
|
@@ -262,6 +266,35 @@ type clusterCacheSync struct { | |
resyncTimeout time.Duration | ||
} | ||
|
||
// listItemTaskLimiter limits the amount of list items to process in parallel. | ||
type listItemTaskLimiter struct { | ||
sem WeightedSemaphore | ||
wg sync.WaitGroup | ||
} | ||
|
||
// Run executes the given task concurrently, blocking if the pool is at capacity. | ||
func (t *listItemTaskLimiter) Run(ctx context.Context, task func()) error { | ||
t.wg.Add(1) | ||
if err := t.sem.Acquire(ctx, 1); err != nil { | ||
t.wg.Done() | ||
return fmt.Errorf("failed to acquire semaphore: %w", err) | ||
} | ||
|
||
go func() { | ||
defer t.wg.Done() | ||
defer t.sem.Release(1) | ||
|
||
task() | ||
}() | ||
|
||
return nil | ||
} | ||
|
||
// Wait blocks until all submitted tasks have completed. | ||
func (t *listItemTaskLimiter) Wait() { | ||
t.wg.Wait() | ||
} | ||
|
||
// ListRetryFuncNever never retries on errors | ||
func ListRetryFuncNever(_ error) bool { | ||
return false | ||
|
@@ -446,6 +479,13 @@ func (c *clusterCache) newResource(un *unstructured.Unstructured) *Resource { | |
return resource | ||
} | ||
|
||
func (c *clusterCache) newListItemTaskLimiter() *listItemTaskLimiter { | ||
return &listItemTaskLimiter{ | ||
sem: semaphore.NewWeighted(c.listItemSemaphoreWeight), | ||
wg: sync.WaitGroup{}, | ||
} | ||
} | ||
|
||
func (c *clusterCache) setNode(n *Resource) { | ||
key := n.ResourceKey() | ||
c.resources[key] = n | ||
|
@@ -629,17 +669,33 @@ func (c *clusterCache) listResources(ctx context.Context, resClient dynamic.Reso | |
|
||
// loadInitialState loads the state of all the resources retrieved by the given resource client. | ||
func (c *clusterCache) loadInitialState(ctx context.Context, api kube.APIResourceInfo, resClient dynamic.ResourceInterface, ns string, lock bool) (string, error) { | ||
var items []*Resource | ||
var ( | ||
items []*Resource | ||
listLock = sync.Mutex{} | ||
limiter = c.newListItemTaskLimiter() | ||
) | ||
|
||
resourceVersion, err := c.listResources(ctx, resClient, func(listPager *pager.ListPager) error { | ||
return listPager.EachListItem(ctx, metav1.ListOptions{}, func(obj runtime.Object) error { | ||
if un, ok := obj.(*unstructured.Unstructured); !ok { | ||
return fmt.Errorf("object %s/%s has an unexpected type", un.GroupVersionKind().String(), un.GetName()) | ||
} else { | ||
items = append(items, c.newResource(un)) | ||
if err := limiter.Run(ctx, func() { | ||
newRes := c.newResource(un) | ||
listLock.Lock() | ||
items = append(items, newRes) | ||
listLock.Unlock() | ||
}); err != nil { | ||
return fmt.Errorf("failed to process list item: %w", err) | ||
} | ||
} | ||
return nil | ||
}) | ||
}) | ||
Comment on lines
678
to
694
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just to call this out as a trade-off, I think this will cause a change in ordering when using concurrency. But this is only when its enabled. Not a bad trade-off, just something to be aware of. |
||
|
||
// Wait until all items have completed processing. | ||
limiter.Wait() | ||
|
||
if err != nil { | ||
return "", fmt.Errorf("failed to load initial state of resource %s: %w", api.GroupKind.String(), err) | ||
} | ||
|
@@ -938,19 +994,29 @@ func (c *clusterCache) sync() error { | |
lock.Unlock() | ||
|
||
return c.processApi(client, api, func(resClient dynamic.ResourceInterface, ns string) error { | ||
limiter := c.newListItemTaskLimiter() | ||
|
||
resourceVersion, err := c.listResources(ctx, resClient, func(listPager *pager.ListPager) error { | ||
return listPager.EachListItem(context.Background(), metav1.ListOptions{}, func(obj runtime.Object) error { | ||
if un, ok := obj.(*unstructured.Unstructured); !ok { | ||
return fmt.Errorf("object %s/%s has an unexpected type", un.GroupVersionKind().String(), un.GetName()) | ||
} else { | ||
newRes := c.newResource(un) | ||
lock.Lock() | ||
c.setNode(newRes) | ||
lock.Unlock() | ||
if err := limiter.Run(ctx, func() { | ||
newRes := c.newResource(un) | ||
lock.Lock() | ||
c.setNode(newRes) | ||
lock.Unlock() | ||
}); err != nil { | ||
return fmt.Errorf("failed to process list item: %w", err) | ||
} | ||
} | ||
return nil | ||
}) | ||
}) | ||
|
||
// Wait until all items have completed processing. | ||
limiter.Wait() | ||
|
||
if err != nil { | ||
if c.isRestrictedResource(err) { | ||
keep := false | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is great that it maintains existing behavior by default