Skip to content

Commit

Permalink
Use an explicit lock for dockerClient.tokenCache instead of sync.Map
Browse files Browse the repository at this point in the history
We will want to manage concurrency in more detail.

Should not change behavior.

Signed-off-by: Miloslav Trmač <[email protected]>
  • Loading branch information
mtrmac committed Jul 11, 2024
1 parent 1729768 commit 10367f7
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions docker/docker_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ type dockerClient struct {
supportsSignatures bool

// Private state for setupRequestAuth (key: string, value: bearerToken)
tokenCache sync.Map
tokenCacheLock sync.Mutex // Protects tokenCache
tokenCache map[string]bearerToken
// Private state for detectProperties:
detectPropertiesOnce sync.Once // detectPropertiesOnce is used to execute detectProperties() at most once.
detectPropertiesError error // detectPropertiesError caches the initial error.
Expand Down Expand Up @@ -269,6 +270,7 @@ func newDockerClient(sys *types.SystemContext, registry, reference string) (*doc
registry: registry,
userAgent: userAgent,
tlsClientConfig: tlsClientConfig,
tokenCache: map[string]bearerToken{},
reportedWarnings: set.New[string](),
}, nil
}
Expand Down Expand Up @@ -751,10 +753,12 @@ func (c *dockerClient) obtainBearerToken(ctx context.Context, challenge challeng
}

var token bearerToken
t, inCache := c.tokenCache.Load(cacheKey)
if inCache {
token = t.(bearerToken)
}
var inCache bool
func() { // A scope for defer
c.tokenCacheLock.Lock()
defer c.tokenCacheLock.Unlock()
token, inCache = c.tokenCache[cacheKey]
}()
if !inCache || time.Now().After(token.expirationTime) {
var (
t *bearerToken
Expand All @@ -770,7 +774,11 @@ func (c *dockerClient) obtainBearerToken(ctx context.Context, challenge challeng
}

token = *t
c.tokenCache.Store(cacheKey, token)
func() { // A scope for defer
c.tokenCacheLock.Lock()
defer c.tokenCacheLock.Unlock()
c.tokenCache[cacheKey] = token
}()
}
return token.token, nil
}
Expand Down

0 comments on commit 10367f7

Please sign in to comment.