dockerutil

package module
v0.0.0-...-2253830 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: GPL-3.0 Imports: 29 Imported by: 3

README

this module handles docker compose management for my transliteration libraries. I think of it as an internal pkg and therefore I recommend not using except if you want to fork it.

Documentation

Overview

Package dockerutil provides reusable Docker container management functionality for transliteration services.

Index

Constants

View Source
const ServicePortKey contextKey = "service.port"

Variables

View Source
var (
	// ErrNotInitialized is returned when operations are attempted before initialization
	ErrNotInitialized = errors.New("project not initialized, was Init() called?")

	// logger internal to the library:
	Logger = zerolog.Nop()
)
View Source
var (
	// docker's logger:
	// never disable this logger at it is monitored for init message.
	// To hide logs pass level zerolog.Disabled in LogConfig to NewContainerLogConsumer.
	DockerLogger    zerolog.Logger
	DockerLogBuffer bytes.Buffer
)

Functions

func DockerBackendName

func DockerBackendName() string

func EngineIsReachable

func EngineIsReachable() error

EngineIsReachable verifies if Docker daemon is running and accessible Returns nil if Docker is reachable, otherwise returns an error with details

func GetConfigDir

func GetConfigDir(projectName string) (string, error)

GetConfigDir returns the platform-specific configuration directory

func GetImagePullBaseline

func GetImagePullBaseline(ctx context.Context, imageName string) (baseline int64, totalSize int64, err error)

GetImagePullBaseline calculates bytes already cached locally for an image. It fetches the remote manifest (metadata only, no layer downloads) and compares layer DiffIDs against locally cached layers via Docker's ImageInspect API.

Returns (baseline, totalSize, error) where: - baseline: bytes already cached locally - totalSize: total compressed size of all layers

func GetImagesManifestInfo

func GetImagesManifestInfo(ctx context.Context, imageNames []string) (totalUniqueBytes int64, layers map[string]int64, err error)

GetImagesManifestInfo fetches manifests for multiple images, deduplicating shared layers. Returns the total size of unique layers across all images.

func PullImage

func PullImage(ctx context.Context, imageName string, opts PullOptions) error

PullImage pulls a Docker image with retry logic and verification

func PullImages

func PullImages(ctx context.Context, imageNames []string, opts PullOptions) error

PullImages pulls multiple Docker images with unified progress tracking. Layers shared between images are deduplicated automatically. Progress callback receives accurate (current, total) across all images.

func SetLogOutput

func SetLogOutput(output LogOutput)

SetLogOutput configures where Docker logs are written

Types

type Config

type Config struct {
	ProjectName      string
	Project          *types.Project // Compose project defined in Go
	RequiredServices []string
	LogConsumer      LogConsumer
	Timeout          Timeout
	OnPullProgress   func(current, total int64, status string) // Progress callback for image pulls
}

Config holds configuration options for DockerManager

type ContainerLogConsumer

type ContainerLogConsumer struct {
	Prefix          string
	ShowService     bool
	ShowType        bool
	Level           zerolog.Level
	InitChan        chan struct{}
	FailedChan      chan error
	InitMessage     string // Message that indicates initialization is complete
	ProgressHandler ProgressHandler
	Milestones      []ProgressMilestone
	// contains filtered or unexported fields
}

ContainerLogConsumer implements log consumption for Docker containers

func NewContainerLogConsumer

func NewContainerLogConsumer(config LogConfig) *ContainerLogConsumer

NewContainerLogConsumer creates a new log consumer with the specified configuration

func (*ContainerLogConsumer) Close

func (l *ContainerLogConsumer) Close()

Close closes the initialization and failure channels

func (*ContainerLogConsumer) Err

func (l *ContainerLogConsumer) Err(containerName, message string)

Err handles stderr messages from containers

func (*ContainerLogConsumer) GetInitChan

func (l *ContainerLogConsumer) GetInitChan() chan struct{}

func (*ContainerLogConsumer) GetInitMessage

func (l *ContainerLogConsumer) GetInitMessage() string

func (*ContainerLogConsumer) Log

func (l *ContainerLogConsumer) Log(containerName, message string)

Log handles stdout messages from containers

func (*ContainerLogConsumer) Register

func (l *ContainerLogConsumer) Register(container string)

Register handles container registration events

func (*ContainerLogConsumer) Status

func (l *ContainerLogConsumer) Status(container, msg string)

Status handles container status messages

type DockerManager

type DockerManager struct {
	Timeout Timeout
	// contains filtered or unexported fields
}

DockerManager handles Docker container lifecycle management

func NewDockerManager

func NewDockerManager(ctx context.Context, cfg Config) (*DockerManager, error)

NewDockerManager creates a new Docker service manager instance

func (*DockerManager) Close

func (dm *DockerManager) Close() error

Close implements io.Closer

func (*DockerManager) Down

func (dm *DockerManager) Down() error

func (*DockerManager) GetClient

func (dm *DockerManager) GetClient() (*client.Client, error)

GetClient returns the underlying Docker client

func (*DockerManager) Init

func (dm *DockerManager) Init() error

Init builds and up the containers

func (*DockerManager) InitQuiet

func (dm *DockerManager) InitQuiet() error

InitQuiet initializes with reduced logging

func (*DockerManager) InitRecreate

func (dm *DockerManager) InitRecreate() error

InitRecreate remove existing containers, builds and up new containers

func (*DockerManager) InitRecreateNoCache

func (dm *DockerManager) InitRecreateNoCache() error

InitRecreateNoCache remove existing containers and downloads the lastest version of dependencies then builds and up the containers

func (*DockerManager) Status

func (dm *DockerManager) Status() (string, error)

Status returns the current status of containers

func (*DockerManager) Stop

func (dm *DockerManager) Stop() error

Stop stops all running containers Uses a fresh context to ensure cleanup succeeds even if original context was canceled

type ImageManifestInfo

type ImageManifestInfo struct {
	ImageName  string
	TotalSize  int64
	LayerCount int
	Layers     []LayerDigestSize
}

ImageManifestInfo contains size information for an image

func GetImageManifestInfo

func GetImageManifestInfo(ctx context.Context, imageName string) (*ImageManifestInfo, error)

GetImageManifestInfo fetches manifest to get exact layer sizes without pulling. Uses Digest for layer identification (suitable for deduplication across images).

type LayerDigestSize

type LayerDigestSize struct {
	Digest string
	Size   int64
}

LayerDigestSize contains digest and size for a layer

type LogConfig

type LogConfig struct {
	Prefix      string
	ShowService bool
	ShowType    bool
	LogLevel    zerolog.Level
	InitMessage string
}

LogConfig holds configuration for the log consumer

type LogConsumer

type LogConsumer interface {
	Log(containerName, message string)
	Err(containerName, message string)
	Status(container, msg string)
	Register(container string)
	GetInitChan() chan struct{}
	GetInitMessage() string
}

LogConsumer defines the interface for consuming Docker container logs

type LogOutput

type LogOutput int
const (
	LogToNowhere LogOutput = iota
	LogToStdout
	LogToBuffer
	LogToBoth
)

type ProgressHandler

type ProgressHandler func(progress float64, description string, logMessage string)

ProgressHandler is called when milestones are reached The logMessage parameter contains the full log line for extracting additional information

type ProgressMilestone

type ProgressMilestone struct {
	Pattern     string  // Regex pattern to match
	Progress    float64 // Progress percentage (0-100) when this milestone is reached
	Description string  // User-friendly description
}

ProgressMilestone represents a log pattern that indicates progress

type PullOptions

type PullOptions struct {
	MaxRetries      uint64        // Default: 3 (0 = unlimited until MaxElapsedTime)
	InitialInterval time.Duration // Default: 10s
	MaxInterval     time.Duration // Default: 60s
	MaxElapsedTime  time.Duration // Default: 0 (no limit)
	ClientTimeout   time.Duration // Default: 10m - HTTP client timeout per request
	OnProgress      func(current, total int64, status string)
	OnRetry         func(err error, duration time.Duration)
}

PullOptions configures image pull behavior

func DefaultPullOptions

func DefaultPullOptions() PullOptions

DefaultPullOptions returns sensible defaults for large image pulls

type Timeout

type Timeout struct {
	Create   time.Duration
	Recreate time.Duration
	// until containers reached the running|healthy state
	Start time.Duration
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL