// pumpStdout handles reading data from stdout of the process and writing
// it to websocket connection.
431435
func pumpStdout(conn *websocket.Conn, stdout io.Reader, done chan struct{}) {
	go pinger(conn, done)
	defer func() {
		_ = conn.Close()
		close(done) // make sure to close the pinger when we are done.
	}()

	s := bufio.NewScanner(stdout)
	for s.Scan() {
		if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
			log.Println("[ERROR] failed to set write deadline: ", err)
		}
		if err := conn.WriteMessage(websocket.TextMessage, bytes.TrimSpace(s.Bytes())); err != nil {
			break
		}
	}
	if s.Err() != nil {
		err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, s.Err().Error()), time.Time{})
		if err != nil {
			log.Println("[ERROR] WriteControl failed: ", err)
		}
	}
}
727467
func (c *context) emit(e *event) {
	if e.Timestamp == 0 {
		e.Timestamp = fromDuration(time.Since(consts.start))
	}
	// sync.WaitGroup.Add() use atomic.AddUint64().
	globals.wg.Add(1)
	go func() {
		defer globals.wg.Done()
		e.Pid = c.pid
		e.Tid = 1
		// Locking is done in a goroutine to not create implicit synchronization
		// when tracing.
		globals.lockWriter.Lock()
		defer globals.lockWriter.Unlock()
		if globals.out != nil {
			if globals.first {
				globals.first = false
			} else {
				// Writing is done in a goroutine to reduce cost.
				if _, err := globals.out.Write([]byte(",")); err != nil {
					log.Printf("failed writing to trace: %s", err)
					go Stop()
					return
				}
			}
			if err := globals.encoder.Encode(e); err != nil {
				log.Printf("failed writing to trace: %s", err)
				go Stop()
			}
		}
	}()
}
1040538
func makeBreachedOutput(outpoint *wire.OutPoint,
	witnessType input.WitnessType,
	secondLevelScript []byte,
	signDescriptor *input.SignDescriptor,
	confHeight uint32) breachedOutput {

	amount := signDescriptor.Output.Value

	return breachedOutput{
		amt:                      btcutil.Amount(amount),
		outpoint:                 *outpoint,
		secondLevelWitnessScript: secondLevelScript,
		witnessType:              witnessType,
		signDesc:                 *signDescriptor,
		confHeight:               confHeight,
	}
}
1353926
func pumpStdin(conn *websocket.Conn, stdin io.WriteCloser) {
	// Setup our connection's websocket ping/pong handlers from our const values.
	defer conn.Close()
	conn.SetReadLimit(maxMessageSize)
	if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
		log.Println("[ERROR] failed to set read deadline: ", err)
	}
	conn.SetPongHandler(func(string) error {
		if err := conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
			log.Println("[ERROR] failed to set read deadline: ", err)
		}
		return nil
	})
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			break
		}
		message = append(message, '\n')
		if _, err := stdin.Write(message); err != nil {
			break
		}
	}
}
1276965
func NewOutputChannelBuffer(o Output, bufSize int) *OutputChannel {
	oc := &OutputChannel{
		input:  make(chan map[string]interface{}, bufSize),
		output: o,
		stop:   make(chan struct{}),
	}

	go func() {
		for {
			select {
			case msg := <-oc.input:
				if err := o.Write(msg); err != nil {
					critialLogger.Print("cannot write log message: ", err.Error())
				}
			case <-oc.stop:
				close(oc.stop)
				return
			}
		}
	}()

	return oc
}
709008
func NewStdoutClient(filename string, prefix string) *StdoutClient {
	var err error
	// allow %HOST% in the prefix string
	prefix = strings.Replace(prefix, "%HOST%", Hostname, 1)
	var fh *os.File
	if filename == "" {
		fh = os.Stdout
	} else {
		fh, err = os.OpenFile(filename, os.O_WRONLY, 0644)
		if nil != err {
			fmt.Printf("Cannot open file '%s' for stats output: %s\n", filename, err.Error())
		}
	}
	return &StdoutClient{
		FD:     fh,
		prefix: prefix,
		Logger: log.New(os.Stdout, "[StdoutClient] ", log.Ldate|log.Ltime),
	}
}
926654
func (w *spanWorker) bufferFunc(msg *spanMsg) (stop bool) {
	var lastTokenSeen = msg.token
	w.processMsg(msg)
outer:
	for len(w.buffer) < w.batchSize {
		select {
		case msg = <-w.input:
			if msg.token != lastTokenSeen {
				// if the token changes, then emit what ever is in the buffer before proceeding
				w.emit(lastTokenSeen)
				lastTokenSeen = msg.token
			}
			w.processMsg(msg)
		default:
			break outer // emit what ever is in the buffer if there are no more datapoints to read
		}
	}
	// emit the data in the buffer
	w.emit(msg.token)
	return
}
818128
func GetPumpsClient() *pumpcli.PumpsClient {
	pumpsClientLock.RLock()
	client := pumpsClient
	pumpsClientLock.RUnlock()
	return client
}
447189
func Websocket(route string, httpHandler websocket.Handler) {
	mainServer.Websocket(route, httpHandler)
}
692580
func (xc *CommonExchange) websocket() (websocketFeed, WebsocketProcessor) {
	xc.mtx.RLock()
	defer xc.mtx.RUnlock()
	return xc.ws, xc.wsProcessor
}
1132569
func NewBlockDataToJSONStdOut(m ...*sync.Mutex) *BlockDataToJSONStdOut {
	if len(m) > 1 {
		panic("Too many inputs.")
	}
	if len(m) > 0 {
		return &BlockDataToJSONStdOut{m[0]}
	}
	return &BlockDataToJSONStdOut{}
}
760322
func (b *BaseKvdb) LockTimedout(key string) {
	b.lock.Lock()
	defer b.lock.Unlock()
	b.lockTimedout(key)
}
791845
func (c *connector) Flush() error {
	buf := c.out

	written := 0
	all := buf.Readable()
	for {
		if written == all {
			break
		}

		n, err := c.conn.Write(buf.buf[buf.readerIndex+written : buf.writerIndex])
		if err != nil {
			for _, sm := range c.opts.middlewares {
				sm.WriteError(err, c)
			}

			c.writeRelease()
			return err
		}

		written += n
	}

	c.writeRelease()
	return nil
}
23723
func Stdout() io.Writer {
	stdout := colorable.NewColorableStdout()
	if stdout == os.Stdout {
		return os.Stdout
	}

	return &WinColorTerminal{output: stdout}
}
742995
func (c *Conn) Flush() error {
	if f, ok := c.w.(flusher); ok {
		return f.Flush()
	}
	return nil
}
1277370
func plumbCommand(cmd *exec.Cmd, channel ssh.Channel, sidechannel io.Writer) *sync.WaitGroup {
	var wg sync.WaitGroup
	inpipe, _ := cmd.StdinPipe()
	go func() {
		io.Copy(inpipe, channel)
		inpipe.Close()
	}()

	cmd.Stdout = channel
	cmd.Stderr = channel.Stderr()

	return &wg
}
197719
func Output(lv Level, calldepth int, s string) error {
	return std.Output(lv, calldepth, s)
}