go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/connection/docker_snapshot.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package connection
     5  
     6  import (
     7  	"context"
     8  	"os"
     9  
    10  	"go.mondoo.com/cnquery/providers-sdk/v1/inventory"
    11  	"go.mondoo.com/cnquery/providers/os/connection/container/cache"
    12  	"go.mondoo.com/cnquery/providers/os/connection/shared"
    13  )
    14  
    15  const (
    16  	DockerSnapshot shared.ConnectionType = "docker-snapshot"
    17  )
    18  
    19  var _ shared.Connection = &DockerSnapshotConnection{}
    20  
    21  type DockerSnapshotConnection struct {
    22  	TarConnection
    23  }
    24  
    25  func NewDockerSnapshotConnection(id uint32, conf *inventory.Config, asset *inventory.Asset) (*DockerSnapshotConnection, error) {
    26  	tarConnection, err := NewWithClose(id, conf, asset, func() {})
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	// FIXME: ??? use NewFromDockerEngine
    32  
    33  	return &DockerSnapshotConnection{*tarConnection}, nil
    34  }
    35  
    36  // NewFromDockerEngine creates a snapshot for a docker engine container and opens it
    37  func NewFromDockerEngine(id uint32, conf *inventory.Config, asset *inventory.Asset) (*DockerSnapshotConnection, error) {
    38  	// cache container on local disk
    39  	f, err := cache.RandomFile()
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	err = ExportSnapshot(conf.Host, f)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	tarConnection, err := NewWithClose(id, &inventory.Config{
    50  		Type: "tar",
    51  		Options: map[string]string{
    52  			OPTION_FILE: f.Name(),
    53  		},
    54  	}, asset, func() {
    55  		// remove temporary file on stream close
    56  		os.Remove(f.Name())
    57  	})
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return &DockerSnapshotConnection{*tarConnection}, nil
    63  }
    64  
    65  // ExportSnapshot exports a given container from docker engine to a tar file
    66  func ExportSnapshot(containerid string, f *os.File) error {
    67  	dc, err := GetDockerClient()
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	rc, err := dc.ContainerExport(context.Background(), containerid)
    73  	if err != nil {
    74  		return err
    75  	}
    76  
    77  	return cache.StreamToTmpFile(rc, f)
    78  }
    79  
    80  func (p *DockerSnapshotConnection) ID() uint32 {
    81  	return p.id
    82  }
    83  
    84  func (p *DockerSnapshotConnection) Name() string {
    85  	return string(DockerSnapshot)
    86  }
    87  
    88  func (p *DockerSnapshotConnection) Type() shared.ConnectionType {
    89  	return DockerSnapshot
    90  }