|
| 1 | +package kube |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "os/exec" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// PodInfo names one pod and the containers declared in its spec, in spec order. |
| 12 | +// It is what the picker needs to offer a pod (and, when there is more than one, |
| 13 | +// a container) to browse. |
| 14 | +type PodInfo struct { |
| 15 | + Name string |
| 16 | + Containers []string |
| 17 | +} |
| 18 | + |
| 19 | +// Discovery runs read-only `kubectl get`/`kubectl config` commands to enumerate |
| 20 | +// what a session could target. It is the discovery counterpart to Client: where |
| 21 | +// Client is bound to one pod and execs inside it, Discovery is unbound and only |
| 22 | +// reads cluster/kubeconfig metadata, so it lives as its own type rather than on |
| 23 | +// Client. |
| 24 | +type Discovery struct { |
| 25 | + // Bin overrides the kubectl executable. Empty means "kubectl" on PATH. |
| 26 | + Bin string |
| 27 | +} |
| 28 | + |
| 29 | +func (d *Discovery) bin() string { |
| 30 | + if d.Bin != "" { |
| 31 | + return d.Bin |
| 32 | + } |
| 33 | + return "kubectl" |
| 34 | +} |
| 35 | + |
| 36 | +// cmd builds `kubectl [--context X] <args...>` bound to ctx, so a slow listing |
| 37 | +// is killed when the (Go) context is canceled. The kube context is per-call |
| 38 | +// (not bound on Discovery) because the picker switches contexts as the user |
| 39 | +// drills, so each listing names the context it wants. Unlike Client.Exec these |
| 40 | +// are top-level kubectl subcommands, not `exec` into a pod. |
| 41 | +func (d *Discovery) cmd(ctx context.Context, kubeCtx string, args ...string) *exec.Cmd { |
| 42 | + if kubeCtx != "" { |
| 43 | + args = append([]string{"--context", kubeCtx}, args...) |
| 44 | + } |
| 45 | + return exec.CommandContext(ctx, d.bin(), args...) |
| 46 | +} |
| 47 | + |
| 48 | +// namespacesArgs / podsJSONPath / podsArgs are split out from the methods so the |
| 49 | +// exact kubectl invocation can be asserted in tests without shelling out, the |
| 50 | +// way TestClientExecArgs checks Exec. |
| 51 | +func contextsArgs() []string { return []string{"config", "get-contexts", "-o", "name"} } |
| 52 | +func currentContextArgs() []string { return []string{"config", "current-context"} } |
| 53 | +func namespacesArgs() []string { return []string{"get", "namespaces", "-o", "name"} } |
| 54 | + |
| 55 | +// podsJSONPath emits one line per pod: "<name>\t<c1> <c2> …". It is a raw string |
| 56 | +// so the \t and \n reach kubectl's jsonpath parser literally (it, not Go, |
| 57 | +// expands them). |
| 58 | +const podsJSONPath = `{range .items[*]}{.metadata.name}{"\t"}{range .spec.containers[*]}{.name}{" "}{end}{"\n"}{end}` |
| 59 | + |
| 60 | +func podsArgs(namespace string) []string { |
| 61 | + args := []string{"get", "pods"} |
| 62 | + if namespace != "" { |
| 63 | + args = append(args, "-n", namespace) |
| 64 | + } |
| 65 | + return append(args, "-o", "jsonpath="+podsJSONPath) |
| 66 | +} |
| 67 | + |
| 68 | +// Contexts lists the context names in the user's kubeconfig (`kubectl config |
| 69 | +// get-contexts -o name`). It reads only local kubeconfig — no cluster calls — |
| 70 | +// so the picker can offer a context to choose before touching any cluster. |
| 71 | +func (d *Discovery) Contexts(ctx context.Context) ([]string, error) { |
| 72 | + out, err := d.run(ctx, "", contextsArgs()...) |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + return parseNames(out, ""), nil |
| 77 | +} |
| 78 | + |
| 79 | +// CurrentContext returns kubeconfig's current context name (`kubectl config |
| 80 | +// current-context`), so the picker can preselect it. It errors if no current |
| 81 | +// context is set, which the picker treats as "no preselection". |
| 82 | +func (d *Discovery) CurrentContext(ctx context.Context) (string, error) { |
| 83 | + out, err := d.run(ctx, "", currentContextArgs()...) |
| 84 | + if err != nil { |
| 85 | + return "", err |
| 86 | + } |
| 87 | + return strings.TrimSpace(out), nil |
| 88 | +} |
| 89 | + |
| 90 | +// Namespaces lists kubeCtx's namespaces (empty kubeCtx means the current |
| 91 | +// context). It runs `kubectl get namespaces -o name`, which needs cluster-wide |
| 92 | +// list permission; on a restricted cluster it returns the kubectl error, which |
| 93 | +// the picker treats as "fall back to typing". |
| 94 | +func (d *Discovery) Namespaces(ctx context.Context, kubeCtx string) ([]string, error) { |
| 95 | + out, err := d.run(ctx, kubeCtx, namespacesArgs()...) |
| 96 | + if err != nil { |
| 97 | + return nil, err |
| 98 | + } |
| 99 | + return parseNames(out, "namespace/"), nil |
| 100 | +} |
| 101 | + |
| 102 | +// Pods lists the pods in kubeCtx's namespace and the containers each declares. |
| 103 | +func (d *Discovery) Pods(ctx context.Context, kubeCtx, namespace string) ([]PodInfo, error) { |
| 104 | + out, err := d.run(ctx, kubeCtx, podsArgs(namespace)...) |
| 105 | + if err != nil { |
| 106 | + return nil, err |
| 107 | + } |
| 108 | + return parsePods(out), nil |
| 109 | +} |
| 110 | + |
| 111 | +// KubeconfigNamespaces returns the namespace configured for kubeCtx (or the |
| 112 | +// current context, if kubeCtx is empty) as a one-element list — or empty if that |
| 113 | +// context sets none. It reads only local kubeconfig (no cluster calls), so it |
| 114 | +// works even where Namespaces is forbidden, which is exactly when the picker |
| 115 | +// uses it to prefill the typed-namespace fallback. Only this context's namespace |
| 116 | +// is offered: namespaces from other contexts belong to other clusters and would |
| 117 | +// be irrelevant (or misleading) suggestions here. |
| 118 | +func (d *Discovery) KubeconfigNamespaces(ctx context.Context, kubeCtx string) ([]string, error) { |
| 119 | + // `--minify` reduces the view to kubeCtx (or the current context), so this |
| 120 | + // jsonpath yields just that context's namespace. |
| 121 | + out, err := d.run(ctx, kubeCtx, "config", "view", "--minify", "-o", "jsonpath={..namespace}") |
| 122 | + if err != nil { |
| 123 | + return nil, err |
| 124 | + } |
| 125 | + return strings.Fields(out), nil |
| 126 | +} |
| 127 | + |
| 128 | +// run executes a kubectl command in kubeCtx (empty means the current context), |
| 129 | +// returning stdout or a trimmed-stderr error, mirroring remote.Lister.run. |
| 130 | +// Canceling ctx kills the process. |
| 131 | +func (d *Discovery) run(ctx context.Context, kubeCtx string, args ...string) (string, error) { |
| 132 | + cmd := d.cmd(ctx, kubeCtx, args...) |
| 133 | + var out, errb bytes.Buffer |
| 134 | + cmd.Stdout = &out |
| 135 | + cmd.Stderr = &errb |
| 136 | + if err := cmd.Run(); err != nil { |
| 137 | + if msg := strings.TrimSpace(errb.String()); msg != "" { |
| 138 | + return "", fmt.Errorf("%s", msg) |
| 139 | + } |
| 140 | + return "", err |
| 141 | + } |
| 142 | + return out.String(), nil |
| 143 | +} |
| 144 | + |
| 145 | +// parseNames splits `-o name` output ("<kind>/<name>" per line) into bare names, |
| 146 | +// stripping prefix and skipping blanks. |
| 147 | +func parseNames(out, prefix string) []string { |
| 148 | + var names []string |
| 149 | + for _, line := range strings.Split(out, "\n") { |
| 150 | + line = strings.TrimSpace(line) |
| 151 | + if line == "" { |
| 152 | + continue |
| 153 | + } |
| 154 | + names = append(names, strings.TrimPrefix(line, prefix)) |
| 155 | + } |
| 156 | + return names |
| 157 | +} |
| 158 | + |
| 159 | +// parsePods turns the podsJSONPath output into PodInfo. Each line is |
| 160 | +// "<name>\t<space-separated containers>"; a line with no tab (a pod with no |
| 161 | +// listed containers) yields a PodInfo with no containers. |
| 162 | +func parsePods(out string) []PodInfo { |
| 163 | + var pods []PodInfo |
| 164 | + for _, line := range strings.Split(out, "\n") { |
| 165 | + line = strings.TrimRight(line, "\r") |
| 166 | + name, rest, _ := strings.Cut(line, "\t") |
| 167 | + name = strings.TrimSpace(name) |
| 168 | + if name == "" { |
| 169 | + continue |
| 170 | + } |
| 171 | + var containers []string |
| 172 | + if cs := strings.Fields(rest); len(cs) > 0 { |
| 173 | + containers = cs |
| 174 | + } |
| 175 | + pods = append(pods, PodInfo{Name: name, Containers: containers}) |
| 176 | + } |
| 177 | + return pods |
| 178 | +} |
0 commit comments