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
39 "git.arvados.org/arvados.git/lib/cmd"
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)
92 if ok, code := cmd.ParseFlags(flag.CommandLine, os.Args[0], os.Args[1:], "", os.Stderr); !ok {
94 } else if *getVersion {
95 fmt.Printf("%s %s\n", os.Args[0], version)
99 lgr := log.New(os.Stderr, "", log.LstdFlags)
101 if *ReadThreads > 0 && *WriteThreads == 0 && !*UseIndex {
102 lgr.Fatal("At least one write thread is required if rthreads is non-zero and -use-index is not enabled")
105 if *ReadThreads == 0 && *WriteThreads == 0 {
106 lgr.Fatal("Nothing to do!")
109 kc := createKeepClient(lgr)
111 // When UseIndex is set, we need a KeepClient with SystemRoot powers to get
112 // the block index from the Keepstore. We use the SystemRootToken from
113 // the Arvados config.yml for that.
114 var cluster *arvados.Cluster
115 if *ReadThreads > 0 && *UseIndex {
116 cluster = loadConfig(lgr)
117 kc.Arvados.ApiToken = cluster.SystemRootToken
120 ctx, cancel := context.WithCancel(context.Background())
122 sigChan := make(chan os.Signal, 1)
123 signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
127 //fmt.Print("\r") // Suppress the ^C print
131 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"
134 var nextBufs []chan []byte
135 for i := 0; i < *WriteThreads; i++ {
136 nextBuf := make(chan []byte, 1)
137 nextBufs = append(nextBufs, nextBuf)
138 go makeBufs(nextBuf, i, lgr)
141 for i := 0; i < *Repeat && ctx.Err() == nil; i++ {
142 summary = runExperiment(ctx, cluster, kc, nextBufs, summary, csvHeader, lgr)
143 lgr.Printf("*************************** experiment %d complete ******************************\n", i)
144 summary += fmt.Sprintf(",%d\n", i)
147 lgr.Println("Summary:")
150 fmt.Println(csvHeader + ",Experiment")
154 func runExperiment(ctx context.Context, cluster *arvados.Cluster, kc *keepclient.KeepClient, nextBufs []chan []byte, summary string, csvHeader string, lgr *log.Logger) (newSummary string) {
155 // Send 1234 to bytesInChan when we receive 1234 bytes from keepstore.
156 var bytesInChan = make(chan uint64)
157 var bytesOutChan = make(chan uint64)
158 // Send struct{}{} to errorsChan when an error happens.
159 var errorsChan = make(chan struct{})
161 var nextLocator atomic.Value
162 // when UseIndex is set, this channel is used instead of nextLocator
163 var indexLocatorChan = make(chan string, 2)
168 ready := make(chan struct{})
170 if *ReadThreads > 0 {
173 lgr.Printf("Start warmup phase, waiting for 1 available block before reading starts\n")
175 lgr.Printf("Start warmup phase, waiting for block index before reading starts\n")
178 if warmup && !*UseIndex {
180 locator, _, err := kc.PutB(<-nextBufs[0])
183 errorsChan <- struct{}{}
185 nextLocator.Store(locator)
186 lgr.Println("Warmup complete!")
189 } else if warmup && *UseIndex {
190 // Get list of blocks to read
191 go getIndexLocators(ctx, cluster, kc, indexLocatorChan, lgr)
195 case <-indexLocatorChan:
196 lgr.Println("Warmup complete!")
209 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(*RunTime))
212 for i := 0; i < *WriteThreads; i++ {
213 go doWrites(ctx, kc, nextBufs[i], &nextLocator, bytesOutChan, errorsChan, lgr)
216 for i := 0; i < *ReadThreads; i++ {
217 go doReads(ctx, kc, nil, indexLocatorChan, bytesInChan, errorsChan, lgr)
220 for i := 0; i < *ReadThreads; i++ {
221 go doReads(ctx, kc, &nextLocator, nil, bytesInChan, errorsChan, lgr)
226 var tickChan <-chan time.Time
227 if *StatsInterval > 0 {
228 tickChan = time.NewTicker(*StatsInterval).C
233 var rateIn, rateOut float64
234 var maxRateIn, maxRateOut float64
235 var exit, printCsv bool
236 csv := log.New(os.Stdout, "", 0)
238 csv.Println(csvHeader)
246 case i := <-bytesInChan:
248 case o := <-bytesOutChan:
254 elapsed := time.Since(t0)
255 rateIn = float64(bytesIn) / elapsed.Seconds() / 1048576
256 if rateIn > maxRateIn {
259 rateOut = float64(bytesOut) / elapsed.Seconds() / 1048576
260 if rateOut > maxRateOut {
263 line := fmt.Sprintf("%v,%v,%v,%.1f,%.1f,%v,%.1f,%.1f,%d,%d,%d,%t,%t,%d,%d,%s,%s,%s,%t,%s,%d",
264 time.Now().Format("2006/01/02 15:04:05"),
266 bytesIn, rateIn, maxRateIn,
267 bytesOut, rateOut, maxRateOut,
292 func makeBufs(nextBuf chan<- []byte, threadID int, lgr *log.Logger) {
293 buf := make([]byte, *BlockSize)
295 binary.PutVarint(buf, int64(threadID))
298 if randSize > *BlockSize {
299 randSize = *BlockSize
303 rnd := make([]byte, randSize)
304 if _, err := io.ReadFull(rand.Reader, rnd); err != nil {
307 buf = append(rnd, buf[randSize:]...)
313 func doWrites(ctx context.Context, kc *keepclient.KeepClient, nextBuf <-chan []byte, nextLocator *atomic.Value, bytesOutChan chan<- uint64, errorsChan chan<- struct{}, lgr *log.Logger) {
314 for ctx.Err() == nil {
315 //lgr.Printf("%s nextbuf %s, waiting for nextBuf\n",nextBuf,time.Now())
317 //lgr.Printf("%s nextbuf %s, done waiting for nextBuf\n",nextBuf,time.Now())
318 locator, _, err := kc.PutB(buf)
321 errorsChan <- struct{}{}
324 bytesOutChan <- uint64(len(buf))
325 nextLocator.Store(locator)
329 func getIndexLocators(ctx context.Context, cluster *arvados.Cluster, kc *keepclient.KeepClient, indexLocatorChan chan<- string, lgr *log.Logger) {
330 if ctx.Err() != nil {
333 locatorsMap := make(map[string]bool)
334 var locators []string
336 for uuid := range kc.LocalRoots() {
337 reader, err := kc.GetIndex(uuid, "")
339 lgr.Fatalf("Error getting index: %s\n", err)
341 scanner := bufio.NewScanner(reader)
343 locatorsMap[strings.Split(scanner.Text(), " ")[0]] = true
347 for l := range locatorsMap {
348 locators = append(locators, l)
350 lgr.Printf("Found %d locators\n", count)
351 lgr.Printf("Found %d locators (deduplicated)\n", len(locators))
352 if len(locators) < 1 {
353 lgr.Fatal("Error: no locators found. The keepstores do not seem to contain any data. Remove the -use-index cli argument.")
356 mathRand.Seed(time.Now().UnixNano())
357 mathRand.Shuffle(len(locators), func(i, j int) { locators[i], locators[j] = locators[j], locators[i] })
359 for _, locator := range locators {
360 // We need the Collections.BlobSigningKey to sign our block requests. This requires access to /etc/arvados/config.yml
361 signedLocator := arvados.SignLocator(locator, kc.Arvados.ApiToken, time.Now().Local().Add(1*time.Hour), cluster.Collections.BlobSigningTTL.Duration(), []byte(cluster.Collections.BlobSigningKey))
365 case indexLocatorChan <- signedLocator:
368 lgr.Fatal("Error: ran out of locators to read!")
371 func loadConfig(lgr *log.Logger) (cluster *arvados.Cluster) {
372 loader := config.NewLoader(os.Stdin, nil)
373 loader.SkipLegacy = true
375 cfg, err := loader.Load()
379 cluster, err = cfg.GetCluster("")
386 func doReads(ctx context.Context, kc *keepclient.KeepClient, nextLocator *atomic.Value, indexLocatorChan <-chan string, bytesInChan chan<- uint64, errorsChan chan<- struct{}, lgr *log.Logger) {
387 for ctx.Err() == nil {
389 if indexLocatorChan != nil {
393 case locator = <-indexLocatorChan:
396 locator = nextLocator.Load().(string)
398 rdr, size, url, err := kc.Get(locator)
401 errorsChan <- struct{}{}
404 n, err := io.Copy(ioutil.Discard, rdr)
406 if n != size || err != nil {
407 lgr.Printf("Got %d bytes (expected %d) from %s: %v", n, size, url, err)
408 errorsChan <- struct{}{}
410 // Note we don't count the bytes received in
411 // partial/corrupt responses: we are measuring
412 // throughput, not resource consumption.
414 bytesInChan <- uint64(n)
418 func overrideServices(kc *keepclient.KeepClient, lgr *log.Logger) {
419 roots := make(map[string]string)
420 if *ServiceURL != "" {
421 roots["zzzzz-bi6l4-000000000000000"] = *ServiceURL
422 } else if *ServiceUUID != "" {
423 for uuid, url := range kc.GatewayRoots() {
424 if uuid == *ServiceUUID {
430 lgr.Fatalf("Service %q was not in list advertised by API %+q", *ServiceUUID, kc.GatewayRoots())
435 kc.SetServiceRoots(roots, roots, roots)