run.go 11 KB

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