util.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cmd
  15. import (
  16. "crypto/rand"
  17. "fmt"
  18. "os"
  19. "github.com/coreos/etcd/clientv3"
  20. )
  21. var (
  22. // dialTotal counts the number of mustCreateConn calls so that endpoint
  23. // connections can be handed out in round-robin order
  24. dialTotal int
  25. )
  26. func mustCreateConn() *clientv3.Client {
  27. endpoint := endpoints[dialTotal%len(endpoints)]
  28. dialTotal++
  29. cfgtls := &tls
  30. if cfgtls.Empty() {
  31. cfgtls = nil
  32. }
  33. client, err := clientv3.New(
  34. clientv3.Config{
  35. Endpoints: []string{endpoint},
  36. TLS: cfgtls,
  37. },
  38. )
  39. if err != nil {
  40. fmt.Fprintf(os.Stderr, "dial error: %v\n", err)
  41. os.Exit(1)
  42. }
  43. return client
  44. }
  45. func mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {
  46. conns := make([]*clientv3.Client, totalConns)
  47. for i := range conns {
  48. conns[i] = mustCreateConn()
  49. }
  50. clients := make([]*clientv3.Client, totalClients)
  51. for i := range clients {
  52. clients[i] = conns[i%int(totalConns)]
  53. }
  54. return clients
  55. }
  56. func mustRandBytes(n int) []byte {
  57. rb := make([]byte, n)
  58. _, err := rand.Read(rb)
  59. if err != nil {
  60. fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
  61. os.Exit(1)
  62. }
  63. return rb
  64. }