run.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/fatih/color"
  10. "github.com/porter-dev/porter/cli/cmd/api"
  11. "github.com/porter-dev/porter/cli/cmd/utils"
  12. "github.com/spf13/cobra"
  13. v1 "k8s.io/api/core/v1"
  14. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  15. "k8s.io/kubectl/pkg/util/term"
  16. "k8s.io/apimachinery/pkg/runtime"
  17. "k8s.io/apimachinery/pkg/runtime/schema"
  18. "k8s.io/client-go/kubernetes"
  19. "k8s.io/client-go/rest"
  20. "k8s.io/client-go/tools/clientcmd"
  21. "k8s.io/client-go/tools/remotecommand"
  22. )
  23. var namespace string
  24. // runCmd represents the "porter run" base command when called
  25. // without any subcommands
  26. var runCmd = &cobra.Command{
  27. Use: "run [release] -- COMMAND [args...]",
  28. Args: cobra.MinimumNArgs(2),
  29. Short: "Runs a command inside a connected cluster container.",
  30. Run: func(cmd *cobra.Command, args []string) {
  31. err := checkLoginAndRun(args, run)
  32. if err != nil {
  33. os.Exit(1)
  34. }
  35. },
  36. }
  37. var existingPod bool
  38. func init() {
  39. rootCmd.AddCommand(runCmd)
  40. runCmd.PersistentFlags().StringVar(
  41. &namespace,
  42. "namespace",
  43. "default",
  44. "namespace of release to connect to",
  45. )
  46. runCmd.PersistentFlags().BoolVarP(
  47. &existingPod,
  48. "existing_pod",
  49. "e",
  50. false,
  51. "whether to connect to an existing pod",
  52. )
  53. }
  54. func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
  55. color.New(color.FgGreen).Println("Running", strings.Join(args[1:], " "), "for release", args[0])
  56. podsSimple, err := getPods(client, namespace, args[0])
  57. if err != nil {
  58. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  59. }
  60. // if length of pods is 0, throw error
  61. var selectedPod podSimple
  62. if len(podsSimple) == 0 {
  63. return fmt.Errorf("At least one pod must exist in this deployment.")
  64. } else if len(podsSimple) == 1 || !existingPod {
  65. selectedPod = podsSimple[0]
  66. } else {
  67. podNames := make([]string, 0)
  68. for _, podSimple := range podsSimple {
  69. podNames = append(podNames, podSimple.Name)
  70. }
  71. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  72. if err != nil {
  73. return err
  74. }
  75. // find selected pod
  76. for _, podSimple := range podsSimple {
  77. if selectedPodName == podSimple.Name {
  78. selectedPod = podSimple
  79. }
  80. }
  81. }
  82. var selectedContainerName string
  83. // if the selected pod has multiple container, spawn selector
  84. if len(selectedPod.ContainerNames) == 0 {
  85. return fmt.Errorf("At least one pod must exist in this deployment.")
  86. } else if len(selectedPod.ContainerNames) == 1 {
  87. selectedContainerName = selectedPod.ContainerNames[0]
  88. } else {
  89. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  90. if err != nil {
  91. return err
  92. }
  93. selectedContainerName = selectedContainer
  94. }
  95. config := &PorterRunSharedConfig{
  96. Client: client,
  97. }
  98. err = config.setSharedConfig()
  99. if err != nil {
  100. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  101. }
  102. if existingPod {
  103. return executeRun(config, namespace, selectedPod.Name, selectedContainerName, args[1:])
  104. }
  105. return executeRunEphemeral(config, namespace, selectedPod.Name, selectedContainerName, args[1:])
  106. }
  107. type PorterRunSharedConfig struct {
  108. Client *api.Client
  109. RestConf *rest.Config
  110. Clientset *kubernetes.Clientset
  111. RestClient *rest.RESTClient
  112. }
  113. func (p *PorterRunSharedConfig) setSharedConfig() error {
  114. pID := config.Project
  115. cID := config.Cluster
  116. kubeResp, err := p.Client.GetKubeconfig(context.TODO(), pID, cID)
  117. if err != nil {
  118. return err
  119. }
  120. kubeBytes := kubeResp.Kubeconfig
  121. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  122. if err != nil {
  123. return err
  124. }
  125. restConf, err := cmdConf.ClientConfig()
  126. if err != nil {
  127. return err
  128. }
  129. restConf.GroupVersion = &schema.GroupVersion{
  130. Group: "api",
  131. Version: "v1",
  132. }
  133. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  134. p.RestConf = restConf
  135. clientset, err := kubernetes.NewForConfig(restConf)
  136. if err != nil {
  137. return err
  138. }
  139. p.Clientset = clientset
  140. restClient, err := rest.RESTClientFor(restConf)
  141. if err != nil {
  142. return err
  143. }
  144. p.RestClient = restClient
  145. return nil
  146. }
  147. type podSimple struct {
  148. Name string
  149. ContainerNames []string
  150. }
  151. func getPods(client *api.Client, namespace, releaseName string) ([]podSimple, error) {
  152. pID := config.Project
  153. cID := config.Cluster
  154. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  155. if err != nil {
  156. return nil, err
  157. }
  158. res := make([]podSimple, 0)
  159. for _, pod := range resp {
  160. containerNames := make([]string, 0)
  161. for _, container := range pod.Spec.Containers {
  162. containerNames = append(containerNames, container.Name)
  163. }
  164. res = append(res, podSimple{
  165. Name: pod.ObjectMeta.Name,
  166. ContainerNames: containerNames,
  167. })
  168. }
  169. return res, nil
  170. }
  171. func executeRun(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  172. req := config.RestClient.Post().
  173. Resource("pods").
  174. Name(name).
  175. Namespace(namespace).
  176. SubResource("exec")
  177. for _, arg := range args {
  178. req.Param("command", arg)
  179. }
  180. req.Param("stdin", "true")
  181. req.Param("stdout", "true")
  182. req.Param("tty", "true")
  183. req.Param("container", container)
  184. t := term.TTY{
  185. In: os.Stdin,
  186. Out: os.Stdout,
  187. Raw: true,
  188. }
  189. fn := func() error {
  190. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  191. if err != nil {
  192. return err
  193. }
  194. return exec.Stream(remotecommand.StreamOptions{
  195. Stdin: os.Stdin,
  196. Stdout: os.Stdout,
  197. Stderr: os.Stderr,
  198. Tty: true,
  199. })
  200. }
  201. if err := t.Safe(fn); err != nil {
  202. return err
  203. }
  204. return nil
  205. }
  206. func executeRunEphemeral(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  207. existing, err := getExistingPod(config, name, namespace)
  208. if err != nil {
  209. return err
  210. }
  211. newPod, err := createPodFromExisting(config, existing, args)
  212. if err != nil {
  213. return err
  214. }
  215. podName := newPod.ObjectMeta.Name
  216. t := term.TTY{
  217. In: os.Stdin,
  218. Out: os.Stdout,
  219. Raw: true,
  220. }
  221. fn := func() error {
  222. req := config.RestClient.Post().
  223. Resource("pods").
  224. Name(podName).
  225. Namespace("default").
  226. SubResource("attach")
  227. req.Param("stdin", "true")
  228. req.Param("stdout", "true")
  229. req.Param("tty", "true")
  230. req.Param("container", container)
  231. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  232. if err != nil {
  233. return err
  234. }
  235. return exec.Stream(remotecommand.StreamOptions{
  236. Stdin: os.Stdin,
  237. Stdout: os.Stdout,
  238. Stderr: os.Stderr,
  239. Tty: true,
  240. })
  241. }
  242. color.New(color.FgYellow).Println("Attempting connection to the container, this may take up to 10 seconds. If you don't see a command prompt, try pressing enter.")
  243. for i := 0; i < 5; i++ {
  244. err = t.Safe(fn)
  245. if err == nil {
  246. break
  247. }
  248. time.Sleep(2 * time.Second)
  249. // ugly way to catch no TTY errors, such as when running command "echo \"hello\""
  250. if i == 4 && err != nil {
  251. color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:\n")
  252. var writtenBytes int64
  253. writtenBytes, err = pipePodLogsToStdout(config, namespace, podName, container, false)
  254. if writtenBytes == 0 {
  255. color.New(color.FgYellow).Println("Could not get logs. Pod events:\n")
  256. err = pipeEventsToStdout(config, namespace, podName, container, false)
  257. }
  258. }
  259. }
  260. // delete the ephemeral pod
  261. deletePod(config, podName, namespace)
  262. return err
  263. }
  264. func pipePodLogsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) (int64, error) {
  265. podLogOpts := v1.PodLogOptions{
  266. Container: container,
  267. Follow: follow,
  268. }
  269. req := config.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  270. podLogs, err := req.Stream(
  271. context.Background(),
  272. )
  273. if err != nil {
  274. return 0, err
  275. }
  276. defer podLogs.Close()
  277. return io.Copy(os.Stdout, podLogs)
  278. }
  279. func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
  280. // creates the clientset
  281. resp, err := config.Clientset.CoreV1().Events(namespace).List(
  282. context.TODO(),
  283. metav1.ListOptions{
  284. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  285. },
  286. )
  287. if err != nil {
  288. return err
  289. }
  290. for _, event := range resp.Items {
  291. color.New(color.FgRed).Println(event.Message)
  292. }
  293. return nil
  294. }
  295. func getExistingPod(config *PorterRunSharedConfig, name, namespace string) (*v1.Pod, error) {
  296. return config.Clientset.CoreV1().Pods(namespace).Get(
  297. context.Background(),
  298. name,
  299. metav1.GetOptions{},
  300. )
  301. }
  302. func deletePod(config *PorterRunSharedConfig, name, namespace string) error {
  303. // update the config in case the operation has taken longer than token expiry time
  304. config.setSharedConfig()
  305. err := config.Clientset.CoreV1().Pods(namespace).Delete(
  306. context.Background(),
  307. name,
  308. metav1.DeleteOptions{},
  309. )
  310. if err != nil {
  311. color.New(color.FgRed).Println("Could not delete ephemeral pod: %s", err.Error())
  312. return err
  313. }
  314. color.New(color.FgGreen).Println("Sucessfully deleted ephemeral pod")
  315. return nil
  316. }
  317. func createPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args []string) (*v1.Pod, error) {
  318. newPod := existing.DeepCopy()
  319. // only copy the pod spec, overwrite metadata
  320. newPod.ObjectMeta = metav1.ObjectMeta{
  321. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  322. Namespace: existing.ObjectMeta.Namespace,
  323. }
  324. newPod.Status = v1.PodStatus{}
  325. // set restart policy to never
  326. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  327. // change the command in the pod to the passed in pod command
  328. cmdRoot := args[0]
  329. cmdArgs := make([]string, 0)
  330. if len(args) > 1 {
  331. cmdArgs = args[1:]
  332. }
  333. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  334. newPod.Spec.Containers[0].Args = cmdArgs
  335. newPod.Spec.Containers[0].TTY = true
  336. newPod.Spec.Containers[0].Stdin = true
  337. newPod.Spec.Containers[0].StdinOnce = true
  338. newPod.Spec.NodeName = ""
  339. // create the pod and return it
  340. return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  341. context.Background(),
  342. newPod,
  343. metav1.CreateOptions{},
  344. )
  345. }