Skip to content

Commit

Permalink
ADD: token cli to help the user to manage the namespace and the token
Browse files Browse the repository at this point in the history
  • Loading branch information
git-hulk committed Nov 22, 2019
1 parent e612598 commit baf463b
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 6 deletions.
8 changes: 5 additions & 3 deletions README.md
Expand Up @@ -32,6 +32,8 @@ To start in developing mode:
./_build/lmstfy-server -c config/demo-conf.toml -bt debug -sv
```

**You can use the `./scripts/token-cli` to manage the namesace and the token**

## HTTP API

From a thousand miles above, the main work flow looks like:
Expand Down Expand Up @@ -182,15 +184,15 @@ NOTE: to consume multiple queues, `timeout` (seconds) must be specified.
```

- 400

```
{
"error": string
}
```

- 404

```
{
"msg": "no job available"
Expand Down Expand Up @@ -278,7 +280,7 @@ NOTE: Peek can't return the job data if its ttl expired.
```

- 404

```
{
"error": "job not found"
Expand Down
16 changes: 16 additions & 0 deletions auth/token.go
@@ -1,16 +1,20 @@
package auth

import (
"errors"
"strings"
"sync"

"github.com/go-redis/redis"
"github.com/meitu/lmstfy/config"
"github.com/meitu/lmstfy/engine"
"github.com/meitu/lmstfy/uuid"
)

const TokenPrefix = "tk"

var ErrPoolNotExist error = errors.New("the pool was not exists")

type TokenManager struct {
cli *redis.Client
cache map[string]bool // Caching {pool+namespace+token} => bool
Expand Down Expand Up @@ -53,6 +57,9 @@ func NewTokenManager(cli *redis.Client) *TokenManager {
}

func (tm *TokenManager) New(pool, namespace, description string) (token string, err error) {
if exists := engine.ExistsPool(pool); !exists {
return "", ErrPoolNotExist
}
token = uuid.GenUniqueID()
err = tm.cli.HSet(tokenKey(pool, namespace), token, description).Err()
if err != nil {
Expand All @@ -68,6 +75,9 @@ func (tm *TokenManager) New(pool, namespace, description string) (token string,
}

func (tm *TokenManager) Exist(pool, namespace, token string) (exist bool, err error) {
if exists := engine.ExistsPool(pool); !exists {
return false, ErrPoolNotExist
}
tm.rwmu.RLock()
if tm.cache[cacheKey(pool, namespace, token)] {
tm.rwmu.RUnlock()
Expand All @@ -84,13 +94,19 @@ func (tm *TokenManager) Exist(pool, namespace, token string) (exist bool, err er
}

func (tm *TokenManager) Delete(pool, namespace, token string) error {
if exists := engine.ExistsPool(pool); !exists {
return ErrPoolNotExist
}
tm.rwmu.Lock()
delete(tm.cache, cacheKey(pool, namespace, token))
tm.rwmu.Unlock()
return tm.cli.HDel(tokenKey(pool, namespace), token).Err()
}

func (tm *TokenManager) List(pool, namespace string) (tokens map[string]string, err error) {
if exists := engine.ExistsPool(pool); !exists {
return nil, ErrPoolNotExist
}
val, err := tm.cli.HGetAll(tokenKey(pool, namespace)).Result()
if err != nil {
return nil, err
Expand Down
7 changes: 7 additions & 0 deletions engine/engine.go
Expand Up @@ -56,6 +56,13 @@ func GetPools() []string {
return GetPoolsByKind("redis")
}

func ExistsPool(pool string) bool {
if pool == "" {
pool = "default"
}
return GetEngine(pool) != nil
}

func GetEngine(pool string) Engine {
if pool == "" {
pool = config.DefaultPoolName
Expand Down
62 changes: 62 additions & 0 deletions scripts/token-cli
@@ -0,0 +1,62 @@
#!/usr/bin/python

import argparse
import requests

# arguments
examples = """examples:
./token-cli 127.0.0.1:7778 --pools # list pools
./token-cli 127.0.0.1:7778 -c -p pool -n namespace -D description # create new namespace
./token-cli 127.0.0.1:7778 -d -p pool -n namespace # delete the namespace
./token-cli 127.0.0.1:7778 -l -p pool -n namespace # list tokens in namespace
"""
parser = parser = argparse.ArgumentParser(
description="Manage the namepace and tokens",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)

parser.add_argument("server", type=str, help="the server address(host:port)")
parser.add_argument("-D", "--description", type=str, help="the description")
parser.add_argument("-p", "--pool", type=str, help="the name of pool")
parser.add_argument("-n", "--namespace", type=str, help="the name of namespace")
parser.add_argument("-t", "--token", type=str, help="the token to delete")
parser.add_argument("-c", "--create", action="store_true", help="create the namespace")
parser.add_argument("-d", "--delete", action="store_true", help="delete the namespace")
parser.add_argument("-l", "--list", action="store_true", help="list tokens")
parser.add_argument("-P", "--pools", action="store_true", help="list pools")
args = parser.parse_args()

addr = "http://"+args.server
if args.pools:
r = requests.get(addr+"/pools")
print(r.text)
exit(0)

if args.namespace == None:
print("param 'namespace' is missing, please use -n to assign the namespace")
exit(1)
if args.create and args.description == None:
print("param 'description' is missing, please use -D to assign the description")
exit(1)
if args.delete and args.token == None:
print("param 'token' is missing, please use -t to assign the token")
exit(1)

if args.pool == None:
args.pool = ""

if args.list:
r = requests.get(addr+"/token/"+args.namespace+"?pool="+args.pool)
print(r.text)
elif args.create:
r = requests.post(addr+"/token/"+args.namespace+"?pool="+args.pool, data = {'description':args.description})
print(r.text)
elif args.delete:
r = requests.delete(addr+"/token/"+args.namespace+"/"+args.token+"?pool="+args.pool)
if r.status_code == 204:
print("ok")
else:
print(r.text)
else:
print("aha, I'm do nothing.")

18 changes: 15 additions & 3 deletions server/handlers/admin.go
Expand Up @@ -27,7 +27,11 @@ func ListTokens(c *gin.Context) {
tm := auth.GetTokenManager()
tokens, err := tm.List(c.Query("pool"), c.Param("namespace"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
if err == auth.ErrPoolNotExist {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
}
return
}
c.IndentedJSON(http.StatusOK, gin.H{"tokens": tokens})
Expand All @@ -48,7 +52,11 @@ func NewToken(c *gin.Context) {
tm := auth.GetTokenManager()
token, err := tm.New(c.Query("pool"), c.Param("namespace"), desc)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
if err == auth.ErrPoolNotExist {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
}
return
}
c.IndentedJSON(http.StatusCreated, gin.H{"token": token})
Expand All @@ -58,7 +66,11 @@ func NewToken(c *gin.Context) {
func DeleteToken(c *gin.Context) {
tm := auth.GetTokenManager()
if err := tm.Delete(c.Query("pool"), c.Param("namespace"), c.Param("token")); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
if err == auth.ErrPoolNotExist {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
}
return
}
c.Status(http.StatusNoContent)
Expand Down

0 comments on commit baf463b

Please sign in to comment.