manager

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrorCh chan error

Functions

This section is empty.

Types

type Chaos

type Chaos struct {
	Type   string
	Action []chaosAction
}

type ContainerFromImage

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

func (*ContainerFromImage) AddImageBuildOptionsBuildArgs

func (el *ContainerFromImage) AddImageBuildOptionsBuildArgs(key string, value *string) (ref *ContainerFromImage)

AddImageBuildOptionsBuildArgs

English:

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

 Input:
   key: Argument name
   value: Argument value

Example:

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

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

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

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

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

Português:

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

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

Exemplo:

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

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

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

    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 (*ContainerFromImage) ArgsEscaped

func (el *ContainerFromImage) ArgsEscaped(argsEscaped bool) (ref *ContainerFromImage)

ArgsEscaped

True if command is already escaped (meaning treat as a command line) (Windows specific)

func (*ContainerFromImage) AutoDockerfileGenerator

func (el *ContainerFromImage) AutoDockerfileGenerator(autoDockerfile DockerfileAuto) (ref *ContainerFromImage)

AutoDockerfileGenerator

Defines the dockerfile generator object

func (*ContainerFromImage) CPUs

func (el *ContainerFromImage) CPUs(value string) (ref *ContainerFromImage)

CPUs

English:

Limit the specific CPUs or cores a container can use.

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

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

The first CPU is numbered 0.

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

Português:

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

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

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

A primeira CPU é numerada como 0.

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

func (*ContainerFromImage) CacheFrom

func (el *ContainerFromImage) CacheFrom(values []string) (ref *ContainerFromImage)

CacheFrom

English:

Specifies images that are used for matching cache.

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

Note:

Images specified here do not need to have a valid parent chain to match cache.

Português:

Especifica imagens que são usadas para correspondência de cache.

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

Note:

As imagens especificadas aqui não precisam ter uma cadeia pai válida para corresponder a cache.

func (*ContainerFromImage) Cmd

func (el *ContainerFromImage) Cmd(cmd ...[]string) (ref *ContainerFromImage)

Cmd

Command to run when starting the container

func (*ContainerFromImage) Command

func (el *ContainerFromImage) Command(key int, command ...string) (exitCode int, running bool, stdOutput []byte, stdError []byte, err error)

Command

Runs a command within a specific container.

Input:
  key: Container key defined in the Create() command, where the largest valid key equals "copies - 1".
    Exemplo, Create(name, copies). Se copies = 1, só há um container criado e a chave de acesso dele é 0
  command: List of commands to run inside docker.
    Example: Google's osv-scanner project requires the "/root/osv-scanner" command to run inside an alpine container
    Therefore, the correct way to execute the command in container 0 will be:
    Command(0, "/bin/ash", "-c", "/root/osv-scanner --json -r /scan > /report/report.json")

func (*ContainerFromImage) Create

func (el *ContainerFromImage) Create(containerName string, copies int) (ref *ContainerFromImage)

Create

Cria o container.

Before this function is called, all settings functions must have been defined.

Input:
  containerName: name from container
  copies: number total of containers

func (*ContainerFromImage) Detach

func (el *ContainerFromImage) Detach() (ref *ContainerFromImage)

Detach

Detach container from monitor and network

func (*ContainerFromImage) DetachMonitor

func (el *ContainerFromImage) DetachMonitor() (ref *ContainerFromImage)

DetachMonitor

Detach container from monitor

func (*ContainerFromImage) DockerfileBuild added in v0.1.4

func (el *ContainerFromImage) DockerfileBuild(workDir, dst, src string) (ref *ContainerFromImage)

DockerfileBuild

workDir: Define work dir. e.g. /app (Dockerfile: WORKDIR /app) dst: Define the destination and source files for go build command e.g. SetGolangSrc("/app/main", "/app/main.go"): RUN go build -ldflags="-w -s" -o (dst) /app/main (src) /app/main.go src: Define the destination and source files for go build command e.g. SetGolangSrc("/app/main", "/app/main.go"): RUN go build -ldflags="-w -s" -o (dst) /app/main (src) /app/main.go

func (*ContainerFromImage) DockerfilePath

func (el *ContainerFromImage) DockerfilePath(path string) (ref *ContainerFromImage)

DockerfilePath

English:

Defines a Dockerfile to build the image.

Português:

Define um arquivo Dockerfile para construir a imagem.

func (*ContainerFromImage) DomainName

func (el *ContainerFromImage) DomainName(name string) (ref *ContainerFromImage)

DomainName

Defines the domain name of the container

func (*ContainerFromImage) EnableChaos

func (el *ContainerFromImage) EnableChaos(maxStopped, maxPaused, maxPausedStoppedSameTime int) (ref *ContainerFromImage)

func (*ContainerFromImage) End

func (el *ContainerFromImage) End()

func (*ContainerFromImage) Entrypoint

func (el *ContainerFromImage) Entrypoint(entrypoint ...string) (ref *ContainerFromImage)

Entrypoint

Entrypoint to run when starting the container

func (*ContainerFromImage) EnvironmentVar

func (el *ContainerFromImage) EnvironmentVar(env ...[]string) (ref *ContainerFromImage)

EnvironmentVar

List of environment variable to set in the container

func (*ContainerFromImage) ExtraHosts

func (el *ContainerFromImage) ExtraHosts(values []string) (ref *ContainerFromImage)

ExtraHosts

English:

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

 Input:
   values: hosts to mapping

Example:

values = []string{
  "somehost:162.242.195.82",
  "otherhost:50.31.209.229",
}

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

  162.242.195.82 somehost
  50.31.209.229 otherhost

Português:

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

 Entrada:
   values: hosts para mapeamento

Exemplo:

values = []string{
  "somehost:162.242.195.82",
  "otherhost:50.31.209.229",
}

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

  162.242.195.82 somehost
  50.31.209.229 otherhost

func (*ContainerFromImage) FailFlag

func (el *ContainerFromImage) FailFlag(path string, flags ...string) (ref *ContainerFromImage)

FailFlag

Define um texto, que quando encontrado na saída padrão do container, define o teste como falho.

Input:
  path: path to save the container standard output
  flags: texts to be searched for in the container standard output

func (*ContainerFromImage) GetGitCloneToBuild

func (el *ContainerFromImage) GetGitCloneToBuild() (url string)

GetGitCloneToBuild

English:

Returns the URL of the repository to clone for image transformation

Note:

  • See the SetGitCloneToBuild() function for more details.

Português:

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

Nota:

  • Veja a função SetGitCloneToBuild() para mais detalhes.

func (*ContainerFromImage) GetSshKeyFileName

func (el *ContainerFromImage) GetSshKeyFileName(dir string) (fileName string, err error)

GetSshKeyFileName

English:

Returns the name of the last generated ssh key.

Português:

Retorna o nome da chave ssh gerada por último.

func (*ContainerFromImage) GitCloneToBuild

func (el *ContainerFromImage) GitCloneToBuild(url string) (ref *ContainerFromImage)

GitCloneToBuild

English:

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

 Input:
   url: Address of the repository containing the project

Note:

  • If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically;
  • To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder;
  • The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
  • If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
  • If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually;
  • This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository;
  • The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*';
  • The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

Português:

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

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

Nota:

  • Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática;
  • Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/;
  • A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
  • Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma;
  • Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual;
  • Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git;
  • O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*';
  • O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

func (*ContainerFromImage) GitCloneToBuildWithPrivateSSHKey

func (el *ContainerFromImage) GitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password string) (ref *ContainerFromImage)

GitCloneToBuildWithPrivateSSHKey

English:

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

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

Note:

  • If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically;
  • To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder;
  • The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
  • If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
  • If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually;
  • This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository;
  • The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*';
  • The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

code:

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

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

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

Português:

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

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

Nota:

  • Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática;
  • Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/;
  • A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
  • Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma;
  • Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual;
  • Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git;
  • O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*';
  • O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

code:

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

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

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

func (*ContainerFromImage) GitCloneToBuildWithPrivateToken

func (el *ContainerFromImage) GitCloneToBuildWithPrivateToken(url, privateToken string) (ref *ContainerFromImage)

GitCloneToBuildWithPrivateToken

English:

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

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

Note:

  • If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically;
  • To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder;
  • The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
  • If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
  • If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually;
  • This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository;
  • The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*';
  • The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

code:

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

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

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

Português:

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

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

Nota:

  • Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática;
  • Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/;
  • A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
  • Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma;
  • Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual;
  • Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git;
  • O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*';
  • O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

code:

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

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

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

func (*ContainerFromImage) GitPassword added in v0.1.5

func (el *ContainerFromImage) GitPassword(password string) (ref *ContainerFromImage)

GitPassword

English:

Set the password from the git user

Português:

Define a senha do usuário git

func (*ContainerFromImage) GitPathPrivateRepository

func (el *ContainerFromImage) GitPathPrivateRepository(value string) (ref *ContainerFromImage)

GitPathPrivateRepository

English:

Path do private repository defined in "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"

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

Português:

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

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

func (*ContainerFromImage) GitPrivateToken added in v0.1.5

func (el *ContainerFromImage) GitPrivateToken(token string) (ref *ContainerFromImage)

func (*ContainerFromImage) GitSshPassword

func (el *ContainerFromImage) GitSshPassword(password string) (ref *ContainerFromImage)

GitSshPassword

English:

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

 Input:
   password: git ssh certificate password

Note:

  • If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically;
  • To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder;
  • The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above;
  • If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password;
  • If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually;
  • This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository;
  • The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*';
  • The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().

Português:

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

 Entrada:
   password: senha da chave ssh

Nota:

  • Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática;
  • Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/;
  • A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima;
  • Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma;
  • Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual;
  • Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git;
  • O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*';
  • O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().

func (*ContainerFromImage) GitSshPrivateKeyPath added in v0.1.5

func (el *ContainerFromImage) GitSshPrivateKeyPath(path string) (ref *ContainerFromImage)

func (*ContainerFromImage) GitUser added in v0.1.5

func (el *ContainerFromImage) GitUser(user string) (ref *ContainerFromImage)

func (*ContainerFromImage) Healthcheck

func (el *ContainerFromImage) Healthcheck(interval, timeout, startPeriod time.Duration, retries int, test ...string) (ref *ContainerFromImage)

Healthcheck

Check the health of the container.

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

func (*ContainerFromImage) HostName

func (el *ContainerFromImage) HostName(hostname ...string) (ref *ContainerFromImage)

HostName

Defines the hostname of the container

func (*ContainerFromImage) ImageCacheName

func (el *ContainerFromImage) ImageCacheName(name string) (ref *ContainerFromImage)

func (*ContainerFromImage) IsolationDefault

func (el *ContainerFromImage) IsolationDefault() (ref *ContainerFromImage)

IsolationDefault

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 (*ContainerFromImage) IsolationHyperV

func (el *ContainerFromImage) IsolationHyperV() (ref *ContainerFromImage)

IsolationHyperV

English:

Set HyperV isolation mode

Português:

Define o método de isolamento como sendo HyperV

func (*ContainerFromImage) IsolationProcess

func (el *ContainerFromImage) IsolationProcess() (ref *ContainerFromImage)

IsolationProcess

English:

Set process isolation mode

Português:

Determina o método de isolamento do processo

func (*ContainerFromImage) Labels

func (el *ContainerFromImage) Labels(labels map[string]string) (ref *ContainerFromImage)

Labels

List of labels set to this container

func (*ContainerFromImage) MacAddress

func (el *ContainerFromImage) MacAddress(macAddress string) (ref *ContainerFromImage)

MacAddress

Mac Address of the container

func (*ContainerFromImage) MakeDockerfile

func (el *ContainerFromImage) MakeDockerfile() (ref *ContainerFromImage)

MakeDockerfile

Mounts a standard Dockerfile automatically

func (*ContainerFromImage) Memory

func (el *ContainerFromImage) Memory(value int64) (ref *ContainerFromImage)

Memory

English:

The maximum amount of memory the container can use.

 Input:
   value: amount of memory in bytes

Note:

Português:

Memória máxima total que o container pode usar.

 Entrada:
   value: Quantidade de memória em bytes

Nota:

func (*ContainerFromImage) MemorySwap

func (el *ContainerFromImage) MemorySwap(value int64) (ref *ContainerFromImage)

MemorySwap

English:

Set memory swap (--memory-swap)

Note:

Português:

habilita a opção memory swp

Note:

func (*ContainerFromImage) Mems

func (el *ContainerFromImage) Mems(value string) (ref *ContainerFromImage)

Mems

English:

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

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

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

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

Português:

Define memory node (MEMs) (--cpuset-mems)

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

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

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

func (*ContainerFromImage) NetworkDisabled

func (el *ContainerFromImage) NetworkDisabled(disabled bool) (ref *ContainerFromImage)

NetworkDisabled

Is network disabled

func (*ContainerFromImage) NoCache

func (el *ContainerFromImage) NoCache() (ref *ContainerFromImage)

NoCache

English:

Set image build no cache

Português:

Define a opção `sem cache` para a construção da imagem

func (*ContainerFromImage) OnBuild

func (el *ContainerFromImage) OnBuild(onBuild ...string) (ref *ContainerFromImage)

OnBuild

The OnBuild function adds to the image a trigger instruction to be executed later, 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:

ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src

Warning:
Chaining ONBUILD instructions using ONBUILD ONBUILD isn’t allowed.

Warning:
The ONBUILD instruction may not trigger FROM or MAINTAINER instructions.

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

func (*ContainerFromImage) OpenStdin

func (el *ContainerFromImage) OpenStdin(open bool) (ref *ContainerFromImage)

OpenStdin

Open stdin

func (*ContainerFromImage) Period

func (el *ContainerFromImage) Period(value int64) (ref *ContainerFromImage)

Period

English:

Specify the CPU CFS scheduler period, which is used alongside --cpu-quota.

 Input:
   value: CPU CFS scheduler period

Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the
default.

For most use-cases, --cpus is a more convenient alternative.

Português:

Especifique o período do agendador CFS da CPU, que é usado junto com --cpu-quota.

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

O padrão é 100.000 microssegundos (100 milissegundos). A maioria dos usuários não altera o padrão.

Para a maioria dos casos de uso, --cpus é uma alternativa mais conveniente.

func (*ContainerFromImage) Platform

func (el *ContainerFromImage) Platform(value string) (ref *ContainerFromImage)

Platform

English:

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

 Input:
   value: target platform

Examples:

osx
windows/amd64
linux/arm64/v8

Português:

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

 Entrada:
   value: plataforma de destino

Exemplos:

osx
windows/amd64
linux/arm64/v8

func (*ContainerFromImage) Ports

func (el *ContainerFromImage) Ports(containerProtocol string, containerPort int64, localPort ...int64) (ref *ContainerFromImage)

Ports

Defines, which port of the container will be exposed to the world

Input:
  containerProtocol: network protocol `tcp` or `utc`
  containerPort: port number on the container. e.g., 27017 for MongoDB
  localPort: port number on the host computer. e.g.,: 27017 for MongoDB

Notes:
  * When `localPort` receives one more value, each container created will receive a different value.
    - Imagine creating 3 containers and passing the values 27016 and 27015. The first container created will receive
    27016, the second, 27015 and the third will not receive value;
    - Imagine creating 3 containers and passing the values 27016, 0 and 27015. The first container created will
    receive 27016, the second will not receive value, and the third receive 27015.

func (*ContainerFromImage) PrivateRepositoryAutoConfig

func (el *ContainerFromImage) PrivateRepositoryAutoConfig() (ref *ContainerFromImage)

PrivateRepositoryAutoConfig

English:

Copies the ssh ~/.ssh/id_rsa file and the ~/.gitconfig file to the SSH_ID_RSA_FILE and
GITCONFIG_FILE variables.

 Output:
   err: Standard error object

 Notes:
   * For change ssh key file name, use SetSshKeyFileName() function.

Português:

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

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

 Notas:
   * Para mudar o nome do arquivo ssh usado como chave, use a função SetSshKeyFileName().

func (*ContainerFromImage) Quota

func (el *ContainerFromImage) Quota(value int64) (ref *ContainerFromImage)

Quota

English:

Defines the host machine’s CPU cycles.

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

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

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

It does not guarantee or reserve any specific CPU access.

Português:

Define os ciclos de CPU da máquina hospedeira.

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

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

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

Não garante ou reserva nenhum acesso específico à CPU.

func (*ContainerFromImage) Remove

func (el *ContainerFromImage) Remove() (ref *ContainerFromImage)

Remove

Removes all containers controlled by the control object

func (*ContainerFromImage) ReplaceBeforeBuild

func (el *ContainerFromImage) ReplaceBeforeBuild(dst, src string) (ref *ContainerFromImage)

ReplaceBeforeBuild

Replaces or adds files to the project, in the temporary folder, before the image is created.

func (*ContainerFromImage) Reports

func (el *ContainerFromImage) Reports() (ref *ContainerFromImage)

Reports

Sets SaveStatistics(), VulnerabilityScanner() and FailFlag() functions to default values.

Note:
  This function is called automatically by the factory

func (*ContainerFromImage) SaveStatistics

func (el *ContainerFromImage) SaveStatistics(path string) (ref *ContainerFromImage)

SaveStatistics

Salva um arquivo com as estatísticas de consumo de memória e processamento do container durante os testes

| read      | pre read  | pids - current (linux) | pids - limit (linux) | num of process (windows) | storage - read count (windows) | storage - write count (windows) | cpu - online | cpu - system usage | cpu - usage in user mode | cpu - usage in kernel mode | cpu - total usage | cpu - throttled time | cpu - throttled periods | cpu - throttling periods | pre cpu - online | pre cpu - system usage | pre cpu - usage in user mode | pre cpu - usage in kernel mode | pre cpu - total usage | pre cpu - throttled time | pre cpu - throttled periods | pre cpu - throttling periods | memory - limit | memory - commit peak | memory - commit | memory - fail cnt | memory - usage | memory - max usage | memory - private working set |
|-----------|-----------|------------------------|----------------------|--------------------------|--------------------------------|---------------------------------|--------------|--------------------|--------------------------|----------------------------|-------------------|----------------------|-------------------------|--------------------------|------------------|------------------------|------------------------------|--------------------------------|-----------------------|--------------------------|-----------------------------|------------------------------|----------------|----------------------|-----------------|-------------------|----------------|--------------------|------------------------------|
| 270355545 | 267925794 | 36                     | -1                   | 0                        | 0                              | 0                               | 8            | 128396690000000    | 1333036000               | 273231000                  | 1606267000        | 0                    | 0                       | 0                        | 8                | 128388860000000        | 1122134000                   | 188896000                      | 1311030000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 67489792       | 0                  | 0                            |
| 315625547 | 312487880 | 36                     | -1                   | 0                        | 0                              | 0                               | 8            | 128443910000000    | 2428358000               | 705437000                  | 3133796000        | 0                    | 0                       | 0                        | 8                | 128436100000000        | 2261894000                   | 623029000                      | 2884924000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 74043392       | 0                  | 0                            |
| 331017884 | 328716175 | 37                     | -1                   | 0                        | 0                              | 0                               | 8            | 128490870000000    | 3388019000               | 1217971000                 | 4605991000        | 0                    | 0                       | 0                        | 8                | 128483010000000        | 3235788000                   | 1129258000                     | 4365046000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 79872000       | 0                  | 0                            |
| 375934470 | 373538303 | 37                     | -1                   | 0                        | 0                              | 0                               | 8            | 128538150000000    | 4373956000               | 1736955000                 | 6110912000        | 0                    | 0                       | 0                        | 8                | 128530300000000        | 4209072000                   | 1648809000                     | 5857882000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 85491712       | 0                  | 0                            |
| 392846000 | 389797833 | 37                     | -1                   | 0                        | 0                              | 0                               | 8            | 128585060000000    | 5392002000               | 2341771000                 | 7733774000        | 0                    | 0                       | 0                        | 8                | 128577290000000        | 5213464000                   | 2236247000                     | 7449711000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 91275264       | 0                  | 0                            |
| 438223378 | 435128169 | 36                     | -1                   | 0                        | 0                              | 0                               | 8            | 128632160000000    | 6476036000               | 2913993000                 | 9390029000        | 0                    | 0                       | 0                        | 8                | 128624350000000        | 6290689000                   | 2803815000                     | 9094505000            | 0                        | 0                           | 0                            | 12544057344    | 0                    | 0               | 0                 | 97112064       | 0                  | 0                            |

func (*ContainerFromImage) SetImageBuildOptionsSecurityOpt

func (el *ContainerFromImage) SetImageBuildOptionsSecurityOpt(value []string) (ref *ContainerFromImage)

SetImageBuildOptionsSecurityOpt

English:

Set the container security options

 Input:
   values: container security options

Examples:

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

Português:

Modifica as opções de segurança do container

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

Exemplos:

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

func (*ContainerFromImage) Shares

func (el *ContainerFromImage) Shares(value int64) (ref *ContainerFromImage)

Shares

English:

Set the CPU shares of the image build options.

 Input:
   value: CPU shares (Default: 1024)

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

This is only enforced when CPU cycles are constrained.

When plenty of CPU cycles are available, all containers use as much CPU as they need.

In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled
in swarm mode.

It prioritizes container CPU resources for the available CPU cycles.

It does not guarantee or reserve any specific CPU access.

Português:

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

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

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

Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão
disponíveis, todos os container usam a quantidade de CPU de que precisam. Dessa forma, este é um
limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm.

Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis.

Não garante ou reserva nenhum acesso específico à CPU.

func (*ContainerFromImage) Shell

func (el *ContainerFromImage) Shell(shell ...[]string) (ref *ContainerFromImage)

Shell

Shell for shell-form of RUN, CMD, ENTRYPOINT

func (*ContainerFromImage) Squash

func (el *ContainerFromImage) Squash(value bool) (ref *ContainerFromImage)

Squash

English:

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

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

Português:

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

 Entrada:
   value: true preserva a imagem original e cria uma nova imagem a partir da imagem pai

func (*ContainerFromImage) Start

func (el *ContainerFromImage) Start() (ref *ContainerFromImage)

Start

Initializes all containers controlled by the control object

func (*ContainerFromImage) StdinOnce

func (el *ContainerFromImage) StdinOnce(once bool) (ref *ContainerFromImage)

StdinOnce

If true, close stdin after the 1 attached client disconnects

func (*ContainerFromImage) Stop

func (el *ContainerFromImage) Stop() (ref *ContainerFromImage)

Stop

Stops all containers controlled by the control object

func (*ContainerFromImage) StopSignal

func (el *ContainerFromImage) StopSignal(signal string) (ref *ContainerFromImage)

StopSignal

Signal to stop a container

func (*ContainerFromImage) StopTimeout

func (el *ContainerFromImage) StopTimeout(timeout time.Duration) (ref *ContainerFromImage)

StopTimeout

Timeout to stop the container after command `container.Stop()`

func (*ContainerFromImage) Target

func (el *ContainerFromImage) Target(value string) (ref *ContainerFromImage)

Target

English:

Build the specified stage as defined inside the Dockerfile.

 Input:
   value: stage name

Note:

Português:

Monta o container a partir do estágio definido no arquivo Dockerfile.

 Entrada:
   value: nome do estágio

Nota:

func (*ContainerFromImage) Tty

func (el *ContainerFromImage) Tty(tty bool) (ref *ContainerFromImage)

Tty

Attach standard streams to a tty, including stdin if it is not closed

func (*ContainerFromImage) User

func (el *ContainerFromImage) User(name string) (ref *ContainerFromImage)

User

User that will run the command(s) inside the container, also support user:group

func (*ContainerFromImage) Volumes

func (el *ContainerFromImage) Volumes(containerPath string, hostPath ...string) (ref *ContainerFromImage)

Volumes

List of volumes (mounts) used for the container

 Input:
   containerPath: folder or file path inside the container
   hostPath: list of folders or files within the host computer

	Notes:
	  * When `hostPath` receives one more value, each container created will receive a different value.
	    - Imagine creating 3 containers and passing the values `pathA` and `pathB`. The first container created will
	    receive `pathA`, the second, `pathB` and the third will not receive value;
	    - Imagine creating 3 containers and passing the values `pathA`, `` and `pathB`. The first container created will
	    receive `pathA`, the second will not receive value, and the third receive `pathB`.

func (*ContainerFromImage) VulnerabilityScanner

func (el *ContainerFromImage) VulnerabilityScanner(path string) (ref *ContainerFromImage)

VulnerabilityScanner

Uses google's "osv-scanner" project to look for packages containing vulnerabilities in the code under test.

 Example:

		# Vulnerability Report

		This report is based on an open database and shows known vulnerabilities. Validity: Sun Dec 18 11:09:02 2022

		## Path

		Path: /scan/go.mod
		Type: lockfile

		### Packages

		| Ecosystem | Package          | Version |
		|-----------|------------------|---------|
		| Go        | golang.org/x/net | 0.2.0   |

		### Details:

		An attacker can cause excessive memory growth in a Go server accepting HTTP/2 requests.

		HTTP/2 server connections contain a cache of HTTP header keys sent by the client. While the total number of entries in this cache is capped, an attacker sending very large keys can cause the server to allocate approximately 64 MiB per open connection.

		### Affected:

		| Ecosystem | Package          |
		|-----------|------------------|
		| Go        | stdlib           |
		| Go        | golang.org/x/net |

		| type   | URL                                                                                                                                                  |
		|--------|------------------------------------------------------------------------------------------------------------------------------------------------------|
		| REPORT | [https://go.dev/issue/56350](https://go.dev/issue/56350)                                                                                             |
		| FIX    | [https://go.dev/cl/455717](https://go.dev/cl/455717)                                                                                                 |
		| FIX    | [https://go.dev/cl/455635](https://go.dev/cl/455635)                                                                                                 |
		| WEB    | [https://groups.google.com/g/golang-announce/c/L_3rmdT0BMU/m/yZDrXjIiBQAJ](https://groups.google.com/g/golang-announce/c/L_3rmdT0BMU/m/yZDrXjIiBQAJ) |

func (*ContainerFromImage) WaitForFlag

func (el *ContainerFromImage) WaitForFlag(text string) (ref *ContainerFromImage)

WaitForFlag

Wait for a flag (word) in the container's standard output

func (*ContainerFromImage) WaitForFlagTimeout

func (el *ContainerFromImage) WaitForFlagTimeout(text string, timeout time.Duration) (ref *ContainerFromImage)

WaitForFlagTimeout

Wait for a flag (word) in the container's standard output

func (*ContainerFromImage) WaitStatusNotRunning

func (el *ContainerFromImage) WaitStatusNotRunning(timeout time.Duration) (ref *ContainerFromImage)

func (*ContainerFromImage) WorkingDir

func (el *ContainerFromImage) WorkingDir(workingDir string) (ref *ContainerFromImage)

WorkingDir

Current directory (PWD) in the command will be launched

type DockerfileAuto

type DockerfileAuto interface {
	MountDefaultDockerfile(args map[string]*string, ports []nat.Port, volumes []mount.Mount, installExtraPackages bool, useCache bool, imageCacheName string) (dockerfile string, err error)
	Prayer()
	SetFinalImageName(name string)
	AddCopyToFinalImage(src, dst string)
	SetDefaultSshFileName(name string)
}

DockerfileAuto

English: Interface from automatic Dockerfile generator.

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

One way to do this automatically is to use the Dockerfile example below, where the arguments SSH_ID_RSA_FILE
contains the file ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contains the file ~/.ssh/known_hosts and GITCONFIG_FILE
contains the file ~/.gitconfig.

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

If you want to copy the files into the image automatically, use SetPrivateRepositoryAutoConfig() and the
function will copy the files ~/.ssh/id_rsa, ~/.ssh/known_hosts and ~/.gitconfig to the viable arguments
located above.

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

The Dockerfile below can be used as a base

  # (en) first stage of the process
  # (pt) primeira etapa do processo
  FROM golang:1.16-alpine as builder

  # (en) enable the argument variables
  # (pt) habilita as variáveis de argumento
  ARG SSH_ID_RSA_FILE
  ARG KNOWN_HOSTS_FILE
  ARG GITCONFIG_FILE
  ARG GIT_PRIVATE_REPO

  # (en) creates the .ssh directory within the root directory
  # (pt) cria o diretório .ssh dentro do diretório root
  RUN mkdir -p /root/.ssh/ && \
      # (en) creates the id_esa file inside the .ssh directory
      # (pt) cria o arquivo id_esa dentro do diretório .ssh
      echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/ && \
      # (en) creates the known_hosts file inside the .ssh directory
      # (pt) cria o arquivo known_hosts dentro do diretório .ssh
      echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.ssh/known_hosts && \
      # (en) creates the .gitconfig file at the root of the root directory
      # (pt) cria o arquivo .gitconfig na raiz do diretório /root
      echo "$GITCONFIG_FILE" > /root/.gitconfig && \
      # (en) adjust file access security
      # (pt) ajusta a segurança de acesso do arquivo
      chmod -R 600 /root/.gitconfig && \
      # (en) prepares the OS for installation
      # (pt) prepara o OS para instalação
      apk update && \
      # (en) install git and openssh
      # (pt) instala o git e o openssh
      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 Manager

type Manager struct {
	TickerStats       *time.Ticker
	TickerFail        *time.Ticker
	Id                []string
	DockerSys         []*builder.DockerSystem
	Chaos             []Chaos
	ChaosConfig       chaosConfig
	ImageBuildOptions types.ImageBuildOptions

	DoneCh chan struct{}

	FailCh chan string
	// contains filtered or unexported fields
}

func (*Manager) ContainerFromFolder

func (el *Manager) ContainerFromFolder(imageName, buildPath string) (containerFromImage *ContainerFromImage)

func (*Manager) ContainerFromGit

func (el *Manager) ContainerFromGit(imageName, serverPath string) (containerFromImage *ContainerFromImage)

func (*Manager) ContainerFromImage

func (el *Manager) ContainerFromImage(imageName string) (containerFromImage *ContainerFromImage)

func (*Manager) New

func (el *Manager) New()

func (*Manager) Primordial

func (el *Manager) Primordial() (primordial *Primordial)

type NetworkInterface

type NetworkInterface interface {
	Init() (err error)
	GetConfiguration() (IP string, networkConfiguration *networkTypes.NetworkingConfig, err error)
	NetworkCreate(name, subnet, gateway string) (err error)
	GetNetworkName() (name string)
	GetNetworkID() (ID string)
	Remove() (err error)
}

type Primordial

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

func (*Primordial) Done added in v0.1.5

func (el *Primordial) Done()

Done

End of test before requested time

func (*Primordial) GarbageCollector

func (el *Primordial) GarbageCollector(names ...string) (ref *Primordial)

GarbageCollector

Deletes all Docker elements with `delete` in the name.

Input:
  names: additional list of terms to be deleted

Example:
  GarbageCollector("mongo") will delete any docker element with the term `mongo` contained in the name, which
  includes the image named `mongo:6.0.6`, container named `mongodb` and network name `mongodb_network`

func (*Primordial) GetLastError added in v0.1.1

func (el *Primordial) GetLastError() (err error)

GetLastError

Returns the last error from the test

func (*Primordial) Monitor

func (el *Primordial) Monitor(duration time.Duration) (pass bool)

Monitor

Monitors the test for errors while waiting for the test to end.

Notes:
  * When the test timer ends, Monitor() waits for all test pipelines to finish, hooking up all containers at the
    end of the test

func (*Primordial) NetworkCreate

func (el *Primordial) NetworkCreate(name, subnet, gateway string) (ref *Primordial)

NetworkCreate

Create a docker network to be used in the chaos test

Input:
  name: network name
  subnet: subnet value. eg. 10.0.0.0/16
  gateway: gateway value. eg. "10.0.0.1

Notes:
  * If there is already a network with the same name and the same configuration, nothing will be done;
  * If a network with the same name and different configuration already exists, the network will be deleted and a new network created.

func (*Primordial) Test

func (el *Primordial) Test(t *testing.T, pathToSave string, names ...string) (ref *Primordial)

Jump to

Keyboard shortcuts

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