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