util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "github.com/coreos/etcd/pkg/report"
  22. )
  23. var (
  24. // dialTotal counts the number of mustCreateConn calls so that endpoint
  25. // connections can be handed out in round-robin order
  26. dialTotal int
  27. )
  28. func mustCreateConn() *clientv3.Client {
  29. endpoint := endpoints[dialTotal%len(endpoints)]
  30. dialTotal++
  31. cfg := clientv3.Config{
  32. Endpoints: []string{endpoint},
  33. DialTimeout: dialTimeout,
  34. }
  35. if !tls.Empty() {
  36. cfgtls, err := tls.ClientConfig()
  37. if err != nil {
  38. fmt.Fprintf(os.Stderr, "bad tls config: %v\n", err)
  39. os.Exit(1)
  40. }
  41. cfg.TLS = cfgtls
  42. }
  43. if len(user) != 0 {
  44. splitted := strings.SplitN(user, ":", 2)
  45. if len(splitted) != 2 {
  46. fmt.Fprintf(os.Stderr, "bad user information: %s\n", user)
  47. os.Exit(1)
  48. }
  49. cfg.Username = splitted[0]
  50. cfg.Password = splitted[1]
  51. }
  52. client, err := clientv3.New(cfg)
  53. if err != nil {
  54. fmt.Fprintf(os.Stderr, "dial error: %v\n", err)
  55. os.Exit(1)
  56. }
  57. return client
  58. }
  59. func mustCreateClients(totalClients, totalConns uint) []*clientv3.Client {
  60. conns := make([]*clientv3.Client, totalConns)
  61. for i := range conns {
  62. conns[i] = mustCreateConn()
  63. }
  64. clients := make([]*clientv3.Client, totalClients)
  65. for i := range clients {
  66. clients[i] = conns[i%int(totalConns)]
  67. }
  68. return clients
  69. }
  70. func mustRandBytes(n int) []byte {
  71. rb := make([]byte, n)
  72. _, err := rand.Read(rb)
  73. if err != nil {
  74. fmt.Fprintf(os.Stderr, "failed to generate value: %v\n", err)
  75. os.Exit(1)
  76. }
  77. return rb
  78. }
  79. func newReport() report.Report {
  80. p := "%4.4f"
  81. if precise {
  82. p = "%g"
  83. }
  84. if sample {
  85. return report.NewReportSample(p)
  86. }
  87. return report.NewReport(p)
  88. }