github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/cmd/octsdb/telnet.go (about)

     1  // Copyright (c) 2016 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"net"
    10  
    11  	"github.com/aristanetworks/glog"
    12  )
    13  
    14  type telnetClient struct {
    15  	addr string
    16  	conn net.Conn
    17  }
    18  
    19  func newTelnetClient(addr string) OpenTSDBConn {
    20  	return &telnetClient{
    21  		addr: addr,
    22  	}
    23  }
    24  
    25  func readErrors(conn net.Conn) {
    26  	var buf [4096]byte
    27  	for {
    28  		// TODO: We should add a buffer to read line-by-line properly instead
    29  		// of using a fixed-size buffer and splitting on newlines manually.
    30  		n, err := conn.Read(buf[:])
    31  		if n == 0 {
    32  			return
    33  		} else if n > 0 {
    34  			for _, line := range bytes.Split(buf[:n], []byte{'\n'}) {
    35  				if s := string(line); s != "" {
    36  					glog.Info("tsd replied: ", s)
    37  				}
    38  			}
    39  		}
    40  		if err != nil {
    41  			return
    42  		}
    43  	}
    44  }
    45  
    46  func (c *telnetClient) Put(d *DataPoint) error {
    47  	return c.PutBytes([]byte(d.String()))
    48  }
    49  
    50  func (c *telnetClient) PutBytes(d []byte) error {
    51  	var err error
    52  	if c.conn == nil {
    53  		c.conn, err = net.Dial("tcp", c.addr)
    54  		if err != nil {
    55  			return err
    56  		}
    57  		go readErrors(c.conn)
    58  	}
    59  	_, err = c.conn.Write(d)
    60  	if err != nil {
    61  		c.conn.Close()
    62  		c.conn = nil
    63  	}
    64  	return err
    65  }