github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/disk_usage.go (about)

     1  package daemon // import "github.com/docker/docker/daemon"
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/docker/api/server/router/system"
     8  	"github.com/docker/docker/api/types"
     9  	"github.com/docker/docker/api/types/volume"
    10  	"golang.org/x/sync/errgroup"
    11  )
    12  
    13  // ContainerDiskUsage returns information about container data disk usage.
    14  func (daemon *Daemon) ContainerDiskUsage(ctx context.Context) ([]*types.Container, error) {
    15  	ch := daemon.usage.DoChan("ContainerDiskUsage", func() (interface{}, error) {
    16  		// Retrieve container list
    17  		containers, err := daemon.Containers(context.TODO(), &types.ContainerListOptions{
    18  			Size: true,
    19  			All:  true,
    20  		})
    21  		if err != nil {
    22  			return nil, fmt.Errorf("failed to retrieve container list: %v", err)
    23  		}
    24  		return containers, nil
    25  	})
    26  	select {
    27  	case <-ctx.Done():
    28  		return nil, ctx.Err()
    29  	case res := <-ch:
    30  		if res.Err != nil {
    31  			return nil, res.Err
    32  		}
    33  		return res.Val.([]*types.Container), nil
    34  	}
    35  }
    36  
    37  // SystemDiskUsage returns information about the daemon data disk usage.
    38  // Callers must not mutate contents of the returned fields.
    39  func (daemon *Daemon) SystemDiskUsage(ctx context.Context, opts system.DiskUsageOptions) (*types.DiskUsage, error) {
    40  	eg, ctx := errgroup.WithContext(ctx)
    41  
    42  	var containers []*types.Container
    43  	if opts.Containers {
    44  		eg.Go(func() error {
    45  			var err error
    46  			containers, err = daemon.ContainerDiskUsage(ctx)
    47  			return err
    48  		})
    49  	}
    50  
    51  	var (
    52  		images     []*types.ImageSummary
    53  		layersSize int64
    54  	)
    55  	if opts.Images {
    56  		eg.Go(func() error {
    57  			var err error
    58  			images, err = daemon.imageService.ImageDiskUsage(ctx)
    59  			return err
    60  		})
    61  		eg.Go(func() error {
    62  			var err error
    63  			layersSize, err = daemon.imageService.LayerDiskUsage(ctx)
    64  			return err
    65  		})
    66  	}
    67  
    68  	var volumes []*volume.Volume
    69  	if opts.Volumes {
    70  		eg.Go(func() error {
    71  			var err error
    72  			volumes, err = daemon.volumes.LocalVolumesSize(ctx)
    73  			return err
    74  		})
    75  	}
    76  
    77  	if err := eg.Wait(); err != nil {
    78  		return nil, err
    79  	}
    80  	return &types.DiskUsage{
    81  		LayersSize: layersSize,
    82  		Containers: containers,
    83  		Volumes:    volumes,
    84  		Images:     images,
    85  	}, nil
    86  }