jsonmessage.go 8.0 KB

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