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