Add token cache

Token cache prevents the need to get a new token for every registry interaction.
Since the tokens are short lived, the cache expires after only a minute.

Signed-off-by: Derek McGowan <derek@mcgstyle.net> (github: dmcgowan)
This commit is contained in:
Derek McGowan 2015-01-15 13:06:52 -08:00
parent 5bf94a6438
commit 9c24fc93ad

View file

@ -10,6 +10,8 @@ import (
"os" "os"
"path" "path"
"strings" "strings"
"sync"
"time"
log "github.com/Sirupsen/logrus" log "github.com/Sirupsen/logrus"
"github.com/docker/docker/utils" "github.com/docker/docker/utils"
@ -43,6 +45,10 @@ type RequestAuthorization struct {
resource string resource string
scope string scope string
actions []string actions []string
tokenLock sync.Mutex
tokenCache string
tokenExpiration time.Time
} }
func NewRequestAuthorization(authConfig *AuthConfig, registryEndpoint *Endpoint, resource, scope string, actions []string) *RequestAuthorization { func NewRequestAuthorization(authConfig *AuthConfig, registryEndpoint *Endpoint, resource, scope string, actions []string) *RequestAuthorization {
@ -56,7 +62,14 @@ func NewRequestAuthorization(authConfig *AuthConfig, registryEndpoint *Endpoint,
} }
func (auth *RequestAuthorization) getToken() (string, error) { func (auth *RequestAuthorization) getToken() (string, error) {
// TODO check if already has token and before expiration auth.tokenLock.Lock()
defer auth.tokenLock.Unlock()
now := time.Now()
if now.Before(auth.tokenExpiration) {
log.Debugf("Using cached token for %s", auth.authConfig.Username)
return auth.tokenCache, nil
}
client := &http.Client{ client := &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
DisableKeepAlives: true, DisableKeepAlives: true,
@ -80,14 +93,18 @@ func (auth *RequestAuthorization) getToken() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
// TODO cache token and set expiration to one minute from now auth.tokenCache = token
auth.tokenExpiration = now.Add(time.Minute)
return token, nil return token, nil
default: default:
log.Infof("Unsupported auth scheme: %q", challenge.Scheme) log.Infof("Unsupported auth scheme: %q", challenge.Scheme)
} }
} }
// TODO no expiration, do not reattempt to get a token
// Do not expire cache since there are no challenges which use a token
auth.tokenExpiration = time.Now().Add(time.Hour * 24)
return "", nil return "", nil
} }