fix: ScalerCache gets the lock before operate the scalers #6739
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.
With the current implementation, a race condition can happen because we check the scalers size before signaling the lock, so hypothetically, the value of
c.Scalers
can change between the line when it's checked and the line when is accessed, allowing the case wherec.Scalers
is cleaned and then the index is accessed, generating a panic because of accessing out of the array length.Checking the code and considering the original problem of the issue, my hypothesis is that the scaler fails during the HPA metric request. It calls to GetScaledObjectMetrics and there, after the scaler failure, the whole ScaledObject is refreshed, triggering the only code that changes the value of
c.Scalers
from a valid slice tonil
. (cache Close())If an operator loop starts just after the metric requests, it could happen that the refresh action has been triggered over the current cache item that is in process of being revoked, generating the race condition because the length of
s.Scalers
has been verified without any lock (so in theory the index exists), and then the execution pointer has waited until the write lock is released (whenc.Scalers
is alreadynil
). As soon as the Close() code ends, the lock is released and the code within the refresh function continues, trying to access an index that existed during the check but not during the access because of not locking the read lock before checkingc.Scalers
Checklist
Fixes #6725