github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/pkg/jsonmessage/jsonmessage.go (about)

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