1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Testing tool for Keep services.
7 // keepexercise helps measure throughput and test reliability under
8 // various usage patterns.
10 // By default, it reads and writes blocks containing 2^26 NUL
11 // bytes. This generates network traffic without consuming much disk
14 // For a more realistic test, enable -vary-request. Warning: this will
15 // fill your storage volumes with random data if you leave it running,
16 // which can cost you money or leave you with too little room for
37 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
38 "git.arvados.org/arvados.git/sdk/go/keepclient"
43 // Command line config knobs
45 BlockSize = flag.Int("block-size", keepclient.BLOCKSIZE, "bytes per read/write op")
46 ReadThreads = flag.Int("rthreads", 1, "number of concurrent readers")
47 WriteThreads = flag.Int("wthreads", 1, "number of concurrent writers")
48 VaryRequest = flag.Bool("vary-request", false, "vary the data for each request: consumes disk space, exercises write behavior")
49 VaryThread = flag.Bool("vary-thread", false, "use -wthreads different data blocks")
50 Replicas = flag.Int("replicas", 1, "replication level for writing")
51 StatsInterval = flag.Duration("stats-interval", time.Second, "time interval between IO stats reports, or 0 to disable")
52 ServiceURL = flag.String("url", "", "specify scheme://host of a single keep service to exercise (instead of using all advertised services like normal clients)")
53 ServiceUUID = flag.String("uuid", "", "specify UUID of a single advertised keep service to exercise")
54 getVersion = flag.Bool("version", false, "Print version information and exit.")
55 RunTime = flag.Duration("run-time", 0, "time to run (e.g. 60s), or 0 to run indefinitely (default)")
56 Repeat = flag.Int("repeat", 1, "number of times to repeat the experiment (default 1)")
65 // Print version information if requested
67 fmt.Printf("keep-exercise %s\n", version)
71 stderr := log.New(os.Stderr, "", log.LstdFlags)
73 if *ReadThreads > 0 && *WriteThreads == 0 {
74 stderr.Fatal("At least one write thread is required if rthreads is non-zero")
77 if *ReadThreads == 0 && *WriteThreads == 0 {
78 stderr.Fatal("Nothing to do!")
81 arv, err := arvadosclient.MakeArvadosClient()
85 kc, err := keepclient.MakeKeepClient(arv)
89 kc.Want_replicas = *Replicas
91 kc.HTTPClient = &http.Client{
92 Timeout: 10 * time.Minute,
93 // It's not safe to copy *http.DefaultTransport
94 // because it has a mutex (which might be locked)
95 // protecting a private map (which might not be nil).
96 // So we build our own, using the Go 1.12 default
98 Transport: &http.Transport{
99 TLSClientConfig: arvadosclient.MakeTLSConfig(arv.ApiInsecure),
103 overrideServices(kc, stderr)
104 csvHeader = "Timestamp,Elapsed,Read (bytes),Avg Read Speed (MiB/s),Peak Read Speed (MiB/s),Written (bytes),Avg Write Speed (MiB/s),Peak Write Speed (MiB/s),Errors,ReadThreads,WriteThreads,VaryRequest,VaryThread,BlockSize,Replicas,StatsInterval,ServiceURL,ServiceUUID,RunTime,Repeat"
106 for i := 0; i < *Repeat; i++ {
107 runExperiment(kc, stderr)
108 stderr.Printf("*************************** experiment %d complete ******************************\n", i)
109 summary += fmt.Sprintf(",%d\n", i)
111 stderr.Println("Summary:")
113 fmt.Println(csvHeader + ",Experiment")
117 func runExperiment(kc *keepclient.KeepClient, stderr *log.Logger) {
118 var wg sync.WaitGroup
119 var nextLocator atomic.Value
122 stopCh := make(chan struct{})
123 if *ReadThreads > 0 {
124 stderr.Printf("Start warmup phase, waiting for 1 available block before reading starts\n")
126 for i := 0; i < *WriteThreads; i++ {
127 nextBuf := make(chan []byte, 1)
129 go makeBufs(&wg, nextBuf, i, stopCh, stderr)
131 go doWrites(&wg, kc, nextBuf, &nextLocator, stopCh, stderr)
133 if *ReadThreads > 0 {
134 for nextLocator.Load() == nil {
136 case _ = <-bytesOutChan:
139 stderr.Printf("Warmup complete")
141 go countBeans(&wg, stopCh, stderr)
142 for i := 0; i < *ReadThreads; i++ {
144 go doReads(&wg, kc, &nextLocator, stopCh, stderr)
149 // Send 1234 to bytesInChan when we receive 1234 bytes from keepstore.
150 var bytesInChan = make(chan uint64)
151 var bytesOutChan = make(chan uint64)
153 // Send struct{}{} to errorsChan when an error happens.
154 var errorsChan = make(chan struct{})
156 func countBeans(wg *sync.WaitGroup, stopCh chan struct{}, stderr *log.Logger) {
159 var tickChan <-chan time.Time
160 var endChan <-chan time.Time
161 c := make(chan os.Signal, 1)
162 signal.Notify(c, os.Interrupt, syscall.SIGTERM)
163 if *StatsInterval > 0 {
164 tickChan = time.NewTicker(*StatsInterval).C
167 endChan = time.NewTicker(*RunTime).C
172 var rateIn, rateOut float64
173 var maxRateIn, maxRateOut float64
174 var exit, abort, printCsv bool
175 csv := log.New(os.Stdout, "", 0)
176 csv.Println(csvHeader)
187 fmt.Print("\r") // Suppress the ^C print
188 case i := <-bytesInChan:
190 case o := <-bytesOutChan:
196 elapsed := time.Since(t0)
197 rateIn = float64(bytesIn) / elapsed.Seconds() / 1048576
198 if rateIn > maxRateIn {
201 rateOut = float64(bytesOut) / elapsed.Seconds() / 1048576
202 if rateOut > maxRateOut {
205 line := fmt.Sprintf("%v,%v,%v,%.1f,%.1f,%v,%.1f,%.1f,%d,%d,%d,%t,%t,%d,%d,%s,%s,%s,%s,%d",
206 time.Now().Format("2006-01-02 15:04:05"),
208 bytesIn, rateIn, maxRateIn,
209 bytesOut, rateOut, maxRateOut,
239 func makeBufs(wg *sync.WaitGroup, nextBuf chan<- []byte, threadID int, stopCh <-chan struct{}, stderr *log.Logger) {
241 buf := make([]byte, *BlockSize)
243 binary.PutVarint(buf, int64(threadID))
246 if randSize > *BlockSize {
247 randSize = *BlockSize
251 rnd := make([]byte, randSize)
252 if _, err := io.ReadFull(rand.Reader, rnd); err != nil {
255 buf = append(rnd, buf[randSize:]...)
266 func doWrites(wg *sync.WaitGroup, kc *keepclient.KeepClient, nextBuf <-chan []byte, nextLocator *atomic.Value, stopCh <-chan struct{}, stderr *log.Logger) {
273 case buf := <-nextBuf:
274 locator, _, err := kc.PutB(buf)
277 errorsChan <- struct{}{}
283 case bytesOutChan <- uint64(len(buf)):
285 nextLocator.Store(locator)
290 func doReads(wg *sync.WaitGroup, kc *keepclient.KeepClient, nextLocator *atomic.Value, stopCh <-chan struct{}, stderr *log.Logger) {
295 locator = nextLocator.Load().(string)
296 rdr, size, url, err := kc.Get(locator)
299 errorsChan <- struct{}{}
302 n, err := io.Copy(ioutil.Discard, rdr)
304 if n != size || err != nil {
305 stderr.Printf("Got %d bytes (expected %d) from %s: %v", n, size, url, err)
306 errorsChan <- struct{}{}
308 // Note we don't count the bytes received in
309 // partial/corrupt responses: we are measuring
310 // throughput, not resource consumption.
315 case bytesInChan <- uint64(n):
320 func overrideServices(kc *keepclient.KeepClient, stderr *log.Logger) {
321 roots := make(map[string]string)
322 if *ServiceURL != "" {
323 roots["zzzzz-bi6l4-000000000000000"] = *ServiceURL
324 } else if *ServiceUUID != "" {
325 for uuid, url := range kc.GatewayRoots() {
326 if uuid == *ServiceUUID {
332 stderr.Fatalf("Service %q was not in list advertised by API %+q", *ServiceUUID, kc.GatewayRoots())
337 kc.SetServiceRoots(roots, roots, roots)