Skip to content
This repository has been archived by the owner on Jan 8, 2024. It is now read-only.

Commit

Permalink
Don't reissue tokens for the same task id
Browse files Browse the repository at this point in the history
  • Loading branch information
nemosupremo committed May 3, 2016
1 parent 8b120cf commit cb62fcf
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
12 changes: 12 additions & 0 deletions provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
)

var errTaskNotFresh = errors.New("This task has been running too long to request a token.")
var errAlreadyGivenKey = errors.New("This task has already been given a token.")
var usedTaskIds = NewTtlSet()

func createToken(token string, opts interface{}) (string, error) {
r, err := goreq.Request{
Expand Down Expand Up @@ -113,6 +115,15 @@ func Provide(c *gin.Context) {
decoder := json.NewDecoder(c.Request.Body)
if err := decoder.Decode(&reqParams); err == nil {
if task, err := getMesosTask(reqParams.TaskId); err == nil {
if usedTaskIds.Has(reqParams.TaskId) {
atomic.AddInt32(&state.Stats.Denied, 1)
c.JSON(403, struct {
Status string `json:"status"`
Ok bool `json:"ok"`
Error string `json:"error"`
}{string(state.Status), false, errAlreadyGivenKey.Error()})
return
}
startTime := time.Unix(0, int64(task.Statuses[len(task.Statuses)-1].Timestamp*1000000000))
if time.Now().Sub(startTime) > config.MaxTaskLife {
atomic.AddInt32(&state.Stats.Denied, 1)
Expand All @@ -128,6 +139,7 @@ func Provide(c *gin.Context) {
state.RUnlock()
if tempToken, err := createTokenPair(token, policy); err == nil {
atomic.AddInt32(&state.Stats.Successful, 1)
usedTaskIds.Put(reqParams.TaskId, config.MaxTaskLife+1*time.Minute)
c.JSON(200, struct {
Status string `json:"status"`
Ok bool `json:"ok"`
Expand Down
55 changes: 55 additions & 0 deletions ttlset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"sync"
"time"
)

type TtlSet struct {
sync.RWMutex
s map[string]time.Time
quit chan struct{}
}

func NewTtlSet() *TtlSet {
t := &TtlSet{}
t.s = make(map[string]time.Time)
t.quit = make(chan struct{})
go t.garbageCollector()
return t
}

func (t *TtlSet) Has(key string) bool {
t.RLock()
defer t.RUnlock()
_, ok := t.s[key]
return ok
}

func (t *TtlSet) Put(key string, ttl time.Duration) {
t.Lock()
t.s[key] = time.Now().Add(ttl)
t.Unlock()
}

func (t *TtlSet) cleanup() {
t.Lock()
for k, v := range t.s {
if time.Now().After(v) {
delete(t.s, k)
}
}
t.Unlock()
}

func (t *TtlSet) garbageCollector() {
ticker := time.Tick(5 * time.Second)
for {
select {
case <-ticker:
t.cleanup()
case <-t.quit:
return
}
}
}

0 comments on commit cb62fcf

Please sign in to comment.