github.com/opsramp/moby@v1.13.1/pkg/jsonmessage/jsonmessage.go (about)

     1  package jsonmessage
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/docker/docker/pkg/jsonlog"
    11  	"github.com/docker/docker/pkg/term"
    12  	"github.com/docker/go-units"
    13  )
    14  
    15  // JSONError wraps a concrete Code and Message, `Code` is
    16  // is an integer error code, `Message` is the error message.
    17  type JSONError struct {
    18  	Code    int    `json:"code,omitempty"`
    19  	Message string `json:"message,omitempty"`
    20  }
    21  
    22  func (e *JSONError) Error() string {
    23  	return e.Message
    24  }
    25  
    26  // JSONProgress describes a Progress. terminalFd is the fd of the current terminal,
    27  // Start is the initial value for the operation. Current is the current status and
    28  // value of the progress made towards Total. Total is the end value describing when
    29  // we made 100% progress for an operation.
    30  type JSONProgress struct {
    31  	terminalFd uintptr
    32  	Current    int64 `json:"current,omitempty"`
    33  	Total      int64 `json:"total,omitempty"`
    34  	Start      int64 `json:"start,omitempty"`
    35  }
    36  
    37  func (p *JSONProgress) String() string {
    38  	var (
    39  		width       = 200
    40  		pbBox       string
    41  		numbersBox  string
    42  		timeLeftBox string
    43  	)
    44  
    45  	ws, err := term.GetWinsize(p.terminalFd)
    46  	if err == nil {
    47  		width = int(ws.Width)
    48  	}
    49  
    50  	if p.Current <= 0 && p.Total <= 0 {
    51  		return ""
    52  	}
    53  	current := units.HumanSize(float64(p.Current))
    54  	if p.Total <= 0 {
    55  		return fmt.Sprintf("%8v", current)
    56  	}
    57  	total := units.HumanSize(float64(p.Total))
    58  	percentage := int(float64(p.Current)/float64(p.Total)*100) / 2
    59  	if percentage > 50 {
    60  		percentage = 50
    61  	}
    62  	if width > 110 {
    63  		// this number can't be negative gh#7136
    64  		numSpaces := 0
    65  		if 50-percentage > 0 {
    66  			numSpaces = 50 - percentage
    67  		}
    68  		pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces))
    69  	}
    70  
    71  	numbersBox = fmt.Sprintf("%8v/%v", current, total)
    72  
    73  	if p.Current > p.Total {
    74  		// remove total display if the reported current is wonky.
    75  		numbersBox = fmt.Sprintf("%8v", current)
    76  	}
    77  
    78  	if p.Current > 0 && p.Start > 0 && percentage < 50 {
    79  		fromStart := time.Now().UTC().Sub(time.Unix(p.Start, 0))
    80  		perEntry := fromStart / time.Duration(p.Current)
    81  		left := time.Duration(p.Total-p.Current) * perEntry
    82  		left = (left / time.Second) * time.Second
    83  
    84  		if width > 50 {
    85  			timeLeftBox = " " + left.String()
    86  		}
    87  	}
    88  	return pbBox + numbersBox + timeLeftBox
    89  }
    90  
    91  // JSONMessage defines a message struct. It describes
    92  // the created time, where it from, status, ID of the
    93  // message. It's used for docker events.
    94  type JSONMessage struct {
    95  	Stream          string        `json:"stream,omitempty"`
    96  	Status          string        `json:"status,omitempty"`
    97  	Progress        *JSONProgress `json:"progressDetail,omitempty"`
    98  	ProgressMessage string        `json:"progress,omitempty"` //deprecated
    99  	ID              string        `json:"id,omitempty"`
   100  	From            string        `json:"from,omitempty"`
   101  	Time            int64         `json:"time,omitempty"`
   102  	TimeNano        int64         `json:"timeNano,omitempty"`
   103  	Error           *JSONError    `json:"errorDetail,omitempty"`
   104  	ErrorMessage    string        `json:"error,omitempty"` //deprecated
   105  	// Aux contains out-of-band data, such as digests for push signing.
   106  	Aux *json.RawMessage `json:"aux,omitempty"`
   107  }
   108  
   109  // Display displays the JSONMessage to `out`. `isTerminal` describes if `out`
   110  // is a terminal. If this is the case, it will erase the entire current line
   111  // when displaying the progressbar.
   112  func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error {
   113  	if jm.Error != nil {
   114  		if jm.Error.Code == 401 {
   115  			return fmt.Errorf("Authentication is required.")
   116  		}
   117  		return jm.Error
   118  	}
   119  	var endl string
   120  	if isTerminal && jm.Stream == "" && jm.Progress != nil {
   121  		// <ESC>[2K = erase entire current line
   122  		fmt.Fprintf(out, "%c[2K\r", 27)
   123  		endl = "\r"
   124  	} else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal
   125  		return nil
   126  	}
   127  	if jm.TimeNano != 0 {
   128  		fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(jsonlog.RFC3339NanoFixed))
   129  	} else if jm.Time != 0 {
   130  		fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(jsonlog.RFC3339NanoFixed))
   131  	}
   132  	if jm.ID != "" {
   133  		fmt.Fprintf(out, "%s: ", jm.ID)
   134  	}
   135  	if jm.From != "" {
   136  		fmt.Fprintf(out, "(from %s) ", jm.From)
   137  	}
   138  	if jm.Progress != nil && isTerminal {
   139  		fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl)
   140  	} else if jm.ProgressMessage != "" { //deprecated
   141  		fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl)
   142  	} else if jm.Stream != "" {
   143  		fmt.Fprintf(out, "%s%s", jm.Stream, endl)
   144  	} else {
   145  		fmt.Fprintf(out, "%s%s\n", jm.Status, endl)
   146  	}
   147  	return nil
   148  }
   149  
   150  // DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal`
   151  // describes if `out` is a terminal. If this is the case, it will print `\n` at the end of
   152  // each line and move the cursor while displaying.
   153  func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(*json.RawMessage)) error {
   154  	var (
   155  		dec = json.NewDecoder(in)
   156  		ids = make(map[string]int)
   157  	)
   158  	for {
   159  		diff := 0
   160  		var jm JSONMessage
   161  		if err := dec.Decode(&jm); err != nil {
   162  			if err == io.EOF {
   163  				break
   164  			}
   165  			return err
   166  		}
   167  
   168  		if jm.Aux != nil {
   169  			if auxCallback != nil {
   170  				auxCallback(jm.Aux)
   171  			}
   172  			continue
   173  		}
   174  
   175  		if jm.Progress != nil {
   176  			jm.Progress.terminalFd = terminalFd
   177  		}
   178  		if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") {
   179  			line, ok := ids[jm.ID]
   180  			if !ok {
   181  				// NOTE: This approach of using len(id) to
   182  				// figure out the number of lines of history
   183  				// only works as long as we clear the history
   184  				// when we output something that's not
   185  				// accounted for in the map, such as a line
   186  				// with no ID.
   187  				line = len(ids)
   188  				ids[jm.ID] = line
   189  				if isTerminal {
   190  					fmt.Fprintf(out, "\n")
   191  				}
   192  			}
   193  			diff = len(ids) - line
   194  			if isTerminal && diff > 0 {
   195  				fmt.Fprintf(out, "%c[%dA", 27, diff)
   196  			}
   197  		} else {
   198  			// When outputting something that isn't progress
   199  			// output, clear the history of previous lines. We
   200  			// don't want progress entries from some previous
   201  			// operation to be updated (for example, pull -a
   202  			// with multiple tags).
   203  			ids = make(map[string]int)
   204  		}
   205  		err := jm.Display(out, isTerminal)
   206  		if jm.ID != "" && isTerminal && diff > 0 {
   207  			fmt.Fprintf(out, "%c[%dB", 27, diff)
   208  		}
   209  		if err != nil {
   210  			return err
   211  		}
   212  	}
   213  	return nil
   214  }
   215  
   216  type stream interface {
   217  	io.Writer
   218  	FD() uintptr
   219  	IsTerminal() bool
   220  }
   221  
   222  // DisplayJSONMessagesToStream prints json messages to the output stream
   223  func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(*json.RawMessage)) error {
   224  	return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback)
   225  }