github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/jsonmessage/jsonmessage.go (about)

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