logs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/porter-dev/porter/cli/cmd/api"
  6. "github.com/porter-dev/porter/cli/cmd/utils"
  7. "github.com/spf13/cobra"
  8. )
  9. // logsCmd represents the "porter logs" base command when called
  10. // without any subcommands
  11. var logsCmd = &cobra.Command{
  12. Use: "logs [release]",
  13. Short: "Logs the output from a given application.",
  14. Run: func(cmd *cobra.Command, args []string) {
  15. err := checkLoginAndRun(args, logs)
  16. if err != nil {
  17. os.Exit(1)
  18. }
  19. },
  20. }
  21. var follow bool
  22. func init() {
  23. rootCmd.AddCommand(logsCmd)
  24. logsCmd.PersistentFlags().StringVar(
  25. &namespace,
  26. "namespace",
  27. "default",
  28. "namespace of release to connect to",
  29. )
  30. logsCmd.PersistentFlags().BoolVarP(
  31. &follow,
  32. "follow",
  33. "f",
  34. false,
  35. "specify if the logs should be streamed",
  36. )
  37. }
  38. func logs(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
  39. podsSimple, err := getPods(client, namespace, args[0])
  40. if err != nil {
  41. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  42. }
  43. // if length of pods is 0, throw error
  44. var selectedPod podSimple
  45. if len(podsSimple) == 0 {
  46. return fmt.Errorf("At least one pod must exist in this deployment.")
  47. } else if len(podsSimple) == 1 {
  48. selectedPod = podsSimple[0]
  49. } else {
  50. podNames := make([]string, 0)
  51. for _, podSimple := range podsSimple {
  52. podNames = append(podNames, podSimple.Name)
  53. }
  54. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  55. if err != nil {
  56. return err
  57. }
  58. // find selected pod
  59. for _, podSimple := range podsSimple {
  60. if selectedPodName == podSimple.Name {
  61. selectedPod = podSimple
  62. }
  63. }
  64. }
  65. var selectedContainerName string
  66. // if the selected pod has multiple container, spawn selector
  67. if len(selectedPod.ContainerNames) == 0 {
  68. return fmt.Errorf("At least one pod must exist in this deployment.")
  69. } else if len(selectedPod.ContainerNames) == 1 {
  70. selectedContainerName = selectedPod.ContainerNames[0]
  71. } else {
  72. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  73. if err != nil {
  74. return err
  75. }
  76. selectedContainerName = selectedContainer
  77. }
  78. restConf, err := getRESTConfig(client)
  79. if err != nil {
  80. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  81. }
  82. return pipePodLogsToStdout(restConf, namespace, selectedPod.Name, selectedContainerName, follow)
  83. }