Skip to content

API proposal: "bass plus" container networking - #4163

Closed
shykes wants to merge 3 commits into
dagger:mainfrom
shykes:networking-bass-plus
Closed

shykes wants to merge 3 commits into
dagger:mainfrom
shykes:networking-bass-plus

Conversation

@shykes

@shykes shykes commented Dec 10, 2022 •

Copy link
Copy Markdown
Contributor

Overview

This is a proposal for a unified container networking API. It is directly inspired by the design of bass as described by @vito, with some API tweaks and expanded to also support networking between containers and host (c2h and h2c).

Features include:

  • A standalone service API
  • DNS-based service discovery with configurable service alias
  • Host proxy service for c2h and h2c
  • Health checks and service coordination

Standalone service API

As discussed with @aluzzardi : we don't currently have a source of truth API design for services, so I'm including one here. If a source of truth emerges elsewhere, I can rebase my proposal on top of it.

DNS-based service discovery

The primitive for this design is point-to-point IP connectivity between containers, with DNS-based service discovery.

Both the overall design, and specifics of how to implement it on top of buildkit (keep the IP address out of llb, use solve first to dedup, etc), are directly lifted from Bass. See this comment for details.

Note: the part about TLS injection is awesome, and I think we should do exactly the same thing. It is not included in this proposal simply for lack of time, but adding it should not require any major API changes.

Configurable service alias

This is an important feature layered on top of the Bass design.

In addition to allocating a unique, non-configurable hostname for each service.. we allow each downstream consumer of a service to define its own alias for that service. This alias should be implemented as a CNAME record pointing to the unique service hostname. Crucially, aliases are local to each container. This avoids naming conflicts which in turn makes user-configurable aliases possible. The tradeoff is increased complexity in implementing the resolver, since there are as many DNS resolver configurations as there are containers. Note that resolver configuration can no longer be updated after executing the process (command or service) that will do the resolving, which should help reduce complexity.

This approach to service discovery has a major benefit: compatibility with existing software. Virtually any program that connects to a TCP or UDP service can be packaged in a Dagger container, and wired to another service, with zero code modification or wrapper. This was a deliberate design decision in Docker as well. It was controversial at the time because Heroku-style $PORT conventions were all the rage. But not requiring code modification or wrappers turned out to be a huge advantage for adoption.

Host proxy service for c2h and h2c

For communication between containers and host, we build on top of the Service primitive with a special "proxy service". A proxy service follows the same networking rules as a regular container service (see DNS-based service discovery and Configurable service alias). But instead of running a user-defined container image, it runs Dagger's builtin proxy with port forwarding rules in both directions.

This "everything is a service approach" has DX and OX benefits:

  • DX benefits: less concepts to learn; easier to swap host and container services for mocking and decoupling. For example, a pipeline might take a Service dependency as argument, and the caller can decide whether to pass a container or host service.

  • OX benefits: easier to understand the operational model; if you look at a list of running services, you are looking at all networking involving your containers (except outbound to the public internet). Any operational tooling on services also benefits host networking: stats, hooks, access control, pluggable networking backends, visualization, etc.

Health checks and service coordination

A simple mechanism for health checks and coordination is included. The default behavior is what most users expect: wait for the services you depend on to be available, before running your own.

Note that thanks to the "everything is a service" approach, health checks and coordination work exactly the same way for both c2c and c2h.

@shykes

shykes commented Dec 13, 2022 •

Copy link
Copy Markdown
Contributor Author

Update: added h2c support

@shykes
shykes requested a review from sipsma December 13, 2022 08:55
@shykes

shykes commented Dec 13, 2022

Copy link
Copy Markdown
Contributor Author

FYI, I added more details on the summary above.

Signed-off-by: Solomon Hykes <[email protected]>
Signed-off-by: Solomon Hykes <[email protected]>
Signed-off-by: Solomon Hykes <[email protected]>
@vito

vito commented Dec 13, 2022 •

Copy link
Copy Markdown
Contributor

Really excited to dig in to this!


re: service aliases:

In addition to allocating a unique, non-configurable hostname for each service.. we allow each downstream consumer of a service to define its own alias for that service. This alias should be implemented as a CNAME record pointing to the unique service hostname. Crucially, aliases are local to each container. This avoids naming conflicts which in turn makes user-configurable aliases possible. The tradeoff is increased complexity in implementing the resolver, since there are as many DNS resolver configurations as there are containers. Note that resolver configuration can no longer be updated after executing the process (command or service) that will do the resolving, which should help reduce complexity.

I like the idea here but I think there may be significant technical hurdles (possibly blockers).

The great thing is that it lets you avoid using interpolation/env vars and write code like the following instead. (Arbitrary code based on my original mockup for a minimal diff.)

diff --git a/test.go b/test.go
index 8c50b1c..c4c7edd 100644
--- a/test.go
+++ b/test.go
@@ -17,8 +17,8 @@ func TestServices(t *testing.T) {

        client := c.Container().
                From("alpine").
-               WithServiceVariable("URL", srv.Address("http", "http://$host:$port")).
-               WithExec([]string{"sh", "-c", "wget -O- $URL"})
+               WithServiceDependency(srv, "mysvc").
+               WithExec([]string{"wget", "-O-", "http://mysvc:8080"})

        out, err := client.Stdout(ctx)
        require.NoError(t, err)

The main difference is being able to avoid templating + env vars + the sh -c wrapper for wget because now we can know the client-side hostname ahead of time and just write static argv.

Here are the downsides I see:

  • If the service is using TLS, the certificate it serves won't match the hostname expected by the client. To me this is the main blocker. TLS isn't part of the proposal yet but I think we still have to consider this point ahead of time.
  • The client is now hard-coding the destination port of the service, introducing a bit of coupling. It also kind of forces us (Dagger) to commit to direct IP addressing rather than being able to reach for proxies to handle a less hospitable network.
  • The complexity overhead for client-side-only CNAMES on top of the regular c2c DNS layer does seem a bit high, but I'm curious to experiment with that anyway, so not really docking marks for it. Also there's a chance we could dodge the CNAME complexity by injecting values into /etc/hosts with our OCI runtime anyway.

re: start/stop:

Bass doesn't have either of these and makes it transparent instead (start when any client needs, stop when all clients are done), so I just have some questions to build bridges in my brain:

  • Is it called start just to match user's traditional intuition around stateful services, and it's actually just a constructor for a Service that is lazily started under the hood (Bass-style)? (I think I might be wrong here.)
  • Is stop around because we want to support long-running services with ports exposed on the host? Is that for running "production" applications? Or maybe just for local dev testing?
  • What happens if I call stop on a service that's actively being used by another client (in Buildkit) I don't know about?

re: proxy: I like it! Statefulness (having a stop) seems to make sense here because we don't have control over the client (we can't know when it's "done").

@shykes

shykes commented Dec 13, 2022 •

Copy link
Copy Markdown
Contributor Author

re: service aliases:

I like the idea here but I think there may be significant technical hurdles (possibly blockers).

The main difference is being able to avoid templating + env vars + the sh -c wrapper for wget because now we can know the client-side hostname ahead of time and just write static argv.

Yes, exactly. I consider this to be a major advantage, which motivates me to at least try to address the potential downsides.

Speaking of which...

Here are the downsides I see:

  • If the service is using TLS, the certificate it serves won't match the hostname expected by the client. To me this is the main blocker. TLS isn't part of the proposal yet but I think we still have to consider this point ahead of time.

I agree that we should consider TLS now. A few potential solutions, keeping in mind that I am absolutely not a TLS wizard:

  1. No TLS injection: developers should avoid TLS in container networking. Devil's advocate argument: you have to trust the underlying network anyway, and both sides of the connection. If you really do need encryption, it could be injected at the transport layer, with CNI hooks or equivalent (eg. wireguard everywhere).

  2. Dagger handles TLS termination. Instead of resolving to the target service IP, the service alias resolves to a loopback interface injected by the shim, with TLS listeners using the correct hostname. The TLS listener then forwards traffic to the actual service port. The actual service port may also use TLS, although it's not necessary. This is comparable to how CDNs handle TLS termination.

  3. To use TLS, client must do an additional lookup. For example we could enshrine that service alias is always a CNAME. Without TLS, just use the alias as hostname. With TLS: first lookup the CNAME record to get the "real" hostname; then connect to that.

  4. this probably doesn't work, writing it down to be thorough: services could perhaps handle TLS termination themselves, with Dagger providing certificates on-the-fly to match the aliases that the service is reachable as. Reasons this probably doesn't work: a) supporting multiple hostnames and loading multiple certificates is either impossible, or so complex and domain-specific that it's just not worth the effort. b) service aliases can be added dynamically after the service is started, but we probably don't want services themselves to be dynamically reconfigured after they start.

  5. That's all I got :)

  • The client is now hard-coding the destination port of the service, introducing a bit of coupling. It also kind of forces us (Dagger) to commit to direct IP addressing rather than being able to reach for proxies to handle a less hospitable network.

I actually think this is a good thing. Direct IP addressing is the correct abstraction layer to focus on. It's "low" enough that we can support 99% of real world use cases, and "high" enough that we can still implement lots of magic. This is especially true now that we have full control over buildkit configuration, CNI hooks etc. IMO we should only move up to the port layer if we absolutely cannot find a way to make it work at the IP layer. In Docker we didn't have the luxury of offering a complete networking model at the IP layer, and we missed it sorely every day, especially for c2c.

"Less hospitable networks" are definitely a reality, but I think there are good tools we can reach for:

  • Escape hatch: if a c2c dependency is too complex, split your pipeline in 2, and use c2h and h2c to connect them while bypassing c2c.
  • Operator hooks: in the future we can leverage CNI hooks to expose networking hooks of our own (probably with less control than full blown CNI, but close enough to be useful).
  • The complexity overhead for client-side-only CNAMES on top of the regular c2c DNS layer does seem a bit high, but I'm curious to experiment with that anyway, so not really docking marks for it. Also there's a chance we could dodge the CNAME complexity by injecting values into /etc/hosts with our OCI runtime anyway.

I agree with your assessment. I started with CNAME because of the extra information it carries (you can look up the real hostname with a CNAME lookup). Whether that's actually useful remains to be seen (see option 3 in how to handle TLS, above).

re: start/stop:

Bass doesn't have either of these and makes it transparent instead (start when any client needs, stop when all clients are done), so I just have some questions to build bridges in my brain:

  • Is it called start just to match user's traditional intuition around stateful services, and it's actually just a constructor for a Service that is lazily started under the hood (Bass-style)? (I think I might be wrong here.)
  • Is stop around because we want to support long-running services with ports exposed on the host? Is that for running "production" applications? Or maybe just for local dev testing?
  • What happens if I call stop on a service that's actively being used by another client (in Buildkit) I don't know about?

This is a question for @aluzzardi , I just copy-pasted this field from his original design :)

Thanks for the thoughtful review!

@vito

vito commented Dec 14, 2022 •

Copy link
Copy Markdown
Contributor

Yes, exactly. I consider this to be a major advantage, which motivates me to at least try to address the potential downsides.

On the same page! 👍

  1. No TLS injection: developers should avoid TLS in container networking. Devil's advocate argument: you have to trust the underlying network anyway, and both sides of the connection. If you really do need encryption, it could be injected at the transport layer, with CNI hooks or equivalent (eg. wireguard everywhere).

Yeah, I largely agree. There were only two things that led me to adding TLS:

  1. My "north star" was to be able to run a Docker registry as a service (specifically Nixery) and use it for fetching images for thunks. But Buildkit requires TLS if the host isn't localhost/127.0.0.1. I tried various workarounds but decided to try to solve the general case by just supporting TLS and installing a CA so the Buildkit host trusts its own services.
  2. Since Bass is enforcing content-addressed hostnames, it's impossible to mint your own cert for your service, since adding the cert would change the content and thus the hostname.

With your proposal, the second point has changed slightly: the user can control hostnames, but on the client side instead. So now you could theoretically generate a CA + certificate for the alias, pass the cert + key to the service, and the CA to the client. It wouldn't help for the Buildkit -> registry traffic, but that's a bit of a corner case, and it might be something we can address in the future if Buildkit does moby/buildkit#3366.

2. Dagger handles TLS termination. Instead of resolving to the target service IP, the service alias resolves to a loopback interface injected by the shim, with TLS listeners using the correct hostname. The TLS listener then forwards traffic to the actual service port. The actual service port may also use TLS, although it's not necessary. This is comparable to how CDNs handle TLS termination.

Yeah this seems like a reasonable approach.

I actually think this is a good thing. Direct IP addressing is the correct abstraction layer to focus on. It's "low" enough that we can support 99% of real world use cases, and "high" enough that we can still implement lots of magic. This is especially true now that we have full control over buildkit configuration, CNI hooks etc. IMO we should only move up to the port layer if we absolutely cannot find a way to make it work at the IP layer. In Docker we didn't have the luxury of offering a complete networking model at the IP layer, and we missed it sorely every day, especially for c2c.

Fair. I agree that direct addressing is a much more powerful layer to build upon and it wouldn't be a terrible thing to make it a hard requirement.

I think it's worth thinking about the client/server coupling aspect though. What if the server and the client are written by different people or are organized into separate parts of the codebase? Say for example an extension provides a Service - how does the person writing the client know to configure :8080?

In #4080 (comment) this is addressed by having each port be named, and then using the template string to substitute $port with the port's value. Not really pushing this idea though; I can't say I'm thrilled to have to define a template string format. This mockup stems from Bass, but we might not land on that approach organically for Dagger (there were other contributing factors for that design in Bass).

I don't have a solution I love for this yet, but here's a strawman: make exposed ports named, and have the client use Service { address(port: String!): String! } to get the full host:port address like DNSHASHABC:8080. The downside is having to make an extra call to the engine just to construct a string, but the upside is we don't need all the CNAME machinery and have a less-coupled client/server.

@shykes

shykes commented Dec 14, 2022

Copy link
Copy Markdown
Contributor Author

I consider this to be a major advantage, which motivates me to at least try to address the potential downsides.
On the same page! 👍
🥳

With your proposal [...] you could theoretically generate a CA + certificate for the alias, pass the cert + key to the service, and the CA to the client. It wouldn't help for the Buildkit -> registry traffic, but that's a bit of a corner case, and it might be something we can address in the future if Buildkit does moby/buildkit#3366.

The buildkit->registry use case is interesting. It agree that it's a corner case, since it's the only one that involves the buildkit
host
(as opposed to the client host, or the container). I don't mind doing some specific magic for this case - it's probably better that way actually, since at the moment Container { publish } is kind of backdoor to the worker machine's own network, which is something we would rather abstract away (ideally outbound traffic would be denied by default unless it goes to a designated exit interface, ie no "host networking" in the docker sense). My guess is that anyone trying to talk to a private registry from a Dagger container is hoping to do so via the exact networking path we should not allow. Same for private git repos and http endpoints. All that stuff should go either through public internet, or the client host.

  1. Dagger handles TLS termination [...]

Yeah this seems like a reasonable approach.

🥳

[...] Direct IP addressing is the correct abstraction layer to focus on. [...]

Fair. I agree that direct addressing is a much more powerful layer to build upon and it wouldn't be a terrible thing to make it a hard requirement.

I think it's worth thinking about the client/server coupling aspect though. What if the server and the client are written by different people or are organized into separate parts of the codebase? Say for example an extension provides a Service - how does the person writing the client know to configure :8080?

That is a good question.

I think no matter what, there will always be some level of tight coupling. Either my client requires your port :8080, or it requires your port "potato". Either way I need to go read your docs to know which value to use in my code. And if I use another service, I will need to go read their docs.

Sure, in theory you could change your service to listen to port :8081, and my client is shielded from that change because it's still called "potato". But I don't know how useful that is in practice, and it comes at the cost of a little bit more friction in various places. I think that friction adds up.

In #4080 (comment) this is addressed by having each port be named, and then using the template string to substitute $port with the port's value. Not really pushing this idea though; I can't say I'm thrilled to have to define a template string format. This mockup stems from Bass, but we might not land on that approach organically for Dagger (there were other contributing factors for that design in Bass).

I don't have a solution I love for this yet, but here's a strawman: make exposed ports named, and have the client use Service { address(port: String!): String! } to get the full host:port address like DNSHASHABC:8080. The downside is having to make an extra call to the engine just to construct a string, but the upside is we don't need all the CNAME machinery and have a less-coupled client/server.

At the risk of invoking my Docker experience too much (I know you're familiar with this fear 😄), one lesson I learned is that people have very subjective opinions on how to do service discovery "right". There is no method that will make everyone happy, and not break someone's software somewhere. So IMO the best method is "no method": provide the bare minimum for a solid experience, and let people build their own Rube Goldberg machine on top for service discovery - and they will!

For example, some software just needs to control the entire port range, because they will allocate ports dynamically as part of their own damn protocol. Just ask @gerhard about RabbitMQ networking... Here's a teaser 😁

RabbitMQ nodes will use a port from a certain range known as the inter-node communication port range. The same port is used by CLI tools when they need to contact the node. The range can be modified.

RabbitMQ nodes communicate with CLI tools and other nodes using a port known as the distribution port. It is dynamically allocated from a range of values. For RabbitMQ, the default range is limited to a single value computed as RABBITMQ_NODE_PORT (AMQP 0-9-1 and AMQP 1.0 port) + 20000, which results in using port 25672. This single port can be configured using the RABBITMQ_DIST_PORT environment variable.

The more opinions we have on the topic of port allocation, port naming etc, the less software will be able to use it, and the more important it is to make it optional or just not define it at all.

That said I think there is one feature missing from my proposal: port introspection. There should be an API call to list ports by a given service, with the description (that's what the "description" field is for exposePort). Noting that exposing a port is optional: for example RabbitMQ users would expose the static ports, but just ignore the whole thing and use their own code to allocate and connect to the dynamic ones. And that's OK!

Sorry for the wall of text :)

@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@vito

vito commented Jan 12, 2023 •

Copy link
Copy Markdown
Contributor

@shykes continuing the conversation in case someone else wants to carry the torch:

I think no matter what, there will always be some level of tight coupling. Either my client requires your port :8080, or it requires your port "potato".

True

Either way I need to go read your docs to know which value to use in my code. And if I use another service, I will need to go read their docs.

Realistically, that documentation probably won't exist for "internal" CI code so I wouldn't want to completely rely on it. One way to get around the docs requirement is to let user guess and get feedback when they're wrong via helpful error messages. Another is through introspection as you proposed (more on that later).

Sure, in theory you could change your service to listen to port :8081, and my client is shielded from that change because it's still called "potato". But I don't know how useful that is in practice, and it comes at the cost of a little bit more friction in various places. I think that friction adds up.

Yep - using a named port will be helpful if your dependency changes in any way. Either things will continue to work (backwards-compatible change to different port), or you'll get unknown port xyz instead connection refused (port no longer exists) or a garbage response (port changed semantics) and potentially debugging the wrong thing for an hour.

But as you said it comes down to whether the frequency and acuteness of this pain justifies the added friction, and whether we can make that friction feel justified by other means (e.g. code that's more readable, maintainable, or easier to write).

That said I think there is one feature missing from my proposal: port introspection. There should be an API call to list ports by a given service, with the description (that's what the "description" field is for exposePort).

This is definitely important - I had this in mind when bringing up named ports too. Also we'd probably want a separate description field even with names.

The code authoring workflow seems kind of awkward though. To figure out the port I want to use I would have to write throwaway code to call the port introspection API, print them, and exit. Then I would run my pipeline, deduce the port from the description, and then hardcode the port and delete the code.

With named ports I could write svc.Address("banana"), get an error message like unknown port: banana; known ports: http, https, and then update the call in-place. It replaces throwaway code with a smaller amount of production code, and it'll short-circuit your pipeline for you if you get the name wrong since it's an error.

The more opinions we have on the topic of port allocation, port naming etc, the less software will be able to use it, and the more important it is to make it optional or just not define it at all.

[...]

Noting that exposing a port is optional: for example RabbitMQ users would expose the static ports, but just ignore the whole thing and use their own code to allocate and connect to the dynamic ones. And that's OK!

Completely agree that this is OK either way, and I don't think this really changes based on whether ports are named or queried before they're used. With direct addressing this and any other dynamic software should Just Work, but it does imply we would need a way to get a service's address without a port or port name. I suppose the port name param could be optional, or we could add svc.Hostname().


A not-so-hidden motivator for all of the above is to avoid the CNAME complexity. It's not the higher-order bit (DX comes first), but it's still there.

With that in mind, here's an alternative proposal without port names: instead of calling svc.Address("http"), you call svc.Address(8080).

This is roughly the same as above, but without port names. We wouldn't need the CNAME complexity, and you'd get a nice error if the port isn't among the service's exposed ports. It won't handle a port changing semantics, but that seems less likely.

In the dynamic case (RabbitMQ), you could just do svc.Hostname() and reach ports directly.


edit: Also just to be clear I'm good with sticking with CNAME + direct ports as proposed, just trying to navigate the decision tree. 😄

@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@vito

vito commented Jan 31, 2023

Copy link
Copy Markdown
Contributor

@shykes Some interesting prior art from testcontainers which has a ton of parallels to what we're trying to solve here:

  • PortEndpoint gives you an address to a given port e.g. container.PortEndpoint(ctx, "8080/tcp", "")
  • Endpoint is a shortcut for getting the first port exposed by the container
  • Host for getting the container hostname
  • Ports for getting all the ports exposed by the container

Also, they have an additional way for checking service health: waiting for a log line to appear! It's implemented as a pluggable WaitingFor field satisfied by an interface and you can see it used in their quickstart. Their quickstart also shows a client using Endpoint to get an address. Could be worth considering if we want an alternative way to see if the service is running rather than probing its port.

Their model seems closest to the last part of my last comment. No named ports, and you call a method to get an address to a given port. They also allow you to specify a protocol if you want to get proto://host:port.

@vito vito mentioned this pull request Feb 1, 2023
13 of 16 tasks
@github-actions

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@vito vito removed the kind/stale label Feb 15, 2023
@github-actions

github-actions Bot commented Mar 2, 2023

Copy link
Copy Markdown
Contributor

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stalled for 7 days with no activity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants