get.porter.sh/porter@v1.3.0/pkg/cnab/provider/docker_linux.go (about)

     1  package cnabprovider
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os/exec"
     7  	"strings"
     8  
     9  	"github.com/docker/docker/api/types/container"
    10  	"github.com/docker/docker/api/types/mount"
    11  )
    12  
    13  func (r *Runtime) getDockerGroupId() (string, error) {
    14  	resp, err := r.NewCommand(context.Background(), "getent", "group", "docker").Output()
    15  	if err != nil {
    16  		if exitErr, ok := err.(*exec.ExitError); ok {
    17  			return "", fmt.Errorf("error querying for the docker group id: %s", string(exitErr.Stderr))
    18  		}
    19  		return "", fmt.Errorf("error querying for the docker group id: %w", err)
    20  	}
    21  	output := strings.TrimSpace(string(resp))
    22  	parts := strings.Split(output, ":")
    23  	if len(parts) < 3 {
    24  		return "", fmt.Errorf("could not determine the id of the docker group, unexpected output returned from 'getent group docker': '%s'", output)
    25  	}
    26  
    27  	// The command should return GROUP:x:GID
    28  	return parts[2], nil
    29  }
    30  
    31  func (r *Runtime) mountDockerSocket(cfg *container.Config, hostCfg *container.HostConfig) error {
    32  	// Add the container to the docker group so that it can access the docker socket
    33  	dockerGID, err := r.getDockerGroupId()
    34  	if err != nil {
    35  		return err
    36  	}
    37  	hostCfg.GroupAdd = []string{dockerGID}
    38  
    39  	// Equivalent of using: -v /var/run/docker.sock:/var/run/docker.sock
    40  	// Required for DooD, or "Docker-out-of-Docker"
    41  	dockerSockMount := mount.Mount{
    42  		Source:   "/var/run/docker.sock",
    43  		Target:   "/var/run/docker.sock",
    44  		Type:     "bind",
    45  		ReadOnly: false,
    46  	}
    47  	hostCfg.Mounts = append(hostCfg.Mounts, dockerSockMount)
    48  	return nil
    49  }
    50  
    51  func (r *Runtime) addVolumeMountToHostConfig(hostConfig *container.HostConfig, source string, target string, readOnly bool) error {
    52  	mount := mount.Mount{
    53  		Source:   source,
    54  		Target:   target,
    55  		Type:     "bind",
    56  		ReadOnly: readOnly,
    57  	}
    58  	hostConfig.Mounts = append(hostConfig.Mounts, mount)
    59  	return nil
    60  }