github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/integration-cli/docker_api_stats_test.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"os/exec"
     9  	"runtime"
    10  	"strconv"
    11  	"strings"
    12  	"sync"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/docker/docker/api/types"
    17  	"github.com/docker/docker/api/types/versions"
    18  	"github.com/docker/docker/client"
    19  	"github.com/docker/docker/testutil/request"
    20  	"gotest.tools/v3/assert"
    21  	"gotest.tools/v3/skip"
    22  )
    23  
    24  var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ")
    25  
    26  func (s *DockerAPISuite) TestAPIStatsNoStreamGetCpu(c *testing.T) {
    27  	skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
    28  	out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done")
    29  
    30  	id := strings.TrimSpace(out)
    31  	assert.NilError(c, waitRun(id))
    32  	resp, body, err := request.Get(fmt.Sprintf("/containers/%s/stats?stream=false", id))
    33  	assert.NilError(c, err)
    34  	assert.Equal(c, resp.StatusCode, http.StatusOK)
    35  	assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
    36  	assert.Equal(c, resp.Header.Get("Content-Type"), "application/json")
    37  
    38  	var v *types.Stats
    39  	err = json.NewDecoder(body).Decode(&v)
    40  	assert.NilError(c, err)
    41  	body.Close()
    42  
    43  	var cpuPercent = 0.0
    44  
    45  	if testEnv.OSType != "windows" {
    46  		cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage)
    47  		systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage)
    48  		cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
    49  	} else {
    50  		// Max number of 100ns intervals between the previous time read and now
    51  		possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
    52  		possIntervals /= 100                                         // Convert to number of 100ns intervals
    53  		possIntervals *= uint64(v.NumProcs)                          // Multiple by the number of processors
    54  
    55  		// Intervals used
    56  		intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
    57  
    58  		// Percentage avoiding divide-by-zero
    59  		if possIntervals > 0 {
    60  			cpuPercent = float64(intervalsUsed) / float64(possIntervals) * 100.0
    61  		}
    62  	}
    63  
    64  	assert.Assert(c, cpuPercent != 0.0, "docker stats with no-stream get cpu usage failed: was %v", cpuPercent)
    65  }
    66  
    67  func (s *DockerAPISuite) TestAPIStatsStoppedContainerInGoroutines(c *testing.T) {
    68  	out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1")
    69  	id := strings.TrimSpace(out)
    70  
    71  	getGoRoutines := func() int {
    72  		_, body, err := request.Get("/info")
    73  		assert.NilError(c, err)
    74  		info := types.Info{}
    75  		err = json.NewDecoder(body).Decode(&info)
    76  		assert.NilError(c, err)
    77  		body.Close()
    78  		return info.NGoroutines
    79  	}
    80  
    81  	// When the HTTP connection is closed, the number of goroutines should not increase.
    82  	routines := getGoRoutines()
    83  	_, body, err := request.Get("/containers/" + id + "/stats")
    84  	assert.NilError(c, err)
    85  	body.Close()
    86  
    87  	t := time.After(30 * time.Second)
    88  	for {
    89  		select {
    90  		case <-t:
    91  			assert.Assert(c, getGoRoutines() <= routines)
    92  			return
    93  		default:
    94  			if n := getGoRoutines(); n <= routines {
    95  				return
    96  			}
    97  			time.Sleep(200 * time.Millisecond)
    98  		}
    99  	}
   100  }
   101  
   102  func (s *DockerAPISuite) TestAPIStatsNetworkStats(c *testing.T) {
   103  	skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination")
   104  	testRequires(c, testEnv.IsLocalDaemon)
   105  
   106  	out := runSleepingContainer(c)
   107  	id := strings.TrimSpace(out)
   108  	assert.NilError(c, waitRun(id))
   109  
   110  	// Retrieve the container address
   111  	net := "bridge"
   112  	if testEnv.OSType == "windows" {
   113  		net = "nat"
   114  	}
   115  	contIP := findContainerIP(c, id, net)
   116  	numPings := 1
   117  
   118  	var preRxPackets uint64
   119  	var preTxPackets uint64
   120  	var postRxPackets uint64
   121  	var postTxPackets uint64
   122  
   123  	// Get the container networking stats before and after pinging the container
   124  	nwStatsPre := getNetworkStats(c, id)
   125  	for _, v := range nwStatsPre {
   126  		preRxPackets += v.RxPackets
   127  		preTxPackets += v.TxPackets
   128  	}
   129  
   130  	countParam := "-c"
   131  	if runtime.GOOS == "windows" {
   132  		countParam = "-n" // Ping count parameter is -n on Windows
   133  	}
   134  	pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).CombinedOutput()
   135  	if err != nil && runtime.GOOS == "linux" {
   136  		// If it fails then try a work-around, but just for linux.
   137  		// If this fails too then go back to the old error for reporting.
   138  		//
   139  		// The ping will sometimes fail due to an apparmor issue where it
   140  		// denies access to the libc.so.6 shared library - running it
   141  		// via /lib64/ld-linux-x86-64.so.2 seems to work around it.
   142  		pingout2, err2 := exec.Command("/lib64/ld-linux-x86-64.so.2", "/bin/ping", contIP, "-c", strconv.Itoa(numPings)).CombinedOutput()
   143  		if err2 == nil {
   144  			pingout = pingout2
   145  			err = err2
   146  		}
   147  	}
   148  	assert.NilError(c, err)
   149  	pingouts := string(pingout[:])
   150  	nwStatsPost := getNetworkStats(c, id)
   151  	for _, v := range nwStatsPost {
   152  		postRxPackets += v.RxPackets
   153  		postTxPackets += v.TxPackets
   154  	}
   155  
   156  	// Verify the stats contain at least the expected number of packets
   157  	// On Linux, account for ARP.
   158  	expRxPkts := preRxPackets + uint64(numPings)
   159  	expTxPkts := preTxPackets + uint64(numPings)
   160  	if testEnv.OSType != "windows" {
   161  		expRxPkts++
   162  		expTxPkts++
   163  	}
   164  	assert.Assert(c, postTxPackets >= expTxPkts, "Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)
   165  	assert.Assert(c, postRxPackets >= expRxPkts, "Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)
   166  }
   167  
   168  func (s *DockerAPISuite) TestAPIStatsNetworkStatsVersioning(c *testing.T) {
   169  	// Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21
   170  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
   171  
   172  	out := runSleepingContainer(c)
   173  	id := strings.TrimSpace(out)
   174  	assert.NilError(c, waitRun(id))
   175  	wg := sync.WaitGroup{}
   176  
   177  	for i := 17; i <= 21; i++ {
   178  		wg.Add(1)
   179  		go func(i int) {
   180  			defer wg.Done()
   181  			apiVersion := fmt.Sprintf("v1.%d", i)
   182  			statsJSONBlob := getVersionedStats(c, id, apiVersion)
   183  			if versions.LessThan(apiVersion, "v1.21") {
   184  				assert.Assert(c, jsonBlobHasLTv121NetworkStats(statsJSONBlob), "Stats JSON blob from API %s %#v does not look like a <v1.21 API stats structure", apiVersion, statsJSONBlob)
   185  			} else {
   186  				assert.Assert(c, jsonBlobHasGTE121NetworkStats(statsJSONBlob), "Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob)
   187  			}
   188  		}(i)
   189  	}
   190  	wg.Wait()
   191  }
   192  
   193  func getNetworkStats(c *testing.T, id string) map[string]types.NetworkStats {
   194  	var st *types.StatsJSON
   195  
   196  	_, body, err := request.Get("/containers/" + id + "/stats?stream=false")
   197  	assert.NilError(c, err)
   198  
   199  	err = json.NewDecoder(body).Decode(&st)
   200  	assert.NilError(c, err)
   201  	body.Close()
   202  
   203  	return st.Networks
   204  }
   205  
   206  // getVersionedStats returns stats result for the
   207  // container with id using an API call with version apiVersion. Since the
   208  // stats result type differs between API versions, we simply return
   209  // map[string]interface{}.
   210  func getVersionedStats(c *testing.T, id string, apiVersion string) map[string]interface{} {
   211  	stats := make(map[string]interface{})
   212  
   213  	_, body, err := request.Get("/" + apiVersion + "/containers/" + id + "/stats?stream=false")
   214  	assert.NilError(c, err)
   215  	defer body.Close()
   216  
   217  	err = json.NewDecoder(body).Decode(&stats)
   218  	assert.NilError(c, err, "failed to decode stat: %s", err)
   219  
   220  	return stats
   221  }
   222  
   223  func jsonBlobHasLTv121NetworkStats(blob map[string]interface{}) bool {
   224  	networkStatsIntfc, ok := blob["network"]
   225  	if !ok {
   226  		return false
   227  	}
   228  	networkStats, ok := networkStatsIntfc.(map[string]interface{})
   229  	if !ok {
   230  		return false
   231  	}
   232  	for _, expectedKey := range expectedNetworkInterfaceStats {
   233  		if _, ok := networkStats[expectedKey]; !ok {
   234  			return false
   235  		}
   236  	}
   237  	return true
   238  }
   239  
   240  func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool {
   241  	networksStatsIntfc, ok := blob["networks"]
   242  	if !ok {
   243  		return false
   244  	}
   245  	networksStats, ok := networksStatsIntfc.(map[string]interface{})
   246  	if !ok {
   247  		return false
   248  	}
   249  	for _, networkInterfaceStatsIntfc := range networksStats {
   250  		networkInterfaceStats, ok := networkInterfaceStatsIntfc.(map[string]interface{})
   251  		if !ok {
   252  			return false
   253  		}
   254  		for _, expectedKey := range expectedNetworkInterfaceStats {
   255  			if _, ok := networkInterfaceStats[expectedKey]; !ok {
   256  				return false
   257  			}
   258  		}
   259  	}
   260  	return true
   261  }
   262  
   263  func (s *DockerAPISuite) TestAPIStatsContainerNotFound(c *testing.T) {
   264  	testRequires(c, DaemonIsLinux)
   265  	cli, err := client.NewClientWithOpts(client.FromEnv)
   266  	assert.NilError(c, err)
   267  	defer cli.Close()
   268  
   269  	expected := "No such container: nonexistent"
   270  
   271  	_, err = cli.ContainerStats(context.Background(), "nonexistent", true)
   272  	assert.ErrorContains(c, err, expected)
   273  	_, err = cli.ContainerStats(context.Background(), "nonexistent", false)
   274  	assert.ErrorContains(c, err, expected)
   275  }
   276  
   277  func (s *DockerAPISuite) TestAPIStatsNoStreamConnectedContainers(c *testing.T) {
   278  	testRequires(c, DaemonIsLinux)
   279  
   280  	out1 := runSleepingContainer(c)
   281  	id1 := strings.TrimSpace(out1)
   282  	assert.NilError(c, waitRun(id1))
   283  
   284  	out2 := runSleepingContainer(c, "--net", "container:"+id1)
   285  	id2 := strings.TrimSpace(out2)
   286  	assert.NilError(c, waitRun(id2))
   287  
   288  	ch := make(chan error, 1)
   289  	go func() {
   290  		resp, body, err := request.Get("/containers/" + id2 + "/stats?stream=false")
   291  		defer body.Close()
   292  		if err != nil {
   293  			ch <- err
   294  		}
   295  		if resp.StatusCode != http.StatusOK {
   296  			ch <- fmt.Errorf("Invalid StatusCode %v", resp.StatusCode)
   297  		}
   298  		if resp.Header.Get("Content-Type") != "application/json" {
   299  			ch <- fmt.Errorf("Invalid 'Content-Type' %v", resp.Header.Get("Content-Type"))
   300  		}
   301  		var v *types.Stats
   302  		if err := json.NewDecoder(body).Decode(&v); err != nil {
   303  			ch <- err
   304  		}
   305  		ch <- nil
   306  	}()
   307  
   308  	select {
   309  	case err := <-ch:
   310  		assert.NilError(c, err, "Error in stats Engine API: %v", err)
   311  	case <-time.After(15 * time.Second):
   312  		c.Fatalf("Stats did not return after timeout")
   313  	}
   314  }