iotmakerdockerbuilder

package module
v0.9.31 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2021 License: Apache-2.0 Imports: 31 Imported by: 3

README

iotmaker.docker.builder

./image/docker.png

English

This project creates a simple way to manipulate containers from Golang code

Status: Starting to document in English

Português

Status: Documentando em ingles

Este projeto cria uma API Golang simples para criar e manipular o docker a partir de um código Golang

Examples / Exemplos

Create a docker network / Cria uma rede docker

English: Creates a docker network with subnet 10.0.0.0/16 and gateway 10.0.0.1

Português: Cria uma rede docker com subnet 10.0.0.0/16 e gateway 10.0.0.1

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

  // create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
  err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
  if err != nil { panic(err) }

English: use the container.SetNetworkDocker(&netDocker) command to link the container to the network

Português: use o comando container.SetNetworkDocker(&netDocker) para ligar um container com o docker

Container nats

English: Creates a nats container, from the https://nats.io/ project and expects it to be ready, monitoring standard output and looking for the text "Listening for route connections on 0.0.0.0:6222"

Português: Cria um container nats, do projeto https://nats.io/ e espera o mesmo ficar pronto, monitorando a saída padrão e procurando pelo texto "Listening for route connections on 0.0.0.0:6222"

  var err error

  // create a container
  var container = ContainerBuilder{}
  // set image name for docker pull
  container.SetImageName("nats:latest")
  // link container and network [optional] (next ip address is 10.0.0.2)
  container.SetNetworkDocker(&netDocker)
  // 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 { panic(err) }

  // image nats:latest pull command [optional]
  err = container.ImagePull()
  if err != nil { 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.ContainerBuildFromImage()
  if err != nil { panic(err) }

Container from github project

English: Creates a container based on a golang project contained in a remote git repository.

If you don't want to make the Dockerfile, use the container.MakeDefaultDockerfileForMe() command if the go.mod file is present and the main.go file is in the root directory.

If the repository is private, use the container.SetPrivateRepositoryAutoConfig() command to automatically copy the credentials contained in ~/.ssh and the ~/.gitconfig file into the image.

If the repository is private, use the container.SetPrivateRepositoryAutoConfig() command to automatically copy the credentials contained in ~/.ssh and the ~/.gitconfig file into the image.

Note that the image is built in two steps and credentials will be lost.

If the image needs to access a private repository, use the container.SetGitPathPrivateRepository() function to enter the repository.

Português: Cria um container baseado em um projeto golang contido em um repositório git remoto.

Caso você não queira fazer o Dockerfile, use o comando container.MakeDefaultDockerfileForMe() se o arquivo go.mod estiver presente e o arquivo main.go estiver na raiz do repositório.

Se o repositório for privado, use o comando container.SetPrivateRepositoryAutoConfig() para copiar as credenciais contidas em ~/.ssh/ e o arquivo ~/.gitconfig de forma automática para dentro da imagem.

Perceba que a imagem é construída em duas etapas e as credenciais serão perdidas.

Se a imagem necessitar acessar um repositório privado, use a função container.SetGitPathPrivateRepository() para informar o repositório.

  var err error
  var container = ContainerBuilder{}
  // new image name delete:latest
  container.SetImageName("delete:latest")
  // container name container_delete_server_after_test
  container.SetContainerName("container_delete_server_after_test")
  // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
  container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
    
  // see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
  // SetGitCloneToBuildWithPrivateToken()
    
  // set a waits for the text to appear in the standard container output to proceed [optional]
  container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)
  // change and open port 3000 to 3030
  container.AddPortToChange("3000", "3030")
  // replace container folder /static to host folder ./test/static
  err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
  if err != nil { 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) }

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

MongoDB

English: Create a MongoDB container.

To archive data non-ephemerally, use the mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer() command to define where to archive the data on the host computer.

Português: Cria um container MongoDB.

Para arquivar dados de forma não efêmera, use o comando mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer() para definir onde arquivar os dados no computador hospedeiro.

  var err error
  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",
    },
  )
  err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
  mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)
  err = mongoDocker.Init()
  err = mongoDocker.ContainerBuildFromImage()

Container from folder

English: Mount a container from a folder on the host computer.

If you don't want to make the Dockerfile, use the container.MakeDefaultDockerfileForMe() command if the go.mod file is present and the main.go file is in the root directory.

If the repository is private, use the container.SetPrivateRepositoryAutoConfig() command to automatically copy the credentials contained in ~/.ssh and the ~/.gitconfig file into the image.

If the repository is private, use the container.SetPrivateRepositoryAutoConfig() command to automatically copy the credentials contained in ~/.ssh and the ~/.gitconfig file into the image.

Note that the image is built in two steps and credentials will be lost.

If the image needs to access a private repository, use the container.SetGitPathPrivateRepository() function to enter the repository.

Português: Monta um container a partir de uma pasta no computador hospedeiro.

Caso você não queira fazer o Dockerfile, use o comando container.MakeDefaultDockerfileForMe() se o arquivo go.mod estiver presente e o arquivo main.go estiver na raiz do repositório.

Se o repositório for privado, use o comando container.SetPrivateRepositoryAutoConfig() para copiar as credenciais contidas em ~/.ssh/ e o arquivo ~/.gitconfig de forma automática para dentro da imagem.

Perceba que a imagem é construída em duas etapas e as credenciais serão perdidas.

Se a imagem necessitar acessar um repositório privado, use a função container.SetGitPathPrivateRepository() para informar o repositório.

  var err error

  GarbageCollector()
  var container = ContainerBuilder{}
  // new image name delete:latest
  container.SetImageName("delete:latest")
  // set a folder path to make a new image
  container.SetBuildFolderPath("./test/server")
  // container 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) }

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

  // builder new image from folder
  err = container.ImageBuildFromFolder()
  if err != nil { panic(err) }

  // build a new container from image
  err = container.ContainerBuildFromImage()
  if err != nil { panic(err) }

Documentation

Overview

Package iotmakerdockerbuilder

English: Golang and Docker in a simple way.

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.

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

	// KAll
	//
	// English: Enable all values to log
	KAll = 0x7FFFFFFFFFFFFFF

	// KReadingTime
	//
	// English: Reading time
	KReadingTime     = 0b0000000000000000000000000000000000000000000000000000000000000001
	KReadingTimeComa = 0b0111111111111111111111111111111111111111111111111111111111111110

	KFilterLog     = 0b0000000000000000000000000000000000000000000000000000000000000010
	KFilterLogComa = 0b0111111111111111111111111111111111111111111111111111111111111100

	// KCurrentNumberOfOidsInTheCGroup
	//
	// English: Linux specific stats, not populated on Windows. Current is the number of pids in the cgroup
	KCurrentNumberOfOidsInTheCGroup     = 0b0000000000000000000000000000000000000000000000000000000000000100
	KCurrentNumberOfOidsInTheCGroupComa = 0b0111111111111111111111111111111111111111111111111111111111111000

	// KLimitOnTheNumberOfPidsInTheCGroup
	//
	// 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.
	KLimitOnTheNumberOfPidsInTheCGroup     = 0b0000000000000000000000000000000000000000000000000000000000001000
	KLimitOnTheNumberOfPidsInTheCGroupComa = 0b0111111111111111111111111111111111111111111111111111111111110000

	// KTotalCPUTimeConsumed
	//
	// English: Total CPU time consumed. (Units: nanoseconds on Linux, Units: 100's of nanoseconds on Windows)
	KTotalCPUTimeConsumed     = 0b0000000000000000000000000000000000000000000000000000000000010000
	KTotalCPUTimeConsumedComa = 0b0111111111111111111111111111111111111111111111111111111111100000

	// KTotalCPUTimeConsumedPerCore
	//
	// English: Total CPU time consumed. (Units: nanoseconds on Linux, Units: 100's of nanoseconds on Windows)
	KTotalCPUTimeConsumedPerCore     = 0b0000000000000000000000000000000000000000000000000000000000100000
	KTotalCPUTimeConsumedPerCoreComa = 0b0111111111111111111111111111111111111111111111111111111111000000

	// KTimeSpentByTasksOfTheCGroupInKernelMode
	//
	// 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.)
	KTimeSpentByTasksOfTheCGroupInKernelMode     = 0b0000000000000000000000000000000000000000000000000000000001000000
	KTimeSpentByTasksOfTheCGroupInKernelModeComa = 0b0111111111111111111111111111111111111111111111111111111110000000

	// KTimeSpentByTasksOfTheCGroupInUserMode
	//
	// 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)
	KTimeSpentByTasksOfTheCGroupInUserMode     = 0b0000000000000000000000000000000000000000000000000000000010000000
	KTimeSpentByTasksOfTheCGroupInUserModeComa = 0b0111111111111111111111111111111111111111111111111111111100000000

	// KSystemUsage
	//
	// English: System Usage. Linux only.
	KSystemUsage     = 0b0000000000000000000000000000000000000000000000000000000100000000
	KSystemUsageComa = 0b0111111111111111111111111111111111111111111111111111111000000000

	// KOnlineCPUs
	//
	// English: Online CPUs. Linux only.
	KOnlineCPUs     = 0b0000000000000000000000000000000000000000000000000000001000000000
	KOnlineCPUsComa = 0b0111111111111111111111111111111111111111111111111111110000000000

	// KNumberOfPeriodsWithThrottlingActive
	//
	// English: Throttling Data. Linux only. Number of periods with throttling active.
	KNumberOfPeriodsWithThrottlingActive     = 0b0000000000000000000000000000000000000000000000000000010000000000
	KNumberOfPeriodsWithThrottlingActiveComa = 0b0111111111111111111111111111111111111111111111111111100000000000

	// KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit
	//
	// English: Throttling Data. Linux only. Number of periods when the container hits its throttling limit.
	KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit     = 0b0000000000000000000000000000000000000000000000000000100000000000
	KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitComa = 0b0111111111111111111111111111111111111111111111111111000000000000

	// KAggregateTimeTheContainerWasThrottledForInNanoseconds
	//
	// English: Throttling Data. Linux only. Aggregate time the container was throttled for in nanoseconds.
	KAggregateTimeTheContainerWasThrottledForInNanoseconds     = 0b0000000000000000000000000000000000000000000000000001000000000000
	KAggregateTimeTheContainerWasThrottledForInNanosecondsComa = 0b0111111111111111111111111111111111111111111111111110000000000000

	// KTotalPreCPUTimeConsumed
	//
	// English: Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows.
	KTotalPreCPUTimeConsumed     = 0b0000000000000000000000000000000000000000000000000010000000000000
	KTotalPreCPUTimeConsumedComa = 0b0111111111111111111111111111111111111111111111111100000000000000

	// KTotalPreCPUTimeConsumedPerCore
	//
	// English: Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows.
	KTotalPreCPUTimeConsumedPerCore     = 0b0000000000000000000000000000000000000000000000000100000000000000
	KTotalPreCPUTimeConsumedPerCoreComa = 0b0111111111111111111111111111111111111111111111111000000000000000

	// KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode
	//
	// 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.)
	KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode     = 0b0000000000000000000000000000000000000000000000001000000000000000
	KTimeSpentByPreCPUTasksOfTheCGroupInKernelModeComa = 0b0111111111111111111111111111111111111111111111110000000000000000

	// KTimeSpentByPreCPUTasksOfTheCGroupInUserMode
	//
	// 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)
	KTimeSpentByPreCPUTasksOfTheCGroupInUserMode     = 0b0000000000000000000000000000000000000000000000010000000000000000
	KTimeSpentByPreCPUTasksOfTheCGroupInUserModeComa = 0b0111111111111111111111111111111111111111111111100000000000000000

	// KPreCPUSystemUsage
	//
	// English: System Usage. (Linux only)
	KPreCPUSystemUsage     = 0b0000000000000000000000000000000000000000000000100000000000000000
	KPreCPUSystemUsageComa = 0b0111111111111111111111111111111111111111111111000000000000000000

	// KOnlinePreCPUs
	//
	// English: Online CPUs. (Linux only)
	KOnlinePreCPUs     = 0b0000000000000000000000000000000000000000000001000000000000000000
	KOnlinePreCPUsComa = 0b0111111111111111111111111111111111111111111110000000000000000000

	// KAggregatePreCPUTimeTheContainerWasThrottled
	//
	// English: Throttling Data. (Linux only) - Aggregate time the container was throttled for in nanoseconds
	KAggregatePreCPUTimeTheContainerWasThrottled     = 0b0000000000000000000000000000000000000000000010000000000000000000
	KAggregatePreCPUTimeTheContainerWasThrottledComa = 0b0111111111111111111111111111111111111111111100000000000000000000

	// KNumberOfPeriodsWithPreCPUThrottlingActive
	//
	// English: Throttling Data. (Linux only) - Number of periods with throttling active
	KNumberOfPeriodsWithPreCPUThrottlingActive     = 0b0000000000000000000000000000000000000000000100000000000000000000
	KNumberOfPeriodsWithPreCPUThrottlingActiveComa = 0b0111111111111111111111111111111111111111111000000000000000000000

	// KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit
	//
	// English: Throttling Data. (Linux only) - Number of periods when the container hits its throttling limit.
	KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit     = 0b0000000000000000000000000000000000000000001000000000000000000000
	KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitComa = 0b0111111111111111111111111111111111111111110000000000000000000000

	// KCurrentResCounterUsageForMemory
	//
	// English: Current res_counter usage for memory
	KCurrentResCounterUsageForMemory     = 0b0000000000000000000000000000000000000000010000000000000000000000
	KCurrentResCounterUsageForMemoryComa = 0b0111111111111111111111111111111111111111100000000000000000000000

	// KMaximumUsageEverRecorded
	//
	// English: Maximum usage ever recorded
	KMaximumUsageEverRecorded     = 0b0000000000000000000000000000000000000000100000000000000000000000
	KMaximumUsageEverRecordedComa = 0b0111111111111111111111111111111111111111000000000000000000000000

	// KNumberOfTimesMemoryUsageHitsLimits
	//
	// English: Number of times memory usage hits limits
	KNumberOfTimesMemoryUsageHitsLimits     = 0b0000000000000000000000000000000000000001000000000000000000000000
	KNumberOfTimesMemoryUsageHitsLimitsComa = 0b0111111111111111111111111111111111111110000000000000000000000000

	// KMemoryLimit
	//
	// English: Memory limit
	KMemoryLimit     = 0b0000000000000000000000000000000000000010000000000000000000000000
	KMemoryLimitComa = 0b0111111111111111111111111111111111111100000000000000000000000000

	// KCommittedBytes
	//
	// English: Committed bytes
	KCommittedBytes     = 0b0000000000000000000000000000000000000100000000000000000000000000
	KCommittedBytesComa = 0b0111111111111111111111111111111111111000000000000000000000000000

	// KPeakCommittedBytes
	//
	// English: Peak committed bytes
	KPeakCommittedBytes     = 0b0000000000000000000000000000000000001000000000000000000000000000
	KPeakCommittedBytesComa = 0b0111111111111111111111111111111111110000000000000000000000000000

	// KPrivateWorkingSet
	//
	// English: Private working set
	KPrivateWorkingSet     = 0b0000000000000000000000000000000000010000000000000000000000000000
	KPrivateWorkingSetComa = 0b0111111111111111111111111111111111100000000000000000000000000000

	KBlkioIoServiceBytesRecursive     = 0b0000000000000000000000000000000000100000000000000000000000000000
	KBlkioIoServiceBytesRecursiveComa = 0b0111111111111111111111111111111111000000000000000000000000000000

	KBlkioIoServicedRecursive     = 0b0000000000000000000000000000000001000000000000000000000000000000
	KBlkioIoServicedRecursiveComa = 0b0111111111111111111111111111111110000000000000000000000000000000

	KBlkioIoQueuedRecursive     = 0b0000000000000000000000000000000010000000000000000000000000000000
	KBlkioIoQueuedRecursiveComa = 0b0111111111111111111111111111111100000000000000000000000000000000

	KBlkioIoServiceTimeRecursive     = 0b0000000000000000000000000000000100000000000000000000000000000000
	KBlkioIoServiceTimeRecursiveComa = 0b0111111111111111111111111111111000000000000000000000000000000000

	KBlkioIoWaitTimeRecursive     = 0b0000000000000000000000000000001000000000000000000000000000000000
	KBlkioIoWaitTimeRecursiveComa = 0b0111111111111111111111111111110000000000000000000000000000000000

	KBlkioIoMergedRecursive     = 0b0000000000000000000000000000010000000000000000000000000000000000
	KBlkioIoMergedRecursiveComa = 0b0111111111111111111111111111100000000000000000000000000000000000

	KBlkioIoTimeRecursive     = 0b0000000000000000000000000000100000000000000000000000000000000000
	KBlkioIoTimeRecursiveComa = 0b0111111111111111111111111111000000000000000000000000000000000000

	KBlkioSectorsRecursive     = 0b0000000000000000000000000001000000000000000000000000000000000000
	KBlkioSectorsRecursiveComa = 0b0111111111111111111111111110000000000000000000000000000000000000

	// KMacOsLogWithAllCores
	//
	// English: Mac OS Log
	KMacOsLogWithAllCores = KReadingTime |
		KCurrentNumberOfOidsInTheCGroup |
		KTotalCPUTimeConsumed |
		KTotalCPUTimeConsumedPerCore |
		KTimeSpentByTasksOfTheCGroupInKernelMode |
		KSystemUsage |
		KOnlineCPUs |
		KTotalPreCPUTimeConsumed |
		KTotalPreCPUTimeConsumedPerCore |
		KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode |
		KPreCPUSystemUsage |
		KOnlinePreCPUs |
		KCurrentResCounterUsageForMemory |
		KMaximumUsageEverRecorded |
		KMemoryLimit |
		KBlkioIoServiceBytesRecursive |
		KBlkioIoServicedRecursive |
		KBlkioIoQueuedRecursive |
		KBlkioIoServiceTimeRecursive |
		KBlkioIoWaitTimeRecursive |
		KBlkioIoMergedRecursive |
		KBlkioIoTimeRecursive |
		KBlkioSectorsRecursive // não aparece no mac

	// KMacOsLog
	//
	// English: Mac OS Log
	KMacOsLog = KReadingTime |
		KCurrentNumberOfOidsInTheCGroup |
		KTotalCPUTimeConsumed |
		KTimeSpentByTasksOfTheCGroupInKernelMode |
		KSystemUsage |
		KOnlineCPUs |
		KTotalPreCPUTimeConsumed |
		KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode |
		KPreCPUSystemUsage |
		KOnlinePreCPUs |
		KCurrentResCounterUsageForMemory |
		KMaximumUsageEverRecorded |
		KMemoryLimit |
		KBlkioIoServiceBytesRecursive |
		KBlkioIoServicedRecursive |
		KBlkioIoQueuedRecursive |
		KBlkioIoServiceTimeRecursive |
		KBlkioIoWaitTimeRecursive |
		KBlkioIoMergedRecursive |
		KBlkioIoTimeRecursive |
		KBlkioSectorsRecursive // não aparece no mac
)
View Source
const (
	KLogReadingTimeLabel  = "Reading time"
	KLogReadingTimeValue  = "KReadingTime"
	KLogReadingTimeRegexp = "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}.\\d{4,}(\\s\\+\\d{4})?\\sUTC"

	KLogCurrentNumberOfOidsInTheCGroupLabel  = "Linux specific stats - not populated on Windows. Current is the number of pids in the cgroup"
	KLogCurrentNumberOfOidsInTheCGroupValue  = "KCurrentNumberOfOidsInTheCGroup"
	KLogCurrentNumberOfOidsInTheCGroupRegexp = "\\d+"

	KLogLimitOnTheNumberOfPidsInTheCGroupLabel  = "" /* 155-byte string literal not displayed */
	KLogLimitOnTheNumberOfPidsInTheCGroupValue  = "KLimitOnTheNumberOfPidsInTheCGroup"
	KLogLimitOnTheNumberOfPidsInTheCGroupRegexp = "\\d+"

	KLogTotalCPUTimeConsumedLabel  = "Total CPU time consumed. (Units: nanoseconds on Linux - Units: 100's of nanoseconds on Windows)"
	KLogTotalCPUTimeConsumedValue  = "KTotalCPUTimeConsumed"
	KLogTotalCPUTimeConsumedRegexp = "\\d+"

	KLogTotalCPUTimeConsumedPerCoreLabel  = "Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows."
	KLogTotalCPUTimeConsumedPerCoreValue  = "KTotalCPUTimeConsumedPerCore"
	KLogTotalCPUTimeConsumedPerCoreRegexp = "\\d+"

	KLogTimeSpentByTasksOfTheCGroupInKernelModeLabel  = "" /* 212-byte string literal not displayed */
	KLogTimeSpentByTasksOfTheCGroupInKernelModeValue  = "KTimeSpentByTasksOfTheCGroupInKernelMode"
	KLogTimeSpentByTasksOfTheCGroupInKernelModeRegexp = "\\d+"

	KLogTimeSpentByTasksOfTheCGroupInUserModeLabel  = "" /* 208-byte string literal not displayed */
	KLogTimeSpentByTasksOfTheCGroupInUserModeValue  = "KTimeSpentByTasksOfTheCGroupInUserMode"
	KLogTimeSpentByTasksOfTheCGroupInUserModeRegexp = "\\d+"

	KLogSystemUsageLabel  = "System Usage. Linux only."
	KLogSystemUsageValue  = "KSystemUsage"
	KLogSystemUsageRegexp = "\\d+"

	KLogOnlineCPUsLabel  = "Online CPUs. Linux only."
	KLogOnlineCPUsValue  = "KOnlineCPUs"
	KLogOnlineCPUsRegexp = "\\d+"

	KLogNumberOfPeriodsWithThrottlingActiveLabel  = "Throttling Data. Linux only. Number of periods with throttling active."
	KLogNumberOfPeriodsWithThrottlingActiveValue  = "KNumberOfPeriodsWithThrottlingActive"
	KLogNumberOfPeriodsWithThrottlingActiveRegexp = "\\d+"

	KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitLabel  = "Throttling Data. Linux only. Number of periods when the container hits its throttling limit."
	KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitValue  = "KNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimit"
	KLogNumberOfPeriodsWhenTheContainerHitsItsThrottlingLimitRegexp = "\\d+"

	KLogAggregateTimeTheContainerWasThrottledForInNanosecondsLabel  = "Throttling Data. Linux only. Aggregate time the container was throttled for in nanoseconds."
	KLogAggregateTimeTheContainerWasThrottledForInNanosecondsValue  = "KAggregateTimeTheContainerWasThrottledForInNanoseconds"
	KLogAggregateTimeTheContainerWasThrottledForInNanosecondsRegexp = "\\d+"

	KLogTotalPreCPUTimeConsumedLabel  = "Total CPU time consumed. (Units: nanoseconds on Linux. Units: 100's of nanoseconds on Windows)"
	KLogTotalPreCPUTimeConsumedValue  = "KTotalPreCPUTimeConsumed"
	KLogTotalPreCPUTimeConsumedRegexp = "\\d+"

	KLogTotalPreCPUTimeConsumedPerCoreLabel  = "Total CPU time consumed per core (Units: nanoseconds on Linux). Not used on Windows."
	KLogTotalPreCPUTimeConsumedPerCoreValue  = "KTotalPreCPUTimeConsumedPerCore"
	KLogTotalPreCPUTimeConsumedPerCoreRegexp = "\\d+"

	KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeLabel  = "" /* 214-byte string literal not displayed */
	KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeValue  = "KTimeSpentByPreCPUTasksOfTheCGroupInKernelMode"
	KLogTimeSpentByPreCPUTasksOfTheCGroupInKernelModeRegexp = "\\d+"

	KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeLabel  = "" /* 208-byte string literal not displayed */
	KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeValue  = "KTimeSpentByPreCPUTasksOfTheCGroupInUserMode"
	KLogTimeSpentByPreCPUTasksOfTheCGroupInUserModeRegexp = "\\d+"

	KLogPreCPUSystemUsageLabel  = "System Usage. (Linux only)"
	KLogPreCPUSystemUsageValue  = "KPreCPUSystemUsage"
	KLogPreCPUSystemUsageRegexp = "\\d+"

	KLogOnlinePreCPUsLabel  = "Online CPUs. (Linux only)"
	KLogOnlinePreCPUsValue  = "KOnlinePreCPUs"
	KLogOnlinePreCPUsRegexp = "\\d+"

	KLogAggregatePreCPUTimeTheContainerWasThrottledLabel  = "Throttling Data. (Linux only) - Aggregate time the container was throttled for in nanoseconds."
	KLogAggregatePreCPUTimeTheContainerWasThrottledValue  = "KAggregatePreCPUTimeTheContainerWasThrottled"
	KLogAggregatePreCPUTimeTheContainerWasThrottledRegexp = "\\d+"

	KLogNumberOfPeriodsWithPreCPUThrottlingActiveLabel  = "Throttling Data. (Linux only) - Number of periods with throttling active."
	KLogNumberOfPeriodsWithPreCPUThrottlingActiveValue  = "KNumberOfPeriodsWithPreCPUThrottlingActive"
	KLogNumberOfPeriodsWithPreCPUThrottlingActiveRegexp = "\\d+"

	KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitLabel  = "Throttling Data. (Linux only) - Number of periods when the container hits its throttling limit."
	KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitValue  = "KNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimit"
	KLogNumberOfPeriodsWhenTheContainerPreCPUHitsItsThrottlingLimitRegexp = "\\d+"

	KLogCurrentResCounterUsageForMemoryLabel  = "Current res_counter usage for memory"
	KLogCurrentResCounterUsageForMemoryValue  = "KCurrentResCounterUsageForMemory"
	KLogCurrentResCounterUsageForMemoryRegexp = "\\d+"

	KLogMaximumUsageEverRecordedLabel  = "Maximum usage ever recorded."
	KLogMaximumUsageEverRecordedValue  = "KMaximumUsageEverRecorded"
	KLogMaximumUsageEverRecordedRegexp = "\\d+"

	KLogNumberOfTimesMemoryUsageHitsLimitsLabel  = "Number of times memory usage hits limits."
	KLogNumberOfTimesMemoryUsageHitsLimitsValue  = "KNumberOfTimesMemoryUsageHitsLimits"
	KLogNumberOfTimesMemoryUsageHitsLimitsRegexp = "\\d+"

	KLogMemoryLimitLabel  = "Memory limit"
	KLogMemoryLimitValue  = "KMemoryLimit"
	KLogMemoryLimitRegexp = "\\d+"

	KLogCommittedBytesLabel  = "Committed bytes"
	KLogCommittedBytesValue  = "KCommittedBytes"
	KLogCommittedBytesRegexp = "\\d+"

	KLogPeakCommittedBytesLabel  = "Peak committed bytes"
	KLogPeakCommittedBytesValue  = "KPeakCommittedBytes"
	KLogPeakCommittedBytesRegexp = "\\d+"

	KLogPrivateWorkingSetLabel  = "Private working set"
	KLogPrivateWorkingSetValue  = "KPrivateWorkingSet"
	KLogPrivateWorkingSetRegexp = "\\d+"
)

Variables

This section is empty.

Functions

func ConfigScene added in v0.9.11

func ConfigScene(sceneName string, maxStopedContainers, maxPausedContainers, maxTotalPausedAndStoppedContainers int)

ConfigScene

English: Add and configure a test scene prevents all containers in the scene from stopping at the same time

Português: Adiciona e configura uma cena de teste impede que todos os container da cena parem ao mesmo tempo

func DirCheckExists added in v0.9.25

func DirCheckExists(path string) (exists bool)

func GarbageCollector

func GarbageCollector()

GarbageCollector

English: A great use of this code is to build container during unit testing, and in this case, you can add the term delete to the name of all docker elements created during the test, so that they are deleted in a simple way. e.g..: network_to_delete_after_test

Português: Uma grande utilidade desse código é levantar container durante testes unitários, e nesse caso, você pode adicionar o termo delete ao nome de todos os elementos docker criado durante o teste, para que os mesmos sejam apagados de forma simples. ex.: network_to_delete_after_test

func MakeDir added in v0.9.25

func MakeDir(path string) (err error)

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 is one small entity 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 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.

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 aggregates and wraps all CPU related info of 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 stores All CPU stats aggregated since container inception.

type ContainerBuilder

type ContainerBuilder struct {
	IPV4Address string
	// contains filtered or unexported fields
}

ContainerBuilder

English: Docker manager

Português: Gerenciador de containers e imagens docker

func (*ContainerBuilder) AddFailMatchFlag added in v0.9.11

func (e *ContainerBuilder) AddFailMatchFlag(value string)

AddFailMatchFlag

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: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)

// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()

// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")

// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/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.
container.SetImageBuildOptionsMemory(100 * KMegaByte)

container.AddFailMatchFlag(
	"counter: 400000",
)

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

// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Starts container monitoring at two second intervals. This functionality 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(time.NewTicker(2 * time.Second))

// English: Gets the event channel pointer inside the container.
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()

select {
case e := <-*event:
	fmt.Printf("container name: %v\n", e.ContainerName)
	fmt.Printf("done: %v\n", e.Done)
	fmt.Printf("fail: %v\n", e.Fail)
	fmt.Printf("error: %v\n", e.Error)
}

// English: Stop container monitoring.
// Português: Para o monitoramento do container.
_ = container.StopMonitor()

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

var data []byte
data, err = ioutil.ReadFile("./log1/log2/log3/log.0.log")
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

if len(data) == 0 {
	fmt.Println("log file error")
}

_ = os.Remove("./log1/log2/log3/log.0.log")
_ = os.Remove("./log1/log2/log3/")
_ = os.Remove("./log1/log2/")
_ = os.Remove("./log1/")
Output:

image size: 1.38 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

English: Error text searched for in the container's standard output.

Input:
  value: Error text
  logFilePath: path to diretory to save container default output into file

Português: Texto indicativo de erro procurado na saída padrão do container.

Entrada:
  value: Texto indicativo de erro
  logFilePath: caminho do diretório para salvar a saída padrão do container em arquivo

func (*ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer added in v0.5.22

func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)

AddFileOrFolderToLinkBetweenConputerHostAndContainer

English: Links a file or folder between the computer host and the container.

Input:
  computerHostPath:    Path of the file or folder inside the host computer.
  insideContainerPath: Path inside the container.
Output:
  err: Default error object.

Português: Vincula um arquivo ou pasta entre o computador e o container.

Entrada:
  computerHostPath:    Caminho do arquivo ou pasta no computador hospedeiro.
  insideContainerPath: Caminho dentro do container.
Output:
  err: Objeto de erro padrão.
Example
var err error

GarbageCollector()

var container = ContainerBuilder{}

// new image name delete:latest
container.SetImageName("delete:latest")

// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")

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

// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()

// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout(
	"Stating server on port 3000",
	10*time.Second,
)

// change and open port 3000 to 3030
container.AddPortToChange(
	"3000",
	"3030",
)

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

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

// todo: fazer o inspect

// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

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

// container "container_delete_server_after_test" running and ready for use on this code point on port 3030

// read server inside a container on address http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

// print output
fmt.Printf("%s", body)

GarbageCollector()
Output:

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

func (*ContainerBuilder) AddFilterAndReplaceToLog added in v0.9.16

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

AddFilterAndReplaceToLog

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.
  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 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`.
  search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
  replace: Elemento da troca da expressão regular [opcional].

func (*ContainerBuilder) AddFilterToFail added in v0.9.11

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

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: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)

// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()

// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")

// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/counter")

// English: Defines the name of the docker container to be created.
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")

// English: Defines the maximum amount of memory to be used by the docker container.
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)

// English: Defines the log file path with container statistical data
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetLogPath("./test.counter.log.csv")

// 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.AddFilterAndReplaceToLog(
	// English: Label to be written to log file
	// Português: Rótulo a ser escrito no arquivo de log
	"contador",

	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"counter",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"\\.",
	",",
)

// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"done!",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
	"${value}",
)

// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"counter: 40",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
	"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)

// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor(time.NewTicker(2 * time.Second))

// English: Gets the event channel pointer inside the container.
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()

select {
case e := <-*event:
	fmt.Printf("container name: %v\n", e.ContainerName)
	fmt.Printf("done: %v\n", e.Done)
	fmt.Printf("fail: %v\n", e.Fail)
	fmt.Printf("error: %v\n", e.Error)
	fmt.Printf("message: %v\n", e.Message)
}

// English: Stop container monitoring.
// Português: Para o monitoramento do container.
container.StopMonitor()

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
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) AddFilterToLog added in v0.9.11

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

AddFilterToLog

English: Adds a filter to search and convert a textual value to a column in the log file.

Input:
  label: Value to be placed in the log file column.
  match: Simple text searched in the container's standard output to activate the filter
  filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter.

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

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

var 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.SetLogPath("./test.counter.log.csv")

// 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.AddFilterAndReplaceToLog(
	// English: Label to be written to log file
	// Português: Rótulo a ser escrito no arquivo de log
	"contador",

	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"counter",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"\\.",
	":",
)

// English: Adds a filter to look for a value in the container's standard output indicating the success of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando o sucesso do teste.
container.AddFilterToSuccess(
	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"done!",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
	"${value}",
)

// English: Adds a filter to look for a value in the container's standard output indicating the fail of the test.
// Português: Adiciona um filtro para procurar um valor na saída padrão do container indicando a falha do teste.
container.AddFilterToFail(
	// English: Simple text searched in the container's standard output to activate the filter
	// Português: Texto simples procurado na saída padrão do container para ativar o filtro
	"counter: 40",

	// English: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
	// Português: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",

	// English: Regular expression used for search and replacement in the text found in the previous step [optional].
	// Português: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
	"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)

// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor(time.NewTicker(2 * time.Second))

// English: Gets the event channel pointer inside the container.
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()

select {
case e := <-*event:
	fmt.Printf("container name: %v\n", e.ContainerName)
	fmt.Printf("done: %v\n", e.Done)
	fmt.Printf("fail: %v\n", e.Fail)
	fmt.Printf("error: %v\n", e.Error)
	fmt.Printf("message: %v\n", e.Message)
}

// English: Stop container monitoring.
// Português: Para o monitoramento do container.
container.StopMonitor()

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
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) AddFilterToRestartContainer added in v0.9.11

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

AddFilterToRestartContainer

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: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

var container = ContainerBuilder{}

// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)

// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()

// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")

// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/chaos")

// English: Defines the name of the docker container to be created.
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")

// English: Defines the maximum amount of memory to be used by the docker container.
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)

// English: Defines the log file path with container statistical data
// Português: Define o caminho do arquivo de log com dados estatísticos do container
container.SetLogPath("./test.counter.log.csv")

// 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.AddFilterAndReplaceToLog(
	// 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}",
)

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.SetTimeToStartChaos(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.SetTimeBeforeRestart(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.SetTimeToPause(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.SetTimeToUnpause(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.SetTimeToRestart(2*time.Second, 5*time.Second)

// English: Enable chaos test
// Português: Habilita o teste de caos
container.EnableChaos(true)

// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Starts container monitoring at two second intervals. This functionality generates the log and monitors the standard output of the container.
// Português: Inicializa o monitoramento do container com intervalos de dois segundos. Esta funcionalidade gera o log e monitora a saída padrão do container.
container.StartMonitor(time.NewTicker(2 * time.Second))

// English: Gets the event channel pointer inside the container.
// Português: Pega o ponteiro do canal de eventos dentro do container.
event := container.GetChaosEvent()

select {
case e := <-*event:
	fmt.Printf("container name: %v\n", e.ContainerName)
	fmt.Printf("done: %v\n", e.Done)
	fmt.Printf("fail: %v\n", e.Fail)
	fmt.Printf("error: %v\n", e.Error)
	fmt.Printf("message: %v\n", e.Message)
}

// English: Stop container monitoring.
// Português: Para o monitoramento do container.
container.StopMonitor()

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
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) AddFilterToStartChaos added in v0.9.11

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

AddFilterToStartChaos

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.

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.

func (*ContainerBuilder) AddFilterToSuccess added in v0.9.11

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

AddFilterToFail

English: Adds a filter to the container's standard output to look for a textual value indicating test success.

Input:
  match: Simple text searched in the container's standard output to activate the filter
  filter: Regular expression used to filter what goes into the log using the `valueToGet` parameter.
  search: Regular expression used for search and replacement in the text found in the previous step [optional].
  replace: Regular expression replace element [optional].

Português: Adiciona um filtro na saída padrão do container para procurar um valor textual indicador de sucesso do teste.

Entrada:
  match: Texto simples procurado na saída padrão do container para ativar o filtro
  filter: Expressão regular usada para filtrar o que vai para o log usando o parâmetro `valueToGet`.
  search: Expressão regular usada para busca e substituição no texto encontrado na etapa anterior [opcional].
  replace: Elemento da troca da expressão regular [opcional].

func (*ContainerBuilder) AddImageBuildOptionsBuildArgs

func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)

AddImageBuildOptionsBuildArgs

English: Set build-time variables (--build-arg)

Input:
  key: Argument name
  value: Argument value

Example:

key:   argument key (e.g. Dockerfile: ARG key)
value: argument value

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

  code:
    var key = "GIT_PRIVATE_REPO"
    var value = "github.com/yourgit"

    var container = ContainerBuilder{}
    container.AddImageBuildOptionsBuildArgs(key, &value)

  Dockerfile:
    FROM golang:1.16-alpine as builder
    ARG GIT_PRIVATE_REPO
    RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO

Português: Adiciona uma variável durante a construção (--build-arg)

Input:
  key: Nome do argumento.
  value: Valor do argumento.

Exemplo:

key:   chave do argumento (ex. Dockerfile: ARG key)
value: valor do argumento

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

  code:
    var key = "GIT_PRIVATE_REPO"
    var value = "github.com/yourgit"

    var container = ContainerBuilder{}
    container.AddImageBuildOptionsBuildArgs(key, &value)

  Dockerfile:
    FROM golang:1.16-alpine as builder
    ARG GIT_PRIVATE_REPO
    RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO

func (*ContainerBuilder) AddLogFilter added in v0.9.11

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

AddLogFilter

English: Adds a filter to the container's standard output to search for a textual value and populate the container's log file.

Input:
  label: Column label in log file
  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 e preencher o arquivo de log do container.

Entrada:
  label: Rótulo da coluna no 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].

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

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

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

GarbageCollector()

var container = ContainerBuilder{}

// new image name delete:latest
container.SetImageName("delete:latest")

// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")

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

// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()

// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")

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

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

// todo: fazer o inspect

// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

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

// container "container_delete_server_after_test" running and ready for use on this code point on port 3030

// read server inside a container on address http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

// print output
fmt.Printf("%s", body)

GarbageCollector()
Output:

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

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

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

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

GarbageCollector()

var container = ContainerBuilder{}

// new image name delete:latest
container.SetImageName("delete:latest")

// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")

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

// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()

// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 20*time.Second)

// open port 3000 [optional in this case: default code open all ports]
container.AddPortToExpose("3000")

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

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

//todo: fazer o inspect

// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

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

// container "container_delete_server_after_test" running and ready for use on this code point on port 3030

// read server inside a container on address http://localhost:3000/
var resp *http.Response
resp, err = http.Get("http://localhost:3000/")
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

// print output
fmt.Printf("%s", body)

GarbageCollector()
Output:

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

func (*ContainerBuilder) AddRestartFilter added in v0.9.11

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

func (*ContainerBuilder) AddRestartMatchFlag added in v0.9.11

func (e *ContainerBuilder) AddRestartMatchFlag(value string)

func (*ContainerBuilder) AddSuccessFilter added in v0.9.11

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

func (*ContainerBuilder) AddSuccessMatchFlag added in v0.9.11

func (e *ContainerBuilder) AddSuccessMatchFlag(value string)

func (*ContainerBuilder) ContainerBuildAndStartFromImage added in v0.5.40

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

ContainerBuildAndStartFromImage

English: Transforms an image downloaded by ImagePull() or created by ImageBuildFromFolder() into a container and start it.

Output:
  err: Default object error from golang

Português: Transforma uma imagem baixada por ImagePull() ou criada por ImageBuildFromFolder() em container e o inicializa.

Saída:
  err: Objeto padrão de erro golang
Example
var err error

GarbageCollector()

var container = ContainerBuilder{}

// new image name delete:latest
container.SetImageName("delete:latest")

// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")

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

// see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and
// SetGitCloneToBuildWithPrivateToken()

// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)

// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")

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

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

// todo: fazer o inspect

// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	log.Printf("container.ImageBuildFromServer().error: %v", err.Error())
	panic(err)
}

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

// container "container_delete_server_after_test" running and ready for use on this code point on port 3030

// read server inside a container on address http://localhost:3030/
var resp *http.Response
resp, err = http.Get("http://localhost:3030/")
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
	util.TraceToLog()
	log.Printf("http.Get().error: %v", err.Error())
	panic(err)
}

// print output
fmt.Printf("%s", body)

GarbageCollector()
Output:

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

func (*ContainerBuilder) ContainerBuildWithoutStartingItFromImage added in v0.5.40

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

func (*ContainerBuilder) ContainerFindIdByName added in v0.5.19

func (e *ContainerBuilder) ContainerFindIdByName(name string) (id string, err error)

func (*ContainerBuilder) ContainerFindIdByNameContains added in v0.5.19

func (e *ContainerBuilder) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)

func (*ContainerBuilder) ContainerInspect

func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)

ContainerInspect

English: inspects the container

Português: inspeciona o container

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.

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

removeVolumes: removes docker volumes linked to the container

Português: parar e remover o container

removeVolumes: remove os volumes docker vinculados ao container

func (*ContainerBuilder) ContainerRestart added in v0.5.40

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

func (*ContainerBuilder) ContainerRestartWithTimeout added in v0.5.40

func (e *ContainerBuilder) ContainerRestartWithTimeout(timeout time.Duration) (err error)

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.

ContainerStart (português): Inicializar um container pausado ou parado.

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

Nota: - Ha duas formas de criar um container:
        ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o
        registro aa rede docker, para que o mesmo funcione de forma correta.
        ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a
        primeira vez que o mesmo roda, ele deve ter o seu registro de rede
        inicializado para que possa funcionar de forma correta.
      - Apos inicializado a primeira vez, use as funções, ContainerStart,
        ContainerPause e ContainerStop, caso necessite controlar o container.

func (*ContainerBuilder) ContainerStartAfterBuild added in v0.5.40

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

ContainerStartAfterBuild (english):

ContainerStartAfterBuild (português): Inicia um container recem criado.

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

Nota: - Ha duas formas de criar um container:
        ContainerBuildAndStartFromImage, inicializa o oncontainer e inicializa o
        registro aa rede docker, para que o mesmo funcione de forma correta.
        ContainerBuildWithoutStartingItFromImage apenas cria o container, por isto, a
        primeira vez que o mesmo roda, ele deve ter o seu registro de rede
        inicializado para que possa funcionar de forma correta.
      - Apos inicializado a primeira vez, use as funções, ContainerStart,
        ContainerPause e ContainerStop, caso necessite controlar o container.

func (*ContainerBuilder) ContainerStatisticsOneShot added in v0.5.44

func (e *ContainerBuilder) ContainerStatisticsOneShot() (
	statsRet types.Stats,
	err error,
)

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.

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

func (*ContainerBuilder) EnableChaos added in v0.9.11

func (e *ContainerBuilder) EnableChaos(enable bool)

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

Português: Inspeciona a rede do docker e devolve o IP atual do container

Example
var err error

GarbageCollector()

var container = ContainerBuilder{}

// set image name for docker pull
container.SetImageName("nats:latest")

// set a container name
container.SetContainerName("container_delete_nats_after_test")

// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)

// inialize the container object
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// image nats:latest pull command [optional]
err = container.ImagePull()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// container build and start from image nats:latest
// waits for the text "Listening for route connections on 0.0.0.0:6222" to appear  in the standard container output
// to proceed
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	util.TraceToLog()
	panic(err)
}

var IP string
IP, err = container.FindCurrentIPV4Address()
if err != nil {
	util.TraceToLog()
	panic(err)
}

if IP != container.GetIPV4Address() {
	err = errors.New("all ip address must be a samer IP")
	util.TraceToLog()
	panic(err)
}

// container "container_delete_nats_after_test" running and ready for use on this code point on var IP
// all nats ports are open
// you can use AddPortToExpose("4222"), to open only ports defineds inside code;
// you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port
// 1111;
// you can use SetDoNotOpenContainersPorts() to not open containers ports

GarbageCollector()

// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
	util.TraceToLog()
	panic(err)
}
Output:

func (*ContainerBuilder) FindTextInsideContainerLog

func (e *ContainerBuilder) FindTextInsideContainerLog(value string) (contains bool, err error)

FindTextInsideContainerLog

English: search for text in standard container output.

value: searched text

Português: procurar por um texto na saída padrão do container.

value: texto procurado

func (*ContainerBuilder) GetBuildFolderPath added in v0.9.11

func (e *ContainerBuilder) GetBuildFolderPath() (buildPath string)

func (*ContainerBuilder) GetChannelEvent

func (e *ContainerBuilder) GetChannelEvent() (channel *chan iotmakerdocker.ContainerPullStatusSendToChannel)

GetChannelEvent (english):

GetChannelEvent (português): Canal disparado durante o processo de image build ou container build e retorna informações como andamento do download da imagem, processo de extração da mesma entre outras informações

Waiting: Esperando o processo ser iniciado pelo docker
Downloading: Estado do download da imagem, caso a mesma não exista na máquina host
  Count: Quantidade de blocos a serem baixados
  Current: Total de bytes baixados até o momento
  Total: Total de bytes a serem baixados
  Percent: Percentual atual do processo com uma casa decimal de precisão
DownloadComplete: todo: fazer
Extracting: Estado da extração da imagem baixada
  Count: Quantidade de blocos a serem extraídos
  Current: Total de bytes extraídos até o momento
  Total: Total de bytes a serem extraídos
  Percent: Percentual atual do processo com uma casa decimal de precisão
PullComplete: todo: fazer
ImageName: nome da imagem baixada
ImageID: ID da imagem baixada. (Cuidado: este valor só é definido ao final do processo)
ContainerID: ID do container criado. (Cuidado: este valor só é definido ao final do processo)
Closed: todo: fazer
Stream: saída padrão do container durante o processo de build
SuccessfullyBuildContainer: sucesso ao fim do processo de build do container
SuccessfullyBuildImage: sucesso ao fim do processo de build da imagem
IdAuxiliaryImages: usado pelo coletor de lixo para apagar as imagens axiliares ao fim do processo de build

func (*ContainerBuilder) GetChannelOnContainerInspect

func (e *ContainerBuilder) GetChannelOnContainerInspect() (channel *chan bool)

GetChannelOnContainerInspect

English: Channel triggered at each ticker cycle defined in SetInspectInterval()

Português: Canal disparado a cada ciclo do ticker definido em SetInspectInterval()

func (*ContainerBuilder) GetChannelOnContainerReady

func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)

GetChannelOnContainerReady

English: Channel fired when the container is ready for use

Note: This channel expects the container to signal that it is ready, but it does not take into account whether
the application contained in the container is ready. For this reason, it is recommended to use SetWaitString()

Português: Canal disparado quando o container está pronto para uso

Nota: Este canal espera o container sinalizar que está pronto, mas, ele não considera se a aplicação contida
no container está pronta. Por isto, é recomendado o uso de SetWaitString()

func (*ContainerBuilder) GetChaosEvent added in v0.9.11

func (e *ContainerBuilder) GetChaosEvent() (eventChannel *chan Event)

func (*ContainerBuilder) GetContainerID

func (e *ContainerBuilder) GetContainerID() (ID string)

GetContainerID

English: Returns the ID of the created container

Português: Retorna o ID do container criado

func (*ContainerBuilder) GetContainerInfo added in v0.9.11

func (e *ContainerBuilder) GetContainerInfo() (info types.Info, err error)

func (ContainerBuilder) GetContainerIsStarted added in v0.9.11

func (e ContainerBuilder) GetContainerIsStarted() (started bool)

func (*ContainerBuilder) GetContainerLog

func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)

GetContainerLog

English: Returns the current standard output of the container.

Português: Retorna a saída padrão atual do container.

func (*ContainerBuilder) GetContainerName added in v0.9.11

func (e *ContainerBuilder) GetContainerName() (containerName string)

func (*ContainerBuilder) GetGitCloneToBuild added in v0.9.11

func (e *ContainerBuilder) GetGitCloneToBuild() (url string)

func (*ContainerBuilder) GetIPV4Address

func (e *ContainerBuilder) GetIPV4Address() (IP string)

GetIPV4Address

English: Returns the last IP read from the container

Note: If the container is disconnected or connected to another network after creation, this information may
change

Português: Retorna o último IP lido do container

Nota: Caso o container seja desconectado ou conectado a outra rede após a criação, esta informação pode mudar

func (*ContainerBuilder) GetIdByContainerName

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

GetIdByContainerName

English: Returns the container ID defined in SetContainerName()

Português: Retorna o ID do container definido em SetContainerName()

func (*ContainerBuilder) GetImageArchitecture added in v0.9.11

func (e *ContainerBuilder) GetImageArchitecture() (architecture string)

func (*ContainerBuilder) GetImageAuthor added in v0.9.11

func (e *ContainerBuilder) GetImageAuthor() (author string)

func (*ContainerBuilder) GetImageCacheName added in v0.9.11

func (e *ContainerBuilder) GetImageCacheName() (name string)

func (*ContainerBuilder) GetImageComment added in v0.9.11

func (e *ContainerBuilder) GetImageComment() (comment string)

func (*ContainerBuilder) GetImageContainer added in v0.9.11

func (e *ContainerBuilder) GetImageContainer() (container string)

func (*ContainerBuilder) GetImageCreated added in v0.9.11

func (e *ContainerBuilder) GetImageCreated() (created time.Time)

func (*ContainerBuilder) GetImageExpirationTime added in v0.9.12

func (e *ContainerBuilder) GetImageExpirationTime() (expiration time.Duration)

func (*ContainerBuilder) GetImageID

func (e *ContainerBuilder) GetImageID() (ID string)

GetImageID

English: Returns the image ID.

Português: Retorna o ID da imagem.

func (*ContainerBuilder) GetImageName

func (e *ContainerBuilder) GetImageName() (name string)

GetImageName

English: Returns the name of the image.

Português: Retorna o nome da imagem.

func (*ContainerBuilder) GetImageOs added in v0.9.11

func (e *ContainerBuilder) GetImageOs() (os string)

func (*ContainerBuilder) GetImageOsVersion added in v0.9.11

func (e *ContainerBuilder) GetImageOsVersion() (osVersion string)

func (*ContainerBuilder) GetImageParent added in v0.9.11

func (e *ContainerBuilder) GetImageParent() (parent string)

func (*ContainerBuilder) GetImageRepoDigests added in v0.9.11

func (e *ContainerBuilder) GetImageRepoDigests() (repoDigests []string)

func (*ContainerBuilder) GetImageRepoTags added in v0.9.11

func (e *ContainerBuilder) GetImageRepoTags() (repoTags []string)

func (*ContainerBuilder) GetImageSize added in v0.9.11

func (e *ContainerBuilder) GetImageSize() (size int64)

func (*ContainerBuilder) GetImageVariant added in v0.9.11

func (e *ContainerBuilder) GetImageVariant() (variant string)

func (*ContainerBuilder) GetImageVirtualSize added in v0.9.11

func (e *ContainerBuilder) GetImageVirtualSize() (virtualSize int64)

func (*ContainerBuilder) GetInitialized added in v0.9.11

func (e *ContainerBuilder) GetInitialized() (initialized bool)

func (*ContainerBuilder) GetLastInspect

func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)

GetLastInspect

English: Returns the container data based on the last ticker cycle defined in SetInspectInterval()

Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the
information is ready for use

Português: Retorna os dados do container baseado no último ciclo do ticker definido em SetInspectInterval()

Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão
prontas para uso

func (*ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog added in v0.5.43

func (e *ContainerBuilder) GetLastLineOfOccurrenceBySearchTextInsideContainerLog(value string) (text string, contains bool, err error)

func (*ContainerBuilder) GetLastLogs

func (e *ContainerBuilder) GetLastLogs() (logs string)

GetLastLogs

English: Returns the standard container output based on the last ticker cycle defined in SetInspectInterval()

Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the
information is ready for use

Português: Retorna a saída padrão do container baseado no último ciclo do ticker definido em SetInspectInterval()

Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão
prontas para uso

func (*ContainerBuilder) GetMetadata added in v0.9.25

func (e *ContainerBuilder) GetMetadata() (metadata map[string]interface{})

GetMetadata

English: Returns a list of user-defined data

Output:
  metadata: map[string]interface{} with user defined data

Português: Retorna uma lista de dados definida oelo usuário

Saída:
  metadata: map[string]interface{} com dados definidos oelo usuário

func (*ContainerBuilder) GetNetworkGatewayIPV4

func (e *ContainerBuilder) GetNetworkGatewayIPV4() (IPV4 string)

GetNetworkGatewayIPV4

English: Returns the gateway from the network to the IPV4 network

Português: Retorna o gateway da rede para rede IPV4

func (*ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName

func (e *ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName(networkName string) (IPV4 string, err error)

GetNetworkGatewayIPV4ByNetworkName

English: If the container is connected to more than one network, this function returns the gateway of the chosen network.

Note: the default docker network is named "bridge"

Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o gateway da rede escolhida.

Nota: a rede padrão do docker tem o nome "bridge"

func (*ContainerBuilder) GetNetworkIPV4

func (e *ContainerBuilder) GetNetworkIPV4() (IPV4 string)

GetNetworkIPV4

English: Return the IPV4 from the docker network

Português: Retorno o IPV4 da rede do docker

func (*ContainerBuilder) GetNetworkIPV4ByNetworkName

func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)

GetNetworkIPV4ByNetworkName

English: If the container is connected to more than one network, this function returns the IPV4 of the chosen network.

Note: the default docker network is named "bridge"

Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o IPV4 da rede escolhida.

Nota: a rede padrão do docker tem o nome "bridge"

func (*ContainerBuilder) GetNetworkInterface

func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)

GetNetworkInterface

English: Returns the object defined for the network control

Português: Retorna o objeto definido para o controle da rede

func (*ContainerBuilder) GetProblem added in v0.9.23

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

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

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: transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma imagem docker

Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles,
será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta
raiz.
Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile"
Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz,
com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo
Dockerfile padrão
Example
package main

import (
	"fmt"
	iotmakerdocker "github.com/helmutkemper/iotmaker.docker/v1.0.1"
	"github.com/helmutkemper/util"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"
)

func ImageBuildViewer(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) {
	go func(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) {
		for {

			select {
			case event := <-*ch:
				var stream = event.Stream
				stream = strings.ReplaceAll(stream, "\n", "")
				stream = strings.ReplaceAll(stream, "\r", "")
				stream = strings.Trim(stream, " ")

				if stream == "" {
					continue
				}

				log.Printf("%v", stream)

				if event.Closed == true {
					return
				}
			}
		}
	}(ch)
}

func main() {
	var err error

	GarbageCollector()

	var container = ContainerBuilder{}
	// new image name delete:latest
	container.SetImageName("delete:latest")
	// set a folder path to make a new image
	container.SetBuildFolderPath("./test/server")
	container.MakeDefaultDockerfileForMeWithInstallExtras()
	// container name container_delete_server_after_test
	container.SetContainerName("container_delete_server_after_test")
	// set a waits for the text to appear in the standard container output to proceed [optional]
	container.SetWaitStringWithTimeout("starting server at port 3000", 10*time.Second)
	// change and open port 3000 to 3030
	container.AddPortToExpose("3000")
	// replace container folder /static to host folder ./test/static
	err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
	if err != nil {
		panic(err)
	}

	// show image build stram on std out
	ImageBuildViewer(container.GetChannelEvent())

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

	// todo: fazer o teste do inspect

	// builder new image from folder
	_, err = container.ImageBuildFromFolder()
	if err != nil {
		panic(err)
	}

	// build a new container from image
	err = container.ContainerBuildAndStartFromImage()
	if err != nil {
		panic(err)
	}

	// Server is ready for use o port 3000

	// read server inside a container on address http://localhost:3000/
	var resp *http.Response
	resp, err = http.Get("http://localhost:3000/")
	if err != nil {
		util.TraceToLog()
		log.Printf("http.Get().error: %v", err.Error())
		panic(err)
	}

	var body []byte
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		util.TraceToLog()
		log.Printf("http.Get().error: %v", err.Error())
		panic(err)
	}

	// print output
	fmt.Printf("%s", body)

	GarbageCollector()

}
Output:

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

func (*ContainerBuilder) ImageBuildFromServer

func (e *ContainerBuilder) ImageBuildFromServer() (inspect types.ImageInspect, err error)

ImageBuildFromServer

English: Build a docker image from a project contained in a git repository.

Note: The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh();
SetPrivateRepositoryAutoConfig() copies the git credentials contained in ~/.ssh and the settings of
~/.gitconfig;
The SetGitConfigFile(), SetSshIdRsaFile() and SetSshKnownHostsFile() functions can be used to set git security
and configuration files manually.

Português: Monta uma imagem docker a partir de um projeto contido em um repositório git.

Nota: O repositório pode ser definido pelos métodos SetGitCloneToBuild(),
SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e
SetGitCloneToBuildWithUserPassworh();
SetPrivateRepositoryAutoConfig() copia as credências do git contidas em ~/.ssh e as configurações de
~/.gitconfig;
As funções SetGitConfigFile(), SetSshIdRsaFile() e SetSshKnownHostsFile() podem ser usadas para definir os
arquivos de configurações se segurança do git manualmente.

func (*ContainerBuilder) ImageFindIdByName added in v0.5.19

func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)

func (*ContainerBuilder) ImageFindIdByNameContains added in v0.5.19

func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)

func (*ContainerBuilder) ImageInspect added in v0.9.11

func (e *ContainerBuilder) ImageInspect() (inspect types.ImageInspect, err error)

func (*ContainerBuilder) ImageListExposedPorts

func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)

ImageListExposedPorts

English: Lists all the ports defined in the image to be exposed.

Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(),
AddPortToChange() and AddPortToExpose();
By default, all doors are closed.

Português: Lista todas as portas definidas na imagem para serem expostas.

Nota: As portas expostas na criação do container podem ser definidas por SetOpenAllContainersPorts(),
AddPortToChange() e AddPortToExpose();
Por padrão, todas as portas ficam fechadas.
Example
var err error
var portList []nat.Port

// create a container
var container = ContainerBuilder{}
// set image name for docker pull
container.SetImageName("nats:latest")
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

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

portList, err = container.ImageListExposedPorts()
if err != nil {
	util.TraceToLog()
	panic(err)
}

var portsToPrint = make([]string, 0)

for _, p := range portList {
	portsToPrint = append(portsToPrint, fmt.Sprintf("port: %v/%v\n", p.Port(), p.Proto()))
}

sort.Strings(portsToPrint)

for _, print := range portsToPrint {
	fmt.Printf("%v", print)
}

err = container.ImageRemove()
if err != nil {
	util.TraceToLog()
	panic(err)
}
Output:

port: 4222/tcp
port: 6222/tcp
port: 8222/tcp

func (*ContainerBuilder) ImageListExposedVolumes

func (e *ContainerBuilder) ImageListExposedVolumes() (list []string, err error)

ImageListExposedVolumes

English: Lists all volumes defined in the image.

Note: Use the AddFileOrFolderToLinkBetweenConputerHostAndContainer() function to link folders and files
between the host computer and the container

Português: Lista todos os volumes definidos na imagem.

Nota: Use a função AddFileOrFolderToLinkBetweenConputerHostAndContainer() para vincular pastas e arquivos
entre o computador hospedeiro e o container
Example
var err error
var volumes []string

GarbageCollector()

var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// todo: fazer o teste do inspect
_, err = container.ImageBuildFromServer()
if err != nil {
	util.TraceToLog()
	panic(err)
}

volumes, err = container.ImageListExposedVolumes()
if err != nil {
	util.TraceToLog()
	panic(err)
}

fmt.Printf("%v", volumes[0])

GarbageCollector()
Output:

/static

func (*ContainerBuilder) ImagePull

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

ImagePull

English: downloads the image to be mounted. (equivalent to the docker pull image command)

Português: baixa a imagem a ser montada. (equivale ao comando docker pull image)

Example
var err error

GarbageCollector()

// create a network [optional]
var netDocker = dockerNetwork.ContainerBuilderNetwork{}
err = netDocker.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
	util.TraceToLog()
	panic(err)
}

// create a container
var container = ContainerBuilder{}
// link container and network [optional] (next ip address is 10.0.0.2)
container.SetNetworkDocker(&netDocker)
// set image name for docker pull
container.SetImageName("nats:latest")
// set a container name
container.SetContainerName("container_delete_nats_after_test")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second)

// inialize the container object
err = container.Init()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// image nats:latest pull command [optional]
err = container.ImagePull()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// container build and start from image nats:latest
// waits for the text "Listening for route connections on 0.0.0.0:6222" to appear  in the standard container output
// to proceed
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	util.TraceToLog()
	panic(err)
}

// container "container_delete_nats_after_test" running and ready for use on this code point on IP 10.0.0.2
// all nats ports are open
// you can use AddPortToExpose("4222"), to open only ports defineds inside code;
// you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port
// 1111;
// you can use SetDoNotOpenContainersPorts() to not open containers ports

GarbageCollector()

// use this function to remove image, ONLY before container stoped and deleted
err = container.ImageRemoveByName("nats:latest")
if err != nil {
	util.TraceToLog()
	panic(err)
}
Output:

func (*ContainerBuilder) ImageRemove

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

ImageRemove

English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)

Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)

func (*ContainerBuilder) ImageRemoveByName

func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)

ImageRemoveByName

English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)

name: full image name

Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)

name: nome completo da imagem

func (*ContainerBuilder) Init

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

Init

English: Initializes the object and should be called only after all settings have been configured

Português: Inicializa o objeto e deve ser chamado apenas depois de toas as configurações serem definidas

func (*ContainerBuilder) MakeDefaultDockerfileForMe

func (e *ContainerBuilder) MakeDefaultDockerfileForMe()

MakeDefaultDockerfileForMe

English: Automatically mount the Dockerfile-iotmaker inside the target folder.

If there are ports exposed in the configurations, they will be defined automatically and the same goes for volumes, where files shared between the host and the container will expose the folder containing the file inside the container as volume.

Caution: the Dockerfile-iotmaker may be overwritten.

Rules: For Golang projects, the go.mod file is mandatory;
The main.go file containing the main package must be at the root folder.

Note: If you need a dockerfile made for another programming language, see the DockerfileAuto interface and the
SetDockerfileBuilder() function

Português: Monta o arquivo Dockerfile-iotmaker dentro da pasta alvo de forma automática.

Caso haja portas expostas nas configurações, as mesmas serão definidas automaticamente e o mesmo vale para volumes, onde arquivos compartilhados entre o host e o container exporá a pasta contendo o arquivo dentro do container como um volume.

Cuidado: o arquivo Dockerfile-iotmaker pode ser sobrescrito.

Regras: Para projetos Golang, o arquivo go.mod é obrigatório;
O arquivo main.go contendo o package main deve está na raiz do diretório.

Nota: Caso necessite de um dockerfile feito para outra linguagem de programação, veja a interface
DockerfileAuto e a função SetDockerfileBuilder()

func (*ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras added in v0.5.40

func (e *ContainerBuilder) MakeDefaultDockerfileForMeWithInstallExtras()

func (*ContainerBuilder) NetworkChangeIp added in v0.9.11

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

NetworkChangeIp

English: Change the IP address of the container, to the next IP in the docker network manager list

Output:
  err: Default object error from golang

Português: Troca o endereço IP do container, para o próximo IP da lista do gerenciador de rede docker

Saída:
  err: Objeto padrão de erro golang
Example
var err error
var imageInspect types.ImageInspect

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()

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

// create a network named delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
	panic(err)
}

var container = ContainerBuilder{}

container.SetNetworkDocker(netDocker)

// English: print the standard output of the container
// Português: imprime a saída padrão do container
container.SetPrintBuildOnStrOut()

// English: If there is an image named `cache:latest`, it will be used as a base to create the container.
// Português: Caso exista uma imagem de nome `cache:latest`, ela será usada como base para criar o container.
container.SetCacheEnable(true)

// English: Mount a default dockerfile for golang where the `main.go` file and the `go.mod` file should be in the root folder
// Português: Monta um dockerfile padrão para o golang onde o arquivo `main.go` e o arquivo `go.mod` devem está na pasta raiz
container.MakeDefaultDockerfileForMe()

// English: Name of the new image to be created.
// Português: Nome da nova imagem a ser criada.
container.SetImageName("delete:latest")

// English: Defines the path where the golang code to be transformed into a docker image is located.
// Português: Define o caminho onde está o código golang a ser transformado em imagem docker.
container.SetBuildFolderPath("./test/doNothing")

// English: Defines the name of the docker container to be created.
// Português: Define o nome do container docker a ser criado.
container.SetContainerName("container_counter_delete_after_test")

// English: Defines the maximum amount of memory to be used by the docker container.
// Português: Define a quantidade máxima de memória a ser usada pelo container docker.
container.SetImageBuildOptionsMemory(100 * KMegaByte)

// English: Wait for a textual event on the container's standard output before continuing
// Português: Espera por um evento textual na saída padrão do container antes de continuar
container.SetWaitStringWithTimeout("done!", 15*time.Second)

// English: Initializes the container manager object.
// Português: Inicializa o objeto gerenciador de container.
err = container.Init()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

// English: Creates an image from a project folder.
// Português: Cria uma imagem a partir de uma pasta de projeto.
imageInspect, err = container.ImageBuildFromFolder()
if err != nil {
	fmt.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

// English: Creates and initializes the container based on the created image.
// Português: Cria e inicializa o container baseado na imagem criada.
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	log.Printf("error: %v", err.Error())
	GarbageCollector()
	return
}

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

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

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

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

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

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

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

// English: Deletes all docker elements with the term `delete` in the name.
// Português: Apaga todos os elementos docker com o termo `delete` no nome.
GarbageCollector()
Output:

image size: 1.31 MB
image os: linux
IP: 10.0.0.2
IP: 10.0.0.3

func (*ContainerBuilder) RemoveAllByNameContains

func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)

RemoveAllByNameContains

English: searches for networks, volumes, containers and images that contain the term defined in "value" in the name, and tries to remove them from docker

Português: procura por redes, volumes, container e imagens que contenham o termo definido em "value" no nome, e tenta remover os mesmos do docker

func (*ContainerBuilder) SetBuildFolderPath

func (e *ContainerBuilder) SetBuildFolderPath(value string)

SetBuildFolderPath

English: Defines the path of the folder to be transformed into an image

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

value: caminho da pasta a ser transformada em imagem

  Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles,
  será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta
  raiz.
  Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile"
  Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz,
  com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo
  Dockerfile padrão

func (*ContainerBuilder) SetCacheEnable added in v0.5.40

func (e *ContainerBuilder) SetCacheEnable(value bool)

SetCacheEnable (english): When true, looks for an image named `chache:latest` as a basis for creating new images when the MakeDefaultDockerfileForMe function is used.

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

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

Example:

Folder: cache
File: Dockerfile-iotmaker
Need: Image with nats.io drive installed
Content:

FROM golang:1.16-alpine as builder
RUN mkdir -p /root/.ssh/ && \
    apk update && \
    apk add --no-cache build-base && \
    apk add --no-cache alpine-sdk && \
    rm -rf /var/cache/apk/*
ARG CGO_ENABLED=0

RUN go get -u github.com/nats-io/nats.go

Code Golang:

var imageCacheName = "cache:latest"
var imageId string
var container = &dockerBuilder.ContainerBuilder{}

imageId, err = container.ImageFindIdByName(imageCacheName)
if err != nil && err.Error() != "image name not found" {
  return
}

if imageId != "" {
  return
}

container.SetImageName(imageCacheName)
container.SetPrintBuildOnStrOut()
container.SetContainerName(imageCacheName)
container.SetBuildFolderPath("./cache")
err = container.Init()
if err != nil {
  return
}

err = container.ImageBuildFromFolder()
if err != nil {
  return
}

SetCacheEnable (português): Quando true, procura por uma imagem de nome `chache:latest` como base para a criação de novas imagens quando a função MakeDefaultDockerfileForMe é usada.

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

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

Exemplo:

Pasta: cache
Arquivo: Dockerfile-iotmaker
Necessidade: Imagem com o drive do nats.io instalada
Conteúdo:

FROM golang:1.16-alpine as builder
RUN mkdir -p /root/.ssh/ && \
    apk update && \
    apk add --no-cache build-base && \
    apk add --no-cache alpine-sdk && \
    rm -rf /var/cache/apk/*
ARG CGO_ENABLED=0

RUN go get -u github.com/nats-io/nats.go

Código Golang:

var imageCacheName = "cache:latest"
var imageId string
var container = &dockerBuilder.ContainerBuilder{}

imageId, err = container.ImageFindIdByName(imageCacheName)
if err != nil && err.Error() != "image name not found" {
  return
}

if imageId != "" {
  return
}

container.SetImageName(imageCacheName)
container.SetPrintBuildOnStrOut()
container.SetContainerName(imageCacheName)
container.SetBuildFolderPath("./cache")
err = container.Init()
if err != nil {
  return
}

err = container.ImageBuildFromFolder()
if err != nil {
  return
}

func (*ContainerBuilder) SetContainerAttachStandardStreamsToTty

func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)

SetContainerAttachStandardStreamsToTty

English: attach standard streams to tty

Português: anexa a saída padrão do tty

func (*ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer

func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)

SetContainerCommandToRunWhenStartingTheContainer

English: command to run when stating the container (style Dockerfile CMD)

Português: comando a ser executado quando o container inicia (estilo Dockerfile CMD)

func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer

func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)

SetContainerEntrypointToRunWhenStartingTheContainer

English: entrypoint to run when stating the container

Português: entrypoint a ser executado quando o container inicia

func (*ContainerBuilder) SetContainerHealthcheck

func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)

SetContainerHealthcheck

English: holds configuration settings for the HEALTHCHECK feature.

 Test:       Test is the test to perform to check that the container is healthy.
             An empty slice means to inherit the default.
             The options are:
             {}: inherit healthcheck
             {"NONE"}: disable healthcheck
             {"CMD", args...}: exec arguments directly
             {"CMD-SHELL", command}: run command with system's default shell
Interval:    Interval is the time to wait between checks (Zero means inherit).
Timeout:     Timeout is the time to wait before considering the check to have hung (Zero means inherit).
StartPeriod: The start period for the container to initialize before the retries starts to count down
             (Zero means inherit).
Retries:     Retries is the number of consecutive failures needed to consider a container as unhealthy
             (Zero means inherit).

Português: define definições de configuração para o recurso HEALTHCHECK.

 Test:       Test é o teste a ser executado para testar a saúde do container
             se não for definido, herda o teste padrão
             As opções são:
             {}: herda o teste padrão
             {"NONE"}: desabilita o healthcheck
             {"CMD", args...}: executa os argumentos diretamente
             {"CMD-SHELL", command} : executa o comando com shell padrão do sistema
Interval:    intervalo entre testes (zero herda o valor padrão).
Timeout:     intervalo de espera antes de considerar o teste com problemas (zero herda o valor padrão).
StartPeriod: tempo de espera pela incialização do container antes dos testes começarem
             (zero herda o valor padrão).
Retries:     número de testes consecutivos antes de considerar o teste com problemas
             (zero herda o valor padrão).

func (*ContainerBuilder) SetContainerName

func (e *ContainerBuilder) SetContainerName(value string)

SetContainerName

English: Defines the name of the container

value: container name

Português: Define o nome do container

value: nome do container

func (*ContainerBuilder) SetContainerRestartPolicyAlways

func (e *ContainerBuilder) SetContainerRestartPolicyAlways()

SetContainerRestartPolicyAlways

English: Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted.

Português: Define a política de reinício do container como sempre reinicia o container quando ele para, mesmo quando ele é parado manualmente.

func (*ContainerBuilder) SetContainerRestartPolicyNo

func (e *ContainerBuilder) SetContainerRestartPolicyNo()

SetContainerRestartPolicyNo

English: Do not automatically restart the container. (the default)

Português: Define a política de reinício do container como não reiniciar o container (padrão).

func (*ContainerBuilder) SetContainerRestartPolicyOnFailure

func (e *ContainerBuilder) SetContainerRestartPolicyOnFailure()

SetContainerRestartPolicyOnFailure

English: Restart the container if it exits due to an error, which manifests as a non-zero exit code

Português: Define a política de reinício do container como reinicia o container se houver um erro (com o manifesto informando um código de erro diferente de zero).

func (*ContainerBuilder) SetContainerRestartPolicyUnlessStopped

func (e *ContainerBuilder) SetContainerRestartPolicyUnlessStopped()

SetContainerRestartPolicyUnlessStopped

English: Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

Português: Define a política de reinício do container como sempre reinicia o container, caso ele não tenha sido parado manualmente.

func (*ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint

func (e *ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint(values []string)

SetContainerShellForShellFormOfRunCmdEntrypoint

English: shell for shell-form of run cmd entrypoint

Português: define o terminal (shell) para executar o entrypoint

func (*ContainerBuilder) SetCsvFileReader added in v0.9.16

func (e *ContainerBuilder) SetCsvFileReader(value bool)

func (*ContainerBuilder) SetCsvFileRowSeparator added in v0.9.16

func (e *ContainerBuilder) SetCsvFileRowSeparator(value string)

func (*ContainerBuilder) SetCsvFileRowsToPrint added in v0.9.16

func (e *ContainerBuilder) SetCsvFileRowsToPrint(value int64)
Example
var err error

GarbageCollector()

var container = ContainerBuilder{}
// imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// caso exista uma imagem de nome cache:latest, ela será usada como base para criar o container
container.SetCacheEnable(true)
// monta um dockerfile padrão para o golang onde o arquivo main.go e o arquivo go.mod devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// new image name delete:latest
container.SetImageName("delete:latest")
// set a folder path to make a new image
container.SetBuildFolderPath("./test/counter")
// container name container_delete_server_after_test
container.SetContainerName("container_counter_delete_after_test")
// define o limite de memória
container.SetImageBuildOptionsMemory(100 * KMegaByte)

container.SetLogPath("./test.counter.log.36.csv")
container.AddFilterToLog(
	"contador",
	"counter",
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
)
container.AddFilterToSuccess(
	"done!",
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
	"${value}",
)
container.AddFilterToFail(
	"counter: 40",
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
	"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)

container.SetCsvFileRowsToPrint(KAll)

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

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

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

container.StartMonitor(time.NewTicker(2 * time.Second))

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

GarbageCollector()
Output:

func (*ContainerBuilder) SetCsvFileValueSeparator added in v0.9.16

func (e *ContainerBuilder) SetCsvFileValueSeparator(value string)

func (*ContainerBuilder) SetDockerfileBuilder added in v0.5.11

func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)

SetDockerfileBuilder

English: Defines a new object containing the builder of the dockerfile.

Note: see the DockerfileAuto interface for further instructions.

Português: Define um novo objeto contendo o construtor do arquivo dockerfile.

Nota: veja a interface DockerfileAuto para mais instruções.

func (*ContainerBuilder) SetEnvironmentVar

func (e *ContainerBuilder) SetEnvironmentVar(value []string)

SetEnvironmentVar

English: Defines environment variables

value: slice of string containing one environment variable per key

Português: Define as variáveis de ambiente

value: slice de string contendo um variável de ambiente por chave
Example
var err error

GarbageCollector()

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

// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
	panic(err)
}

// At this point in the code, the network has been created and is ready for use

var mongoDocker = &ContainerBuilder{}
// set a docker network
//mongoDocker.SetNetworkDocker(&netDocker)
// set an image name
mongoDocker.SetImageName("mongo:latest")
// set a container name
mongoDocker.SetContainerName("container_delete_mongo_after_test")
// set a port to expose
mongoDocker.AddPortToExpose("27017")
// se a environment var list
mongoDocker.SetEnvironmentVar(
	[]string{
		"--host 0.0.0.0",
	},
)
// set a MongoDB data dir to ./test/data
//err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
if err != nil {
	panic(err)
}
// set a text indicating for container ready for use
mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)

// inicialize the object before sets
err = mongoDocker.Init()
if err != nil {
	panic(err)
}

// build a container
err = mongoDocker.ContainerBuildAndStartFromImage()
if err != nil {
	panic(err)
}

// Output:
//

// At this point, the MongoDB is ready for use on port 27017

// Stop and delete the container
// GarbageCollector()
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.

url: Address of the repository containing the project

  Note:

  If the repository is private and the host computer has access to the git server, use
  SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
  ~/.gitconfig automatically;

  To be able to access private repositories from inside the container, build the image in two or more steps
  and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
  file to the /root folder;

  The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;

  If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;

  If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
  SetSshIdRsaFile() to define the files manually;

  This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
  generate an image from the contents of a git repository;

  The repository must contain a Dockerfile file and it will be searched for in the following order:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  and '.*dockerfile.*';

  The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.

url: Endereço do repositório contendo o projeto

  Nota:

  Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
  SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
  ~/.gitconfig de forma automática;

  Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
  e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
  para a pasta /root/;

  A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;

  Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
  da mesma;

  Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
  SetSshIdRsaFile() para definir os arquivos de forma manual;

  Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
  imagem a partir do conteúdo de um repositório git;

  O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  e '.*dockerfile.*';

  O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
Example
var err error

GarbageCollector()

var container = ContainerBuilder{}
// new image name delete:latest
container.SetImageName("delete:latest")
// container name container_delete_server_after_test
container.SetContainerName("container_delete_server_after_test")
// git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git
container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git")
// set a waits for the text to appear in the standard container output to proceed [optional]
container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second)
// change and open port 3000 to 3030
container.AddPortToChange("3000", "3030")
// replace container folder /static to host folder ./test/static
err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static")
if err != nil {
	panic(err)
}

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

// builder new image from git project
_, err = container.ImageBuildFromServer()
if err != nil {
	panic(err)
}

// build a new container from image
err = container.ContainerBuildAndStartFromImage()
if err != nil {
	panic(err)
}

// At this point, the container is ready for use on port 3030

// Stop and delete the container
GarbageCollector()
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.

url: Address of the repository containing the project
privateSSHKeyPath: this is the path of the private ssh key compatible with the public key registered in git
password: password used when the ssh key was generated or empty string

  Note:

  If the repository is private and the host computer has access to the git server, use
  SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
  ~/.gitconfig automatically;

  To be able to access private repositories from inside the container, build the image in two or more steps
  and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
  file to the /root folder;

  The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;

  If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;

  If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
  SetSshIdRsaFile() to define the files manually;

  This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
  generate an image from the contents of a git repository;

  The repository must contain a Dockerfile file and it will be searched for in the following order:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  and '.*dockerfile.*';

  The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var privateSSHKeyPath string
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa")
    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password)
    container.SetGitConfigFile(string(file))

Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.

url: Endereço do repositório contendo o projeto
privateSSHKeyPath: este é o caminho da chave ssh privada compatível com a chave pública cadastrada no git
password: senha usada no momento que a chave ssh foi gerada ou string em branco

  Nota:

  Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
  SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
  ~/.gitconfig de forma automática;

  Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
  e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
  para a pasta /root/;

  A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;

  Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
  da mesma;

  Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
  SetSshIdRsaFile() para definir os arquivos de forma manual;

  Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
  imagem a partir do conteúdo de um repositório git;

  O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  e '.*dockerfile.*';

  O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var privateSSHKeyPath string
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa")
    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password)
    container.SetGitConfigFile(string(file))

func (*ContainerBuilder) SetGitCloneToBuildWithPrivateToken

func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)

SetGitCloneToBuildWithPrivateToken

English: Defines the path of a repository to be used as the base of the image to be mounted.

url: Address of the repository containing the project
privateToken: token defined on your git tool portal

  Note:

  If the repository is private and the host computer has access to the git server, use
  SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
  ~/.gitconfig automatically;

  To be able to access private repositories from inside the container, build the image in two or more steps
  and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
  file to the /root folder;

  The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;

  If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;

  If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
  SetSshIdRsaFile() to define the files manually;

  This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
  generate an image from the contents of a git repository;

  The repository must contain a Dockerfile file and it will be searched for in the following order:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  and '.*dockerfile.*';

  The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
    container.SetGitConfigFile(string(file))

Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.

url: Endereço do repositório contendo o projeto
privateToken: token definido no portal da sua ferramenta git

  Nota:

  Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
  SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
  ~/.gitconfig de forma automática;

  Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
  e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
  para a pasta /root/;

  A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;

  Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
  da mesma;

  Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
  SetSshIdRsaFile() para definir os arquivos de forma manual;

  Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
  imagem a partir do conteúdo de um repositório git;

  O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  e '.*dockerfile.*';

  O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
    container.SetGitConfigFile(string(file))

func (*ContainerBuilder) SetGitCloneToBuildWithUserPassworh

func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)

SetGitCloneToBuildWithUserPassworh

English: Defines the path of a repository to be used as the base of the image to be mounted.

url: Address of the repository containing the project
user: git user
password: git password

  Note:

  If the repository is private and the host computer has access to the git server, use
  SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
  ~/.gitconfig automatically;

  To be able to access private repositories from inside the container, build the image in two or more steps
  and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
  file to the /root folder;

  The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;

  If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;

  If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
  SetSshIdRsaFile() to define the files manually;

  This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
  generate an image from the contents of a git repository;

  The repository must contain a Dockerfile file and it will be searched for in the following order:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  and '.*dockerfile.*';

  The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
    container.SetGitConfigFile(string(file))

Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.

url: Endereço do repositório contendo o projeto
user: git user
password: git password

  Nota:

  Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
  SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
  ~/.gitconfig de forma automática;

  Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
  e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
  para a pasta /root/;

  A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;

  Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
  da mesma;

  Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
  SetSshIdRsaFile() para definir os arquivos de forma manual;

  Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
  imagem a partir do conteúdo de um repositório git;

  O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
  './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
  e '.*dockerfile.*';

  O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
  SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

  code:
    var err error
    var usr *user.User
    var userGitConfigPath string
    var file []byte
    usr, err = user.Current()
    if err != nil {
      panic(err)
    }

    userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig")
    file, err = ioutil.ReadFile(userGitConfigPath)

    var container = ContainerBuilder{}
    container.SetGitCloneToBuildWithPrivateToken(url, privateToken)
    container.SetGitConfigFile(string(file))

func (*ContainerBuilder) SetGitConfigFile

func (e *ContainerBuilder) SetGitConfigFile(value string)

SetGitConfigFile

English: Defines the contents of the .gitconfig file

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetGitConfigFile(string(file))

Português: Define o conteúdo do arquivo .gitconfig

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".gitconfig")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetGitConfigFile(string(file))

func (*ContainerBuilder) SetGitPathPrivateRepository

func (e *ContainerBuilder) SetGitPathPrivateRepository(value string)

SetGitPathPrivateRepository

English: path do private repository defined in "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"

Example: github.com/helmutkemper

Português: caminho do repositório privado definido em "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"

Exemplo: github.com/helmutkemper

func (*ContainerBuilder) SetGitSshPassword

func (e *ContainerBuilder) SetGitSshPassword(password string)

SetGitSshPassword

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

Note:

If the repository is private and the host computer has access to the git server, use
SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of
~/.gitconfig automatically;

To be able to access private repositories from inside the container, build the image in two or more steps
and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig
file to the /root folder;

The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;

If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;

If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and
SetSshIdRsaFile() to define the files manually;

This function must be used with the ImageBuildFromServer() and SetImageName() function to download and
generate an image from the contents of a git repository;

The repository must contain a Dockerfile file and it will be searched for in the following order:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
and '.*dockerfile.*';

The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

Português: Define a senha da chave ssh para repositórios git privados.

Nota:

Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use
SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de
~/.gitconfig de forma automática;

Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas
e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig
para a pasta /root/;

A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;

Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha
da mesma;

Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual;

Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma
imagem a partir do conteúdo de um repositório git;

O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem:
'./Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*'
e '.*dockerfile.*';

O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(),
SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

func (*ContainerBuilder) SetImageBuildOptionsCPUPeriod

func (e *ContainerBuilder) SetImageBuildOptionsCPUPeriod(value int64)

SetImageBuildOptionsCPUPeriod

English: Specify the CPU CFS scheduler period, which is used alongside --cpu-quota. Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the default. For most use-cases, --cpus is a more convenient alternative.

Português: Especifique o período do agendador CFS da CPU, que é usado junto com --cpu-quota. O padrão é 100.000 microssegundos (100 milissegundos). A maioria dos usuários não altera o padrão. Para a maioria dos casos de uso, --cpus é uma alternativa mais conveniente.

func (*ContainerBuilder) SetImageBuildOptionsCPUQuota

func (e *ContainerBuilder) SetImageBuildOptionsCPUQuota(value int64)

SetImageBuildOptionsCPUQuota

English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles.

This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.

Português: Defina este flag para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina hospedeira.

Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os containeres usam a quantidade de CPU de que precisam. Dessa forma, é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.

func (*ContainerBuilder) SetImageBuildOptionsCPUSetCPUs

func (e *ContainerBuilder) SetImageBuildOptionsCPUSetCPUs(value string)

SetImageBuildOptionsCPUSetCPUs

English: Limit the specific CPUs or cores a container can use.

A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU.

The first CPU is numbered 0.

A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).

Português: Limite a quantidade de CPUs ou núcleos específicos que um container pode usar.

Uma lista separada por vírgulas ou intervalo separado por hífen de CPUs que um container pode usar, se você tiver mais de uma CPU.

A primeira CPU é numerada como 0.

Um valor válido pode ser 0-3 (para usar a primeira, segunda, terceira e quarta CPU) ou 1,3 (para usar a segunda e a quarta CPU).

func (*ContainerBuilder) SetImageBuildOptionsCPUSetMems

func (e *ContainerBuilder) SetImageBuildOptionsCPUSetMems(value string)

SetImageBuildOptionsCPUSetMems

English: Define a memory nodes (MEMs) (--cpuset-mems)

--cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.

If you have four memory nodes on your system (0-3), use --cpuset-mems=0,1 then processes in your Docker container will only use memory from the first two memory nodes.

Português: Define memory node (MEMs) (--cpuset-mems)

--cpuset-mems="" Memory nodes (MEMs) no qual permitir a execução (0-3, 0,1). Só funciona em sistemas NUMA.

Se você tiver quatro nodes de memória em seu sistema (0-3), use --cpuset-mems=0,1 então, os processos em seu container do Docker usarão apenas a memória dos dois primeiros nodes.

func (*ContainerBuilder) SetImageBuildOptionsCPUShares

func (e *ContainerBuilder) SetImageBuildOptionsCPUShares(value int64)

SetImageBuildOptionsCPUShares

English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles. This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.

Português: Defina este sinalizador para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina host. Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os container usam a quantidade de CPU de que precisam. Dessa forma, este é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.

func (*ContainerBuilder) SetImageBuildOptionsCacheFrom

func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)

SetImageBuildOptionsCacheFrom

English: specifies images that are used for matching cache. Images specified here do not need to have a valid parent chain to match cache.

Português: especifica imagens que são usadas para correspondência de cache. As imagens especificadas aqui não precisam ter uma cadeia pai válida para corresponder a cache.

func (*ContainerBuilder) SetImageBuildOptionsExtraHosts

func (e *ContainerBuilder) SetImageBuildOptionsExtraHosts(values []string)

SetImageBuildOptionsExtraHosts

English: Add hostname mappings at build-time. Use the same values as the docker client --add-host parameter.

values:
  somehost:162.242.195.82
  otherhost:50.31.209.229

An entry with the ip address and hostname is created in /etc/hosts inside containers for this build, e.g:

  162.242.195.82 somehost
  50.31.209.229 otherhost

Português): Adiciona itens ao mapa de hostname durante o processo de construção da imagem. Use os mesmos valores que em docker client --add-host parameter.

values:
  somehost:162.242.195.82
  otherhost:50.31.209.229

Uma nova entrada com o endereço ip e hostname será criada dentro de /etc/hosts do container. Exemplo:

  162.242.195.82 somehost
  50.31.209.229 otherhost

func (*ContainerBuilder) SetImageBuildOptionsIsolationDefault

func (e *ContainerBuilder) SetImageBuildOptionsIsolationDefault()

SetImageBuildOptionsIsolationDefault

English: Set default isolation mode on current daemon

Português: Define o método de isolamento do processo como sendo o mesmo do deamon

func (*ContainerBuilder) SetImageBuildOptionsIsolationHyperV

func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()

SetImageBuildOptionsIsolationHyperV

English: Set HyperV isolation mode

Português: Define o método de isolamento como sendo HyperV

func (*ContainerBuilder) SetImageBuildOptionsIsolationProcess

func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()

SetImageBuildOptionsIsolationProcess

English: Set process isolation mode

Português: Determina o método de isolamento do processo

func (*ContainerBuilder) SetImageBuildOptionsMemory

func (e *ContainerBuilder) SetImageBuildOptionsMemory(value int64)

SetImageBuildOptionsMemory

English: The maximum amount of memory the container can use. If you set this option, the minimum allowed value is 4 * 1024 * 1024 (4 megabyte).

Use value * KKiloByte, value * KMegaByte and value * KGigaByte
See https://docs.docker.com/engine/reference/run/#user-memory-constraints

Português: Memória máxima total que o container pode usar. Se você vai usar esta opção, o máximo permitido é 4 * 1024 * 1024 (4 megabyte)

Use value * KKiloByte, value * KMegaByte e value * KGigaByte
See https://docs.docker.com/engine/reference/run/#user-memory-constraints

func (*ContainerBuilder) SetImageBuildOptionsMemorySwap

func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)

SetImageBuildOptionsMemorySwap

English: Set memory swap (--memory-swap)

Use value * KKiloByte, value * KMegaByte and value * KGigaByte
See https://docs.docker.com/engine/reference/run/#user-memory-constraints

Português: habilita a opção memory swp

Use value * KKiloByte, value * KMegaByte e value * KGigaByte
See https://docs.docker.com/engine/reference/run/#user-memory-constraints

func (*ContainerBuilder) SetImageBuildOptionsNoCache

func (e *ContainerBuilder) SetImageBuildOptionsNoCache()

SetImageBuildOptionsNoCache

English: Set image build no cache

Português: Define a opção `sem cache` para a construção da imagem

func (*ContainerBuilder) SetImageBuildOptionsPlatform

func (e *ContainerBuilder) SetImageBuildOptionsPlatform(value string)

SetImageBuildOptionsPlatform

English: Target platform containers for this service will run on, using the os[/arch[/variant]] syntax, e.g.

osx
windows/amd64
linux/arm64/v8

Português: Especifica a plataforma de container onde o serviço vai rodar, usando a sintaxe os[/arch[/variant]]

osx
windows/amd64
linux/arm64/v8

func (*ContainerBuilder) SetImageBuildOptionsSecurityOpt

func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)

SetImageBuildOptionsSecurityOpt

English: Set the container security options

label=user:USER        — Set the label user for the container
label=role:ROLE        — Set the label role for the container
label=type:TYPE        — Set the label type for the container
label=level:LEVEL      — Set the label level for the container
label=disable          — Turn off label confinement for the container
apparmor=PROFILE       — Set the apparmor profile to be applied to the container
no-new-privileges:true — Disable container processes from gaining new privileges
seccomp=unconfined     — Turn off seccomp confinement for the container
seccomp=profile.json   — White-listed syscalls seccomp Json file to be used as a seccomp filter

Português: Modifica as opções de segurança do container

label=user:USER        — Determina o rótulo user para o container
label=role:ROLE        — Determina o rótulo role para o container
label=type:TYPE        — Determina o rótulo type para o container
label=level:LEVEL      — Determina o rótulo level para o container
label=disable          — Desliga o confinamento do rótulo para o container
apparmor=PROFILE       — Habilita o perfil definido pelo apparmor do linux para ser definido ao container
no-new-privileges:true — Impede o processo do container a ganhar novos privilégios
seccomp=unconfined     — Desliga o confinamento causado pelo seccomp do linux ao container
seccomp=profile.json   — White-listed syscalls seccomp Json file to be used as a seccomp filter

func (*ContainerBuilder) SetImageBuildOptionsSquash

func (e *ContainerBuilder) SetImageBuildOptionsSquash(value bool)

SetImageBuildOptionsSquash

English: squash the resulting image's layers to the parent preserves the original image and creates a new one from the parent with all the changes applied to a single layer

Português: Usa o conteúdo dos layers da imagem pai para criar uma imagem nova, preservando a imagem pai, e aplica todas as mudanças a um novo layer

func (*ContainerBuilder) SetImageBuildOptionsTarget

func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)

SetImageBuildOptionsTarget

English: Build the specified stage as defined inside the Dockerfile. See the multi-stage build docs for details.

See https://docs.docker.com/develop/develop-images/multistage-build/

Português: Monta o container a partir do estágio definido no arquivo Dockerfile. Veja a documentação de múltiplos estágios para mais detalhes.

See https://docs.docker.com/develop/develop-images/multistage-build/

func (*ContainerBuilder) SetImageCacheName added in v0.5.40

func (e *ContainerBuilder) SetImageCacheName(name string)

func (*ContainerBuilder) SetImageExpirationTime added in v0.9.12

func (e *ContainerBuilder) SetImageExpirationTime(expiration time.Duration)

func (*ContainerBuilder) SetImageName

func (e *ContainerBuilder) SetImageName(value string)

SetImageName

English: Defines the name of the image to be used or created

value: name of the image to be downloaded or created

  Note: the image name must have the version tag

Português: Define o nome da imagem a ser usada ou criada

value: noma da imagem a ser baixada ou criada

  Nota: o nome da imagem deve ter a tag de versão

func (*ContainerBuilder) SetInspectInterval

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

SetInspectInterval

English: Defines the container's monitoring interval [optional]

value: time interval between container inspection events

  Note: This function has a high computational cost and should be used sparingly.
  The captured values are presented by GetLastInspect() and GetChannelOnContainerInspect()

Português: Define o intervalo de monitoramento do container [opcional]

value: intervalo de tempo entre os eventos de inspeção do container

  Nota: Esta função tem um custo computacional elevado e deve ser usada com moderação.
  Os valores capturados são apresentados por GetLastInspect() e GetChannelOnContainerInspect()

func (*ContainerBuilder) SetLogPath added in v0.9.11

func (e *ContainerBuilder) SetLogPath(path string)
Example
var err error
var imageInspect types.ImageInspect

GarbageCollector()

var container = ContainerBuilder{}
// imprime a saída padrão do container
container.SetPrintBuildOnStrOut()
// caso exista uma imagem de nome cache:latest, ela será usada como base para criar o container
container.SetCacheEnable(true)
// monta um dockerfile padrão para o golang onde o arquivo main.go e o arquivo go.mod devem está na pasta raiz
container.MakeDefaultDockerfileForMe()
// new image name delete:latest
container.SetImageName("delete:latest")
// set a folder path to make a new image
container.SetBuildFolderPath("./test/counter")
// container name container_delete_server_after_test
container.SetContainerName("container_counter_delete_after_test")
// define o limite de memória
container.SetImageBuildOptionsMemory(100 * KMegaByte)

container.SetLogPath("./test.counter.log.csv")
container.AddFilterAndReplaceToLog(
	"contador",
	"counter",
	"^.*?counter: (?P<valueToGet>[\\d\\.]+)",
	"\\.",
	",",
)
container.AddFilterToSuccess(
	"done!",
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ done!).*",
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+(?P<value>done!).*",
	"${value}",
)
container.AddFilterToFail(
	"counter: 40",
	"^.*?(?P<valueToGet>\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ counter: [\\d\\.]+).*",
	"(?P<date>\\d+/\\d+/\\d+)\\s+(?P<hour>\\d+:\\d+:\\d+)\\s+counter:\\s+(?P<value>[\\d\\.]+).*",
	"Test Fail! Counter Value: ${value} - Hour: ${hour} - Date: ${date}",
)

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

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

fmt.Printf("image size: %v\n", container.SizeToString(imageInspect.Size))
fmt.Printf("image os: %v\n", imageInspect.Os)

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

container.StartMonitor(time.NewTicker(2 * time.Second))

event := container.GetChaosEvent()

select {
case e := <-*event:
	fmt.Printf("container name: %v\n", e.ContainerName)
	fmt.Printf("done: %v\n", e.Done)
	fmt.Printf("fail: %v\n", e.Fail)
	fmt.Printf("error: %v\n", e.Error)
	fmt.Printf("message: %v\n", e.Message)
}

container.StopMonitor()

GarbageCollector()
Output:

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

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

network: pointer to the network manager object.

  Note: compatible with dockerBuilderNetwork.ContainerBuilderNetwork{} object

Português: Define o ponteiro do gerenciador de rede docker

network: ponteiro para o objeto gerenciador de rede.

  Nota: compatível com o objeto dockerBuilderNetwork.ContainerBuilderNetwork{}
Example
var err error

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

// create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1
err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1")
if err != nil {
	panic(err)
}

// At this point in the code, the network has been created and is ready for use

var mongoDocker = &ContainerBuilder{}
// set a docker network
mongoDocker.SetNetworkDocker(&netDocker)
// set an image name
mongoDocker.SetImageName("mongo:latest")
// set a container name
mongoDocker.SetContainerName("container_delete_mongo_after_test")
// set a port to expose
mongoDocker.AddPortToExpose("27017")
// se a environment var list
mongoDocker.SetEnvironmentVar(
	[]string{
		"--host 0.0.0.0",
	},
)
// set a MongoDB data dir to ./test/data
err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data")
if err != nil {
	panic(err)
}
// set a text indicating for container ready for use
mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)

// inicialize the object before sets
err = mongoDocker.Init()
if err != nil {
	panic(err)
}

// build a container
err = mongoDocker.ContainerBuildAndStartFromImage()
if err != nil {
	panic(err)
}

// At this point, the MongoDB is ready for use on port 27017

// Stop and delete the container
GarbageCollector()
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.

The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.

Any build instruction can be registered as a trigger.

This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration.

For example, if your image is a reusable Python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called after that. You can’t just call ADD and RUN now, because you don’t yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate Dockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code.

The solution is to use ONBUILD to register advance instructions to run later, during the next build stage.

Here’s how it works:

When it encounters an OnBuild instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. At the end of the build, a list of all triggers is stored in the image manifest, under the key OnBuild. They can be inspected with the docker inspect command. Later the image may be used as a base for a new build, using the FROM instruction. As part of processing the FROM instruction, the downstream builder looks for OnBuild triggers, and executes them in the same order they were registered. If any of the triggers fail, the FROM instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual. Triggers are cleared from the final image after being executed. In other words they are not inherited by “grand-children” builds.

For example you might add something like this:

[]string{
  "ADD . /app/src",
  "RUN /usr/local/bin/python-build --dir /app/src",
}

Warning:

The ONBUILD instruction may not trigger FROM or MAINTAINER instructions.

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

SetOnBuild (português): Adiciona à imagem uma instrução de gatilho a ser executada posteriormente, quando a imagem for usada como base para outra construção.

O gatilho será executado no contexto do downstream build , como se tivesse sido inserido imediatamente após a instrução FROM no downstream Dockerfile.

Qualquer instrução de construção pode ser registrada como um gatilho.

Isso é útil se você estiver construindo uma imagem que será usada como base para construir outras imagens, por exemplo, um ambiente de construção de aplicativo ou um daemon que pode ser personalizado com configuração específica do usuário.

Por exemplo, se sua imagem for um construtor de aplicativo Python reutilizável, ela exigirá que o código-fonte do aplicativo seja adicionado em um diretório específico e pode exigir que um script de construção seja chamado depois disso. Você não pode simplesmente chamar ADD e RUN agora, porque você ainda não tem acesso ao código-fonte do aplicativo e será diferente para cada construção de aplicativo. Você poderia simplesmente fornecer aos desenvolvedores de aplicativos um Dockerfile padrão para copiar e colar em seus aplicativos, mas isso é ineficiente, sujeito a erros e difícil de atualizar porque se mistura com o código específico do aplicativo.

A solução é usar o OnBuild para registrar instruções antecipadas para executar mais tarde, durante o próximo estágio de compilação.

Funciona assim:

Ao encontrar uma instrução OnBuild, o construtor adiciona um gatilho aos metadados da imagem que está sendo construída. A instrução não afeta de outra forma a construção atual. No final da construção, uma lista de todos os gatilhos é armazenada no manifesto da imagem, sob a chave OnBuild. Eles podem ser inspecionados com o comando docker inspect. Posteriormente, a imagem pode ser usada como base para uma nova construção, usando a instrução FROM. Como parte do processamento da instrução FROM, o downstream builder procura gatilhos OnBuild e os executa na mesma ordem em que foram registrados. Se qualquer um dos gatilhos falhar, a instrução FROM é abortada, o que, por sua vez, faz com que o build falhe. Se todos os gatilhos forem bem-sucedidos, a instrução FROM será concluída e a construção continuará normalmente. Os gatilhos são apagados da imagem final após serem executados. Em outras palavras, eles não são herdados por construções de "netos".

Por exemplo, você pode adicionar algo assim:

[]string{
  "ADD . /app/src",
  "RUN /usr/local/bin/python-build --dir /app/src",
}

Atenção:

A instrução ONBUILD não pode disparar as instruções FROM ou MAINTAINER.

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.

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

func (*ContainerBuilder) SetRestartProbability added in v0.9.11

func (e *ContainerBuilder) SetRestartProbability(restartProbability, restartChangeIpProbability float64, limit int)

func (*ContainerBuilder) SetSceneName added in v0.9.11

func (e *ContainerBuilder) SetSceneName(name string)

func (*ContainerBuilder) SetSshIdRsaFile

func (e *ContainerBuilder) SetSshIdRsaFile(value string)

SetSshIdRsaFile

English: Set a id_rsa file from shh

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetSshIdRsaFile(string(file))

Português: Define o arquivo id_rsa do shh

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetSshIdRsaFile(string(file))

func (*ContainerBuilder) SetSshKnownHostsFile

func (e *ContainerBuilder) SetSshKnownHostsFile(value string)

SetSshKnownHostsFile

English: set a sseh knownhosts file

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetSshKnownHostsFile(string(file))

Português: define o arquivo knownhosts do ssh

var err error
var usr *user.User
var path string
var file []byte
usr, err = user.Current()
if err != nil {
  panic(err)
}

path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts")
file, err = ioutil.ReadFile(path)
if err != nil {
  panic(err)
}

var container = ContainerBuilder{}
container.SetSshKnownHostsFile(string(file))

func (*ContainerBuilder) SetTimeBeforeRestart added in v0.9.11

func (e *ContainerBuilder) SetTimeBeforeRestart(min, max time.Duration)

func (*ContainerBuilder) SetTimeToPause added in v0.9.11

func (e *ContainerBuilder) SetTimeToPause(min, max time.Duration)

func (*ContainerBuilder) SetTimeToRestart added in v0.9.11

func (e *ContainerBuilder) SetTimeToRestart(min, max time.Duration)

func (*ContainerBuilder) SetTimeToStartChaos added in v0.9.11

func (e *ContainerBuilder) SetTimeToStartChaos(min, max time.Duration)

func (*ContainerBuilder) SetTimeToUnpause added in v0.9.11

func (e *ContainerBuilder) SetTimeToUnpause(min, max time.Duration)

func (*ContainerBuilder) SetWaitString

func (e *ContainerBuilder) SetWaitString(value string)

SetWaitString

English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use

value: searched text

Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso

value: texto procurado

func (*ContainerBuilder) SetWaitStringWithTimeout

func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)

SetWaitStringWithTimeout

English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use

value: text emitted to default output reporting by an expected event
timeout: maximum waiting time

Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso

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

func (*ContainerBuilder) SizeToString added in v0.9.11

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

func (*ContainerBuilder) StartMonitor added in v0.9.11

func (e *ContainerBuilder) StartMonitor(duration *time.Ticker)

func (*ContainerBuilder) StopMonitor added in v0.9.11

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

func (*ContainerBuilder) WaitForTextInContainerLog

func (e *ContainerBuilder) WaitForTextInContainerLog(value string) (dockerLogs string, err error)

WaitForTextInContainerLog

English: Wait for the text to appear in the container's default output

value: searched text

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

value: texto procurado

func (*ContainerBuilder) WaitForTextInContainerLogWithTimeout

func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)

WaitForTextInContainerLogWithTimeout

English: Wait for the text to appear in the container's default output

value: searched text
timeout: wait timeout

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

value: texto procurado
timeout: tempo limite de espera

type DockerfileAuto

type DockerfileAuto interface {
	MountDefaultDockerfile(args map[string]*string, changePorts []dockerfileGolang.ChangePort, openPorts []string, exposePorts []string, volumes []mount.Mount, installExtraPackages bool, useCache bool, imageCacheName string) (dockerfile string, err error)
	Prayer()
}

DockerfileAuto

English: Interface from automatic Dockerfile generator.

Note: To be able to access private repositories from inside the container, build the image in two or more
steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder and the .gitconfig
file to the /root folder.

One way to do this automatically is to use the Dockerfile example below, where the arguments SSH_ID_RSA_FILE
contains the file ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contains the file ~/.ssh/known_hosts and GITCONFIG_FILE
contains the file ~/.gitconfig.

If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password.

If you want to copy the files into the image automatically, use SetPrivateRepositoryAutoConfig() and the
function will copy the files ~/.ssh/id_rsa, ~/.ssh/known_hosts and ~/.gitconfig to the viable arguments
located above.

If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile()
to define the files manually.

The Dockerfile below can be used as a base

  # (en) first stage of the process
  # (pt) primeira etapa do processo
  FROM golang:1.16-alpine as builder

  # (en) enable the argument variables
  # (pt) habilita as variáveis de argumento
  ARG SSH_ID_RSA_FILE
  ARG KNOWN_HOSTS_FILE
  ARG GITCONFIG_FILE
  ARG GIT_PRIVATE_REPO

  # (en) creates the .ssh directory within the root directory
  # (pt) cria o diretório .ssh dentro do diretório root
  RUN mkdir -p /root/.ssh/ && \
      # (en) creates the id_esa file inside the .ssh directory
      # (pt) cria o arquivo id_esa dentro do diretório .ssh
      echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/ && \
      # (en) creates the known_hosts file inside the .ssh directory
      # (pt) cria o arquivo known_hosts dentro do diretório .ssh
      echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/known_hosts && \
      # (en) creates the .gitconfig file at the root of the root directory
      # (pt) cria o arquivo .gitconfig na raiz do diretório /root
      echo "$GITCONFIG_FILE" > /root/.gitconfig && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.gitconfig && \
      # (en) prepares the OS for installation
      # (pt) prepara o OS para instalação
      apk update && \
      # (en) install git and openssh
      # (pt) instala o git e o opnssh
      apk add --no-cache build-base git openssh && \
      # (en) clear the cache
      # (pt) limpa a cache
      rm -rf /var/cache/apk/*

  # (en) creates the /app directory, where your code will be installed
  # (pt) cria o diretório /app, onde seu código vai ser instalado
  WORKDIR /app
  # (en) copy your project into the /app folder
  # (pt) copia seu projeto para dentro da pasta /app
  COPY . .
  # (en) enables the golang compiler to run on an extremely simple OS, scratch
  # (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch
  ARG CGO_ENABLED=0
  # (en) adjust git to work with shh
  # (pt) ajusta o git para funcionar com shh
  RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/
  # (en) defines the path of the private repository
  # (pt) define o caminho do repositório privado
  RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
  # (en) install the dependencies in the go.mod file
  # (pt) instala as dependências no arquivo go.mod
  RUN go mod tidy
  # (en) compiles the main.go file
  # (pt) compila o arquivo main.go
  RUN go build -ldflags="-w -s" -o /app/main /app/main.go
  # (en) creates a new scratch-based image
  # (pt) cria uma nova imagem baseada no scratch
  # (en) scratch is an extremely simple OS capable of generating very small images
  # (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas
  # (en) discarding the previous image erases git access credentials for your security and reduces the size of the
  #      image to save server space
  # (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho
  #      da imagem para poupar espaço no servidor
  FROM scratch
  # (en) copy your project to the new image
  # (pt) copia o seu projeto para a nova imagem
  COPY --from=builder /app/main .
  # (en) execute your project
  # (pt) executa o seu projeto
  CMD ["/main"]

Português: Interface do gerador de dockerfile automático.

Nota: Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais
etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo
.gitconfig para a pasta /root/.

Uma maneira de fazer isto de forma automática é usar o exemplo de Dockerfile abaixo, onde os argumentos
SSH_ID_RSA_FILE contém o arquivo ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contém o arquivo ~/.ssh/known_hosts e
GITCONFIG_FILE contém o arquivo ~/.gitconfig.

Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da
mesma.

Caso você queira copiar os arquivos para dentro da imagem de forma automática, use
SetPrivateRepositoryAutoConfig() e a função copiará os arquivos ~/.ssh/id_rsa, ~/.ssh/known_hosts e
~/.gitconfig para as viáveis de argumentos sitada anteriormente.

Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e
SetSshIdRsaFile() para definir os arquivos de forma manual.

O arquivo Dockerfile abaixo pode ser usado como base

  # (en) first stage of the process
  # (pt) primeira etapa do processo
  FROM golang:1.16-alpine as builder

  # (en) enable the argument variables
  # (pt) habilita as variáveis de argumento
  ARG SSH_ID_RSA_FILE
  ARG KNOWN_HOSTS_FILE
  ARG GITCONFIG_FILE
  ARG GIT_PRIVATE_REPO

  # (en) creates the .ssh directory within the root directory
  # (pt) cria o diretório .ssh dentro do diretório root
  RUN mkdir -p /root/.ssh/ && \
      # (en) creates the id_esa file inside the .ssh directory
      # (pt) cria o arquivo id_esa dentro do diretório .ssh
      echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/ && \
      # (en) creates the known_hosts file inside the .ssh directory
      # (pt) cria o arquivo known_hosts dentro do diretório .ssh
      echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/known_hosts && \
      # (en) creates the .gitconfig file at the root of the root directory
      # (pt) cria o arquivo .gitconfig na raiz do diretório /root
      echo "$GITCONFIG_FILE" > /root/.gitconfig && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.gitconfig && \
      # (en) prepares the OS for installation
      # (pt) prepara o OS para instalação
      apk update && \
      # (en) install git and openssh
      # (pt) instala o git e o opnssh
      apk add --no-cache build-base git openssh && \
      # (en) clear the cache
      # (pt) limpa a cache
      rm -rf /var/cache/apk/*

  # (en) creates the /app directory, where your code will be installed
  # (pt) cria o diretório /app, onde seu código vai ser instalado
  WORKDIR /app
  # (en) copy your project into the /app folder
  # (pt) copia seu projeto para dentro da pasta /app
  COPY . .
  # (en) enables the golang compiler to run on an extremely simple OS, scratch
  # (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch
  ARG CGO_ENABLED=0
  # (en) adjust git to work with shh
  # (pt) ajusta o git para funcionar com shh
  RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/
  # (en) defines the path of the private repository
  # (pt) define o caminho do repositório privado
  RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
  # (en) install the dependencies in the go.mod file
  # (pt) instala as dependências no arquivo go.mod
  RUN go mod tidy
  # (en) compiles the main.go file
  # (pt) compila o arquivo main.go
  RUN go build -ldflags="-w -s" -o /app/main /app/main.go
  # (en) creates a new scratch-based image
  # (pt) cria uma nova imagem baseada no scratch
  # (en) scratch is an extremely simple OS capable of generating very small images
  # (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas
  # (en) discarding the previous image erases git access credentials for your security and reduces the size of the
  #      image to save server space
  # (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho
  #      da imagem para poupar espaço no servidor
  FROM scratch
  # (en) copy your project to the new image
  # (pt) copia o seu projeto para a nova imagem
  COPY --from=builder /app/main .
  # (en) execute your project
  # (pt) executa o seu projeto
  CMD ["/main"]

type Event added in v0.9.11

type Event struct {
	ContainerName string
	Message       string
	Error         bool
	Done          bool
	Fail          bool
}

type HealthConfig

type HealthConfig struct {
	// Test is the test to perform to check that the container is healthy.
	// An empty slice means to inherit the default.
	// The options are:
	// {} : inherit healthcheck
	// {"NONE"} : disable healthcheck
	// {"CMD", args...} : exec arguments directly
	// {"CMD-SHELL", command} : run command with system's default shell
	Test []string `json:",omitempty"`

	// Zero means to inherit. Durations are expressed as integer nanoseconds.
	Interval    time.Duration `json:",omitempty"` // Interval is the time to wait between checks.
	Timeout     time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung.
	StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down.

	// Retries is the number of consecutive failures needed to consider a container as unhealthy.
	// Zero means inherit.
	Retries int `json:",omitempty"`
}

HealthConfig

English: holds configuration settings for the HEALTHCHECK feature.

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

type LogFilter added in v0.9.11

type LogFilter struct {
	Label string

	// Texto contido na linha (tudo ou nada)
	Match string

	// expressão regular contendo o filtro para capturar o elemento
	// Ex.: ^(.*?)(?P<valueToGet>\\d+)(.*)
	Filter string

	// texto usado em replaceAll
	// Ex.: search: "." replace: "," para compatibilizar número com o excel
	Search  string
	Replace string

	// path to sabe container default output into file format
	LogPath string
}

type MemoryStats added in v0.5.44

type MemoryStats struct {

	// current res_counter usage for memory
	Usage uint64 `json:"usage,omitempty"`
	// maximum usage ever recorded.
	MaxUsage uint64 `json:"max_usage,omitempty"`
	// all the stats exported via memory.stat.
	Stats map[string]uint64 `json:"stats,omitempty"`
	// number of times memory usage hits limits.
	Failcnt uint64 `json:"failcnt,omitempty"`
	Limit   uint64 `json:"limit,omitempty"`

	// committed bytes
	Commit uint64 `json:"commitbytes,omitempty"`
	// peak committed bytes
	CommitPeak uint64 `json:"commitpeakbytes,omitempty"`
	// private working set
	PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"`
}

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

type 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

	GarbageCollector()

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

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

	var mongoDocker = &ContainerBuilder{}
	mongoDocker.SetNetworkDocker(netDocker)
	mongoDocker.SetImageName("mongo:latest")
	mongoDocker.SetContainerName("container_delete_mongo_after_test")
	//mongoDocker.AddPortToChange("27017", "27016")
	//mongoDocker.AddPortToExpose("27017")
	mongoDocker.SetEnvironmentVar(
		[]string{
			"--bind_ip_all",
			"--host 0.0.0.0",
			"--bind 0.0.0.0",
		},
	)
	mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second)
	err = mongoDocker.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

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

	var redis = ContainerBuilder{}
	redis.SetNetworkDocker(netDocker)
	redis.SetImageName("redis:latest")
	redis.SetContainerName("container_delete_redis_test")
	redis.AddPortToExpose("6379")
	redis.SetWaitStringWithTimeout("Ready to accept connections", 10*time.Second)

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

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

	var chaos = NetworkChaos{}
	chaos.SetNetworkDocker(netDocker)
	chaos.SetFatherContainer(mongoDocker)
	chaos.SetPorts(27017, 27016, false)
	err = chaos.Init()
	if err != nil {
		util.TraceToLog()
		panic(err)
	}

	err = testNetworkOverloaded(
		"mongodb://0.0.0.0:27016",
		2*time.Second,
	)

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

}

// testNetworkOverloaded (English): Tests the new network port
// testNetworkOverloaded (Português): Testa a nova porta de rede
func testNetworkOverloaded(
	address string,
	timeout time.Duration,
) (
	err error,
) {

	// (English): Runtime measurement starts
	// (Português): Começa a medição do tempo de execução
	start := time.Now()

	var mongoClient *mongo.Client
	var cancel context.CancelFunc
	var ctx context.Context

	// (English): Prepare the MongoDB client
	// (Português): Prepara o cliente do MongoDB
	mongoClient, err = mongo.NewClient(options.Client().ApplyURI(address))
	if err != nil {
		return
	}

	// (English): Connects to MongoDB
	// (Português): Conecta ao MongoDB
	err = mongoClient.Connect(ctx)
	if err != nil {
		return
	}

	// (English): Prepares the timeout
	// (Português): Prepara o tempo limite
	ctx, cancel = context.WithTimeout(context.Background(), timeout)
	defer cancel()

	// (English): Ping() to test the MongoDB connection
	// (Português): Faz um ping() para testar a conexão do MongoDB
	err = mongoClient.Ping(ctx, readpref.Primary())
	if err != nil {
		return
	}

	// (English): New collection format
	// (Português): Formato da nova coleção
	type Trainer struct {
		Name string
		Age  int
		City string
	}

	// (English): Creates the 'test' bank and the 'dinos' collection
	// (Português): Cria o banco 'test' e a coleção 'dinos'
	collection := mongoClient.Database("test").Collection("dinos")

	// (English): Prepares the data to be inserted
	// (Português): Prepara os dados a serem inseridos
	trainerData := Trainer{"T-Rex", 10, "Jurassic Town"}

	for i := 0; i != 100; i += 1 {
		// (English): Insert the data
		// (Português): Insere os dados
		_, err = collection.InsertOne(context.TODO(), trainerData)
		if err != nil {
			log.Printf("collection.InsertOne().error: %v", err)
			return
		}
	}

	// (English): Stop the operation time measurement
	// (Português): Para a medição de tempo da operação
	duration := time.Since(start)
	fmt.Printf("End!\n")
	fmt.Printf("Duration: %v\n\n", duration)

	return
}
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) (IsOnTheEdge bool)

SetContainerPaused

English: Increments the paused 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 pausados

Entrada:
  sceneName: nome único da cena
Saída:
  IsOnTheEdge: 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 Português: Monta um teatro de containers com senas lineares ou de caos, permitindo ao desenvolvedor montar em sua máquina de trabalho testes de micro caos durante o desenvolvimento das suas aplicações.
package theater Português: Monta um teatro de containers com senas lineares ou de caos, permitindo ao desenvolvedor montar em sua máquina de trabalho testes de micro caos durante o desenvolvimento das suas aplicações.

Jump to

Keyboard shortcuts

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