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
40 "git.arvados.org/arvados.git/lib/config"
41 "git.arvados.org/arvados.git/sdk/go/arvados"
42 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
43 "git.arvados.org/arvados.git/sdk/go/keepclient"
48 // Command line config knobs
50 BlockSize = flag.Int("block-size", keepclient.BLOCKSIZE, "bytes per read/write op")
51 ReadThreads = flag.Int("rthreads", 1, "number of concurrent readers")
52 WriteThreads = flag.Int("wthreads", 1, "number of concurrent writers")
53 VaryRequest = flag.Bool("vary-request", false, "vary the data for each request: consumes disk space, exercises write behavior")
54 VaryThread = flag.Bool("vary-thread", false, "use -wthreads different data blocks")
55 Replicas = flag.Int("replicas", 1, "replication level for writing")
56 StatsInterval = flag.Duration("stats-interval", time.Second, "time interval between IO stats reports, or 0 to disable")
57 ServiceURL = flag.String("url", "", "specify scheme://host of a single keep service to exercise (instead of using all advertised services like normal clients)")
58 ServiceUUID = flag.String("uuid", "", "specify UUID of a single advertised keep service to exercise")
59 getVersion = flag.Bool("version", false, "Print version information and exit.")
60 RunTime = flag.Duration("run-time", 0, "time to run (e.g. 60s), or 0 to run indefinitely (default)")
61 Repeat = flag.Int("repeat", 1, "number of times to repeat the experiment (default 1)")
62 UseIndex = flag.Bool("use-index", false, "use the GetIndex call to get a list of blocks to read. Requires the SystemRoot token. Use this to rule out caching effects when reading.")
65 func createKeepClient(lgr *log.Logger) (kc *keepclient.KeepClient) {
66 arv, err := arvadosclient.MakeArvadosClient()
70 kc, err = keepclient.MakeKeepClient(arv)
74 kc.Want_replicas = *Replicas
76 kc.HTTPClient = &http.Client{
77 Timeout: 10 * time.Minute,
78 // It's not safe to copy *http.DefaultTransport
79 // because it has a mutex (which might be locked)
80 // protecting a private map (which might not be nil).
81 // So we build our own, using the Go 1.12 default
83 Transport: &http.Transport{
84 TLSClientConfig: arvadosclient.MakeTLSConfig(arv.ApiInsecure),
87 overrideServices(kc, lgr)
94 // Print version information if requested
96 fmt.Printf("keep-exercise %s\n", version)
100 lgr := log.New(os.Stderr, "", log.LstdFlags)
102 if *ReadThreads > 0 && *WriteThreads == 0 && !*UseIndex {
103 lgr.Fatal("At least one write thread is required if rthreads is non-zero and -use-index is not enabled")
106 if *ReadThreads == 0 && *WriteThreads == 0 {
107 lgr.Fatal("Nothing to do!")
110 kc := createKeepClient(lgr)
112 // When UseIndex is set, we need a KeepClient with SystemRoot powers to get
113 // the block index from the Keepstore. We use the SystemRootToken from
114 // the Arvados config.yml for that.
115 var cluster *arvados.Cluster
116 if *ReadThreads > 0 && *UseIndex {
117 cluster = loadConfig(lgr)
118 kc.Arvados.ApiToken = cluster.SystemRootToken
121 ctx, cancel := context.WithCancel(context.Background())
123 sigChan := make(chan os.Signal, 1)
124 signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
128 //fmt.Print("\r") // Suppress the ^C print
132 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,UseIndex,RunTime,Repeat"
135 var nextBufs []chan []byte
136 for i := 0; i < *WriteThreads; i++ {
137 nextBuf := make(chan []byte, 1)
138 nextBufs = append(nextBufs, nextBuf)
139 go makeBufs(nextBuf, i, lgr)
142 for i := 0; i < *Repeat && ctx.Err() == nil; i++ {
143 summary = runExperiment(ctx, cluster, kc, nextBufs, summary, csvHeader, lgr)
144 lgr.Printf("*************************** experiment %d complete ******************************\n", i)
145 summary += fmt.Sprintf(",%d\n", i)
148 lgr.Println("Summary:")
151 fmt.Println(csvHeader + ",Experiment")
155 func runExperiment(ctx context.Context, cluster *arvados.Cluster, kc *keepclient.KeepClient, nextBufs []chan []byte, summary string, csvHeader string, lgr *log.Logger) (newSummary string) {
156 // Send 1234 to bytesInChan when we receive 1234 bytes from keepstore.
157 var bytesInChan = make(chan uint64)
158 var bytesOutChan = make(chan uint64)
159 // Send struct{}{} to errorsChan when an error happens.
160 var errorsChan = make(chan struct{})
162 var nextLocator atomic.Value
163 // when UseIndex is set, this channel is used instead of nextLocator
164 var indexLocatorChan = make(chan string, 2)
169 ready := make(chan struct{})
171 if *ReadThreads > 0 {
174 lgr.Printf("Start warmup phase, waiting for 1 available block before reading starts\n")
176 lgr.Printf("Start warmup phase, waiting for block index before reading starts\n")
179 if warmup && !*UseIndex {
181 locator, _, err := kc.PutB(<-nextBufs[0])
184 errorsChan <- struct{}{}
186 nextLocator.Store(locator)
187 lgr.Println("Warmup complete!")
190 } else if warmup && *UseIndex {
191 // Get list of blocks to read
192 go getIndexLocators(ctx, cluster, kc, indexLocatorChan, lgr)
196 case <-indexLocatorChan:
197 lgr.Println("Warmup complete!")
210 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(*RunTime))
213 for i := 0; i < *WriteThreads; i++ {
214 go doWrites(ctx, kc, nextBufs[i], &nextLocator, bytesOutChan, errorsChan, lgr)
217 for i := 0; i < *ReadThreads; i++ {
218 go doReads(ctx, kc, nil, indexLocatorChan, bytesInChan, errorsChan, lgr)
221 for i := 0; i < *ReadThreads; i++ {
222 go doReads(ctx, kc, &nextLocator, nil, bytesInChan, errorsChan, lgr)
227 var tickChan <-chan time.Time
228 if *StatsInterval > 0 {
229 tickChan = time.NewTicker(*StatsInterval).C
234 var rateIn, rateOut float64
235 var maxRateIn, maxRateOut float64
236 var exit, printCsv bool
237 csv := log.New(os.Stdout, "", 0)
239 csv.Println(csvHeader)
247 case i := <-bytesInChan:
249 case o := <-bytesOutChan:
255 elapsed := time.Since(t0)
256 rateIn = float64(bytesIn) / elapsed.Seconds() / 1048576
257 if rateIn > maxRateIn {
260 rateOut = float64(bytesOut) / elapsed.Seconds() / 1048576
261 if rateOut > maxRateOut {
264 line := fmt.Sprintf("%v,%v,%v,%.1f,%.1f,%v,%.1f,%.1f,%d,%d,%d,%t,%t,%d,%d,%s,%s,%s,%t,%s,%d",
265 time.Now().Format("2006/01/02 15:04:05"),
267 bytesIn, rateIn, maxRateIn,
268 bytesOut, rateOut, maxRateOut,
293 func makeBufs(nextBuf chan<- []byte, threadID int, lgr *log.Logger) {
294 buf := make([]byte, *BlockSize)
296 binary.PutVarint(buf, int64(threadID))
299 if randSize > *BlockSize {
300 randSize = *BlockSize
304 rnd := make([]byte, randSize)
305 if _, err := io.ReadFull(rand.Reader, rnd); err != nil {
308 buf = append(rnd, buf[randSize:]...)
314 func doWrites(ctx context.Context, kc *keepclient.KeepClient, nextBuf <-chan []byte, nextLocator *atomic.Value, bytesOutChan chan<- uint64, errorsChan chan<- struct{}, lgr *log.Logger) {
315 for ctx.Err() == nil {
316 //lgr.Printf("%s nextbuf %s, waiting for nextBuf\n",nextBuf,time.Now())
318 //lgr.Printf("%s nextbuf %s, done waiting for nextBuf\n",nextBuf,time.Now())
319 locator, _, err := kc.PutB(buf)
322 errorsChan <- struct{}{}
325 bytesOutChan <- uint64(len(buf))
326 nextLocator.Store(locator)
330 func getIndexLocators(ctx context.Context, cluster *arvados.Cluster, kc *keepclient.KeepClient, indexLocatorChan chan<- string, lgr *log.Logger) {
331 if ctx.Err() != nil {
334 locatorsMap := make(map[string]bool)
335 var locators []string
337 for uuid := range kc.LocalRoots() {
338 reader, err := kc.GetIndex(uuid, "")
340 lgr.Fatalf("Error getting index: %s\n", err)
342 scanner := bufio.NewScanner(reader)
344 locatorsMap[strings.Split(scanner.Text(), " ")[0]] = true
348 for l := range locatorsMap {
349 locators = append(locators, l)
351 lgr.Printf("Found %d locators\n", count)
352 lgr.Printf("Found %d locators (deduplicated)\n", len(locators))
353 if len(locators) < 1 {
354 lgr.Fatal("Error: no locators found. The keepstores do not seem to contain any data. Remove the -use-index cli argument.")
357 mathRand.Seed(time.Now().UnixNano())
358 mathRand.Shuffle(len(locators), func(i, j int) { locators[i], locators[j] = locators[j], locators[i] })
360 for _, locator := range locators {
361 // We need the Collections.BlobSigningKey to sign our block requests. This requires access to /etc/arvados/config.yml
362 signedLocator := arvados.SignLocator(locator, kc.Arvados.ApiToken, time.Now().Local().Add(1*time.Hour), cluster.Collections.BlobSigningTTL.Duration(), []byte(cluster.Collections.BlobSigningKey))
366 case indexLocatorChan <- signedLocator:
369 lgr.Fatal("Error: ran out of locators to read!")
372 func loadConfig(lgr *log.Logger) (cluster *arvados.Cluster) {
373 loader := config.NewLoader(os.Stdin, nil)
374 loader.SkipLegacy = true
376 cfg, err := loader.Load()
380 cluster, err = cfg.GetCluster("")
387 func doReads(ctx context.Context, kc *keepclient.KeepClient, nextLocator *atomic.Value, indexLocatorChan <-chan string, bytesInChan chan<- uint64, errorsChan chan<- struct{}, lgr *log.Logger) {
388 for ctx.Err() == nil {
390 if indexLocatorChan != nil {
394 case locator = <-indexLocatorChan:
397 locator = nextLocator.Load().(string)
399 rdr, size, url, err := kc.Get(locator)
402 errorsChan <- struct{}{}
405 n, err := io.Copy(ioutil.Discard, rdr)
407 if n != size || err != nil {
408 lgr.Printf("Got %d bytes (expected %d) from %s: %v", n, size, url, err)
409 errorsChan <- struct{}{}
411 // Note we don't count the bytes received in
412 // partial/corrupt responses: we are measuring
413 // throughput, not resource consumption.
415 bytesInChan <- uint64(n)
419 func overrideServices(kc *keepclient.KeepClient, lgr *log.Logger) {
420 roots := make(map[string]string)
421 if *ServiceURL != "" {
422 roots["zzzzz-bi6l4-000000000000000"] = *ServiceURL
423 } else if *ServiceUUID != "" {
424 for uuid, url := range kc.GatewayRoots() {
425 if uuid == *ServiceUUID {
431 lgr.Fatalf("Service %q was not in list advertised by API %+q", *ServiceUUID, kc.GatewayRoots())
436 kc.SetServiceRoots(roots, roots, roots)