Skip to content

Commit 77583c1

Browse files
committed
feat: add nerdctl-container support for client
Signed-off-by: Wei Zhang <[email protected]>
1 parent 617b78c commit 77583c1

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Package nerdctlcontainer provides connhelper for nerdctl-container://<container>
2+
package nerdctlcontainer
3+
4+
import (
5+
"context"
6+
"net"
7+
"net/url"
8+
9+
"github.com/docker/cli/cli/connhelper/commandconn"
10+
"github.com/moby/buildkit/client/connhelper"
11+
"github.com/pkg/errors"
12+
)
13+
14+
func init() {
15+
connhelper.Register("nerdctl-container", Helper)
16+
}
17+
18+
// Helper returns helper for connecting to a Nerdctl container.
19+
// Requires BuildKit v0.5.0 or later in the container.
20+
func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
21+
sp, err := SpecFromURL(u)
22+
if err != nil {
23+
return nil, err
24+
}
25+
return &connhelper.ConnectionHelper{
26+
ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
27+
// using background context because context remains active for the duration of the process, after dial has completed
28+
return commandconn.New(context.Background(), "nerdctl", []string{"exec", "-i", sp.Container, "buildctl", "dial-stdio"}...)
29+
},
30+
}, nil
31+
}
32+
33+
// Spec
34+
type Spec struct {
35+
Container string
36+
}
37+
38+
// SpecFromURL creates Spec from URL.
39+
// URL is like nerdctl-container://<container>
40+
// Only <container> part is mandatory.
41+
func SpecFromURL(u *url.URL) (*Spec, error) {
42+
sp := Spec{
43+
Container: u.Hostname(),
44+
}
45+
if sp.Container == "" {
46+
return nil, errors.New("url lacks container name")
47+
}
48+
return &sp, nil
49+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package nerdctlcontainer
2+
3+
import (
4+
"net/url"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestSpecFromURL(t *testing.T) {
11+
cases := map[string]*Spec{
12+
"nerdctl-container://containername": {
13+
Container: "containername",
14+
},
15+
"nerdctl-container://": nil,
16+
}
17+
for s, expected := range cases {
18+
u, err := url.Parse(s)
19+
if err != nil {
20+
t.Fatal(err)
21+
}
22+
got, err := SpecFromURL(u)
23+
if expected != nil {
24+
require.NoError(t, err)
25+
require.EqualValues(t, expected, got, s)
26+
} else {
27+
require.Error(t, err, s)
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)