shard.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package datahub
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "strings"
  7. )
  8. type ShardEntry struct {
  9. ShardId string `json:"ShardId"`
  10. State ShardState `json:"State"`
  11. BeginHashKey string `json:"BeginHashKey"`
  12. EndHashKey string `json:"EndHashKey"`
  13. ClosedTime int64 `json:"ClosedTime"`
  14. ParentShardIds []string `json:"ParentShardIds"`
  15. LeftShardId string `json:"LeftShardId"`
  16. RightShardId string `json:"RightShardId"`
  17. Address string `json:"Address"`
  18. }
  19. func generateSpliteKey(projectName, topicName, shardId string, datahub DataHubApi) (string, error) {
  20. ls, err := datahub.ListShard(projectName, topicName)
  21. if err != nil {
  22. return "", err
  23. }
  24. shards := ls.Shards
  25. splitKey := ""
  26. for _, shard := range shards {
  27. if strings.EqualFold(shardId, shard.ShardId) {
  28. if shard.State != ACTIVE {
  29. return "", errors.New(fmt.Sprintf("Only active shard can be split,the shard %s state is %s", shard.ShardId, shard.State))
  30. }
  31. splitKey, err = getSplitKey(shard.BeginHashKey, shard.EndHashKey)
  32. splitKey = strings.ToUpper(splitKey)
  33. if err != nil {
  34. return "", err
  35. }
  36. }
  37. }
  38. if splitKey == "" {
  39. return "", errors.New(fmt.Sprintf("Shard not exist"))
  40. }
  41. return splitKey, nil
  42. }
  43. func getSplitKey(beginHashKey, endHashKey string) (string, error) {
  44. var begin, end, sum, quo big.Int
  45. base := 16
  46. if len(beginHashKey) != 32 || len(endHashKey) != 32 {
  47. return "", errors.New(fmt.Sprintf("Invalid Hash Key Range", ))
  48. }
  49. _, ok := begin.SetString(beginHashKey, base)
  50. if !ok {
  51. return "", errors.New(fmt.Sprintf("Invalid Hash Key Range"))
  52. }
  53. _, ok = end.SetString(endHashKey, base)
  54. if !ok {
  55. return "", errors.New(fmt.Sprintf("Invalid Hash Key Range"))
  56. }
  57. sum.Add(&begin, &end)
  58. quo.Quo(&sum, big.NewInt(2))
  59. return quo.Text(base), nil
  60. }