Documentation
¶
Overview ¶
Package iotmakerdockerbuilder
English:
Golang and Docker in a simple way ¶
Documentation in progress ¶
This package facilitates the use of docker containers by golang code, enabling the creation of unit tests involving containers in linear and chaos scenarios, enabling the development of microservices and failure simulation.
Português: Golang e Docker de forma simples.
Este pacote facilita o uso de containers docker por código golang, possibilitando a criação de testes unitários envolvendo containers em cenários linear e de caos possibilitando o desenvolvimento de microsserviços e simulação de falha.
Transforme teste unitário em cenário de caos ¶
A criação de microsserviços requerem uma nova abordagem de testes, onde nem sempre, os testes unitários são fáceis de fazer.
Imagine um microsserviço simples, uma simples comunicação gRPC entre duas instâncias do mesmo serviço.
Como fazer um simples teste para saber se eles se conectam?
Este módulo tem a finalidade de resolver este problema, adicionando ao código golang de teste a capacidade de criar vários elementos docker de forma muito rápida no meio dos testes unitários.
Imagine poder criar uma rede docker, apontar para uma pasta contendo o projeto e subir quantos containers quiser, com a capacidade de gerar relatórios e simular falhas de comunicação aleatórias com algumas poucas linhas de código.
Criando uma rede docker ¶
A rede é opcional e permite controlar melhor o endereço IP de cada instância do serviço em teste, além de permitir isolar a comunicação entre eles.
Exemplo de código para criação de rede
package code
import (
dockerBuilder "github.com/helmutkemper/iotmaker.docker.builder"
dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network"
"log"
"testing"
)
func TestCode(t *testing.T) {
var err error
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
}
Uma vez criada a rede, cada instância do serviço adicionada ao docker ganhará um endereço IP seguindo a ordem de criação da instância.
Por exemplo, a primeira instância criada irá para o endereço `10.0.0.2` e a seguinte irá para o endereço `10.0.0.3`, e assim por diante.
Uma vez criada a rede, basta usar o comando `container.SetNetworkDocker(&netDocker)` e a mesma será ligada a nova rede de forma transperente.
Caso queira trocar o IP de uma instância, para simular uma troca de IP aleatória, basta rodar o comando `container.NetworkChangeIp()` e a instância terá o seu IP trocado para o próximo IP da lista.
Subindo um container baseado em uma imagem pública ¶
Imagine que o seu projeto necessita de um container `nats:latest` para rodar, logo temos o código golang:
package code
import (
dockerBuilder "github.com/helmutkemper/iotmaker.docker.builder"
dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network"
"log"
"testing"
)
func TestCode(t *testing.T) {
var err error
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Create a container
var container = dockerBuilder.ContainerBuilder{}
// Set image name for docker pull
container.SetImageName("nats:latest")
// Expose nats port [optional]
container.AddPortToExpose("4222")
// Link container and network [optional] (next ip address is 10.0.0.2)
container.SetNetworkDocker(&netDocker)
// Set a container name.
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
container.SetContainerName("container_delete_nats_after_test")
// Set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)
// Inialize the container object
err = container.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Image nats:latest pull command
err = container.ImagePull()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Container build and start from image nats:latest
// Waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container
// output to proceed
err = container.ContainerBuildFromImage()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
}
Como padrão, todos os parâmetros são adicionados primeiro e em seguida o objeto é inicializado, com o comando `container.Init()`.
Como este exemplo usa uma imagem pública, o primeiro comando é o comando `container.ImagePull()`, para que a imagem definida em `container.SetImageName("nats:latest")` seja baixada.
Logo em seguida, o comando `container.ContainerBuildFromImage()` gera um container de nome `container.SetContainerName("container_delete_nats_after_test")` e deixa o código parado até a saída padrão do container exibir o texto [opcional] `container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)`.
Subindo um container baseado em uma pasta local com acesso a repositório privado ¶
Esta configuração permite transformar uma pasta local em uma imagem, de forma simples, mesmo se o projeto necessitar acessar um repositório git privado, protegido com chave `ssh`
package code
import (
dockerBuilder "github.com/helmutkemper/iotmaker.docker.builder"
dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network"
"log"
"testing"
)
func TestCode(t *testing.T) {
var err error
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Create a container
container = dockerBuilder.ContainerBuilder{}
// Adds an expiration date, in order to prevent the creation of the same image multiple times in a row during the
// same test [optional]
container.SetImageExpirationTime(5 * time.Minute)
// Link container and network [optional] (next ip address is 10.0.0.2)
container.SetNetworkDocker(netDocker)
// Print the container's standard output to golang's standard output
container.SetPrintBuildOnStrOut()
// Enables the use of the "cache:latest" image [optional].
// To prevent an image from downloading the same dependency multiple times for each test, you can create an image
// named "cache:latest" and use this image as the basis for the test images.
container.SetCacheEnable(true)
// Determines the name of the image to be created during the test.
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
container.SetImageName("data_rand_pod_image:latest")
// Determina o nome do container. Lembre-se que ele deve ser único.
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
container.SetContainerName("delete_data_rand_pod_container")
// Determines the path of the folder where your project is located.
container.SetBuildFolderPath("./project_folder")
// Enables the creation of the "Dockerfile-oitmaker" file automatically, as long as the "main.go" and "go.mod" files
// are in the project root.
container.MakeDefaultDockerfileForMe()
// Defines a list of private repositories used in the project. Separate values by a comma.
container.SetGitPathPrivateRepository("github.com/helmutkemper")
// Copy the "~/.ssh/id_rsa.pub" and "~/.ssh/known_hosts" credentials into the container.
// The automatic creation of the container is done in two steps and the credentials are erased when the first image
// is erased.
err = container.SetPrivateRepositoryAutoConfig()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("data rand container started", 10*time.Second)
// It links a folder/file contained on the computer where the test runs and a folder/file contained in the container
// [optional]
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./memory/container", "/containerMemory")
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// It links a folder/file contained on the computer where the test runs and a folder/file contained in the container
// [optional]
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./memory/config", "/config")
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Inialize the container object
err = container.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Generates an image from a project folder
_, err = container.ImageBuildFromFolder()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Container build and start from image nats:latest
// Waits for the text "data rand container started" to appear in the standard container
// output to proceed
err = container.ContainerBuildFromImage()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
}
Os comandos básicos para a criação de imagem são `container.SetBuildFolderPath("./project_folder")`, para definir a pasta local, onde o projeto se encontra, e `container.ImageBuildFromFolder()`, encarregado de transformar o conteúdo da pasta em imagem.
Caso haja a necessidade de compartilhar conteúdo local com o container, o comando `container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./memory/config", "/config")` fará a ligação entre pastas e arquivos no computador local com o container.
Criando uma imagem de cache ¶
Em muitos casos de teste, criar uma imagem de cache ajuda a baixar menos dependência na hora de criar as imagens e deixa o teste mais rápido.
A forma de fazer isto é bem simples, basta criar uma imagem de nome `cache:latest`.
package code
import (
dockerBuilder "github.com/helmutkemper/iotmaker.docker.builder"
"log"
"testing"
)
func TestCache(t *testing.T) {
var err error
// Create a container
container = dockerBuilder.ContainerBuilder{}
// Adds an expiration date, in order to prevent the creation of the same image multiple times in a row during the
// same test [optional]
container.SetImageExpirationTime(365 * 24 * time.Hour)
// Print the container's standard output to golang's standard output
container.SetPrintBuildOnStrOut()
// Determines the name of the image to be created during the test.
// Use the term "delete" to enable the function "dockerBuilder.GarbageCollector()", which will search for and remove
// all docker elements with the term "delete" contained in the name. For example, network, image, container and
// volumes.
container.SetImageName("cache:latest")
// Determines the path of the folder where your project is located.
container.SetBuildFolderPath("./cache_folder")
// Inialize the container object
err = container.Init()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
// Generates an image from a project folder
_, err = container.ImageBuildFromFolder()
if err != nil {
log.Printf("error: %v", err)
t.Fail()
}
}
A criação da cache é usada em paralelo com os comandos `container.SetCacheEnable(true)` e `container.MakeDefaultDockerfileForMe()`, onde eles vão usar como base a imagem `cache:latest` e a imagem de cache será criada em cima da imagem `golang:1.17-alpine`.
Caso você não tenha prática em criar imagens, use o exemplo abaixo, onde `RUN go get ...` são as dependências usadas por você.
FROM golang:1.17-alpine as builder RUN mkdir -p /root/.ssh/ && \ apk update && \ apk add openssh && \ apk add --no-cache build-base && \ apk add --no-cache alpine-sdk && \ rm -rf /var/cache/apk/* ARG CGO_ENABLED=0 RUN go get ... RUN go get ... RUN go get ... RUN go get ... RUN go get ...
Usando repositórios privados ¶
Caso seus projetos necessitem usar repositórios privados, o comando `container.MakeDefaultDockerfileForMe()` sempre faz a criação da imagem em duas etapas e as credencias de segurança ficam na primeira etapa, descartada ao final do processo, evitando uma cópia das suas credencias de segurança em uma imagem pública.
O comando `container.SetPrivateRepositoryAutoConfig()` copia as suas credenciais de segurança padrão `~/.ssh/id_rsa.pub`, `~/.ssh/known_hosts` e `~/.gitconfig`
Em seguida, devemos informar os repositórios privados com o comando `container.SetGitPathPrivateRepository("github.com/user1,github.com/user2")`.
Caso você tenha problema em baixar repositórios privados, adicione o cógido abaixo ao arquivo `~/.gitconfig`
[core] autocrlf = input [url "ssh://git@github.com/"] insteadOf = https://github.com/ [url "git://"] insteadOf = https://
Para quem não tem prática em processo de build em duas etapas, na primeira etapa é criada uma imagem grande com todas as depend6encias e programas necessários para o processode construção do código. Porém, ao final do processo, apenas o binário gerado na primeira etapa é copiado para uma imagem nova, o que deixa a imagem final pequena.
Index ¶
- Constants
- func ConfigChaosScene(sceneName string, ...)
- func GarbageCollector(names ...string)
- func ImageMakeCache(projectPath, cacheName string, expirationDate time.Duration) (err error)
- func ImageMakeCacheWithDefaultName(projectPath string, expirationDate time.Duration) (err error)
- type BlkioStatEntry
- type BlkioStats
- type CPUStats
- type CPUUsage
- type ContainerBuilder
- func (e *ContainerBuilder) AddFailMatchFlag(value string)
- func (e *ContainerBuilder) AddFailMatchFlagToFileLog(value, logDirectoryPath string) (err error)
- func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
- func (e *ContainerBuilder) AddFilterToFail(match, filter, search, replace string)
- func (e *ContainerBuilder) AddFilterToLog(label, match, filter string)
- func (e *ContainerBuilder) AddFilterToLogWithReplace(label, match, filter, search, replace string)
- func (e *ContainerBuilder) AddFilterToRestartContainer(match, filter, search, replace string)
- func (e *ContainerBuilder) AddFilterToStartChaos(match, filter, search, replace string)
- func (e *ContainerBuilder) AddFilterToSuccess(match, filter, search, replace string)
- func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)
- func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
- func (e *ContainerBuilder) AddPortToDockerfileExpose(value string)
- func (e *ContainerBuilder) AddPortToExpose(value string)
- func (e *ContainerBuilder) AddRestartMatchFlag(value string)
- func (e *ContainerBuilder) AddRestartMatchFlagToFileLog(value, logDirectoryPath string) (err error)
- func (e *ContainerBuilder) AddStartChaosMatchFlag(value string)
- func (e *ContainerBuilder) AddStartChaosMatchFlagToFileLog(value, logDirectoryPath string) (err error)
- func (e *ContainerBuilder) AddSuccessMatchFlag(value string)
- func (e *ContainerBuilder) ContainerBuildAndStartFromImage() (err error)
- func (e *ContainerBuilder) ContainerBuildWithoutStartingItFromImage() (err error)
- func (e *ContainerBuilder) ContainerCopyFrom(containerPathList []string, hostPathList []string) (statsList []types.ContainerPathStat, err error)
- func (e *ContainerBuilder) ContainerCopyTo(hostPathList []string, containerPathList []string) (err error)
- func (e *ContainerBuilder) ContainerExecCommand(commands []string) (exitCode int, runing bool, stdOutput []byte, stdError []byte, err error)
- func (e *ContainerBuilder) ContainerFindIdByName(name string) (id string, err error)
- func (e *ContainerBuilder) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)
- func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)
- func (e *ContainerBuilder) ContainerPause() (err error)
- func (e *ContainerBuilder) ContainerRemove(removeVolumes bool) (err error)
- func (e *ContainerBuilder) ContainerRestart() (err error)
- func (e *ContainerBuilder) ContainerRestartWithTimeout(timeout time.Duration) (err error)
- func (e *ContainerBuilder) ContainerSetDisabePauseOnChaosScene(value bool)
- func (e *ContainerBuilder) ContainerSetDisabeStopOnChaosScene(value bool)
- func (e *ContainerBuilder) ContainerStart() (err error)
- func (e *ContainerBuilder) ContainerStartAfterBuild() (err error)
- func (e *ContainerBuilder) ContainerStatisticsOneShot() (stats types.Stats, err error)
- func (e *ContainerBuilder) ContainerStop() (err error)
- func (e *ContainerBuilder) ContainerUnpause() (err error)
- func (e *ContainerBuilder) EnableChaosScene(enable bool)
- func (e *ContainerBuilder) FindCurrentIPV4Address() (IP string, err error)
- func (e *ContainerBuilder) FindTextInsideContainerLog(value string) (contains bool, err error)
- func (e *ContainerBuilder) GetBuildFolderPath() (buildPath string)
- func (e *ContainerBuilder) GetChannelEvent() (channel *chan iotmakerdocker.ContainerPullStatusSendToChannel)
- func (e *ContainerBuilder) GetChannelOnContainerInspect() (channel *chan bool)
- func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)
- func (e *ContainerBuilder) GetChaosEvent() (eventChannel chan Event)
- func (e *ContainerBuilder) GetContainerID() (ID string)
- func (e *ContainerBuilder) GetContainerInfo() (info types.Info, err error)
- func (e ContainerBuilder) GetContainerIsStarted() (started bool)
- func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
- func (e *ContainerBuilder) GetContainerName() (containerName string)
- func (e *ContainerBuilder) GetFailFlag() (fail bool)
- func (e *ContainerBuilder) GetGitCloneToBuild() (url string)
- func (e *ContainerBuilder) GetIPV4Address() (IP string)
- func (e *ContainerBuilder) GetIdByContainerName() (err error)
- func (e *ContainerBuilder) GetImageArchitecture() (architecture string)
- func (e *ContainerBuilder) GetImageAuthor() (author string)
- func (e *ContainerBuilder) GetImageCacheName() (name string)
- func (e *ContainerBuilder) GetImageComment() (comment string)
- func (e *ContainerBuilder) GetImageContainer() (container string)
- func (e *ContainerBuilder) GetImageCreated() (created time.Time)
- func (e *ContainerBuilder) GetImageExpirationTime() (expiration time.Duration)
- func (e *ContainerBuilder) GetImageID() (ID string)
- func (e *ContainerBuilder) GetImageName() (name string)
- func (e *ContainerBuilder) GetImageOs() (os string)
- func (e *ContainerBuilder) GetImageOsVersion() (osVersion string)
- func (e *ContainerBuilder) GetImageParent() (parent string)
- func (e *ContainerBuilder) GetImageRepoDigests() (repoDigests []string)
- func (e *ContainerBuilder) GetImageRepoTags() (repoTags []string)
- func (e *ContainerBuilder) GetImageSize() (size int64)
- func (e *ContainerBuilder) GetImageVariant() (variant string)
- func (e *ContainerBuilder) GetImageVirtualSize() (virtualSize int64)
- func (e *ContainerBuilder) GetInitialized() (initialized bool)
- func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)
- func (e *ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog(value string) (text string, contains bool, err error)
- func (e *ContainerBuilder) GetLastLogs() (logs string)
- func (e *ContainerBuilder) GetMetadata() (metadata map[string]interface{})
- func (e *ContainerBuilder) GetNetworkGatewayIPV4() (IPV4 string)
- func (e *ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName(networkName string) (IPV4 string, err error)
- func (e *ContainerBuilder) GetNetworkIPV4() (IPV4 string)
- func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)
- func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *ContainerBuilder) GetProblem() (problem string)
- func (e *ContainerBuilder) GetSuccessFlag() (success bool)
- func (e *ContainerBuilder) ImageBuildFromFolder() (inspect types.ImageInspect, err error)
- func (e *ContainerBuilder) ImageBuildFromServer() (inspect types.ImageInspect, err error)
- func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)
- func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)
- func (e *ContainerBuilder) ImageInspect() (inspect types.ImageInspect, err error)
- func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)
- func (e *ContainerBuilder) ImageListExposedVolumes() (list []string, err error)
- func (e *ContainerBuilder) ImagePull() (err error)
- func (e *ContainerBuilder) ImageRemove() (err error)
- func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)
- func (e *ContainerBuilder) Init() (err error)
- func (e *ContainerBuilder) MakeDefaultDockerfileForMe()
- func (e *ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras()
- func (e *ContainerBuilder) NetworkChangeIp() (err error)
- func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
- func (e *ContainerBuilder) SetBuildFolderPath(value string)
- func (e *ContainerBuilder) SetCacheEnable(value bool)
- func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)
- func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)
- func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
- func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)
- func (e *ContainerBuilder) SetContainerName(value string)
- func (e *ContainerBuilder) SetContainerRestartPolicyAlways()
- func (e *ContainerBuilder) SetContainerRestartPolicyNo()
- func (e *ContainerBuilder) SetContainerRestartPolicyOnFailure()
- func (e *ContainerBuilder) SetContainerRestartPolicyUnlessStopped()
- func (e *ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint(values []string)
- func (e *ContainerBuilder) SetCsvFileReader(value bool)
- func (e *ContainerBuilder) SetCsvFileRowSeparator(value string)
- func (e *ContainerBuilder) SetCsvFileRowsToPrint(value int64)
- func (e *ContainerBuilder) SetCsvFileValueSeparator(value string)
- func (e *ContainerBuilder) SetCsvLogPath(path string, removeOldFile bool)
- func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)
- func (e *ContainerBuilder) SetEnvironmentVar(value []string)
- func (e *ContainerBuilder) SetGitCloneToBuild(url string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)
- func (e *ContainerBuilder) SetGitConfigFile(value string)
- func (e *ContainerBuilder) SetGitPathPrivateRepository(value string)
- func (e *ContainerBuilder) SetGitSshPassword(password string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUPeriod(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUQuota(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUSetCPUs(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUSetMems(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUShares(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)
- func (e *ContainerBuilder) SetImageBuildOptionsExtraHosts(values []string)
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationDefault()
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()
- func (e *ContainerBuilder) SetImageBuildOptionsMemory(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsNoCache()
- func (e *ContainerBuilder) SetImageBuildOptionsPlatform(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)
- func (e *ContainerBuilder) SetImageBuildOptionsSquash(value bool)
- func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)
- func (e *ContainerBuilder) SetImageCacheName(name string)
- func (e *ContainerBuilder) SetImageExpirationTime(expiration time.Duration)
- func (e *ContainerBuilder) SetImageName(value string)
- func (e *ContainerBuilder) SetInspectInterval(value time.Duration)
- func (e *ContainerBuilder) SetMetadata(metadata map[string]interface{})
- func (e *ContainerBuilder) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *ContainerBuilder) SetOnBuild(onBuild []string)
- func (e *ContainerBuilder) SetOpenAllContainersPorts()
- func (e *ContainerBuilder) SetPrintBuildOnStrOut()
- func (e *ContainerBuilder) SetPrivateRepositoryAutoConfig() (err error)
- func (e *ContainerBuilder) SetRestartProbability(restartProbability, restartChangeIpProbability float64, limit int)
- func (e *ContainerBuilder) SetSceneNameOnChaosScene(name string)
- func (e *ContainerBuilder) SetSshIdRsaFile(value string)
- func (e *ContainerBuilder) SetSshKnownHostsFile(value string)
- func (e *ContainerBuilder) SetTimeBeforeStartChaosInThisContainerOnChaosScene(min, max time.Duration)
- func (e *ContainerBuilder) SetTimeOnContainerPausedStateOnChaosScene(min, max time.Duration)
- func (e *ContainerBuilder) SetTimeOnContainerUnpausedStateOnChaosScene(min, max time.Duration)
- func (e *ContainerBuilder) SetTimeToRestartThisContainerAfterStopEventOnChaosScene(min, max time.Duration)
- func (e *ContainerBuilder) SetTimeToStartChaosOnChaosScene(min, max time.Duration)
- func (e *ContainerBuilder) SetWaitString(value string)
- func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)
- func (e *ContainerBuilder) SizeToString(value int64) string
- func (e *ContainerBuilder) StartMonitor()
- func (e *ContainerBuilder) StopMonitor() (err error)
- func (e ContainerBuilder) TestDockerInstall() (err error)
- func (e *ContainerBuilder) WaitForTextInContainerLog(value string) (dockerLogs string, err error)
- func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)
- type DockerfileAuto
- type Event
- type HealthConfig
- type LogFilter
- type MemoryStats
- type NameAndId
- type NetworkChaos
- func (e *NetworkChaos) Init() (err error)
- func (e *NetworkChaos) SetContainerName(value string)
- func (e *NetworkChaos) SetFatherContainer(fatherContainer *ContainerBuilder)
- func (e *NetworkChaos) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *NetworkChaos) SetPorts(listenPort, outputPort int, invert bool)
- type PidsStats
- type Restart
- type Stats
- type StorageStats
- type TestContainerLog
- type Theater
- func (e *Theater) ConfigScene(sceneName string, ...)
- func (e *Theater) Init()
- func (e *Theater) SetContainerPaused(sceneName string) (doNotPauseContainer bool)
- func (e *Theater) SetContainerStopped(sceneName string) (IsOnTheEdge bool)
- func (e *Theater) SetContainerUnPaused(sceneName string)
- func (e *Theater) SetContainerUnStopped(sceneName string)
- type ThrottlingData
- type Timers
Examples ¶
- ConfigChaosScene
- ContainerBuilder.AddFailMatchFlag
- ContainerBuilder.AddFailMatchFlagToFileLog
- ContainerBuilder.AddFileOrFolderToLinkBetweenConputerHostAndContainer
- ContainerBuilder.AddFilterToFail
- ContainerBuilder.AddFilterToLog
- ContainerBuilder.AddFilterToRestartContainer
- ContainerBuilder.AddFilterToStartChaos
- ContainerBuilder.AddPortToChange
- ContainerBuilder.AddPortToExpose
- ContainerBuilder.ContainerBuildAndStartFromImage
- ContainerBuilder.ContainerCopyTo
- ContainerBuilder.FindCurrentIPV4Address
- ContainerBuilder.ImageBuildFromFolder
- ContainerBuilder.ImageListExposedPorts
- ContainerBuilder.ImageListExposedVolumes
- ContainerBuilder.ImagePull
- ContainerBuilder.NetworkChangeIp
- ContainerBuilder.SetCsvFileRowsToPrint
- ContainerBuilder.SetCsvLogPath
- ContainerBuilder.SetEnvironmentVar
- ContainerBuilder.SetGitCloneToBuild
- ContainerBuilder.SetNetworkDocker
- NetworkChaos.Init
Constants ¶
const ( // KKiloByte // // English: 1024 Bytes multiplier // // Example: // 5 * KKiloByte = 5 KBytes // // Português: multiplicador de 1024 Bytes // // Exemplo: // 5 * KKiloByte = 5 KBytes KKiloByte = 1024 // KMegaByte // // English: 1024 KBytes multiplier // // Example: // 5 * KMegaByte = 5 MBytes // // Português: multiplicador de 1024 KBytes // // Exemplo: // 5 * KMegaByte = 5 MBytes KMegaByte = 1024 * 1024 // KGigaByte // // English: 1024 MBytes multiplier // // Example: // 5 * KGigaByte = 5 GBytes // // Português: multiplicador de 1024 MBytes // // Exemplo: // 5 * KGigaByte = 5 GBytes KGigaByte = 1024 * 1024 * 1024 // KTeraByte ( // // English: 1024 GBytes multiplier // // Example: // 5 * KTeraByte = 5 TBytes // // Português: multiplicador de 1024 GBytes // // Exemplo: // 5 * KTeraByte = 5 TBytes KTeraByte = 1024 * 1024 * 1024 * 1024 // KLogColumnAll // // English: Enable all values to log KLogColumnAll = 0x7FFFFFFFFFFFFFF // KLogColumnReadingTime // // English: Reading time KLogColumnReadingTime = 0b0000000000000000000000000000000000000000000000000000000000000001 KReadingTimeComa = 0b0111111111111111111111111111111111111111111111111111111111111110 KFilterLog = 0b0000000000000000000000000000000000000000000000000000000000000010 KLogColumnFilterLogComa = 0b0111111111111111111111111111111111111111111111111111111111111100 // KLogColumnCurrentNumberOfOidsInTheCGroup // // English: Linux specific stats, not populated on Windows. Current is the number of pids in the cgroup KLogColumnCurrentNumberOfOidsInTheCGroup = 0b0000000000000000000000000000000000000000000000000000000000000100 KCurrentNumberOfOidsInTheCGroupComa = 0b0111111111111111111111111111111111111111111111111111111111111000 // KLogColumnLimitOnTheNumberOfPidsInTheCGroup // // English: Linux specific stats, not populated on Windows. Limit is the hard limit on the number of pids in the cgroup. A "Limit" of 0 means that there is no limit. KLogColumnLimitOnTheNumberOfPidsInTheCGroup = 0b0000000000000000000000000000000000000000000000000000000000001000 KLimitOnTheNumberOfPidsInTheCGroupComa = 0b0111111111111111111111111111111111111111111111111111111111110000 // KLogColumnTotalCPUTimeConsumed // // English: Total CPU time consumed. (Units: nanoseconds on Linux, Units: 100's of nanoseconds on Windows) KLogColumnTotalCPUTimeConsumed = 0b0000000000000000000000000000000000000000000000000000000000010000 KTotalCPUTimeConsumedComa = 0b0111111111111111111111111111111111111111111111111111111111100000 // KLogColumnTotalCPUTimeConsumedPerCore // // English: Total CPU time consumed. (Units: nanoseconds on Linux, Units: 100's of nanoseconds on Windows) KLogColumnTotalCPUTimeConsumedPerCore = 0b0000000000000000000000000000000000000000000000000000000000100000 KTotalCPUTimeConsumedPerCoreComa = 0b0111111111111111111111111111111111111111111111111111111111000000 // KLogColumnTimeSpentByTasksOfTheCGroupInKernelMode // // English: Time spent by tasks of the cgroup in kernel mode (Units: nanoseconds on Linux). Time spent by all container processes in kernel mode (Units: 100's of nanoseconds on Windows.Not populated for Hyper-V Containers.) KLogColumnTimeSpentByTasksOfTheCGroupInKernelMode = 0b0000000000000000000000000000000000000000000000000000000001000000 KTimeSpentByTasksOfTheCGroupInKernelModeComa = 0b0111111111111111111111111111111111111111111111111111111110000000 // KLogColumnTimeSpentByTasksOfTheCGroupInUserMode // // English: Time spent by tasks of the cgroup in user mode (Units: nanoseconds on Linux). Time spent by all container processes in user mode (Units: 100's of nanoseconds on Windows. Not populated for Hyper-V Containers) KLogColumnTimeSpentByTasksOfTheCGroupInUserMode = 0b0000000000000000000000000000000000000000000000000000000010000000 KTimeSpentByTasksOfTheCGroupInUserModeComa = 0b0111111111111111111111111111111111111111111111111111111100000000 // KLogColumnSystemUsage // // English: System Usage. Linux only. KLogColumnSystemUsage = 0b0000000000000000000000000000000000000000000000000000000100000000 KSystemUsageComa = 0b0111111111111111111111111111111111111111111111111111111000000000 // KOnlineCPUs // // English: Online CPUs. Linux only. KLogColumnOnlineCPUs = 0b0000000000000000000000000000000000000000000000000000001000000000 KOnlineCPUsComa = 0b0111111111111111111111111111111111111111111111111111110000000000 // KLogColumnNumberOfPeriodsWithThrottlingActive // // English: Throttling Data. Linux only. Number of periods with throttling active. KLogColumnNumberOfPeriodsWithThrottlingActive = 0b0000000000000000000000000000000000000000000000000000010000000000 KNumberOfPeriodsWithThrottlingActiveComa = 0b0111111111111111111111111111111111111111111111111111100000000000 // KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit // // English: Throttling Data. Linux only. Number of periods when the container hits its throttling limit. KLogColumnNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit = 0b0000000000000000000000000000000000000000000000000000100000000000 KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitComa = 0b0111111111111111111111111111111111111111111111111111000000000000 // KAggregateTimeTheContainerWasThrottledForInNanoseconds // // English: Throttling Data. Linux only. Aggregate time the container was throttled for in nanoseconds. KLogColumnAggregateTimeTheContainerWasThrottledForInNanoseconds = 0b0000000000000000000000000000000000000000000000000001000000000000 KAggregateTimeTheContainerWasThrottledForInNanosecondsComa = 0b0111111111111111111111111111111111111111111111111110000000000000 // KLogColumnTotalPreCPUTimeConsumed // // English: Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows. KLogColumnTotalPreCPUTimeConsumed = 0b0000000000000000000000000000000000000000000000000010000000000000 KTotalPreCPUTimeConsumedComa = 0b0111111111111111111111111111111111111111111111111100000000000000 // KLogColumnTotalPreCPUTimeConsumedPerCore // // English: Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows. KLogColumnTotalPreCPUTimeConsumedPerCore = 0b0000000000000000000000000000000000000000000000000100000000000000 KTotalPreCPUTimeConsumedPerCoreComa = 0b0111111111111111111111111111111111111111111111111000000000000000 // KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInKernelMode // // English: Time spent by tasks of the cgroup in kernel mode (Units: nanoseconds on Linux) - Time spent by all container processes in kernel mode (Units: 100's of nanoseconds on Windows - Not populated for Hyper-V Containers.) KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInKernelMode = 0b0000000000000000000000000000000000000000000000001000000000000000 KTimeSpentByPreCPUTasksOfTheCGroupInKernelModeComa = 0b0111111111111111111111111111111111111111111111110000000000000000 // KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInUserMode // // English: Time spent by tasks of the cgroup in user mode (Units: nanoseconds on Linux) - Time spent by all container processes in user mode (Units: 100's of nanoseconds on Windows. Not populated for Hyper-V Containers) KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInUserMode = 0b0000000000000000000000000000000000000000000000010000000000000000 KTimeSpentByPreCPUTasksOfTheCGroupInUserModeComa = 0b0111111111111111111111111111111111111111111111100000000000000000 // KLogColumnPreCPUSystemUsage // // English: System Usage. (Linux only) KLogColumnPreCPUSystemUsage = 0b0000000000000000000000000000000000000000000000100000000000000000 KPreCPUSystemUsageComa = 0b0111111111111111111111111111111111111111111111000000000000000000 // KLogColumnOnlinePreCPUs // // English: Online CPUs. (Linux only) KLogColumnOnlinePreCPUs = 0b0000000000000000000000000000000000000000000001000000000000000000 KOnlinePreCPUsComa = 0b0111111111111111111111111111111111111111111110000000000000000000 // KLogColumnAggregatePreCPUTimeTheContainerWasThrottled // // English: Throttling Data. (Linux only) - Aggregate time the container was throttled for in nanoseconds KLogColumnAggregatePreCPUTimeTheContainerWasThrottled = 0b0000000000000000000000000000000000000000000010000000000000000000 KAggregatePreCPUTimeTheContainerWasThrottledComa = 0b0111111111111111111111111111111111111111111100000000000000000000 // KLogColumnNumberOfPeriodsWithPreCPUThrottlingActive // // English: Throttling Data. (Linux only) - Number of periods with throttling active KLogColumnNumberOfPeriodsWithPreCPUThrottlingActive = 0b0000000000000000000000000000000000000000000100000000000000000000 KNumberOfPeriodsWithPreCPUThrottlingActiveComa = 0b0111111111111111111111111111111111111111111000000000000000000000 // KLogColumnNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit // // English: Throttling Data. (Linux only) - Number of periods when the container hits its throttling limit. KLogColumnNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit = 0b0000000000000000000000000000000000000000001000000000000000000000 KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitComa = 0b0111111111111111111111111111111111111111110000000000000000000000 // KLogColumnCurrentResCounterUsageForMemory // // English: Current res_counter usage for memory KLogColumnCurrentResCounterUsageForMemory = 0b0000000000000000000000000000000000000000010000000000000000000000 KCurrentResCounterUsageForMemoryComa = 0b0111111111111111111111111111111111111111100000000000000000000000 // KLogColumnMaximumUsageEverRecorded // // English: Maximum usage ever recorded KLogColumnMaximumUsageEverRecorded = 0b0000000000000000000000000000000000000000100000000000000000000000 KMaximumUsageEverRecordedComa = 0b0111111111111111111111111111111111111111000000000000000000000000 // KLogColumnNumberOfTimesMemoryUsageHitsLimits // // English: Number of times memory usage hits limits KLogColumnNumberOfTimesMemoryUsageHitsLimits = 0b0000000000000000000000000000000000000001000000000000000000000000 KNumberOfTimesMemoryUsageHitsLimitsComa = 0b0111111111111111111111111111111111111110000000000000000000000000 // KLogColumnMemoryLimit // // English: Memory limit KLogColumnMemoryLimit = 0b0000000000000000000000000000000000000010000000000000000000000000 KMemoryLimitComa = 0b0111111111111111111111111111111111111100000000000000000000000000 // KLogColumnCommittedBytes // // English: Committed bytes KLogColumnCommittedBytes = 0b0000000000000000000000000000000000000100000000000000000000000000 KCommittedBytesComa = 0b0111111111111111111111111111111111111000000000000000000000000000 // KLogColumnPeakCommittedBytes // // English: Peak committed bytes KLogColumnPeakCommittedBytes = 0b0000000000000000000000000000000000001000000000000000000000000000 KPeakCommittedBytesComa = 0b0111111111111111111111111111111111110000000000000000000000000000 // KLogColumnPrivateWorkingSet // // English: Private working set KLogColumnPrivateWorkingSet = 0b0000000000000000000000000000000000010000000000000000000000000000 KPrivateWorkingSetComa = 0b0111111111111111111111111111111111100000000000000000000000000000 KLogColumnBlkioIoServiceBytesRecursive = 0b0000000000000000000000000000000000100000000000000000000000000000 KBlkioIoServiceBytesRecursiveComa = 0b0111111111111111111111111111111111000000000000000000000000000000 KLogColumnBlkioIoServicedRecursive = 0b0000000000000000000000000000000001000000000000000000000000000000 KBlkioIoServicedRecursiveComa = 0b0111111111111111111111111111111110000000000000000000000000000000 KLogColumnBlkioIoQueuedRecursive = 0b0000000000000000000000000000000010000000000000000000000000000000 KBlkioIoQueuedRecursiveComa = 0b0111111111111111111111111111111100000000000000000000000000000000 KLogColumnBlkioIoServiceTimeRecursive = 0b0000000000000000000000000000000100000000000000000000000000000000 KBlkioIoServiceTimeRecursiveComa = 0b0111111111111111111111111111111000000000000000000000000000000000 KLogColumnBlkioIoWaitTimeRecursive = 0b0000000000000000000000000000001000000000000000000000000000000000 KBlkioIoWaitTimeRecursiveComa = 0b0111111111111111111111111111110000000000000000000000000000000000 KLogColumnBlkioIoMergedRecursive = 0b0000000000000000000000000000010000000000000000000000000000000000 KBlkioIoMergedRecursiveComa = 0b0111111111111111111111111111100000000000000000000000000000000000 KLogColumnBlkioIoTimeRecursive = 0b0000000000000000000000000000100000000000000000000000000000000000 KBlkioIoTimeRecursiveComa = 0b0111111111111111111111111111000000000000000000000000000000000000 KLogColumnBlkioSectorsRecursive = 0b0000000000000000000000000001000000000000000000000000000000000000 KBlkioSectorsRecursiveComa = 0b0111111111111111111111111110000000000000000000000000000000000000 // KLogColumnMacOsLogWithAllCores // // English: Mac OS Log KLogColumnMacOsLogWithAllCores = KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | KLogColumnTotalCPUTimeConsumed | KLogColumnTotalCPUTimeConsumedPerCore | KLogColumnTimeSpentByTasksOfTheCGroupInKernelMode | KLogColumnSystemUsage | KLogColumnOnlineCPUs | KLogColumnTotalPreCPUTimeConsumed | KLogColumnTotalPreCPUTimeConsumedPerCore | KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInKernelMode | KLogColumnPreCPUSystemUsage | KLogColumnOnlinePreCPUs | KLogColumnCurrentResCounterUsageForMemory | KLogColumnMaximumUsageEverRecorded | KLogColumnMemoryLimit | KLogColumnBlkioIoServiceBytesRecursive | KLogColumnBlkioIoServicedRecursive | KLogColumnBlkioIoQueuedRecursive | KLogColumnBlkioIoServiceTimeRecursive | KLogColumnBlkioIoWaitTimeRecursive | KLogColumnBlkioIoMergedRecursive | KLogColumnBlkioIoTimeRecursive | KLogColumnBlkioSectorsRecursive // não aparece no mac // KLogColumnMacOs // // English: Mac OS Log KLogColumnMacOs = KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | KLogColumnTotalCPUTimeConsumed | KLogColumnTimeSpentByTasksOfTheCGroupInKernelMode | KLogColumnSystemUsage | KLogColumnOnlineCPUs | KLogColumnTotalPreCPUTimeConsumed | KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInKernelMode | KLogColumnPreCPUSystemUsage | KLogColumnOnlinePreCPUs | KLogColumnCurrentResCounterUsageForMemory | KLogColumnMaximumUsageEverRecorded | KLogColumnMemoryLimit | KLogColumnBlkioIoServiceBytesRecursive | KLogColumnBlkioIoServicedRecursive | KLogColumnBlkioIoQueuedRecursive | KLogColumnBlkioIoServiceTimeRecursive | KLogColumnBlkioIoWaitTimeRecursive | KLogColumnBlkioIoMergedRecursive | KLogColumnBlkioIoTimeRecursive | KLogColumnBlkioSectorsRecursive // não aparece no mac KLogColumnWindows = KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | KLogColumnTotalCPUTimeConsumed | KLogColumnTotalCPUTimeConsumedPerCore | KLogColumnTimeSpentByTasksOfTheCGroupInKernelMode | KLogColumnTimeSpentByTasksOfTheCGroupInUserMode | KLogColumnSystemUsage | KLogColumnOnlineCPUs | KLogColumnTotalPreCPUTimeConsumed | KLogColumnTotalPreCPUTimeConsumedPerCore | KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInKernelMode | KLogColumnTimeSpentByPreCPUTasksOfTheCGroupInUserMode | KLogColumnPreCPUSystemUsage | KLogColumnOnlinePreCPUs | KLogColumnCurrentResCounterUsageForMemory | KLogColumnMaximumUsageEverRecorded | KLogColumnMemoryLimit )
const ( KLogReadingTimeLabel = "Reading time" KLogReadingTimeValue = "KReadingTime" KLogReadingTimeRegexp = "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}.\\d{4,}(\\s\\+\\d{4})?\\sUTC" KLogCurrentNumberOfOidsInTheCGroupLabel = "Linux specific stats - not populated on Windows. Current is the number of pids in the cgroup" KLogCurrentNumberOfOidsInTheCGroupValue = "KCurrentNumberOfOidsInTheCGroup" KLogCurrentNumberOfOidsInTheCGroupRegexp = "\\d+" KLogLimitOnTheNumberOfPidsInTheCGroupLabel = "" /* 155-byte string literal not displayed */ KLogLimitOnTheNumberOfPidsInTheCGroupValue = "KLimitOnTheNumberOfPidsInTheCGroup" KLogLimitOnTheNumberOfPidsInTheCGroupRegexp = "\\d+" KLogTotalCPUTimeConsumedLabel = "Total CPU time consumed. (Units: nanoseconds on Linux - Units: 100's of nanoseconds on Windows)" KLogTotalCPUTimeConsumedValue = "KTotalCPUTimeConsumed" KLogTotalCPUTimeConsumedRegexp = "\\d+" KLogTotalCPUTimeConsumedPerCoreLabel = "Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows." KLogTotalCPUTimeConsumedPerCoreValue = "KTotalCPUTimeConsumedPerCore" KLogTotalCPUTimeConsumedPerCoreRegexp = "\\d+" KLogTimeSpentByTasksOfTheCGroupInKernelModeLabel = "" /* 212-byte string literal not displayed */ KLogTimeSpentByTasksOfTheCGroupInKernelModeValue = "KTimeSpentByTasksOfTheCGroupInKernelMode" KLogTimeSpentByTasksOfTheCGroupInKernelModeRegexp = "\\d+" KLogTimeSpentByTasksOfTheCGroupInUserModeLabel = "" /* 208-byte string literal not displayed */ KLogTimeSpentByTasksOfTheCGroupInUserModeValue = "KTimeSpentByTasksOfTheCGroupInUserMode" KLogTimeSpentByTasksOfTheCGroupInUserModeRegexp = "\\d+" KLogSystemUsageLabel = "System Usage. Linux only." KLogSystemUsageValue = "KSystemUsage" KLogSystemUsageRegexp = "\\d+" KLogOnlineCPUsLabel = "Online CPUs. Linux only." KLogOnlineCPUsValue = "KOnlineCPUs" KLogOnlineCPUsRegexp = "\\d+" KLogNumberOfPeriodsWithThrottlingActiveLabel = "Throttling Data. Linux only. Number of periods with throttling active." KLogNumberOfPeriodsWithThrottlingActiveValue = "KNumberOfPeriodsWithThrottlingActive" KLogNumberOfPeriodsWithThrottlingActiveRegexp = "\\d+" KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitLabel = "Throttling Data. Linux only. Number of periods when the container hits its throttling limit." KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitValue = "KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit" KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitRegexp = "\\d+" KLogAggregateTimeTheContainerWasThrottledForInNanosecondsLabel = "Throttling Data. Linux only. Aggregate time the container was throttled for in nanoseconds." KLogAggregateTimeTheContainerWasThrottledForInNanosecondsValue = "KAggregateTimeTheContainerWasThrottledForInNanoseconds" KLogAggregateTimeTheContainerWasThrottledForInNanosecondsRegexp = "\\d+" KLogTotalPreCPUTimeConsumedLabel = "Total CPU time consumed. (Units: nanoseconds on Linux. Units: 100's of nanoseconds on Windows)" KLogTotalPreCPUTimeConsumedValue = "KTotalPreCPUTimeConsumed" KLogTotalPreCPUTimeConsumedRegexp = "\\d+" KLogTotalPreCPUTimeConsumedPerCoreLabel = "Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows." KLogTotalPreCPUTimeConsumedPerCoreValue = "KTotalPreCPUTimeConsumedPerCore" KLogTotalPreCPUTimeConsumedPerCoreRegexp = "\\d+" KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeLabel = "" /* 214-byte string literal not displayed */ KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeValue = "KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode" KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeRegexp = "\\d+" KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeLabel = "" /* 208-byte string literal not displayed */ KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeValue = "KTimeSpentByPreCPUTasksOfTheCGroupInUserMode" KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeRegexp = "\\d+" KLogPreCPUSystemUsageLabel = "System Usage. (Linux only)" KLogPreCPUSystemUsageValue = "KPreCPUSystemUsage" KLogPreCPUSystemUsageRegexp = "\\d+" KLogOnlinePreCPUsLabel = "Online CPUs. (Linux only)" KLogOnlinePreCPUsValue = "KOnlinePreCPUs" KLogOnlinePreCPUsRegexp = "\\d+" KLogAggregatePreCPUTimeTheContainerWasThrottledLabel = "Throttling Data. (Linux only) - Aggregate time the container was throttled for in nanoseconds." KLogAggregatePreCPUTimeTheContainerWasThrottledValue = "KAggregatePreCPUTimeTheContainerWasThrottled" KLogAggregatePreCPUTimeTheContainerWasThrottledRegexp = "\\d+" KLogNumberOfPeriodsWithPreCPUThrottlingActiveLabel = "Throttling Data. (Linux only) - Number of periods with throttling active." KLogNumberOfPeriodsWithPreCPUThrottlingActiveValue = "KNumberOfPeriodsWithPreCPUThrottlingActive" KLogNumberOfPeriodsWithPreCPUThrottlingActiveRegexp = "\\d+" KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitLabel = "Throttling Data. (Linux only) - Number of periods when the container hits its throttling limit." KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitValue = "KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit" KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitRegexp = "\\d+" KLogCurrentResCounterUsageForMemoryLabel = "Current res_counter usage for memory" KLogCurrentResCounterUsageForMemoryValue = "KCurrentResCounterUsageForMemory" KLogCurrentResCounterUsageForMemoryRegexp = "\\d+" KLogMaximumUsageEverRecordedLabel = "Maximum usage ever recorded." KLogMaximumUsageEverRecordedValue = "KMaximumUsageEverRecorded" KLogMaximumUsageEverRecordedRegexp = "\\d+" KLogNumberOfTimesMemoryUsageHitsLimitsLabel = "Number of times memory usage hits limits." KLogNumberOfTimesMemoryUsageHitsLimitsValue = "KNumberOfTimesMemoryUsageHitsLimits" KLogNumberOfTimesMemoryUsageHitsLimitsRegexp = "\\d+" KLogMemoryLimitLabel = "Memory limit" KLogMemoryLimitValue = "KMemoryLimit" KLogMemoryLimitRegexp = "\\d+" KLogCommittedBytesLabel = "Committed bytes" KLogCommittedBytesValue = "KCommittedBytes" KLogCommittedBytesRegexp = "\\d+" KLogPeakCommittedBytesLabel = "Peak committed bytes" KLogPeakCommittedBytesValue = "KPeakCommittedBytes" KLogPeakCommittedBytesRegexp = "\\d+" KLogPrivateWorkingSetLabel = "Private working set" KLogPrivateWorkingSetValue = "KPrivateWorkingSet" KLogPrivateWorkingSetRegexp = "\\d+" )
Variables ¶
This section is empty.
Functions ¶
func ConfigChaosScene ¶ added in v0.9.41
func ConfigChaosScene( sceneName string, maxStopedContainers, maxPausedContainers, maxTotalPausedAndStoppedContainers int, )
ConfigChaosScene
English:
Add and configure a test scene prevents all containers in the scene from stopping at the same time Input: sceneName: unique name for the scene maxStopedContainers: Maximum number of stopped containers maxPausedContainers: Maximum number of paused containers maxTotalPausedAndStoppedContainers: Maximum number of containers stopped and paused at the same time
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Adiciona e configura uma cena de teste impedindo que todos os container da cena parem ao mesmo tempo Entrada: sceneName: Nome único para a cena maxStopedContainers: Quantidade máxima de containers parados maxPausedContainers: Quantidade máxima de containers pausados maxTotalPausedAndStoppedContainers: Quantidade máxima de containers parados e pausados ao mesmo tempo
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Example ¶
package main
import (
"errors"
"fmt"
dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network"
"github.com/helmutkemper/util"
"strconv"
"time"
)
func main() {
var err error
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
// English: Create a chaos scene named nats_chaos and control the number of containers stopped at the same time
//
// Português: Cria uma cena de caos de nome nats_chaos e controla a quantidade de containers parados ao mesmo tempo
ConfigChaosScene("nats_chaos", 2, 2, 2)
// English: Create a docker network controler
//
// Português: Cria um controlador de rede do docker
var netDocker = &dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
util.TraceToLog()
fmt.Printf("Error: %s\n", err.Error())
return
}
// English: Create a network named nats_network_delete_after_test, subnet 10.0.0.0/16 and gatway 10.0.0.1
//
// Português: Cria uma rede de nome nats_network_delete_after_test, subrede 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("nats_network_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
util.TraceToLog()
fmt.Printf("Error: %s\n", err.Error())
return
}
// English: Create a docker container named container_delete_nats_after_test_ + i
//
// Português: Cria um container do docker de nome container_delete_nats_after_test_ + i
for i := 0; i != 3; i += 1 {
go func(i int, err error) {
err = mountNatsContainer(i, netDocker)
if err != nil {
util.TraceToLog()
fmt.Printf("Error: %s\n", err.Error())
return
}
}(i, err)
}
// English: Let the test run for two minutes before closing it
//
// Português: Deixa o teste rodar por dois minutos antes de o encerrar
time.Sleep(2 * 60 * time.Second)
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
}
func mountNatsContainer(loop int, network *dockerNetwork.ContainerBuilderNetwork) (err error) {
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
//
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: Sets a validity time for the image, preventing the same image from being remade for a period of time.
// In some tests, the same image is created inside a loop, and adding an expiration date causes the same image to be used without having to redo the same image at each loop iteration.
//
// Português: Define uma tempo de validade para a imagem, evitando que a mesma imagem seja refeita durante um período de tempo.
// Em alguns testes, a mesma imagem é criada dentro de um laço, e adicionar uma data de validade faz a mesma imagem ser usada sem a necessidade de refazer a mesma imagem a cada interação do loop
//
// [optional/opcional]
container.SetImageExpirationTime(5 * time.Minute)
// English: Link this container to a chaos scene for greater control
//
// Português: Vincula este container a uma cena de caos para maior controle
container.SetSceneNameOnChaosScene("nats_chaos")
// English: Set image name for docker pull
//
// Português: Define o nome da imagem para o docker pull
container.SetImageName("nats:latest")
// English: set a container name
//
// Português: Define o nome do container
container.SetContainerName("container_delete_nats_after_test_" + strconv.Itoa(loop))
// English: Links the container to the previously created network
//
// Português: Vincula o container a rede criada previamente
container.SetNetworkDocker(network)
// English: Defines a wait for text, where the text must appear in the container's standard output to proceed [optional]
//
// Português: Define uma espera por texto, onde o texto deve aparecer na saída padrão do container para prosseguir [opcional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)
// English: Defines the probability of the container restarting and changing the IP address in the process.
//
// Português: Define a probalidade do container reiniciar e mudar o endereço IP no processo.
container.SetRestartProbability(0.9, 1.0, 5)
// English: Defines a time window used to start chaos testing after container initialized
//
// Português: Define uma janela de tempo usada para começar o teste de caos depois do container inicializado
container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to release container restart after the container has been initialized
//
// Português: Define uma janela de tempo usada para liberar o reinício do container depois do container ter sido inicializado
container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to pause the container
//
// Português: Define uma janela de tempo usada para pausar o container
container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to unpause the container
//
// Português: Define uma janela de tempo usada para remover a pausa do container
container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to restart the container after stopping
//
// Português: Define uma janela de tempo usada para reiniciar o container depois de parado
container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)
// English: Enable chaos test
//
// Português: Habilita o teste de caos
container.EnableChaosScene(true)
// English: Initialize the container's control object
//
// Português: Inicializa o objeto de controle do container
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// image nats:latest pull command [optional]
//err = container.ImagePull()
if err != nil {
util.TraceToLog()
panic(err)
}
// container build and start from image nats:latest
// waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container output
// to proceed
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
panic(err)
}
var IP string
IP, err = container.FindCurrentIPV4Address()
if err != nil {
util.TraceToLog()
panic(err)
}
if IP != container.GetIPV4Address() {
err = errors.New("all ip address must be a samer IP")
util.TraceToLog()
panic(err)
}
// container "container_delete_nats_after_test" running and ready for use on this code point on var IP
// all nats ports are open
// you can use AddPortToExpose("4222"), to open only ports defineds inside code;
// you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port
// 1111;
// you can use SetDoNotOpenContainersPorts() to not open containers ports
// English: Starts container monitoring at two second intervals. This functionality monitors the container's standard output and generates the log defined by the SetCsvLogPath() function.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade monitora a saída padrão do container e gera o log definido pela função SetCsvLogPath().
// StartMonitor() é usado durante o teste de caos e na geração do log de desempenho do container.
// [optional/opcional]
container.StartMonitor()
return
}
func GarbageCollector ¶
func GarbageCollector(names ...string)
GarbageCollector
English:
Removes docker elements created during unit tests, such as networks, containers, images and volumes with the term delete in the name.
Eg: network_to_delete_after_test
Input:
names: Terms contained in the name of docker elements indicated for removal.
Eg: nats, removes network, container image, and volume elements that contain the term "nats" in the name. [optional]
Português:
Remove elementos docker criados dutente os testtes unitários, como por exemplo, redes, contêineres, imagens e volumes com o termo delete no nome.
ex.: network_to_delete_after_test
Entrada:
names: Termos contidos no nome dos elementos docker indicados para remoção.
Ex.: nats, remove os elementos de rede, imagem container e volumes que contenham o termo "nats" no nome. [opcional]
func ImageMakeCache ¶ added in v0.9.41
ImageMakeCache
English:
Creates a cached image used as a basis for creating new images.
The way to use this function is:
First option: * Create a folder containing the Dockerfile file to be used as a base for creating new images; * Enable the use of image cache in your projects with the container.SetCacheEnable(true) function; * Define the name of the cache image used in your projects, with the container.SetImageCacheName() function; * Use container.MakeDefaultDockerfileForMeWithInstallExtras() or container.MakeDefaultDockerfileForMe() functions. Second option: * Create a folder containing the Dockerfile file to be used as a base for creating new images; * Create your own Dockerfile and instead of using `FROM golang:1.16-alpine`, use the name of the cacge, eg `FROM cache:latest`;
Português:
Cria uma imagem cache usada como base para a criação de novas imagens.
A forma de usar esta função é:
Primeira opção: * Criar uma pasta contendo o arquivo Dockerfile a ser usado como base para a criação de novas imagens; * Habilitar o uso da imagem cache nos seus projetos com a função container.SetCacheEnable(true); * Definir o nome da imagem cache usada nos seus projetos, com a função container.SetImageCacheName(); * Usar as funções container.MakeDefaultDockerfileForMeWithInstallExtras() ou container.MakeDefaultDockerfileForMe(). Segunda opção: * Criar uma pasta contendo o arquivo Dockerfile a ser usado como base para a criação de novas imagens; * Criar seu próprio Dockerfile e em vez de usar `FROM golang:1.16-alpine`, usar o nome da cacge, por exemplo, `FROM cache:latest`;
func ImageMakeCacheWithDefaultName ¶ added in v0.9.41
ImageMakeCache
English:
Creates a cached image used as a basis for creating new images.
The way to use this function is:
First option: * Create a folder containing the Dockerfile file to be used as a base for creating new images; * Enable the use of image cache in your projects with the container.SetCacheEnable(true) function; * Use container.MakeDefaultDockerfileForMeWithInstallExtras() or container.MakeDefaultDockerfileForMe() functions. Second option: * Create a folder containing the Dockerfile file to be used as a base for creating new images; * Create your own Dockerfile and instead of using `FROM golang:1.16-alpine`, use the name of the cacge, eg `FROM cache:latest`;
Português:
Cria uma imagem cache usada como base para a criação de novas imagens.
A forma de usar esta função é:
Primeira opção: * Criar uma pasta contendo o arquivo Dockerfile a ser usado como base para a criação de novas imagens; * Habilitar o uso da imagem cache nos seus projetos com a função container.SetCacheEnable(true); * Usar as funções container.MakeDefaultDockerfileForMeWithInstallExtras() ou container.MakeDefaultDockerfileForMe(). Segunda opção: * Criar uma pasta contendo o arquivo Dockerfile a ser usado como base para a criação de novas imagens; * Criar seu próprio Dockerfile e em vez de usar `FROM golang:1.16-alpine`, usar o nome da cacge, por exemplo, `FROM cache:latest`;
Types ¶
type BlkioStatEntry ¶ added in v0.5.44
type BlkioStatEntry struct {
Major uint64 `json:"major"`
Minor uint64 `json:"minor"`
Op string `json:"op"`
Value uint64 `json:"value"`
}
BlkioStatEntry
Português:
Estrutura para armazenar uma peça de estatísticas de Blkio Não usado no windows.
English:
Structure to store a piece of Blkio stats Not used on Windows.
type BlkioStats ¶ added in v0.5.44
type BlkioStats struct {
// number of bytes transferred to and from the block device
IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"`
IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"`
IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"`
IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"`
IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"`
IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"`
SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"`
}
BlkioStats
English:
Stores All IO service stats for data read and write. This is a Linux specific structure as the differences between expressing block I/O on Windows and Linux are sufficiently significant to make little sense attempting to morph into a combined structure.
Português:
Armazena todos os estatísticas de serviço de IO para leitura e escrita de dados. Este é um estrutura Linux específica devido às diferenças entre expressar o IO de bloco no Windows e Linux são suficientemente significativas para fazer pouco sentido tentar morfar em uma combinação de estrutura.
type CPUStats ¶ added in v0.5.44
type CPUStats struct {
// CPU Usage. Linux and Windows.
CPUUsage CPUUsage `json:"cpu_usage"`
// System Usage. Linux only.
SystemUsage uint64 `json:"system_cpu_usage,omitempty"`
// Online CPUs. Linux only.
OnlineCPUs uint32 `json:"online_cpus,omitempty"`
// Throttling Data. Linux only.
ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}
CPUStats
English:
Aggregates and wraps all CPU related info of container
Português:
Agrega e embrulha todas as informações de CPU do container
type CPUUsage ¶ added in v0.5.44
type CPUUsage struct {
// Total CPU time consumed.
// Units: nanoseconds (Linux)
// Units: 100's of nanoseconds (Windows)
TotalUsage uint64 `json:"total_usage"`
// Total CPU time consumed per core (Linux). Not used on Windows.
// Units: nanoseconds.
PercpuUsage []uint64 `json:"percpu_usage,omitempty"`
// Time spent by tasks of the cgroup in kernel mode (Linux).
// Time spent by all container processes in kernel mode (Windows).
// Units: nanoseconds (Linux).
// Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers.
UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
// Time spent by tasks of the cgroup in user mode (Linux).
// Time spent by all container processes in user mode (Windows).
// Units: nanoseconds (Linux).
// Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers
UsageInUsermode uint64 `json:"usage_in_usermode"`
}
CPUUsage
English:
Stores All CPU stats aggregated since container inception.
Português:
Armazena todos os estatísticas de CPU agregadas desde o container.
type ContainerBuilder ¶
type ContainerBuilder struct {
IPV4Address string
// contains filtered or unexported fields
}
ContainerBuilder
English:
Docker manager
Português:
Gerenciador de containers e imagens docker
func (*ContainerBuilder) AddFailMatchFlag ¶ added in v0.9.11
func (e *ContainerBuilder) AddFailMatchFlag(value string)
AddFailMatchFlag
Similar:
AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()
English:
Error text searched for in the container's standard output. Input: value: Error text
Português:
Texto indicativo de erro procurado na saída padrão do container. Entrada: value: Texto indicativo de erro
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"io/ioutil"
"log"
"os"
"time"
)
func main() {
ContainerBuilderAddFailMatchFlag()
}
func ContainerBuilderAddFailMatchFlag() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
// [optional/opcional]
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
//
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
// [optional/opcional]
container.MakeDefaultDockerfileForMe()
// English: Sets a validity time for the image, preventing the same image from being remade for a period of time.
// In some tests, the same image is created inside a loop, and adding an expiration date causes the same image to be used without having to redo the same image at each loop iteration.
//
// Português: Define uma tempo de validade para a imagem, evitando que a mesma imagem seja refeita durante um período de tempo.
// Em alguns testes, a mesma imagem é criada dentro de um laço, e adicionar uma data de validade faz a mesma imagem ser usada sem a necessidade de refazer a mesma imagem a cada interação do loop
// [optional/opcional]
container.SetImageExpirationTime(5 * time.Minute)
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Golang project path to be turned into docker image
//
// Português: Caminho do projeto em Golang a ser transformado em imagem docker
container.SetBuildFolderPath("./test/bug")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
//
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
// [optional/opcional]
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines a log, in the form of a CSV file, of the container's performance, with indicators of memory consumption and access times. Note: The log format varies by platform, macos, windows, linux.
//
// Português: Define um log, na forma de arquivo CSV, de desempenho do container, com indicadores de consumo de memória e tempos de acesso. Nota: O formato do log varia de acordo com a plataforma, macos, windows, linux.
// [optional/opcional]
container.SetCsvLogPath("./test.counter.log.csv", true)
// English: Swaps the comma by tab, making the file compatible with floating-point numbers
//
// Português: Troca a virgula por tabulação, compatibilizando o arquivo com números de ponto flutuante
container.SetCsvFileValueSeparator("\t")
// English: Prints in the header of the file the name of the constant responsible for printing the column in the log.
//
// Português: Imprime no cabeçalho do arquivo o nome da constante responsável por imprimir a coluna no log.
// [optional/opcional]
container.SetCsvFileReader(true)
// English: Defines which columns to print in the log. To see all columns, set SetCsvFileRowsToPrint(KLogColumnAll) and SetCsvFileReader(true).
// Open the log file, define the columns to be printed in the log, and then use SetCsvFileRowsToPrint(KReadingTime | KCurrentNumberOfOidsInTheCGroup | KLimitOnTheNumberOfPidsInTheCGroup | ...)
//
// Português: Define quais colunas imprimir no log. Para vê todas as colunas, defina SetCsvFileRowsToPrint(KLogColumnAll) e SetCsvFileReader(true).
// Abra o arquivo de log, defina as colunas a serem impressas no log e em seguida, use SetCsvFileRowsToPrint(KReadingTime | KCurrentNumberOfOidsInTheCGroup | ...)
// [optional/opcional]
container.SetCsvFileRowsToPrint(KLogColumnAll)
// English: Sets a text search filter on the container's standard output and writes the text to the log defined by SetCsvLogPath()
// The container example prints a counter to standard output `log.Printf("counter: %.2f", counter)`. `label` adds the column name; `match` searches for text; `filter` applies a regular expression; `search` and `replace` do a replacement on top of the found value before writing to the log.
//
// Português: Define um filtro de busca por texto na saída padrão do container e escreve o texto no log definido por SetCsvLogPath()
// O container de exemplo imprime um contador na saída padrão `log.Printf("counter: %.2f", counter)`. `label` adiciona o nome da coluna; `match` procura pelo texto; `filter` aplica uma expressão regular; `search` e `replace` fazem uma substuição em cima do valor encontrado antes de escrever no log.
// [optional/opcional]
container.AddFilterToLogWithReplace(
"contador",
"counter",
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
"\\.",
",",
)
// English: Adds a failure indicator to the project. Failure indicator is a text searched for in the container's standard output and indicates something that should not have happened during the test.
//
// Português: Adiciona um indicador de falha ao projeto. Indicador de falha é um texto procurado na saída padrão do container e indica algo que não deveria ter acontecido durante o teste.
// [optional/opcional]
container.AddFailMatchFlag(
"counter: 40",
)
// English: Adds a log file write failure indicator to the project. Failure indicator is a text searched for in the container's standard output and indicates something that should not have happened during the test.
// Some critical failures can be monitored and when they happen, the container's standard output is filed in a `log.N.log` file, where N is an automatically incremented number.
//
// Português: Adiciona um indicador de falha com gravação de arquivo em log ao projeto. Indicador de falha é um texto procurado na saída padrão do container e indica algo que não deveria ter acontecido durante o teste.
// Algumas falhas críticas podem ser monitoradas e quando elas acontecem, a saída padrão do container é arquivada em um arquivo `log.N.log`, onde N é um número incrementado automaticamente.
// [optional/opcional]
err = container.AddFailMatchFlagToFileLog(
"bug:",
"./log1/log2/log3",
)
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality monitors the container's standard output and generates the log defined by the SetCsvLogPath() function.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade monitora a saída padrão do container e gera o log definido pela função SetCsvLogPath().
// StartMonitor() é usado durante o teste de caos e na geração do log de desempenho do container.
// [optional/opcional]
container.StartMonitor()
// English: Gets the event channel inside the container.
//
// Português: Pega o canal de eventos dentro do container.
event := container.GetChaosEvent()
// English: Let the example run until a failure happens to terminate the test
//
// Português: Deixa o exemplo rodar até que uma falha aconteça para terminar o teste
var fail bool
for {
select {
case e := <-event:
if e.Fail == true {
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fail = e.Fail
}
}
if fail == true {
break
}
}
// English: For container monitoring. Note: This function should be used to avoid trying to read a container that no longer exists, erased by the GarbageCollector() function.
//
// Português: Para o monitoramento do container. Nota: Esta função deve ser usada para evitar tentativa de leitura em um container que não existe mais, apagado pela função GarbageCollector().
// [optional/opcional]
_ = container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
var data []byte
data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
if len(data) == 0 {
fmt.Println("log file error")
}
_ = os.Remove("./log1/log2/log3/log.0.log")
_ = os.Remove("./log1/log2/log3/")
_ = os.Remove("./log1/log2/")
_ = os.Remove("./log1/")
func (*ContainerBuilder) AddFailMatchFlagToFileLog ¶ added in v0.9.25
func (e *ContainerBuilder) AddFailMatchFlagToFileLog(value, logDirectoryPath string) (err error)
AddFailMatchFlagToFileLog
Similar:
AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()
English:
Error text searched for in the container's standard output. Input: value: Error text logDirectoryPath: File path where the container's standard output filed in a `log.N.log` file will be saved, where N is an automatically incremented number. e.g.: "./bug/critical/" Output: err: Default error object
Português:
Texto indicativo de erro procurado na saída padrão do container. Entrada: value: Texto indicativo de erro logDirectoryPath: Caminho do arquivo onde será salva a saída padrão do container arquivada em um arquivo `log.N.log`, onde N é um número incrementado automaticamente. Ex.: "./bug/critical/" Output: err: Objeto de erro padrão
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"io/ioutil"
"log"
"os"
"time"
)
func main() {
ContainerBuilderAddFailMatchFlagToFileLog()
}
func ContainerBuilderAddFailMatchFlagToFileLog() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
// [optional/opcional]
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
//
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
// [optional/opcional]
container.MakeDefaultDockerfileForMe()
// English: Sets a validity time for the image, preventing the same image from being remade for a period of time.
// In some tests, the same image is created inside a loop, and adding an expiration date causes the same image to be used without having to redo the same image at each loop iteration.
//
// Português: Define uma tempo de validade para a imagem, evitando que a mesma imagem seja refeita durante um período de tempo.
// Em alguns testes, a mesma imagem é criada dentro de um laço, e adicionar uma data de validade faz a mesma imagem ser usada sem a necessidade de refazer a mesma imagem a cada interação do loop
// [optional/opcional]
container.SetImageExpirationTime(5 * time.Minute)
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Golang project path to be turned into docker image
//
// Português: Caminho do projeto em Golang a ser transformado em imagem docker
container.SetBuildFolderPath("./test/bug")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
//
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
// [optional/opcional]
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines a log, in the form of a CSV file, of the container's performance, with indicators of memory consumption and access times. Note: The log format varies by platform, macos, windows, linux.
//
// Português: Define um log, na forma de arquivo CSV, de desempenho do container, com indicadores de consumo de memória e tempos de acesso. Nota: O formato do log varia de acordo com a plataforma, macos, windows, linux.
// [optional/opcional]
container.SetCsvLogPath("./test.counter.log.csv", true)
// English: Swaps the comma by tab, making the file compatible with floating-point numbers
//
// Português: Troca a virgula por tabulação, compatibilizando o arquivo com números de ponto flutuante
container.SetCsvFileValueSeparator("\t")
// English: Prints in the header of the file the name of the constant responsible for printing the column in the log.
//
// Português: Imprime no cabeçalho do arquivo o nome da constante responsável por imprimir a coluna no log.
// [optional/opcional]
container.SetCsvFileReader(true)
// English: Defines which columns to print in the log. To see all columns, set SetCsvFileRowsToPrint(KLogColumnAll) and SetCsvFileReader(true).
// Open the log file, define the columns to be printed in the log, and then use SetCsvFileRowsToPrint(KReadingTime | KCurrentNumberOfOidsInTheCGroup | KLimitOnTheNumberOfPidsInTheCGroup | ...)
//
// Português: Define quais colunas imprimir no log. Para vê todas as colunas, defina SetCsvFileRowsToPrint(KLogColumnAll) e SetCsvFileReader(true).
// Abra o arquivo de log, defina as colunas a serem impressas no log e em seguida, use SetCsvFileRowsToPrint(KReadingTime | KCurrentNumberOfOidsInTheCGroup | ...)
// [optional/opcional]
container.SetCsvFileRowsToPrint(KLogColumnAll)
// English: Sets a text search filter on the container's standard output and writes the text to the log defined by SetCsvLogPath()
// The container example prints a counter to standard output `log.Printf("counter: %.2f", counter)`. `label` adds the column name; `match` searches for text; `filter` applies a regular expression; `search` and `replace` do a replacement on top of the found value before writing to the log.
//
// Português: Define um filtro de busca por texto na saída padrão do container e escreve o texto no log definido por SetCsvLogPath()
// O container de exemplo imprime um contador na saída padrão `log.Printf("counter: %.2f", counter)`. `label` adiciona o nome da coluna; `match` procura pelo texto; `filter` aplica uma expressão regular; `search` e `replace` fazem uma substuição em cima do valor encontrado antes de escrever no log.
// [optional/opcional]
container.AddFilterToLogWithReplace(
"contador",
"counter",
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
"\\.",
",",
)
// English: Adds a failure indicator to the project. Failure indicator is a text searched for in the container's standard output and indicates something that should not have happened during the test.
//
// Português: Adiciona um indicador de falha ao projeto. Indicador de falha é um texto procurado na saída padrão do container e indica algo que não deveria ter acontecido durante o teste.
// [optional/opcional]
container.AddFailMatchFlag(
"counter: 40",
)
// English: Adds a log file write failure indicator to the project. Failure indicator is a text searched for in the container's standard output and indicates something that should not have happened during the test.
// Some critical failures can be monitored and when they happen, the container's standard output is filed in a `log.N.log` file, where N is an automatically incremented number.
//
// Português: Adiciona um indicador de falha com gravação de arquivo em log ao projeto. Indicador de falha é um texto procurado na saída padrão do container e indica algo que não deveria ter acontecido durante o teste.
// Algumas falhas críticas podem ser monitoradas e quando elas acontecem, a saída padrão do container é arquivada em um arquivo `log.N.log`, onde N é um número incrementado automaticamente.
// [optional/opcional]
err = container.AddFailMatchFlagToFileLog(
"bug:",
"./log1/log2/log3",
)
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality monitors the container's standard output and generates the log defined by the SetCsvLogPath() function.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade monitora a saída padrão do container e gera o log definido pela função SetCsvLogPath().
// StartMonitor() é usado durante o teste de caos e na geração do log de desempenho do container.
// [optional/opcional]
container.StartMonitor()
// English: Gets the event channel inside the container.
//
// Português: Pega o canal de eventos dentro do container.
event := container.GetChaosEvent()
// English: Let the example run until a failure happens to terminate the test
//
// Português: Deixa o exemplo rodar até que uma falha aconteça para terminar o teste
var fail bool
for {
select {
case e := <-event:
if e.Fail == true {
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fail = e.Fail
}
}
if fail == true {
break
}
}
// English: For container monitoring. Note: This function should be used to avoid trying to read a container that no longer exists, erased by the GarbageCollector() function.
//
// Português: Para o monitoramento do container. Nota: Esta função deve ser usada para evitar tentativa de leitura em um container que não existe mais, apagado pela função GarbageCollector().
// [optional/opcional]
_ = container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
var data []byte
data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
if len(data) == 0 {
fmt.Println("log file error")
}
_ = os.Remove("./log1/log2/log3/log.0.log")
_ = os.Remove("./log1/log2/log3/")
_ = os.Remove("./log1/log2/")
_ = os.Remove("./log1/")
func (*ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer ¶ added in v0.5.22
func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
AddFileOrFolderToLinkBetweenConputerHostAndContainer
English:
Links a file or folder between the computer host and the container. Input: computerHostPath: Path of the file or folder inside the host computer. insideContainerPath: Path inside the container. Output: err: Default error object.
Português:
Vincula um arquivo ou pasta entre o computador e o container. Entrada: computerHostPath: Caminho do arquivo ou pasta no computador hospedeiro. insideContainerPath: Caminho dentro do container. Output: err: Objeto de erro padrão.
Example ¶
package main
import (
"fmt"
"github.com/helmutkemper/util"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
AddFileOrFolderToLinkBetweenConputerHostAndContainer()
}
func AddFileOrFolderToLinkBetweenConputerHostAndContainer() {
var err error
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: Sets a validity time for the image, preventing the same image from being remade for a period of time.
// In some tests, the same image is created inside a loop, and adding an expiration date causes the same image to be used without having to redo the same image at each loop iteration.
//
// Português: Define uma tempo de validade para a imagem, evitando que a mesma imagem seja refeita durante um período de tempo.
// Em alguns testes, a mesma imagem é criada dentro de um laço, e adicionar uma data de validade faz a mesma imagem ser usada sem a necessidade de refazer a mesma imagem a cada interação do loop
// [optional/opcional]
container.SetImageExpirationTime(5 * time.Minute)
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_delete_server_after_test")
// English: git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
//
// Português: repositório git a ser clonado https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// English: See the functions: SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and SetGitCloneToBuildWithPrivateToken()
//
// Português: Veja as funções: SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() e SetGitCloneToBuildWithPrivateToken()
// English: Set a waits for the text to appear in the standard container output to proceed [optional]
//
// Português: Define a espera pelo texto aguardado aparecer na saída padrão do container para prosseguir [opcional]
container.SetWaitStringWithTimeout(
"Stating server on port 3000",
10*time.Second,
)
// English: Change and open port 3000 to 3030
//
// Português: Mude e abra a porta 3000 para 3030
container.AddPortToChange(
"3000",
"3030",
)
// English: Replace container folder /static to host folder ./test/static
//
// Português: Substitua a pasta do container /static para a pasta da máquina ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer(
"./test/static",
"/static",
)
if err != nil {
log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
util.TraceToLog()
panic(err)
}
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
//todo: fazer o inspect
// English: Creates an image from a project server.
//
// Português: Cria uma imagem a partir do servidor com o projeto.
_, err = container.ImageBuildFromServer()
if err != nil {
util.TraceToLog()
log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
panic(err)
}
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
panic(err)
}
// English: container "container_delete_server_after_test" running and ready for use on this code point on port 3030
//
// Português: container "container_delete_server_after_test" executando e pronto para uso nesse ponto do código na porta 3030
// English: Read server inside a container on address http://localhost:3030/
//
// Português: Lê o servidor dentro do container em http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
// English: Print the output from get() function
//
// Português: Imprime a saída da função get()
fmt.Printf("%s", body)
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
func (*ContainerBuilder) AddFilterToFail ¶ added in v0.9.11
func (e *ContainerBuilder) AddFilterToFail(match, filter, search, replace string)
AddFilterToFail
Similar:
AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()
English:
Adds a filter to the container's standard output to look for a textual value indicating test failure.
Input: match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. search: Regular expression used for search and replacement in the text found in the previous step [optional]. replace: Regular expression replace element [optional].
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual indicador de falha do teste. Entrada: match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional]. replace: Elemento da troca da expressão regular [opcional].
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"log"
)
func main() {
AddFilterToFail()
}
func AddFilterToFail() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
//
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the path where the golang code to be transformed into a docker image is located.
//
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/counter")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
//
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines the log file path with container statistical data
//
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetCsvLogPath("./test.counter.log.csv", true)
// English: Determines the separator of the CSV file.
//
// Português: Determina o separador do arquivo CSV.
container.SetCsvFileValueSeparator("\t")
// English: Adds a search filter to the standard output of the container, to save the information in the log file
//
// Português: Adiciona um filtro de busca na saída padrão do container, para salvar a informação no arquivo de log
container.AddFilterToLogWithReplace(
// English: Label to be written to log file
//
// Português: Rótulo a ser escrito no arquivo de log
"contador",
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"\\.",
",",
)
// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"done!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter: 40",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor()
// English: Gets the event channel pointer inside the container.
//
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()
select {
case e := <-event:
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fmt.Printf("message: %v\n", e.Message)
}
// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
func (*ContainerBuilder) AddFilterToLog ¶ added in v0.9.11
func (e *ContainerBuilder) AddFilterToLog(label, match, filter string)
AddFilterToLog
Similar: AddFilterToLogWithReplace(), AddFilterToLog()
English: Adds a filter to search and convert a textual value to a column in the log file.
Input: label: Value to be placed in the log file column. match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. Note: - This function is used in conjunction with SetCsvLogPath(), StartMonitor(), StopMonitor().
Português: Adiciona um filtro para procurar e converter um valor textual em uma coluna no arquivo de log.
Entrada: label: Valor do rótulo a ser colocado na coluna do arquivo de log. match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. Nota: - Esta função é usada em conjunto com SetCsvLogPath(), StartMonitor(), StopMonitor()
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"log"
)
func main() {
AddFilterToLog()
}
func AddFilterToLog() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMeWithInstallExtras()
// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/counter")
container.SetCsvFileReader(true)
// English: Defines the name of the docker container to be created.
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines the log file path with container statistical data
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetCsvLogPath("./test.counter.log.csv", true)
// English: Adds a search filter to the standard output of the container, to save the information in the log file
// Português: Adiciona um filtro de busca na saída padrão do container, para salvar a informação no arquivo de log
container.AddFilterToLogWithReplace(
// English: Label to be written to log file
// Português: Rótulo a ser escrito no arquivo de log
"contador",
// English: Simple text searched in the container's standard output to activate the filter
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"\\.",
":",
)
// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
// English: Simple text searched in the container's standard output to activate the filter
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"done!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
// English: Simple text searched in the container's standard output to activate the filter
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter: 40",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor()
// English: Gets the event channel pointer inside the container.
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()
select {
case e := <-event:
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fmt.Printf("message: %v\n", e.Message)
}
// English: Stop container monitoring.
// Português: Para o monitoramento do container.
container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
func (*ContainerBuilder) AddFilterToLogWithReplace ¶ added in v0.9.35
func (e *ContainerBuilder) AddFilterToLogWithReplace(label, match, filter, search, replace string)
AddFilterToLogWithReplace
Similar:
AddFilterToLogWithReplace(), AddFilterToLog()
English:
Adds a filter to search and convert a textual value to a column in the CSV log file. Input: label: Value to be placed in the log file column. match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. search: Regular expression used for search and replacement in the text found in the previous step [optional]. replace: Regular expression replace element [optional].
Note:
- This function is used in conjunction with SetCsvLogPath(), StartMonitor(), StopMonitor().
Português:
Adiciona um filtro para procurar e converter um valor textual em uma coluna no arquivo de log CSV. Entrada: label: Valor do rótulo a ser colocado na coluna do arquivo de log. match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional]. replace: Elemento da troca da expressão regular [opcional].
Nota:
- Esta função é usada em conjunto com SetCsvLogPath(), StartMonitor(), StopMonitor()
func (*ContainerBuilder) AddFilterToRestartContainer ¶ added in v0.9.11
func (e *ContainerBuilder) AddFilterToRestartContainer(match, filter, search, replace string)
AddFilterToRestartContainer
Similar:
AddFilterToRestartContainer(), AddRestartMatchFlag(), AddRestartMatchFlagToFileLog()
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual liberando a possibilidade do container ser reinicado durante o teste de caos. Entrada: match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional]. replace: Elemento da troca da expressão regular [opcional].
Nota:
- Teste de caos é um teste feito quando há a necessidade de simular falhas dos microsserviços envolvidos no projeto. Durante o teste de caos, o container pode ser pausado, para simular um container não respondendo devido a sobrecarga, ou parado e reiniciado, simulando uma queda crítica, onde um microsserviço foi reinicializado depois de um tempo sem resposta.
English:
Adds a filter to the standard output of the container to look for a textual value releasing the possibility of the container being restarted during the chaos test. Input: match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. search: Regular expression used for search and replacement in the text found in the previous step [optional]. replace: Regular expression replace element [optional].
Note:
- Chaos testing is a test performed when there is a need to simulate failures of the microservices involved in the project. During chaos testing, the container can be paused, to simulate a container not responding due to overload, or stopped and restarted, simulating a critical crash, where a microservice was restarted after an unresponsive time.
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"log"
"time"
)
func main() {
AddFilterToRestartContainer()
}
func AddFilterToRestartContainer() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
//
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the path where the golang code to be transformed into a docker image is located.
//
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/chaos")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
//
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines the log file path with container statistical data
//
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetCsvLogPath("./test.counter.log.csv", true)
container.SetCsvFileValueSeparator("\t")
// English: Adds a search filter to the standard output of the container, to save the information in the log file
//
// Português: Adiciona um filtro de busca na saída padrão do container, para salvar a informação no arquivo de log
container.AddFilterToLogWithReplace(
// English: Label to be written to log file
//
// Português: Rótulo a ser escrito no arquivo de log
"contador",
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"\\.",
",",
)
// English: Adds a filter to look for a value in the container's standard output indicating the possibility of restarting the container.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a possibilidade de reiniciar o container.
container.AddFilterToRestartContainer(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"restart-me!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>restart-me!)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"",
"",
)
// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"done!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter: 340",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
// English: Adds a filter to look for a value in the container's standard output releasing the chaos test to be started
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container liberando o início do teste de caos
container.AddFilterToStartChaos(
"chaos enable",
"chaos enable",
"",
"",
)
// English: Defines the probability of the container restarting and changing the IP address in the process.
//
// Português: Define a probalidade do container reiniciar e mudar o endereço IP no processo.
container.SetRestartProbability(0.9, 1.0, 1)
// English: Defines a time window used to start chaos testing after container initialized
//
// Português: Define uma janela de tempo usada para começar o teste de caos depois do container inicializado
container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to release container restart after the container has been initialized
//
// Português: Define uma janela de tempo usada para liberar o reinício do container depois do container ter sido inicializado
container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to pause the container
//
// Português: Define uma janela de tempo usada para pausar o container
container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to unpause the container
//
// Português: Define uma janela de tempo usada para remover a pausa do container
container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to restart the container after stopping
//
// Português: Define uma janela de tempo usada para reiniciar o container depois de parado
container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)
// English: Enable chaos test
//
// Português: Habilita o teste de caos
container.EnableChaosScene(true)
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor()
// English: Gets the event channel pointer inside the container.
//
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()
select {
case e := <-event:
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fmt.Printf("message: %v\n", e.Message)
}
// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
func (*ContainerBuilder) AddFilterToStartChaos ¶ added in v0.9.11
func (e *ContainerBuilder) AddFilterToStartChaos(match, filter, search, replace string)
AddFilterToStartChaos
Similar:
AddStartChaosMatchFlag(), AddStartChaosMatchFlagToFileLog(), AddFilterToStartChaos()
English:
Adds a filter to the container's standard output to look for a textual value releasing the start of the chaos test. Input: match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. search: Regular expression used for search and replacement in the text found in the previous step [optional]. replace: Regular expression replace element [optional].
Note:
- Chaos testing is a test performed when there is a need to simulate failures of the microservices involved in the project. During chaos testing, the container can be paused, to simulate a container not responding due to overload, or stopped and restarted, simulating a critical crash, where a microservice was restarted after an unresponsive time.
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual liberando o início do teste de caos. Entrada: match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional]. replace: Elemento da troca da expressão regular [opcional].
Nota:
- Teste de caos é um teste feito quando há a necessidade de simular falhas dos microsserviços envolvidos no projeto. Durante o teste de caos, o container pode ser pausado, para simular um container não respondendo devido a sobrecarga, ou parado e reiniciado, simulando uma queda crítica, onde um microsserviço foi reinicializado depois de um tempo sem resposta.
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"log"
"time"
)
func main() {
AddFilterToStartChaos()
}
func AddFilterToStartChaos() {
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
//
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the path where the golang code to be transformed into a docker image is located.
//
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/chaos")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
//
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Defines the log file path with container statistical data
//
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetCsvLogPath("./test.counter.log.csv", true)
// English: Defines the separator used in the CSV file
//
// Português: Define o separador usado no arquivo CSV
container.SetCsvFileValueSeparator("\t")
// English: Adds a search filter to the standard output of the container, to save the information in the log file
//
// Português: Adiciona um filtro de busca na saída padrão do container, para salvar a informação no arquivo de log
container.AddFilterToLogWithReplace(
// English: Label to be written to log file
//
// Português: Rótulo a ser escrito no arquivo de log
"contador",
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"\\.",
",",
)
// English: Adds a filter to look for a value in the container's standard output indicating the possibility of restarting the container.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a possibilidade de reiniciar o container.
container.AddFilterToRestartContainer(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"restart-me!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>restart-me!)",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"",
"",
)
// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"done!",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
// English: Simple text searched in the container's standard output to activate the filter
//
// Português: Texto simples procurado na saída padrão do container para ativar o filtro
"counter: 340",
// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
//
// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
// English: Regular expression used for search and replacement in the text found in the previous step [optional].
//
// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
// English: Adds a filter to look for a value in the container's standard output releasing the chaos test to be started
//
// Português: Adiciona um filtro para procurar um valor na saída padrão do container liberando o início do teste de caos
container.AddFilterToStartChaos(
"chaos enable",
"chaos enable",
"",
"",
)
// English: Defines the probability of the container restarting and changing the IP address in the process.
//
// Português: Define a probalidade do container reiniciar e mudar o endereço IP no processo.
container.SetRestartProbability(0.9, 1.0, 1)
// English: Defines a time window used to start chaos testing after container initialized
//
// Português: Define uma janela de tempo usada para começar o teste de caos depois do container inicializado
container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to release container restart after the container has been initialized
//
// Português: Define uma janela de tempo usada para liberar o reinício do container depois do container ter sido inicializado
container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to pause the container
//
// Português: Define uma janela de tempo usada para pausar o container
container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Defines a time window used to unpause the container
//
// Português: Define uma janela de tempo usada para remover a pausa do container
container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)
// English: Sets a time window used to restart the container after stopping
//
// Português: Define uma janela de tempo usada para reiniciar o container depois de parado
container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)
// English: Enable chaos test
//
// Português: Habilita o teste de caos
container.EnableChaosScene(true)
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
//
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor()
// English: Gets the event channel pointer inside the container.
//
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()
select {
case e := <-event:
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fmt.Printf("message: %v\n", e.Message)
}
// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
container.StopMonitor()
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
func (*ContainerBuilder) AddFilterToSuccess ¶ added in v0.9.11
func (e *ContainerBuilder) AddFilterToSuccess(match, filter, search, replace string)
AddFilterToFail
English:
Adds a filter to the container's standard output to look for a textual value indicating test success. Input: match: Simple text searched in the container's standard output to activate the filter filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter. search: Regular expression used for search and replacement in the text found in the previous step [optional]. replace: Regular expression replace element [optional].
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual indicador de sucesso do teste. Entrada: match: Texto simples procurado na saída padrão do container para ativar o filtro filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`. search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional]. replace: Elemento da troca da expressão regular [opcional].
func (*ContainerBuilder) AddImageBuildOptionsBuildArgs ¶
func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)
AddImageBuildOptionsBuildArgs
English:
Set build-time variables (--build-arg) Input: key: Argument name value: Argument value
Example:
key: argument key (e.g. Dockerfile: ARG key)
value: argument value
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234
see https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
code:
var key = "GIT_PRIVATE_REPO"
var value = "github.com/yourgit"
var container = ContainerBuilder{}
container.AddImageBuildOptionsBuildArgs(key, &value)
Dockerfile:
FROM golang:1.16-alpine as builder
ARG GIT_PRIVATE_REPO
RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO
Português:
Adiciona uma variável durante a construção (--build-arg) Input: key: Nome do argumento. value: Valor do argumento.
Exemplo:
key: chave do argumento (ex. Dockerfile: ARG key)
value: valor do argumento
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234
Veja https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
code:
var key = "GIT_PRIVATE_REPO"
var value = "github.com/yourgit"
var container = ContainerBuilder{}
container.AddImageBuildOptionsBuildArgs(key, &value)
Dockerfile:
FROM golang:1.16-alpine as builder
ARG GIT_PRIVATE_REPO
RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO
func (*ContainerBuilder) AddPortToChange ¶
func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
AddPortToChange
English:
Defines a new port to be exposed on the network and links with the port defined in the image Input: imagePort: port defined in the image, in the form of a numeric string newPort: new port value to be exposed on the network
Nota:
- The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose();
- By default, all doors are closed;
- The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português:
Define uma nova porta a ser exposta na rede e vincula com a porta definida na imagem Entrada: imagePort: porta definida na imagem, na forma de string numérica newPort: novo valor da porta a se exposta na rede
Nota:
- As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose();
- Por padrão, todas as portas ficam fechadas;
- A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
Example ¶
package main
import (
"fmt"
"github.com/helmutkemper/util"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
AddPortToChange()
}
func AddPortToChange() {
var err error
GarbageCollector()
var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)
// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")
// replace container folder /static to host folder ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
util.TraceToLog()
panic(err)
}
// inicialize container object
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// todo: fazer o inspect
// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
util.TraceToLog()
log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
panic(err)
}
// container build from image delete:latest
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
panic(err)
}
// container "container_delete_server_after_test" running and ready for use on this code point on port 3030
// read server inside a container on address http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
// print output
fmt.Printf("%s", body)
GarbageCollector()
func (*ContainerBuilder) AddPortToDockerfileExpose ¶ added in v0.5.40
func (e *ContainerBuilder) AddPortToDockerfileExpose(value string)
AddPortToDockerfileExpose
English:
Add ports to dockerfile expose tag. Input: value: port in string form (without a colon, ":")
Português:
Adiciona portas a tag expose do dockerfile. Entrada: value: porta na forma de string (sem dois pontos, ":")
func (*ContainerBuilder) AddPortToExpose ¶ added in v0.5.18
func (e *ContainerBuilder) AddPortToExpose(value string)
AddPortToExpose
English:
Defines the port to be exposed on the network Input: value: port in the form of a numeric string
Note:
- The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose();
- By default, all doors are closed;
- The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português:
Define a porta a ser expostas na rede Entrada: value: porta na forma de string numérica
Nota:
- As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose();
- Por padrão, todas as portas ficam fechadas;
- A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
Example ¶
package main
import (
"fmt"
"github.com/helmutkemper/util"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
AddPortToExpose()
}
func AddPortToExpose() {
var err error
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
//
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_delete_server_after_test")
//todo: documentar
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
// English: Set a waits for the text to appear in the standard container output to proceed [optional]
//
// Português: Define a espera pelo texto aguardado aparecer na saída padrão do container para prosseguir [opcional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 20*time.Second)
// open port 3000 [optional in this case: default code open all ports]
container.AddPortToExpose("3000")
// English: Replace container folder /static to host folder ./test/static
//
// Português: Substitua a pasta do container /static para a pasta da máquina ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
util.TraceToLog()
panic(err)
}
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
util.TraceToLog()
log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
panic(err)
}
// container build from image delete:latest
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
panic(err)
}
// container "container_delete_server_after_test" running and ready for use on this code point on port 3030
// read server inside a container on address http://localhost:3000/
var resp *http.Response
resp, err = http.Get("http://localhost:3000/")
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
// print output
fmt.Printf("%s", body)
GarbageCollector()
func (*ContainerBuilder) AddRestartMatchFlag ¶ added in v0.9.11
func (e *ContainerBuilder) AddRestartMatchFlag(value string)
AddRestartMatchFlag
Similar:
AddFilterToRestartContainer(), AddRestartMatchFlag(), AddRestartMatchFlagToFileLog()
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual liberando a possibilidade do container ser reinicado durante o teste de caos. Entrada: value: Texto simples procurado na saída padrão do container para ativar o filtro
Nota:
- Teste de caos é um teste feito quando há a necessidade de simular falhas dos microsserviços envolvidos no projeto. Durante o teste de caos, o container pode ser pausado, para simular um container não respondendo devido a sobrecarga, ou parado e reiniciado, simulando uma queda crítica, onde um microsserviço foi reinicializado depois de um tempo sem resposta.
English:
Adds a filter to the standard output of the container to look for a textual value releasing the possibility of the container being restarted during the chaos test. Input: value: Simple text searched in the container's standard output to activate the filter
Note:
- Chaos testing is a test performed when there is a need to simulate failures of the microservices involved in the project. During chaos testing, the container can be paused, to simulate a container not responding due to overload, or stopped and restarted, simulating a critical crash, where a microservice was restarted after an unresponsive time.
func (*ContainerBuilder) AddRestartMatchFlagToFileLog ¶ added in v0.9.32
func (e *ContainerBuilder) AddRestartMatchFlagToFileLog(value, logDirectoryPath string) (err error)
AddRestartMatchFlagToFileLog
Similar:
AddFilterToRestartContainer(), AddRestartMatchFlag(), AddRestartMatchFlagToFileLog()
English:
Adds a filter to the standard output of the container to look for a textual value releasing the
possibility of the container being restarted during the chaos test.
Input:
value: Simple text searched in the container's standard output to activate the filter
logDirectoryPath: File path where the container's standard output filed in a `log.N.log` file
will be saved, where N is an automatically incremented number. e.g.: "./bug/critical/"
Note:
- Chaos testing is a test performed when there is a need to simulate failures of the microservices involved in the project. During chaos testing, the container can be paused, to simulate a container not responding due to overload, or stopped and restarted, simulating a critical crash, where a microservice was restarted after an unresponsive time.
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual liberando a
possibilidade do container ser reinicado durante o teste de caos.
Entrada:
value: Texto simples procurado na saída padrão do container para ativar o filtro
logDirectoryPath: Caminho do arquivo onde será salva a saída padrão do container arquivada em um
arquivo `log.N.log`, onde N é um número incrementado automaticamente. Ex.: "./bug/critical/"
Nota:
- Teste de caos é um teste feito quando há a necessidade de simular falhas dos microsserviços envolvidos no projeto. Durante o teste de caos, o container pode ser pausado, para simular um container não respondendo devido a sobrecarga, ou parado e reiniciado, simulando uma queda crítica, onde um microsserviço foi reinicializado depois de um tempo sem resposta.
func (*ContainerBuilder) AddStartChaosMatchFlag ¶ added in v0.9.36
func (e *ContainerBuilder) AddStartChaosMatchFlag(value string)
AddStartChaosMatchFlag
Similar: AddStartChaosMatchFlag(), AddStartChaosMatchFlagToFileLog(), AddFilterToStartChaos()
English: Adds a filter to the container's standard output to look for a textual value releasing the start of the chaos test.
Input: value: Error text
Português: Adiciona um filtro na saída padrão do container para procurar um valor textual liberando o início do teste de caos.
Entrada: value: Texto indicativo de erro
func (*ContainerBuilder) AddStartChaosMatchFlagToFileLog ¶ added in v0.9.36
func (e *ContainerBuilder) AddStartChaosMatchFlagToFileLog(value, logDirectoryPath string) (err error)
AddStartChaosMatchFlagToFileLog
Similar:
AddStartChaosMatchFlag(), AddStartChaosMatchFlagToFileLog(), AddFilterToStartChaos()
English:
Adds a filter to the container's standard output to look for a textual value releasing the start of
the chaos test.
Input:
value: Error text
logDirectoryPath: File path where the container's standard output filed in a `log.N.log` file
will be saved, where N is an automatically incremented number. e.g.: "./bug/critical/"
Output:
err: Default error object
Português:
Adiciona um filtro na saída padrão do container para procurar um valor textual liberando o início
do teste de caos.
Entrada:
value: Texto indicativo de erro
logDirectoryPath: Caminho do arquivo onde será salva a saída padrão do container arquivada em um
arquivo `log.N.log`, onde N é um número incrementado automaticamente. Ex.: "./bug/critical/"
Output:
err: Objeto de erro padrão
func (*ContainerBuilder) AddSuccessMatchFlag ¶ added in v0.9.11
func (e *ContainerBuilder) AddSuccessMatchFlag(value string)
AddSuccessMatchFlag
English:
Adds a text to be searched for in the container's standard output, indicating test success Input: value: Text searched for in the container's standard output
Português:
Adiciona um texto a ser procurado na saída padrão do conteiner, indicando sucesso do teste Entrada: value: Texto procurado na saída padrão do container
func (*ContainerBuilder) ContainerBuildAndStartFromImage ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerBuildAndStartFromImage() (err error)
ContainerBuildAndStartFromImage
English:
Transforms an image downloaded by ImagePull() or created by ImageBuildFromFolder() into a container and start it. Output: err: Default object error from golang
Português:
Transforma uma imagem baixada por ImagePull() ou criada por ImageBuildFromFolder() em container e o inicializa. Saída: err: Objeto padrão de erro golang
Example ¶
var err error
GarbageCollector()
var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)
// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")
// replace container folder /static to host folder ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
util.TraceToLog()
panic(err)
}
// inicialize container object
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// todo: fazer o inspect
// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
util.TraceToLog()
log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
panic(err)
}
// container build from image delete:latest
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
panic(err)
}
// container "container_delete_server_after_test" running and ready for use on this code point on port 3030
// read server inside a container on address http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
// print output
fmt.Printf("%s", body)
GarbageCollector()
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) ContainerBuildWithoutStartingItFromImage ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerBuildWithoutStartingItFromImage() (err error)
ContainerBuildWithoutStartingItFromImage
English:
Transforms an image downloaded by ImagePull() or created by ImageBuildFromFolder() into a container Output: err: Default object error from golang
Português:
Transforma uma imagem baixada por ImagePull() ou criada por ImageBuildFromFolder() em container Saída: err: Objeto padrão de erro golang
func (*ContainerBuilder) ContainerCopyFrom ¶ added in v0.9.40
func (e *ContainerBuilder) ContainerCopyFrom( containerPathList []string, hostPathList []string, ) ( statsList []types.ContainerPathStat, err error, )
ContainerCopyFrom
Português:
Copia um arquivo contido no container para uma pasta local
Entrada:
containerPathList: lista de arquivos contidos no container (caminho + nome do arquivo)
hostPathList: lista de caminhos dos arquivos a serem salvos no host (caminho + nome do
arquivo)
Saída:
statsList: Lista de informações dos arquivos
err: Objeto padrão de error
English:
Copy a file contained in the container to a local folder Input: containerPathList: list of files contained in the container (folder path + file name) hostPathList: list of file paths to be saved on the host (folder path + file name) Output: statsList: List of file information err: Default error object
func (*ContainerBuilder) ContainerCopyTo ¶ added in v0.9.40
func (e *ContainerBuilder) ContainerCopyTo( hostPathList []string, containerPathList []string, ) ( err error, )
ContainerCopyTo
Português:
Copia um arquivo contido no computador local para dentro do container Entrada: hostPathList: lista de arquivos a serem salvos no computador hospedeiro (caminho + nome do arquivo) containerPathList: lista de arquivos contidos no container (apenas o caminho) Saída: err: Objeto de erro padrão
English:
Copy a file contained on the local computer into the container Input: hostPathList: list of files to be saved on the host computer (path + filename) containerPathList: list of files contained in the container (path only) Output: err: standard error object
Example ¶
package main
import (
"fmt"
"github.com/docker/docker/api/types"
"log"
)
func main() {
var err error
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
//err = buildGoLintImage()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
err = builAlpineImage()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
}
func buildGoLintImage() (err error) {
var imageInspect types.ImageInspect
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("golint_delete:latest")
// English: Golang project path to be turned into docker image
//
// Português: Caminho do projeto em Golang a ser transformado em imagem docker
container.SetBuildFolderPath("./example/golint/imageGolintBuild")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_golint_delete_after_test")
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
var copyResponse []types.ContainerPathStat
copyResponse, err = container.ContainerCopyFrom(
[]string{"/go/pkg/mod/github.com/golangci/golangci-lint@v1.23.6/bin/golangci-lint"},
[]string{"./example/golint/golangci-lint"},
)
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
fmt.Printf("file name: %v\n", copyResponse[0].Name)
return
}
func builAlpineImage() (err error) {
var imageInspect types.ImageInspect
var container = ContainerBuilder{}
// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
// [optional/opcional]
container.SetPrintBuildOnStrOut()
// English: Name of the new image to be created.
//
// Português: Nome da nova imagem a ser criada.
container.SetImageName("alpine_delete:latest")
// English: Golang project path to be turned into docker image
//
// Português: Caminho do projeto em Golang a ser transformado em imagem docker
container.SetBuildFolderPath("./example/golint/imageAlpineBuild")
// English: Defines the name of the docker container to be created.
//
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_alpine_delete_after_test")
// English: Initializes the container manager object.
//
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
//
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
//
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
err = container.ContainerCopyTo(
[]string{"./example/golint/golangci-lint"},
[]string{"/go"},
)
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
var exitCode int
var runing bool
var stdOutput []byte
var stdError []byte
exitCode, runing, stdOutput, stdError, err = container.ContainerExecCommand([]string{"ls", "-l"})
log.Printf("exitCode: %v", exitCode)
log.Printf("runing: %v", runing)
log.Printf("stdOutput: %v", string(stdOutput))
log.Printf("stdError: %v", string(stdError))
exitCode, runing, stdOutput, stdError, err = container.ContainerExecCommand([]string{"./golangci-lint"})
log.Printf("exitCode: %v", exitCode)
log.Printf("runing: %v", runing)
log.Printf("stdOutput: %v", string(stdOutput))
log.Printf("stdError: %v", string(stdError))
// English: Deletes all docker elements with the term `delete` in the name.
//
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
// [optional/opcional]
GarbageCollector()
return
}
Output: image size: 1.4 MB image os: linux container name: container_counter_delete_after_test done: false fail: true error: false
func (*ContainerBuilder) ContainerExecCommand ¶ added in v0.9.41
func (e *ContainerBuilder) ContainerExecCommand( commands []string, ) ( exitCode int, runing bool, stdOutput []byte, stdError []byte, err error, )
ContainerExecCommand
Português:
Executa comandos dentro do container.
Entrada:
commands: lista de comandos. Ex.: []string{"ls", "-l"}
Saída:
exitCode: código de saída do comando.
runing: indica se o comando está rodando.
stdOutput: saída padrão do comando.
stdError: saída de erro do comando.
err: objeto de erro padrão.
English:
Execute commands inside the container.
Input:
commands: command list. Eg: []string{"ls", "-l"}
Output:
exitCode: command exit code.
runing: indicates whether the command is running.
stdOutput: standard output of the command.
stdError: error output from the command.
err: standard error object.
func (*ContainerBuilder) ContainerFindIdByName ¶ added in v0.5.19
func (e *ContainerBuilder) ContainerFindIdByName(name string) (id string, err error)
ContainerFindIdByName
Similar:
ContainerFindIdByName(), ContainerFindIdByNameContains()
English:
Searches and returns the ID of the container, if it exists Input: name: Full name of the container. Output: id: container ID err: standard error object
Português:
Procura e retorna o ID do container, caso o mesmo exista Entrada: name: Nome completo do container. Saída: id: ID do container err: Objeto de erro padrão
func (*ContainerBuilder) ContainerFindIdByNameContains ¶ added in v0.5.19
func (e *ContainerBuilder) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)
ContainerFindIdByNameContains
Similar:
ContainerFindIdByName(), ContainerFindIdByNameContains()
English:
Searches and returns the ID list of the container name Input: name: name of the container. Output: id: list of containers ID err: standard error object
Português:
Procura e retorna uma lista de IDs de containers Entrada: name: Nome do container. Saída: id: lista de IDs dos containers err: Objeto de erro padrão
func (*ContainerBuilder) ContainerInspect ¶
func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)
ContainerInspect
English:
Inspects the container Output: inspect: Contains information about the container, such as ID, name, status, volumes, etc. err: Standard error object.
Português:
Inspeciona o container Saída: inspect: Contém informações sobre o container, como ID, nome, status, volumes, etc. err: Objeto de erro padrão.
func (*ContainerBuilder) ContainerPause ¶
func (e *ContainerBuilder) ContainerPause() (err error)
ContainerPause
English:
Pause the container. Output: err: Default error object.
Note:
- There are two ways to create a container: ContainerBuildAndStartFromImage, initializes the oncontainer and initializes the registry to the docker network, so that it works correctly. ContainerBuildWithoutStartingItFromImage just creates the container, so the first time it runs, it must have its network registry initialized so it can work properly.
- After initializing the first time, use the functions, ContainerStart, ContainerPause and ContainerStop, if you need to control the container.
Português:
Pausa o container. Saída: err: Objeto de erro padrão.
Nota:
- Ha duas formas de criar um container: ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o registro aa rede docker, para que o mesmo funcione de forma correta. ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a primeira vez que o mesmo roda, ele deve ter o seu registro de rede inicializado para que possa funcionar de forma correta.
- Apos inicializado a primeira vez, use as funções, ContainerStart, ContainerPause e ContainerStop, caso necessite controlar o container.
func (*ContainerBuilder) ContainerRemove ¶
func (e *ContainerBuilder) ContainerRemove(removeVolumes bool) (err error)
ContainerRemove
English:
Stop and remove the container Input: removeVolumes: removes docker volumes linked to the container Output: err: standard error object
Português:
Parar e remover o container Entrada: removeVolumes: remove os volumes docker vinculados ao container Saída: err: Objeto de erro padrão
func (*ContainerBuilder) ContainerRestart ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerRestart() (err error)
ContainerRestart
English:
Restarts a container stopped by ContainerStop().
Output: err: standard error object
Português:
Reinicia um container parado por ContainerStop(). Saída: err: objeto de erro padrão
func (*ContainerBuilder) ContainerRestartWithTimeout ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerRestartWithTimeout(timeout time.Duration) (err error)
ContainerRestartWithTimeout
English:
Restarts a container stopped by ContainerStop(). Input: timeout: timeout to restar container Output: err: standard error object
Português:
Reinicia um container parado por ContainerStop(). Entrada: timeout: tempo limite para reinício do container Saída: err: objeto de erro padrão
func (*ContainerBuilder) ContainerSetDisabePauseOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) ContainerSetDisabePauseOnChaosScene(value bool)
ContainerSetDisabePauseOnChaosScene
English:
Set the container pause functionality to be disabled when the chaos scene is running Input: value: true to disable the container pause functionality
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define se a funcionalidade de pausar o container será desabilitada quando a cena de chaos estiver em execução Entrada: value: true para desabilitar a funcionalidade de pausar o container
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) ContainerSetDisabeStopOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) ContainerSetDisabeStopOnChaosScene(value bool)
ContainerSetDisabeStopOnChaosScene
English:
Set the container stop functionality to be disabled when the chaos scene is running Input: value: true to disable the container stop functionality
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define se a funcionalidade de parar o container será desabilitada quando a cena de chaos estiver em execução Entrada: value: true para desabilitar a funcionalidade de parar o container
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) ContainerStart ¶
func (e *ContainerBuilder) ContainerStart() (err error)
ContainerStart
English:
Initialize a paused or stoped container Output: err: Default error object.
Note:
- There are two ways to create a container: ContainerBuildAndStartFromImage, initializes the oncontainer and initializes the registry to the docker network, so that it works correctly. ContainerBuildWithoutStartingItFromImage just creates the container, so the first time it runs, it must have its network registry initialized so it can work properly.
- After initializing the first time, use the functions, ContainerStart, ContainerPause and ContainerStop, if you need to control the container.
Português:
Inicializar um container pausado ou parado. Saída: err: Objeto de erro padrão.
Nota:
- Ha duas formas de criar um container: ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o registro aa rede docker, para que o mesmo funcione de forma correta. ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a primeira vez que o mesmo roda, ele deve ter o seu registro de rede inicializado para que possa funcionar de forma correta.
- Apos inicializado a primeira vez, use as funções, ContainerStart, ContainerPause e ContainerStop, caso necessite controlar o container.
func (*ContainerBuilder) ContainerStartAfterBuild ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerStartAfterBuild() (err error)
ContainerStartAfterBuild (english):
ContainerStartAfterBuild (português): Inicia um container recem criado.
Saída:
err: Objeto de erro padrão
Nota: - Ha duas formas de criar um container:
ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o
registro aa rede docker, para que o mesmo funcione de forma correta.
ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a
primeira vez que o mesmo roda, ele deve ter o seu registro de rede
inicializado para que possa funcionar de forma correta.
- Apos inicializado a primeira vez, use as funções, ContainerStart,
ContainerPause e ContainerStop, caso necessite controlar o container.
func (*ContainerBuilder) ContainerStatisticsOneShot ¶ added in v0.5.44
func (e *ContainerBuilder) ContainerStatisticsOneShot() ( stats types.Stats, err error, )
ContainerStatisticsOneShot
English:
Returns the container's memory and system consumption data at the time of the query. Output: stats: Container statistics such as memory, bytes read/written, CPUs, access times, etc. err: standard error object
Português:
Retorna os dados de consumo de memória e sistema do container no instante da consulta.
Saída:
stats: Estatísticas do conbtainer, como memória, bytes lidos/escritos, CPUs, tempos de acesso,
etc.
err: Objeto de erro padrão
func (*ContainerBuilder) ContainerStop ¶
func (e *ContainerBuilder) ContainerStop() (err error)
ContainerStop
English:
Stop the container Output: err: Default error object.
Note:
- There are two ways to create a container: ContainerBuildAndStartFromImage, initializes the oncontainer and initializes the registry to the docker network, so that it works correctly. ContainerBuildWithoutStartingItFromImage just creates the container, so the first time it runs, it must have its network registry initialized, so it can work properly.
- After initializing the first time, use the functions, ContainerStart, ContainerPause and ContainerStop, if you need to control the container.
Português:
Para o container. Saída: err: Objeto de erro padrão.
Nota:
- Ha duas formas de criar um container: ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o registro aa rede docker, para que o mesmo funcione de forma correta. ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a primeira vez que o mesmo roda, ele deve ter o seu registro de rede inicializado para que possa funcionar de forma correta.
- Apos inicializado a primeira vez, use as funções, ContainerStart, ContainerPause e ContainerStop, caso necessite controlar o container.
func (*ContainerBuilder) ContainerUnpause ¶ added in v0.5.40
func (e *ContainerBuilder) ContainerUnpause() (err error)
ContainerUnpause
English:
Remove the pause from the previously paused container with the container.Pause() command Output: err: Standard error object.
Português:
Remove a pausa do container previamente pausado com o comando container.Pause() Saída: err: Objeto de erro padrão.
func (*ContainerBuilder) EnableChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) EnableChaosScene(enable bool)
EnableChaosScene
English:
Enables chaos functionality in containers. Input: enable: enable chaos manager
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Habilita a funcionalidade de caos nos containers. Entrada: enable: habilita o gerenciador de caos
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) FindCurrentIPV4Address ¶
func (e *ContainerBuilder) FindCurrentIPV4Address() (IP string, err error)
FindCurrentIPV4Address
English:
Inspects the docker's network and returns the current IP of the container Output: IP: container IP address IPV4 err: standard error object
Português:
Inspeciona a rede do docker e devolve o IP atual do container Saída: IP: endereço IP do container IPV4 err: objeto de erro padrão
Example ¶
var err error
GarbageCollector()
var container = ContainerBuilder{}
// set image name for docker pull
container.SetImageName("nats:latest")
// set a container name
container.SetContainerName("container_delete_nats_after_test")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)
// inialize the container object
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// image nats:latest pull command [optional]
err = container.ImagePull()
if err != nil {
util.TraceToLog()
panic(err)
}
// container build and start from image nats:latest
// waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container output
// to proceed
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
panic(err)
}
var IP string
IP, err = container.FindCurrentIPV4Address()
if err != nil {
util.TraceToLog()
panic(err)
}
if IP != container.GetIPV4Address() {
err = errors.New("all ip address must be a samer IP")
util.TraceToLog()
panic(err)
}
// container "container_delete_nats_after_test" running and ready for use on this code point on var IP
// all nats ports are open
// you can use AddPortToExpose("4222"), to open only ports defineds inside code;
// you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port
// 1111;
// you can use SetDoNotOpenContainersPorts() to not open containers ports
GarbageCollector()
// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
util.TraceToLog()
panic(err)
}
func (*ContainerBuilder) FindTextInsideContainerLog ¶
func (e *ContainerBuilder) FindTextInsideContainerLog(value string) (contains bool, err error)
FindTextInsideContainerLog
English:
Search for text in standard container output. Input: value: searched text Output: contains: true if text was found err: standard error object
Português:
Procurar por um texto na saída padrão do container. Entrada: value: texto procurado Saída: contains: true se o texto foi encontrado err: objeto de erro padrão
func (*ContainerBuilder) GetBuildFolderPath ¶ added in v0.9.11
func (e *ContainerBuilder) GetBuildFolderPath() (buildPath string)
GetBuildFolderPath
English:
Returns the project path used to mount the image Output: buildPath: string with the project path
Português:
Retorna o caminho do projeto usado para montar a imagem Saída: buildPath: string com o caminho do projeto
func (*ContainerBuilder) GetChannelEvent ¶
func (e *ContainerBuilder) GetChannelEvent() (channel *chan iotmakerdocker.ContainerPullStatusSendToChannel)
GetChannelEvent (english):
GetChannelEvent (português): Canal disparado durante o processo de image build ou container build e retorna informações como andamento do download da imagem, processo de extração da mesma entre outras informações
Waiting: Esperando o processo ser iniciado pelo docker Downloading: Estado do download da imagem, caso a mesma não exista na máquina host Count: Quantidade de blocos a serem baixados Current: Total de bytes baixados até o momento Total: Total de bytes a serem baixados Percent: Percentual atual do processo com uma casa decimal de precisão DownloadComplete: todo: fazer Extracting: Estado da extração da imagem baixada Count: Quantidade de blocos a serem extraídos Current: Total de bytes extraídos até o momento Total: Total de bytes a serem extraídos Percent: Percentual atual do processo com uma casa decimal de precisão PullComplete: todo: fazer ImageName: nome da imagem baixada ImageID: ID da imagem baixada. (Cuidado: este valor só é definido ao final do processo) ContainerID: ID do container criado. (Cuidado: este valor só é definido ao final do processo) Closed: todo: fazer Stream: saída padrão do container durante o processo de build SuccessfullyBuildContainer: sucesso ao fim do processo de build do container SuccessfullyBuildImage: sucesso ao fim do processo de build da imagem IdAuxiliaryImages: usado pelo coletor de lixo para apagar as imagens axiliares ao fim do processo de build
func (*ContainerBuilder) GetChannelOnContainerInspect ¶
func (e *ContainerBuilder) GetChannelOnContainerInspect() (channel *chan bool)
GetChannelOnContainerInspect
English:
Channel triggered at each ticker cycle defined in SetInspectInterval()
Português:
Canal disparado a cada ciclo do ticker definido em SetInspectInterval()
func (*ContainerBuilder) GetChannelOnContainerReady ¶
func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)
GetChannelOnContainerReady
English: Channel fired when the container is ready for use
Note: This channel expects the container to signal that it is ready, but it does not take into account whether the application contained in the container is ready. For this reason, it is recommended to use SetWaitString()
Português: Canal disparado quando o container está pronto para uso
Nota: Este canal espera o container sinalizar que está pronto, mas, ele não considera se a aplicação contida no container está pronta. Por isto, é recomendado o uso de SetWaitString()
func (*ContainerBuilder) GetChaosEvent ¶ added in v0.9.11
func (e *ContainerBuilder) GetChaosEvent() (eventChannel chan Event)
func (*ContainerBuilder) GetContainerID ¶
func (e *ContainerBuilder) GetContainerID() (ID string)
GetContainerID
English: Returns the ID of the created container
Português: Retorna o ID do container criado
func (*ContainerBuilder) GetContainerInfo ¶ added in v0.9.11
func (e *ContainerBuilder) GetContainerInfo() (info types.Info, err error)
func (ContainerBuilder) GetContainerIsStarted ¶ added in v0.9.11
func (e ContainerBuilder) GetContainerIsStarted() (started bool)
func (*ContainerBuilder) GetContainerLog ¶
func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
GetContainerLog
English: Returns the current standard output of the container.
Português: Retorna a saída padrão atual do container.
func (*ContainerBuilder) GetContainerName ¶ added in v0.9.11
func (e *ContainerBuilder) GetContainerName() (containerName string)
func (*ContainerBuilder) GetFailFlag ¶ added in v0.9.32
func (e *ContainerBuilder) GetFailFlag() (fail bool)
func (*ContainerBuilder) GetGitCloneToBuild ¶ added in v0.9.11
func (e *ContainerBuilder) GetGitCloneToBuild() (url string)
func (*ContainerBuilder) GetIPV4Address ¶
func (e *ContainerBuilder) GetIPV4Address() (IP string)
GetIPV4Address
English: Returns the last IP read from the container
Note: If the container is disconnected or connected to another network after creation, this information may change
Português: Retorna o último IP lido do container
Nota: Caso o container seja desconectado ou conectado a outra rede após a criação, esta informação pode mudar
func (*ContainerBuilder) GetIdByContainerName ¶
func (e *ContainerBuilder) GetIdByContainerName() (err error)
GetIdByContainerName
English: Returns the container ID defined in SetContainerName()
Português: Retorna o ID do container definido em SetContainerName()
func (*ContainerBuilder) GetImageArchitecture ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageArchitecture() (architecture string)
func (*ContainerBuilder) GetImageAuthor ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageAuthor() (author string)
func (*ContainerBuilder) GetImageCacheName ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageCacheName() (name string)
func (*ContainerBuilder) GetImageComment ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageComment() (comment string)
func (*ContainerBuilder) GetImageContainer ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageContainer() (container string)
func (*ContainerBuilder) GetImageCreated ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageCreated() (created time.Time)
func (*ContainerBuilder) GetImageExpirationTime ¶ added in v0.9.12
func (e *ContainerBuilder) GetImageExpirationTime() (expiration time.Duration)
func (*ContainerBuilder) GetImageID ¶
func (e *ContainerBuilder) GetImageID() (ID string)
GetImageID
English: Returns the image ID.
Português: Retorna o ID da imagem.
func (*ContainerBuilder) GetImageName ¶
func (e *ContainerBuilder) GetImageName() (name string)
GetImageName
English: Returns the name of the image.
Português: Retorna o nome da imagem.
func (*ContainerBuilder) GetImageOs ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageOs() (os string)
func (*ContainerBuilder) GetImageOsVersion ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageOsVersion() (osVersion string)
func (*ContainerBuilder) GetImageParent ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageParent() (parent string)
func (*ContainerBuilder) GetImageRepoDigests ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageRepoDigests() (repoDigests []string)
func (*ContainerBuilder) GetImageRepoTags ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageRepoTags() (repoTags []string)
func (*ContainerBuilder) GetImageSize ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageSize() (size int64)
func (*ContainerBuilder) GetImageVariant ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageVariant() (variant string)
func (*ContainerBuilder) GetImageVirtualSize ¶ added in v0.9.11
func (e *ContainerBuilder) GetImageVirtualSize() (virtualSize int64)
func (*ContainerBuilder) GetInitialized ¶ added in v0.9.11
func (e *ContainerBuilder) GetInitialized() (initialized bool)
func (*ContainerBuilder) GetLastInspect ¶
func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)
GetLastInspect
English: Returns the container data based on the last ticker cycle defined in SetInspectInterval()
Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the information is ready for use
Português: Retorna os dados do container baseado no último ciclo do ticker definido em SetInspectInterval()
Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão prontas para uso
func (*ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog ¶ added in v0.5.43
func (e *ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog(value string) (text string, contains bool, err error)
func (*ContainerBuilder) GetLastLogs ¶
func (e *ContainerBuilder) GetLastLogs() (logs string)
GetLastLogs
English: Returns the standard container output based on the last ticker cycle defined in SetInspectInterval()
Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the information is ready for use
Português: Retorna a saída padrão do container baseado no último ciclo do ticker definido em SetInspectInterval()
Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão prontas para uso
func (*ContainerBuilder) GetMetadata ¶ added in v0.9.25
func (e *ContainerBuilder) GetMetadata() (metadata map[string]interface{})
GetMetadata
English: Returns a list of user-defined data
Output:
metadata: map[string]interface{} with user defined data
Português: Retorna uma lista de dados definida oelo usuário
Saída:
metadata: map[string]interface{} com dados definidos oelo usuário
func (*ContainerBuilder) GetNetworkGatewayIPV4 ¶
func (e *ContainerBuilder) GetNetworkGatewayIPV4() (IPV4 string)
GetNetworkGatewayIPV4
English: Returns the gateway from the network to the IPV4 network
Português: Retorna o gateway da rede para rede IPV4
func (*ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName ¶
func (e *ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName(networkName string) (IPV4 string, err error)
GetNetworkGatewayIPV4ByNetworkName
English: If the container is connected to more than one network, this function returns the gateway of the chosen network.
Note: the default docker network is named "bridge"
Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o gateway da rede escolhida.
Nota: a rede padrão do docker tem o nome "bridge"
func (*ContainerBuilder) GetNetworkIPV4 ¶
func (e *ContainerBuilder) GetNetworkIPV4() (IPV4 string)
GetNetworkIPV4
English: Return the IPV4 from the docker network
Português: Retorno o IPV4 da rede do docker
func (*ContainerBuilder) GetNetworkIPV4ByNetworkName ¶
func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)
GetNetworkIPV4ByNetworkName
English: If the container is connected to more than one network, this function returns the IPV4 of the chosen network.
Note: the default docker network is named "bridge"
Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o IPV4 da rede escolhida.
Nota: a rede padrão do docker tem o nome "bridge"
func (*ContainerBuilder) GetNetworkInterface ¶
func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)
GetNetworkInterface
English: Returns the object defined for the network control
Português: Retorna o objeto definido para o controle da rede
func (*ContainerBuilder) GetProblem ¶ added in v0.9.23
func (e *ContainerBuilder) GetProblem() (problem string)
func (*ContainerBuilder) GetSuccessFlag ¶ added in v0.9.32
func (e *ContainerBuilder) GetSuccessFlag() (success bool)
func (*ContainerBuilder) ImageBuildFromFolder ¶
func (e *ContainerBuilder) ImageBuildFromFolder() (inspect types.ImageInspect, err error)
ImageBuildFromFolder
English: transforms the contents of the folder defined in SetBuildFolderPath() into a docker image
The folder must contain a dockerfile file, but since different uses can have different dockerfiles, the following order will be given when searching for the file: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" in the root folder; If not found, a recursive search will be done for "Dockerfile" and "dockerfile"; If the project is in golang and the main.go file, containing the package main, is contained in the root folder, with the go.mod file, the MakeDefaultDockerfileForMe() function can be used to use a standard Dockerfile file
Português: transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma imagem docker
Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles, será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta raiz. Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile" Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz, com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo Dockerfile padrão
Example ¶
package main
import (
"fmt"
iotmakerdocker "github.com/helmutkemper/iotmaker.docker/v1.0.1"
"github.com/helmutkemper/util"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
func ImageBuildViewer(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) {
go func(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) {
for {
select {
case event := <-*ch:
var stream = event.Stream
stream = strings.ReplaceAll(stream, "\n", "")
stream = strings.ReplaceAll(stream, "\r", "")
stream = strings.Trim(stream, " ")
if stream == "" {
continue
}
log.Printf("%v", stream)
if event.Closed == true {
return
}
}
}
}(ch)
}
func main() {
var err error
GarbageCollector()
var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// set a folder path to make a new image
container.SetBuildFolderPath("./test/server")
container.MakeDefaultDockerfileForMeWithInstallExtras()
// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("starting server at port 3000", 10*time.Second)
// change and open port 3000 to 3030
container.AddPortToExpose("3000")
// replace container folder /static to host folder ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
panic(err)
}
// show image build stram on std out
ImageBuildViewer(container.GetChannelEvent())
// inicialize container object
err = container.Init()
if err != nil {
panic(err)
}
// todo: fazer o teste do inspect
// builder new image from folder
_, err = container.ImageBuildFromFolder()
if err != nil {
panic(err)
}
// build a new container from image
err = container.ContainerBuildAndStartFromImage()
if err != nil {
panic(err)
}
// Server is ready for use o port 3000
// read server inside a container on address http://localhost:3000/
var resp *http.Response
resp, err = http.Get("http://localhost:3000/")
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
util.TraceToLog()
log.Printf("http.Get().error: %v", err.Error())
panic(err)
}
// print output
fmt.Printf("%s", body)
GarbageCollector()
}
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) ImageBuildFromServer ¶
func (e *ContainerBuilder) ImageBuildFromServer() (inspect types.ImageInspect, err error)
ImageBuildFromServer
English: Build a docker image from a project contained in a git repository.
Note: The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh(); SetPrivateRepositoryAutoConfig() copies the git credentials contained in ~/.ssh and the settings of ~/.gitconfig; The SetGitConfigFile(), SetSshIdRsaFile() and SetSshKnownHostsFile() functions can be used to set git security and configuration files manually.
Português: Monta uma imagem docker a partir de um projeto contido em um repositório git.
Nota: O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh(); SetPrivateRepositoryAutoConfig() copia as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig; As funções SetGitConfigFile(), SetSshIdRsaFile() e SetSshKnownHostsFile() podem ser usadas para definir os arquivos de configurações se segurança do git manualmente.
func (*ContainerBuilder) ImageFindIdByName ¶ added in v0.5.19
func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)
func (*ContainerBuilder) ImageFindIdByNameContains ¶ added in v0.5.19
func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)
func (*ContainerBuilder) ImageInspect ¶ added in v0.9.11
func (e *ContainerBuilder) ImageInspect() (inspect types.ImageInspect, err error)
func (*ContainerBuilder) ImageListExposedPorts ¶
func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)
ImageListExposedPorts
English: Lists all the ports defined in the image to be exposed.
Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose(); By default, all doors are closed.
Português: Lista todas as portas definidas na imagem para serem expostas.
Nota: As portas expostas na criação do container podem ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas.
Example ¶
var err error
var portList []nat.Port
// create a container
var container = ContainerBuilder{}
// set image name for docker pull
container.SetImageName("nats:latest")
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
err = container.ImagePull()
if err != nil {
util.TraceToLog()
panic(err)
}
portList, err = container.ImageListExposedPorts()
if err != nil {
util.TraceToLog()
panic(err)
}
var portsToPrint = make([]string, 0)
for _, p := range portList {
portsToPrint = append(portsToPrint, fmt.Sprintf("port: %v/%v\n", p.Port(), p.Proto()))
}
sort.Strings(portsToPrint)
for _, print := range portsToPrint {
fmt.Printf("%v", print)
}
err = container.ImageRemove()
if err != nil {
util.TraceToLog()
panic(err)
}
Output: port: 4222/tcp port: 6222/tcp port: 8222/tcp
func (*ContainerBuilder) ImageListExposedVolumes ¶
func (e *ContainerBuilder) ImageListExposedVolumes() (list []string, err error)
ImageListExposedVolumes
English: Lists all volumes defined in the image.
Note: Use the AddFileOrFolderToLinkBetweenConputerHostAndContainer() function to link folders and files between the host computer and the container
Português: Lista todos os volumes definidos na imagem.
Nota: Use a função AddFileOrFolderToLinkBetweenConputerHostAndContainer() para vincular pastas e arquivos entre o computador hospedeiro e o container
Example ¶
var err error
var volumes []string
GarbageCollector()
var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// todo: fazer o teste do inspect
_, err = container.ImageBuildFromServer()
if err != nil {
util.TraceToLog()
panic(err)
}
volumes, err = container.ImageListExposedVolumes()
if err != nil {
util.TraceToLog()
panic(err)
}
fmt.Printf("%v", volumes[0])
GarbageCollector()
Output: /static
func (*ContainerBuilder) ImagePull ¶
func (e *ContainerBuilder) ImagePull() (err error)
ImagePull
English: downloads the image to be mounted. (equivalent to the docker pull image command)
Português: baixa a imagem a ser montada. (equivale ao comando docker pull image)
Example ¶
var err error
GarbageCollector()
// create a network [optional]
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
util.TraceToLog()
panic(err)
}
// create a container
var container = ContainerBuilder{}
// link container and network [optional] (next ip address is 10.0.0.2)
container.SetNetworkDocker(&netDocker)
// set image name for docker pull
container.SetImageName("nats:latest")
// set a container name
container.SetContainerName("container_delete_nats_after_test")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)
// inialize the container object
err = container.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
// image nats:latest pull command [optional]
err = container.ImagePull()
if err != nil {
util.TraceToLog()
panic(err)
}
// container build and start from image nats:latest
// waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container output
// to proceed
err = container.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
panic(err)
}
// container "container_delete_nats_after_test" running and ready for use on this code point on IP 10.0.0.2
// all nats ports are open
// you can use AddPortToExpose("4222"), to open only ports defineds inside code;
// you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port
// 1111;
// you can use SetDoNotOpenContainersPorts() to not open containers ports
GarbageCollector()
// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
util.TraceToLog()
panic(err)
}
func (*ContainerBuilder) ImageRemove ¶
func (e *ContainerBuilder) ImageRemove() (err error)
ImageRemove
English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)
Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)
func (*ContainerBuilder) ImageRemoveByName ¶
func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)
ImageRemoveByName
English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)
name: full image name
Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)
name: nome completo da imagem
func (*ContainerBuilder) Init ¶
func (e *ContainerBuilder) Init() (err error)
Init
English: Initializes the object and should be called only after all settings have been configured
Português: Inicializa o objeto e deve ser chamado apenas depois de toas as configurações serem definidas
func (*ContainerBuilder) MakeDefaultDockerfileForMe ¶
func (e *ContainerBuilder) MakeDefaultDockerfileForMe()
MakeDefaultDockerfileForMe
Similar: MakeDefaultDockerfileForMe(), MakeDefaultDockerfileForMeWithInstallExtras()
English: Automatically mount the Dockerfile-iotmaker inside the target folder.
If there are ports exposed in the configurations, they will be defined automatically and the same goes for volumes, where files shared between the host and the container will expose the folder containing the file inside the container as volume.
Caution: the Dockerfile-iotmaker may be overwritten.
Rules: - For Golang projects, the go.mod file is mandatory;
- The main.go file containing the main package must be at the root folder.
Note: - If you need a dockerfile made for another programming language, see the DockerfileAuto interface and the
SetDockerfileBuilder() function;
- If the image cache is enabled and image cahe is not found, the
MakeDefaultDockerfileForMeWithInstallExtras() function will be used. It will download git, open-ssh and
other tools necessary for the first part of the build in two steps;
- The tools downloaded in the first step of the build and the ssh and git credentials will be discarded,
only the binary generated by Golang will be transferred to the second image.
Português: Monta o arquivo Dockerfile-iotmaker dentro da pasta alvo de forma automática.
Caso haja portas expostas ou volumes nas configurações, as mesmas serão definidas automaticamente, onde arquivos compartilhados entre o host e o container exporá a pasta contendo o arquivo dentro do container como um volume.
Cuidado: o arquivo Dockerfile-iotmaker pode ser sobrescrito.
Regras: - Para projetos Golang, o arquivo go.mod é obrigatório;
- O arquivo main.go contendo o package main deve está na raiz do diretório.
Nota: - Caso necessite de um dockerfile feito para outra linguagem de programação, veja a interface
DockerfileAuto e a função SetDockerfileBuilder();
- Caso a imagem cache esteja habilitada e não seja encontrada, será usada a função
MakeDefaultDockerfileForMeWithInstallExtras(), que baixará git, open-ssh e outras ferramentas necessárias
para a primeira parte do build em duas etapas;
- As ferramentas baixadas na primeira etapa do build e as credenciais ssh e git serão descartadas e apenas o
binário gerado pelo Golang será transferido para a segunda imagem.
func (*ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras ¶ added in v0.5.40
func (e *ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras()
MakeDefaultDockerfileForMeWithInstallExtras
Similar: MakeDefaultDockerfileForMe(), MakeDefaultDockerfileForMeWithInstallExtras()
English: Automatically mount the Dockerfile-iotmaker inside the target folder.
If there are ports exposed in the configurations, they will be defined automatically and the same goes for volumes, where files shared between the host and the container will expose the folder containing the file inside the container as volume.
Caution: the Dockerfile-iotmaker may be overwritten.
Rules: - For Golang projects, the go.mod file is mandatory;
- The main.go file containing the main package must be at the root folder.
Note: - If you need a dockerfile made for another programming language, see the DockerfileAuto interface and the
SetDockerfileBuilder() function;
- The tools downloaded in the first step of the build and the ssh and git credentials will be discarded,
only the binary generated by Golang will be transferred to the second image.
Português: Monta o arquivo Dockerfile-iotmaker dentro da pasta alvo de forma automática.
Caso haja portas expostas ou volumes nas configurações, as mesmas serão definidas automaticamente, onde arquivos compartilhados entre o host e o container exporá a pasta contendo o arquivo dentro do container como um volume.
Cuidado: o arquivo Dockerfile-iotmaker pode ser sobrescrito.
Regras: - Para projetos Golang, o arquivo go.mod é obrigatório;
- O arquivo main.go contendo o package main deve está na raiz do diretório.
Nota: - Caso necessite de um dockerfile feito para outra linguagem de programação, veja a interface
DockerfileAuto e a função SetDockerfileBuilder();
- As ferramentas baixadas na primeira etapa do build e as credenciais ssh e git serão descartadas e apenas o
binário gerado pelo Golang será transferido para a segunda imagem.
func (*ContainerBuilder) NetworkChangeIp ¶ added in v0.9.11
func (e *ContainerBuilder) NetworkChangeIp() (err error)
NetworkChangeIp
English: Change the IP address of the container, to the next IP in the docker network manager list
Output: err: Default object error from golang
Português: Troca o endereço IP do container, para o próximo IP da lista do gerenciador de rede docker
Saída: err: Objeto padrão de erro golang
Example ¶
var err error
var imageInspect types.ImageInspect
// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
var netDocker = &dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
panic(err)
}
// create a network named delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetNetworkDocker(netDocker)
// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)
// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")
// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/doNothing")
// English: Defines the name of the docker container to be created.
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")
// English: Defines the maximum amount of memory to be used by the docker container.
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)
// English: Wait for a textual event on the container's standard output before continuing
// Português: Espera por um evento textual na saída padrão do container antes de continuar
container.SetWaitStringWithTimeout("done!", 15*time.Second)
// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
var containerInspect iotmakerdocker.ContainerInspect
containerInspect, err = container.ContainerInspect()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("IP: %v\n", containerInspect.Network.Networks["delete_after_test"].IPAddress)
err = container.ContainerStop()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
err = container.NetworkChangeIp()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
err = container.ContainerStart()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
containerInspect, err = container.ContainerInspect()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("IP: %v\n", containerInspect.Network.Networks["delete_after_test"].IPAddress)
// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
Output: image size: 1.31 MB image os: linux IP: 10.0.0.2 IP: 10.0.0.3
func (*ContainerBuilder) RemoveAllByNameContains ¶
func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
RemoveAllByNameContains
English: searches for networks, volumes, containers and images that contain the term defined in "value" in the name, and tries to remove them from docker
Português: procura por redes, volumes, container e imagens que contenham o termo definido em "value" no nome, e tenta remover os mesmos do docker
func (*ContainerBuilder) SetBuildFolderPath ¶
func (e *ContainerBuilder) SetBuildFolderPath(value string)
SetBuildFolderPath
English: Defines the path of the folder to be transformed into an image
Input: value: path of the folder to be transformed into an image Note: The folder must contain a dockerfile file, but since different uses can have different dockerfiles, the following order will be given when searching for the file: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" in the root folder; If not found, a recursive search will be done for "Dockerfile" and "dockerfile"; If the project is in golang and the main.go file, containing the package main, is contained in the root folder, with the go.mod file, the MakeDefaultDockerfileForMe() function can be used to use a standard Dockerfile file
Português: Define o caminho da pasta a ser transformada em imagem
Entrada: value: caminho da pasta a ser transformada em imagem Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles, será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta raiz. Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile" Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz, com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo Dockerfile padrão
func (*ContainerBuilder) SetCacheEnable ¶ added in v0.5.40
func (e *ContainerBuilder) SetCacheEnable(value bool)
SetCacheEnable
English: When true, looks for an image named `chache:latest` as a basis for creating new images when the MakeDefaultDockerfileForMe() function is used.
This function is extremely useful when developing new applications, reducing the time to create images with each new test.
Input:
value: true to enable the use of image named cache:latest as the basis for new
images if it exists
Example:
Folder: cache
File: Dockerfile-iotmaker
Need: Image with nats.io drive installed
Content:
FROM golang:1.16-alpine as builder
RUN mkdir -p /root/.ssh/ && \
apk update && \
apk add --no-cache build-base && \
apk add --no-cache alpine-sdk && \
rm -rf /var/cache/apk/*
ARG CGO_ENABLED=0
RUN go get -u github.com/nats-io/nats.go
Code Golang:
var imageCacheName = "cache:latest"
var imageId string
var container = &dockerBuilder.ContainerBuilder{}
imageId, err = container.ImageFindIdByName(imageCacheName)
if err != nil && err.Error() != "image name not found" {
return
}
if imageId != "" {
return
}
container.SetImageName(imageCacheName)
container.SetPrintBuildOnStrOut()
container.SetContainerName(imageCacheName)
container.SetBuildFolderPath("./cache")
err = container.Init()
if err != nil {
return
}
err = container.ImageBuildFromFolder()
if err != nil {
return
}
Português: Quando true, procura por uma imagem de nome `chache:latest` como base para a criação de novas imagens quando a função MakeDefaultDockerfileForMe() é usada.
Esta função é extremamente útil no desenvolvimento de novas aplicações, reduzindo o tempo de criação de imagens a cada novo teste.
Entrada:
value: true para habilitar o uso da imagem de nome cache:latest como base para
novas imagens, caso a mesma exista
Exemplo:
Pasta: cache
Arquivo: Dockerfile-iotmaker
Necessidade: Imagem com o drive do nats.io instalada
Conteúdo:
FROM golang:1.16-alpine as builder
RUN mkdir -p /root/.ssh/ && \
apk update && \
apk add --no-cache build-base && \
apk add --no-cache alpine-sdk && \
rm -rf /var/cache/apk/*
ARG CGO_ENABLED=0
RUN go get -u github.com/nats-io/nats.go
Código Golang:
var imageCacheName = "cache:latest"
var imageId string
var container = &dockerBuilder.ContainerBuilder{}
imageId, err = container.ImageFindIdByName(imageCacheName)
if err != nil && err.Error() != "image name not found" {
return
}
if imageId != "" {
return
}
container.SetImageName(imageCacheName)
container.SetPrintBuildOnStrOut()
container.SetContainerName(imageCacheName)
container.SetBuildFolderPath("./cache")
err = container.Init()
if err != nil {
return
}
err = container.ImageBuildFromFolder()
if err != nil {
return
}
func (*ContainerBuilder) SetContainerAttachStandardStreamsToTty ¶
func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)
SetContainerAttachStandardStreamsToTty
English: attach standard streams to tty
Português: anexa a saída padrão do tty
func (*ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)
SetContainerCommandToRunWhenStartingTheContainer
English: command to run when stating the container (style Dockerfile CMD)
Português: comando a ser executado quando o container inicia (estilo Dockerfile CMD)
func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
SetContainerEntrypointToRunWhenStartingTheContainer
English: entrypoint to run when stating the container
Português: entrypoint a ser executado quando o container inicia
func (*ContainerBuilder) SetContainerHealthcheck ¶
func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)
SetContainerHealthcheck
English: holds configuration settings for the HEALTHCHECK feature.
Test: Test is the test to perform to check that the container is healthy.
An empty slice means to inherit the default.
The options are:
{}: inherit healthcheck
{"NONE"}: disable healthcheck
{"CMD", args...}: exec arguments directly
{"CMD-SHELL", command}: run command with system's default shell
Interval: Interval is the time to wait between checks (Zero means inherit).
Timeout: Timeout is the time to wait before considering the check to have hung (Zero means inherit).
StartPeriod: The start period for the container to initialize before the retries starts to count down
(Zero means inherit).
Retries: Retries is the number of consecutive failures needed to consider a container as unhealthy
(Zero means inherit).
Português: define definições de configuração para o recurso HEALTHCHECK.
Test: Test é o teste a ser executado para testar a saúde do container
se não for definido, herda o teste padrão
As opções são:
{}: herda o teste padrão
{"NONE"}: desabilita o healthcheck
{"CMD", args...}: executa os argumentos diretamente
{"CMD-SHELL", command} : executa o comando com shell padrão do sistema
Interval: intervalo entre testes (zero herda o valor padrão).
Timeout: intervalo de espera antes de considerar o teste com problemas (zero herda o valor padrão).
StartPeriod: tempo de espera pela incialização do container antes dos testes começarem
(zero herda o valor padrão).
Retries: número de testes consecutivos antes de considerar o teste com problemas
(zero herda o valor padrão).
func (*ContainerBuilder) SetContainerName ¶
func (e *ContainerBuilder) SetContainerName(value string)
SetContainerName
English: Defines the name of the container
Input: value: container name
Português: Define o nome do container
Entrada: value: nome do container
func (*ContainerBuilder) SetContainerRestartPolicyAlways ¶
func (e *ContainerBuilder) SetContainerRestartPolicyAlways()
SetContainerRestartPolicyAlways
English: Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted.
Português: Define a política de reinício do container como sempre reinicia o container quando ele para, mesmo quando ele é parado manualmente.
func (*ContainerBuilder) SetContainerRestartPolicyNo ¶
func (e *ContainerBuilder) SetContainerRestartPolicyNo()
SetContainerRestartPolicyNo
English: Do not automatically restart the container. (the default)
Português: Define a política de reinício do container como não reiniciar o container (padrão).
func (*ContainerBuilder) SetContainerRestartPolicyOnFailure ¶
func (e *ContainerBuilder) SetContainerRestartPolicyOnFailure()
SetContainerRestartPolicyOnFailure
English: Restart the container if it exits due to an error, which manifests as a non-zero exit code
Português: Define a política de reinício do container como reinicia o container se houver um erro (com o manifesto informando um código de erro diferente de zero).
func (*ContainerBuilder) SetContainerRestartPolicyUnlessStopped ¶
func (e *ContainerBuilder) SetContainerRestartPolicyUnlessStopped()
SetContainerRestartPolicyUnlessStopped
English: Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
Português: Define a política de reinício do container como sempre reinicia o container, caso ele não tenha sido parado manualmente.
func (*ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint ¶
func (e *ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint(values []string)
SetContainerShellForShellFormOfRunCmdEntrypoint
English: shell for shell-form of run cmd entrypoint
Português: define o terminal (shell) para executar o entrypoint
func (*ContainerBuilder) SetCsvFileReader ¶ added in v0.9.16
func (e *ContainerBuilder) SetCsvFileReader(value bool)
SetCsvFileReader
func (*ContainerBuilder) SetCsvFileRowSeparator ¶ added in v0.9.16
func (e *ContainerBuilder) SetCsvFileRowSeparator(value string)
SetCsvFileRowSeparator
English: Defines the log file line separator, in CSV format, containing container usage statistics.
Input:
value: separador de linha do arquivo CSV (valor padrão: "\n")
Nota: - Esta função é usada em conjunto com as funções SetCsvLogPath(), StartMonitor(), StopMonitor(),
SetCsvFileRowSeparator(), SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog() e
AddFilterToLogWithReplace();
- As colunas de dados preenchidos varia de acordo com o sistema operacional.
Português: Define o separador de linha do arquivo de log, em formato CSV, contendo estatísticas de uso do container.
Entrada:
value: separador de linha do arquivo CSV (valor padrão: "\n")
Nota: - Esta função é usada em conjunto com as funções SetCsvLogPath(), StartMonitor(), StopMonitor(),
SetCsvFileRowSeparator(), SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog() e
AddFilterToLogWithReplace();
- As colunas de dados preenchidos varia de acordo com o sistema operacional.
func (*ContainerBuilder) SetCsvFileRowsToPrint ¶ added in v0.9.16
func (e *ContainerBuilder) SetCsvFileRowsToPrint(value int64)
SetCsvFileRowsToPrint
Português: Define quais colunas vão ser impressas no log, na forma de arquivo CSV, com informações de desempenho do container, com indicadores de consumo de memória e tempos de acesso.
Entrada:
value: Lista das colunas impressas no arquivo CSV. Ex.: KLogColumnMacOs, KLogColumnWindows, KLogColumnAll ou qualquer combinação de KLogColumn... concatenado com pipe, KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | KLogColumnTotalCPUTimeConsumed
Nota: - Para vê a lista completa de colunas, use SetCsvFileRowsToPrint(KLogColumnAll) e SetCsvFileReader(true).
Isto irá imprimir os nomes das constantes em cima de cada coluna do log.
Example ¶
var err error
GarbageCollector()
var container = ContainerBuilder{}
// imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// caso exista uma imagem de nome cache:latest, ela será usada como base para criar o container
container.SetCacheEnable(true)
// monta um dockerfile padrão para o golang onde o arquivo main.go e o arquivo go.mod devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// new image name delete:latest
container.SetImageName("delete:latest")
// set a folder path to make a new image
container.SetBuildFolderPath("./test/counter")
// container name container_delete_server_after_test
container.SetContainerName("container_counter_delete_after_test")
// define o limite de memória
container.SetImageBuildOptionsMemory(100 * KMegaByte)
container.SetCsvLogPath("./test.counter.log.36.csv", true)
container.AddFilterToLog(
"contador",
"counter",
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
)
container.AddFilterToSuccess(
"done!",
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
container.AddFilterToFail(
"counter: 40",
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
container.SetCsvFileRowsToPrint(KLogColumnAll)
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
_, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
container.StartMonitor()
event := container.GetChaosEvent()
for {
var end = false
select {
case e := <-event:
if e.Done == true || e.Fail == true || e.Error == true {
end = true
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
log.Printf("message: %v\n", e.Message)
break
}
}
if end == true {
break
}
}
err = container.StopMonitor()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
GarbageCollector()
Output: container name: container_counter_delete_after_test done: true fail: false error: false
func (*ContainerBuilder) SetCsvFileValueSeparator ¶ added in v0.9.16
func (e *ContainerBuilder) SetCsvFileValueSeparator(value string)
SetCsvFileValueSeparator
English: Defines the column separator of the log file, in CSV format, containing container usage statistics.
Input:
value: CSV file column separator (default value: ",")
Note: - This function is used in conjunction with the SetCsvLogPath(), StartMonitor(), StopMonitor(),
SetCsvFileRowSeparator(), SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog() and
AddFilterToLogWithReplace() functions;
- The data columns populated varies by operating system.
Português: Define o separador de coluna do arquivo de log, em formato CSV, contendo estatísticas de uso do container.
Entrada:
value: separador de coluna do arquivo CSV (valor padrão: ",")
Nota: - Esta função é usada em conjunto com as funções SetCsvLogPath(), StartMonitor(), StopMonitor(),
SetCsvFileRowSeparator(), SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog() e
AddFilterToLogWithReplace();
- As colunas de dados preenchidos varia de acordo com o sistema operacional.
func (*ContainerBuilder) SetCsvLogPath ¶ added in v0.9.34
func (e *ContainerBuilder) SetCsvLogPath(path string, removeOldFile bool)
SetCsvLogPath
English: Defines the log file path, in CSV format, containing container usage statistics.
Input:
path: Log file path.
removeOldFile: true deletes the file if it exists; false adds more records to the existing file.
Note: - This function must be used in conjunction with the StartMonitor() and StopMonitor() functions;
- The data columns populated varies by operating system;
- See the SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog(), AddFilterToLogWithReplace(),
SetCsvFileValueSeparator() and SetCsvFileRowSeparator() functions to change some log settings.
Português: Define o caminho do arquivo de log, em formato CSV, contendo estatísticas de uso do container.
Entrada:
path: Caminho do arquivo de log.
removeOldFile: true apaga o arquivo caso o mesmo exista; false adiciona mais registros ao arquivo existente.
Nota: - Esta função deve ser usada em conjunto com as funções StartMonitor() e StopMonitor();
- As colunas de dados preenchidos varia de acordo com o sistema operacional;
- Veja as funções SetCsvFileReader(), SetCsvFileRowsToPrint(), AddFilterToLog(), AddFilterToLogWithReplace(),
SetCsvFileValueSeparator() e SetCsvFileRowSeparator() para alterar algumas configurações do log.
Example ¶
var err error
var imageInspect types.ImageInspect
GarbageCollector()
var container = ContainerBuilder{}
// imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// caso exista uma imagem de nome cache:latest, ela será usada como base para criar o container
container.SetCacheEnable(true)
// monta um dockerfile padrão para o golang onde o arquivo main.go e o arquivo go.mod devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// new image name delete:latest
container.SetImageName("delete:latest")
// set a folder path to make a new image
container.SetBuildFolderPath("./test/counter")
// container name container_delete_server_after_test
container.SetContainerName("container_counter_delete_after_test")
// define o limite de memória
container.SetImageBuildOptionsMemory(100 * KMegaByte)
container.SetCsvLogPath("./test.counter.log.csv", true)
container.SetCsvFileValueSeparator("\t")
container.AddFilterToLogWithReplace(
"contador",
"counter",
"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
"\\.",
",",
)
container.AddFilterToSuccess(
"done!",
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
"${value}",
)
container.AddFilterToFail(
"counter: 40",
"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)
err = container.Init()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
fmt.Printf("error: %v", err.Error())
GarbageCollector()
return
}
fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)
err = container.ContainerBuildAndStartFromImage()
if err != nil {
log.Printf("error: %v", err.Error())
GarbageCollector()
return
}
container.StartMonitor()
event := container.GetChaosEvent()
select {
case e := <-event:
fmt.Printf("container name: %v\n", e.ContainerName)
fmt.Printf("done: %v\n", e.Done)
fmt.Printf("fail: %v\n", e.Fail)
fmt.Printf("error: %v\n", e.Error)
fmt.Printf("message: %v\n", e.Message)
}
container.StopMonitor()
GarbageCollector()
Output: image size: 1.38 MB image os: linux container name: container_counter_delete_after_test done: true fail: false error: false message: done!
func (*ContainerBuilder) SetDockerfileBuilder ¶ added in v0.5.11
func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)
SetDockerfileBuilder
English: Defines a new object containing the builder of the dockerfile.
Note: see the DockerfileAuto interface for further instructions.
Português: Define um novo objeto contendo o construtor do arquivo dockerfile.
Nota: veja a interface DockerfileAuto para mais instruções.
func (*ContainerBuilder) SetEnvironmentVar ¶
func (e *ContainerBuilder) SetEnvironmentVar(value []string)
SetEnvironmentVar
English: Defines environment variables
value: slice of string containing one environment variable per key
Português: Define as variáveis de ambiente
value: slice de string contendo um variável de ambiente por chave
Example ¶
var err error
GarbageCollector()
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
panic(err)
}
// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
panic(err)
}
// At this point in the code, the network has been created and is ready for use
var mongoDocker = &ContainerBuilder{}
// set a docker network
//mongoDocker.SetNetworkDocker(&netDocker)
// set an image name
mongoDocker.SetImageName("mongo:latest")
// set a container name
mongoDocker.SetContainerName("container_delete_mongo_after_test")
// set a port to expose
mongoDocker.AddPortToExpose("27017")
// se a environment var list
mongoDocker.SetEnvironmentVar(
[]string{
"--host 0.0.0.0",
},
)
// set a MongoDB data dir to ./test/data
//err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
if err != nil {
panic(err)
}
// set a text indicating for container ready for use
mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)
// inicialize the object before sets
err = mongoDocker.Init()
if err != nil {
panic(err)
}
// build a container
err = mongoDocker.ContainerBuildAndStartFromImage()
if err != nil {
panic(err)
}
// Output:
//
// At this point, the MongoDB is ready for use on port 27017
// Stop and delete the container
// GarbageCollector()
func (*ContainerBuilder) SetGitCloneToBuild ¶
func (e *ContainerBuilder) SetGitCloneToBuild(url string)
SetGitCloneToBuild
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
Example ¶
var err error
GarbageCollector()
var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)
// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")
// replace container folder /static to host folder ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
panic(err)
}
// inicialize container object
err = container.Init()
if err != nil {
panic(err)
}
// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
panic(err)
}
// build a new container from image
err = container.ContainerBuildAndStartFromImage()
if err != nil {
panic(err)
}
// At this point, the container is ready for use on port 3030
// Stop and delete the container
GarbageCollector()
func (*ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password string)
SetGitCloneToBuildWithPrivateSSHKey
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project
privateSSHKeyPath: this is the path of the private ssh key compatible with the public key registered in git
password: password used when the ssh key was generated or empty string
Note:
If the repository is private and the host computer has access to the git server, use
SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
~/.gitconfig automatically;
To be able to access private repositories from inside the container, build the image in two or more steps
and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
file to the /root folder;
The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
SetSshIdRsaFile() to define the files manually;
This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
generate an image from the contents of a git repository;
The repository must contain a Dockerfile file and it will be searched for in the following order:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
and '.*dockerfile.*';
The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var privateSSHKeyPath string
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa")
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password)
container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto
privateSSHKeyPath: este é o caminho da chave ssh privada compatível com a chave pública cadastrada no git
password: senha usada no momento que a chave ssh foi gerada ou string em branco
Nota:
Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
~/.gitconfig de forma automática;
Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
para a pasta /root/;
A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
da mesma;
Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual;
Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
imagem a partir do conteúdo de um repositório git;
O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
e '.*dockerfile.*';
O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var privateSSHKeyPath string
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa")
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password)
container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitCloneToBuildWithPrivateToken ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)
SetGitCloneToBuildWithPrivateToken
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project
privateToken: token defined on your git tool portal
Note:
If the repository is private and the host computer has access to the git server, use
SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
~/.gitconfig automatically;
To be able to access private repositories from inside the container, build the image in two or more steps
and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
file to the /root folder;
The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
SetSshIdRsaFile() to define the files manually;
This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
generate an image from the contents of a git repository;
The repository must contain a Dockerfile file and it will be searched for in the following order:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
and '.*dockerfile.*';
The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto
privateToken: token definido no portal da sua ferramenta git
Nota:
Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
~/.gitconfig de forma automática;
Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
para a pasta /root/;
A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
da mesma;
Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual;
Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
imagem a partir do conteúdo de um repositório git;
O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
e '.*dockerfile.*';
O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitCloneToBuildWithUserPassworh ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)
SetGitCloneToBuildWithUserPassworh
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project
user: git user
password: git password
Note:
If the repository is private and the host computer has access to the git server, use
SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
~/.gitconfig automatically;
To be able to access private repositories from inside the container, build the image in two or more steps
and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
file to the /root folder;
The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
SetSshIdRsaFile() to define the files manually;
This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
generate an image from the contents of a git repository;
The repository must contain a Dockerfile file and it will be searched for in the following order:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
and '.*dockerfile.*';
The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto
user: git user
password: git password
Nota:
Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
~/.gitconfig de forma automática;
Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
para a pasta /root/;
A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
da mesma;
Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual;
Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
imagem a partir do conteúdo de um repositório git;
O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
e '.*dockerfile.*';
O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
code:
var err error
var usr *user.User
var userGitConfigPath string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(userGitConfigPath)
var container = ContainerBuilder{}
container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitConfigFile ¶
func (e *ContainerBuilder) SetGitConfigFile(value string)
SetGitConfigFile
English: Defines the contents of the .gitconfig file
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetGitConfigFile(string(file))
Português: Define o conteúdo do arquivo .gitconfig
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitPathPrivateRepository ¶
func (e *ContainerBuilder) SetGitPathPrivateRepository(value string)
SetGitPathPrivateRepository
English: path do private repository defined in "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
Example: github.com/helmutkemper
Português: caminho do repositório privado definido em "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
Exemplo: github.com/helmutkemper
func (*ContainerBuilder) SetGitSshPassword ¶
func (e *ContainerBuilder) SetGitSshPassword(password string)
SetGitSshPassword
English: Sets the password for the ssh key for private git repositories.
Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
Português: Define a senha da chave ssh para repositórios git privados.
Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
func (*ContainerBuilder) SetImageBuildOptionsCPUPeriod ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUPeriod(value int64)
SetImageBuildOptionsCPUPeriod
English: Specify the CPU CFS scheduler period, which is used alongside --cpu-quota. Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the default. For most use-cases, --cpus is a more convenient alternative.
Português: Especifique o período do agendador CFS da CPU, que é usado junto com --cpu-quota. O padrão é 100.000 microssegundos (100 milissegundos). A maioria dos usuários não altera o padrão. Para a maioria dos casos de uso, --cpus é uma alternativa mais conveniente.
func (*ContainerBuilder) SetImageBuildOptionsCPUQuota ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUQuota(value int64)
SetImageBuildOptionsCPUQuota
English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles.
This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.
Português: Defina este flag para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina hospedeira.
Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os containeres usam a quantidade de CPU de que precisam. Dessa forma, é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.
func (*ContainerBuilder) SetImageBuildOptionsCPUSetCPUs ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUSetCPUs(value string)
SetImageBuildOptionsCPUSetCPUs
English: Limit the specific CPUs or cores a container can use.
A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU.
The first CPU is numbered 0.
A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).
Português: Limite a quantidade de CPUs ou núcleos específicos que um container pode usar.
Uma lista separada por vírgulas ou intervalo separado por hífen de CPUs que um container pode usar, se você tiver mais de uma CPU.
A primeira CPU é numerada como 0.
Um valor válido pode ser 0-3 (para usar a primeira, segunda, terceira e quarta CPU) ou 1,3 (para usar a segunda e a quarta CPU).
func (*ContainerBuilder) SetImageBuildOptionsCPUSetMems ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUSetMems(value string)
SetImageBuildOptionsCPUSetMems
English: Define a memory nodes (MEMs) (--cpuset-mems)
--cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
If you have four memory nodes on your system (0-3), use --cpuset-mems=0,1 then processes in your Docker container will only use memory from the first two memory nodes.
Português: Define memory node (MEMs) (--cpuset-mems)
--cpuset-mems="" Memory nodes (MEMs) no qual permitir a execução (0-3, 0,1). Só funciona em sistemas NUMA.
Se você tiver quatro nodes de memória em seu sistema (0-3), use --cpuset-mems=0,1 então, os processos em seu container do Docker usarão apenas a memória dos dois primeiros nodes.
func (*ContainerBuilder) SetImageBuildOptionsCPUShares ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUShares(value int64)
SetImageBuildOptionsCPUShares
English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles. This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.
Português: Defina este sinalizador para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina host. Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os container usam a quantidade de CPU de que precisam. Dessa forma, este é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.
func (*ContainerBuilder) SetImageBuildOptionsCacheFrom ¶
func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)
SetImageBuildOptionsCacheFrom
English: specifies images that are used for matching cache. Images specified here do not need to have a valid parent chain to match cache.
Português: especifica imagens que são usadas para correspondência de cache. As imagens especificadas aqui não precisam ter uma cadeia pai válida para corresponder a cache.
func (*ContainerBuilder) SetImageBuildOptionsExtraHosts ¶
func (e *ContainerBuilder) SetImageBuildOptionsExtraHosts(values []string)
SetImageBuildOptionsExtraHosts
English: Add hostname mappings at build-time. Use the same values as the docker client --add-host parameter.
values: somehost:162.242.195.82 otherhost:50.31.209.229 An entry with the ip address and hostname is created in /etc/hosts inside containers for this build, e.g: 162.242.195.82 somehost 50.31.209.229 otherhost
Português): Adiciona itens ao mapa de hostname durante o processo de construção da imagem. Use os mesmos valores que em docker client --add-host parameter.
values: somehost:162.242.195.82 otherhost:50.31.209.229 Uma nova entrada com o endereço ip e hostname será criada dentro de /etc/hosts do container. Exemplo: 162.242.195.82 somehost 50.31.209.229 otherhost
func (*ContainerBuilder) SetImageBuildOptionsIsolationDefault ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationDefault()
SetImageBuildOptionsIsolationDefault
English: Set default isolation mode on current daemon
Português: Define o método de isolamento do processo como sendo o mesmo do deamon
func (*ContainerBuilder) SetImageBuildOptionsIsolationHyperV ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()
SetImageBuildOptionsIsolationHyperV
English: Set HyperV isolation mode
Português: Define o método de isolamento como sendo HyperV
func (*ContainerBuilder) SetImageBuildOptionsIsolationProcess ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()
SetImageBuildOptionsIsolationProcess
English: Set process isolation mode
Português: Determina o método de isolamento do processo
func (*ContainerBuilder) SetImageBuildOptionsMemory ¶
func (e *ContainerBuilder) SetImageBuildOptionsMemory(value int64)
SetImageBuildOptionsMemory
English: The maximum amount of memory the container can use. If you set this option, the minimum allowed value is 4 * 1024 * 1024 (4 megabyte).
Input: value: amount of memory in bytes Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
Português: Memória máxima total que o container pode usar. Se você vai usar esta opção, o máximo permitido é 4 * 1024 * 1024 (4 megabyte)
Entrada: value: Quantidade de memória em bytes Use value * KKiloByte, value * KMegaByte e value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
func (*ContainerBuilder) SetImageBuildOptionsMemorySwap ¶
func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)
SetImageBuildOptionsMemorySwap
English: Set memory swap (--memory-swap)
Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
Português: habilita a opção memory swp
Use value * KKiloByte, value * KMegaByte e value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
func (*ContainerBuilder) SetImageBuildOptionsNoCache ¶
func (e *ContainerBuilder) SetImageBuildOptionsNoCache()
SetImageBuildOptionsNoCache
English: Set image build no cache
Português: Define a opção `sem cache` para a construção da imagem
func (*ContainerBuilder) SetImageBuildOptionsPlatform ¶
func (e *ContainerBuilder) SetImageBuildOptionsPlatform(value string)
SetImageBuildOptionsPlatform
English: Target platform containers for this service will run on, using the os[/arch[/variant]] syntax, e.g.
osx windows/amd64 linux/arm64/v8
Português: Especifica a plataforma de container onde o serviço vai rodar, usando a sintaxe os[/arch[/variant]]
osx windows/amd64 linux/arm64/v8
func (*ContainerBuilder) SetImageBuildOptionsSecurityOpt ¶
func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)
SetImageBuildOptionsSecurityOpt
English: Set the container security options
label=user:USER — Set the label user for the container label=role:ROLE — Set the label role for the container label=type:TYPE — Set the label type for the container label=level:LEVEL — Set the label level for the container label=disable — Turn off label confinement for the container apparmor=PROFILE — Set the apparmor profile to be applied to the container no-new-privileges:true — Disable container processes from gaining new privileges seccomp=unconfined — Turn off seccomp confinement for the container seccomp=profile.json — White-listed syscalls seccomp Json file to be used as a seccomp filter
Português: Modifica as opções de segurança do container
label=user:USER — Determina o rótulo user para o container label=role:ROLE — Determina o rótulo role para o container label=type:TYPE — Determina o rótulo type para o container label=level:LEVEL — Determina o rótulo level para o container label=disable — Desliga o confinamento do rótulo para o container apparmor=PROFILE — Habilita o perfil definido pelo apparmor do linux para ser definido ao container no-new-privileges:true — Impede o processo do container a ganhar novos privilégios seccomp=unconfined — Desliga o confinamento causado pelo seccomp do linux ao container seccomp=profile.json — White-listed syscalls seccomp Json file to be used as a seccomp filter
func (*ContainerBuilder) SetImageBuildOptionsSquash ¶
func (e *ContainerBuilder) SetImageBuildOptionsSquash(value bool)
SetImageBuildOptionsSquash
English: squash the resulting image's layers to the parent preserves the original image and creates a new one from the parent with all the changes applied to a single layer
Português: Usa o conteúdo dos layers da imagem pai para criar uma imagem nova, preservando a imagem pai, e aplica todas as mudanças a um novo layer
func (*ContainerBuilder) SetImageBuildOptionsTarget ¶
func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)
SetImageBuildOptionsTarget
English: Build the specified stage as defined inside the Dockerfile. See the multi-stage build docs for details.
See https://docs.docker.com/develop/develop-images/multistage-build/
Português: Monta o container a partir do estágio definido no arquivo Dockerfile. Veja a documentação de múltiplos estágios para mais detalhes.
See https://docs.docker.com/develop/develop-images/multistage-build/
func (*ContainerBuilder) SetImageCacheName ¶ added in v0.5.40
func (e *ContainerBuilder) SetImageCacheName(name string)
func (*ContainerBuilder) SetImageExpirationTime ¶ added in v0.9.12
func (e *ContainerBuilder) SetImageExpirationTime(expiration time.Duration)
SetImageExpirationTime
English: Sets image validity time, preventing image build more than once within a certain period of time.
Input:
expiration: Image expiration time
Note: - This feature prevents creation of the same image when the test uses loops to generate multiple containers
from the same image.
Português: Define o tempo de validade da imagem, evitando o build da imagem mais de uma vez dentro de um certo período de tempo.
Entrada:
expiration: Tempo de validade da imagem
Nota: - Esta funcionalidade impede a criação da mesma imagem quando o teste usa laços para gerar vários containers
da mesma imagem.
func (*ContainerBuilder) SetImageName ¶
func (e *ContainerBuilder) SetImageName(value string)
SetImageName
English: Defines the name of the image to be used or created
Input: value: name of the image to be downloaded or created Note: - the image name must have the version tag. E.g.: name:latest
Português: Define o nome da imagem a ser usada ou criada
Entrada: value: noma da imagem a ser baixada ou criada Nota: - o nome da imagem deve ter a tag de versão. Ex.: nome:latest
func (*ContainerBuilder) SetInspectInterval ¶
func (e *ContainerBuilder) SetInspectInterval(value time.Duration)
SetInspectInterval
English: Defines the container's monitoring interval [optional]
value: time interval between container inspection events Note: This function has a high computational cost and should be used sparingly. The captured values are presented by GetLastInspect() and GetChannelOnContainerInspect()
Português: Define o intervalo de monitoramento do container [opcional]
value: intervalo de tempo entre os eventos de inspeção do container Nota: Esta função tem um custo computacional elevado e deve ser usada com moderação. Os valores capturados são apresentados por GetLastInspect() e GetChannelOnContainerInspect()
func (*ContainerBuilder) SetMetadata ¶ added in v0.9.25
func (e *ContainerBuilder) SetMetadata(metadata map[string]interface{})
SetMetadata
English: Sets a list of user-defined data
Input:
metadata: map[string]interface{} with user defined data
Português: Define uma lista de dados definidos pelo usuário
Entrada:
metadata: map[string]interface{} com dados definidos oelo usuário
func (*ContainerBuilder) SetNetworkDocker ¶
func (e *ContainerBuilder) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
SetNetworkDocker
English: Sets the docker network manager pointer
network: pointer to the network manager object.
Note: compatible with dockerBuilderNetwork.ContainerBuilderNetwork{} object
Português: Define o ponteiro do gerenciador de rede docker
network: ponteiro para o objeto gerenciador de rede.
Nota: compatível com o objeto dockerBuilderNetwork.ContainerBuilderNetwork{}
Example ¶
var err error
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
panic(err)
}
// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
panic(err)
}
// At this point in the code, the network has been created and is ready for use
var mongoDocker = &ContainerBuilder{}
// set a docker network
mongoDocker.SetNetworkDocker(&netDocker)
// set an image name
mongoDocker.SetImageName("mongo:latest")
// set a container name
mongoDocker.SetContainerName("container_delete_mongo_after_test")
// set a port to expose
mongoDocker.AddPortToExpose("27017")
// se a environment var list
mongoDocker.SetEnvironmentVar(
[]string{
"--host 0.0.0.0",
},
)
// set a MongoDB data dir to ./test/data
err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
if err != nil {
panic(err)
}
// set a text indicating for container ready for use
mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)
// inicialize the object before sets
err = mongoDocker.Init()
if err != nil {
panic(err)
}
// build a container
err = mongoDocker.ContainerBuildAndStartFromImage()
if err != nil {
panic(err)
}
// At this point, the MongoDB is ready for use on port 27017
// Stop and delete the container
GarbageCollector()
func (*ContainerBuilder) SetOnBuild ¶ added in v0.5.40
func (e *ContainerBuilder) SetOnBuild(onBuild []string)
SetOnBuild (english): Adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build.
The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.
Any build instruction can be registered as a trigger.
This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration.
For example, if your image is a reusable Python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called after that. You can’t just call ADD and RUN now, because you don’t yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate Dockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code.
The solution is to use ONBUILD to register advance instructions to run later, during the next build stage.
Here’s how it works:
When it encounters an OnBuild instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. At the end of the build, a list of all triggers is stored in the image manifest, under the key OnBuild. They can be inspected with the docker inspect command. Later the image may be used as a base for a new build, using the FROM instruction. As part of processing the FROM instruction, the downstream builder looks for OnBuild triggers, and executes them in the same order they were registered. If any of the triggers fail, the FROM instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual. Triggers are cleared from the final image after being executed. In other words they are not inherited by “grand-children” builds.
For example you might add something like this:
[]string{
"ADD . /app/src",
"RUN /usr/local/bin/python-build --dir /app/src",
}
Warning:
The ONBUILD instruction may not trigger FROM or MAINTAINER instructions.
https://docs.docker.com/engine/reference/builder/#onbuild
SetOnBuild (português): Adiciona à imagem uma instrução de gatilho a ser executada posteriormente, quando a imagem for usada como base para outra construção.
O gatilho será executado no contexto do downstream build , como se tivesse sido inserido imediatamente após a instrução FROM no downstream Dockerfile.
Qualquer instrução de construção pode ser registrada como um gatilho.
Isso é útil se você estiver construindo uma imagem que será usada como base para construir outras imagens, por exemplo, um ambiente de construção de aplicativo ou um daemon que pode ser personalizado com configuração específica do usuário.
Por exemplo, se sua imagem for um construtor de aplicativo Python reutilizável, ela exigirá que o código-fonte do aplicativo seja adicionado em um diretório específico e pode exigir que um script de construção seja chamado depois disso. Você não pode simplesmente chamar ADD e RUN agora, porque você ainda não tem acesso ao código-fonte do aplicativo e será diferente para cada construção de aplicativo. Você poderia simplesmente fornecer aos desenvolvedores de aplicativos um Dockerfile padrão para copiar e colar em seus aplicativos, mas isso é ineficiente, sujeito a erros e difícil de atualizar porque se mistura com o código específico do aplicativo.
A solução é usar o OnBuild para registrar instruções antecipadas para executar mais tarde, durante o próximo estágio de compilação.
Funciona assim:
Ao encontrar uma instrução OnBuild, o construtor adiciona um gatilho aos metadados da imagem que está sendo construída. A instrução não afeta de outra forma a construção atual. No final da construção, uma lista de todos os gatilhos é armazenada no manifesto da imagem, sob a chave OnBuild. Eles podem ser inspecionados com o comando docker inspect. Posteriormente, a imagem pode ser usada como base para uma nova construção, usando a instrução FROM. Como parte do processamento da instrução FROM, o downstream builder procura gatilhos OnBuild e os executa na mesma ordem em que foram registrados. Se qualquer um dos gatilhos falhar, a instrução FROM é abortada, o que, por sua vez, faz com que o build falhe. Se todos os gatilhos forem bem-sucedidos, a instrução FROM será concluída e a construção continuará normalmente. Os gatilhos são apagados da imagem final após serem executados. Em outras palavras, eles não são herdados por construções de "netos".
Por exemplo, você pode adicionar algo assim:
[]string{
"ADD . /app/src",
"RUN /usr/local/bin/python-build --dir /app/src",
}
Atenção:
A instrução ONBUILD não pode disparar as instruções FROM ou MAINTAINER.
func (*ContainerBuilder) SetOpenAllContainersPorts ¶
func (e *ContainerBuilder) SetOpenAllContainersPorts()
SetOpenAllContainersPorts
English: Automatically exposes all ports listed in the image used to generate the container
Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose(); By default, all doors are closed; The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português: Expõe automaticamente todas as portas listadas na imagem usada para gerar o container
Nota: As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas; A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
func (*ContainerBuilder) SetPrintBuildOnStrOut ¶ added in v0.5.10
func (e *ContainerBuilder) SetPrintBuildOnStrOut()
SetPrintBuildOnStrOut
English: Prints the standard output used when building the image or the container to the standard output of the log.
Português: Imprime a saída padrão usada durante a construção da imagem ou do container no log.
func (*ContainerBuilder) SetPrivateRepositoryAutoConfig ¶
func (e *ContainerBuilder) SetPrivateRepositoryAutoConfig() (err error)
SetPrivateRepositoryAutoConfig
English: Copies the ssh ~/.ssh/id_rsa file and the ~/.gitconfig file to the SSH_ID_RSA_FILE and GITCONFIG_FILE variables.
Português: Copia o arquivo ssh ~/.ssh/id_rsa e o arquivo ~/.gitconfig para as variáveis SSH_ID_RSA_FILE e GITCONFIG_FILE.
func (*ContainerBuilder) SetRestartProbability ¶ added in v0.9.11
func (e *ContainerBuilder) SetRestartProbability(restartProbability, restartChangeIpProbability float64, limit int)
func (*ContainerBuilder) SetSceneNameOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetSceneNameOnChaosScene(name string)
SetSceneNameOnChaosScene
English:
Adds the container to a scene Scenes help control the maximum amount of container stopped or paused at the same time
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Adiciona o container a uma cena Cenas ajudam a controlar a quantidade máxima de container parados ou pausados ao mesmo tempo
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetSshIdRsaFile ¶
func (e *ContainerBuilder) SetSshIdRsaFile(value string)
SetSshIdRsaFile
English: Set a id_rsa file from shh
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetSshIdRsaFile(string(file))
Português: Define o arquivo id_rsa do shh
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetSshIdRsaFile(string(file))
func (*ContainerBuilder) SetSshKnownHostsFile ¶
func (e *ContainerBuilder) SetSshKnownHostsFile(value string)
SetSshKnownHostsFile
English: set a sseh knownhosts file
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetSshKnownHostsFile(string(file))
Português: define o arquivo knownhosts do ssh
var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
panic(err)
}
path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts")
file, err = ioutil.ReadFile(path)
if err != nil {
panic(err)
}
var container = ContainerBuilder{}
container.SetSshKnownHostsFile(string(file))
func (*ContainerBuilder) SetTimeBeforeStartChaosInThisContainerOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetTimeBeforeStartChaosInThisContainerOnChaosScene(min, max time.Duration)
SetTimeBeforeStartChaosInThisContainerOnChaosScene
English:
Defines the minimum and maximum waiting times before enabling the restart of containers in a chaos scenario The choice of time will be made randomly between the minimum and maximum values Input: min: minimum waiting time max: maximum wait time
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define os tempos mínimo e máximos de espera antes de habilitar o reinício dos containers em um cenário de caos A escolha do tempo será feita de forma aleatória entre os valores mínimo e máximo Entrada: min: tempo de espera mínimo max: tempo de espera máximo
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetTimeOnContainerPausedStateOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetTimeOnContainerPausedStateOnChaosScene(min, max time.Duration)
SetTimeOnContainerPausedStateOnChaosScene
English:
Sets the minimum and maximum times for the container pause Input: min: minimum time for container pause max: maximum time for container pause
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define os tempos mínimos e máximos para a pausa do container Entrada: min: tempo mínimo para a pausa do container max: tempo máximo para a pausa do container
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetTimeOnContainerUnpausedStateOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetTimeOnContainerUnpausedStateOnChaosScene(min, max time.Duration)
SetTimeOnContainerUnpausedStateOnChaosScene
English:
Defines the minimum and maximum times where the container is kept out of the paused state Input: min: minimum time out of sleep state max: maximum time out of sleep state
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define os tempos mínimos e máximos onde o container é mantido fora do estado de pausa Entrada: min: tempo mínimo fora do estado de pausa max: tempo máximo fora do estado de pausa
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetTimeToRestartThisContainerAfterStopEventOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetTimeToRestartThisContainerAfterStopEventOnChaosScene(min, max time.Duration)
SetTimeToRestartThisContainerAfterStopEventOnChaosScene
English
Defines the minimum and maximum times to restart the container after the container stop event. Input: min: minimum timeout before restarting container max: maximum timeout before restarting container
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Define os tempos mínimos e máximos para reiniciar o container após o evento de parar container. Entrada: min: tempo mínimo de espera antes de reiniciar o container max: tempo máximo de espera antes de reiniciar o container
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetTimeToStartChaosOnChaosScene ¶ added in v0.9.41
func (e *ContainerBuilder) SetTimeToStartChaosOnChaosScene(min, max time.Duration)
SetTimeToStartChaosOnChaosScene
English:
This function sets a timeout before the chaos test starts, when indicator text is encountered in the standard output. Input: min: minimum waiting time until chaos test starts max: maximum waiting time until chaos test starts
Basically, the idea is that you put at some point in the test a text like, chaos can be initialized, in the container's standard output and the time gives a random character to when the chaos starts.
Note:
The following functions are used together during chaos testing: [optional] iotmakerdockerbuilder.ConfigChaosScene()
Mandatory set: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [optional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
Português:
Esta função define um tempo de espera antes do teste de caos começar, quando o texto indicador é incontrado na saída padrão. Entrada: min: tempo mínimo de espera até o teste de caos começar max: tempo máximo de espera até o teste de caos começar
Basicamente, a ideia é que você coloque em algum ponto do teste um texto tipo, caos pode ser inicializado, na saída padrão do container e o tempo dá um caráter aleatório a quando o caos começa.
Nota:
As funções a seguir são usadas em conjunto durante o teste de caos: [opcional] iotmakerdockerbuilder.ConfigChaosScene()
Conjunto obrigatório: ContainerBuilder.EnableChaosScene() ContainerBuilder.SetTimeOnContainerUnpausedStateOnChaosScene() ContainerBuilder.SetTimeToStartChaosOnChaosScene() ContainerBuilder.SetTimeToRestartThisContainerAfterStopEventOnChaosScene() ContainerBuilder.SetTimeOnContainerPausedStateOnChaosScene() ContainerBuilder.SetTimeBeforeStartChaosInThisContainerOnChaosScene() ContainerBuilder.SetSceneNameOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabePauseOnChaosScene() [opcional] ContainerBuilder.ContainerSetDisabeStopOnChaosScene()
func (*ContainerBuilder) SetWaitString ¶
func (e *ContainerBuilder) SetWaitString(value string)
SetWaitString
English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use
value: searched text
Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso
value: texto procurado
func (*ContainerBuilder) SetWaitStringWithTimeout ¶
func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)
SetWaitStringWithTimeout
English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use
value: text emitted to default output reporting by an expected event timeout: maximum waiting time
Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso
value: texto emitido na saída padrão informando por um evento esperado timeout: tempo máximo de espera
func (*ContainerBuilder) SizeToString ¶ added in v0.9.11
func (e *ContainerBuilder) SizeToString(value int64) string
func (*ContainerBuilder) StartMonitor ¶ added in v0.9.11
func (e *ContainerBuilder) StartMonitor()
StartMonitor
Português: Habilitar um time.Ticker com a finalidade de colher informações de desempenho do container na forma de um log CSV e gerencia o controle de caos, caso o mesmo tenha sido habilitado.
Nota: - Esta função é usada em conjunto com as funções EnableChaosScene() e SetCsvLogPath()
English: Enable a time.Ticker in order to gather performance information from the container in the form of a CSV log and manage chaos control, if it has been enabled.
Nota: - Esta função é usada em conjunto com as funções EnableChaosScene() e SetCsvLogPath()
func (*ContainerBuilder) StopMonitor ¶ added in v0.9.11
func (e *ContainerBuilder) StopMonitor() (err error)
func (ContainerBuilder) TestDockerInstall ¶ added in v0.9.36
func (e ContainerBuilder) TestDockerInstall() (err error)
func (*ContainerBuilder) WaitForTextInContainerLog ¶
func (e *ContainerBuilder) WaitForTextInContainerLog(value string) (dockerLogs string, err error)
WaitForTextInContainerLog
English: Wait for the text to appear in the container's default output
value: searched text
Português: Espera pelo texto aparecer na saída padrão do container
value: texto procurado
func (*ContainerBuilder) WaitForTextInContainerLogWithTimeout ¶
func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)
WaitForTextInContainerLogWithTimeout
English: Wait for the text to appear in the container's default output
value: searched text timeout: wait timeout
Português: Espera pelo texto aparecer na saída padrão do container
value: texto procurado timeout: tempo limite de espera
type DockerfileAuto ¶
type DockerfileAuto interface {
MountDefaultDockerfile(args map[string]*string, changePorts []dockerfileGolang.ChangePort, openPorts []string, exposePorts []string, volumes []mount.Mount, installExtraPackages bool, useCache bool, imageCacheName string) (dockerfile string, err error)
Prayer()
}
DockerfileAuto
English: Interface from automatic Dockerfile generator.
Note: To be able to access private repositories from inside the container, build the image in two or more
steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder and the .gitconfig
file to the /root folder.
One way to do this automatically is to use the Dockerfile example below, where the arguments SSH_ID_RSA_FILE
contains the file ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contains the file ~/.ssh/known_hosts and GITCONFIG_FILE
contains the file ~/.gitconfig.
If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password.
If you want to copy the files into the image automatically, use SetPrivateRepositoryAutoConfig() and the
function will copy the files ~/.ssh/id_rsa, ~/.ssh/known_hosts and ~/.gitconfig to the viable arguments
located above.
If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile()
to define the files manually.
The Dockerfile below can be used as a base
# (en) first stage of the process
# (pt) primeira etapa do processo
FROM golang:1.16-alpine as builder
# (en) enable the argument variables
# (pt) habilita as variáveis de argumento
ARG SSH_ID_RSA_FILE
ARG KNOWN_HOSTS_FILE
ARG GITCONFIG_FILE
ARG GIT_PRIVATE_REPO
# (en) creates the .ssh directory within the root directory
# (pt) cria o diretório .ssh dentro do diretório root
RUN mkdir -p /root/.ssh/ && \
# (en) creates the id_esa file inside the .ssh directory
# (pt) cria o arquivo id_esa dentro do diretório .ssh
echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.ssh/ && \
# (en) creates the known_hosts file inside the .ssh directory
# (pt) cria o arquivo known_hosts dentro do diretório .ssh
echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.ssh/known_hosts && \
# (en) creates the .gitconfig file at the root of the root directory
# (pt) cria o arquivo .gitconfig na raiz do diretório /root
echo "$GITCONFIG_FILE" > /root/.gitconfig && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.gitconfig && \
# (en) prepares the OS for installation
# (pt) prepara o OS para instalação
apk update && \
# (en) install git and openssh
# (pt) instala o git e o opnssh
apk add --no-cache build-base git openssh && \
# (en) clear the cache
# (pt) limpa a cache
rm -rf /var/cache/apk/*
# (en) creates the /app directory, where your code will be installed
# (pt) cria o diretório /app, onde seu código vai ser instalado
WORKDIR /app
# (en) copy your project into the /app folder
# (pt) copia seu projeto para dentro da pasta /app
COPY . .
# (en) enables the golang compiler to run on an extremely simple OS, scratch
# (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch
ARG CGO_ENABLED=0
# (en) adjust git to work with shh
# (pt) ajusta o git para funcionar com shh
RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/
# (en) defines the path of the private repository
# (pt) define o caminho do repositório privado
RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
# (en) install the dependencies in the go.mod file
# (pt) instala as dependências no arquivo go.mod
RUN go mod tidy
# (en) compiles the main.go file
# (pt) compila o arquivo main.go
RUN go build -ldflags="-w -s" -o /app/main /app/main.go
# (en) creates a new scratch-based image
# (pt) cria uma nova imagem baseada no scratch
# (en) scratch is an extremely simple OS capable of generating very small images
# (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas
# (en) discarding the previous image erases git access credentials for your security and reduces the size of the
# image to save server space
# (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho
# da imagem para poupar espaço no servidor
FROM scratch
# (en) copy your project to the new image
# (pt) copia o seu projeto para a nova imagem
COPY --from=builder /app/main .
# (en) execute your project
# (pt) executa o seu projeto
CMD ["/main"]
Português: Interface do gerador de dockerfile automático.
Nota: Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais
etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo
.gitconfig para a pasta /root/.
Uma maneira de fazer isto de forma automática é usar o exemplo de Dockerfile abaixo, onde os argumentos
SSH_ID_RSA_FILE contém o arquivo ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contém o arquivo ~/.ssh/known_hosts e
GITCONFIG_FILE contém o arquivo ~/.gitconfig.
Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da
mesma.
Caso você queira copiar os arquivos para dentro da imagem de forma automática, use
SetPrivateRepositoryAutoConfig() e a função copiará os arquivos ~/.ssh/id_rsa, ~/.ssh/known_hosts e
~/.gitconfig para as viáveis de argumentos sitada anteriormente.
Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual.
O arquivo Dockerfile abaixo pode ser usado como base
# (en) first stage of the process
# (pt) primeira etapa do processo
FROM golang:1.16-alpine as builder
# (en) enable the argument variables
# (pt) habilita as variáveis de argumento
ARG SSH_ID_RSA_FILE
ARG KNOWN_HOSTS_FILE
ARG GITCONFIG_FILE
ARG GIT_PRIVATE_REPO
# (en) creates the .ssh directory within the root directory
# (pt) cria o diretório .ssh dentro do diretório root
RUN mkdir -p /root/.ssh/ && \
# (en) creates the id_esa file inside the .ssh directory
# (pt) cria o arquivo id_esa dentro do diretório .ssh
echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.ssh/ && \
# (en) creates the known_hosts file inside the .ssh directory
# (pt) cria o arquivo known_hosts dentro do diretório .ssh
echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.ssh/known_hosts && \
# (en) creates the .gitconfig file at the root of the root directory
# (pt) cria o arquivo .gitconfig na raiz do diretório /root
echo "$GITCONFIG_FILE" > /root/.gitconfig && \
# (en) adjust file access security
# (pt) ajusta a segurança de acesso do arquivo
chmod -R 600 /root/.gitconfig && \
# (en) prepares the OS for installation
# (pt) prepara o OS para instalação
apk update && \
# (en) install git and openssh
# (pt) instala o git e o opnssh
apk add --no-cache build-base git openssh && \
# (en) clear the cache
# (pt) limpa a cache
rm -rf /var/cache/apk/*
# (en) creates the /app directory, where your code will be installed
# (pt) cria o diretório /app, onde seu código vai ser instalado
WORKDIR /app
# (en) copy your project into the /app folder
# (pt) copia seu projeto para dentro da pasta /app
COPY . .
# (en) enables the golang compiler to run on an extremely simple OS, scratch
# (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch
ARG CGO_ENABLED=0
# (en) adjust git to work with shh
# (pt) ajusta o git para funcionar com shh
RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/
# (en) defines the path of the private repository
# (pt) define o caminho do repositório privado
RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
# (en) install the dependencies in the go.mod file
# (pt) instala as dependências no arquivo go.mod
RUN go mod tidy
# (en) compiles the main.go file
# (pt) compila o arquivo main.go
RUN go build -ldflags="-w -s" -o /app/main /app/main.go
# (en) creates a new scratch-based image
# (pt) cria uma nova imagem baseada no scratch
# (en) scratch is an extremely simple OS capable of generating very small images
# (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas
# (en) discarding the previous image erases git access credentials for your security and reduces the size of the
# image to save server space
# (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho
# da imagem para poupar espaço no servidor
FROM scratch
# (en) copy your project to the new image
# (pt) copia o seu projeto para a nova imagem
COPY --from=builder /app/main .
# (en) execute your project
# (pt) executa o seu projeto
CMD ["/main"]
type HealthConfig ¶
type HealthConfig struct {
// Test is the test to perform to check that the container is healthy.
// An empty slice means to inherit the default.
// The options are:
// {} : inherit healthcheck
// {"NONE"} : disable healthcheck
// {"CMD", args...} : exec arguments directly
// {"CMD-SHELL", command} : run command with system's default shell
Test []string `json:",omitempty"`
// Zero means to inherit. Durations are expressed as integer nanoseconds.
Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks.
Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung.
StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down.
// Retries is the number of consecutive failures needed to consider a container as unhealthy.
// Zero means inherit.
Retries int `json:",omitempty"`
}
HealthConfig
English: holds configuration settings for the HEALTHCHECK feature.
Português: contém as configurações para o HEALTHCHECK
type LogFilter ¶ added in v0.9.11
type LogFilter struct {
Label string
// Texto contido na linha (tudo ou nada)
Match string
// expressão regular contendo o filtro para capturar o elemento
// Ex.: ^(.*?)(?P<valueToGet>\\d+)(.*)
Filter string
// texto usado em replaceAll
// Ex.: search: "." replace: "," para compatibilizar número com o excel
Search string
Replace string
// path to sabe container default output into file format
LogPath string
}
type MemoryStats ¶ added in v0.5.44
type MemoryStats struct {
// current res_counter usage for memory
Usage uint64 `json:"usage,omitempty"`
// maximum usage ever recorded.
MaxUsage uint64 `json:"max_usage,omitempty"`
// all the stats exported via memory.stat.
Stats map[string]uint64 `json:"stats,omitempty"`
// number of times memory usage hits limits.
Failcnt uint64 `json:"failcnt,omitempty"`
Limit uint64 `json:"limit,omitempty"`
// committed bytes
Commit uint64 `json:"commitbytes,omitempty"`
// peak committed bytes
CommitPeak uint64 `json:"commitpeakbytes,omitempty"`
// private working set
PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"`
}
MemoryStats aggregates all memory stats since container inception on Linux. Windows returns stats for commit and private working set only.
type NetworkChaos ¶ added in v0.5.40
type NetworkChaos struct {
// contains filtered or unexported fields
}
func (*NetworkChaos) Init ¶ added in v0.5.40
func (e *NetworkChaos) Init() (err error)
Example ¶
package main
import (
"context"
"fmt"
dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network"
"github.com/helmutkemper/util"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"time"
)
func main() {
var err error
GarbageCollector()
var netDocker = &dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
util.TraceToLog()
panic(err)
}
var mongoDocker = &ContainerBuilder{}
mongoDocker.SetNetworkDocker(netDocker)
mongoDocker.SetImageName("mongo:latest")
mongoDocker.SetContainerName("container_delete_mongo_after_test")
//mongoDocker.AddPortToChange("27017", "27016")
//mongoDocker.AddPortToExpose("27017")
mongoDocker.SetEnvironmentVar(
[]string{
"--bind_ip_all",
"--host 0.0.0.0",
"--bind 0.0.0.0",
},
)
mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)
err = mongoDocker.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
err = mongoDocker.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
panic(err)
}
var redis = ContainerBuilder{}
redis.SetNetworkDocker(netDocker)
redis.SetImageName("redis:latest")
redis.SetContainerName("container_delete_redis_test")
redis.AddPortToExpose("6379")
redis.SetWaitStringWithTimeout("Ready to accept connections", 10*time.Second)
err = redis.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
err = redis.ContainerBuildAndStartFromImage()
if err != nil {
util.TraceToLog()
panic(err)
}
var chaos = NetworkChaos{}
chaos.SetNetworkDocker(netDocker)
chaos.SetFatherContainer(mongoDocker)
chaos.SetPorts(27017, 27016, false)
err = chaos.Init()
if err != nil {
util.TraceToLog()
panic(err)
}
err = testNetworkOverloaded(
"mongodb://0.0.0.0:27016",
2*time.Second,
)
if err != nil {
util.TraceToLog()
panic(err)
}
}
// testNetworkOverloaded (English): Tests the new network port
// testNetworkOverloaded (Português): Testa a nova porta de rede
func testNetworkOverloaded(
address string,
timeout time.Duration,
) (
err error,
) {
// (English): Runtime measurement starts
// (Português): Começa a medição do tempo de execução
start := time.Now()
var mongoClient *mongo.Client
var cancel context.CancelFunc
var ctx context.Context
// (English): Prepare the MongoDB client
// (Português): Prepara o cliente do MongoDB
mongoClient, err = mongo.NewClient(options.Client().ApplyURI(address))
if err != nil {
return
}
// (English): Connects to MongoDB
// (Português): Conecta ao MongoDB
err = mongoClient.Connect(ctx)
if err != nil {
return
}
// (English): Prepares the timeout
// (Português): Prepara o tempo limite
ctx, cancel = context.WithTimeout(context.Background(), timeout)
defer cancel()
// (English): Ping() to test the MongoDB connection
// (Português): Faz um ping() para testar a conexão do MongoDB
err = mongoClient.Ping(ctx, readpref.Primary())
if err != nil {
return
}
// (English): New collection format
// (Português): Formato da nova coleção
type Trainer struct {
Name string
Age int
City string
}
// (English): Creates the 'test' bank and the 'dinos' collection
// (Português): Cria o banco 'test' e a coleção 'dinos'
collection := mongoClient.Database("test").Collection("dinos")
// (English): Prepares the data to be inserted
// (Português): Prepara os dados a serem inseridos
trainerData := Trainer{"T-Rex", 10, "Jurassic Town"}
for i := 0; i != 100; i += 1 {
// (English): Insert the data
// (Português): Insere os dados
_, err = collection.InsertOne(context.TODO(), trainerData)
if err != nil {
log.Printf("collection.InsertOne().error: %v", err)
return
}
}
// (English): Stop the operation time measurement
// (Português): Para a medição de tempo da operação
duration := time.Since(start)
fmt.Printf("End!\n")
fmt.Printf("Duration: %v\n\n", duration)
return
}
func (*NetworkChaos) SetContainerName ¶ added in v0.5.40
func (e *NetworkChaos) SetContainerName(value string)
func (*NetworkChaos) SetFatherContainer ¶ added in v0.5.40
func (e *NetworkChaos) SetFatherContainer(fatherContainer *ContainerBuilder)
func (*NetworkChaos) SetNetworkDocker ¶ added in v0.5.40
func (e *NetworkChaos) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
SetNetworkDocker (english):
SetNetworkDocker (português): Define o ponteiro do gerenciador de rede docker
Entrada:
network: ponteiro para o objeto gerenciador de rede.
Nota: - A entrada network deve ser compatível com a interface
dockerBuilderNetwork.ContainerBuilderNetwork{}
func (*NetworkChaos) SetPorts ¶ added in v0.5.40
func (e *NetworkChaos) SetPorts(listenPort, outputPort int, invert bool)
type PidsStats ¶ added in v0.5.44
type PidsStats struct {
// Current is the number of pids in the cgroup
Current uint64 `json:"current,omitempty"`
// Limit is the hard limit on the number of pids in the cgroup.
// A "Limit" of 0 means that there is no limit.
Limit uint64 `json:"limit,omitempty"`
}
PidsStats contains the stats of a container's pids
type Stats ¶ added in v0.5.44
type Stats struct {
// Common stats
Read time.Time `json:"read"`
PreRead time.Time `json:"preread"`
// Linux specific stats, not populated on Windows.
PidsStats PidsStats `json:"pids_stats,omitempty"`
BlkioStats BlkioStats `json:"blkio_stats,omitempty"`
// Windows specific stats, not populated on Linux.
NumProcs uint32 `json:"num_procs"`
StorageStats StorageStats `json:"storage_stats,omitempty"`
// Shared stats
CPUStats CPUStats `json:"cpu_stats,omitempty"`
PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous"
MemoryStats MemoryStats `json:"memory_stats,omitempty"`
}
Stats is Ultimate struct aggregating all types of stats of one container
type StorageStats ¶ added in v0.5.44
type StorageStats struct {
ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"`
ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"`
WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"`
WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"`
}
StorageStats is the disk I/O stats for read/write on Windows.
type TestContainerLog ¶ added in v0.9.16
type TestContainerLog struct {
// contains filtered or unexported fields
}
type Theater ¶ added in v0.9.11
type Theater struct {
// contains filtered or unexported fields
}
Theater
English: Theater is the collection of scene
Português: Teatro é a coleção de cenas
func (*Theater) ConfigScene ¶ added in v0.9.11
func (e *Theater) ConfigScene(sceneName string, maxStopedContainers, maxPausedContainers, maxTotalPausedAndStoppedContainers int)
ConfigScene
English: Create and configure a new scene.
Input: sceneName: unique name of the scene maxStopedContainers: maximum number of stopped containers maxPausedContainers: maximum number of paused containers
Português: Cria e configura uma cena nova.
Entrada: sceneName: nome único da cena maxStopedContainers: quantidade máxima de containers parados maxPausedContainers: quantidade máxima de containers pausados
func (*Theater) Init ¶ added in v0.9.11
func (e *Theater) Init()
Init
English: Initialization must always be the first function called.
Português: A inicialização sempre deve ser a primeira função chamada.
func (*Theater) SetContainerPaused ¶ added in v0.9.11
SetContainerPaused
English: Increments the paused containers counter
Input: sceneName: unique name of the scene Output: doNotPauseContainer: the maximum number of containers has been reached
Português: Incrementa o contador de containers pausados
Entrada: sceneName: nome único da cena Saída: doNotPauseContainer: a quantidade máxima de containers foi atingida
func (*Theater) SetContainerStopped ¶ added in v0.9.11
SetContainerStopped
English: Increments the stopped containers counter
Input: sceneName: unique name of the scene Output: IsOnTheEdge: the maximum number of containers has been reached
Português: Incrementa o contador de containers parados
Entrada: sceneName: nome único da cena Saída: IsOnTheEdge: a quantidade máxima de containers foi atingida
func (*Theater) SetContainerUnPaused ¶ added in v0.9.11
SetContainerUnPaused
English: Decreases the paused containers counter
Input: sceneName: unique name of the scene
Português: Decrementa o contador de containers pausados
Entrada: sceneName: nome único da cena
func (*Theater) SetContainerUnStopped ¶ added in v0.9.11
SetContainerUnStopped
English: Decreases the stopped containers counter
Input: sceneName: unique name of the scene
Português: Decrementa o contador de containers parados
Entrada: sceneName: nome único da cena
type ThrottlingData ¶ added in v0.5.44
type ThrottlingData struct {
// Number of periods with throttling active
Periods uint64 `json:"periods"`
// Number of periods when the container hits its throttling limit.
ThrottledPeriods uint64 `json:"throttled_periods"`
// Aggregate time the container was throttled for in nanoseconds.
ThrottledTime uint64 `json:"throttled_time"`
}
ThrottlingData stores CPU throttling stats of one running container. Not used on Windows.
Source Files
¶
- conts.go
- doc.go
- funcAddFailMatchFlag.go
- funcAddFailMatchFlagToFileLog.go
- funcAddFiileOrFolderToLinkBetweenConputerHostAndContainer.go
- funcAddFilterToFail.go
- funcAddFilterToLog.go
- funcAddFilterToLogWithReplace.go
- funcAddFilterToRestartContainer.go
- funcAddFilterToStartChaos.go
- funcAddFilterToSuccess.go
- funcAddImageBuildOptionsBuildArgs.go
- funcAddImageBuildOptionsGitCredentials.go
- funcAddPortToChange.go
- funcAddPortToDockerfileExpose.go
- funcAddPortToExpose.go
- funcAddProblem.go
- funcAddRestartMatchFlag.go
- funcAddRestartMatchFlagToFileLog.go
- funcAddStartChaosMatchFlag.go
- funcAddStartChaosMatchFlagToFileLog.go
- funcAddSuccessMatchFlag.go
- funcConfigChaosScene.go
- funcContainerBuildAndStartFromImage.go
- funcContainerBuildWithoutStartingItFromImage.go
- funcContainerCopyFrom.go
- funcContainerCopyTo.go
- funcContainerExecCommand.go
- funcContainerFindIdByName.go
- funcContainerFindIdByNameContains.go
- funcContainerInspect.go
- funcContainerPause.go
- funcContainerRemove.go
- funcContainerRestart.go
- funcContainerRestartWithTimeout.go
- funcContainerSetDisabePauseOnChaosScene.go
- funcContainerSetDisabeStopOnChaosScene.go
- funcContainerStart.go
- funcContainerStartAfterBuild.go
- funcContainerStatisticsOneShot.go
- funcContainerStop.go
- funcContainerUnpause.go
- funcEnableChaosScene.go
- funcFindCurrentIPV4Address.go
- funcFindCurrentIPV4AddressSupport.go
- funcFindTextInsideContainerLog.go
- funcGarbageCollector.go
- funcGetBuildFolderPath.go
- funcGetChannelEvent.go
- funcGetChannelOnContainerInspect.go
- funcGetChannelOnContainerReady.go
- funcGetChaosEvent.go
- funcGetContainerID.go
- funcGetContainerInfo.go
- funcGetContainerIsStarted.go
- funcGetContainerLog.go
- funcGetContainerName.go
- funcGetFailFlag.go
- funcGetGitCloneToBuild.go
- funcGetIdByContainerName.go
- funcGetImageArchitecture.go
- funcGetImageAuthor.go
- funcGetImageCacheName.go
- funcGetImageComment.go
- funcGetImageContainer.go
- funcGetImageCreated.go
- funcGetImageExpirationTime.go
- funcGetImageID.go
- funcGetImageName.go
- funcGetImageOs.go
- funcGetImageOsVersion.go
- funcGetImageParent.go
- funcGetImageRepoDigests.go
- funcGetImageRepoTags.go
- funcGetImageSize.go
- funcGetImageVariant.go
- funcGetImageVirtualSize.go
- funcGetInitialized.go
- funcGetIpAddress.go
- funcGetLastInspect.go
- funcGetLastLineOfOccurrenceBySearchTextInsideContainerLog.go
- funcGetLastLogs.go
- funcGetMetadata.go
- funcGetNetworkGatewayIPV4.go
- funcGetNetworkGatewayIPV4ByNetworkName.go
- funcGetNetworkIPV4.go
- funcGetNetworkIPV4ByNetworkName.go
- funcGetNetworkInterface.go
- funcGetProbalityNumber.go
- funcGetProblem.go
- funcGetRandSeed.go
- funcGetSuccessFlag.go
- funcGitMakePublicSshKey.go
- funcImageBuildFromFolder.go
- funcImageBuildFromServer.go
- funcImageExpirationTimeIsValid.go
- funcImageFindIdByName.go
- funcImageFindIdByNameContains.go
- funcImageInspect.go
- funcImageListExposedPorts.go
- funcImageListExposedVolumes.go
- funcImageMakeCache.go
- funcImageMakeCacheWithDefaultName.go
- funcImagePull.go
- funcImageRemove.go
- funcImageRemoveByName.go
- funcIncIpV4Address.go
- funcInit.go
- funcLogsCleaner.go
- funcLogsSearchAndReplaceIntoText.go
- funcMakeDefaultDockerfileForMeWithInstallExtras.go
- funcMakeDefaultGolangDockerfileForMe.go
- funcManagerChaos.go
- funcNetworkChangeIp.go
- funcRemoveAllByNameContains.go
- funcSelectBetweenMaxAndMin.go
- funcSetBuildFolderPath.go
- funcSetCacheEnable.go
- funcSetContainerAttachStandardStreamsToTty.go
- funcSetContainerCommandToRunWhenStartingTheContainer.go
- funcSetContainerEntrypointToRunWhenStartingTheContainer.go
- funcSetContainerHealthcheck.go
- funcSetContainerName.go
- funcSetContainerRestartPolicyAlways.go
- funcSetContainerRestartPolicyNo.go
- funcSetContainerRestartPolicyOnFailure.go
- funcSetContainerRestartPolicyUnlessStopped.go
- funcSetContainerShellForShellFormOfRunCmdEntrypoint.go
- funcSetCsvFileReader.go
- funcSetCsvFileRowSeparator.go
- funcSetCsvFileRowsToPrint.go
- funcSetCsvFileValueSeparator.go
- funcSetCsvLogPath.go
- funcSetDoNotOpenContainersPorts.go
- funcSetDockerfileBuilder.go
- funcSetEnvironmentVar.go
- funcSetGitCloneToBuild.go
- funcSetGitCloneToBuildWithPrivateSshKey.go
- funcSetGitCloneToBuildWithPrivateToken.go
- funcSetGitCloneToBuildWithUserPassworh.go
- funcSetGitConfigFile.go
- funcSetGitPathPrivateRepository.go
- funcSetGitSshPassword.go
- funcSetImageBuildOptionsCPUPeriod.go
- funcSetImageBuildOptionsCPUQuota.go
- funcSetImageBuildOptionsCPUSetCPUs.go
- funcSetImageBuildOptionsCPUSetMems.go
- funcSetImageBuildOptionsCPUShares.go
- funcSetImageBuildOptionsCacheFrom.go
- funcSetImageBuildOptionsExtraHosts.go
- funcSetImageBuildOptionsIsolationDefault.go
- funcSetImageBuildOptionsIsolationHyperV.go
- funcSetImageBuildOptionsIsolationProcess.go
- funcSetImageBuildOptionsMemory.go
- funcSetImageBuildOptionsMemorySwap.go
- funcSetImageBuildOptionsNoCache.go
- funcSetImageBuildOptionsPlatform.go
- funcSetImageBuildOptionsSecurityOpt.go
- funcSetImageBuildOptionsSquash.go
- funcSetImageBuildOptionsTarget.go
- funcSetImageCacheName.go
- funcSetImageExpirationTime.go
- funcSetImageName.go
- funcSetInspectInterval.go
- funcSetMetadata.go
- funcSetNetworkDocker.go
- funcSetOnBuild.go
- funcSetPrintBuildOnStrOut.go
- funcSetPrivateRepositoryAutoConfig.go
- funcSetRestartProbability.go
- funcSetSceneNameOnChaosScene.go
- funcSetSshIdRsaFile.go
- funcSetSshKnownHostsFile.go
- funcSetTimeBeforeStartChaosInThisContainerOnChaosScene.go
- funcSetTimeOnContainerPausedStateOnChaosScene.go
- funcSetTimeOnContainerUnpausedStateOnChaosScene.go
- funcSetTimeToRestartThisContainerAfterStopEventOnChaosScene.go
- funcSetTimeToStartChaosOnChaosScene.go
- funcSetWaitString.go
- funcSetWaitStringWithTimeout.go
- funcSizeToString.go
- funcStartMonitor.go
- funcStopMonitor.go
- funcStopMonitorAfterStopped.go
- funcTestDockerInstall.go
- funcTestLogFile.go
- funcTraceCodeLine.go
- funcVerifyImageName.go
- funcVerifyStatusError.go
- funcWaitForTextInContainerLog.go
- funcWaitForTextInContainerLogWithTimeout.go
- funcWriteAggregatePreCPUTimeTheContainerWasThrottled.go
- funcWriteAggregateTimeTheContainerWasThrottledForInNanoseconds.go
- funcWriteBlkioIoMergedRecursive.go
- funcWriteBlkioIoQueuedRecursive.go
- funcWriteBlkioIoServiceBytesRecursive.go
- funcWriteBlkioIoServiceTimeRecursive.go
- funcWriteBlkioIoServicedRecursive.go
- funcWriteBlkioIoTimeRecursive.go
- funcWriteBlkioIoWaitTimeRecursive.go
- funcWriteBlkioSectorsRecursive.go
- funcWriteCommittedBytes.go
- funcWriteConstAggregatePreCPUTimeTheContainerWasThrottled.go
- funcWriteConstAggregateTimeTheContainerWasThrottledForInNanoseconds.go
- funcWriteConstBlkioIoMergedRecursive.go
- funcWriteConstBlkioIoQueuedRecursive.go
- funcWriteConstBlkioIoServiceBytesRecursive.go
- funcWriteConstBlkioIoServiceTimeRecursive.go
- funcWriteConstBlkioIoServicedRecursive.go
- funcWriteConstBlkioIoTimeRecursive.go
- funcWriteConstBlkioIoWaitTimeRecursive.go
- funcWriteConstBlkioSectorsRecursive.go
- funcWriteConstCommittedBytes.go
- funcWriteConstCurrentNumberOfOidsInTheCGroup.go
- funcWriteConstCurrentResCounterUsageForMemory.go
- funcWriteConstFilterIntoLog.go
- funcWriteConstLimitOnTheNumberOfPidsInTheCGroup.go
- funcWriteConstMaximumUsageEverRecorded.go
- funcWriteConstMemoryLimit.go
- funcWriteConstNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit.go
- funcWriteConstNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit.go
- funcWriteConstNumberOfPeriodsWithPreCPUThrottlingActive.go
- funcWriteConstNumberOfPeriodsWithThrottlingActive.go
- funcWriteConstNumberOfTimesMemoryUsageHitsLimits.go
- funcWriteConstOnlineCPUs.go
- funcWriteConstOnlinePreCPUs.go
- funcWriteConstPeakCommittedBytes.go
- funcWriteConstPreCPUSystemUsage.go
- funcWriteConstPrivateWorkingSet.go
- funcWriteConstReadingTime.go
- funcWriteConstSystemUsage.go
- funcWriteConstTimeSpentByPreCPUTasksOfTheCGroupInKernelMode.go
- funcWriteConstTimeSpentByPreCPUTasksOfTheCGroupInUserMode.go
- funcWriteConstTimeSpentByTasksOfTheCGroupInKernelMode.go
- funcWriteConstTimeSpentByTasksOfTheCGroupInUserMode.go
- funcWriteConstTotalCPUTimeConsumed.go
- funcWriteConstTotalCPUTimeConsumedPerCore.go
- funcWriteConstTotalPreCPUTimeConsumed.go
- funcWriteConstTotalPreCPUTimeConsumedPerCore.go
- funcWriteContainerConstToFile.go
- funcWriteContainerLabelToFile.go
- funcWriteContainerLogToFile.go
- funcWriteContainerStatsToFile.go
- funcWriteCurrentNumberOfOidsInTheCGroup.go
- funcWriteCurrentResCounterUsageForMemory.go
- funcWriteFilterIntoLog.go
- funcWriteLabelAggregatePreCPUTimeTheContainerWasThrottled.go
- funcWriteLabelAggregateTimeTheContainerWasThrottledForInNanoseconds.go
- funcWriteLabelBlkioIoMergedRecursive.go
- funcWriteLabelBlkioIoQueuedRecursive.go
- funcWriteLabelBlkioIoServiceBytesRecursive.go
- funcWriteLabelBlkioIoServiceTimeRecursive.go
- funcWriteLabelBlkioIoServicedRecursive.go
- funcWriteLabelBlkioIoTimeRecursive.go
- funcWriteLabelBlkioIoWaitTimeRecursive.go
- funcWriteLabelBlkioSectorsRecursive.go
- funcWriteLabelCommittedBytes.go
- funcWriteLabelCurrentNumberOfOidsInTheCGroup.go
- funcWriteLabelCurrentResCounterUsageForMemory.go
- funcWriteLabelFilterIntoLog.go
- funcWriteLabelLimitOnTheNumberOfPidsInTheCGroup.go
- funcWriteLabelMaximumUsageEverRecorded.go
- funcWriteLabelMemoryLimit.go
- funcWriteLabelNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit.go
- funcWriteLabelNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit.go
- funcWriteLabelNumberOfPeriodsWithPreCPUThrottlingActive.go
- funcWriteLabelNumberOfPeriodsWithThrottlingActive.go
- funcWriteLabelNumberOfTimesMemoryUsageHitsLimits.go
- funcWriteLabelOnlineCPUs.go
- funcWriteLabelOnlinePreCPUs.go
- funcWriteLabelPeakCommittedBytes.go
- funcWriteLabelPreCPUSystemUsage.go
- funcWriteLabelPrivateWorkingSet.go
- funcWriteLabelReadingTime.go
- funcWriteLabelSystemUsage.go
- funcWriteLabelTimeSpentByPreCPUTasksOfTheCGroupInKernelMode.go
- funcWriteLabelTimeSpentByPreCPUTasksOfTheCGroupInUserMode.go
- funcWriteLabelTimeSpentByTasksOfTheCGroupInKernelMode.go
- funcWriteLabelTimeSpentByTasksOfTheCGroupInUserMode.go
- funcWriteLabelTotalCPUTimeConsumed.go
- funcWriteLabelTotalCPUTimeConsumedPerCore.go
- funcWriteLabelTotalPreCPUTimeConsumed.go
- funcWriteLabelTotalPreCPUTimeConsumedPerCore.go
- funcWriteLimitOnTheNumberOfPidsInTheCGroup.go
- funcWriteMaximumUsageEverRecorded.go
- funcWriteMemoryLimit.go
- funcWriteNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit.go
- funcWriteNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit.go
- funcWriteNumberOfPeriodsWithPreCPUThrottlingActive.go
- funcWriteNumberOfPeriodsWithThrottlingActive.go
- funcWriteNumberOfTimesMemoryUsageHitsLimits.go
- funcWriteOnlineCPUs.go
- funcWriteOnlinePreCPUs.go
- funcWritePeakCommittedBytes.go
- funcWritePreCPUSystemUsage.go
- funcWritePrivateWorkingSet.go
- funcWriteReadingTime.go
- funcWriteSystemUsage.go
- funcWriteTimeSpentByPreCPUTasksOfTheCGroupInKernelMode.go
- funcWriteTimeSpentByPreCPUTasksOfTheCGroupInUserMode.go
- funcWriteTimeSpentByTasksOfTheCGroupInKernelMode.go
- funcWriteTimeSpentByTasksOfTheCGroupInUserMode.go
- funcWriteTotalCPUTimeConsumed.go
- funcWriteTotalCPUTimeConsumedPerCore.go
- funcWriteTotalPreCPUTimeConsumed.go
- funcWriteTotalPreCPUTimeConsumedPerCore.go
- typeBlkioStatEntry.go
- typeBlkioStats.go
- typeCPUStats.go
- typeCPUUsage.go
- typeChaos.go
- typeContainerBuilder.go
- typeDockerfileAuto.go
- typeEvent.go
- typeGitData.go
- typeHealthConfig.go
- typeLogFilter.go
- typeMemoryStats.go
- typeNameAndId.go
- typeNetworkChaos.go
- typePidsStats.go
- typeRestart.go
- typeScene.go
- typeStats.go
- typeStorageStats.go
- typeThrottlingData.go
- typeTimers.go
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
build_from_github
command
|
|
|
build_from_private_github
command
|
|
|
container_from_folder
command
|
|
|
mongodb
command
|
|
|
mongodb_ephemeral
command
|
|
|
nats
command
|
|
|
package theater Português: Monta um teatro de containers com senas lineares ou de caos, permitindo ao desenvolvedor montar em sua máquina de trabalho testes de micro caos durante o desenvolvimento das suas aplicações.
|
package theater Português: Monta um teatro de containers com senas lineares ou de caos, permitindo ao desenvolvedor montar em sua máquina de trabalho testes de micro caos durante o desenvolvimento das suas aplicações. |