/
get.go
98 lines (78 loc) · 2.25 KB
/
get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cmd
import (
"context"
"errors"
"fmt"
"os"
pb "github.com/linkerd/linkerd2/controller/gen/public"
"github.com/linkerd/linkerd2/pkg/k8s"
"github.com/spf13/cobra"
)
type getOptions struct {
namespace string
allNamespaces bool
}
func newGetOptions() *getOptions {
return &getOptions{
namespace: "default",
allNamespaces: false,
}
}
func newCmdGet() *cobra.Command {
options := newGetOptions()
cmd := &cobra.Command{
Use: "get [flags] pods",
Short: "Display one or many mesh resources",
Long: `Display one or many mesh resources.
Only pod resources (aka pods, po) are supported.`,
Example: ` # get all pods
linkerd get pods
# get pods from namespace linkerd
linkerd get pods --namespace linkerd`,
Args: cobra.ExactArgs(1),
ValidArgs: []string{k8s.Pod},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("please specify a resource type")
}
if len(args) > 1 {
return errors.New("please specify only one resource type")
}
friendlyName := args[0]
resourceType, err := k8s.CanonicalResourceNameFromFriendlyName(friendlyName)
if err != nil || resourceType != k8s.Pod {
return fmt.Errorf("invalid resource type %s, valid types: %s", friendlyName, k8s.Pod)
}
podNames, err := getPods(validatedPublicAPIClient(false), options)
if err != nil {
return err
}
if len(podNames) == 0 {
fmt.Fprintln(os.Stderr, "No resources found.")
os.Exit(0)
}
for _, podName := range podNames {
fmt.Println(podName)
}
return nil
},
}
cmd.PersistentFlags().StringVarP(&options.namespace, "namespace", "n", options.namespace, "Namespace of pods")
cmd.PersistentFlags().BoolVar(&options.allNamespaces, "all-namespaces", options.allNamespaces, "If present, returns pods across all namespaces, ignoring the \"--namespace\" flag")
return cmd
}
func getPods(apiClient pb.ApiClient, options *getOptions) ([]string, error) {
req := &pb.ListPodsRequest{}
if !options.allNamespaces {
req.Namespace = options.namespace
}
resp, err := apiClient.ListPods(context.Background(), req)
if err != nil {
return nil, err
}
names := make([]string, 0)
for _, pod := range resp.GetPods() {
names = append(names, pod.Name)
}
return names, nil
}