forked from BlueMountainCapital/riemann-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.cs
328 lines (297 loc) · 9.63 KB
/
Client.cs
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using ProtoBuf;
using Riemann.Proto;
namespace Riemann {
///
/// <summary>Client represents a connection to the Riemann service.</summary>
///
public class Client : IDisposable, IClient
{
private RiemannTags _tag;
private readonly object _tagLock = new object();
private class RiemannTags : IDisposable {
private readonly Client _owner;
private readonly RiemannTags _underlying;
private readonly string _tag;
public RiemannTags(Client owner, RiemannTags underlying, string tag) {
_owner = owner;
_underlying = underlying;
_tag = tag;
}
public void Dispose() {
_owner._tag = _underlying;
}
public IEnumerable<string> Tags {
get {
if (_underlying != null) {
foreach (var tag in _underlying.Tags) {
yield return tag;
}
}
yield return _tag;
}
}
}
private readonly string _host;
private readonly ushort _port;
private readonly string _name = GetFqdn();
private readonly bool _throwExceptionsOnTicks;
private readonly bool _useTcp;
private static string GetFqdn() {
var properties = IPGlobalProperties.GetIPGlobalProperties();
return string.Format("{0}.{1}", properties.HostName, properties.DomainName);
}
///
/// <summary>Constructs a new Client with the specified host, port</summary>
/// <param name='host'>Remote hostname to connect to. Default: localhost</param>
/// <param name='port'>Port to connect to. Default: 5555</param>
/// <param name='throwExceptionOnTicks'>Throw an exception on the background thread managing the TickEvents. Default: true</param>
/// <param name="useTcp">Use TCP for transport (UDP otherwise). Default: false</param>
///
public Client(string host = "localhost", int port = 5555, bool throwExceptionOnTicks = true, bool useTcp = false) {
_writer = new Lazy<Stream>(MakeStream);
_datagram = new Lazy<Socket>(MakeDatagram);
_host = host;
_port = (ushort)port;
_throwExceptionsOnTicks = throwExceptionOnTicks;
_useTcp = useTcp;
}
///
/// <summary>Adds a tag to the current context (relative to this client). This call is not thread-safe.</summary>
/// <param name='tag'>New tag to add to the Riemann events sent using this client.</param>
///
public IDisposable Tag(string tag) {
lock (_tagLock) {
_tag = new RiemannTags(this, _tag, tag);
return _tag;
}
}
private class TickDisposable : IDisposable {
public readonly int TickTime;
public readonly string Service;
public int NextTick;
public bool RemoveRequested;
private readonly Func<TickEvent> _onTick;
public TickDisposable(int tickTime, string service, Func<TickEvent> onTick) {
TickTime = tickTime;
Service = service;
_onTick = onTick;
}
public void Dispose() {
RemoveRequested = true;
}
public TickEvent Tick() {
return _onTick();
}
}
private readonly object _timerLock = new object();
private Timer _timer;
private List<TickDisposable> _ticks;
///
/// <summary>
/// After <paramref name="tickTimeInSeconds" /> seconds, <paramref name="onTick" /> will be invoked.
/// The resulting <see cref="TickEvent" /> is composed with the <paramref name="service" /> to generate an Event.
/// </summary>
/// <param name="tickTimeInSeconds">
/// Number of seconds to wait before calling the event back.
/// <note>Because only a single thread calls the events back, it may be called back sooner.</note>
/// </param>
/// <param name="service">Name of the service to send to Riemann</param>
/// <param name="onTick">Function to call back after wait period</param>
/// <returns>
/// A disposable that, if called, will remove this callback from getting called.
/// <note>An additional tick may elapse after removal, due to the multithreaded nature.</note>
/// </returns>
public IDisposable Tick(int tickTimeInSeconds, string service, Func<TickEvent> onTick) {
var disposable = new TickDisposable(tickTimeInSeconds, service, onTick);
lock(_timerLock) {
if (_ticks == null) {
_ticks = new List<TickDisposable>();
_timer = new Timer(_=> ProcessTicks());
_timer.Change(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0));
}
_ticks.Add(disposable);
}
return disposable;
}
private void ProcessTicks() {
try {
var events = new List<Event>();
List<TickDisposable> ticks;
lock (_timerLock) {
ticks = _ticks.ToList();
}
var removals = new List<TickDisposable>();
foreach (var tick in ticks) {
if (tick.RemoveRequested) {
removals.Add(tick);
}
tick.NextTick = tick.NextTick - 1;
if (tick.NextTick <= 0) {
var t = tick.Tick();
events.Add(new Event(tick.Service, t.State, t.Description, t.MetricValue, tick.TickTime * 2));
tick.NextTick = tick.TickTime;
}
}
if (removals.Count > 0) {
lock (_timerLock) {
if (removals.Count == _ticks.Count) {
_ticks = null;
_timer.Dispose();
_timer = null;
} else {
foreach (var removal in removals) {
_ticks.Remove(removal);
}
}
}
}
if (events.Count > 0) {
SendEvents(events);
}
} catch {
if (_throwExceptionsOnTicks) throw;
}
}
private readonly Lazy<Stream> _writer;
private readonly Lazy<Socket> _datagram;
private const SocketError SocketErrorMessageTooLong = SocketError.MessageSize;
private Stream MakeStream() {
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(_host, _port);
return new NetworkStream(socket, true);
}
private Stream Stream {
get { return _writer.Value; }
}
private Socket MakeDatagram() {
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(_host, _port);
return socket;
}
private Socket Datagram {
get { return _datagram.Value; }
}
///
/// <summary>Send many events to Riemann at once.</summary>
/// <param name="events">
/// Enumerable of the events to process.
/// Enumerable will be enumerated after being passed in.
/// </param>
///
public void SendEvents(IEnumerable<Event> events) {
var tags = new List<string>();
lock (_tagLock) {
if (_tag != null) {
tags = _tag.Tags.ToList();
}
}
var protoEvents = events.Select(
e => {
var evnt = new Proto.Event
{
host = _name,
service = e.Service,
state = e.State,
description = e.Description,
metric_f = e.Metric,
ttl = e.TTL
};
evnt.tags.AddRange(e.Tags);
return evnt;
}).ToList();
var message = new Proto.Msg();
foreach (var protoEvent in protoEvents) {
if(protoEvent.tags.Count == 0)
protoEvent.tags.AddRange(tags);
message.events.Add(protoEvent);
}
var array = MessageBytes(message);
if (_useTcp) {
WriteToStream(array);
return;
}
try {
Datagram.Send(array);
} catch (SocketException se) {
if (se.SocketErrorCode == SocketErrorMessageTooLong) {
WriteToStream(array);
} else {
throw;
}
}
}
private void WriteToStream(Byte[] array) {
var x = BitConverter.GetBytes(array.Length);
Array.Reverse(x);
Stream.Write(x, 0, 4);
Stream.Write(array, 0, array.Length);
Stream.Flush();
}
private static byte[] MessageBytes(Msg message)
{
using (var memoryStream = new MemoryStream()) {
Serializer.Serialize(memoryStream, message);
return memoryStream.ToArray();
}
}
///
/// <summary>Send a single event to Riemann.</summary>
/// <param name='service'>Name of the service to push.</param>
/// <param name='state'>State of the service; usual values are "ok", "critical", "warning"</param>
/// <param name='description'>
/// A description of the current state, if applicable.
/// Use null or an empty string to denote no additional information.
/// </param>
/// <param name='metric'>A value related to the service.</param>
/// <param name='ttl'>Number of seconds this event will be applicable for.</param>
/// <param name="tags">List of tags to associate with this event</param>
///
public void SendEvent(string service, string state, string description, float metric, int ttl = 0, List<string> tags = null)
{
var ev = new Event(service, state, description, metric, ttl, tags);
SendEvents(new[] {ev});
}
///
/// <summary>Queries Riemann</summary>
/// <param name='query'>Query to send Riemann for process</param>
/// <returns>List of States that answer the query.</returns>
///
public IEnumerable<Proto.State> Query(string query) {
var q = new Proto.Query {@string = query};
var msg = new Proto.Msg {query = q};
Serializer.Serialize(Stream, msg);
var response = Serializer.Deserialize<Proto.Msg>(Stream);
if (response.ok) {
return response.states;
}
throw new Exception(response.error);
}
///
/// <summary>Cleans up state related to this client.</summary>
///
public void Dispose() {
if (_writer.IsValueCreated) {
_writer.Value.Close();
_writer.Value.Dispose();
}
if (_datagram.IsValueCreated) {
_datagram.Value.Close();
_datagram.Value.Dispose();
}
GC.SuppressFinalize(this);
}
///
/// <summary>Closes connections.</summary>
///
~Client() {
Dispose();
}
}
}