util.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2015 The etcd Authors
  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. endpoint := endpoints[dialTotal%len(endpoints)]
  29. dialTotal++
  30. cfg := clientv3.Config{Endpoints: []string{endpoint}}
  31. if !tls.Empty() {
  32. cfgtls, err := tls.ClientConfig()
  33. if err != nil {
  34. fmt.Fprintf(os.Stderr, "bad tls config: %v\n", err)
  35. os.Exit(1)
  36. }
  37. cfg.TLS = cfgtls
  38. }
  39. if len(user) != 0 {
  40. splitted := strings.SplitN(user, ":", 2)
  41. if len(splitted) != 2 {
  42. fmt.Fprintf(os.Stderr, "bad user information: %s\n", user)
  43. os.Exit(1)
  44. }
  45. cfg.Username = splitted[0]
  46. cfg.Password = splitted[1]
  47. }
  48. client, err := clientv3.New(cfg)
  49. if err != nil {
  50. fmt.Fprintf(os.Stderr, "dial error: %v\n", err)
  51. os.Exit(1)
  52. }
  53. return client
  54. }
  55. func mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {
  56. conns := make([]*clientv3.Client, totalConns)
  57. for i := range conns {
  58. conns[i] = mustCreateConn()
  59. }
  60. clients := make([]*clientv3.Client, totalClients)
  61. for i := range clients {
  62. clients[i] = conns[i%int(totalConns)]
  63. }
  64. return clients
  65. }
  66. func mustRandBytes(n int) []byte {
  67. rb := make([]byte, n)
  68. _, err := rand.Read(rb)
  69. if err != nil {
  70. fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
  71. os.Exit(1)
  72. }
  73. return rb
  74. }