cluster.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "text/tabwriter"
  7. "github.com/porter-dev/porter/cli/cmd/api"
  8. "github.com/spf13/cobra"
  9. )
  10. // clusterCmd represents the "porter cluster" base command when called
  11. // without any subcommands
  12. var clusterCmd = &cobra.Command{
  13. Use: "cluster",
  14. Short: "Commands that read from a connected cluster",
  15. }
  16. var listClusterNSCmd = &cobra.Command{
  17. Use: "namespace list",
  18. Short: "Lists the namespaces in a cluster (used for testing connection)",
  19. Run: func(cmd *cobra.Command, args []string) {
  20. err := checkLoginAndRun(args, listNamespaces)
  21. if err != nil {
  22. os.Exit(1)
  23. }
  24. },
  25. }
  26. func init() {
  27. rootCmd.AddCommand(clusterCmd)
  28. clusterCmd.PersistentFlags().UintVar(
  29. &clusterID,
  30. "cluster-id",
  31. getClusterID(),
  32. "id of the cluster",
  33. )
  34. clusterCmd.AddCommand(listClusterNSCmd)
  35. }
  36. func listNamespaces(user *api.AuthCheckResponse, client *api.Client, args []string) error {
  37. pID := getProjectID()
  38. clusters, err := client.ListProjectClusters(context.Background(), pID)
  39. if err != nil {
  40. return err
  41. }
  42. // get the service account based on the cluster id
  43. cID := getClusterID()
  44. var saID uint = 0
  45. for _, cluster := range clusters {
  46. if cluster.ID == cID {
  47. saID = cluster.ServiceAccountID
  48. }
  49. }
  50. if saID == 0 {
  51. return fmt.Errorf("could not find cluster with id %d", cID)
  52. }
  53. // get the list of namespaces
  54. namespaces, err := client.GetK8sNamespaces(
  55. context.Background(),
  56. pID,
  57. saID,
  58. cID,
  59. )
  60. if err != nil {
  61. return err
  62. }
  63. w := new(tabwriter.Writer)
  64. w.Init(os.Stdout, 3, 8, 0, '\t', tabwriter.AlignRight)
  65. fmt.Fprintf(w, "%s\t%s\n", "NAME", "STATUS")
  66. for _, namespace := range namespaces.Items {
  67. fmt.Fprintf(w, "%s\t%s\n", namespace.Name, namespace.Status.Phase)
  68. }
  69. w.Flush()
  70. return nil
  71. }