util.go 2.3 KB

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