ps.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "sort"
  20. "strings"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose-cli/api/client"
  23. "github.com/docker/compose-cli/cli/formatter"
  24. )
  25. type psOptions struct {
  26. *projectOptions
  27. Format string
  28. Quiet bool
  29. }
  30. func psCommand(p *projectOptions) *cobra.Command {
  31. opts := psOptions{
  32. projectOptions: p,
  33. }
  34. psCmd := &cobra.Command{
  35. Use: "ps",
  36. Short: "List containers",
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. return runPs(cmd.Context(), opts)
  39. },
  40. }
  41. psCmd.Flags().StringVar(&opts.Format, "format", "pretty", "Format the output. Values: [pretty | json].")
  42. psCmd.Flags().BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs")
  43. return psCmd
  44. }
  45. func runPs(ctx context.Context, opts psOptions) error {
  46. c, err := client.NewWithDefaultLocalBackend(ctx)
  47. if err != nil {
  48. return err
  49. }
  50. projectName, err := opts.toProjectName()
  51. if err != nil {
  52. return err
  53. }
  54. containers, err := c.ComposeService().Ps(ctx, projectName)
  55. if err != nil {
  56. return err
  57. }
  58. if opts.Quiet {
  59. for _, s := range containers {
  60. fmt.Println(s.ID)
  61. }
  62. return nil
  63. }
  64. sort.Slice(containers, func(i, j int) bool {
  65. return containers[i].Name < containers[j].Name
  66. })
  67. return formatter.Print(containers, opts.Format, os.Stdout,
  68. func(w io.Writer) {
  69. for _, container := range containers {
  70. var ports []string
  71. for _, p := range container.Publishers {
  72. if p.URL == "" {
  73. ports = append(ports, fmt.Sprintf("%d/%s", p.TargetPort, p.Protocol))
  74. } else {
  75. ports = append(ports, fmt.Sprintf("%s->%d/%s", p.URL, p.TargetPort, p.Protocol))
  76. }
  77. }
  78. _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", container.Name, container.Service, container.State, container.Health, strings.Join(ports, ", "))
  79. }
  80. },
  81. "NAME", "SERVICE", "STATE", "HEALTH", "PORTS")
  82. }