github.com/MetalBlockchain/metalgo@v1.11.9/tests/antithesis/node_health.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package antithesis
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"log"
    10  	"time"
    11  
    12  	"github.com/MetalBlockchain/metalgo/api/health"
    13  )
    14  
    15  // Waits for the nodes at the provided URIs to report healthy.
    16  func AwaitHealthyNodes(ctx context.Context, uris []string) error {
    17  	for _, uri := range uris {
    18  		if err := awaitHealthyNode(ctx, uri); err != nil {
    19  			return err
    20  		}
    21  	}
    22  	log.Println("all nodes reported healthy")
    23  	return nil
    24  }
    25  
    26  func awaitHealthyNode(ctx context.Context, uri string) error {
    27  	client := health.NewClient(uri)
    28  	ticker := time.NewTicker(100 * time.Millisecond)
    29  	defer ticker.Stop()
    30  
    31  	log.Printf("awaiting node health at %s", uri)
    32  	for {
    33  		res, err := client.Health(ctx, nil)
    34  		switch {
    35  		case err != nil:
    36  			log.Printf("node couldn't be reached at %s", uri)
    37  		case res.Healthy:
    38  			log.Printf("node reported healthy at %s", uri)
    39  			return nil
    40  		default:
    41  			log.Printf("node reported unhealthy at %s", uri)
    42  		}
    43  
    44  		select {
    45  		case <-ticker.C:
    46  		case <-ctx.Done():
    47  			return fmt.Errorf("node health check cancelled at %s: %w", uri, ctx.Err())
    48  		}
    49  	}
    50  }