ps.go 2.1 KB

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