-
-
Notifications
You must be signed in to change notification settings - Fork 584
feat: client proof of concept #2996
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
stevenh
wants to merge
1
commit into
main
Choose a base branch
from
feat/client-poc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+339
−0
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| package client | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "time" | ||
|
|
||
| "github.com/cenkalti/backoff/v4" | ||
| "github.com/docker/docker/api/types" | ||
| "github.com/docker/docker/pkg/jsonmessage" | ||
| "github.com/moby/term" | ||
| ) | ||
|
|
||
| // buildOptions is a type that represents all options for building an image. | ||
| type buildOptions struct { | ||
| options types.ImageBuildOptions | ||
| logWriter io.Writer | ||
| } | ||
|
|
||
| // LogWriter returns writer for build logs. | ||
| // Default: [io.Discard]. | ||
| func (bo buildOptions) LogWriter() io.Writer { | ||
| if bo.logWriter != nil { | ||
| return bo.logWriter | ||
| } | ||
|
|
||
| return io.Discard | ||
| } | ||
|
|
||
| // BuildOption is a type that represents an option for building an image. | ||
| type BuildOption func(*buildOptions) error | ||
|
|
||
| // BuildOptions returns a build option that sets the options for building an image. | ||
| // TODO: Should we expose this or make options for each struct member? | ||
| func BuildOptions(options types.ImageBuildOptions) BuildOption { | ||
| return func(bo *buildOptions) error { | ||
| bo.options = options | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // BuildLogWriter returns a build option that sets the writer for the build logs. | ||
| func BuildLogWriter(w io.Writer) BuildOption { | ||
| return func(bo *buildOptions) error { | ||
| bo.logWriter = w | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // BuildImage builds an image from a build context with the specified options. | ||
| // If buildContext implements [io.Closer], it will be closed before returning. | ||
| // The first tag is returned if the build is successful. | ||
| func (c *Client) BuildImage(ctx context.Context, buildContext io.Reader, options ...BuildOption) (string, error) { | ||
| defer func() { | ||
| // Clean up if necessary. | ||
| if rc, ok := buildContext.(io.Closer); ok { | ||
| rc.Close() | ||
| } | ||
| }() | ||
|
|
||
| if err := c.initOnce(ctx); err != nil { | ||
| return "", fmt.Errorf("init: %w", err) | ||
| } | ||
|
|
||
| var opts buildOptions | ||
| for _, opt := range options { | ||
| if err := opt(&opts); err != nil { | ||
| return "", err | ||
| } | ||
| } | ||
|
|
||
| resp, err := backoff.RetryNotifyWithData( | ||
| func() (*types.ImageBuildResponse, error) { | ||
| resp, err := c.client.ImageBuild(ctx, buildContext, opts.options) | ||
| if err != nil { | ||
| if isPermanentClientError(err) { | ||
| return nil, backoff.Permanent(err) | ||
| } | ||
|
|
||
| // Retryable error. | ||
| return nil, err | ||
| } | ||
|
|
||
| return &resp, nil | ||
| }, | ||
| backoff.WithContext(backoff.NewExponentialBackOff(), ctx), | ||
| func(err error, _ time.Duration) { | ||
| c.log.DebugContext(ctx, "build image", "error", err) | ||
| }, | ||
| ) | ||
| if err != nil { | ||
| return "", fmt.Errorf("build image: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| // Always process the output, even if it is not printed to ensure that errors | ||
| // during the build process are correctly handled. | ||
| output := opts.LogWriter() | ||
| termFd, isTerm := term.GetFdInfo(output) | ||
| if err = jsonmessage.DisplayJSONMessagesStream(resp.Body, output, termFd, isTerm, nil); err != nil { | ||
| return "", fmt.Errorf("build image: %w", err) | ||
| } | ||
|
|
||
| // The first tag is the one we want. | ||
| return opts.options.Tags[0], nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| package client | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log/slog" | ||
| "path/filepath" | ||
| "sync" | ||
|
|
||
| "github.com/docker/docker/client" | ||
|
|
||
| "github.com/testcontainers/testcontainers-go/internal" | ||
| "github.com/testcontainers/testcontainers-go/internal/core" | ||
| ) | ||
|
|
||
| const ( | ||
| // Headers used for docker client requests. | ||
| headerProjectPath = "x-tc-pp" | ||
| headerSessionID = "x-tc-sid" | ||
| headerUserAgent = "User-Agent" | ||
|
|
||
| // TLS certificate files. | ||
| tlsCACertFile = "ca.pem" | ||
| tlsCertFile = "cert.pem" | ||
| tlsKeyFile = "key.pem" | ||
| ) | ||
|
|
||
| // DefaultClient is the default client for interacting with containers. | ||
| var DefaultClient = &Client{} | ||
|
|
||
| // Client is a type that represents a client for interacting with containers. | ||
| type Client struct { | ||
| log slog.Logger | ||
|
|
||
| // mtx is a mutex for synchronizing access to the fields below. | ||
| mtx sync.RWMutex | ||
| client *client.Client | ||
| cfg *config | ||
| err error | ||
| } | ||
|
|
||
| // ClientOption is a type that represents an option for configuring a client. | ||
| type ClientOption func(*Client) error | ||
|
|
||
| // Logger returns a client option that sets the logger for the client. | ||
| func Logger(log slog.Logger) ClientOption { | ||
| return func(c *Client) error { | ||
| c.log = log | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| // NewClient returns a new client for interacting with containers. | ||
| func NewClient(ctx context.Context, options ...ClientOption) (*Client, error) { | ||
| client := &Client{} | ||
| for _, opt := range options { | ||
| if err := opt(client); err != nil { | ||
| return nil, err | ||
| } | ||
| } | ||
|
|
||
| if err := client.initOnce(ctx); err != nil { | ||
| return nil, fmt.Errorf("load config: %w", err) | ||
| } | ||
|
|
||
| return client, nil | ||
| } | ||
|
|
||
| // initOnce initializes the client once. | ||
| // This method is safe for concurrent use by multiple goroutines. | ||
| func (c *Client) initOnce(ctx context.Context) error { | ||
| c.mtx.RLock() | ||
| if c.client != nil || c.err != nil { | ||
| err := c.err | ||
| c.mtx.RUnlock() | ||
| return err | ||
| } | ||
| c.mtx.RUnlock() | ||
|
|
||
| c.mtx.Lock() | ||
| defer c.mtx.Unlock() | ||
|
|
||
| if c.cfg, c.err = newConfig(); c.err != nil { | ||
| return c.err | ||
| } | ||
|
|
||
| opts := []client.Opt{client.FromEnv, client.WithAPIVersionNegotiation()} | ||
|
|
||
| // TODO: handle internally / replace with context related code. | ||
| if dockerHost := core.MustExtractDockerHost(ctx); dockerHost != "" { | ||
| opts = append(opts, client.WithHost(dockerHost)) | ||
| } | ||
|
|
||
| if c.cfg.TLSVerify { | ||
| // For further information see: | ||
| // https://docs.docker.com/engine/security/protect-access/#use-tls-https-to-protect-the-docker-daemon-socket | ||
| opts = append(opts, client.WithTLSClientConfig( | ||
| filepath.Join(c.cfg.CertPath, tlsCACertFile), | ||
| filepath.Join(c.cfg.CertPath, tlsCertFile), | ||
| filepath.Join(c.cfg.CertPath, tlsKeyFile), | ||
| )) | ||
| } | ||
|
|
||
| opts = append(opts, client.WithHTTPHeaders( | ||
| map[string]string{ | ||
| headerProjectPath: core.ProjectPath(), | ||
| headerSessionID: core.SessionID(), | ||
| headerUserAgent: "tc-go/" + internal.Version, | ||
| }), | ||
| ) | ||
|
|
||
| if c.client, c.err = client.NewClientWithOpts(opts...); c.err != nil { | ||
| c.err = fmt.Errorf("new client: %w", c.err) | ||
| return c.err | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package client | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "time" | ||
|
|
||
| "github.com/caarlos0/env/v11" | ||
| "github.com/magiconair/properties" | ||
| ) | ||
|
|
||
| // config represents the configuration for Testcontainers. | ||
| // User values are read from ~/.testcontainers.properties file which can be overridden | ||
| // using the specified environment variables. For more information, see [Custom Configuration]. | ||
| // | ||
| // The Ryuk fields controls the [Garbage Collector] feature, which ensures that resources are | ||
| // cleaned up after the test execution. | ||
| // | ||
| // [Garbage Collector]: https://golang.testcontainers.org/features/garbage_collector/ | ||
| // [Custom Configuration]: https://golang.testcontainers.org/features/configuration/ | ||
| type config struct { // TODO: consider renaming adding default values to the struct fields. | ||
| // Host is the address of the Docker daemon. | ||
| Host string `properties:"docker.host" env:"DOCKER_HOST"` | ||
|
|
||
| // TLSVerify is a flag to enable or disable TLS verification when connecting to a Docker daemon. | ||
| TLSVerify bool `properties:"docker.tls.verify" env:"DOCKER_TLS_VERIFY"` | ||
|
|
||
| // CertPath is the path to the directory containing the Docker certificates. | ||
| // This is used when connecting to a Docker daemon over TLS. | ||
| CertPath string `properties:"docker.cert.path" env:"DOCKER_CERT_PATH"` | ||
|
|
||
| // HubImageNamePrefix is the prefix used for the images pulled from the Docker Hub. | ||
| // This is useful when running tests in environments with restricted internet access. | ||
| HubImageNamePrefix string `properties:"hub.image.name.prefix" env:"TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX"` | ||
|
|
||
| // TestcontainersHost is the address of the Testcontainers host. | ||
| TestcontainersHost string `properties:"tc.host" env:"TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE"` | ||
|
|
||
| // Ryuk is the configuration for the Garbage Collector. | ||
| Ryuk ryukConfig | ||
| } | ||
|
|
||
| type ryukConfig struct { | ||
| // Disabled is a flag to enable or disable the Garbage Collector. | ||
| // Setting this to true will prevent testcontainers from automatically cleaning up | ||
| // resources, which is particularly important in tests which timeout as they | ||
| // don't run test clean up. | ||
| Disabled bool `properties:"ryuk.disabled" env:"TESTCONTAINERS_RYUK_DISABLED"` | ||
|
|
||
| // Privileged is a flag to enable or disable the privileged mode for the Garbage Collector container. | ||
| // Setting this to true will run the Garbage Collector container in privileged mode. | ||
| Privileged bool `properties:"ryuk.container.privileged" env:"TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED"` | ||
|
|
||
| // ReconnectionTimeout is the time to wait before attempting to reconnect to the Garbage Collector container. | ||
| ReconnectionTimeout time.Duration `properties:"ryuk.reconnection.timeout,default=10s" env:"TESTCONTAINERS_RYUK_RECONNECTION_TIMEOUT"` | ||
|
|
||
| // ConnectionTimeout is the time to wait before timing out when connecting to the Garbage Collector container. | ||
| ConnectionTimeout time.Duration `properties:"ryuk.connection.timeout,default=1m" env:"TESTCONTAINERS_RYUK_CONNECTION_TIMEOUT"` | ||
|
|
||
| // Verbose is a flag to enable or disable verbose logging for the Garbage Collector. | ||
| Verbose bool `properties:"ryuk.verbose" env:"TESTCONTAINERS_RYUK_VERBOSE"` | ||
| } | ||
|
|
||
| // newConfig returns a new configuration loaded from the properties file | ||
| // located in the user's home directory and overridden by environment variables. | ||
| func newConfig() (*config, error) { | ||
| home, err := os.UserHomeDir() | ||
| if err != nil { | ||
| return nil, fmt.Errorf("user home dir: %w", err) | ||
| } | ||
|
|
||
| props, err := properties.LoadFiles([]string{filepath.Join(home, ".testcontainers.properties")}, properties.UTF8, true) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("load properties file: %w", err) | ||
| } | ||
|
|
||
| var cfg config | ||
| if err := props.Decode(&cfg); err != nil { | ||
| return nil, fmt.Errorf("decode properties: %w", err) | ||
| } | ||
|
|
||
| if err := env.Parse(cfg); err != nil { | ||
| return nil, fmt.Errorf("parse env: %w", err) | ||
| } | ||
|
|
||
| return &cfg, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package client | ||
|
|
||
| import ( | ||
| "github.com/docker/docker/errdefs" | ||
| ) | ||
|
|
||
| var permanentClientErrors = []func(error) bool{ | ||
| errdefs.IsNotFound, | ||
| errdefs.IsInvalidParameter, | ||
| errdefs.IsUnauthorized, | ||
| errdefs.IsForbidden, | ||
| errdefs.IsNotImplemented, | ||
| errdefs.IsSystem, | ||
| } | ||
|
|
||
| func isPermanentClientError(err error) bool { | ||
| for _, isErrFn := range permanentClientErrors { | ||
| if isErrFn(err) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
question: are we going to use
WithXXXoptions orXXX(like here)?