top.go 2.2 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. "text/tabwriter"
  22. "github.com/spf13/cobra"
  23. "github.com/docker/compose-cli/api/client"
  24. )
  25. type topOptions struct {
  26. *projectOptions
  27. }
  28. func topCommand(p *projectOptions) *cobra.Command {
  29. opts := topOptions{
  30. projectOptions: p,
  31. }
  32. topCmd := &cobra.Command{
  33. Use: "top",
  34. Short: "Display the running processes",
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. return runTop(cmd.Context(), opts, args)
  37. },
  38. }
  39. return topCmd
  40. }
  41. func runTop(ctx context.Context, opts topOptions, services []string) error {
  42. c, err := client.New(ctx)
  43. if err != nil {
  44. return err
  45. }
  46. projectName, err := opts.toProjectName()
  47. if err != nil {
  48. return err
  49. }
  50. containers, err := c.ComposeService().Top(ctx, projectName, services)
  51. if err != nil {
  52. return err
  53. }
  54. sort.Slice(containers, func(i, j int) bool {
  55. return containers[i].Name < containers[j].Name
  56. })
  57. for _, container := range containers {
  58. fmt.Printf("%s\n", container.Name)
  59. err := psPrinter(os.Stdout, func(w io.Writer) {
  60. for _, proc := range container.Processes {
  61. info := []interface{}{}
  62. for _, p := range proc {
  63. info = append(info, p)
  64. }
  65. _, _ = fmt.Fprintf(w, strings.Repeat("%s\t", len(info))+"\n", info...)
  66. }
  67. fmt.Fprintln(w)
  68. },
  69. container.Titles...)
  70. if err != nil {
  71. return err
  72. }
  73. }
  74. return nil
  75. }
  76. func psPrinter(out io.Writer, printer func(writer io.Writer), headers ...string) error {
  77. w := tabwriter.NewWriter(out, 5, 1, 3, ' ', 0)
  78. _, _ = fmt.Fprintln(w, strings.Join(headers, "\t"))
  79. printer(w)
  80. return w.Flush()
  81. }