util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package zk
  2. import (
  3. "crypto/sha1"
  4. "encoding/base64"
  5. "fmt"
  6. "math/rand"
  7. "strconv"
  8. "strings"
  9. )
  10. // AuthACL produces an ACL list containing a single ACL which uses the
  11. // provided permissions, with the scheme "auth", and ID "", which is used
  12. // by ZooKeeper to represent any authenticated user.
  13. func AuthACL(perms int32) []ACL {
  14. return []ACL{{perms, "auth", ""}}
  15. }
  16. // WorldACL produces an ACL list containing a single ACL which uses the
  17. // provided permissions, with the scheme "world", and ID "anyone", which
  18. // is used by ZooKeeper to represent any user at all.
  19. func WorldACL(perms int32) []ACL {
  20. return []ACL{{perms, "world", "anyone"}}
  21. }
  22. func DigestACL(perms int32, user, password string) []ACL {
  23. userPass := []byte(fmt.Sprintf("%s:%s", user, password))
  24. h := sha1.New()
  25. if n, err := h.Write(userPass); err != nil || n != len(userPass) {
  26. panic("SHA1 failed")
  27. }
  28. digest := base64.StdEncoding.EncodeToString(h.Sum(nil))
  29. return []ACL{{perms, "digest", fmt.Sprintf("%s:%s", user, digest)}}
  30. }
  31. // FormatServers takes a slice of addresses, and makes sure they are in a format
  32. // that resembles <addr>:<port>. If the server has no port provided, the
  33. // DefaultPort constant is added to the end.
  34. func FormatServers(servers []string) []string {
  35. for i := range servers {
  36. if !strings.Contains(servers[i], ":") {
  37. servers[i] = servers[i] + ":" + strconv.Itoa(DefaultPort)
  38. }
  39. }
  40. return servers
  41. }
  42. // stringShuffle performs a Fisher-Yates shuffle on a slice of strings
  43. func stringShuffle(s []string) {
  44. for i := len(s) - 1; i > 0; i-- {
  45. j := rand.Intn(i + 1)
  46. s[i], s[j] = s[j], s[i]
  47. }
  48. }