This repository has been archived by the owner on Dec 1, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
client.go
112 lines (94 loc) · 2.39 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// A Riemann client for Go, featuring concurrency, sending events and state updates, queries,
// and feature parity with the reference implementation written in Ruby.
//
// Copyright (C) 2014 by Christopher Gilbert <christopher.john.gilbert@gmail.com>
package goryman
import (
"net"
"time"
pb "github.com/golang/protobuf/proto"
"github.com/bigdatadev/goryman/proto"
)
// GorymanClient is a client library to send events to Riemann
type GorymanClient struct {
udp *UdpTransport
tcp *TcpTransport
addr string
}
// NewGorymanClient - Factory
func NewGorymanClient(addr string) *GorymanClient {
return &GorymanClient{
addr: addr,
}
}
// Connect creates a UDP and TCP connection to a Riemann server
func (c *GorymanClient) Connect() error {
udp, err := net.DialTimeout("udp", c.addr, time.Second*5)
if err != nil {
return err
}
tcp, err := net.DialTimeout("tcp", c.addr, time.Second*5)
if err != nil {
return err
}
c.udp = NewUdpTransport(udp)
c.tcp = NewTcpTransport(tcp)
return nil
}
// Close the connection to Riemann
func (c *GorymanClient) Close() error {
if nil == c.udp && nil == c.tcp {
return nil
}
err := c.udp.Close()
if err != nil {
return err
}
return c.tcp.Close()
}
// Send an event
func (c *GorymanClient) SendEvent(e *Event) error {
epb, err := EventToProtocolBuffer(e)
if err != nil {
return err
}
message := &proto.Msg{}
message.Events = append(message.Events, epb)
_, err = c.sendMaybeRecv(message)
return err
}
// Send a state update
func (c *GorymanClient) SendState(s *State) error {
spb, err := StateToProtocolBuffer(s)
if err != nil {
return err
}
message := &proto.Msg{}
message.States = append(message.States, spb)
_, err = c.sendMaybeRecv(message)
return err
}
// Query the server for events
func (c *GorymanClient) QueryEvents(q string) ([]Event, error) {
query := &proto.Query{}
query.String_ = pb.String(q)
message := &proto.Msg{}
message.Query = query
response, err := c.sendRecv(message)
if err != nil {
return nil, err
}
return ProtocolBuffersToEvents(response.GetEvents()), nil
}
// Send and receive data from Riemann
func (c *GorymanClient) sendRecv(m *proto.Msg) (*proto.Msg, error) {
return c.tcp.SendRecv(m)
}
// Send and maybe receive data from Riemann
func (c *GorymanClient) sendMaybeRecv(m *proto.Msg) (*proto.Msg, error) {
_, err := c.udp.SendMaybeRecv(m)
if err != nil {
return c.tcp.SendMaybeRecv(m)
}
return nil, nil
}