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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
|
/*
* Copyright 2013 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.fanout;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for Fanout service implementations.
*
* Subclass implementations can be used as a Sparkleshare PubSub notification
* server. This allows Sparkleshare to be used in conjunction with Gitblit
* behind a corporate firewall that restricts or prohibits client internet access
* to the default Sparkleshare PubSub server: notifications.sparkleshare.org
*
* @author James Moger
*
*/
public abstract class FanoutService implements Runnable {
private final static Logger logger = LoggerFactory.getLogger(FanoutService.class);
public final static int DEFAULT_PORT = 17000;
protected final static int serviceTimeout = 5000;
protected final String host;
protected final int port;
protected final String name;
private Thread serviceThread;
private final Map<String, FanoutServiceConnection> connections;
private final Map<String, Set<FanoutServiceConnection>> subscriptions;
protected final AtomicBoolean isRunning;
private final AtomicBoolean strictRequestTermination;
private final AtomicBoolean allowAllChannelAnnouncements;
private final AtomicInteger concurrentConnectionLimit;
private final Date bootDate;
private final AtomicLong rejectedConnectionCount;
private final AtomicInteger peakConnectionCount;
private final AtomicLong totalConnections;
private final AtomicLong totalAnnouncements;
private final AtomicLong totalMessages;
private final AtomicLong totalSubscribes;
private final AtomicLong totalUnsubscribes;
private final AtomicLong totalPings;
protected FanoutService(String host, int port, String name) {
this.host = host;
this.port = port;
this.name = name;
connections = new ConcurrentHashMap<String, FanoutServiceConnection>();
subscriptions = new ConcurrentHashMap<String, Set<FanoutServiceConnection>>();
subscriptions.put(FanoutConstants.CH_ALL, new ConcurrentSkipListSet<FanoutServiceConnection>());
isRunning = new AtomicBoolean(false);
strictRequestTermination = new AtomicBoolean(false);
allowAllChannelAnnouncements = new AtomicBoolean(false);
concurrentConnectionLimit = new AtomicInteger(0);
bootDate = new Date();
rejectedConnectionCount = new AtomicLong(0);
peakConnectionCount = new AtomicInteger(0);
totalConnections = new AtomicLong(0);
totalAnnouncements = new AtomicLong(0);
totalMessages = new AtomicLong(0);
totalSubscribes = new AtomicLong(0);
totalUnsubscribes = new AtomicLong(0);
totalPings = new AtomicLong(0);
}
/*
* Abstract methods
*/
protected abstract boolean isConnected();
protected abstract boolean connect();
protected abstract void listen() throws IOException;
protected abstract void disconnect();
/**
* Returns true if the service requires \n request termination.
*
* @return true if request requires \n termination
*/
public boolean isStrictRequestTermination() {
return strictRequestTermination.get();
}
/**
* Control the termination of fanout requests. If true, fanout requests must
* be terminated with \n. If false, fanout requests may be terminated with
* \n, \r, \r\n, or \n\r. This is useful for debugging with a telnet client.
*
* @param isStrictTermination
*/
public void setStrictRequestTermination(boolean isStrictTermination) {
strictRequestTermination.set(isStrictTermination);
}
/**
* Returns the maximum allowable concurrent fanout connections.
*
* @return the maximum allowable concurrent connection count
*/
public int getConcurrentConnectionLimit() {
return concurrentConnectionLimit.get();
}
/**
* Sets the maximum allowable concurrent fanout connection count.
*
* @param value
*/
public void setConcurrentConnectionLimit(int value) {
concurrentConnectionLimit.set(value);
}
/**
* Returns true if connections are allowed to announce on the all channel.
*
* @return true if connections are allowed to announce on the all channel
*/
public boolean allowAllChannelAnnouncements() {
return allowAllChannelAnnouncements.get();
}
/**
* Allows/prohibits connections from announcing on the ALL channel.
*
* @param value
*/
public void setAllowAllChannelAnnouncements(boolean value) {
allowAllChannelAnnouncements.set(value);
}
/**
* Returns the current connections
*
* @param channel
* @return map of current connections keyed by their id
*/
public Map<String, FanoutServiceConnection> getCurrentConnections() {
return connections;
}
/**
* Returns all subscriptions
*
* @return map of current subscriptions keyed by channel name
*/
public Map<String, Set<FanoutServiceConnection>> getCurrentSubscriptions() {
return subscriptions;
}
/**
* Returns the subscriptions for the specified channel
*
* @param channel
* @return set of subscribed connections for the specified channel
*/
public Set<FanoutServiceConnection> getCurrentSubscriptions(String channel) {
return subscriptions.get(channel);
}
/**
* Returns the runtime statistics object for this service.
*
* @return stats
*/
public FanoutStats getStatistics() {
FanoutStats stats = new FanoutStats();
// settings
stats.allowAllChannelAnnouncements = allowAllChannelAnnouncements();
stats.concurrentConnectionLimit = getConcurrentConnectionLimit();
stats.strictRequestTermination = isStrictRequestTermination();
// runtime stats
stats.bootDate = bootDate;
stats.rejectedConnectionCount = rejectedConnectionCount.get();
stats.peakConnectionCount = peakConnectionCount.get();
stats.totalConnections = totalConnections.get();
stats.totalAnnouncements = totalAnnouncements.get();
stats.totalMessages = totalMessages.get();
stats.totalSubscribes = totalSubscribes.get();
stats.totalUnsubscribes = totalUnsubscribes.get();
stats.totalPings = totalPings.get();
stats.currentConnections = connections.size();
stats.currentChannels = subscriptions.size();
stats.currentSubscriptions = subscriptions.size() * connections.size();
return stats;
}
/**
* Returns true if the service is ready.
*
* @return true, if the service is ready
*/
public boolean isReady() {
if (isRunning.get()) {
return isConnected();
}
return false;
}
/**
* Start the Fanout service thread and immediatel return.
*
*/
public void start() {
if (isRunning.get()) {
logger.warn(MessageFormat.format("{0} is already running", name));
return;
}
serviceThread = new Thread(this);
serviceThread.setName(MessageFormat.format("{0} {1}:{2,number,0}", name, host == null ? "all" : host, port));
serviceThread.start();
}
/**
* Start the Fanout service thread and wait until it is accepting connections.
*
*/
public void startSynchronously() {
start();
while (!isReady()) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
/**
* Stop the Fanout service. This method returns when the service has been
* completely shutdown.
*/
public void stop() {
if (!isRunning.get()) {
logger.warn(MessageFormat.format("{0} is not running", name));
return;
}
logger.info(MessageFormat.format("stopping {0}...", name));
isRunning.set(false);
try {
if (serviceThread != null) {
serviceThread.join();
serviceThread = null;
}
} catch (InterruptedException e1) {
logger.error("", e1);
}
logger.info(MessageFormat.format("stopped {0}", name));
}
/**
* Main execution method of the service
*/
@Override
public final void run() {
disconnect();
resetState();
isRunning.set(true);
while (isRunning.get()) {
if (connect()) {
try {
listen();
} catch (IOException e) {
logger.error(MessageFormat.format("error processing {0}", name), e);
isRunning.set(false);
}
} else {
try {
Thread.sleep(serviceTimeout);
} catch (InterruptedException x) {
}
}
}
disconnect();
resetState();
}
protected void resetState() {
// reset state data
connections.clear();
subscriptions.clear();
rejectedConnectionCount.set(0);
peakConnectionCount.set(0);
totalConnections.set(0);
totalAnnouncements.set(0);
totalMessages.set(0);
totalSubscribes.set(0);
totalUnsubscribes.set(0);
totalPings.set(0);
}
/**
* Configure the client connection socket.
*
* @param socket
* @throws SocketException
*/
protected void configureClientSocket(Socket socket) throws SocketException {
socket.setKeepAlive(true);
socket.setSoLinger(true, 0); // immediately discard any remaining data
}
/**
* Add the connection to the connections map.
*
* @param connection
* @return false if the connection was rejected due to too many concurrent
* connections
*/
protected boolean addConnection(FanoutServiceConnection connection) {
int limit = getConcurrentConnectionLimit();
if (limit > 0 && connections.size() > limit) {
logger.info(MessageFormat.format("hit {0,number,0} connection limit, rejecting fanout connection", concurrentConnectionLimit));
increment(rejectedConnectionCount);
connection.busy();
return false;
}
// add the connection to our map
connections.put(connection.id, connection);
// track peak number of concurrent connections
if (connections.size() > peakConnectionCount.get()) {
peakConnectionCount.set(connections.size());
}
logger.info("fanout new connection " + connection.id);
connection.connected();
return true;
}
/**
* Remove the connection from the connections list and from subscriptions.
*
* @param connection
*/
protected void removeConnection(FanoutServiceConnection connection) {
connections.remove(connection.id);
Iterator<Map.Entry<String, Set<FanoutServiceConnection>>> itr = subscriptions.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<String, Set<FanoutServiceConnection>> entry = itr.next();
Set<FanoutServiceConnection> subscriptions = entry.getValue();
subscriptions.remove(connection);
if (!FanoutConstants.CH_ALL.equals(entry.getKey())) {
if (subscriptions.size() == 0) {
itr.remove();
logger.info(MessageFormat.format("fanout remove channel {0}, no subscribers", entry.getKey()));
}
}
}
logger.info(MessageFormat.format("fanout connection {0} removed", connection.id));
}
/**
* Tests to see if the connection is being monitored by the service.
*
* @param connection
* @return true if the service is monitoring the connection
*/
protected boolean hasConnection(FanoutServiceConnection connection) {
return connections.containsKey(connection.id);
}
/**
* Reply to a connection on the specified channel.
*
* @param connection
* @param channel
* @param message
* @return the reply
*/
protected String reply(FanoutServiceConnection connection, String channel, String message) {
if (channel != null && channel.length() > 0) {
increment(totalMessages);
}
return connection.reply(channel, message);
}
/**
* Service method to broadcast a message to all connections.
*
* @param message
*/
public void broadcastAll(String message) {
broadcast(connections.values(), FanoutConstants.CH_ALL, message);
increment(totalAnnouncements);
}
/**
* Service method to broadcast a message to connections subscribed to the
* channel.
*
* @param message
*/
public void broadcast(String channel, String message) {
List<FanoutServiceConnection> connections = new ArrayList<FanoutServiceConnection>(subscriptions.get(channel));
broadcast(connections, channel, message);
increment(totalAnnouncements);
}
/**
* Broadcast a message to connections subscribed to the specified channel.
*
* @param connections
* @param channel
* @param message
*/
protected void broadcast(Collection<FanoutServiceConnection> connections, String channel, String message) {
for (FanoutServiceConnection connection : connections) {
reply(connection, channel, message);
}
}
/**
* Process an incoming Fanout request.
*
* @param connection
* @param req
* @return the reply to the request, may be null
*/
protected String processRequest(FanoutServiceConnection connection, String req) {
logger.info(MessageFormat.format("fanout request from {0}: {1}", connection.id, req));
String[] fields = req.split(" ", 3);
String action = fields[0];
String channel = fields.length >= 2 ? fields[1] : null;
String message = fields.length >= 3 ? fields[2] : null;
try {
return processRequest(connection, action, channel, message);
} catch (IllegalArgumentException e) {
// invalid action
logger.error(MessageFormat.format("fanout connection {0} requested invalid action {1}", connection.id, action));
logger.error(asHexArray(req));
}
return null;
}
/**
* Process the Fanout request.
*
* @param connection
* @param action
* @param channel
* @param message
* @return the reply to the request, may be null
* @throws IllegalArgumentException
*/
protected String processRequest(FanoutServiceConnection connection, String action, String channel, String message) throws IllegalArgumentException {
if ("ping".equals(action)) {
// ping
increment(totalPings);
return reply(connection, null, "" + System.currentTimeMillis());
} else if ("info".equals(action)) {
// info
String info = getStatistics().info();
return reply(connection, null, info);
} else if ("announce".equals(action)) {
// announcement
if (!allowAllChannelAnnouncements.get() && FanoutConstants.CH_ALL.equals(channel)) {
// prohibiting connection-sourced all announcements
logger.warn(MessageFormat.format("fanout connection {0} attempted to announce {1} on ALL channel", connection.id, message));
} else if ("debug".equals(channel)) {
// prohibiting connection-sourced debug announcements
logger.warn(MessageFormat.format("fanout connection {0} attempted to announce {1} on DEBUG channel", connection.id, message));
} else {
// acceptable announcement
List<FanoutServiceConnection> connections = new ArrayList<FanoutServiceConnection>(subscriptions.get(channel));
connections.remove(connection); // remove announcer
broadcast(connections, channel, message);
increment(totalAnnouncements);
}
} else if ("subscribe".equals(action)) {
// subscribe
if (!subscriptions.containsKey(channel)) {
logger.info(MessageFormat.format("fanout new channel {0}", channel));
subscriptions.put(channel, new ConcurrentSkipListSet<FanoutServiceConnection>());
}
subscriptions.get(channel).add(connection);
logger.debug(MessageFormat.format("fanout connection {0} subscribed to channel {1}", connection.id, channel));
increment(totalSubscribes);
} else if ("unsubscribe".equals(action)) {
// unsubscribe
if (subscriptions.containsKey(channel)) {
subscriptions.get(channel).remove(connection);
if (subscriptions.get(channel).size() == 0) {
subscriptions.remove(channel);
}
increment(totalUnsubscribes);
}
} else {
// invalid action
throw new IllegalArgumentException(action);
}
return null;
}
private String asHexArray(String req) {
StringBuilder sb = new StringBuilder();
for (char c : req.toCharArray()) {
sb.append(Integer.toHexString(c)).append(' ');
}
return "[ " + sb.toString().trim() + " ]";
}
/**
* Increment a long and prevent negative rollover.
*
* @param counter
*/
private void increment(AtomicLong counter) {
long v = counter.incrementAndGet();
if (v < 0) {
counter.set(0);
}
}
@Override
public String toString() {
return name;
}
}
|