dockerfluent

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2024 License: MIT Imports: 19 Imported by: 0

README

DockerFluent

DockerFluent is a Go library that provides a fluent interface for interacting with Docker. It offers a chainable API for common Docker operations and includes advanced features like sorting, partitioning, and grouping containers, as well as AI-powered analysis of Docker environments.

Installation

go get github.com/vinodhalaharvi/dockerfluent

Usage

Here are some examples of how to use DockerFluent:

Deploying an Nginx Container
func ExampleDockerFluent_DeployNginx() {
    ctx := context.Background()
    dockerF, _ := New()
    
    err := dockerF.PullImage(ctx, "nginx:latest").
        CreateContainer(ctx, &container.Config{
            Image:        "nginx:latest",
            ExposedPorts: nat.PortSet{"80/tcp": struct{}{}},
        }, &container.HostConfig{
            PortBindings: nat.PortMap{"80/tcp": []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: "8080"}}},
        }, "example-nginx").
        StartContainer(ctx, "example-nginx").
        WaitForHealthy(ctx, "example-nginx", 30*time.Second).
        AIChain(ctx, "Analyze the Nginx container configuration and suggest optimizations.", processAIResponse).
        Error()

    if err != nil {
        log.Printf("Error in ExampleDeployNginx: %v", err)
    } else {
        fmt.Println("Nginx container deployed and analyzed successfully!")
    }

    // Cleanup
    dockerF.StopContainer(ctx, "example-nginx").RemoveContainer(ctx, "example-nginx")
}
Building a Custom Image
func ExampleDockerFluent_BuildCustomImage() {
    ctx := context.Background()
    dockerF, _ := New()

    dockerfile := `
FROM golang:1.16-alpine
WORKDIR /app
COPY . .
RUN go build -o main .
CMD ["./main"]
`

    err := dockerF.
        BuildImage(ctx, dockerfile, "custom-go-app:latest").
        CreateContainer(ctx, &container.Config{
            Image: "custom-go-app:latest",
        }, &container.HostConfig{}, "custom-go-app").
        StartContainer(ctx, "custom-go-app").
        WaitForHealthy(ctx, "custom-go-app", 30*time.Second).
        BulkInspectAndAnalyze(ctx).
        AIChain(ctx, "Analyze the custom Go app container and suggest performance improvements.", processAIResponse).
        Error()

    if err != nil {
        log.Printf("Error in ExampleDockerFluent_BuildCustomImage: %v", err)
    } else {
        fmt.Println("Custom image built, container deployed and analyzed successfully!")
    }

    // Cleanup
    dockerF.StopContainer(ctx, "custom-go-app").RemoveContainer(ctx, "custom-go-app")
}
Deploying a Multi-Container Application
func ExampleDockerFluent_DeployMultiContainerApp() {
    ctx := context.Background()
    dockerF, _ := New()

    err := dockerF.
        PullImage(ctx, "nginx:latest").
        PullImage(ctx, "redis:latest").
        CreateNetwork(ctx, "example-network").
        CreateContainer(ctx, &container.Config{
            Image:        "nginx:latest",
            ExposedPorts: nat.PortSet{"80/tcp": struct{}{}},
        }, &container.HostConfig{
            PortBindings: nat.PortMap{"80/tcp": []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: "8080"}}},
            NetworkMode:  "example-network",
        }, "example-nginx").
        CreateContainer(ctx, &container.Config{
            Image: "redis:latest",
        }, &container.HostConfig{
            NetworkMode: "example-network",
        }, "example-redis").
        StartContainer(ctx, "example-nginx").
        StartContainer(ctx, "example-redis").
        WaitForHealthy(ctx, "example-nginx", 30*time.Second).
        WaitForHealthy(ctx, "example-redis", 30*time.Second).
        BulkInspectAndAnalyze(ctx).
        AIChain(ctx, "Analyze the multi-container setup and suggest improvements.", processAIResponse).
        Error()

    if err != nil {
        log.Printf("Error in ExampleDockerFluent_DeployMultiContainerApp: %v", err)
    } else {
        fmt.Println("Multi-container application deployed and analyzed successfully!")
    }

    // Cleanup
    dockerF.
        StopContainer(ctx, "example-nginx").
        StopContainer(ctx, "example-redis").
        RemoveContainer(ctx, "example-nginx").
        RemoveContainer(ctx, "example-redis").
        RemoveNetwork(ctx, "example-network")
}
Managing Microservices
func ExampleDockerFluent_ManageMicroservices() {
    ctx := context.Background()
    dockerF, _ := New()

    services := []struct {
        name  string
        image string
        port  string
    }{
        {"auth-service", "auth-service:v1", "8081"},
        {"user-service", "user-service:v1", "8082"},
        {"product-service", "product-service:v1", "8083"},
    }

    for _, svc := range services {
        err := dockerF.
            PullImage(ctx, svc.image).
            CreateContainer(ctx, &container.Config{
                Image: svc.image,
                ExposedPorts: nat.PortSet{
                    nat.Port(svc.port + "/tcp"): struct{}{},
                },
            }, &container.HostConfig{
                PortBindings: nat.PortMap{
                    nat.Port(svc.port + "/tcp"): []nat.PortBinding{{HostIP: "0.0.0.0", HostPort: svc.port}},
                },
            }, svc.name).
            StartContainer(ctx, svc.name).
            WaitForHealthy(ctx, svc.name, 30*time.Second).
            Error()

        if err != nil {
            log.Printf("Error deploying %s: %v", svc.name, err)
            return
        }
    }

    // Use the new Sort method to sort containers by creation time
    dockerF.Sort(ctx, func(c1, c2 types.Container) bool {
        return c1.Created > c2.Created
    })

    // Use the new Partition method to separate running and stopped containers
    result, _ := dockerF.Partition(ctx, func(c types.Container) bool {
        return c.State == "running"
    })

    fmt.Printf("Running containers: %d, Stopped containers: %d\n",
        len(result.Matching), len(result.NonMatching))

    // Cleanup
    for _, svc := range services {
        dockerF.StopContainer(ctx, svc.name).RemoveContainer(ctx, svc.name)
    }
}
Monitoring Containers
func ExampleDockerFluent_MonitorContainers() {
    ctx := context.Background()
    dockerF, _ := New()

    containers, _ := dockerF.ListContainers(ctx)

    groups, _ := dockerF.GroupBy(ctx, func(c types.Container) string {
        return c.Image
    })

    for image, containers := range groups {
        fmt.Printf("Image %s has %d containers\n", image, len(containers))
    }

    for _, container := range containers {
        stats, _ := dockerF.Client.ContainerStats(ctx, container.ID, false)
        defer stats.Body.Close()

        var statsJSON types.StatsJSON
        json.NewDecoder(stats.Body).Decode(&statsJSON)

        fmt.Printf("Container %s (Image: %s):\n", container.ID[:12], container.Image)
        fmt.Printf("  CPU: %.2f%%\n", calculateCPUPercentUnix(statsJSON.CPUStats, statsJSON.PreCPUStats))
        fmt.Printf("  Memory: %.2f%%\n", calculateMemoryUsageUnixNoCache(statsJSON.MemoryStats))
    }

    dockerF.AIChain(ctx, "Analyze the container metrics and suggest optimizations for resource usage.", processAIResponse)
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AIChainFunc

type AIChainFunc func(aiResponse string) func(*DockerFluent) *DockerFluent

AIChainFunc is a function type that processes AI responses and returns a DockerFluent operation

type ContainerKeySelector

type ContainerKeySelector func(c types.Container) string

ContainerKeySelector is a function type for selecting a grouping key from a container

type ContainerPredicate

type ContainerPredicate func(c types.Container) bool

ContainerPredicate is a function type for testing a condition on a container

type ContainerSorter

type ContainerSorter func(c1, c2 types.Container) bool

ContainerSorter is a function type for comparing two containers

type DockerFluent

type DockerFluent struct {
	Client *client.Client
	// contains filtered or unexported fields
}

DockerFluent represents a monadic operation on the Docker client

func New

func New(dockerHost ...string) (*DockerFluent, error)

New creates a new DockerFluent instance with optional Docker host

func (*DockerFluent) AIChain

func (d *DockerFluent) AIChain(ctx context.Context, prompt string, aiChainFunc AIChainFunc) *DockerFluent

AIChain sends the current state to OpenAI and processes the response

func (*DockerFluent) Bind

func (d *DockerFluent) Bind(operation func(*client.Client) error) *DockerFluent

Bind chains an operation to the DockerFluent

func (*DockerFluent) BuildImage

func (d *DockerFluent) BuildImage(ctx context.Context, dockerfileContent string, tags ...string) *DockerFluent

BuildImage builds a Docker image from a Dockerfile

func (*DockerFluent) BulkInspectAndAnalyze

func (d *DockerFluent) BulkInspectAndAnalyze(ctx context.Context) *DockerFluent

BulkInspectAndAnalyze inspects all containers and sends the results to OpenAI for analysis

func (*DockerFluent) ConcurrentBind

func (d *DockerFluent) ConcurrentBind(operations ...func(*client.Client) error) *DockerFluent

ConcurrentBind executes multiple operations concurrently

func (*DockerFluent) ConcurrentExec

func (d *DockerFluent) ConcurrentExec(ctx context.Context, execConfigs map[string]types.ExecConfig) []ExecResult

ConcurrentExec executes commands in multiple containers concurrently

func (*DockerFluent) ConcurrentPullImages

func (d *DockerFluent) ConcurrentPullImages(ctx context.Context, images ...string) *DockerFluent

ConcurrentPullImages Update ConcurrentPullImages similarly

func (*DockerFluent) ConcurrentStartContainers

func (d *DockerFluent) ConcurrentStartContainers(ctx context.Context, containerIDs ...string) *DockerFluent

ConcurrentStartContainers starts multiple containers concurrently

func (*DockerFluent) ConcurrentStopContainers

func (d *DockerFluent) ConcurrentStopContainers(ctx context.Context, containerIDs ...string) *DockerFluent

ConcurrentStopContainers stops multiple containers concurrently

func (*DockerFluent) CreateContainer

func (d *DockerFluent) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, name string) *DockerFluent

CreateContainer creates a new container

func (*DockerFluent) CreateNetwork

func (d *DockerFluent) CreateNetwork(ctx context.Context, name string) *DockerFluent

CreateNetwork creates a Docker network

func (*DockerFluent) EnhancedInspect

func (d *DockerFluent) EnhancedInspect(ctx context.Context, id string) (*InspectResult, error)

EnhancedInspect provides a comprehensive inspection of a Docker object

func (*DockerFluent) Error

func (d *DockerFluent) Error() error

Error returns any error that occurred during the chain of operations

func (*DockerFluent) GenerateContainerSVG

func (d *DockerFluent) GenerateContainerSVG(inspectResult *types.ContainerJSON) string

func (*DockerFluent) GetLogs

func (d *DockerFluent) GetLogs(ctx context.Context, containerID string) (io.ReadCloser, error)

GetLogs retrieves logs from a container

func (*DockerFluent) GroupBy

func (d *DockerFluent) GroupBy(ctx context.Context, keySelector ContainerKeySelector) (GroupByResult, error)

GroupBy groups containers based on the provided key selector

func (*DockerFluent) ListContainers

func (d *DockerFluent) ListContainers(ctx context.Context) ([]types.Container, error)

ListContainers lists all containers

func (*DockerFluent) Partition

func (d *DockerFluent) Partition(ctx context.Context, predicate ContainerPredicate) (*PartitionResult, error)

Partition splits containers into two groups based on the provided predicate

func (*DockerFluent) PullImage

func (d *DockerFluent) PullImage(ctx context.Context, img string) *DockerFluent

PullImage pulls a Docker image with detailed progress output

func (*DockerFluent) RemoveContainer

func (d *DockerFluent) RemoveContainer(ctx context.Context, containerID string) *DockerFluent

RemoveContainer removes a container

func (*DockerFluent) RemoveNetwork

func (d *DockerFluent) RemoveNetwork(ctx context.Context, name string) *DockerFluent

RemoveNetwork removes a Docker network

func (*DockerFluent) Sort

Sort sorts the containers based on the provided sorter function

func (*DockerFluent) StartContainer

func (d *DockerFluent) StartContainer(ctx context.Context, containerID string) *DockerFluent

StartContainer starts a container

func (*DockerFluent) StopContainer

func (d *DockerFluent) StopContainer(ctx context.Context, containerID string) *DockerFluent

StopContainer stops a container

func (*DockerFluent) WaitForHealthy

func (d *DockerFluent) WaitForHealthy(ctx context.Context, containerID string, timeout time.Duration) *DockerFluent

type ExecResult

type ExecResult struct {
	ContainerID string
	Output      string
	Error       error
}

ExecResult represents the result of an exec operation

type GroupByResult

type GroupByResult map[string][]types.Container

GroupByResult holds the result of a group by operation

type InspectResult

type InspectResult struct {
	Container *types.ContainerJSON  `json:"container,omitempty"`
	Image     types.ImageInspect    `json:"image,omitempty"`
	Network   types.NetworkResource `json:"network,omitempty"`
	Volume    volume.Volume         `json:"volume,omitempty"`
	Logs      string                `json:"logs,omitempty"`
	Stats     types.Stats           `json:"stats,omitempty"`
	Processes [][]string            `json:"processes,omitempty"`
	//Ports       []types.Port          `json:"ports,omitempty"`
	Ports       nat.PortMap        `json:"ports,omitempty"`
	Mounts      []types.MountPoint `json:"mounts,omitempty"`
	Environment []string           `json:"environment,omitempty"`
}

InspectResult represents the comprehensive inspection result

func (*InspectResult) PrettyPrint

func (r *InspectResult) PrettyPrint() string

PrettyPrint outputs the InspectResult in a formatted JSON

type PartitionResult

type PartitionResult struct {
	Matching    []types.Container
	NonMatching []types.Container
}

PartitionResult holds the result of a partition operation

Jump to

Keyboard shortcuts

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