github.com/galamsiva2020/kubernetes-heapster-monitoring@v0.0.0-20210823134957-3c1baa7c1e70/metrics/sinks/statsd/statsd_client.go (about) 1 // Copyright 2016 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package statsd 16 17 import ( 18 "bytes" 19 "fmt" 20 "github.com/golang/glog" 21 "net" 22 ) 23 24 type statsdClient interface { 25 open() error 26 close() error 27 send(messages []string) error 28 } 29 30 type statsdClientImpl struct { 31 host string 32 numMetricsPerMsg int 33 conn net.Conn 34 } 35 36 func (client *statsdClientImpl) open() error { 37 var err error 38 client.conn, err = net.Dial("udp", client.host) 39 if err != nil { 40 glog.Errorf("Failed to open statsd client connection : %v", err) 41 } else { 42 glog.V(2).Infof("statsd client connection opened : %+v", client.conn) 43 } 44 return err 45 } 46 47 func (client *statsdClientImpl) close() error { 48 if client.conn == nil { 49 glog.Info("statsd client connection already closed") 50 return nil 51 } 52 err := client.conn.Close() 53 client.conn = nil 54 glog.V(2).Infof("statsd client connection closed") 55 return err 56 } 57 58 func (client *statsdClientImpl) send(messages []string) error { 59 if client.conn == nil { 60 err := client.open() 61 if err != nil { 62 return fmt.Errorf("send() failed - %v", err) 63 } 64 } 65 var numMetrics = 0 66 var err, tmpErr error 67 buf := bytes.NewBufferString("") 68 for _, msg := range messages { 69 buf.WriteString(fmt.Sprintf("%s\n", msg)) 70 numMetrics++ 71 if numMetrics >= client.numMetricsPerMsg { 72 _, tmpErr = client.conn.Write(buf.Bytes()) 73 if tmpErr != nil { 74 err = tmpErr 75 } 76 buf.Reset() 77 numMetrics = 0 78 } 79 } 80 if buf.Len() > 0 { 81 _, tmpErr = client.conn.Write(buf.Bytes()) 82 if tmpErr != nil { 83 err = tmpErr 84 } 85 } 86 return err 87 } 88 89 func NewStatsdClient(host string, numMetricsPerMsg int) (client statsdClient, err error) { 90 if numMetricsPerMsg <= 0 { 91 return nil, fmt.Errorf("numMetricsPerMsg should be a positive integer : %d", numMetricsPerMsg) 92 } 93 glog.V(2).Infof("statsd client created") 94 return &statsdClientImpl{host: host, numMetricsPerMsg: numMetricsPerMsg}, nil 95 }