guarantee the read-write operation for cache token is atomic

This commit is contained in:
Wenkai Yin 2016-05-13 16:09:43 +08:00 committed by Tan Jiang
parent 81d2d515c9
commit 0e7daf9bd4

View File

@ -22,6 +22,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"sync"
"time" "time"
token_util "github.com/vmware/harbor/service/token" token_util "github.com/vmware/harbor/service/token"
@ -48,6 +49,7 @@ type tokenHandler struct {
cache string // cached token cache string // cached token
expiresIn int // The duration in seconds since the token was issued that it will remain valid expiresIn int // The duration in seconds since the token was issued that it will remain valid
issuedAt *time.Time // The RFC3339-serialized UTC standard time at which a given token was issued issuedAt *time.Time // The RFC3339-serialized UTC standard time at which a given token was issued
sync.Mutex
} }
// Scheme returns the scheme that the handler can handle // Scheme returns the scheme that the handler can handle
@ -77,8 +79,10 @@ func (t *tokenHandler) AuthorizeRequest(req *http.Request, params map[string]str
expired := true expired := true
if t.expiresIn != 0 && t.issuedAt != nil { cachedToken, cachedExpiredIn, cachedIssuedAt := t.getCachedToken()
expired = t.issuedAt.Add(time.Duration(t.expiresIn) * time.Second).Before(time.Now().UTC())
if len(cachedToken) != 0 && cachedExpiredIn != 0 && cachedIssuedAt != nil {
expired = cachedIssuedAt.Add(time.Duration(cachedExpiredIn) * time.Second).Before(time.Now().UTC())
} }
if expired || hasFrom { if expired || hasFrom {
@ -93,13 +97,11 @@ func (t *tokenHandler) AuthorizeRequest(req *http.Request, params map[string]str
token = to token = to
if !hasFrom { if !hasFrom {
t.cache = token t.updateCachedToken(to, expiresIn, issuedAt)
t.expiresIn = expiresIn
t.issuedAt = issuedAt
log.Debug("add token to cache") log.Debug("add token to cache")
} }
} else { } else {
token = t.cache token = cachedToken
log.Debug("get token from cache") log.Debug("get token from cache")
} }
@ -109,6 +111,20 @@ func (t *tokenHandler) AuthorizeRequest(req *http.Request, params map[string]str
return nil return nil
} }
func (t *tokenHandler) getCachedToken() (string, int, *time.Time) {
t.Lock()
defer t.Unlock()
return t.cache, t.expiresIn, t.issuedAt
}
func (t *tokenHandler) updateCachedToken(token string, expiresIn int, issuedAt *time.Time) {
t.Lock()
defer t.Unlock()
t.cache = token
t.expiresIn = expiresIn
t.issuedAt = issuedAt
}
// Implements interface Handler // Implements interface Handler
type standardTokenHandler struct { type standardTokenHandler struct {
tokenHandler tokenHandler