github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/cmd/swarm-bench/collector.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"net"
     8  	"strconv"
     9  	"time"
    10  
    11  	"github.com/docker/swarmkit/log"
    12  	"github.com/rcrowley/go-metrics"
    13  )
    14  
    15  // Collector waits for tasks to phone home while collecting statistics.
    16  type Collector struct {
    17  	t  metrics.Timer
    18  	ln net.Listener
    19  }
    20  
    21  // Listen starts listening on a TCP port. Tasks have to connect to this address
    22  // once they come online.
    23  func (c *Collector) Listen(port int) error {
    24  	var err error
    25  	c.ln, err = net.Listen("tcp", ":"+strconv.Itoa(port))
    26  	return err
    27  }
    28  
    29  // Collect blocks until `count` tasks phoned home.
    30  func (c *Collector) Collect(ctx context.Context, count uint64) {
    31  	start := time.Now()
    32  	for i := uint64(0); i < count; i++ {
    33  		conn, err := c.ln.Accept()
    34  		if err != nil {
    35  			log.G(ctx).WithError(err).Error("failure accepting connection")
    36  			continue
    37  		}
    38  		c.t.UpdateSince(start)
    39  		conn.Close()
    40  	}
    41  }
    42  
    43  // Stats prints various statistics related to the collection.
    44  func (c *Collector) Stats(w io.Writer, unit time.Duration) {
    45  	du := float64(unit)
    46  	duSuffix := unit.String()[1:]
    47  
    48  	t := c.t.Snapshot()
    49  	ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
    50  
    51  	fmt.Fprintln(w, "stats:")
    52  	fmt.Fprintf(w, "  count:       %9d\n", t.Count())
    53  	fmt.Fprintf(w, "  min:         %12.2f%s\n", float64(t.Min())/du, duSuffix)
    54  	fmt.Fprintf(w, "  max:         %12.2f%s\n", float64(t.Max())/du, duSuffix)
    55  	fmt.Fprintf(w, "  mean:        %12.2f%s\n", t.Mean()/du, duSuffix)
    56  	fmt.Fprintf(w, "  stddev:      %12.2f%s\n", t.StdDev()/du, duSuffix)
    57  	fmt.Fprintf(w, "  median:      %12.2f%s\n", ps[0]/du, duSuffix)
    58  	fmt.Fprintf(w, "  75%%:         %12.2f%s\n", ps[1]/du, duSuffix)
    59  	fmt.Fprintf(w, "  95%%:         %12.2f%s\n", ps[2]/du, duSuffix)
    60  	fmt.Fprintf(w, "  99%%:         %12.2f%s\n", ps[3]/du, duSuffix)
    61  	fmt.Fprintf(w, "  99.9%%:       %12.2f%s\n", ps[4]/du, duSuffix)
    62  	fmt.Fprintf(w, "  1-min rate:  %12.2f\n", t.Rate1())
    63  	fmt.Fprintf(w, "  5-min rate:  %12.2f\n", t.Rate5())
    64  	fmt.Fprintf(w, "  15-min rate: %12.2f\n", t.Rate15())
    65  	fmt.Fprintf(w, "  mean rate:   %12.2f\n", t.RateMean())
    66  }
    67  
    68  // NewCollector creates and returns a collector.
    69  func NewCollector() *Collector {
    70  	return &Collector{
    71  		t: metrics.NewTimer(),
    72  	}
    73  }