github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/pkg/broadcaster/unbuffered.go (about)

     1  package broadcaster // import "github.com/docker/docker/pkg/broadcaster"
     2  
     3  import (
     4  	"io"
     5  	"sync"
     6  )
     7  
     8  // Unbuffered accumulates multiple io.WriteCloser by stream.
     9  type Unbuffered struct {
    10  	mu      sync.Mutex
    11  	writers []io.WriteCloser
    12  }
    13  
    14  // Add adds new io.WriteCloser.
    15  func (w *Unbuffered) Add(writer io.WriteCloser) {
    16  	w.mu.Lock()
    17  	w.writers = append(w.writers, writer)
    18  	w.mu.Unlock()
    19  }
    20  
    21  // Write writes bytes to all writers. Failed writers will be evicted during
    22  // this call.
    23  func (w *Unbuffered) Write(p []byte) (n int, err error) {
    24  	w.mu.Lock()
    25  	var evict []int
    26  	for i, sw := range w.writers {
    27  		if n, err := sw.Write(p); err != nil || n != len(p) {
    28  			// On error, evict the writer
    29  			evict = append(evict, i)
    30  		}
    31  	}
    32  	for n, i := range evict {
    33  		w.writers = append(w.writers[:i-n], w.writers[i-n+1:]...)
    34  	}
    35  	w.mu.Unlock()
    36  	return len(p), nil
    37  }
    38  
    39  // Clean closes and removes all writers. Last non-eol-terminated part of data
    40  // will be saved.
    41  func (w *Unbuffered) Clean() error {
    42  	w.mu.Lock()
    43  	for _, sw := range w.writers {
    44  		sw.Close()
    45  	}
    46  	w.writers = nil
    47  	w.mu.Unlock()
    48  	return nil
    49  }