Browse Source

增加加锁的命令行

gitlink
Sydonian 2 years ago
parent
commit
8634185ca9
3 changed files with 75 additions and 4 deletions
  1. +6
    -3
      internal/cmdline/commandline.go
  2. +68
    -0
      internal/cmdline/distlock.go
  3. +1
    -1
      main.go

+ 6
- 3
internal/cmdline/commandline.go View File

@@ -6,6 +6,7 @@ import (

"gitlink.org.cn/cloudream/client/internal/services"
"gitlink.org.cn/cloudream/common/pkg/cmdtrie"
distlocksvc "gitlink.org.cn/cloudream/common/pkg/distlock/service"
)

type CommandContext struct {
@@ -15,12 +16,14 @@ type CommandContext struct {
var commands cmdtrie.CommandTrie[CommandContext, error] = cmdtrie.NewCommandTrie[CommandContext, error]()

type Commandline struct {
Svc *services.Service
Svc *services.Service
DistLock *distlocksvc.Service
}

func NewCommandline(svc *services.Service) (*Commandline, error) {
func NewCommandline(svc *services.Service, distLock *distlocksvc.Service) (*Commandline, error) {
return &Commandline{
Svc: svc,
Svc: svc,
DistLock: distLock,
}, nil
}



+ 68
- 0
internal/cmdline/distlock.go View File

@@ -0,0 +1,68 @@
package cmdline

import (
"fmt"
"strings"

"gitlink.org.cn/cloudream/common/pkg/distlock"
"gitlink.org.cn/cloudream/common/pkg/distlock/lockprovider"
)

func DistLockLock(ctx CommandContext, lockData []string) error {
req := distlock.LockRequest{}

for _, lock := range lockData {
l, err := parseOneLock(lock)
if err != nil {
return fmt.Errorf("parse lock data %s failed, err: %w", lock, err)
}

req.Locks = append(req.Locks, l)
}

reqID, err := ctx.Cmdline.DistLock.Acquire(req)
if err != nil {
return fmt.Errorf("acquire locks failed, err: %w", err)
}

fmt.Printf("%s\n", reqID)

return nil
}

func parseOneLock(lockData string) (distlock.Lock, error) {
var lock distlock.Lock

fullPathAndTarget := strings.Split(lockData, "@")
if len(fullPathAndTarget) != 2 {
return lock, fmt.Errorf("lock data must contains lock path, name and target")
}

pathAndName := strings.Split(fullPathAndTarget[0], "/")
if len(pathAndName) < 2 {
return lock, fmt.Errorf("lock data must contains lock path, name and target")
}

lock.Path = pathAndName[0 : len(pathAndName)-1]
lock.Name = pathAndName[len(pathAndName)-1]

target := lockprovider.NewStringLockTarget()
comps := strings.Split(fullPathAndTarget[1], "/")
for _, comp := range comps {
target.Add(strings.Split(comp, "."))
}

lock.Target = *target

return lock, nil
}

func DistLockUnlock(ctx CommandContext, reqID string) error {
return ctx.Cmdline.DistLock.Release(reqID)
}

func init() {
commands.MustAdd(DistLockLock, "distlock", "lock")

commands.MustAdd(DistLockUnlock, "distlock", "unlock")
}

+ 1
- 1
main.go View File

@@ -64,7 +64,7 @@ func main() {
os.Exit(1)
}

cmds, err := cmdline.NewCommandline(svc)
cmds, err := cmdline.NewCommandline(svc, distlockSvc)
if err != nil {
log.Warnf("new command line failed, err: %s", err.Error())
os.Exit(1)


Loading…
Cancel
Save