jsonmessage.go 8.7 KB

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