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