github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/internal/containerizedengine/containerd.go (about)

     1  package containerizedengine
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  
     7  	"github.com/containerd/containerd"
     8  	"github.com/containerd/containerd/images"
     9  	"github.com/containerd/containerd/remotes/docker"
    10  	clitypes "github.com/docker/cli/types"
    11  	"github.com/docker/docker/api/types"
    12  	"github.com/docker/docker/pkg/jsonmessage"
    13  	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
    14  )
    15  
    16  // NewClient returns a new containerizedengine client
    17  // This client can be used to manage the lifecycle of
    18  // dockerd running as a container on containerd.
    19  func NewClient(sockPath string) (clitypes.ContainerizedClient, error) {
    20  	if sockPath == "" {
    21  		sockPath = containerdSockPath
    22  	}
    23  	cclient, err := containerd.New(sockPath)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	return &baseClient{
    28  		cclient: cclient,
    29  	}, nil
    30  }
    31  
    32  // Close will close the underlying clients
    33  func (c *baseClient) Close() error {
    34  	return c.cclient.Close()
    35  }
    36  
    37  func (c *baseClient) pullWithAuth(ctx context.Context, imageName string, out clitypes.OutStream,
    38  	authConfig *types.AuthConfig) (containerd.Image, error) {
    39  
    40  	resolver := docker.NewResolver(docker.ResolverOptions{
    41  		Credentials: func(string) (string, string, error) {
    42  			return authConfig.Username, authConfig.Password, nil
    43  		},
    44  	})
    45  
    46  	ongoing := newJobs(imageName)
    47  	pctx, stopProgress := context.WithCancel(ctx)
    48  	progress := make(chan struct{})
    49  	bufin, bufout := io.Pipe()
    50  
    51  	go func() {
    52  		showProgress(pctx, ongoing, c.cclient.ContentStore(), bufout)
    53  	}()
    54  
    55  	go func() {
    56  		jsonmessage.DisplayJSONMessagesToStream(bufin, out, nil)
    57  		close(progress)
    58  	}()
    59  
    60  	h := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
    61  		if desc.MediaType != images.MediaTypeDockerSchema1Manifest {
    62  			ongoing.add(desc)
    63  		}
    64  		return nil, nil
    65  	})
    66  
    67  	image, err := c.cclient.Pull(ctx, imageName,
    68  		containerd.WithResolver(resolver),
    69  		containerd.WithImageHandler(h),
    70  		containerd.WithPullUnpack)
    71  	stopProgress()
    72  
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	<-progress
    77  	return image, nil
    78  }