ps.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2020 Docker, Inc.
  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. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "strings"
  21. "text/tabwriter"
  22. "github.com/spf13/cobra"
  23. "github.com/docker/api/client"
  24. )
  25. func psCommand() *cobra.Command {
  26. opts := composeOptions{}
  27. psCmd := &cobra.Command{
  28. Use: "ps",
  29. RunE: func(cmd *cobra.Command, args []string) error {
  30. return runPs(cmd.Context(), opts)
  31. },
  32. }
  33. psCmd.Flags().StringVarP(&opts.Name, "project-name", "p", "", "Project name")
  34. psCmd.Flags().StringVar(&opts.WorkingDir, "workdir", ".", "Work dir")
  35. psCmd.Flags().StringArrayVarP(&opts.ConfigPaths, "file", "f", []string{}, "Compose configuration files")
  36. return psCmd
  37. }
  38. func runPs(ctx context.Context, opts composeOptions) error {
  39. c, err := client.New(ctx)
  40. if err != nil {
  41. return err
  42. }
  43. composeService := c.ComposeService()
  44. if composeService == nil {
  45. return errors.New("compose not implemented in current context")
  46. }
  47. options, err := opts.toProjectOptions()
  48. if err != nil {
  49. return err
  50. }
  51. serviceList, err := composeService.Ps(ctx, options)
  52. if err != nil {
  53. return err
  54. }
  55. err = printSection(os.Stdout, func(w io.Writer) {
  56. for _, service := range serviceList {
  57. fmt.Fprintf(w, "%s\t%s\t%d/%d\t%s\n", service.ID, service.Name, service.Replicas, service.Desired, strings.Join(service.Ports, ", "))
  58. }
  59. }, "ID", "NAME", "REPLICAS", "PORTS")
  60. return err
  61. }
  62. func printSection(out io.Writer, printer func(io.Writer), headers ...string) error {
  63. w := tabwriter.NewWriter(out, 20, 1, 3, ' ', 0)
  64. fmt.Fprintln(w, strings.Join(headers, "\t"))
  65. printer(w)
  66. return w.Flush()
  67. }