| 1 |
// Package kubepod provides connhelper for kube-pod://<pod> |
| 2 |
package kubepod |
| 3 |
|
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"net" |
| 7 |
"net/url" |
| 8 |
"regexp" |
| 9 |
|
| 10 |
"github.com/docker/cli/cli/connhelper/commandconn" |
| 11 |
"github.com/moby/buildkit/client/connhelper" |
| 12 |
"github.com/pkg/errors" |
| 13 |
) |
| 14 |
|
| 15 |
func init() { |
| 16 |
connhelper.Register("kube-pod", Helper) |
| 17 |
} |
| 18 |
|
| 19 |
// Helper returns helper for connecting to a Kubernetes pod. |
| 20 |
// Requires BuildKit v0.5.0 or later in the pod. |
| 21 |
func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) { |
| 22 |
sp, err := SpecFromURL(u) |
| 23 |
if err != nil { |
| 24 |
return nil, err |
| 25 |
} |
| 26 |
return &connhelper.ConnectionHelper{ |
| 27 |
ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) { |
| 28 |
// using background context because context remains active for the duration of the process, after dial has completed |
| 29 |
return commandconn.New(context.Background(), "kubectl", "--context="+sp.Context, "--namespace="+sp.Namespace, |
| 30 |
"exec", "--container="+sp.Container, "-i", sp.Pod, "--", "buildctl", "dial-stdio") |
| 31 |
}, |
| 32 |
}, nil |
| 33 |
} |
| 34 |
|
| 35 |
// Spec |
| 36 |
type Spec struct { |
| 37 |
Context string |
| 38 |
Namespace string |
| 39 |
Pod string |
| 40 |
Container string |
| 41 |
} |
| 42 |
|
| 43 |
// SpecFromURL creates Spec from URL. |
| 44 |
// URL is like kube-pod://<pod>?context=<context>&namespace=<namespace>&container=<container> . |
| 45 |
// Only <pod> part is mandatory. |
| 46 |
func SpecFromURL(u *url.URL) (*Spec, error) { |
| 47 |
q := u.Query() |
| 48 |
sp := Spec{ |
| 49 |
Context: q.Get("context"), |
| 50 |
Namespace: q.Get("namespace"), |
| 51 |
Pod: u.Hostname(), |
| 52 |
Container: q.Get("container"), |
| 53 |
} |
| 54 |
if sp.Namespace != "" && !validKubeIdentifier(sp.Namespace) { |
| 55 |
return nil, errors.Errorf("unsupported namespace name: %q", sp.Namespace) |
| 56 |
} |
| 57 |
if sp.Pod == "" { |
| 58 |
return nil, errors.New("url lacks pod name") |
| 59 |
} |
| 60 |
if !validKubeIdentifier(sp.Pod) { |
| 61 |
return nil, errors.Errorf("unsupported pod name: %q", sp.Pod) |
| 62 |
} |
| 63 |
if sp.Container != "" && !validKubeIdentifier(sp.Container) { |
| 64 |
return nil, errors.Errorf("unsupported container name: %q", sp.Container) |
| 65 |
} |
| 66 |
return &sp, nil |
| 67 |
} |
| 68 |
|
| 69 |
var kubeIdentifierRegexp = regexp.MustCompile(`^[-a-z0-9.]+$`) |
| 70 |
|
| 71 |
// validKubeIdentifier: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names |
| 72 |
// The length is not checked because future version of Kube may support longer identifiers. |
| 73 |
func validKubeIdentifier(s string) bool { |
| 74 |
return kubeIdentifierRegexp.MatchString(s) |
| 75 |
} |