jsonmessage.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package jsonmessage // import "github.com/docker/docker/pkg/jsonmessage"
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "time"
  8. units "github.com/docker/go-units"
  9. "github.com/moby/term"
  10. "github.com/morikuni/aec"
  11. )
  12. // RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to
  13. // ensure the formatted time isalways the same number of characters.
  14. const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00"
  15. // JSONError wraps a concrete Code and Message, `Code` is
  16. // is an integer error code, `Message` is the error message.
  17. type JSONError struct {
  18. Code int `json:"code,omitempty"`
  19. Message string `json:"message,omitempty"`
  20. }
  21. func (e *JSONError) Error() string {
  22. return e.Message
  23. }
  24. // JSONProgress describes a Progress. terminalFd is the fd of the current terminal,
  25. // Start is the initial value for the operation. Current is the current status and
  26. // value of the progress made towards Total. Total is the end value describing when
  27. // we made 100% progress for an operation.
  28. type JSONProgress struct {
  29. terminalFd uintptr
  30. Current int64 `json:"current,omitempty"`
  31. Total int64 `json:"total,omitempty"`
  32. Start int64 `json:"start,omitempty"`
  33. // If true, don't show xB/yB
  34. HideCounts bool `json:"hidecounts,omitempty"`
  35. Units string `json:"units,omitempty"`
  36. nowFunc func() time.Time
  37. winSize int
  38. }
  39. func (p *JSONProgress) String() string {
  40. var (
  41. width = p.width()
  42. pbBox string
  43. numbersBox string
  44. timeLeftBox string
  45. )
  46. if p.Current <= 0 && p.Total <= 0 {
  47. return ""
  48. }
  49. if p.Total <= 0 {
  50. switch p.Units {
  51. case "":
  52. return fmt.Sprintf("%8v", units.HumanSize(float64(p.Current)))
  53. default:
  54. return fmt.Sprintf("%d %s", p.Current, p.Units)
  55. }
  56. }
  57. percentage := int(float64(p.Current)/float64(p.Total)*100) / 2
  58. if percentage > 50 {
  59. percentage = 50
  60. }
  61. if width > 110 {
  62. // this number can't be negative gh#7136
  63. numSpaces := 0
  64. if 50-percentage > 0 {
  65. numSpaces = 50 - percentage
  66. }
  67. pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces))
  68. }
  69. switch {
  70. case p.HideCounts:
  71. case p.Units == "": // no units, use bytes
  72. current := units.HumanSize(float64(p.Current))
  73. total := units.HumanSize(float64(p.Total))
  74. numbersBox = fmt.Sprintf("%8v/%v", current, total)
  75. if p.Current > p.Total {
  76. // remove total display if the reported current is wonky.
  77. numbersBox = fmt.Sprintf("%8v", current)
  78. }
  79. default:
  80. numbersBox = fmt.Sprintf("%d/%d %s", p.Current, p.Total, p.Units)
  81. if p.Current > p.Total {
  82. // remove total display if the reported current is wonky.
  83. numbersBox = fmt.Sprintf("%d %s", p.Current, p.Units)
  84. }
  85. }
  86. if p.Current > 0 && p.Start > 0 && percentage < 50 {
  87. fromStart := p.now().Sub(time.Unix(p.Start, 0))
  88. perEntry := fromStart / time.Duration(p.Current)
  89. left := time.Duration(p.Total-p.Current) * perEntry
  90. left = (left / time.Second) * time.Second
  91. if width > 50 {
  92. timeLeftBox = " " + left.String()
  93. }
  94. }
  95. return pbBox + numbersBox + timeLeftBox
  96. }
  97. // shim for testing
  98. func (p *JSONProgress) now() time.Time {
  99. if p.nowFunc != nil {
  100. return p.nowFunc()
  101. }
  102. return time.Now().UTC()
  103. }
  104. // shim for testing
  105. func (p *JSONProgress) width() int {
  106. if p.winSize != 0 {
  107. return p.winSize
  108. }
  109. ws, err := term.GetWinsize(p.terminalFd)
  110. if err == nil {
  111. return int(ws.Width)
  112. }
  113. return 200
  114. }
  115. // JSONMessage defines a message struct. It describes
  116. // the created time, where it from, status, ID of the
  117. // message. It's used for docker events.
  118. type JSONMessage struct {
  119. Stream string `json:"stream,omitempty"`
  120. Status string `json:"status,omitempty"`
  121. Progress *JSONProgress `json:"progressDetail,omitempty"`
  122. ProgressMessage string `json:"progress,omitempty"` // deprecated
  123. ID string `json:"id,omitempty"`
  124. From string `json:"from,omitempty"`
  125. Time int64 `json:"time,omitempty"`
  126. TimeNano int64 `json:"timeNano,omitempty"`
  127. Error *JSONError `json:"errorDetail,omitempty"`
  128. ErrorMessage string `json:"error,omitempty"` // deprecated
  129. // Aux contains out-of-band data, such as digests for push signing and image id after building.
  130. Aux *json.RawMessage `json:"aux,omitempty"`
  131. }
  132. func clearLine(out io.Writer) {
  133. eraseMode := aec.EraseModes.All
  134. cl := aec.EraseLine(eraseMode)
  135. fmt.Fprint(out, cl)
  136. }
  137. func cursorUp(out io.Writer, l uint) {
  138. fmt.Fprint(out, aec.Up(l))
  139. }
  140. func cursorDown(out io.Writer, l uint) {
  141. fmt.Fprint(out, aec.Down(l))
  142. }
  143. // Display displays the JSONMessage to `out`. If `isTerminal` is true, it will erase the
  144. // entire current line when displaying the progressbar.
  145. func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error {
  146. if jm.Error != nil {
  147. return jm.Error
  148. }
  149. var endl string
  150. if isTerminal && jm.Stream == "" && jm.Progress != nil {
  151. clearLine(out)
  152. endl = "\r"
  153. fmt.Fprint(out, endl)
  154. } else if jm.Progress != nil && jm.Progress.String() != "" { // disable progressbar in non-terminal
  155. return nil
  156. }
  157. if jm.TimeNano != 0 {
  158. fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed))
  159. } else if jm.Time != 0 {
  160. fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed))
  161. }
  162. if jm.ID != "" {
  163. fmt.Fprintf(out, "%s: ", jm.ID)
  164. }
  165. if jm.From != "" {
  166. fmt.Fprintf(out, "(from %s) ", jm.From)
  167. }
  168. if jm.Progress != nil && isTerminal {
  169. fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl)
  170. } else if jm.ProgressMessage != "" { // deprecated
  171. fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl)
  172. } else if jm.Stream != "" {
  173. fmt.Fprintf(out, "%s%s", jm.Stream, endl)
  174. } else {
  175. fmt.Fprintf(out, "%s%s\n", jm.Status, endl)
  176. }
  177. return nil
  178. }
  179. // DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal`
  180. // describes if `out` is a terminal. If this is the case, it will print `\n` at the end of
  181. // each line and move the cursor while displaying.
  182. func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(JSONMessage)) error {
  183. var (
  184. dec = json.NewDecoder(in)
  185. ids = make(map[string]uint)
  186. )
  187. for {
  188. var diff uint
  189. var jm JSONMessage
  190. if err := dec.Decode(&jm); err != nil {
  191. if err == io.EOF {
  192. break
  193. }
  194. return err
  195. }
  196. if jm.Aux != nil {
  197. if auxCallback != nil {
  198. auxCallback(jm)
  199. }
  200. continue
  201. }
  202. if jm.Progress != nil {
  203. jm.Progress.terminalFd = terminalFd
  204. }
  205. if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") {
  206. line, ok := ids[jm.ID]
  207. if !ok {
  208. // NOTE: This approach of using len(id) to
  209. // figure out the number of lines of history
  210. // only works as long as we clear the history
  211. // when we output something that's not
  212. // accounted for in the map, such as a line
  213. // with no ID.
  214. line = uint(len(ids))
  215. ids[jm.ID] = line
  216. if isTerminal {
  217. fmt.Fprintf(out, "\n")
  218. }
  219. }
  220. diff = uint(len(ids)) - line
  221. if isTerminal {
  222. cursorUp(out, diff)
  223. }
  224. } else {
  225. // When outputting something that isn't progress
  226. // output, clear the history of previous lines. We
  227. // don't want progress entries from some previous
  228. // operation to be updated (for example, pull -a
  229. // with multiple tags).
  230. ids = make(map[string]uint)
  231. }
  232. err := jm.Display(out, isTerminal)
  233. if jm.ID != "" && isTerminal {
  234. cursorDown(out, diff)
  235. }
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. return nil
  241. }
  242. // Stream is an io.Writer for output with utilities to get the output's file
  243. // descriptor and to detect wether it's a terminal.
  244. //
  245. // it is subset of the streams.Out type in
  246. // https://pkg.go.dev/github.com/docker/cli@v20.10.17+incompatible/cli/streams#Out
  247. type Stream interface {
  248. io.Writer
  249. FD() uintptr
  250. IsTerminal() bool
  251. }
  252. // DisplayJSONMessagesToStream prints json messages to the output Stream. It is
  253. // used by the Docker CLI to print JSONMessage streams.
  254. func DisplayJSONMessagesToStream(in io.Reader, stream Stream, auxCallback func(JSONMessage)) error {
  255. return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback)
  256. }