├── LICENSE ├── README.md ├── zabbix.go └── zabbix_test.go /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Alexey Dubkov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | go-zabbix 2 | ============================================================================== 3 | Golang package, implement zabbix sender protocol for send metrics to zabbix. 4 | 5 | Example: 6 | ```go 7 | package main 8 | 9 | import ( 10 | "time" 11 | . "github.com/blacked/go-zabbix" 12 | ) 13 | 14 | const ( 15 | defaultHost = `localhost` 16 | defaultPort = 10051 17 | ) 18 | 19 | func main() { 20 | var metrics []*Metric 21 | metrics = append(metrics, NewMetric("localhost", "cpu", "1.22", time.Now().Unix())) 22 | metrics = append(metrics, NewMetric("localhost", "status", "OK")) 23 | 24 | // Create instance of Packet class 25 | packet := NewPacket(metrics) 26 | 27 | // Send packet to zabbix 28 | z := NewSender(defaultHost, defaultPort) 29 | z.Send(packet) 30 | } 31 | ``` 32 | -------------------------------------------------------------------------------- /zabbix.go: -------------------------------------------------------------------------------- 1 | // Package implement zabbix sender protocol for send metrics to zabbix. 2 | package zabbix 3 | 4 | import ( 5 | "encoding/binary" 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "net" 10 | "time" 11 | ) 12 | 13 | // Metric class. 14 | type Metric struct { 15 | Host string `json:"host"` 16 | Key string `json:"key"` 17 | Value string `json:"value"` 18 | Clock int64 `json:"clock"` 19 | } 20 | 21 | // Metric class constructor. 22 | func NewMetric(host, key, value string, clock ...int64) *Metric { 23 | m := &Metric{Host: host, Key: key, Value: value} 24 | // use current time, if `clock` is not specified 25 | if m.Clock = time.Now().Unix(); len(clock) > 0 { 26 | m.Clock = int64(clock[0]) 27 | } 28 | return m 29 | } 30 | 31 | // Packet class. 32 | type Packet struct { 33 | Request string `json:"request"` 34 | Data []*Metric `json:"data"` 35 | Clock int64 `json:"clock"` 36 | } 37 | 38 | // Packet class cunstructor. 39 | func NewPacket(data []*Metric, clock ...int64) *Packet { 40 | p := &Packet{Request: `sender data`, Data: data} 41 | // use current time, if `clock` is not specified 42 | if p.Clock = time.Now().Unix(); len(clock) > 0 { 43 | p.Clock = int64(clock[0]) 44 | } 45 | return p 46 | } 47 | 48 | // DataLen Packet class method, return 8 bytes with packet length in little endian order. 49 | func (p *Packet) DataLen() []byte { 50 | dataLen := make([]byte, 8) 51 | JSONData, _ := json.Marshal(p) 52 | binary.LittleEndian.PutUint32(dataLen, uint32(len(JSONData))) 53 | return dataLen 54 | } 55 | 56 | // Sender class. 57 | type Sender struct { 58 | Host string 59 | Port int 60 | } 61 | 62 | // Sender class constructor. 63 | func NewSender(host string, port int) *Sender { 64 | s := &Sender{Host: host, Port: port} 65 | return s 66 | } 67 | 68 | // Method Sender class, return zabbix header. 69 | func (s *Sender) getHeader() []byte { 70 | return []byte("ZBXD\x01") 71 | } 72 | 73 | // Method Sender class, resolve uri by name:port. 74 | func (s *Sender) getTCPAddr() (iaddr *net.TCPAddr, err error) { 75 | // format: hostname:port 76 | addr := fmt.Sprintf("%s:%d", s.Host, s.Port) 77 | 78 | // Resolve hostname:port to ip:port 79 | iaddr, err = net.ResolveTCPAddr("tcp", addr) 80 | if err != nil { 81 | err = fmt.Errorf("Connection failed: %s", err.Error()) 82 | return 83 | } 84 | 85 | return 86 | } 87 | 88 | // Method Sender class, make connection to uri. 89 | func (s *Sender) connect() (conn *net.TCPConn, err error) { 90 | 91 | type DialResp struct { 92 | Conn *net.TCPConn 93 | Error error 94 | } 95 | 96 | // Open connection to zabbix host 97 | iaddr, err := s.getTCPAddr() 98 | if err != nil { 99 | return 100 | } 101 | 102 | // dial tcp and handle timeouts 103 | ch := make(chan DialResp) 104 | 105 | go func() { 106 | conn, err = net.DialTCP("tcp", nil, iaddr) 107 | ch <- DialResp{Conn: conn, Error: err} 108 | }() 109 | 110 | select { 111 | case <-time.After(5 * time.Second): 112 | err = fmt.Errorf("Connection Timeout") 113 | case resp := <-ch: 114 | if resp.Error != nil { 115 | err = resp.Error 116 | break 117 | } 118 | 119 | conn = resp.Conn 120 | } 121 | 122 | return 123 | } 124 | 125 | // Method Sender class, read data from connection. 126 | func (s *Sender) read(conn *net.TCPConn) (res []byte, err error) { 127 | res = make([]byte, 1024) 128 | res, err = ioutil.ReadAll(conn) 129 | if err != nil { 130 | err = fmt.Errorf("Error whule receiving the data: %s", err.Error()) 131 | return 132 | } 133 | 134 | return 135 | } 136 | 137 | // Method Sender class, send packet to zabbix. 138 | func (s *Sender) Send(packet *Packet) (res []byte, err error) { 139 | conn, err := s.connect() 140 | if err != nil { 141 | return 142 | } 143 | defer conn.Close() 144 | 145 | dataPacket, _ := json.Marshal(packet) 146 | 147 | /* 148 | fmt.Printf("HEADER: % x (%s)\n", s.getHeader(), s.getHeader()) 149 | fmt.Printf("DATALEN: % x, %d byte\n", packet.DataLen(), len(packet.DataLen())) 150 | fmt.Printf("BODY: %s\n", string(dataPacket)) 151 | */ 152 | 153 | // Fill buffer 154 | buffer := append(s.getHeader(), packet.DataLen()...) 155 | buffer = append(buffer, dataPacket...) 156 | 157 | // Sent packet to zabbix 158 | _, err = conn.Write(buffer) 159 | if err != nil { 160 | err = fmt.Errorf("Error while sending the data: %s", err.Error()) 161 | return 162 | } 163 | 164 | res, err = s.read(conn) 165 | 166 | /* 167 | fmt.Printf("RESPONSE: %s\n", string(res)) 168 | */ 169 | return 170 | } 171 | -------------------------------------------------------------------------------- /zabbix_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import "testing" 4 | 5 | const ( 6 | hostname = `somehost.com` 7 | zabbixhost = `172.30.30.30` 8 | zabbixport = 1234 9 | ) 10 | 11 | func TestSend(t *testing.T) { 12 | sender := NewSender(zabbixhost, zabbixport) 13 | 14 | metrics := []*Metric{NewMetric(hostname, `key`, `value`)} 15 | _, err := sender.Send(NewPacket(metrics)) 16 | 17 | if err == nil { 18 | t.Error("sending should have failed") 19 | } 20 | 21 | t.Logf("error: %v", err.Error()) 22 | } 23 | --------------------------------------------------------------------------------