github.com/goern/docker@v1.9.0-rc1/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/term"
    11  	"github.com/docker/docker/pkg/timeutils"
    12  	"github.com/docker/docker/pkg/units"
    13  )
    14  
    15  // JSONError wraps a concrete Code and Message, `Code` is
    16  // is a 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 negetive 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  }
   106  
   107  // Display displays the JSONMessage to `out`. `isTerminal` describes if `out`
   108  // is a terminal. If this is the case, it will erase the entire current line
   109  // when dislaying the progressbar.
   110  func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error {
   111  	if jm.Error != nil {
   112  		if jm.Error.Code == 401 {
   113  			return fmt.Errorf("Authentication is required.")
   114  		}
   115  		return jm.Error
   116  	}
   117  	var endl string
   118  	if isTerminal && jm.Stream == "" && jm.Progress != nil {
   119  		// <ESC>[2K = erase entire current line
   120  		fmt.Fprintf(out, "%c[2K\r", 27)
   121  		endl = "\r"
   122  	} else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal
   123  		return nil
   124  	}
   125  	if jm.TimeNano != 0 {
   126  		fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(timeutils.RFC3339NanoFixed))
   127  	} else if jm.Time != 0 {
   128  		fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(timeutils.RFC3339NanoFixed))
   129  	}
   130  	if jm.ID != "" {
   131  		fmt.Fprintf(out, "%s: ", jm.ID)
   132  	}
   133  	if jm.From != "" {
   134  		fmt.Fprintf(out, "(from %s) ", jm.From)
   135  	}
   136  	if jm.Progress != nil && isTerminal {
   137  		fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl)
   138  	} else if jm.ProgressMessage != "" { //deprecated
   139  		fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl)
   140  	} else if jm.Stream != "" {
   141  		fmt.Fprintf(out, "%s%s", jm.Stream, endl)
   142  	} else {
   143  		fmt.Fprintf(out, "%s%s\n", jm.Status, endl)
   144  	}
   145  	return nil
   146  }
   147  
   148  // DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal`
   149  // describes if `out` is a terminal. If this is the case, it will print `\n` at the end of
   150  // each line and move the cursor while displaying.
   151  func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool) error {
   152  	var (
   153  		dec  = json.NewDecoder(in)
   154  		ids  = make(map[string]int)
   155  		diff = 0
   156  	)
   157  	for {
   158  		var jm JSONMessage
   159  		if err := dec.Decode(&jm); err != nil {
   160  			if err == io.EOF {
   161  				break
   162  			}
   163  			return err
   164  		}
   165  
   166  		if jm.Progress != nil {
   167  			jm.Progress.terminalFd = terminalFd
   168  		}
   169  		if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") {
   170  			line, ok := ids[jm.ID]
   171  			if !ok {
   172  				line = len(ids)
   173  				ids[jm.ID] = line
   174  				if isTerminal {
   175  					fmt.Fprintf(out, "\n")
   176  				}
   177  				diff = 0
   178  			} else {
   179  				diff = len(ids) - line
   180  			}
   181  			if jm.ID != "" && isTerminal {
   182  				// <ESC>[{diff}A = move cursor up diff rows
   183  				fmt.Fprintf(out, "%c[%dA", 27, diff)
   184  			}
   185  		}
   186  		err := jm.Display(out, isTerminal)
   187  		if jm.ID != "" && isTerminal {
   188  			// <ESC>[{diff}B = move cursor down diff rows
   189  			fmt.Fprintf(out, "%c[%dB", 27, diff)
   190  		}
   191  		if err != nil {
   192  			return err
   193  		}
   194  	}
   195  	return nil
   196  }