util.go 2.2 KB

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