iotmakerdockerbuilder

package module
v1.0.59 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2022 License: Apache-2.0 Imports: 33 Imported by: 3

README

iotmakerdockerbuilder

import "github.com/helmutkemper/iotmaker.docker.builder"
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.SaGarbageCollector()", 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.SaGarbageCollector()", 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.SaGarbageCollector()", 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.SaGarbageCollector()", 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.SaGarbageCollector()", 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.SaGarbageCollector()", 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

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  = "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."
    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  = "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.)."
    KLogTimeSpentByTasksOfTheCGroupInKernelModeValue  = "KTimeSpentByTasksOfTheCGroupInKernelMode"
    KLogTimeSpentByTasksOfTheCGroupInKernelModeRegexp = "\\d+"

    KLogTimeSpentByTasksOfTheCGroupInUserModeLabel  = "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)."
    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  = "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.)"
    KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeValue  = "KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode"
    KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeRegexp = "\\d+"

    KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeLabel  = "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)"
    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+"

    kLogHeaderLine = 0
    kLogLabelLine  = 1
)

Variables

var theater = Theater{}

func ConfigChaosScene

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.
	SaGarbageCollector()

	// 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.
	SaGarbageCollector()

}

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
}
Output

func SaGarbageCollector

func SaGarbageCollector(names ...string)
SaGarbageCollector

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 SaImageMakeCache

func SaImageMakeCache(projectPath, cacheName string, expirationDate time.Duration) (err error)
SaImageMakeCache

English:

Creates a cached image used as a basis for creating new images.

Input:
  projectPath: path of the project folder
  cacheName: name of the cache image
  expirationDate: expiration date of the image

Output:
  err: standard object error

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.

Input:
  projectPath: caminha da pasta do projeto
  cacheName: nome da imagem cache
  expirationDate: data de expiração da imagem.

Output:
  err: standard object error

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 SaImageMakeCacheWithDefaultName

func SaImageMakeCacheWithDefaultName(projectPath string, expirationDate time.Duration) (err error)
SaImageMakeCache

English:

Creates a cached image used as a basis for creating new images.

Input:
  projectPath: path of the project folder
  expirationDate: expiration date of the image

Output:
  err: standard object error

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.

Input:
  projectPath: caminha da pasta do projeto
  expirationDate: data de expiração da imagem.

Output:
  err: standard object error

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`;

func init

func init()

init

English: Launch the test theater

Português: Inicializa o teatro de teste

type BlkioStatEntry

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 BlkioStatEntry struct {
    Major uint64 `json:"major"`
    Minor uint64 `json:"minor"`
    Op    string `json:"op"`
    Value uint64 `json:"value"`
}

type BlkioStats

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 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"`
}

type CPUStats

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 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"`
}

type CPUUsage

CPUUsage

English:

Stores All CPU stats aggregated since container inception.

Português:

Armazena todos os estatísticas de CPU agregadas desde o container.

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"`
}

type ContainerBuilder

ContainerBuilder

English:

Docker manager

Português:

Gerenciador de containers e imagens docker

type ContainerBuilder struct {
    metadata                map[string]interface{}
    problem                 string
    csvValueSeparator       string
    csvRowSeparator         string
    csvConstHeader          bool
    logCpus                 int
    rowsToPrint             int64
    chaos                   chaos
    enableCache             bool
    network                 isolatedNetwork.ContainerBuilderNetworkInterface
    dockerSys               iotmakerdocker.DockerSystem
    changePointer           chan iotmakerdocker.ContainerPullStatusSendToChannel
    onContainerReady        *chan bool
    onContainerInspect      *chan bool
    imageInspected          bool
    imageInstallExtras      bool
    imageCacheName          string
    imageName               string
    imageID                 string
    imageRepoTags           []string
    imageRepoDigests        []string
    imageParent             string
    imageComment            string
    imageCreated            time.Time
    imageContainer          string
    imageAuthor             string
    imageArchitecture       string
    imageVariant            string
    imageOs                 string
    imageOsVersion          string
    imageSize               int64
    imageVirtualSize        int64
    containerName           string
    buildPath               string
    environmentVar          []string
    changePorts             []dockerfileGolang.ChangePort
    openPorts               []string
    exposePortsOnDockerfile []string
    openAllPorts            bool
    waitString              string
    waitStringTimeout       time.Duration
    containerID             string
    ticker                  *time.Ticker
    inspect                 iotmakerdocker.ContainerInspect
    logs                    string
    logsLastSize            int
    inspectInterval         time.Duration
    gitData                 gitData
    volumes                 []mount.Mount
    IPV4Address             string
    autoDockerfile          DockerfileAuto
    containerConfig         container.Config
    restartPolicy           iotmakerdocker.RestartPolicy

    makeDefaultDockerfile bool
    printBuildOutput      bool
    init                  bool
    startedAfterBuild     bool

    contentIdRsaFile               string
    contentIdRsaFileWithScape      string
    contentKnownHostsFile          string
    contentKnownHostsFileWithScape string
    contentGitConfigFile           string
    contentGitConfigFileWithScape  string

    gitPathPrivateRepository string

    buildOptions        types.ImageBuildOptions
    imageExpirationTime time.Duration
}
Example (Func Set Time On Container Paused State On Chaos Scene)

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFailMatchFlag
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

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageExpirationTime(5 * time.Minute)

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/bug")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.SetCsvFileReader(true)

	container.SetCsvFileRowsToPrint(KLogColumnAll)

	container.AddFilterToCvsLogWithReplace(
		"contador",
		"counter",
		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
		"\\.",
		",",
	)

	container.AddFailMatchFlag(
		"counter: 40",
	)

	err = container.AddFailMatchFlagToFileLog(
		"bug:",
		"./log1/log2/log3",
	)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)

				break
			}
		}

		if pass == true {
			break
		}
	}

	_ = container.StopMonitor()

	SaGarbageCollector()

	var data []byte
	data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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/")

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: false
fail: true
error: false

func (*ContainerBuilder) AddFailMatchFlagToFileLog
func (e *ContainerBuilder) AddFailMatchFlagToFileLog(value, logDirectoryPath string) (err error)
AddFailMatchFlagToFileLog

Similar:

AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()

English:

Looks for error text in the container's standard output and saves it to a log file on the host computer

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:

Procura por um texto indicativo de erro na saída padrão do container e o salva em um arquivo de log no computador hospedeiro

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

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageExpirationTime(5 * time.Minute)

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/bug")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.SetCsvFileReader(true)

	container.SetCsvFileRowsToPrint(KLogColumnAll)

	container.AddFilterToCvsLogWithReplace(
		"contador",
		"counter",
		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
		"\\.",
		",",
	)

	container.AddFailMatchFlag(
		"counter: 40",
	)

	err = container.AddFailMatchFlagToFileLog(
		"bug:",
		"./log1/log2/log3",
	)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)

				break
			}
		}

		if pass == true {
			break
		}
	}

	_ = container.StopMonitor()

	SaGarbageCollector()

	var data []byte
	data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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/")

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: false
fail: true
error: false

func (*ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer
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

{

	var err error

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetImageExpirationTime(5 * time.Minute)

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout(
		"Stating server on port 3000",
		10*time.Second,
	)

	container.AddPortToChange(
		"3000",
		"3030",
	)

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer(
		"./test/static",
		"/static",
	)
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) AddFilterToCvsLog
func (e *ContainerBuilder) AddFilterToCvsLog(label, match, filter string)
AddFilterToCvsLog

Similar:

AddFilterToCvsLogWithReplace(), AddFilterToCvsLog()

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

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMeWithInstallExtras()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/counter")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvFileReader(true)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.AddFilterToCvsLogWithReplace(

		"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: 40000000",

		"^.*?(?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())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFilterToCvsLogWithReplace
func (e *ContainerBuilder) AddFilterToCvsLogWithReplace(label, match, filter, search, replace string)
AddFilterToCvsLogWithReplace

Similar:

AddFilterToCvsLogWithReplace(), AddFilterToCvsLog()

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) AddFilterToFail
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

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/counter")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"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())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFilterToRestartContainer
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

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFilterToStartChaos
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

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFilterToSuccess
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].
Example

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234

  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

https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234

  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

{

	var err error

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// English: read server inside a container on address http://localhost:3030/
	//
	// Português: lê o servidor dentro do container na porta 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) AddPortToDockerfileExpose
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
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.
	SaGarbageCollector()

	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)

	SaGarbageCollector()

	// Output:
	// <html><body><p>C is life! Golang is a evolution of C</p></body></html>
}

func (*ContainerBuilder) AddRestartMatchFlag
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.
Example

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddRestartMatchFlag(

		"restart-me!",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddRestartMatchFlagToFileLog
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.
Example

{

	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	err = container.AddRestartMatchFlagToFileLog(

		"restart-me!",

		"./log1/log2/log3",
	)
	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddStartChaosMatchFlag
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
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
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
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

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) ContainerBuildWithoutStartingItFromImage
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
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
Example

package main

import (
	"fmt"
	"github.com/docker/docker/api/types"
	"log"
	"os"
)

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]
	SaGarbageCollector()

	err = buildGoLintImageCopyFromExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = builAlpineImageCopyFromExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	_ = os.Remove("./example/golint/golangci-lint")

}

func buildGoLintImageCopyFromExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	fmt.Printf("file name: %v\n", copyResponse[0].Name)

	return
}

func builAlpineImageCopyFromExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.ContainerCopyTo(
		[]string{"./example/golint/golangci-lint"},
		[]string{"/go"},
	)

	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	return
}
Output
image size: 510.9 MB
image os: linux
file name: golangci-lint
image size: 281.8 MB
image os: linux

func (*ContainerBuilder) ContainerCopyTo
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"
	"os"
)

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]
	SaGarbageCollector()

	err = buildGoLintImageCopyToExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = builAlpineImageCopyToExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	_ = os.Remove("./example/golint/golangci-lint")

}

func buildGoLintImageCopyToExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	fmt.Printf("file name: %v\n", copyResponse[0].Name)

	return
}

func builAlpineImageCopyToExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.ContainerCopyTo(
		[]string{"./example/golint/golangci-lint"},
		[]string{"/go"},
	)

	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	return
}
Output
image size: 510.9 MB
image os: linux
file name: golangci-lint
image size: 281.8 MB
image os: linux

func (*ContainerBuilder) ContainerExecCommand
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
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
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
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
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
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
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
func (e *ContainerBuilder) ContainerStartAfterBuild() (err error)
ContainerStartAfterBuild

English:

Starts a newly created container.

Output:
  err: standard 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, in case you need to control the container.

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
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
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
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()
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetImageName("nats:latest")

	container.SetContainerName("container_delete_nats_after_test")

	container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	err = container.ImagePull()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	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)
	}

	SaGarbageCollector()

	err = container.ImageRemoveByName("nats:latest")
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

}
Output

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
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
func (e *ContainerBuilder) GetChaosEvent() (eventChannel chan Event)
GetChaosEvent

English:

Returns channel of Chaos Winds.

Output:
  eventChannel: chaos event channel
    ContainerName: container name
Message: Error message or event suffered by container, as aborted by system.
     Error: True if there is an error
     Done: Trick for when the chaos roll was successful. See the AddSuccessMatchFlag() function
     Fail: True for when the chaos test failed. See the functions AddFailMatchFlag(),
           AddFailMatchFlagToFileLog(), AddFilterToFail()
     Metadata: Data defined by the SetMetadata() function

Português:

Retorna o canal de ventos de caos.

Saída:
  eventChannel: canal de eventos de caos
    ContainerName: Nome do container
Message: Mensagem de erro ou evento sofrido pelo container, como abortado pelo sistema.
     Error: True se houver erro
     Done: True para quando o teste de caos foi bem sucessido. Veja a função AddSuccessMatchFlag()
     Fail: True para quando o teste de caos falhou. Veja as funções AddFailMatchFlag(),
           AddFailMatchFlagToFileLog(), AddFilterToFail()
     Metadata: Dados definidos pela função SetMetadata()
func (*ContainerBuilder) GetContainerID
func (e *ContainerBuilder) GetContainerID() (ID string)
GetContainerID

English:

Returns the ID of the created container

Output:
  ID: ID of the container

Português:

Retorna o ID do container criado

Saída:
  ID: ID do container
func (*ContainerBuilder) GetContainerInfo
func (e *ContainerBuilder) GetContainerInfo() (info types.Info, err error)
GetContainerInfo

English:

Returns a series of information about the container.

Output:
  info: Container information.
  err: Standard error object.

Português:

Retorna uma séries de informações sobre o container.

Saída:
  info: Informações sobre o container.
  err: Objeto padrão de erro.
func (ContainerBuilder) GetContainerIsStarted
func (e ContainerBuilder) GetContainerIsStarted() (started bool)
GetContainerIsStarted

English:

Returns if the container was initialized after it was generated.

Output:
  started: true for container initialized after generated

Português:

Retorna se o container foi inicializado depois de gerado.

Saída:
  started: true para container inicializado depois de gerado
func (*ContainerBuilder) GetContainerLog
func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
GetContainerLog

English:

Returns the current standard output of the container.

Output:
  log: Texts contained in the container's standard output
  err: Standard error object

Português:

Retorna a saída padrão atual do container.

Saída:
  log: Textos contidos na saída padrão do container
  err: Objeto de erro padrão
func (*ContainerBuilder) GetContainerName
func (e *ContainerBuilder) GetContainerName() (containerName string)
GetContainerName

English:

Returns container name

Output:
  containerName: Container name

Português:

Retorna o nome do container

Saída:
  containerName: Nome do container
func (*ContainerBuilder) GetFailFlag
func (e *ContainerBuilder) GetFailFlag() (fail bool)
GetFailFlag

English:

Returns the fail indicator flag set by the AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail() functions,

Output:
  fail: true if test failed

Português:

Retorna o flag indicador de falha definido pelas funções AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()

Saída:
  fail: true se o teste tiver falhado
func (*ContainerBuilder) GetGitCloneToBuild
func (e *ContainerBuilder) GetGitCloneToBuild() (url string)
GetGitCloneToBuild

English:

Returns the URL of the repository to clone for image transformation

Note:

* See the SetGitCloneToBuild() function for more details.

Português:

Retorna a URL do repositório a ser clonado para a transformação em imagem

Nota:

* Veja a função SetGitCloneToBuild() para mais detalhes.
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) GetImageArchitecture
func (e *ContainerBuilder) GetImageArchitecture() (architecture string)
GetImageArchitecture

English:

Returns the architecture of the image.

Output:
  architecture: image architecture

Português:

Retorna a arquitetura da imagem.

Saída:
  architecture: arquitetura da imagem
func (*ContainerBuilder) GetImageAuthor
func (e *ContainerBuilder) GetImageAuthor() (author string)
GetImageAuthor

English:

Returns the author of the image.

Output:
  author: image author

Português:

Retorna o autor da imagem.

Saída:
  author: autor da imagem
func (*ContainerBuilder) GetImageCacheName
func (e *ContainerBuilder) GetImageCacheName() (name string)
GetImageCacheName

English:

Returns the name of the image cache used to create the image

Output:
  name: name of the image cache

Português:

Devolve o nome da imagem cache usada para criar a imagem

Saída:
  name: nome da imagem cache
func (*ContainerBuilder) GetImageComment
func (e *ContainerBuilder) GetImageComment() (comment string)
GetImageComment

English:

Returns the archived comment of the image

Output:
  comment: image comment

Português:

Retorna o comentário arquivado na imagem

Saída:
  comment: comentário da imagem
func (*ContainerBuilder) GetImageContainer
func (e *ContainerBuilder) GetImageContainer() (imageName string)
GetImageContainer

English:

Returns the name of the image used to create the container

Output:
  imageName: Name of the image used to create the container

Português:

Retorna o nome da imagem usada para criar o container

Saída:
  imageName: Nome da imagem usada para criar o container
func (*ContainerBuilder) GetImageCreatedTime
func (e *ContainerBuilder) GetImageCreatedTime() (created time.Time)
GetImageCreatedTime

English:

Returns the date of creation of the image.

Output:
  created: Time.Time object with the date of creation of the image.

Português:

Retorna a data de criação da imagem.

Saída:
  created: Objeto time.Time com a data de criação da imagem.
func (*ContainerBuilder) GetImageExpirationTime
func (e *ContainerBuilder) GetImageExpirationTime() (expiration time.Duration)
GetImageExpirationTime

Português:

Retorna a data de expiração da imagem, ou seja, a data usada como base para impedir que a mesma imagem seja gerada várias vezes em um único teste.

Saída:
  expiration: Objeto time.Duration com a data de validade da imagem

English:

Returns the image's expiration date, that is, the date used as a basis to prevent the same image from being generated multiple times in a single test.

Output:
  expiration: time.Duration object with the image's expiration date
func (*ContainerBuilder) GetImageID
func (e *ContainerBuilder) GetImageID() (ID string)
GetImageID

English:

Returns the image ID.

Output:
  ID: image ID

Português:

Retorna o ID da imagem.

Saída:
  ID: ID da imagem
func (*ContainerBuilder) GetImageName
func (e *ContainerBuilder) GetImageName() (name string)
GetImageName

English:

Returns the name of the image.

Output:
  name: Name of the image

Português:

Retorna o nome da imagem.

Saída:
  name: Nome da imagem
func (*ContainerBuilder) GetImageOs
func (e *ContainerBuilder) GetImageOs() (os string)
GetImageOs

English:

Returns the operating system used to create the image.

Output:
  os: name of the operating system used to create the image

Português:

Retorna o sistema operacional usado para criar a imagem.

Saída:
  os: nome do sistema operacional usado para criar a imagem
func (*ContainerBuilder) GetImageOsVersion
func (e *ContainerBuilder) GetImageOsVersion() (osVersion string)
GetImageOsVersion

English:

Returns the operating system version of the image

Output:
  osVersion: operating system version of the image

Português:

Retorna a versão do sistema operacional da imagem

Saída:
  osVersion: versão do sistema operacional da imagem
func (*ContainerBuilder) GetImageParent
func (e *ContainerBuilder) GetImageParent() (parent string)
GetImageParent

Retorna o nome da imagem base

Saída:
  parent: nome da imagem base

English:

Returns the name of the base image

Output:
  parent: name of the base image
func (*ContainerBuilder) GetImageRepoDigests
func (e *ContainerBuilder) GetImageRepoDigests() (repoDigests []string)
GetImageRepoDigests

English:

Get image reports

Output:
  repoDigests: image reports

Português:

Obtém relatórios simplificados da imagem

Saída:
  repoDigests: relatórios da imagem

English:

Get image reports

Output:
  repoDigests: image reports
func (*ContainerBuilder) GetImageRepoTags
func (e *ContainerBuilder) GetImageRepoTags() (repoTags []string)
GetImageRepoTags

English:

Get the list of tags of an image repository.

Output:
  repoTags: list of image repository tags.

Português:

Obtém a lista de tags de um repositório de imagens.

Saída:
  repoTags: lista de tags do repositório de imagens.
func (*ContainerBuilder) GetImageSize
func (e *ContainerBuilder) GetImageSize() (size int64)
GetImageSize

English:

Returns the image size

Output:
  size: image size

Português:

Retorna o tamanho da imagem

Saída:
  size: tamanho da imagem
func (*ContainerBuilder) GetImageVariant
func (e *ContainerBuilder) GetImageVariant() (variant string)
func (*ContainerBuilder) GetImageVirtualSize
func (e *ContainerBuilder) GetImageVirtualSize() (virtualSize int64)
GetImageVirtualSize

English:

Returns the virtual size of the image

Output:
  virtualSize: virtual size of the image

Português:

Retorna o tamanho virtual da imagem

Saída:
  virtualSize: tamanho virtual da imagem
func (*ContainerBuilder) GetInitialized
func (e *ContainerBuilder) GetInitialized() (initialized bool)
GetInitialized

English:

Returns if the container control object was initialized

Output:
  initialized: true if the container control object was initialized

Português:

Retorna se o objeto de controle do container foi inicializado

Saída:
  inicializado: true caso o objeto de controle do container foi inicializado
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()

Output:
  inspect: Container information such as name, ID, volumes, network, etc.

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()

Output:
  inspect: Informações sobre o container, como nome, ID, volumes, rede, etc.

Nota:

* A função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as
  informações estão prontas para uso
func (*ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog
func (e *ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog(value string) (text string, contains bool, err error)
GetLastLineOfOccurrenceBySearchTextInsideContainerLog

English:

Returns the last line of output standard output container that contains the text searched

Input:
  value: text to be searched in the standard output of the container

Output:
  text: string with the last line that contains the text searched
  contains: true if the text was found
  err: default error object

Português:

Retorna a ultima linha sa saída padrão do container que contém o texto procurado

Input:
  value: texto procurado na saída padrão do container

Saída:
  text: string com a última linha que contém o texto procurado
  contains: true se o texto foi encontrado
  err: objeto de erro padrão
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()

Output:
  logs: container standard output text

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()

Saída:
  logs: saída padrão do container

Nota:

* A função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as
  informações estão prontas para uso
func (*ContainerBuilder) GetMetadata
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

Output:
  IPV4: IPV4 address of the gateway

Português:

Retorna o gateway da rede para rede IPV4

Saída:
  IPV4: endereço IPV4 do gateway
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.

Input:
  networkName: name of the network

Output:
  IPV4: address of the gateway of the network
  err: standard object error

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.

Entrada:
  networkName: nome da rede

Saída:
  IPV4: endereço do gateway da rede
  err: objeto de erro padrão

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

Output:
  IPV4: network address IPV4

Português:

Retorno o IPV4 da rede do docker

Saída:
  IPV4: endereço IPV4 da rede
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.

Input:
  networkName: string with the name of the network

Output:
  IPV4 IPV4 address of the network
  err: standard object error

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.

Entrada:
  networkName: string com o nome da rede

Saída:
  IPV4: endereço IPV4 da rede
  err: objeto de erro padrão

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

Output:
  network: Object pointer used to configure the network

Português:

Retorna o objeto definido para o controle da rede

Saída:
  network: Ponteiro do objeto usado para configurar a rede
func (*ContainerBuilder) GetProblem
func (e *ContainerBuilder) GetProblem() (problem string)
GetProblem

English:

Return problem description when possible.

Output:
  problem: descrição do problema

Português:

Retorna a descrição do problema, quando possível

Saída:
  problem: descrição do problema
func (*ContainerBuilder) GetSuccessFlag
func (e *ContainerBuilder) GetSuccessFlag() (success bool)
GetSuccessFlag

English:

Get success flag

Output:
  success: success flag

Português:

Retorna a bandeira indicadora de sucesso no teste

Saída:
  success: bandeira indicadora de sucesso no teste
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

Output:
  inspect: Contém informações sobre a imagem criada
  err: standard object error

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() and
  MakeDefaultDockerfileForMeWithInstallExtras() functions can be used to make a standard
  Dockerfile file automatically.

Português:

Transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma imagem docker

Saída:
  inspect: contém informações sobre a imagem criada
  err: objeto de erro padrão

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, podem ser usadas as funções MakeDefaultDockerfileForMe() e
  MakeDefaultDockerfileForMeWithInstallExtras() para ser gerar um arquivo Dockerfile padrão de
  forma automática.
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

	SaGarbageCollector()

	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)

	SaGarbageCollector()

}
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.

Output:
  inspect: Contém informações sobre a imagem criada
  err: standard object error

Note:

* The repository must 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.

Saída:
  inspect: contém informações sobre a imagem criada
  err: objeto de erro padrão

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
func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)
ImageFindIdByName

English:

Find an image by name

Input:
  name: image name

Output:
  id: image ID
  err: default error object

Português:

Encontra uma imagem pelo nome

Input:
  name: nome da imagem

Output:
  id: ID da imagem
  err: Objeto padrão de erro
func (*ContainerBuilder) ImageFindIdByNameContains
func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)
ImageFindIdByNameContains

English:

Find an image by part of the name

Input:
  containerName: Part of the name of the image

Output:
  list: List of images found
  err: Default error object

Português:

Encontra uma imagem por parte do nome

Entrada:
  containerName: Parte do nome da imagem

Saída:
  list: Lista de imagens encontradas
  err: Objeto de erro padrão
func (*ContainerBuilder) ImageInspect
func (e *ContainerBuilder) ImageInspect() (inspect types.ImageInspect, err error)
ImageInspect

English:

Inspects the image and returns information type, ID, name, size, creation date, update date, author, tags, etc

Output:
  inspect: Image information
  err: Default error object

Português:

Inspeciona a imagem e retorna informações tipo, ID, nome, tamanho, data de criação, data de atualização, autor, tags, etc

Saída:
 inspect: Informações da imagem
 err: Objeto de erro padrão
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.

Output:
  portList: List of ports exposed on image creation. (Dockerfile expose port)
  err: standard error object

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.

Saída:
  portList: Lista de portas expostas na criação da imagem. (Dockerfile expose port)
  err: Objeto de erro padrão

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{}

	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.

Output:
  list: List of exposed volumes
  err: Standard error object

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.

Saída:

list: Lista de volumes expostos err: Objeto de erro padrão

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

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetImageName("delete:latest")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, 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])

	SaGarbageCollector()

}
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)

Output:
  err: standart error object

Português:

Baixa a imagem a ser montada. (equivale ao comando docker pull image)

Saída:
  err: objeto de erro padrão
Example

{
	var err error

	SaGarbageCollector()

	// create a network [optional]
	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)
	}

	// create a container
	var container = ContainerBuilder{}

	container.SetNetworkDocker(&netDocker)

	container.SetImageName("nats:latest")

	container.SetContainerName("container_delete_nats_after_test")

	container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	err = container.ImagePull()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	SaGarbageCollector()

	err = container.ImageRemoveByName("nats:latest")
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

}
Output

func (*ContainerBuilder) ImageRemove
func (e *ContainerBuilder) ImageRemove() (err error)
ImageRemove

English:

Remove the image if there are no containers using the image

Output:
  err: Standard error object

Note:

* Remove all containers before use, including stopped containers

Português:

Remove a imagem se não houver containers usando a imagem

Saída:
  err: Objeto de erro padrão

Nota:

* 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

Input:
  name: full image name

Output:
  err: standard error object

Note:

* Remove all containers before use, including stopped containers

Português:

Remove a imagem se não houver containers usando a imagem

Entrada:
  name: nome completo da imagem

Saída:
  err: objeto de erro padrão

Nota:

* Remova todos os containers antes do uso, inclusive os containers parados
func (*ContainerBuilder) Init
func (e *ContainerBuilder) Init() (err error)
Init

English:

Initializes the object.

Output:
  err: Standard error object

Note:

* Should be called only after all settings have been configured

Português:

Inicializa o objeto.

Saída:
  err: Objeto de erro padrão

Nota:

* 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.

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 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;
* 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.

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 haja portas expostas ou volumes nas configurações, as mesmas serão definidas
  automaticamente, o mesmo serve para arquivos compartilhados entre o host e o container;
* 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.
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras
func (e *ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras()
MakeDefaultDockerfileForMeWithInstallExtras

Similar:

MakeDefaultDockerfileForMe(), MakeDefaultDockerfileForMeWithInstallExtras()

English:

Automatically mount the Dockerfile-iotmaker inside the target folder.

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 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;
* 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.

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 haja portas expostas ou volumes nas configurações, as mesmas serão definidas
  automaticamente, o mesmo serve para arquivos compartilhados entre o host e o container;
* 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) NetworkChangeIp
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

	SaGarbageCollector()

	var netDocker = &dockerNetwork.ContainerBuilderNetwork{}
	err = netDocker.Init()
	if err != nil {
		panic(err)
	}

	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)

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/doNothing")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetWaitStringWithTimeout("done!", 15*time.Second)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	var containerInspect iotmakerdocker.ContainerInspect
	containerInspect, err = container.ContainerInspect()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.NetworkChangeIp()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = container.ContainerStart()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	containerInspect, err = container.ContainerInspect()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	fmt.Printf("IP: %v\n", containerInspect.Network.Networks["delete_after_test"].IPAddress)

	SaGarbageCollector()

}
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

Input:
  value: part of the wanted name

Output:
  err: Standard error object

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

Entrada:
  value: parte do nome desejado

Saída:
  err: Objeto de erro padrão
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
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.

Input:
  value: true to enable the use of image named cache:latest as the basis for new images if it
    exists

Note:

* This function is extremely useful when developing new applications, reducing the time to create
  images with each new test.

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.

Entrada:
  value: true para habilitar o uso da imagem de nome cache:latest como base para novas imagens,
    caso a mesma exista

Nota:

* Esta função é extremamente útil no desenvolvimento de novas aplicações, reduzindo o tempo de
  criação de imagens a cada novo teste.

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

Entrada:
  value: true to attach standard streams to tty

Português:

Anexa a saída padrão do tty

Entrada:
  value: true para anexar 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)

Input:
  values: List of commands. Eg.: []string{"ls", "-l"}

Português:

Comando a ser executado quando o container inicia (estilo Dockerfile CMD)

Entrada:
  values: Lista de comandos. Ex.: []string{"ls", "-l"}
func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer
func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
SetContainerEntrypointToRunWhenStartingTheContainer

English:

Entrypoint to run when stating the container

Input:
  values: entrypoint. Eg.: docker run --entrypoint [new_command] [docker_image] [optional:value]

Português:

Entrypoint a ser executado quando o container iniciar

Entrada:
  values: entrypoint. Ex.: docker run --entrypoint [new_command] [docker_image] [optional:value]
func (*ContainerBuilder) SetContainerHealthcheck
func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)
SetContainerHealthcheck

English:

Holds configuration settings for the HEALTHCHECK feature.

Input:
  value: Ponteiro para HealthConfig
    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:

Adiciona definições de configuração para o recurso HEALTHCHECK.

Entrada:
  value: Ponteiro para HealthConfig
    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
Example

{
	var err error

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// English: read server inside a container on address http://localhost:3030/
	//
	// Português: lê o servidor dentro do container na porta 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

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
func (e *ContainerBuilder) SetCsvFileReader(value bool)
SetCsvFileReader

English:

Prints in the header of the file the name of the constant responsible for printing the column in the log.

Input:
  value: true to print the name of the constant responsible for printing the column in the log
    in the header of the file.

Nota:

* The constants printed in the first line of the file are used in the SetCsvFileRowsToPrint()
  function. Simply separate the constants by pipe (|).
  Example: container.SetCsvFileRowsToPrint( KLogColumnReadingTime
           | KLogColumnCurrentNumberOfOidsInTheCGroup | ... )

Português:

Imprime no cabeçalho do arquivo o nome da constante responsável por imprimir a coluna no log.

Entrada:
  value: true para imprimir no cabeçalho do arquivo o nome da constante responsável por imprimir
    a coluna no log.

Nota:

* As constantes impressas na primeira linha do arquivo são usadas na função
  SetCsvFileRowsToPrint(). Basta separar as contantes por pipe (|).
  Exemplo: container.SetCsvFileRowsToPrint( KLogColumnReadingTime
           | KLogColumnCurrentNumberOfOidsInTheCGroup | ... )
func (*ContainerBuilder) SetCsvFileRowSeparator
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(), AddFilterToCvsLog() e
  AddFilterToCvsLogWithReplace();
* 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(), AddFilterToCvsLog() e
  AddFilterToCvsLogWithReplace();
* As colunas de dados preenchidos varia de acordo com o sistema operacional.
func (*ContainerBuilder) SetCsvFileRowsToPrint
func (e *ContainerBuilder) SetCsvFileRowsToPrint(value int64)
SetCsvFileRowsToPrint

English:

Defines which columns will be printed in the log, in the form of a CSV file, with container performance information, memory consumption indicators and access times.

Input:
  value: List of columns printed in CSV file. Eg.: KLogColumnMacOs, KLogColumnWindows,
    KLogColumnAll or any combination of KLogColumn... concatenated with pipe.
    Eg.: KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ...

Nota:

* To see the complete list of columns, use SetCsvFileRowsToPrint(KLogColumnAll) and
  SetCsvFileReader(true).
  This will print the constant names on top of each column in the log.

Português:

Define quais colunas vão ser impressas no log, na forma de arquivo CSV, com informações de desempenho do container, 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.
    Ex.: KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ...

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

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/counter")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.36.csv", true)
	container.AddFilterToCvsLog(
		"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())
		SaGarbageCollector()
		return
	}

	_, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
container name: container_counter_delete_after_test
done: true
fail: false
error: false

func (*ContainerBuilder) SetCsvFileValueSeparator
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(), AddFilterToCvsLog() and
  AddFilterToCvsLogWithReplace() 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(), AddFilterToCvsLog() e
  AddFilterToCvsLogWithReplace();
* As colunas de dados preenchidos varia de acordo com o sistema operacional.
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetCsvLogPath
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(), AddFilterToCvsLog(),
  AddFilterToCvsLogWithReplace(), 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(), AddFilterToCvsLog(),
  AddFilterToCvsLogWithReplace(), SetCsvFileValueSeparator() e SetCsvFileRowSeparator() para alterar
  algumas configurações do log.
Example

{
	var err error
	var imageInspect types.ImageInspect

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/counter")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)
	container.SetCsvFileValueSeparator("\t")
	container.AddFilterToCvsLogWithReplace(
		"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())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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()

	SaGarbageCollector()

}
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
func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)
SetDockerfileBuilder

English:

Defines a new object containing the builder of the dockerfile.

Input:
  value: Object compatible with DockerfileAuto interface

Note:

* Eee the DockerfileAuto interface for further instructions.

Português:

Define um novo objeto contendo o construtor do arquivo dockerfile.

Entrada:
  value: Objeto compatível com a interface DockerfileAuto

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

	SaGarbageCollector()

	var netDocker = dockerNetwork.ContainerBuilderNetwork{}
	err = netDocker.Init()
	if err != nil {
		panic(err)
	}

	err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
	if err != nil {
		panic(err)
	}

	var mongoDocker = &ContainerBuilder{}

	mongoDocker.SetImageName("mongo:latest")

	mongoDocker.SetContainerName("container_delete_mongo_after_test")

	mongoDocker.AddPortToExpose("27017")

	mongoDocker.SetEnvironmentVar(
		[]string{
			"--host 0.0.0.0",
		},
	)

	if err != nil {
		panic(err)
	}

	mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)

	err = mongoDocker.Init()
	if err != nil {
		panic(err)
	}

	err = mongoDocker.ContainerBuildAndStartFromImage()
	if err != nil {
		panic(err)
	}

}
Output

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.

Input:
  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.

Entrada:
  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

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		panic(err)
	}

	err = container.Init()
	if err != nil {
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		panic(err)
	}

	SaGarbageCollector()

}
Output

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.

Input:
  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.

Entrada:
  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.

Input:
  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.

Entrada:
  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.

Input:
  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.

Entrada:
  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

Input:
  value: .gitconfig file contents

Example:

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

Entrada:
value: conteúdo do arquivo .gitconfig

Exemplo:

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"

Input:
  value: Caminho do repositório privado. Eg.: github.com/helmutkemper

Português:

Caminho do repositório privado definido em "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"

Entrada:
  value: Caminho do repositório privado. Ex.: github.com/helmutkemper
Example

this test only work on my acount (sorry)

{
	var err error

	SaGarbageCollector()

	var container = ContainerBuilder{}
	container.SetPrintBuildOnStrOut()
	container.SetGitPathPrivateRepository("github.com/helmutkemper")

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("git@github.com:helmutkemper/iotmaker.docker.builder.private.example.git")
	container.MakeDefaultDockerfileForMeWithInstallExtras()
	err = container.SetPrivateRepositoryAutoConfig()
	if err != nil {
		panic(err)
	}

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		panic(err)
	}

	err = container.Init()
	if err != nil {
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		panic(err)
	}

	// 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) SetGitSshPassword
func (e *ContainerBuilder) SetGitSshPassword(password string)
SetGitSshPassword

English:

Sets the password for the ssh key for private git repositories.

Input:
  password: git ssh certificate 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().

Português:

Define a senha da chave ssh para repositórios git privados.

Entrada:
  password: senha da chave ssh

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.

Input:
  value: CPU CFS scheduler period

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.

Entrada:
  value: período do agendador CFS da CPU

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:

Defines the host machine’s CPU cycles.

Input:
  value: machine’s CPU cycles. (Default: 1024)

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:

Define os ciclos de CPU da máquina hospedeira.

Entrada:
  value: ciclos de CPU da máquina hospedeira. (Default: 1024)

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.

Input:
  value: string with the format "1,2,3"

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.

Entrada:
  value: string com o formato "1,2,3"

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)

Input:
  value: string with the format "0-3,5-7"

--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)

Entrada:
  value: string com o formato "0-3,5-7"

--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 the CPU shares of the image build options.

Input:
  value: CPU shares (Default: 1024)

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:

Define o compartilhamento de CPU na construção da imagem.

Entrada:
  value: Compartilhamento de CPU (Default: 1024)

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.

Entrada:
  values: images that are used for matching cache.

Note:

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.

Entrada:
  values: imagens que são usadas para correspondência de cache.

Note:

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.

Input:
  values: hosts to mapping

Example:

values = []string{
  "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.

Entrada:
  values: hosts para mapeamento

Exemplo:

values = []string{
  "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.

Input:
  value: amount of memory in bytes

Note:

* If you set this option, the minimum allowed value is 4 * 1024 * 1024 (4 megabyte);
* 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.

Entrada:
  value: Quantidade de memória em bytes

Nota:

* Se você vai usar esta opção, o máximo permitido é 4 * 1024 * 1024 (4 megabyte)
* Use value * KKiloByte, value * KMegaByte e value * KGigaByte
  See https://docs.docker.com/engine/reference/run/#user-memory-constraints
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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)
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
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) SetImageBuildOptionsMemorySwap
func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)
SetImageBuildOptionsMemorySwap

English:

Set memory swap (--memory-swap)

Note:

* 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

Note:

* 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.

Input:
  value: target platform

Examples:

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]]

Entrada:
  value: plataforma de destino

Exemplos:

osx
windows/amd64
linux/arm64/v8
func (*ContainerBuilder) SetImageBuildOptionsSecurityOpt
func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)
SetImageBuildOptionsSecurityOpt

English:

Set the container security options

Input:
  values: container security options

Examples:

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

Entrada:
  values: opções de segurança do container

Exemplos:

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

Input:
  value: true preserve the original image and creates a new one from the parent

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

Entrada:
  value: true preserva a imagem original e cria uma nova imagem a partir da imagem pai
func (*ContainerBuilder) SetImageBuildOptionsTarget
func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)
SetImageBuildOptionsTarget

English:

Build the specified stage as defined inside the Dockerfile.

Input:
  value: stage name

Note:

* 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.

Entrada:
  value: nome do estágio

Nota:

* 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
func (e *ContainerBuilder) SetImageCacheName(name string)
SetImageCacheName

English::

Defines the name of the cache image

Input:
  name: Name of the cached image. (Default: "cache:lastest")

Note:

* See SaImageMakeCache(), SetCacheEnable(), MakeDefaultDockerfileForMe() and
  MakeDefaultDockerfileForMeWithInstallExtras() functions

Português:

Define o nome da imagem cache

Entrada:
  name: Nome da imagem cacge. (Default: "cache:lastest")

Nota:

* Veja as funções SaImageMakeCache(), SetCacheEnable(), MakeDefaultDockerfileForMe() e
  MakeDefaultDockerfileForMeWithInstallExtras()
func (*ContainerBuilder) SetImageExpirationTime
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

Example

{

	var err error

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// English: read server inside a container on address http://localhost:3030/
	//
	// Português: lê o servidor dentro do container na porta 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) SetInspectInterval
func (e *ContainerBuilder) SetInspectInterval(value time.Duration)
SetInspectInterval

English:

Defines the container's monitoring interval [optional]

Input:
  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]

Entrada:
  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
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

Input:
  network: pointer to the network manager object.

Note:

* Compatible with dockerBuilderNetwork.ContainerBuilderNetwork{} object

Português:

Define o ponteiro do gerenciador de rede docker

Entrada:
  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)
	}

	err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
	if err != nil {
		panic(err)
	}

	var mongoDocker = &ContainerBuilder{}

	mongoDocker.SetNetworkDocker(&netDocker)

	mongoDocker.SetImageName("mongo:latest")

	mongoDocker.SetContainerName("container_delete_mongo_after_test")

	mongoDocker.AddPortToExpose("27017")

	mongoDocker.SetEnvironmentVar(
		[]string{
			"--host 0.0.0.0",
		},
	)

	err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
	if err != nil {
		panic(err)
	}

	mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)

	err = mongoDocker.Init()
	if err != nil {
		panic(err)
	}

	err = mongoDocker.ContainerBuildAndStartFromImage()
	if err != nil {
		panic(err)
	}

	SaGarbageCollector()

}
Output

func (*ContainerBuilder) SetOnBuild
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.

Input:
  onBuild: List of 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.

Note:

See https://docs.docker.com/engine/reference/builder/#onbuild

Português:

Adiciona à imagem uma instrução de gatilho a ser executada posteriormente, quando a imagem for usada como base para outra construção.

Entrada:
  onBuild: Lista de instruções de gatilho a serem executadas 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.

Nota:

https://docs.docker.com/engine/reference/builder/#onbuild
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
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.

Output:
  err: Standard error object

Português:

Copia o arquivo ssh ~/.ssh/id_rsa e o arquivo ~/.gitconfig para as variáveis SSH_ID_RSA_FILE e GITCONFIG_FILE.

Saída:
  err: Objeto de erro padrão
func (*ContainerBuilder) SetRestartProbability
func (e *ContainerBuilder) SetRestartProbability(restartProbability, restartChangeIpProbability float64, limit int)
SetRestartProbability

English:

Set the restart probability and the probability of changing the ip of the container when it restarts.

Input:
  restartProbability: Probability of restarting a container during the chaos test.
  restartChangeIpProbability: Probability of changing the ip of the container when it restarts.
  limit: Limit of how many times the container will restart.

Português:

Define a probabilidade de reiniciar um container durante o teste de caos e a probabilidade de trocar o ip do container quando ele reiniciar.

Entrada:
  restartProbability: Probabilidade de reiniciar um container durante o teste de caos.
  restartChangeIpProbability: Probabilidade de trocar o ip do container quando ele reiniciar.
  limit: Limite de quantas vezes o container vai reiniciar.
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetSceneNameOnChaosScene
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

Example:

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

Exemplo:

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

Example:

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

Exemplo:

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
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
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()
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetTimeOnContainerUnpausedStateOnChaosScene
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()
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetTimeToRestartThisContainerAfterStopEventOnChaosScene
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()
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetTimeToStartChaosOnChaosScene
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()
Example

{
	var err error
	var imageInspect types.ImageInspect

	err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetCacheEnable(true)

	container.MakeDefaultDockerfileForMe()

	container.SetImageName("delete:latest")

	container.SetBuildFolderPath("./test/chaos")

	container.SetContainerName("container_counter_delete_after_test")

	container.SetImageBuildOptionsMemory(100 * KMegaByte)

	container.SetCsvLogPath("./test.counter.log.csv", true)

	container.SetCsvFileValueSeparator("\t")

	container.AddFilterToCvsLogWithReplace(

		"contador",

		"counter",

		"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

		"\\.",
		",",
	)

	container.AddFilterToRestartContainer(

		"restart-me!",

		"^.*?(?P<valueToGet>restart-me!)",

		"",
		"",
	)

	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: 340",

		"^.*?(?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.AddFilterToStartChaos(
		"chaos enable",
		"chaos enable",
		"",
		"",
	)

	container.SetRestartProbability(0.9, 1.0, 1)

	container.SetTimeToStartChaosOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeBeforeStartChaosInThisContainerOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerPausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeOnContainerUnpausedStateOnChaosScene(2*time.Second, 5*time.Second)

	container.SetTimeToRestartThisContainerAfterStopEventOnChaosScene(2*time.Second, 5*time.Second)

	container.EnableChaosScene(true)

	err = container.Init()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	imageInspect, err = container.ImageBuildFromFolder()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	container.StartMonitor()

	event := container.GetChaosEvent()

	for {
		var pass = false
		select {
		case e := <-event:
			if e.Done == true || e.Error == true || e.Fail == true {
				pass = 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)
				fmt.Printf("message: %v\n", e.Message)

				break
			}
		}

		if pass == true {
			break
		}
	}

	err = container.StopMonitor()
	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	SaGarbageCollector()

}
Output
image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

Input:
  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

Entrada:
  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

Input:
  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

Entrada:
  value: texto emitido na saída padrão informando por um evento esperado
  timeout: tempo máximo de espera
Example

{
	var err error

	SaGarbageCollector()

	var container = ContainerBuilder{}

	container.SetPrintBuildOnStrOut()

	container.SetImageName("delete:latest")

	container.SetContainerName("container_delete_server_after_test")

	container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

	container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

	container.AddPortToChange("3000", "3030")

	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error())
		util.TraceToLog()
		panic(err)
	}

	err = container.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	_, err = container.ImageBuildFromServer()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
		panic(err)
	}

	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		util.TraceToLog()
		log.Printf("container.ContainerBuildAndStartFromImage().error: %v", err.Error())
		panic(err)
	}

	// English: read server inside a container on address http://localhost:3030/
	//
	// Português: lê o servidor dentro do container na porta 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)
	}

	fmt.Printf("%s", body)

	SaGarbageCollector()

}
Output
<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) SizeToString
func (e *ContainerBuilder) SizeToString(value int64) (size string)
SizeToString

Português:

Formata um valor inteiro em uma string contendo o valor em Bytes, KBytes, MBytes e GBytes.

Entrada:
  value: valor inteiro representando um tamanho de memória

Saída:
  size: string contendo o valor em Bytes, KBytes, MBytes e GBytes

English:

Format an integer value into a string containing the value in Bytes, KBytes, MBytes and GBytes.

Input:
  value: integer value representing a memory size

Output:
  size: string containing the value in Bytes, KBytes, MBytes and GBytes
func (*ContainerBuilder) StartMonitor
func (e *ContainerBuilder) StartMonitor()
StartMonitor

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.

Note:

* This function is used in conjunction with the EnableChaosScene(), SetCsvLogPath() and
  StopMonitor() functions;
* StopMonitor() Must be called at the end of the chaos test.

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(), SetCsvLogPath() e
  StopMonitor();
* StopMonitor() Must be called at the end of the chaos test.
func (*ContainerBuilder) StopMonitor
func (e *ContainerBuilder) StopMonitor() (err error)
StopMonitor

English:

Disable 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.

Note:

* This function is used in conjunction with the EnableChaosScene(), SetCsvLogPath() and
  StopMonitor() functions;
* StopMonitor() Must be called at the end of the chaos test.

Português:

Desabilita o 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(), SetCsvLogPath() e
  StopMonitor();
* StopMonitor() Deve ser chamado ao final do teste de caos.
func (ContainerBuilder) TestDockerInstall
func (e ContainerBuilder) TestDockerInstall() (err error)
TestDockerInstall

English:

Test if docker is responding correctly

Output:
  err: Standard error object

Português:

Testa se o docker está respondendo de forma correta

Saída:
  err: Standard error object
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

Input:
  value: searched text

Output:
  dockerLogs: container's default output
  err: standard error object

Português: Espera pelo texto aparecer na saída padrão do container

Entrada:
  value: texto procurado

Saída:
  dockerLogs: saída padrão do container
  err: objeto de erro padrão
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

Input:
  value: searched text
  timeout: wait timeout

Output:
  dockerLogs: container's default output
  err: standard error object

Português:

Espera pelo texto aparecer na saída padrão do container

Entrada:
  value: texto procurado
  timeout: tempo limite de espera

Saída:
  dockerLogs: saída padrão do container
  err: objeto de erro padrão
func (*ContainerBuilder) addImageBuildOptionsGitCredentials
func (e *ContainerBuilder) addImageBuildOptionsGitCredentials() (buildOptions types.ImageBuildOptions)

addImageBuildOptionsGitCredentials

English:

Prepare the git credentials.

Called from SetPrivateRepositoryAutoConfig()

Português:

Prepara as credenciais do git.

Chamada por SetPrivateRepositoryAutoConfig()

func (*ContainerBuilder) addProblem
func (e *ContainerBuilder) addProblem(problem string)

addProblem

English: Adds a description of a problem to explain the error to the user.

Input:
  problem: problem explanation

Português: Adiciona a descrição de um problema para explica o erro ao usuário.

Entrada:
  problem: descrição do problema
func (*ContainerBuilder) findCurrentIPV4AddressSupport
func (e *ContainerBuilder) findCurrentIPV4AddressSupport(networkID string) (IP string, err error)

findCurrentIPV4AddressSupport

English:

Support function for FindCurrentIpAddress()

Input:
  networkID: Docker's network ID

Output:
  IP: network IPV4 address
  err: standard error object

Português: função de apoio a FindCurrentIpAddress()

Entrada:
  networkID: ID da rede docker

Saída:
  IP: endereço IPV4 da rede
  err: objeto de erro padrão
func (*ContainerBuilder) getIdByContainerName
func (e *ContainerBuilder) getIdByContainerName() (err error)

getIdByContainerName

English:

Fills the container ID in the control object from the container name defined in SetContainerName()

Output:
  err: Standard error object

Português:

Preenche o ID do container no objeto de controle a partir do nome do container definido em SetContainerName()

Saída:
  err: Objeto de erro padrão
func (*ContainerBuilder) getProbalityNumber
func (e *ContainerBuilder) getProbalityNumber() (probality float64)

getProbalityNumber

English:

Returns a random number greater than zero and less than one

Output:
  probality: Open point floating point number between 0.0 and 1.0

Português:

Retorna um número aleatório maior do que zero e menor do que um

Saída:
  probality: Número de ponto flutuante de ponto aberto entre 0.0 e 1.0
func (*ContainerBuilder) getRandSeed
func (e *ContainerBuilder) getRandSeed() (seed *rand.Rand)

getRandSeed

English:

Generate random number seed

 Output:
   seed: random number seed

Português:

Gera a semente do número aleatório

 Saída:
   seed: semente do número aleatório
func (*ContainerBuilder) gitMakePublicSshKey
func (e *ContainerBuilder) gitMakePublicSshKey() (publicKeys *ssh.PublicKeys, err error)

gitMakePublicSshKey

English:

Mount the ssl certificate for the git clone function

Output:
  publicKeys: Ponteiro de objeto compatível com o objeto ssh.PublicKeys
  err: standard error object

Português:

Monta o certificado ssl para a função de git clone

Saída:
publicKeys: Ponteiro de objeto compatível com o objeto ssh.PublicKeys
err: objeto de erro padrão
func (*ContainerBuilder) imageExpirationTimeIsValid
func (e *ContainerBuilder) imageExpirationTimeIsValid() (valid bool)

imageExpirationTimeIsValid

English:

Detects if the image is within the expiration date.

Output:
  valid: true, if the image is within the expiry date.

Português:

Detecta se a imagem está dentro do prazo de validade.

Saída:
  valid: true, se a imagem está dentro do prazo de validade.
func (*ContainerBuilder) incIpV4Address
func (e *ContainerBuilder) incIpV4Address(ip string, inc int64) (next string, err error)

incIpV4Address

English:

Receives an IP address in the form of a string and increments it.

Input:
  ip:  only the ip address. e.g.: 10.0.0.1
  inc: number of increments

Output:
  next: the next ip address. e.g.: 10.0.0.2
  err: standard error object

Note:

* This function does not take into account the network configuration, use it with care!

Português:

Recebe um endereço IP na forma de string e incrementa o mesmo.

Entrada:
  ip:  apenas o endereço ip. ex.: 10.0.0.1
  inc: quantidade de incrementos

Saída:
  next: o próximo endereço ip. ex.: 10.0.0.2
  err: objeto de erro padrão

Nota:

Esta função não considera a configuração da rede, use com cuidado!
func (*ContainerBuilder) logsCleaner
func (e *ContainerBuilder) logsCleaner(logs []byte) (logsLine [][]byte)

logsCleaner

English:

Clear blank lines of the container's standard output

Input:
  logs: container's standard output

Output:
  logsLine: List of lines of the container's standard output

Português:

Limpa as linhas em branco da saída padrão do container

 Entrada:
   logs: saída padrão do container

 Saída:
   logsLine: Lista de linhas da saída padrão do container
func (*ContainerBuilder) logsSearchAndReplaceIntoText
func (e *ContainerBuilder) logsSearchAndReplaceIntoText(logs *[]byte, lineList [][]byte, configuration []LogFilter) (line []byte, found bool)
func (*ContainerBuilder) managerChaos
func (e *ContainerBuilder) managerChaos()

managerChaos

English: manages the log and state of the container

Português: gerencia o log e o estado do container

func (*ContainerBuilder) selectBetweenMaxAndMin
func (e *ContainerBuilder) selectBetweenMaxAndMin(max, min time.Duration) (selected time.Duration)
func (*ContainerBuilder) stopMonitorAfterStopped
func (e *ContainerBuilder) stopMonitorAfterStopped() (err error)
func (ContainerBuilder) traceCodeLine
func (e ContainerBuilder) traceCodeLine() (file string, line int)
func (*ContainerBuilder) verifyImageName
func (e *ContainerBuilder) verifyImageName() (err error)

verifyImageName

English: check if the image name has the version tag

Português: verifica se o nome da imagem tem a tag de versão

func (*ContainerBuilder) verifyStatusError
func (e *ContainerBuilder) verifyStatusError(inspect iotmakerdocker.ContainerInspect) (hasError bool)
func (*ContainerBuilder) writeAggregatePreCPUTimeTheContainerWasThrottled
func (e *ContainerBuilder) writeAggregatePreCPUTimeTheContainerWasThrottled(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeAggregateTimeTheContainerWasThrottledForInNanoseconds
func (e *ContainerBuilder) writeAggregateTimeTheContainerWasThrottledForInNanoseconds(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoMergedRecursive
func (e *ContainerBuilder) writeBlkioIoMergedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoQueuedRecursive
func (e *ContainerBuilder) writeBlkioIoQueuedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoServiceBytesRecursive
func (e *ContainerBuilder) writeBlkioIoServiceBytesRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoServiceTimeRecursive
func (e *ContainerBuilder) writeBlkioIoServiceTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoServicedRecursive
func (e *ContainerBuilder) writeBlkioIoServicedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoTimeRecursive
func (e *ContainerBuilder) writeBlkioIoTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioIoWaitTimeRecursive
func (e *ContainerBuilder) writeBlkioIoWaitTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeBlkioSectorsRecursive
func (e *ContainerBuilder) writeBlkioSectorsRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeCommittedBytes
func (e *ContainerBuilder) writeCommittedBytes(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstAggregatePreCPUTimeTheContainerWasThrottled
func (e *ContainerBuilder) writeConstAggregatePreCPUTimeTheContainerWasThrottled(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstAggregateTimeTheContainerWasThrottledForInNanoseconds
func (e *ContainerBuilder) writeConstAggregateTimeTheContainerWasThrottledForInNanoseconds(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoMergedRecursive
func (e *ContainerBuilder) writeConstBlkioIoMergedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoQueuedRecursive
func (e *ContainerBuilder) writeConstBlkioIoQueuedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoServiceBytesRecursive
func (e *ContainerBuilder) writeConstBlkioIoServiceBytesRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoServiceTimeRecursive
func (e *ContainerBuilder) writeConstBlkioIoServiceTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoServicedRecursive
func (e *ContainerBuilder) writeConstBlkioIoServicedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoTimeRecursive
func (e *ContainerBuilder) writeConstBlkioIoTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioIoWaitTimeRecursive
func (e *ContainerBuilder) writeConstBlkioIoWaitTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstBlkioSectorsRecursive
func (e *ContainerBuilder) writeConstBlkioSectorsRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeConstCommittedBytes
func (e *ContainerBuilder) writeConstCommittedBytes(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstCurrentNumberOfOidsInTheCGroup
func (e *ContainerBuilder) writeConstCurrentNumberOfOidsInTheCGroup(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstCurrentResCounterUsageForMemory
func (e *ContainerBuilder) writeConstCurrentResCounterUsageForMemory(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstFilterIntoLog
func (e *ContainerBuilder) writeConstFilterIntoLog(file *os.File, filter []LogFilter) (tab bool, err error)
func (*ContainerBuilder) writeConstLimitOnTheNumberOfPidsInTheCGroup
func (e *ContainerBuilder) writeConstLimitOnTheNumberOfPidsInTheCGroup(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstMaximumUsageEverRecorded
func (e *ContainerBuilder) writeConstMaximumUsageEverRecorded(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstMemoryLimit
func (e *ContainerBuilder) writeConstMemoryLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit
func (e *ContainerBuilder) writeConstNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit
func (e *ContainerBuilder) writeConstNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstNumberOfPeriodsWithPreCPUThrottlingActive
func (e *ContainerBuilder) writeConstNumberOfPeriodsWithPreCPUThrottlingActive(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstNumberOfPeriodsWithThrottlingActive
func (e *ContainerBuilder) writeConstNumberOfPeriodsWithThrottlingActive(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstNumberOfTimesMemoryUsageHitsLimits
func (e *ContainerBuilder) writeConstNumberOfTimesMemoryUsageHitsLimits(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstOnlineCPUs
func (e *ContainerBuilder) writeConstOnlineCPUs(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstOnlinePreCPUs
func (e *ContainerBuilder) writeConstOnlinePreCPUs(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstPeakCommittedBytes
func (e *ContainerBuilder) writeConstPeakCommittedBytes(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstPreCPUSystemUsage
func (e *ContainerBuilder) writeConstPreCPUSystemUsage(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstPrivateWorkingSet
func (e *ContainerBuilder) writeConstPrivateWorkingSet(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstReadingTime
func (e *ContainerBuilder) writeConstReadingTime(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstSystemUsage
func (e *ContainerBuilder) writeConstSystemUsage(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTimeSpentByPreCPUTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeConstTimeSpentByPreCPUTasksOfTheCGroupInKernelMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTimeSpentByPreCPUTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeConstTimeSpentByPreCPUTasksOfTheCGroupInUserMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTimeSpentByTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeConstTimeSpentByTasksOfTheCGroupInKernelMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTimeSpentByTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeConstTimeSpentByTasksOfTheCGroupInUserMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTotalCPUTimeConsumed
func (e *ContainerBuilder) writeConstTotalCPUTimeConsumed(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTotalCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeConstTotalCPUTimeConsumedPerCore(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTotalPreCPUTimeConsumed
func (e *ContainerBuilder) writeConstTotalPreCPUTimeConsumed(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeConstTotalPreCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeConstTotalPreCPUTimeConsumedPerCore(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeContainerConstToFile
func (e *ContainerBuilder) writeContainerConstToFile(file *os.File, stats *types.Stats) (err error)
func (*ContainerBuilder) writeContainerLabelToFile
func (e *ContainerBuilder) writeContainerLabelToFile(file *os.File, stats *types.Stats) (err error)
func (*ContainerBuilder) writeContainerLogToFile
func (e *ContainerBuilder) writeContainerLogToFile(path string, lineList [][]byte) (err error)

writeContainerLogToFile

Português: Escreve um arquivo csv com dados capturados da saída padrão do container e dados estatísticos do container

func (*ContainerBuilder) writeContainerStatsToFile
func (e *ContainerBuilder) writeContainerStatsToFile(file *os.File, stats *types.Stats, lineList *[][]byte) (err error)
func (*ContainerBuilder) writeCurrentNumberOfOidsInTheCGroup
func (e *ContainerBuilder) writeCurrentNumberOfOidsInTheCGroup(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeCurrentResCounterUsageForMemory
func (e *ContainerBuilder) writeCurrentResCounterUsageForMemory(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeFilterIntoLog
func (e *ContainerBuilder) writeFilterIntoLog(file *os.File, filter []LogFilter, lineList *[][]byte) (tab bool, err error)
func (*ContainerBuilder) writeLabelAggregatePreCPUTimeTheContainerWasThrottled
func (e *ContainerBuilder) writeLabelAggregatePreCPUTimeTheContainerWasThrottled(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelAggregateTimeTheContainerWasThrottledForInNanoseconds
func (e *ContainerBuilder) writeLabelAggregateTimeTheContainerWasThrottledForInNanoseconds(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoMergedRecursive
func (e *ContainerBuilder) writeLabelBlkioIoMergedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoQueuedRecursive
func (e *ContainerBuilder) writeLabelBlkioIoQueuedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoServiceBytesRecursive
func (e *ContainerBuilder) writeLabelBlkioIoServiceBytesRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoServiceTimeRecursive
func (e *ContainerBuilder) writeLabelBlkioIoServiceTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoServicedRecursive
func (e *ContainerBuilder) writeLabelBlkioIoServicedRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoTimeRecursive
func (e *ContainerBuilder) writeLabelBlkioIoTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioIoWaitTimeRecursive
func (e *ContainerBuilder) writeLabelBlkioIoWaitTimeRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelBlkioSectorsRecursive
func (e *ContainerBuilder) writeLabelBlkioSectorsRecursive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeLabelCommittedBytes
func (e *ContainerBuilder) writeLabelCommittedBytes(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelCurrentNumberOfOidsInTheCGroup
func (e *ContainerBuilder) writeLabelCurrentNumberOfOidsInTheCGroup(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelCurrentResCounterUsageForMemory
func (e *ContainerBuilder) writeLabelCurrentResCounterUsageForMemory(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelFilterIntoLog
func (e *ContainerBuilder) writeLabelFilterIntoLog(file *os.File, filter []LogFilter) (tab bool, err error)
func (*ContainerBuilder) writeLabelLimitOnTheNumberOfPidsInTheCGroup
func (e *ContainerBuilder) writeLabelLimitOnTheNumberOfPidsInTheCGroup(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelMaximumUsageEverRecorded
func (e *ContainerBuilder) writeLabelMaximumUsageEverRecorded(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelMemoryLimit
func (e *ContainerBuilder) writeLabelMemoryLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit
func (e *ContainerBuilder) writeLabelNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit
func (e *ContainerBuilder) writeLabelNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelNumberOfPeriodsWithPreCPUThrottlingActive
func (e *ContainerBuilder) writeLabelNumberOfPeriodsWithPreCPUThrottlingActive(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelNumberOfPeriodsWithThrottlingActive
func (e *ContainerBuilder) writeLabelNumberOfPeriodsWithThrottlingActive(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelNumberOfTimesMemoryUsageHitsLimits
func (e *ContainerBuilder) writeLabelNumberOfTimesMemoryUsageHitsLimits(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelOnlineCPUs
func (e *ContainerBuilder) writeLabelOnlineCPUs(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelOnlinePreCPUs
func (e *ContainerBuilder) writeLabelOnlinePreCPUs(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelPeakCommittedBytes
func (e *ContainerBuilder) writeLabelPeakCommittedBytes(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelPreCPUSystemUsage
func (e *ContainerBuilder) writeLabelPreCPUSystemUsage(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelPrivateWorkingSet
func (e *ContainerBuilder) writeLabelPrivateWorkingSet(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelReadingTime
func (e *ContainerBuilder) writeLabelReadingTime(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelSystemUsage
func (e *ContainerBuilder) writeLabelSystemUsage(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTimeSpentByPreCPUTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeLabelTimeSpentByPreCPUTasksOfTheCGroupInKernelMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTimeSpentByPreCPUTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeLabelTimeSpentByPreCPUTasksOfTheCGroupInUserMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTimeSpentByTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeLabelTimeSpentByTasksOfTheCGroupInKernelMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTimeSpentByTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeLabelTimeSpentByTasksOfTheCGroupInUserMode(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTotalCPUTimeConsumed
func (e *ContainerBuilder) writeLabelTotalCPUTimeConsumed(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTotalCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeLabelTotalCPUTimeConsumedPerCore(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTotalPreCPUTimeConsumed
func (e *ContainerBuilder) writeLabelTotalPreCPUTimeConsumed(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLabelTotalPreCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeLabelTotalPreCPUTimeConsumedPerCore(file *os.File) (tab bool, err error)
func (*ContainerBuilder) writeLimitOnTheNumberOfPidsInTheCGroup
func (e *ContainerBuilder) writeLimitOnTheNumberOfPidsInTheCGroup(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeMaximumUsageEverRecorded
func (e *ContainerBuilder) writeMaximumUsageEverRecorded(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeMemoryLimit
func (e *ContainerBuilder) writeMemoryLimit(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit
func (e *ContainerBuilder) writeNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit
func (e *ContainerBuilder) writeNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeNumberOfPeriodsWithPreCPUThrottlingActive
func (e *ContainerBuilder) writeNumberOfPeriodsWithPreCPUThrottlingActive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeNumberOfPeriodsWithThrottlingActive
func (e *ContainerBuilder) writeNumberOfPeriodsWithThrottlingActive(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeNumberOfTimesMemoryUsageHitsLimits
func (e *ContainerBuilder) writeNumberOfTimesMemoryUsageHitsLimits(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeOnlineCPUs
func (e *ContainerBuilder) writeOnlineCPUs(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeOnlinePreCPUs
func (e *ContainerBuilder) writeOnlinePreCPUs(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writePeakCommittedBytes
func (e *ContainerBuilder) writePeakCommittedBytes(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writePreCPUSystemUsage
func (e *ContainerBuilder) writePreCPUSystemUsage(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writePrivateWorkingSet
func (e *ContainerBuilder) writePrivateWorkingSet(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeReadingTime
func (e *ContainerBuilder) writeReadingTime(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeSystemUsage
func (e *ContainerBuilder) writeSystemUsage(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTimeSpentByPreCPUTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeTimeSpentByPreCPUTasksOfTheCGroupInKernelMode(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTimeSpentByPreCPUTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeTimeSpentByPreCPUTasksOfTheCGroupInUserMode(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTimeSpentByTasksOfTheCGroupInKernelMode
func (e *ContainerBuilder) writeTimeSpentByTasksOfTheCGroupInKernelMode(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTimeSpentByTasksOfTheCGroupInUserMode
func (e *ContainerBuilder) writeTimeSpentByTasksOfTheCGroupInUserMode(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTotalCPUTimeConsumed
func (e *ContainerBuilder) writeTotalCPUTimeConsumed(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTotalCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeTotalCPUTimeConsumedPerCore(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTotalPreCPUTimeConsumed
func (e *ContainerBuilder) writeTotalPreCPUTimeConsumed(file *os.File, stats *types.Stats) (tab bool, err error)
func (*ContainerBuilder) writeTotalPreCPUTimeConsumedPerCore
func (e *ContainerBuilder) writeTotalPreCPUTimeConsumedPerCore(file *os.File, stats *types.Stats) (tab bool, err error)

type DockerfileAuto

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 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()
}

type Event

type Event struct {
    ContainerName string
    Message       string
    Error         bool
    Done          bool
    Fail          bool
    Metadata      map[string]interface{}
}
func (*Event) clear
func (e *Event) clear()

type HealthConfig

HealthConfig

English: holds configuration settings for the HEALTHCHECK feature.

Português: contém as configurações para o HEALTHCHECK

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"`
}

type LogFilter

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

MemoryStats aggregates all memory stats since container inception on Linux. Windows returns stats for commit and private working set only.

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"`
}

type NameAndId

type NameAndId struct {
    ID   string
    Name string
}

type NetworkChaos

type NetworkChaos struct {
    imageName     string
    builder       *ContainerBuilder
    overload      *ContainerBuilder
    network       isolatedNetwork.ContainerBuilderNetworkInterface
    containerName string
    listenPort    int
    outputPort    int
    invert        bool
}
func (*NetworkChaos) Init
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

	SaGarbageCollector()

	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
}
Output

func (*NetworkChaos) SetContainerName
func (e *NetworkChaos) SetContainerName(value string)
func (*NetworkChaos) SetFatherContainer
func (e *NetworkChaos) SetFatherContainer(fatherContainer *ContainerBuilder)
func (*NetworkChaos) SetNetworkDocker
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
func (e *NetworkChaos) SetPorts(listenPort, outputPort int, invert bool)
func (*NetworkChaos) imageExists
func (e *NetworkChaos) imageExists() (exists bool)

type PidsStats

PidsStats contains the stats of a container's pids

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"`
}

type Restart

type Restart struct {
    FilterToStart      []LogFilter
    TimeToStart        Timers
    RestartProbability float64
    RestartLimit       int

    minimumEventTime time.Time
}

type Stats

Stats is Ultimate struct aggregating all types of stats of one container

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"`
}

type StorageStats

StorageStats is the disk I/O stats for read/write on Windows.

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"`
}

type TestContainerLog

type TestContainerLog struct {
    data [][][]byte
}
func (*TestContainerLog) fileToDataFormat
func (e *TestContainerLog) fileToDataFormat(path string, t *testing.T) (problem pb.Problem)
func (TestContainerLog) findKeyIndex
func (e TestContainerLog) findKeyIndex(key string, t *testing.T) (index int, problem pb.Problem)
func (*TestContainerLog) makeTest
func (e *TestContainerLog) makeTest(path string, listUnderTest *[]parserLog, t *testing.T) (problem pb.Problem)
func (TestContainerLog) proccessKeyList
func (e TestContainerLog) proccessKeyList(listUnderTest *[]parserLog, t *testing.T) (problem pb.Problem)

type Theater

Theater

English: Theater is the collection of scene

Português: Teatro é a coleção de cenas

type Theater struct {
    s   sync.Mutex
    m   map[string]scene
}
func (*Theater) ConfigScene
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
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
func (e *Theater) SetContainerPaused(sceneName string) (doNotPauseContainer bool)
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
func (e *Theater) SetContainerStopped(sceneName string) (IsOnTheEdge bool)
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
func (e *Theater) SetContainerUnPaused(sceneName string)
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
func (e *Theater) SetContainerUnStopped(sceneName string)
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

ThrottlingData stores CPU throttling stats of one running container. Not used on Windows.

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"`
}

type Timers

type Timers struct {
    Min time.Duration
    Max time.Duration
}

type chaos

chaos

English:

Object chaos manager

Português:

Objeto gerenciador de caos

type chaos struct {
    foundSuccess               bool
    foundFail                  bool
    filterToStart              []LogFilter
    filterRestart              []LogFilter
    filterSuccess              []LogFilter
    filterFail                 []LogFilter
    filterLog                  []LogFilter
    sceneName                  string
    logPath                    string
    serviceStartedAt           time.Time
    minimumTimeBeforeRestart   time.Duration
    maximumTimeBeforeRestart   time.Duration
    minimumTimeToStartChaos    time.Duration
    maximumTimeToStartChaos    time.Duration
    minimumTimeToPause         time.Duration
    maximumTimeToPause         time.Duration
    minimumTimeToUnpause       time.Duration
    maximumTimeToUnpause       time.Duration
    minimumTimeToRestart       time.Duration
    maximumTimeToRestart       time.Duration
    restartProbability         float64
    restartChangeIpProbability float64
    restartLimit               int
    enableChaos                bool
    event                      chan Event
    monitorStop                chan struct{}
    monitorRunning             bool
    //containerStarted         bool
    containerPaused          bool
    containerStopped         bool
    linear                   bool
    chaosStarted             bool
    chaosCanRestartContainer bool
    //chaosCanRestartEnd       bool
    eventNext time.Time

    disableStopContainer  bool
    disablePauseContainer bool
}

type gitData

gitData

English: struct based on go-git framework

Português: Estrutura de dados baseada no framework go-git

type gitData struct {
    url               string
    sshPrivateKeyPath string
    privateToke       string
    user              string
    password          string
}

type parserLog

type parserLog struct {
    Label string
    Key   string
    Rule  string
}

type scene

scene

English: Determines the maximum number of stopped and paused containers per scene. The scene grants some control over the chaos in container testing, preventing all containers in a scene from pausing or stopping at the same time.

Português: Determina os números máximos de containers parados e pausados por cena. A cena garante algum controle sobre o caos no teste dos container, impedindo que todos os containers de uma cena sejam pausando ou parados ao mesmo tempo.

type scene struct {
    StopedContainers                   int
    PausedContainers                   int
    MaxStopedContainers                int
    MaxPausedContainers                int
    MaxTotalPausedAndStoppedContainers int
}

Generated by gomarkdoc

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 transparente.

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 gateway 10.0.0.1
	// Use the term "delete" to enable the function "dockerBuilder.SaGarbageCollector()", 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.SaGarbageCollector()", 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)
	// Initialize 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 gateway 10.0.0.1
	// Use the term "delete" to enable the function "dockerBuilder.SaGarbageCollector()", 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.SaGarbageCollector()", 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.SaGarbageCollector()", 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-iotmaker" 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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./memory/config", "/config")
	if err != nil {
		log.Printf("error: %v", err)
		t.Fail()
	}
	// Initialize 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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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.SaGarbageCollector()", 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")
	// Initialize 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ódigo 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 dependências e programas necessários para o processador 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

Examples

Constants

View Source
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
)
View Source
const (
	KLogReadingTimeLabel = "Reading time"
	KLogReadingTimeValue = "KReadingTime"
	//deixou de funcionar após atualização do docker
	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()

func SaGarbageCollector added in v0.9.42

func SaGarbageCollector(names ...string)

SaGarbageCollector

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 SaImageMakeCache added in v0.9.42

func SaImageMakeCache(projectPath, cacheName string, expirationDate time.Duration) (err error)

SaImageMakeCache

English:

Creates a cached image used as a basis for creating new images.

 Input:
   projectPath: path of the project folder
   cacheName: name of the cache image
   expirationDate: expiration date of the image

 Output:
   err: standard object error

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.

 Input:
   projectPath: caminha da pasta do projeto
   cacheName: nome da imagem cache
   expirationDate: data de expiração da imagem.

 Output:
   err: standard object error

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 SaImageMakeCacheWithDefaultName added in v0.9.42

func SaImageMakeCacheWithDefaultName(projectPath string, expirationDate time.Duration) (err error)

SaImageMakeCache

English:

Creates a cached image used as a basis for creating new images.

 Input:
   projectPath: path of the project folder
   expirationDate: expiration date of the image

 Output:
   err: standard object error

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.

 Input:
   projectPath: caminha da pasta do projeto
   expirationDate: data de expiração da imagem.

 Output:
   err: standard object error

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`;

func SaTestDockerInstall added in v0.9.43

func SaTestDockerInstall() (err error)

SaTestDockerInstall

English:

Test if docker is responding correctly

 Output:
   err: Standard error object

Português:

Testa se o docker está respondendo de forma correta

 Saída:
   err: Standard error object

func SaVolumeCreate added in v1.0.46

func SaVolumeCreate(
	labels map[string]string,
	name string,
) (
	volume types.Volume,
	err error,
)

SaVolumeCreate

English:

Create a docker volume

 Input:
   labels: labels list
   name: volume name

 Output:
   list: docker volume list
   err: Standard error object

Português:

Cria um volume docker

 Input:
   labels: lista de rótulos
   name: nome do volume

 Saída:
   list: lista de volumes docker
   err: Objeto de erro padrão

func SaVolumeList added in v1.0.46

func SaVolumeList() (list []types.Volume, err error)

SaVolumeList

English:

List all docker volumes

 Output:
   list: docker volume list
   err: Standard error object

Português:

Lista todos os volumes docker

 Saída:
   list: lista de volumes docker
   err: Objeto de erro padrão

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
Example (FuncSetTimeOnContainerPausedStateOnChaosScene)
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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]
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// English: Defines the column name
	//
	// Português: Define o nome da coluna
	"contador",

	// English: Defines the text to be searched
	//
	// Português: Define o texto a ser procurado
	"counter",

	// English: Defines the regular expression to be applied on the found text
	//
	// Português: Define a expressão regular a ser aplicada no texto encontrado
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

	// English: Defines the text to be replaced on the found text
	//
	// Português: Define o texto a ser substituído no texto encontrado
	"\\.",

	// English: Defines the text to be written on replaced text
	//
	// Português: Define o texto a ser escrito no texto substituído
	",",
)

// 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(
	// English: Defines the text to be searched
	//
	// Português: Define o texto a ser procurado
	"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(
	// English: Defines the text to be searched
	//
	// Português: Define o texto a ser procurado
	"bug:",

	// English: Defines the path to the container standard output to be save as text file
	//
	// Português: Define o caminho onde a saída padrão do container será salva em formato de arquivo texto
	"./log1/log2/log3",
)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)

			break
		}
	}

	if pass == 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 SaGarbageCollector() 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 SaGarbageCollector().
// [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]
SaGarbageCollector()

var data []byte
data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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/")
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: false
fail: true
error: false

func (*ContainerBuilder) AddFailMatchFlagToFileLog added in v0.9.25

func (e *ContainerBuilder) AddFailMatchFlagToFileLog(value, logDirectoryPath string) (err error)

AddFailMatchFlagToFileLog

Similar:

AddFailMatchFlag(), AddFailMatchFlagToFileLog(), AddFilterToFail()

English:

Looks for error text in the container's standard output and saves it to a log file on the host
computer

 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:

Procura por um texto indicativo de erro na saída padrão do container e o salva em um arquivo de
log no computador hospedeiro

 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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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]
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// English: Defines the column name
	//
	// Português: Define o nome da coluna
	"contador",

	// English: Defines the text to be searched
	//
	// Português: Define o texto a ser procurado
	"counter",

	// English: Defines the regular expression to be applied on the found text
	//
	// Português: Define a expressão regular a ser aplicada no texto encontrado
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

	// English: Defines the text to be replaced on the found text
	//
	// Português: Define o texto a ser substituído no texto encontrado
	"\\.",

	// English: Defines the text to be written on replaced text
	//
	// Português: Define o texto a ser escrito no texto substituído
	",",
)

// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)

			break
		}
	}

	if pass == 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 SaGarbageCollector() 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 SaGarbageCollector().
// [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]
SaGarbageCollector()

var data []byte
data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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/")
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: false
fail: true
error: false

func (*ContainerBuilder) AddFileOrFolderToLinkBetweenComputerHostAndContainer added in v1.0.17

func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenComputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)

AddFileOrFolderToLinkBetweenComputerHostAndContainer

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
var err error

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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]
SaGarbageCollector()

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.builder.public.example.git")

// English: See the functions: SetGitCloneToBuildWithUserPassword(), SetGitCloneToBuildWithPrivateSshKey() and SetGitCloneToBuildWithPrivateToken()
//
// Português: Veja as funções: SetGitCloneToBuildWithUserPassword(), 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.AddFileOrFolderToLinkBetweenComputerHostAndContainer(
	"./test/static",
	"/static",
)
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().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)
}

// 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]
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) AddFileToServerBeforeBuild added in v1.0.32

func (e *ContainerBuilder) AddFileToServerBeforeBuild(dst, src string)

func (*ContainerBuilder) AddFilterToCvsLog added in v0.9.42

func (e *ContainerBuilder) AddFilterToCvsLog(label, match, filter string)

AddFilterToCvsLog

Similar:

AddFilterToCvsLogWithReplace(), AddFilterToCvsLog()

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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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")

// 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: Prints the name of the constant used for each column of the container on the first line
// of the report.
// This function must be used in conjunction with the container.SetCsvFileRowsToPrint() function.
//
// Português: Imprime na primeira linha do relatório o nome da constante usada para cada coluna
// do container.
// Esta função deve ser usada em conjunto com a função container.SetCsvFileRowsToPrint()
container.SetCsvFileReader(true)

// 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.AddFilterToCvsLogWithReplace(
	// English: Defines the column name
	//
	// Português: Define o nome da coluna
	"contador",

	// English: Defines the text to be searched
	//
	// Português: Define o texto a ser procurado
	"counter",

	// English: Defines the regular expression to be applied on the found text
	//
	// Português: Define a expressão regular a ser aplicada no texto encontrado
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

	// English: Defines the text to be replaced on the found text
	//
	// Português: Define o texto a ser substituído no texto encontrado
	"\\.",

	// English: Defines the text to be written on replaced text
	//
	// Português: Define o texto a ser escrito no texto substituído
	":",
)

// 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].
	//          Use this feature to clear the message printed on test success event.
	//
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	//            Use esta funcionalidade para limpar a mensagem impressa no evento de sucesso do teste.
	"(?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: 40000000",

	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) AddFilterToCvsLogWithReplace added in v0.9.42

func (e *ContainerBuilder) AddFilterToCvsLogWithReplace(label, match, filter, search, replace string)

AddFilterToCvsLogWithReplace

Similar:

AddFilterToCvsLogWithReplace(), AddFilterToCvsLog()

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) 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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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: 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: 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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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].
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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 log file path with container statistical data
//
// Português: Define o separador usado no arquivo de log em formato 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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234

  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

https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg
docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234

  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) AddMonitorMatchFlagToFileLog added in v1.0.45

func (e *ContainerBuilder) AddMonitorMatchFlagToFileLog(value, logDirectoryPath string) (err error)

AddMonitorMatchFlagToFileLog

English:

Looks for text in the container's standard output and saves it to a log file on the host
computer

 Input:
   value: 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:

Procura por um texto indicativo na saída padrão do container e o salva em um arquivo de log no computador hospedeiro

 Entrada:
   value: Texto indicativo
   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) 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
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.
SaGarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// 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: Project to be cloned from github
//
// Português: Projeto para ser clonado do github
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.builder.public.example.git")

// English: See SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
//
// Português: 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 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
//
// English: troca a porta 3000 pela porta 3030
container.AddPortToChange("3000", "3030")

// English: replace container folder /static to host folder ./test/static
//
// Português: substitui a pasta do container /static pela pasta do host ./test/static
err = container.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().error: %v", err.Error())
	util.TraceToLog()
	panic(err)
}

// English: inicialize container object
//
// Português: inicializa o objeto container
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// English: builder new image from git project
//
// Português: monta a nova imagem a partir do projeto git
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

// English: container build from image delete:latest
//
// Português: monta o container a partir da imagem delete:latest
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 neste ponto de código na porta 3030

// English: read server inside a container on address http://localhost:3030/
//
// Português: lê o servidor dentro do container na porta 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)
}

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.
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

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
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.
SaGarbageCollector()

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")

// 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.builder.public.example.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)

// English: open port 3000
//
// Português: abre porta 3000
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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().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)
}

// English: builder new image from git project
//
// Português: monta a nova imagem a partir do projeto git
_, 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 3000
//
// Português: container "container_delete_server_after_test" executando e pronto para uso neste ponto de código na porta 3000

// English: read server inside a container on address http://localhost:3030/
//
// Português: lê o servidor dentro do container na porta http://localhost:3030/
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)

// 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.
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

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.
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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.AddRestartMatchFlag(
	// 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: 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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.
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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.
err = container.AddRestartMatchFlagToFileLog(
	// 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: Defines the path to the container standard output to be save as text file
	//
	// Português: Define o caminho onde a saída padrão do container será salva em formato de arquivo texto
	"./log1/log2/log3",
)

// 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())
	SaGarbageCollector()
	return
}

// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

SaGarbageCollector()

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.builder.public.example.git")

// see SetGitCloneToBuildWithUserPassword(), 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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().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)

SaGarbageCollector()
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
Example
package main

import (
	"fmt"
	"github.com/docker/docker/api/types"
	"log"
	"os"
)

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]
	SaGarbageCollector()

	err = buildGoLintImageCopyFromExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = buildAlpineImageCopyFromExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	_ = os.Remove("./example/golint/golangci-lint")

}

func buildGoLintImageCopyFromExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	fmt.Printf("file name: %v\n", copyResponse[0].Name)

	return
}

func buildAlpineImageCopyFromExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.ContainerCopyTo(
		[]string{"./example/golint/golangci-lint"},
		[]string{"/go"},
	)

	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	var exitCode int
	var running bool
	var stdOutput []byte
	var stdError []byte
	exitCode, running, stdOutput, stdError, err = container.ContainerExecCommand([]string{"ls", "-l"})

	log.Printf("exitCode: %v", exitCode)
	log.Printf("running: %v", running)
	log.Printf("stdOutput: %v", string(stdOutput))
	log.Printf("stdError: %v", string(stdError))

	exitCode, running, stdOutput, stdError, err = container.ContainerExecCommand([]string{"./golangci-lint"})

	log.Printf("exitCode: %v", exitCode)
	log.Printf("running: %v", running)
	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]
	SaGarbageCollector()

	return
}
Output:

image size: 510.9 MB
image os: linux
file name: golangci-lint
image size: 281.8 MB
image os: linux

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"
	"os"
)

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]
	SaGarbageCollector()

	err = buildGoLintImageCopyToExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = builAlpineImageCopyToExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	_ = os.Remove("./example/golint/golangci-lint")

}

func buildGoLintImageCopyToExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	fmt.Printf("file name: %v\n", copyResponse[0].Name)

	return
}

func builAlpineImageCopyToExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.ContainerCopyTo(
		[]string{"./example/golint/golangci-lint"},
		[]string{"/go"},
	)

	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	return
}
Output:

image size: 510.9 MB
image os: linux
file name: golangci-lint
image size: 281.8 MB
image os: linux

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.
Example
package main

import (
	"fmt"
	"github.com/docker/docker/api/types"
	"log"
	"os"
)

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]
	SaGarbageCollector()

	err = buildGoLintImageExecCommandExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	err = builAlpineImageExecCommandExample()
	if err != nil {
		fmt.Printf("error: %v", err.Error())
		SaGarbageCollector()
		return
	}

	_ = os.Remove("./example/golint/golangci-lint")

}

func buildGoLintImageExecCommandExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	fmt.Printf("file name: %v\n", copyResponse[0].Name)

	return
}

func builAlpineImageExecCommandExample() (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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		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())
		SaGarbageCollector()
		return
	}

	err = container.ContainerCopyTo(
		[]string{"./example/golint/golangci-lint"},
		[]string{"/go"},
	)

	if err != nil {
		log.Printf("error: %v", err.Error())
		SaGarbageCollector()
		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]
	SaGarbageCollector()

	return
}
Output:

image size: 510.9 MB
image os: linux
file name: golangci-lint
image size: 281.8 MB
image os: linux

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:

Starts a newly created container.

 Output:
   err: standard 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, in case you need to control the container.

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) DockerfileAddCopyToFinalImage added in v1.0.18

func (e *ContainerBuilder) DockerfileAddCopyToFinalImage(src, dst string)

DockerfileAddCopyToFinalImage

English:

Add one instruction 'COPY --from=builder /app/`dst` `src`' to final image builder.

Português:

Adiciona uma instrução 'COPY --from=builder /app/`dst` `src`' ao builder da imagem final.

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()

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

SaGarbageCollector()

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

SaGarbageCollector()

// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
	util.TraceToLog()
	panic(err)
}
Output:

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)

GetChaosEvent

English:

 Returns channel of Chaos Winds.

  Output:
    eventChannel: chaos event channel
      ContainerName: container name
	     Message: Error message or event suffered by container, as aborted by system.
	     Error: True if there is an error
	     Done: Trick for when the chaos roll was successful. See the AddSuccessMatchFlag() function
	     Fail: True for when the chaos test failed. See the functions AddFailMatchFlag(),
	           AddFailMatchFlagToFileLog(), AddFilterToFail()
	     Metadata: Data defined by the SetMetadata() function

Português:

 Retorna o canal de ventos de caos.

  Saída:
    eventChannel: canal de eventos de caos
      ContainerName: Nome do container
	     Message: Mensagem de erro ou evento sofrido pelo container, como abortado pelo sistema.
	     Error: True se houver erro
	     Done: True para quando o teste de caos foi bem sucessido. Veja a função AddSuccessMatchFlag()
	     Fail: True para quando o teste de caos falhou. Veja as funções AddFailMatchFlag(),
	           AddFailMatchFlagToFileLog(), AddFilterToFail()
	     Metadata: Dados definidos pela função SetMetadata()

func (*ContainerBuilder) GetContainerID

func (e *ContainerBuilder) GetContainerID() (ID string)

GetContainerID

English:

Returns the ID of the created container

 Output:
   ID: ID of the container

Português:

Retorna o ID do container criado

 Saída:
   ID: ID do container

func (*ContainerBuilder) GetContainerInfo added in v0.9.11

func (e *ContainerBuilder) GetContainerInfo() (info types.Info, err error)

GetContainerInfo

English:

Returns a series of information about the container.

 Output:
   info: Container information.
   err: Standard error object.

Português:

Retorna uma séries de informações sobre o container.

 Saída:
   info: Informações sobre o container.
   err: Objeto padrão de erro.

func (ContainerBuilder) GetContainerIsStarted added in v0.9.11

func (e ContainerBuilder) GetContainerIsStarted() (started bool)

GetContainerIsStarted

English:

Returns if the container was initialized after it was generated.

 Output:
   started: true for container initialized after generated

Português:

Retorna se o container foi inicializado depois de gerado.

 Saída:
   started: true para container inicializado depois de gerado

func (*ContainerBuilder) GetContainerLog

func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)

GetContainerLog

English:

Returns the current standard output of the container.

 Output:
   log: Texts contained in the container's standard output
   err: Standard error object

Português:

Retorna a saída padrão atual do container.

 Saída:
   log: Textos contidos na saída padrão do container
   err: Objeto de erro padrão

func (*ContainerBuilder) GetContainerName added in v0.9.11

func (e *ContainerBuilder) GetContainerName() (containerName string)

GetContainerName

English:

Returns container name

 Output:
   containerName: Container name

Português:

Retorna o nome do container

 Saída:
   containerName: Nome do container

func (*ContainerBuilder) GetFailFlag added in v0.9.32

func (e *ContainerBuilder) GetFailFlag() (fail bool)

GetFailFlag

English:

Returns the fail indicator flag set by the AddFailMatchFlag(), AddFailMatchFlagToFileLog(),
AddFilterToFail() functions,

 Output:
   fail: true if test failed

Português:

Retorna o flag indicador de falha definido pelas funções AddFailMatchFlag(),
AddFailMatchFlagToFileLog(), AddFilterToFail()

 Saída:
   fail: true se o teste tiver falhado

func (*ContainerBuilder) GetGitCloneToBuild added in v0.9.11

func (e *ContainerBuilder) GetGitCloneToBuild() (url string)

GetGitCloneToBuild

English:

Returns the URL of the repository to clone for image transformation

Note:

  • See the SetGitCloneToBuild() function for more details.

Português:

Retorna a URL do repositório a ser clonado para a transformação em imagem

Nota:

  • Veja a função SetGitCloneToBuild() para mais detalhes.

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) GetImageArchitecture added in v0.9.11

func (e *ContainerBuilder) GetImageArchitecture() (architecture string)

GetImageArchitecture

English:

Returns the architecture of the image.

 Output:
   architecture: image architecture

Português:

Retorna a arquitetura da imagem.

 Saída:
   architecture: arquitetura da imagem

func (*ContainerBuilder) GetImageAuthor added in v0.9.11

func (e *ContainerBuilder) GetImageAuthor() (author string)

GetImageAuthor

English:

Returns the author of the image.

 Output:
   author: image author

Português:

Retorna o autor da imagem.

 Saída:
   author: autor da imagem

func (*ContainerBuilder) GetImageCacheName added in v0.9.11

func (e *ContainerBuilder) GetImageCacheName() (name string)

GetImageCacheName

English:

Returns the name of the image cache used to create the image

 Output:
   name: name of the image cache

Português:

Devolve o nome da imagem cache usada para criar a imagem

 Saída:
   name: nome da imagem cache

func (*ContainerBuilder) GetImageComment added in v0.9.11

func (e *ContainerBuilder) GetImageComment() (comment string)

GetImageComment

English:

Returns the archived comment of the image

 Output:
   comment: image comment

Português:

Retorna o comentário arquivado na imagem

 Saída:
   comment: comentário da imagem

func (*ContainerBuilder) GetImageContainer added in v0.9.11

func (e *ContainerBuilder) GetImageContainer() (imageName string)

GetImageContainer

English:

Returns the name of the image used to create the container

 Output:
   imageName: Name of the image used to create the container

Português:

Retorna o nome da imagem usada para criar o container

 Saída:
   imageName: Nome da imagem usada para criar o container

func (*ContainerBuilder) GetImageCreatedTime added in v0.9.42

func (e *ContainerBuilder) GetImageCreatedTime() (created time.Time)

GetImageCreatedTime

English:

Returns the date of creation of the image.

 Output:
   created: Time.Time object with the date of creation of the image.

Português:

Retorna a data de criação da imagem.

 Saída:
   created: Objeto time.Time com a data de criação da imagem.

func (*ContainerBuilder) GetImageExpirationTime added in v0.9.12

func (e *ContainerBuilder) GetImageExpirationTime() (expiration time.Duration)

GetImageExpirationTime

Português:

Retorna a data de expiração da imagem, ou seja, a data usada como base para impedir que a mesma
imagem seja gerada várias vezes em um único teste.

 Saída:
   expiration: Objeto time.Duration com a data de validade da imagem

English:

Returns the image's expiration date, that is, the date used as a basis to prevent the same image
from being generated multiple times in a single test.

 Output:
   expiration: time.Duration object with the image's expiration date

func (*ContainerBuilder) GetImageID

func (e *ContainerBuilder) GetImageID() (ID string)

GetImageID

English:

Returns the image ID.

 Output:
   ID: image ID

Português:

Retorna o ID da imagem.

 Saída:
   ID: ID da imagem

func (*ContainerBuilder) GetImageName

func (e *ContainerBuilder) GetImageName() (name string)

GetImageName

English:

Returns the name of the image.

 Output:
   name: Name of the image

Português:

Retorna o nome da imagem.

 Saída:
   name: Nome da imagem

func (*ContainerBuilder) GetImageOs added in v0.9.11

func (e *ContainerBuilder) GetImageOs() (os string)

GetImageOs

English:

Returns the operating system used to create the image.

 Output:
   os: name of the operating system used to create the image

Português:

Retorna o sistema operacional usado para criar a imagem.

 Saída:
   os: nome do sistema operacional usado para criar a imagem

func (*ContainerBuilder) GetImageOsVersion added in v0.9.11

func (e *ContainerBuilder) GetImageOsVersion() (osVersion string)

GetImageOsVersion

English:

Returns the operating system version of the image

 Output:
   osVersion: operating system version of the image

Português:

Retorna a versão do sistema operacional da imagem

 Saída:
   osVersion: versão do sistema operacional da imagem

func (*ContainerBuilder) GetImageParent added in v0.9.11

func (e *ContainerBuilder) GetImageParent() (parent string)

GetImageParent

Retorna o nome da imagem base

 Saída:
   parent: nome da imagem base

English:

Returns the name of the base image

 Output:
   parent: name of the base image

func (*ContainerBuilder) GetImageRepoDigests added in v0.9.11

func (e *ContainerBuilder) GetImageRepoDigests() (repoDigests []string)

GetImageRepoDigests

English:

Get image reports

 Output:
   repoDigests: image reports

Português:

Obtém relatórios simplificados da imagem

 Saída:
   repoDigests: relatórios da imagem

English:

Get image reports

 Output:
   repoDigests: image reports

func (*ContainerBuilder) GetImageRepoTags added in v0.9.11

func (e *ContainerBuilder) GetImageRepoTags() (repoTags []string)

GetImageRepoTags

English:

Get the list of tags of an image repository.

 Output:
   repoTags: list of image repository tags.

Português:

Obtém a lista de tags de um repositório de imagens.

 Saída:
   repoTags: lista de tags do repositório de imagens.

func (*ContainerBuilder) GetImageSize added in v0.9.11

func (e *ContainerBuilder) GetImageSize() (size int64)

GetImageSize

English:

Returns the image size

 Output:
   size: image size

Português:

Retorna o tamanho da imagem

 Saída:
   size: tamanho da imagem

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)

GetImageVirtualSize

English:

Returns the virtual size of the image

 Output:
   virtualSize: virtual size of the image

Português:

Retorna o tamanho virtual da imagem

 Saída:
   virtualSize: tamanho virtual da imagem

func (*ContainerBuilder) GetInitialized added in v0.9.11

func (e *ContainerBuilder) GetInitialized() (initialized bool)

GetInitialized

English:

Returns if the container control object was initialized

 Output:
   initialized: true if the container control object was initialized

Português:

Retorna se o objeto de controle do container foi inicializado

 Saída:
   inicializado: true caso o objeto de controle do container foi inicializado

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()

 Output:
   inspect: Container information such as name, ID, volumes, network, etc.

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()

 Output:
   inspect: Informações sobre o container, como nome, ID, volumes, rede, etc.

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)

GetLastLineOfOccurrenceBySearchTextInsideContainerLog

English:

Returns the last line of output standard output container that contains the text searched

Input:
  value: text to be searched in the standard output of the container

Output:
  text: string with the last line that contains the text searched
  contains: true if the text was found
  err: default error object

Português:

Retorna a ultima linha sa saída padrão do container que contém o texto procurado

 Input:
   value: texto procurado na saída padrão do container

 Saída:
   text: string com a última linha que contém o texto procurado
   contains: true se o texto foi encontrado
   err: objeto de erro padrão

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()

 Output:
   logs: container standard output text

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()

 Saída:
   logs: saída padrão do container

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

 Output:
   IPV4: IPV4 address of the gateway

Português:

Retorna o gateway da rede para rede IPV4

 Saída:
   IPV4: endereço IPV4 do gateway

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.

 Input:
   networkName: name of the network

 Output:
   IPV4: address of the gateway of the network
   err: standard object error

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.

 Entrada:
   networkName: nome da rede

 Saída:
   IPV4: endereço do gateway da rede
   err: objeto de erro padrão

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

 Output:
   IPV4: network address IPV4

Português:

Retorno o IPV4 da rede do docker

 Saída:
   IPV4: endereço IPV4 da rede

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.

 Input:
   networkName: string with the name of the network

 Output:
   IPV4 IPV4 address of the network
   err: standard object error

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.

 Entrada:
   networkName: string com o nome da rede

 Saída:
   IPV4: endereço IPV4 da rede
   err: objeto de erro padrão

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

 Output:
   network: Object pointer used to configure the network

Português:

Retorna o objeto definido para o controle da rede

 Saída:
   network: Ponteiro do objeto usado para configurar a rede

func (*ContainerBuilder) GetProblem added in v0.9.23

func (e *ContainerBuilder) GetProblem() (problem string)

GetProblem

English:

Return problem description when possible.

 Output:
   problem: descrição do problema

Português:

Retorna a descrição do problema, quando possível

 Saída:
   problem: descrição do problema

func (*ContainerBuilder) GetSshKeyFileName added in v1.0.29

func (e *ContainerBuilder) GetSshKeyFileName(dir string) (fileName string, err error)

GetSshKeyFileName

English:

Returns the name of the last generated ssh key.

Português:

Retorna o nome da chave ssh gerada por último.
Example
var err error
var userData *user.User

userData, err = user.Current()
if err != nil {
	return
}

var fileName string
var cb = ContainerBuilder{}
fileName, err = cb.GetSshKeyFileName(userData.HomeDir)
if err != nil {
	return
}

fmt.Printf("name: %v", fileName)
Output:

name: id_ecdsa

func (*ContainerBuilder) GetSuccessFlag added in v0.9.32

func (e *ContainerBuilder) GetSuccessFlag() (success bool)

GetSuccessFlag

English:

Get success flag

 Output:
   success: success flag

Português:

Retorna a bandeira indicadora de sucesso no teste

 Saída:
   success: bandeira indicadora de sucesso no teste

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

 Output:
   inspect: Contém informações sobre a imagem criada
   err: standard object error

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() and MakeDefaultDockerfileForMeWithInstallExtras() functions can be used to make a standard Dockerfile file automatically.

Português:

Transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma imagem docker

 Saída:
   inspect: contém informações sobre a imagem criada
   err: objeto de erro padrão

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, podem ser usadas as funções MakeDefaultDockerfileForMe() e MakeDefaultDockerfileForMeWithInstallExtras() para ser gerar um arquivo Dockerfile padrão de forma automática.
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

	SaGarbageCollector()

	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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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)

	SaGarbageCollector()

}
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.

 Output:
   inspect: Contém informações sobre a imagem criada
   err: standard object error

Note:

  • The repository must 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.

Saída:
  inspect: contém informações sobre a imagem criada
  err: objeto de erro padrão

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)

ImageFindIdByName

English:

Find an image by name

 Input:
   name: image name

 Output:
   id: image ID
   err: default error object

Português:

Encontra uma imagem pelo nome

 Input:
   name: nome da imagem

 Output:
   id: ID da imagem
   err: Objeto padrão de erro

func (*ContainerBuilder) ImageFindIdByNameContains added in v0.5.19

func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)

ImageFindIdByNameContains

English:

Find an image by part of the name

 Input:
   containerName: Part of the name of the image

 Output:
   list: List of images found
   err: Default error object

Português:

Encontra uma imagem por parte do nome

 Entrada:
   containerName: Parte do nome da imagem

 Saída:
   list: Lista de imagens encontradas
   err: Objeto de erro padrão

func (*ContainerBuilder) ImageInspect added in v0.9.11

func (e *ContainerBuilder) ImageInspect() (inspect types.ImageInspect, err error)

ImageInspect

English:

Inspects the image and returns information type, ID, name, size, creation date, update date,
author, tags, etc

 Output:
   inspect: Image information
   err: Default error object

Português:

Inspeciona a imagem e retorna informações tipo, ID, nome, tamanho, data de criação, data de
atualização, autor, tags, etc

 Saída:
  inspect: Informações da imagem
  err: Objeto de erro padrão

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.

 Output:
   portList: List of ports exposed on image creation. (Dockerfile expose port)
   err: standard error object

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.

 Saída:
   portList: Lista de portas expostas na criação da imagem. (Dockerfile expose port)
   err: Objeto de erro padrão

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.

 Output:
   list: List of exposed volumes
   err: Standard error object

Note:

  • Use the AddFileOrFolderToLinkBetweenComputerHostAndContainer() function to link folders and files between the host computer and the container

Português:

Lista todos os volumes definidos na imagem.

 Saída:
	 list: Lista de volumes expostos
   err: Objeto de erro padrão

Nota:

  • Use a função AddFileOrFolderToLinkBetweenComputerHostAndContainer() para vincular pastas e arquivos entre o computador hospedeiro e o container

func (*ContainerBuilder) ImagePull

func (e *ContainerBuilder) ImagePull() (err error)

ImagePull

English:

Downloads the image to be mounted. (equivalent to the docker pull image command)

 Output:
   err: standart error object

Português:

Baixa a imagem a ser montada. (equivale ao comando docker pull image)

 Saída:
   err: objeto de erro padrão
Example
var err error

SaGarbageCollector()

// 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

SaGarbageCollector()

// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
	util.TraceToLog()
	panic(err)
}
Output:

func (*ContainerBuilder) ImageRemove

func (e *ContainerBuilder) ImageRemove() (err error)

ImageRemove

English:

Remove the image if there are no containers using the image

 Output:
   err: Standard error object

Note:

  • Remove all containers before use, including stopped containers

Português:

Remove a imagem se não houver containers usando a imagem

 Saída:
   err: Objeto de erro padrão

Nota:

  • 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

 Input:
   name: full image name

 Output:
   err: standard error object

Note:

  • Remove all containers before use, including stopped containers

Português:

Remove a imagem se não houver containers usando a imagem

 Entrada:
   name: nome completo da imagem

 Saída:
   err: objeto de erro padrão

Nota:

  • Remova todos os containers antes do uso, inclusive os containers parados

func (*ContainerBuilder) Init

func (e *ContainerBuilder) Init() (err error)

Init

English:

Initializes the object.

 Output:
   err: Standard error object

Note:

  • Should be called only after all settings have been configured

Português:

Inicializa o objeto.

 Saída:
   err: Objeto de erro padrão

Nota:

  • 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.

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 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;
  • 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.

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 haja portas expostas ou volumes nas configurações, as mesmas serão definidas automaticamente, o mesmo serve para arquivos compartilhados entre o host e o container;
  • 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.
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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.

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 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;
  • 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.

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 haja portas expostas ou volumes nas configurações, as mesmas serão definidas automaticamente, o mesmo serve para arquivos compartilhados entre o host e o container;
  • 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) 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.
SaGarbageCollector()

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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	return
}

var containerInspect iotmakerdocker.ContainerInspect
containerInspect, err = container.ContainerInspect()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	return
}

err = container.NetworkChangeIp()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	return
}

err = container.ContainerStart()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	return
}

containerInspect, err = container.ContainerInspect()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.3 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

 Input:
   value: part of the wanted name

 Output:
   err: Standard error object

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

 Entrada:
   value: parte do nome desejado

 Saída:
   err: Objeto de erro padrão

func (*ContainerBuilder) ReplaceDockerfileFromServer added in v1.0.31

func (e *ContainerBuilder) ReplaceDockerfileFromServer(filePath string) (err error)

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.

 Input:
   value: true to enable the use of image named cache:latest as the basis for new images if it
     exists

Note:

  • This function is extremely useful when developing new applications, reducing the time to create images with each new test.

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.

 Entrada:
   value: true para habilitar o uso da imagem de nome cache:latest como base para novas imagens,
     caso a mesma exista

Nota:

  • Esta função é extremamente útil no desenvolvimento de novas aplicações, reduzindo o tempo de criação de imagens a cada novo teste.

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

 Entrada:
   value: true to attach standard streams to tty

Português:

Anexa a saída padrão do tty

 Entrada:
   value: true para anexar 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)

 Input:
   values: List of commands. Eg.: []string{"ls", "-l"}

Português:

Comando a ser executado quando o container inicia (estilo Dockerfile CMD)

 Entrada:
   values: Lista de comandos. Ex.: []string{"ls", "-l"}

func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer

func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)

SetContainerEntrypointToRunWhenStartingTheContainer

English:

Entrypoint to run when stating the container

 Input:
   values: entrypoint. Eg.: docker run --entrypoint [new_command] [docker_image] [optional:value]

Português:

Entrypoint a ser executado quando o container iniciar

 Entrada:
   values: entrypoint. Ex.: docker run --entrypoint [new_command] [docker_image] [optional:value]

func (*ContainerBuilder) SetContainerHealthcheck

func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)

SetContainerHealthcheck

English:

Holds configuration settings for the HEALTHCHECK feature.

 Input:
   value: Ponteiro para HealthConfig
     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:

Adiciona definições de configuração para o recurso HEALTHCHECK.

  Entrada:
    value: Ponteiro para HealthConfig
      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
Example
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.
SaGarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// 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: Project to be cloned from github
//
// Português: Projeto para ser clonado do github
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.builder.public.example.git")

// English: See SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
//
// Português: 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 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
//
// English: troca a porta 3000 pela porta 3030
container.AddPortToChange("3000", "3030")

// English: replace container folder /static to host folder ./test/static
//
// Português: substitui a pasta do container /static pela pasta do host ./test/static
err = container.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().error: %v", err.Error())
	util.TraceToLog()
	panic(err)
}

// English: inicialize container object
//
// Português: inicializa o objeto container
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// English: builder new image from git project
//
// Português: monta a nova imagem a partir do projeto git
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

// English: container build from image delete:latest
//
// Português: monta o container a partir da imagem delete:latest
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 neste ponto de código na porta 3030

// English: read server inside a container on address http://localhost:3030/
//
// Português: lê o servidor dentro do container na porta 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)
}

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.
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

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

English:

Prints in the header of the file the name of the constant responsible for printing the column in
the log.

 Input:
   value: true to print the name of the constant responsible for printing the column in the log
     in the header of the file.

Nota:

  • The constants printed in the first line of the file are used in the SetCsvFileRowsToPrint() function. Simply separate the constants by pipe (|). Example: container.SetCsvFileRowsToPrint( KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ... )

Português:

Imprime no cabeçalho do arquivo o nome da constante responsável por imprimir a coluna no log.

 Entrada:
   value: true para imprimir no cabeçalho do arquivo o nome da constante responsável por imprimir
     a coluna no log.

Nota:

  • As constantes impressas na primeira linha do arquivo são usadas na função SetCsvFileRowsToPrint(). Basta separar as contantes por pipe (|). Exemplo: container.SetCsvFileRowsToPrint( KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ... )

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(), AddFilterToCvsLog() e AddFilterToCvsLogWithReplace();
  • 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(), AddFilterToCvsLog() e AddFilterToCvsLogWithReplace();
  • 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

English:

Defines which columns will be printed in the log, in the form of a CSV file, with container
performance information, memory consumption indicators and access times.

 Input:
   value: List of columns printed in CSV file. Eg.: KLogColumnMacOs, KLogColumnWindows,
     KLogColumnAll or any combination of KLogColumn... concatenated with pipe.
     Eg.: KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ...

Nota:

  • To see the complete list of columns, use SetCsvFileRowsToPrint(KLogColumnAll) and SetCsvFileReader(true). This will print the constant names on top of each column in the log.

Português:

Define quais colunas vão ser impressas no log, na forma de arquivo CSV, com informações de
desempenho do container, 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.
     Ex.: KLogColumnReadingTime | KLogColumnCurrentNumberOfOidsInTheCGroup | ...

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

SaGarbageCollector()

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.AddFilterToCvsLog(
	"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())
	SaGarbageCollector()
	return
}

_, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	return
}

err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	return
}

SaGarbageCollector()
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(), AddFilterToCvsLog() and AddFilterToCvsLogWithReplace() 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(), AddFilterToCvsLog() e AddFilterToCvsLogWithReplace();
  • As colunas de dados preenchidos varia de acordo com o sistema operacional.
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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(), AddFilterToCvsLog(), AddFilterToCvsLogWithReplace(), 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(), AddFilterToCvsLog(), AddFilterToCvsLogWithReplace(), SetCsvFileValueSeparator() e SetCsvFileRowSeparator() para alterar algumas configurações do log.
Example
var err error
var imageInspect types.ImageInspect

SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	"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())
	SaGarbageCollector()
	return
}

imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	return
}

container.StartMonitor()

event := container.GetChaosEvent()

for {
	e := <-event

	if e.Error || e.Fail {
		fmt.Printf("container name: %v\n", e.ContainerName)
		log.Printf("Error: %v", e.Message)
		return
	}
	if e.Done || e.Error || e.Fail {

		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)

		break
	}
}

container.StopMonitor()

SaGarbageCollector()
Output:

image size: 1.4 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.

 Input:
   value: Object compatible with DockerfileAuto interface

Note:

  • Eee the DockerfileAuto interface for further instructions.

Português:

Define um novo objeto contendo o construtor do arquivo dockerfile.

 Entrada:
   value: Objeto compatível com a interface DockerfileAuto

Nota:

  • Veja a interface DockerfileAuto para mais instruções.

func (*ContainerBuilder) SetDockerfilePath added in v1.0.57

func (e *ContainerBuilder) SetDockerfilePath(path string) (err error)

SetDockerfilePath

English:

Defines a Dockerfile to build the image.

Português:

Define um arquivo Dockerfile para construir a imagem.

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

SaGarbageCollector()

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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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
// SaGarbageCollector()
Output:

func (*ContainerBuilder) SetFinalImageName added in v1.0.16

func (e *ContainerBuilder) SetFinalImageName(name string)

SetFinalImageName

English:

Set a two stage build final image name.

 Input:
   name: name of final image

Português:

Define o nome da imagem final para construção de imagem em dois estágios.

 Entrada:
   name: nome da imagem final.

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.

 Input:
   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.

 Entrada:
   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

SaGarbageCollector()

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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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
SaGarbageCollector()
Output:

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.

 Input:
   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_ecdsa")
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.

 Entrada:
   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_ecdsa")
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.

 Input:
   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.

 Entrada:
   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.

 Input:
   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.

 Entrada:
   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

 Input:
   value: .gitconfig file contents

Example:

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

	 Entrada:
    value: conteúdo do arquivo .gitconfig

Exemplo:

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"

 Input:
   value: Caminho do repositório privado. Eg.: github.com/helmutkemper

Português:

Caminho do repositório privado definido em "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"

 Entrada:
   value: Caminho do repositório privado. Ex.: 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.

 Input:
   password: git ssh certificate 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().

Português:

Define a senha da chave ssh para repositórios git privados.

 Entrada:
   password: senha da chave ssh

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.

 Input:
   value: CPU CFS scheduler period

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.

 Entrada:
   value: período do agendador CFS da CPU

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:

Defines the host machine’s CPU cycles.

 Input:
   value: machine’s CPU cycles. (Default: 1024)

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:

Define os ciclos de CPU da máquina hospedeira.

 Entrada:
   value: ciclos de CPU da máquina hospedeira. (Default: 1024)

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.

 Input:
   value: string with the format "1,2,3"

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.

 Entrada:
   value: string com o formato "1,2,3"

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)

 Input:
   value: string with the format "0-3,5-7"

--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)

 Entrada:
   value: string com o formato "0-3,5-7"

--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 the CPU shares of the image build options.

 Input:
   value: CPU shares (Default: 1024)

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:

Define o compartilhamento de CPU na construção da imagem.

 Entrada:
   value: Compartilhamento de CPU (Default: 1024)

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.

 Entrada:
   values: images that are used for matching cache.

Note:

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.

 Entrada:
   values: imagens que são usadas para correspondência de cache.

Note:

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.

 Input:
   values: hosts to mapping

Example:

values = []string{
  "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.

 Entrada:
   values: hosts para mapeamento

Exemplo:

values = []string{
  "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.

 Input:
   value: amount of memory in bytes

Note:

Português:

Memória máxima total que o container pode usar.

 Entrada:
   value: Quantidade de memória em bytes

Nota:

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

for {
	e := <-event

	if e.Error || e.Fail {
		fmt.Printf("container name: %v\n", e.ContainerName)
		log.Printf("Error: %v", e.Message)
		return
	}
	if e.Done || e.Error || e.Fail {

		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)

		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

func (*ContainerBuilder) SetImageBuildOptionsMemorySwap

func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)

SetImageBuildOptionsMemorySwap

English:

Set memory swap (--memory-swap)

Note:

Português:

habilita a opção memory swp

Note:

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.

 Input:
   value: target platform

Examples:

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]]

 Entrada:
   value: plataforma de destino

Exemplos:

osx
windows/amd64
linux/arm64/v8

func (*ContainerBuilder) SetImageBuildOptionsSecurityOpt

func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)

SetImageBuildOptionsSecurityOpt

English:

Set the container security options

 Input:
   values: container security options

Examples:

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

 Entrada:
   values: opções de segurança do container

Exemplos:

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

 Input:
   value: true preserve the original image and creates a new one from the parent

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

 Entrada:
   value: true preserva a imagem original e cria uma nova imagem a partir da imagem pai

func (*ContainerBuilder) SetImageBuildOptionsTarget

func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)

SetImageBuildOptionsTarget

English:

Build the specified stage as defined inside the Dockerfile.

 Input:
   value: stage name

Note:

Português:

Monta o container a partir do estágio definido no arquivo Dockerfile.

 Entrada:
   value: nome do estágio

Nota:

func (*ContainerBuilder) SetImageCacheName added in v0.5.40

func (e *ContainerBuilder) SetImageCacheName(name string)

SetImageCacheName

English::

Defines the name of the cache image

 Input:
   name: Name of the cached image. (Default: "cache:lastest")

Note:

  • See SaImageMakeCache(), SetCacheEnable(), MakeDefaultDockerfileForMe() and MakeDefaultDockerfileForMeWithInstallExtras() functions

Português:

Define o nome da imagem cache

 Entrada:
   name: Nome da imagem cacge. (Default: "cache:lastest")

Nota:

  • Veja as funções SaImageMakeCache(), SetCacheEnable(), MakeDefaultDockerfileForMe() e MakeDefaultDockerfileForMeWithInstallExtras()

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
Example
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.
SaGarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// 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: Project to be cloned from github
//
// Português: Projeto para ser clonado do github
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

// English: See SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
//
// Português: 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 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
//
// English: troca a porta 3000 pela porta 3030
container.AddPortToChange("3000", "3030")

// English: replace container folder /static to host folder ./test/static
//
// Português: substitui a pasta do container /static pela pasta do host ./test/static
err = container.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().error: %v", err.Error())
	util.TraceToLog()
	panic(err)
}

// English: inicialize container object
//
// Português: inicializa o objeto container
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// English: builder new image from git project
//
// Português: monta a nova imagem a partir do projeto git
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

// English: container build from image delete:latest
//
// Português: monta o container a partir da imagem delete:latest
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 neste ponto de código na porta 3030

// English: read server inside a container on address http://localhost:3030/
//
// Português: lê o servidor dentro do container na porta 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)
}

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.
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) SetInspectInterval

func (e *ContainerBuilder) SetInspectInterval(value time.Duration)

SetInspectInterval

English:

Defines the container's monitoring interval [optional]

 Input:
   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]

 Entrada:
   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

SetNetworkDocker

English:

Sets the docker network manager pointer

 Input:
   network: pointer to the network manager object.

Note:

  • Compatible with dockerBuilderNetwork.ContainerBuilderNetwork{} object

Português:

Define o ponteiro do gerenciador de rede docker

 Entrada:
   network: ponteiro para o objeto gerenciador de rede.

Nota:

  • Compatível com o objeto dockerBuilderNetwork.ContainerBuilderNetwork{}
Example
var err error

SaGarbageCollector()

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.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./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)
}

err = mongoDocker.ImagePull()
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
SaGarbageCollector()
Output:

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.

 Input:
   onBuild: List of 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.

Note:

See https://docs.docker.com/engine/reference/builder/#onbuild

Português:

Adiciona à imagem uma instrução de gatilho a ser executada posteriormente, quando a imagem for
usada como base para outra construção.

 Entrada:
   onBuild: Lista de instruções de gatilho a serem executadas 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.

Nota:

https://docs.docker.com/engine/reference/builder/#onbuild

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.

 Output:
   err: Standard error object

 Notes:
   * For change ssh key file name, use SetSshKeyFileName() function.

Português:

Copia o arquivo ssh ~/.ssh/id_rsa e o arquivo ~/.gitconfig para as variáveis SSH_ID_RSA_FILE e
GITCONFIG_FILE.

 Saída:
   err: Objeto de erro padrão

 Notas:
   * Para mudar o nome do arquivo ssh usado como chave, use a função SetSshKeyFileName().

func (*ContainerBuilder) SetRestartProbability added in v0.9.11

func (e *ContainerBuilder) SetRestartProbability(restartProbability, restartChangeIpProbability float64, limit int)

SetRestartProbability

English:

Set the restart probability and the probability of changing the ip of the container when it restarts.

Input:
  restartProbability: Probability of restarting a container during the chaos test.
  restartChangeIpProbability: Probability of changing the ip of the container when it restarts.
  limit: Limit of how many times the container will restart.

Português:

Define a probabilidade de reiniciar um container durante o teste de caos e a probabilidade de
trocar o ip do container quando ele reiniciar.

 Entrada:
   restartProbability: Probabilidade de reiniciar um container durante o teste de caos.
   restartChangeIpProbability: Probabilidade de trocar o ip do container quando ele reiniciar.
   limit: Limite de quantas vezes o container vai reiniciar.
Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

Example:

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_ecdsa")
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

Exemplo:

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_ecdsa")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetSshIdRsaFile(string(file))

func (*ContainerBuilder) SetSshKeyFileName added in v1.0.29

func (e *ContainerBuilder) SetSshKeyFileName(value string)

func (*ContainerBuilder) SetSshKnownHostsFile

func (e *ContainerBuilder) SetSshKnownHostsFile(value string)

SetSshKnownHostsFile

English:

Set a sseh knownhosts file

Example:

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

Exemplo:

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()

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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()

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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()

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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()

Example
var err error
var imageInspect types.ImageInspect

// English: Mounts an image cache and makes imaging up to 5x faster
//
// Português: Monta uma imagem cache e deixa a criação de imagens até 5x mais rápida
// [optional/opcional]
err = SaImageMakeCacheWithDefaultName("./example/cache/", 365*24*60*60*time.Second)
if err != nil {
	fmt.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()

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.AddFilterToCvsLogWithReplace(
	// 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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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())
	SaGarbageCollector()
	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()

// 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
for {
	var pass = false
	select {
	case e := <-event:
		if e.Done == true || e.Error == true || e.Fail == true {
			pass = 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)
			fmt.Printf("message: %v\n", e.Message)

			break
		}
	}

	if pass == true {
		break
	}
}

// English: Stop container monitoring.
//
// Português: Para o monitoramento do container.
err = container.StopMonitor()
if err != nil {
	log.Printf("error: %v", err.Error())
	SaGarbageCollector()
	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.
SaGarbageCollector()
Output:

image size: 1.4 MB
image os: linux
container name: container_counter_delete_after_test
done: true
fail: false
error: false
message: done!

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

 Input:
   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

 Entrada:
   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

 Input:
   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

 Entrada:
   value: texto emitido na saída padrão informando por um evento esperado
   timeout: tempo máximo de espera
Example
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.
SaGarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
//
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// 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: Project to be cloned from github
//
// Português: Projeto para ser clonado do github
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")

// English: See SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()
//
// Português: 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 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
//
// English: troca a porta 3000 pela porta 3030
container.AddPortToChange("3000", "3030")

// English: replace container folder /static to host folder ./test/static
//
// Português: substitui a pasta do container /static pela pasta do host ./test/static
err = container.AddFileOrFolderToLinkBetweenComputerHostAndContainer("./test/static", "/static")
if err != nil {
	log.Printf("container.AddFileOrFolderToLinkBetweenComputerHostAndContainer().error: %v", err.Error())
	util.TraceToLog()
	panic(err)
}

// English: inicialize container object
//
// Português: inicializa o objeto container
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// English: builder new image from git project
//
// Português: monta a nova imagem a partir do projeto git
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

// English: container build from image delete:latest
//
// Português: monta o container a partir da imagem delete:latest
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 neste ponto de código na porta 3030

// English: read server inside a container on address http://localhost:3030/
//
// Português: lê o servidor dentro do container na porta 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)
}

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.
SaGarbageCollector()
Output:

<html><body><p>C is life! Golang is a evolution of C</p></body></html>

func (*ContainerBuilder) SizeToString added in v0.9.11

func (e *ContainerBuilder) SizeToString(value int64) (size string)

SizeToString

Português:

Formata um valor inteiro em uma string contendo o valor em Bytes, KBytes, MBytes e GBytes.

 Entrada:
   value: valor inteiro representando um tamanho de memória

 Saída:
   size: string contendo o valor em Bytes, KBytes, MBytes e GBytes

English:

Format an integer value into a string containing the value in Bytes, KBytes, MBytes and GBytes.

Input:
  value: integer value representing a memory size

Output:
  size: string containing the value in Bytes, KBytes, MBytes and GBytes

func (*ContainerBuilder) StartMonitor added in v0.9.11

func (e *ContainerBuilder) StartMonitor()

StartMonitor

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.

Note:

  • This function is used in conjunction with the EnableChaosScene(), SetCsvLogPath() and StopMonitor() functions;
  • StopMonitor() Must be called at the end of the chaos test.

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(), SetCsvLogPath() e StopMonitor();
  • StopMonitor() Must be called at the end of the chaos test.

func (*ContainerBuilder) StopMonitor added in v0.9.11

func (e *ContainerBuilder) StopMonitor() (err error)

StopMonitor

English:

Disable 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.

Note:

  • This function is used in conjunction with the EnableChaosScene(), SetCsvLogPath() and StopMonitor() functions;
  • StopMonitor() Must be called at the end of the chaos test.

Português:

Desabilita o 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(), SetCsvLogPath() e StopMonitor();
  • StopMonitor() Deve ser chamado ao final do teste de caos.

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

 Input:
   value: searched text

 Output:
   dockerLogs: container's default output
   err: standard error object

Português: Espera pelo texto aparecer na saída padrão do container

Entrada:
  value: texto procurado

Saída:
  dockerLogs: saída padrão do container
  err: objeto de erro padrão

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

 Input:
   value: searched text
   timeout: wait timeout

 Output:
   dockerLogs: container's default output
   err: standard error object

Português:

Espera pelo texto aparecer na saída padrão do container

 Entrada:
   value: texto procurado
   timeout: tempo limite de espera

 Saída:
   dockerLogs: saída padrão do container
   err: objeto de erro padrão

type CopyFile added in v1.0.23

type CopyFile struct {
	Src string
	Dst string
}

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()
	SetFinalImageName(name string)
	AddCopyToFinalImage(src, dst string)
	SetDefaultSshFileName(name string)
}

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 Event added in v0.9.11

type Event struct {
	ContainerName string
	Message       string
	Error         bool
	Done          bool
	Fail          bool
	Metadata      map[string]interface{}
}

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 save container default output into file format
	LogPath string
	// contains filtered or unexported fields
}

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 NameAndId added in v0.5.19

type NameAndId struct {
	ID   string
	Name string
}

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

	SaGarbageCollector()

	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
}
Output:

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 Restart added in v0.9.11

type Restart struct {
	FilterToStart      []LogFilter
	TimeToStart        Timers
	RestartProbability float64
	RestartLimit       int
	// contains filtered or unexported fields
}

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

func (e *Theater) SetContainerPaused(sceneName string) (doNotPauseContainer bool)

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

func (e *Theater) SetContainerStopped(sceneName string) (IsOnTheEdge bool)

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

func (e *Theater) SetContainerUnPaused(sceneName string)

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

func (e *Theater) SetContainerUnStopped(sceneName string)

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.

type Timers added in v0.9.11

type Timers struct {
	Min time.Duration
	Max time.Duration
}

Source Files

Directories

Path Synopsis
example
package theater
package theater

Jump to

Keyboard shortcuts

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