util.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "strings"
  20. "github.com/coreos/etcd/clientv3"
  21. )
  22. var (
  23. // dialTotal counts the number of mustCreateConn calls so that endpoint
  24. // connections can be handed out in round-robin order
  25. dialTotal int
  26. )
  27. func mustCreateConn() *clientv3.Client {
  28. eps := strings.Split(endpoints, ",")
  29. endpoint := eps[dialTotal%len(eps)]
  30. dialTotal++
  31. cfgtls := &tls
  32. if cfgtls.Empty() {
  33. cfgtls = nil
  34. }
  35. client, err := clientv3.New(
  36. clientv3.Config{
  37. Endpoints: []string{endpoint},
  38. TLS: cfgtls,
  39. },
  40. )
  41. if err != nil {
  42. fmt.Fprintf(os.Stderr, "dial error: %v\n", err)
  43. os.Exit(1)
  44. }
  45. return client
  46. }
  47. func mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {
  48. conns := make([]*clientv3.Client, totalConns)
  49. for i := range conns {
  50. conns[i] = mustCreateConn()
  51. }
  52. clients := make([]*clientv3.Client, totalClients)
  53. for i := range clients {
  54. clients[i] = conns[i%int(totalConns)]
  55. }
  56. return clients
  57. }
  58. func mustRandBytes(n int) []byte {
  59. rb := make([]byte, n)
  60. _, err := rand.Read(rb)
  61. if err != nil {
  62. fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
  63. os.Exit(1)
  64. }
  65. return rb
  66. }