commands

package
v0.23.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2023 License: MIT Imports: 35 Imported by: 4

Documentation

Index

Constants

View Source
const (
	APIVersion = "1.25"
)
View Source
const (
	// MustStopContainer tells us that we must stop the container before removing it
	MustStopContainer = iota
)

Variables

This section is empty.

Functions

func HasErrorCode

func HasErrorCode(err error, code int) bool

HasErrorCode is a function

func NewDummyAppConfig

func NewDummyAppConfig() *config.AppConfig

NewDummyAppConfig creates a new dummy AppConfig for testing

func NewDummyLog

func NewDummyLog() *logrus.Entry

NewDummyLog creates a new dummy Log for testing

func WrapError

func WrapError(err error) error

WrapError wraps an error for the sake of showing a stack trace at the top level the go-errors package, for some reason, does not return nil when you try to wrap a non-error, so we're just doing it here

Types

type CommandObject

type CommandObject struct {
	DockerCompose string
	Service       *Service
	Container     *Container
	Image         *Image
	Volume        *Volume
	Network       *Network
}

CommandObject is what we pass to our template resolvers when we are running a custom command. We do not guarantee that all fields will be populated: just the ones that make sense for the current context

type ComplexError

type ComplexError struct {
	Message string
	Code    int
	// contains filtered or unexported fields
}

ComplexError an error which carries a code so that calling code has an easier job to do adapted from https://medium.com/yakka/better-go-error-handling-with-xerrors-1987650e0c79

func (ComplexError) Error

func (ce ComplexError) Error() string

func (ComplexError) Format

func (ce ComplexError) Format(f fmt.State, c rune)

Format is a function

func (ComplexError) FormatError

func (ce ComplexError) FormatError(p xerrors.Printer) error

FormatError is a function

type Container

type Container struct {
	Name            string
	ServiceName     string
	ContainerNumber string // might make this an int in the future if need be

	// OneOff tells us if the container is just a job container or is actually bound to the service
	OneOff          bool
	ProjectName     string
	ID              string
	Container       dockerTypes.Container
	Client          *client.Client
	OSCommand       *OSCommand
	Log             *logrus.Entry
	StatHistory     []*RecordedStats
	Details         dockerTypes.ContainerJSON
	MonitoringStats bool
	DockerCommand   LimitedDockerCommand
	Tr              *i18n.TranslationSet

	StatsMutex deadlock.Mutex
}

Container : A docker Container

func (*Container) Attach

func (c *Container) Attach() (*exec.Cmd, error)

Attach attaches the container

func (*Container) DetailsLoaded added in v0.2.1

func (c *Container) DetailsLoaded() bool

DetailsLoaded tells us whether we have yet loaded the details for a container. Because this is an asynchronous operation, sometimes we have the container before we have its details.

func (*Container) GetLastStats added in v0.20.0

func (c *Container) GetLastStats() (*RecordedStats, bool)

func (*Container) Inspect

func (c *Container) Inspect() (dockerTypes.ContainerJSON, error)

Inspect returns details about the container

func (*Container) Pause added in v0.19.0

func (c *Container) Pause() error

Pause pauses the container

func (*Container) Remove

Remove removes the container

func (*Container) RenderTop

func (c *Container) RenderTop(ctx context.Context) (string, error)

RenderTop returns details about the container

func (*Container) Restart

func (c *Container) Restart() error

Restart restarts the container

func (*Container) Stop

func (c *Container) Stop() error

Stop stops the container

func (*Container) Top

Top returns process information

func (*Container) Unpause added in v0.19.0

func (c *Container) Unpause() error

Unpause unpauses the container

type ContainerStats

type ContainerStats struct {
	Read      time.Time `json:"read"`
	Preread   time.Time `json:"preread"`
	PidsStats struct {
		Current int `json:"current"`
	} `json:"pids_stats"`
	BlkioStats struct {
		IoServiceBytesRecursive []struct {
			Major int    `json:"major"`
			Minor int    `json:"minor"`
			Op    string `json:"op"`
			Value int    `json:"value"`
		} `json:"io_service_bytes_recursive"`
		IoServicedRecursive []struct {
			Major int    `json:"major"`
			Minor int    `json:"minor"`
			Op    string `json:"op"`
			Value int    `json:"value"`
		} `json:"io_serviced_recursive"`
		IoQueueRecursive       []interface{} `json:"io_queue_recursive"`
		IoServiceTimeRecursive []interface{} `json:"io_service_time_recursive"`
		IoWaitTimeRecursive    []interface{} `json:"io_wait_time_recursive"`
		IoMergedRecursive      []interface{} `json:"io_merged_recursive"`
		IoTimeRecursive        []interface{} `json:"io_time_recursive"`
		SectorsRecursive       []interface{} `json:"sectors_recursive"`
	} `json:"blkio_stats"`
	NumProcs     int      `json:"num_procs"`
	StorageStats struct{} `json:"storage_stats"`
	CPUStats     struct {
		CPUUsage struct {
			TotalUsage        int64   `json:"total_usage"`
			PercpuUsage       []int64 `json:"percpu_usage"`
			UsageInKernelmode int64   `json:"usage_in_kernelmode"`
			UsageInUsermode   int64   `json:"usage_in_usermode"`
		} `json:"cpu_usage"`
		SystemCPUUsage int64 `json:"system_cpu_usage"`
		OnlineCpus     int   `json:"online_cpus"`
		ThrottlingData struct {
			Periods          int `json:"periods"`
			ThrottledPeriods int `json:"throttled_periods"`
			ThrottledTime    int `json:"throttled_time"`
		} `json:"throttling_data"`
	} `json:"cpu_stats"`
	PrecpuStats struct {
		CPUUsage struct {
			TotalUsage        int64   `json:"total_usage"`
			PercpuUsage       []int64 `json:"percpu_usage"`
			UsageInKernelmode int64   `json:"usage_in_kernelmode"`
			UsageInUsermode   int64   `json:"usage_in_usermode"`
		} `json:"cpu_usage"`
		SystemCPUUsage int64 `json:"system_cpu_usage"`
		OnlineCpus     int   `json:"online_cpus"`
		ThrottlingData struct {
			Periods          int `json:"periods"`
			ThrottledPeriods int `json:"throttled_periods"`
			ThrottledTime    int `json:"throttled_time"`
		} `json:"throttling_data"`
	} `json:"precpu_stats"`
	MemoryStats struct {
		Usage    int `json:"usage"`
		MaxUsage int `json:"max_usage"`
		Stats    struct {
			ActiveAnon              int   `json:"active_anon"`
			ActiveFile              int   `json:"active_file"`
			Cache                   int   `json:"cache"`
			Dirty                   int   `json:"dirty"`
			HierarchicalMemoryLimit int64 `json:"hierarchical_memory_limit"`
			HierarchicalMemswLimit  int64 `json:"hierarchical_memsw_limit"`
			InactiveAnon            int   `json:"inactive_anon"`
			InactiveFile            int   `json:"inactive_file"`
			MappedFile              int   `json:"mapped_file"`
			Pgfault                 int   `json:"pgfault"`
			Pgmajfault              int   `json:"pgmajfault"`
			Pgpgin                  int   `json:"pgpgin"`
			Pgpgout                 int   `json:"pgpgout"`
			Rss                     int   `json:"rss"`
			RssHuge                 int   `json:"rss_huge"`
			TotalActiveAnon         int   `json:"total_active_anon"`
			TotalActiveFile         int   `json:"total_active_file"`
			TotalCache              int   `json:"total_cache"`
			TotalDirty              int   `json:"total_dirty"`
			TotalInactiveAnon       int   `json:"total_inactive_anon"`
			TotalInactiveFile       int   `json:"total_inactive_file"`
			TotalMappedFile         int   `json:"total_mapped_file"`
			TotalPgfault            int   `json:"total_pgfault"`
			TotalPgmajfault         int   `json:"total_pgmajfault"`
			TotalPgpgin             int   `json:"total_pgpgin"`
			TotalPgpgout            int   `json:"total_pgpgout"`
			TotalRss                int   `json:"total_rss"`
			TotalRssHuge            int   `json:"total_rss_huge"`
			TotalUnevictable        int   `json:"total_unevictable"`
			TotalWriteback          int   `json:"total_writeback"`
			Unevictable             int   `json:"unevictable"`
			Writeback               int   `json:"writeback"`
		} `json:"stats"`
		Limit int64 `json:"limit"`
	} `json:"memory_stats"`
	Name     string `json:"name"`
	ID       string `json:"id"`
	Networks struct {
		Eth0 struct {
			RxBytes   int `json:"rx_bytes"`
			RxPackets int `json:"rx_packets"`
			RxErrors  int `json:"rx_errors"`
			RxDropped int `json:"rx_dropped"`
			TxBytes   int `json:"tx_bytes"`
			TxPackets int `json:"tx_packets"`
			TxErrors  int `json:"tx_errors"`
			TxDropped int `json:"tx_dropped"`
		} `json:"eth0"`
	} `json:"networks"`
}

ContainerStats autogenerated at https://mholt.github.io/json-to-go/

func (*ContainerStats) CalculateContainerCPUPercentage

func (s *ContainerStats) CalculateContainerCPUPercentage() float64

CalculateContainerCPUPercentage calculates the cpu usage of the container as a percent of total CPU usage to calculate CPU usage, we take the increase in CPU time from the container since the last poll, divide that by the total increase in CPU time since the last poll, times by the number of cores, and times by 100 to get a percentage I'm not entirely sure why we need to multiply by the number of cores, but the numbers work

func (*ContainerStats) CalculateContainerMemoryUsage

func (s *ContainerStats) CalculateContainerMemoryUsage() float64

CalculateContainerMemoryUsage calculates the memory usage of the container as a percent of total available memory

type DerivedStats

type DerivedStats struct {
	CPUPercentage    float64
	MemoryPercentage float64
}

DerivedStats contains some useful stats that we've calculated based on the raw container stats that we got back from docker

type DockerCommand

type DockerCommand struct {
	Log                    *logrus.Entry
	OSCommand              *OSCommand
	Tr                     *i18n.TranslationSet
	Config                 *config.AppConfig
	Client                 *client.Client
	InDockerComposeProject bool
	ErrorChan              chan error
	ContainerMutex         deadlock.Mutex
	ServiceMutex           deadlock.Mutex

	Closers []io.Closer
}

DockerCommand is our main docker interface

func NewDockerCommand

func NewDockerCommand(log *logrus.Entry, osCommand *OSCommand, tr *i18n.TranslationSet, config *config.AppConfig, errorChan chan error) (*DockerCommand, error)

NewDockerCommand it runs docker commands

func NewDummyDockerCommand

func NewDummyDockerCommand() *DockerCommand

NewDummyDockerCommand creates a new dummy DockerCommand for testing

func NewDummyDockerCommandWithOSCommand

func NewDummyDockerCommandWithOSCommand(osCommand *OSCommand) *DockerCommand

NewDummyDockerCommandWithOSCommand creates a new dummy DockerCommand for testing

func (*DockerCommand) Close added in v0.17.1

func (c *DockerCommand) Close() error

func (*DockerCommand) CreateClientStatMonitor added in v0.20.0

func (c *DockerCommand) CreateClientStatMonitor(container *Container)

func (*DockerCommand) DockerComposeConfig

func (c *DockerCommand) DockerComposeConfig() string

DockerComposeConfig returns the result of 'docker-compose config'

func (*DockerCommand) GetContainers

func (c *DockerCommand) GetContainers(existingContainers []*Container) ([]*Container, error)

GetContainers gets the docker containers

func (*DockerCommand) GetServices

func (c *DockerCommand) GetServices() ([]*Service, error)

GetServices gets services

func (*DockerCommand) NewCommandObject

func (c *DockerCommand) NewCommandObject(obj CommandObject) CommandObject

NewCommandObject takes a command object and returns a default command object with the passed command object merged in

func (*DockerCommand) PruneContainers

func (c *DockerCommand) PruneContainers() error

PruneContainers prunes containers

func (*DockerCommand) PruneImages

func (c *DockerCommand) PruneImages() error

PruneImages prunes images

func (*DockerCommand) PruneNetworks added in v0.21.0

func (c *DockerCommand) PruneNetworks() error

PruneNetworks prunes networks

func (*DockerCommand) PruneVolumes

func (c *DockerCommand) PruneVolumes() error

PruneVolumes prunes volumes

func (*DockerCommand) RefreshContainersAndServices

func (c *DockerCommand) RefreshContainersAndServices(currentServices []*Service, currentContainers []*Container) ([]*Container, []*Service, error)

func (*DockerCommand) RefreshImages added in v0.2.1

func (c *DockerCommand) RefreshImages() ([]*Image, error)

RefreshImages returns a slice of docker images

func (*DockerCommand) RefreshNetworks added in v0.21.0

func (c *DockerCommand) RefreshNetworks() ([]*Network, error)

RefreshNetworks gets the networks and stores them

func (*DockerCommand) RefreshVolumes

func (c *DockerCommand) RefreshVolumes() ([]*Volume, error)

RefreshVolumes gets the volumes and stores them

func (*DockerCommand) UpdateContainerDetails

func (c *DockerCommand) UpdateContainerDetails(containers []*Container) error

UpdateContainerDetails attaches the details returned from docker inspect to each of the containers this contains a bit more info than what you get from the go-docker client

func (*DockerCommand) ViewAllLogs

func (c *DockerCommand) ViewAllLogs() (*exec.Cmd, error)

ViewAllLogs attaches to a subprocess viewing all the logs from docker-compose

type Image

type Image struct {
	Name          string
	Tag           string
	ID            string
	Image         dockerTypes.ImageSummary
	Client        *client.Client
	OSCommand     *OSCommand
	Log           *logrus.Entry
	DockerCommand LimitedDockerCommand
}

Image : A docker Image

func (*Image) Remove

func (i *Image) Remove(options dockerTypes.ImageRemoveOptions) error

Remove removes the image

func (*Image) RenderHistory

func (i *Image) RenderHistory() (string, error)

RenderHistory renders the history of the image

type LimitedDockerCommand

type LimitedDockerCommand interface {
	NewCommandObject(CommandObject) CommandObject
}

LimitedDockerCommand is a stripped-down DockerCommand with just the methods the container/service/image might need

type Network added in v0.21.0

type Network struct {
	Name          string
	Network       dockerTypes.NetworkResource
	Client        *client.Client
	OSCommand     *OSCommand
	Log           *logrus.Entry
	DockerCommand LimitedDockerCommand
}

Network : A docker Network

func (*Network) Remove added in v0.21.0

func (v *Network) Remove() error

Remove removes the network

type OSCommand

type OSCommand struct {
	Log      *logrus.Entry
	Platform *Platform
	Config   *config.AppConfig
	// contains filtered or unexported fields
}

OSCommand holds all the os commands

func NewDummyOSCommand

func NewDummyOSCommand() *OSCommand

NewDummyOSCommand creates a new dummy OSCommand for testing

func NewOSCommand

func NewOSCommand(log *logrus.Entry, config *config.AppConfig) *OSCommand

NewOSCommand os command runner

func (*OSCommand) AppendLineToFile

func (c *OSCommand) AppendLineToFile(filename, line string) error

AppendLineToFile adds a new line in file

func (*OSCommand) CreateTempFile

func (c *OSCommand) CreateTempFile(filename, content string) (string, error)

CreateTempFile writes a string to a new temp file and returns the file's name

func (*OSCommand) EditFile

func (c *OSCommand) EditFile(filename string) (*exec.Cmd, error)

EditFile opens a file in a subprocess using whatever editor is available, falling back to core.editor, VISUAL, EDITOR, then vi

func (*OSCommand) ExecutableFromString

func (c *OSCommand) ExecutableFromString(commandStr string) *exec.Cmd

ExecutableFromString takes a string like `docker ps -a` and returns an executable command for it

func (*OSCommand) ExecutableFromStringContext added in v0.20.0

func (c *OSCommand) ExecutableFromStringContext(ctx context.Context, commandStr string) *exec.Cmd

Same as ExecutableFromString but cancellable via a context

func (*OSCommand) FileExists

func (c *OSCommand) FileExists(path string) (bool, error)

FileExists checks whether a file exists at the specified path

func (*OSCommand) FileType

func (c *OSCommand) FileType(path string) string

FileType tells us if the file is a file, directory or other

func (*OSCommand) GetLazydockerPath

func (c *OSCommand) GetLazydockerPath() string

GetLazydockerPath returns the path of the currently executed file

func (*OSCommand) Kill

func (c *OSCommand) Kill(cmd *exec.Cmd) error

Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself.

func (*OSCommand) NewCmd added in v0.23.0

func (c *OSCommand) NewCmd(cmdName string, commandArgs ...string) *exec.Cmd

func (*OSCommand) NewCommandStringWithShell added in v0.21.0

func (c *OSCommand) NewCommandStringWithShell(commandStr string) string

func (*OSCommand) OpenFile

func (c *OSCommand) OpenFile(filename string) error

OpenFile opens a file with the given

func (c *OSCommand) OpenLink(link string) error

OpenLink opens a file with the given

func (*OSCommand) PipeCommands

func (c *OSCommand) PipeCommands(commandStrings ...string) error

PipeCommands runs a heap of commands and pipes their inputs/outputs together like A | B | C

func (*OSCommand) PrepareForChildren

func (c *OSCommand) PrepareForChildren(cmd *exec.Cmd)

PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a subprocess, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process.

func (*OSCommand) Quote

func (c *OSCommand) Quote(message string) string

Quote wraps a message in platform-specific quotation marks

func (*OSCommand) Remove

func (c *OSCommand) Remove(filename string) error

Remove removes a file or directory at the specified path

func (*OSCommand) RunCommand

func (c *OSCommand) RunCommand(command string) error

RunCommand runs a command and just returns the error

func (*OSCommand) RunCommandWithOutput

func (c *OSCommand) RunCommandWithOutput(command string) (string, error)

RunCommandWithOutput wrapper around commands returning their output and error

func (*OSCommand) RunCommandWithOutputContext added in v0.20.0

func (c *OSCommand) RunCommandWithOutputContext(ctx context.Context, command string) (string, error)

RunCommandWithOutput wrapper around commands returning their output and error

func (*OSCommand) RunCustomCommand

func (c *OSCommand) RunCustomCommand(command string) *exec.Cmd

RunCustomCommand returns the pointer to a custom command

func (*OSCommand) RunExecutable

func (c *OSCommand) RunExecutable(cmd *exec.Cmd) error

RunExecutable runs an executable file and returns an error if there was one

func (*OSCommand) RunExecutableWithOutput

func (c *OSCommand) RunExecutableWithOutput(cmd *exec.Cmd) (string, error)

RunExecutableWithOutput runs an executable file and returns its output

func (*OSCommand) RunPreparedCommand

func (c *OSCommand) RunPreparedCommand(cmd *exec.Cmd) error

RunPreparedCommand takes a pointer to an exec.Cmd and runs it this is useful if you need to give your command some environment variables before running it

func (*OSCommand) SetCommand

func (c *OSCommand) SetCommand(cmd func(string, ...string) *exec.Cmd)

SetCommand sets the command function used by the struct. To be used for testing only

func (*OSCommand) Unquote

func (c *OSCommand) Unquote(message string) string

Unquote removes wrapping quotations marks if they are present this is needed for removing quotes from staged filenames with spaces

type Platform

type Platform struct {
	// contains filtered or unexported fields
}

Platform stores the os state

type Project added in v0.20.0

type Project struct {
	Name string
}

type RecordedStats

type RecordedStats struct {
	ClientStats  ContainerStats
	DerivedStats DerivedStats
	RecordedAt   time.Time
}

RecordedStats contains both the container stats we've received from docker, and our own derived stats from those container stats. When configuring a graph, you're basically specifying the path of a value in this struct

type Service

type Service struct {
	Name          string
	ID            string
	OSCommand     *OSCommand
	Log           *logrus.Entry
	Container     *Container
	DockerCommand LimitedDockerCommand
}

Service : A docker Service

func (*Service) Attach

func (s *Service) Attach() (*exec.Cmd, error)

Attach attaches to the service

func (*Service) Remove

func (s *Service) Remove(options dockerTypes.ContainerRemoveOptions) error

Remove removes the service's containers

func (*Service) RenderTop

func (s *Service) RenderTop(ctx context.Context) (string, error)

RenderTop renders the process list of the service

func (*Service) Restart

func (s *Service) Restart() error

Restart restarts the service

func (*Service) Start added in v0.18.1

func (s *Service) Start() error

Restart starts the service

func (*Service) Stop

func (s *Service) Stop() error

Stop stops the service's containers

func (*Service) Up added in v0.20.0

func (s *Service) Up() error

Up up's the service

func (*Service) ViewLogs

func (s *Service) ViewLogs() (*exec.Cmd, error)

ViewLogs attaches to a subprocess viewing the service's logs

type Volume

type Volume struct {
	Name          string
	Volume        *dockerTypes.Volume
	Client        *client.Client
	OSCommand     *OSCommand
	Log           *logrus.Entry
	DockerCommand LimitedDockerCommand
}

Volume : A docker Volume

func (*Volume) Remove

func (v *Volume) Remove(force bool) error

Remove removes the volume

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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