print.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package task
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "text/tabwriter"
  7. "time"
  8. "golang.org/x/net/context"
  9. "github.com/docker/docker/api/client"
  10. "github.com/docker/docker/api/client/idresolver"
  11. "github.com/docker/engine-api/types/swarm"
  12. "github.com/docker/go-units"
  13. )
  14. const (
  15. psTaskItemFmt = "%s\t%s\t%s\t%s\t%s %s\t%s\t%s\n"
  16. )
  17. type tasksBySlot []swarm.Task
  18. func (t tasksBySlot) Len() int {
  19. return len(t)
  20. }
  21. func (t tasksBySlot) Swap(i, j int) {
  22. t[i], t[j] = t[j], t[i]
  23. }
  24. func (t tasksBySlot) Less(i, j int) bool {
  25. // Sort by slot.
  26. if t[i].Slot != t[j].Slot {
  27. return t[i].Slot < t[j].Slot
  28. }
  29. // If same slot, sort by most recent.
  30. return t[j].Meta.CreatedAt.Before(t[i].CreatedAt)
  31. }
  32. // Print task information in a table format
  33. func Print(dockerCli *client.DockerCli, ctx context.Context, tasks []swarm.Task, resolver *idresolver.IDResolver) error {
  34. sort.Stable(tasksBySlot(tasks))
  35. writer := tabwriter.NewWriter(dockerCli.Out(), 0, 4, 2, ' ', 0)
  36. // Ignore flushing errors
  37. defer writer.Flush()
  38. fmt.Fprintln(writer, strings.Join([]string{"ID", "NAME", "SERVICE", "IMAGE", "LAST STATE", "DESIRED STATE", "NODE"}, "\t"))
  39. for _, task := range tasks {
  40. serviceValue, err := resolver.Resolve(ctx, swarm.Service{}, task.ServiceID)
  41. if err != nil {
  42. return err
  43. }
  44. nodeValue, err := resolver.Resolve(ctx, swarm.Node{}, task.NodeID)
  45. if err != nil {
  46. return err
  47. }
  48. name := serviceValue
  49. if task.Slot > 0 {
  50. name = fmt.Sprintf("%s.%d", name, task.Slot)
  51. }
  52. fmt.Fprintf(
  53. writer,
  54. psTaskItemFmt,
  55. task.ID,
  56. name,
  57. serviceValue,
  58. task.Spec.ContainerSpec.Image,
  59. client.PrettyPrint(task.Status.State),
  60. units.HumanDuration(time.Since(task.Status.Timestamp)),
  61. client.PrettyPrint(task.DesiredState),
  62. nodeValue,
  63. )
  64. }
  65. return nil
  66. }