You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

distlock.go 2.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package cmdline
  2. /*
  3. import (
  4. "fmt"
  5. "strings"
  6. "github.com/samber/lo"
  7. "gitlink.org.cn/cloudream/common/pkgs/distlock"
  8. "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/distlock/lockprovider"
  9. )
  10. // DistLockLock 尝试获取分布式锁。
  11. // ctx: 命令上下文,包含执行命令所需的服务和配置。
  12. // lockData: 锁数据数组,每个元素包含锁的路径、名称和目标。
  13. // 返回值: 获取锁失败时返回错误。
  14. func DistLockLock(ctx CommandContext, lockData []string) error {
  15. req := distlock.LockRequest{}
  16. // 解析锁数据,填充请求结构体。
  17. for _, lock := range lockData {
  18. l, err := parseOneLock(lock)
  19. if err != nil {
  20. return fmt.Errorf("parse lock data %s failed, err: %w", lock, err)
  21. }
  22. req.Locks = append(req.Locks, l)
  23. }
  24. // 请求分布式锁。
  25. reqID, err := ctx.Cmdline.Svc.DistLock.Acquire(req)
  26. if err != nil {
  27. return fmt.Errorf("acquire locks failed, err: %w", err)
  28. }
  29. fmt.Printf("%s\n", reqID)
  30. return nil
  31. }
  32. // parseOneLock 解析单个锁数据。
  33. // lockData: 待解析的锁数据,格式为"路径/名称@目标字符串"。
  34. // 返回值: 解析得到的锁对象和可能的错误。
  35. func parseOneLock(lockData string) (distlock.Lock, error) {
  36. var lock distlock.Lock
  37. // 解析锁的路径、名称和目标。
  38. fullPathAndTarget := strings.Split(lockData, "@")
  39. if len(fullPathAndTarget) != 2 {
  40. return lock, fmt.Errorf("lock data must contains lock path, name and target")
  41. }
  42. pathAndName := strings.Split(fullPathAndTarget[0], "/")
  43. if len(pathAndName) < 2 {
  44. return lock, fmt.Errorf("lock data must contains lock path, name and target")
  45. }
  46. lock.Path = pathAndName[0 : len(pathAndName)-1]
  47. lock.Name = pathAndName[len(pathAndName)-1]
  48. // 解析目标字符串。
  49. target := lockprovider.NewStringLockTarget()
  50. comps := strings.Split(fullPathAndTarget[1], "/")
  51. for _, comp := range comps {
  52. target.Add(lo.Map(strings.Split(comp, "."), func(str string, index int) any { return str })...)
  53. }
  54. lock.Target = *target
  55. return lock, nil
  56. }
  57. // DistLockUnlock 释放分布式锁。
  58. // ctx: 命令上下文。
  59. // reqID: 请求ID,对应获取锁时返回的ID。
  60. // 返回值: 释放锁失败时返回错误。
  61. func DistLockUnlock(ctx CommandContext, reqID string) error {
  62. ctx.Cmdline.Svc.DistLock.Release(reqID)
  63. return nil
  64. }
  65. // 初始化命令行工具,注册分布式锁相关命令。
  66. func init() {
  67. commands.MustAdd(DistLockLock, "distlock", "lock")
  68. commands.MustAdd(DistLockUnlock, "distlock", "unlock")
  69. }
  70. */

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。