jsonmessage.go 9.1 KB

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