telnet.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. package main
  5. import (
  6. "bytes"
  7. "net"
  8. "notabug.org/themusicgod1/glog"
  9. )
  10. type telnetClient struct {
  11. addr string
  12. conn net.Conn
  13. }
  14. func newTelnetClient(addr string) OpenTSDBConn {
  15. return &telnetClient{
  16. addr: addr,
  17. }
  18. }
  19. func readErrors(conn net.Conn) {
  20. var buf [4096]byte
  21. for {
  22. // TODO: We should add a buffer to read line-by-line properly instead
  23. // of using a fixed-size buffer and splitting on newlines manually.
  24. n, err := conn.Read(buf[:])
  25. if n == 0 {
  26. return
  27. } else if n > 0 {
  28. for _, line := range bytes.Split(buf[:n], []byte{'\n'}) {
  29. if s := string(line); s != "" {
  30. glog.Info("tsd replied: ", s)
  31. }
  32. }
  33. }
  34. if err != nil {
  35. return
  36. }
  37. }
  38. }
  39. func (c *telnetClient) Put(d *DataPoint) error {
  40. return c.PutBytes([]byte(d.String()))
  41. }
  42. func (c *telnetClient) PutBytes(d []byte) error {
  43. var err error
  44. if c.conn == nil {
  45. c.conn, err = net.Dial("tcp", c.addr)
  46. if err != nil {
  47. return err
  48. }
  49. go readErrors(c.conn)
  50. }
  51. _, err = c.conn.Write(d)
  52. if err != nil {
  53. c.conn.Close()
  54. c.conn = nil
  55. }
  56. return err
  57. }