|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "fuse/pkg/kubectl" |
| 7 | + "github.com/spf13/cobra" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + // command itself |
| 12 | + execCmd = &cobra.Command{ |
| 13 | + Use: "exec", |
| 14 | + Short: "Execute command in pods by selector", |
| 15 | + Long: ``, |
| 16 | + RunE: execCmdHandler, |
| 17 | + } |
| 18 | + |
| 19 | + // Flags |
| 20 | + execCommand = "" |
| 21 | + deploymentSelectors = make([]string, 0) |
| 22 | +) |
| 23 | + |
| 24 | +// register all flags |
| 25 | +func init() { |
| 26 | + execCmd.Flags().StringSliceVar(&deploymentSelectors, "deployments", []string{}, "Deployment selector (e.g. app=myapp)") |
| 27 | + execCmd.Flags().StringVar(&execCommand, "command", "", "Command to execute") |
| 28 | + RootCmd.AddCommand(execCmd) |
| 29 | +} |
| 30 | + |
| 31 | +// command handler |
| 32 | +func execCmdHandler(cmd *cobra.Command, args []string) error { |
| 33 | + if execCommand == "" { |
| 34 | + return errors.New("No command provided") |
| 35 | + } |
| 36 | + |
| 37 | + if len(deploymentSelectors) == 0 { |
| 38 | + // get deployment by selector |
| 39 | + return errors.New("No deployment selectors provided") |
| 40 | + } |
| 41 | + |
| 42 | + // get deployment list by selector |
| 43 | + deploymentList := make([]kubectl.Deployment, 0) |
| 44 | + for _, s := range deploymentSelectors { |
| 45 | + resourceList, err := kubectl.CommandDeploymentListBySelector(namespaceFlag, []string{s}).RunAndParse() |
| 46 | + if err != nil { |
| 47 | + return err |
| 48 | + } |
| 49 | + |
| 50 | + dl := resourceList.ToDeploymentList() |
| 51 | + deploymentList = append(deploymentList, dl...) |
| 52 | + } |
| 53 | + |
| 54 | + podList := make([]kubectl.Pod, 0) |
| 55 | + |
| 56 | + // for each deployment, find all pods |
| 57 | + for _, d := range deploymentList { |
| 58 | + podResourceList, err := kubectl.CommandPodListBySelector(namespaceFlag, d.GetPodSelector()).RunAndParse() |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + |
| 63 | + pl := podResourceList.ToPodList() |
| 64 | + podList = append(podList, pl...) |
| 65 | + } |
| 66 | + |
| 67 | + // for each container in pod, exec provided command |
| 68 | + for _, pod := range podList { |
| 69 | + for _, c := range pod.Spec.Containers { |
| 70 | + podName := pod.GetName() |
| 71 | + |
| 72 | + stdout, err := kubectl.CommandExec(namespaceFlag, podName, c.Name, execCommand).RunPlain() |
| 73 | + fmt.Printf("===> Pod: %s, Container: %s:\n", pod.GetKey(), c.Name) |
| 74 | + fmt.Println(string(stdout)) |
| 75 | + |
| 76 | + if err != nil { |
| 77 | + return err |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + return nil |
| 83 | +} |
0 commit comments