github.com/whiteboxio/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/corev1alpha1/actor/sink_head_unix.go (about)

     1  package actor
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"time"
     7  )
     8  
     9  const (
    10  	UnixConnTimeout = 5 * time.Second
    11  )
    12  
    13  type UnixConnBuilder func(*net.UnixAddr, time.Duration) (net.Conn, error)
    14  
    15  var DefaultUnixConnBuilder = func(unixaddr *net.UnixAddr, timeout time.Duration) (net.Conn, error) {
    16  	return net.DialTimeout("unix", unixaddr.String(), timeout)
    17  }
    18  
    19  type SinkHeadUnix struct {
    20  	addr        *net.UnixAddr
    21  	conn        net.Conn
    22  	connbuilder UnixConnBuilder
    23  
    24  	ConnectTimeout time.Duration
    25  	WriteTimeout   time.Duration
    26  }
    27  
    28  var _ (SinkHead) = (*SinkHeadUnix)(nil)
    29  
    30  func NewSinkHeadUnix(unixaddr *net.UnixAddr) (*SinkHeadUnix, error) {
    31  	return &SinkHeadUnix{
    32  		addr:           unixaddr,
    33  		connbuilder:    DefaultUnixConnBuilder,
    34  		ConnectTimeout: UnixConnTimeout,
    35  	}, nil
    36  }
    37  
    38  func (h *SinkHeadUnix) Connect() error {
    39  	conn, err := h.connbuilder(h.addr, h.ConnectTimeout)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	h.conn = conn
    44  
    45  	return nil
    46  }
    47  
    48  func (h *SinkHeadUnix) Start() error {
    49  	return nil
    50  }
    51  
    52  func (h *SinkHeadUnix) Stop() error {
    53  	if h.conn != nil {
    54  		return h.conn.Close()
    55  	}
    56  	return nil
    57  }
    58  
    59  func (h *SinkHeadUnix) Write(data []byte) (int, error, bool) {
    60  	if h.conn == nil {
    61  		return 0, fmt.Errorf("unix sink head conn is nil"), true
    62  	}
    63  	l := len(data)
    64  	buf := make([]byte, l+2)
    65  	copy(buf, data)
    66  	copy(buf[l:], []byte("\r\n"))
    67  	n, err := h.conn.Write(buf)
    68  	rec := false
    69  	if err != nil {
    70  		h.conn = nil
    71  		rec = true
    72  	}
    73  
    74  	return n, err, rec
    75  }