PubSubServer's linux issues fixed

This commit is contained in:
Taha authored and John Colvin committed 2024-06-26 14:28:51 -04:00
1 parent 5cf7eacd82
commit c39fc70a64
53 files changed
+2915 -1464

No files matched your search

@@ -1,77 +1,77 @@
using System;
using System.Collections.Generic;
using System.Text;
//using BCG.Utilities;
using System.Net;
// using System;
// using System.Collections.Generic;
// using System.Text;
// //using BCG.Utilities;
// using System.Net;
namespace BCG
{
public class BlutoSubAddress : SubAddress
{
private string myIp;
private int myPort;
// namespace BCG
// {
// public class BlutoSubAddress : SubAddress
// {
// private string myIp;
// private int myPort;
public static string prefix = "bluto";
// public static string prefix = "bluto";
public BlutoSubAddress(string ip, int port)
{
myIp = ip;
myPort = port;
}
// public BlutoSubAddress(string ip, int port)
// {
// myIp = ip;
// myPort = port;
// }
public BlutoSubAddress(string serverAddress)
{
string[] toks = serverAddress.Split(':');
// TODO
// BlueEventLog.logAssert(toks.Length == 3);
// BlueEventLog.logAssert(toks[0].ToLower().StartsWith(prefix));
// public BlutoSubAddress(string serverAddress)
// {
// string[] toks = serverAddress.Split(':');
// // TODO
// // BlueEventLog.logAssert(toks.Length == 3);
// // BlueEventLog.logAssert(toks[0].ToLower().StartsWith(prefix));
string machineNameOrIP = toks[1].Remove(0, 2);
// string machineNameOrIP = toks[1].Remove(0, 2);
if (machineNameOrIP.Split('.').Length == 4)
myIp = toks[1].Remove(0, 2);
else
{
//get the IP address from DNS
IPAddress[] theAddressList = Dns.GetHostEntry(machineNameOrIP).AddressList;
//BlueEventLog.logAssert(theAddressList.Length == 1, "Error: machine has multiple ip addresses.");
//if we get multiple addresses, we want the one that is of the corret dotted notation
bool oneWorked = false;
foreach (IPAddress addr in theAddressList)
{
if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
myIp = addr.ToString();
oneWorked = true;
}
}
// if (machineNameOrIP.Split('.').Length == 4)
// myIp = toks[1].Remove(0, 2);
// else
// {
// //get the IP address from DNS
// IPAddress[] theAddressList = Dns.GetHostEntry(machineNameOrIP).AddressList;
// //BlueEventLog.logAssert(theAddressList.Length == 1, "Error: machine has multiple ip addresses.");
// //if we get multiple addresses, we want the one that is of the corret dotted notation
// bool oneWorked = false;
// foreach (IPAddress addr in theAddressList)
// {
// if (addr.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
// {
// myIp = addr.ToString();
// oneWorked = true;
if (!oneWorked)
{
throw new ArgumentException("Couldn't form server address from string " + serverAddress);
}
// }
// }
}
myPort = Convert.ToInt32(toks[2]);
}
// if (!oneWorked)
// {
// throw new ArgumentException("Couldn't form server address from string " + serverAddress);
// }
public string ip
{
get { return myIp; }
}
// }
// myPort = Convert.ToInt32(toks[2]);
// }
public int port
{
get { return myPort; }
}
public override string ToString()
{
return prefix + "://" + ip + ":" + port;
}
}
}
// public string ip
// {
// get { return myIp; }
// }
// public int port
// {
// get { return myPort; }
// }
// public override string ToString()
// {
// return prefix + "://" + ip + ":" + port;
// }
// }
// }
@@ -1,88 +1,89 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
// using System;
// using System.Collections.Generic;
// using System.Text;
// using System.Threading;
// using System.Runtime.InteropServices;
namespace BCG
{
public class SmartConnectionManagedWrapper
{
public delegate void MessageDelegate(int msgType, byte[] msg);
private Dictionary<string, MessageDelegate> myServerToDel = new Dictionary<string, MessageDelegate>();
// TODO: remove
// namespace BCG
// {
// public class SmartConnectionManagedWrapper
// {
// public delegate void MessageDelegate(int msgType, byte[] msg);
// private Dictionary<string, MessageDelegate> myServerToDel = new Dictionary<string, MessageDelegate>();
public SmartConnectionManagedWrapper ()
{
ClientToServerConnectionWrapper.init();
Thread readThr = new Thread(new ThreadStart(myReceiveData));
readThr.Start();
}
// public SmartConnectionManagedWrapper ()
// {
// ClientToServerConnectionWrapper.init();
// Thread readThr = new Thread(new ThreadStart(myReceiveData));
// readThr.Start();
// }
public void initConnection(BlutoSubAddress subAddress)
{
ClientToServerConnectionWrapper.initServerConnection(ClientToServerConnectionWrapper.stringToBytes(subAddress.ip),
subAddress.port);
}
// public void initConnection(BlutoSubAddress subAddress)
// {
// ClientToServerConnectionWrapper.initServerConnection(ClientToServerConnectionWrapper.stringToBytes(subAddress.ip),
// subAddress.port);
// }
public void send(BlutoSubAddress address, byte[] data)
{
byte[] ip = ClientToServerConnectionWrapper.stringToBytes (address.ip);
ClientToServerConnectionWrapper.sendDataToServer(ip, address.port, data, data.Length);
}
// public void send(BlutoSubAddress address, byte[] data)
// {
// byte[] ip = ClientToServerConnectionWrapper.stringToBytes (address.ip);
// ClientToServerConnectionWrapper.sendDataToServer(ip, address.port, data, data.Length);
// }
public void resgisterDataCallback(BlutoSubAddress address, MessageDelegate del)
{
lock (this)
{
myServerToDel.Add(address.ToString(), del);
}
}
public void unregisterDataCallback(BlutoSubAddress address, MessageDelegate del)
{
lock (this)
{
myServerToDel.Remove(address.ip);
}
}
// public void resgisterDataCallback(BlutoSubAddress address, MessageDelegate del)
// {
// lock (this)
// {
// myServerToDel.Add(address.ToString(), del);
// }
// }
public string getClientAsSeenByServer(string serverURL)
{
return "";
}
// public void unregisterDataCallback(BlutoSubAddress address, MessageDelegate del)
// {
// lock (this)
// {
// myServerToDel.Remove(address.ip);
// }
// }
private unsafe void myReceiveData()
{
while (true)
{
BlutoTCPClientMessage** psClientPackets = null;
int npts = 0;
///returns as soon as it gets the first element
ClientToServerConnectionWrapper.getServerData(1000, 1, &psClientPackets, out npts);
for (int i = 0; i < npts; i++)
{
string ip = Marshal.PtrToStringAnsi(psClientPackets[i]->ip);
int port = psClientPackets[i]->port;
string serverURL = new BlutoSubAddress(ip, port).ToString();
// public string getClientAsSeenByServer(string serverURL)
// {
// return "";
// }
byte[] msg = null;
if (psClientPackets[i]->msgType == 1)
{
msg = new byte[psClientPackets[i]->size];
Marshal.Copy(psClientPackets[i]->msg, msg, 0, msg.Length);
}
// private unsafe void myReceiveData()
// {
// while (true)
// {
// BlutoTCPClientMessage** psClientPackets = null;
// int npts = 0;
// ///returns as soon as it gets the first element
// ClientToServerConnectionWrapper.getServerData(1000, 1, &psClientPackets, out npts);
// for (int i = 0; i < npts; i++)
// {
// string ip = Marshal.PtrToStringAnsi(psClientPackets[i]->ip);
// int port = psClientPackets[i]->port;
// string serverURL = new BlutoSubAddress(ip, port).ToString();
MessageDelegate cb = null;
lock (this)
{
myServerToDel.TryGetValue(serverURL, out cb);
}
if (cb != null)
cb(psClientPackets[i]->msgType, msg);
}
}
}
// byte[] msg = null;
// if (psClientPackets[i]->msgType == 1)
// {
// msg = new byte[psClientPackets[i]->size];
// Marshal.Copy(psClientPackets[i]->msg, msg, 0, msg.Length);
// }
}
}
// MessageDelegate cb = null;
// lock (this)
// {
// myServerToDel.TryGetValue(serverURL, out cb);
// }
// if (cb != null)
// cb(psClientPackets[i]->msgType, msg);
// }
// }
// }
// }
// }
@@ -72,6 +72,6 @@ namespace BCG {
/// <param name="del"></param>
void register_data_callback(PubSubServerDataDelegate del);
void register_send_confirmation_callback(SendConfirmationDelegate del);
//void register_send_confirmation_callback(SendConfirmationDelegate del);
}
}
@@ -1,52 +1,52 @@
using System;
//using System.Messaging;
// using System;
// //using System.Messaging;
using BCG;
//using BCG.Utilities;
// using BCG;
// //using BCG.Utilities;
namespace BCG
{
public class MSMQSubAddress : SubAddress
{
private string myIP, myQ;
public static readonly string prefix = "msmq";
// namespace BCG
// {
// public class MSMQSubAddress : SubAddress
// {
// private string myIP, myQ;
// public static readonly string prefix = "msmq";
public MSMQSubAddress (string adr)
{
try
{
// throw away prefix
string s = adr;
s = s.Substring(prefix.Length + "://".Length);
// grab IP
myIP = s.Substring(0,s.IndexOf("/"));
// throw away ip
s = s.Substring(myIP.Length + 1);
myQ = s;
}
catch (Exception)
{
throw (new InvalidSubAddress(adr + " is not a valid queue address"));
}
}
// public MSMQSubAddress (string adr)
// {
// try
// {
// // throw away prefix
// string s = adr;
// s = s.Substring(prefix.Length + "://".Length);
// // grab IP
// myIP = s.Substring(0,s.IndexOf("/"));
// // throw away ip
// s = s.Substring(myIP.Length + 1);
// myQ = s;
public MSMQSubAddress (string ip, string simpleQName)
{
myIP = ip;
myQ = simpleQName;
}
// }
// catch (Exception)
// {
// throw (new InvalidSubAddress(adr + " is not a valid queue address"));
// }
// }
public string ip {get {return myIP;}}
// public MSMQSubAddress (string ip, string simpleQName)
// {
// myIP = ip;
// myQ = simpleQName;
// }
public string simpleQueueName {get {return myQ;}}
// public string ip {get {return myIP;}}
public override string ToString() { return prefix + "://" + myIP + "/" + myQ; }
// public string simpleQueueName {get {return myQ;}}
public string formatName
{
get{return "FormatName:DIRECT=TCP:" + myIP + "\\private$\\" + myQ;}
}
}
}
// public override string ToString() { return prefix + "://" + myIP + "/" + myQ; }
// public string formatName
// {
// get{return "FormatName:DIRECT=TCP:" + myIP + "\\private$\\" + myQ;}
// }
// }
// }
@@ -1,296 +1,264 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
//using BCG.Utilities;
//using BCG.Utilities.General;
using System.Threading;
using mbts;
using bts;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Bts.PubSub;
namespace BCG {
/// <summary>
/// Keeps an ITCPConnection for talking to the server. It also monitors heartbeats
/// from the server, and in case of missing hbs, informs its clients, and tries to
/// restablish the connection.
/// Threads :
/// its assumed that IPubSubServerConnection functions (including doWork) will
/// be called from the same thread. ITCPMessageHandler.onData and
/// ITCPConnectionHandler.onConnection will be called on any arbitrary thread
///
/// </summary>
public class PubSubServerManagedTCPConnection : IPubSubServerConnection,// external facing interface to communicate msgs to Pubsubserver
ITCPMessageHandler, // to get messages from ITCPCOnnection
ITCPConnectionHandler { // to get connections from AsyncTCPConnector_APM
private ITCPConnection _connection, _new_connection;
private readonly BlutoSubAddress _server_address;
// if a message(with confirm) can not be sent , its id is queued here,
// on reconnection, _on_send_onfirm_callback is fired with a negative on these ids, so the user
//can re-send it. The re-send mechanism is not in implemented in this class, but by the user of this class
private ThreadSafeQueue<string> _negative_unsent_confs = new ThreadSafeQueue<string>();
// in onData, data is queued here, for polling
private SyncQueue<byte[]> _in_data_queue = new SyncQueue<byte[]>();
private DateTime _last_hb = DateTime.Now;
private PubSubServerConnectionStatusChange _conn_callback;
private PubSubServerDataDelegate _data_callback;
private SendConfirmationDelegate _on_send_confirm_callback;
private readonly TimeSpan _connection_drop_threshold = PubSubConfig.Instance.ConnectionDropThreshold();
public PubSubServerManagedTCPConnection(string server_url)
: this(new BlutoSubAddress(server_url)) { }
public PubSubServerManagedTCPConnection(BlutoSubAddress server_address) {
_server_address = server_address;
_connect_to_ps_server();
}
private void _connect_to_ps_server() {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._connect_to_ps_server server: {_server_address}");
AsyncTCPConnector_APM.connect_to(_server_address, this);
}
#region IPubSubServerConnection Members
public void send_with_confirmation(byte[] data, ref string conf_id) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} data: {data.Length} _connection : {_connection != null}");
if (_connection != null) {
_connection.sendWithConfirmation(data, ref conf_id, (msg_id, confirmed) => {
if (_on_send_confirm_callback != null)
_on_send_confirm_callback(msg_id, confirmed);
});
} else {
bts.Log.Gen.warn($"PubSubServerManagedTCPConnection.sendWithConfirmation server: {_server_address} no connection, buffering send");
conf_id = Guid.NewGuid().ToString();
_negative_unsent_confs.enqueue(conf_id);
}
}
private void _send(byte[] data) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._send server: {_server_address} data: {data.Length} _connection : {_connection != null}");
if (_connection != null) {
bts.Log.Gen.info("PubSubServerManagedTCPConnection.send server: " + _server_address + "data: " + data.Length);
_connection.send(data);
}
}
public void send(bts.PubSubClientMessage ps_msg) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} ps_msg: {ps_msg}");
var msg_bytes = ps_msg.serialize_into_bytes();
PubSubClientMessage msg_retrv = new PubSubClientMessage();
msg_retrv.consruct_deserialize(msg_bytes);
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_address} msg_retrv: {msg_retrv}");
_send(msg_bytes);
}
// private void send(Stream str) {
// BinaryReader br = new BinaryReader(str);
// _send(br.ReadBytes(Convert.ToInt32(str.Length - str.Position)));
// }
// private void send(PubSubMessage msg) {
// send(msg.to_stream());
// }
// public void send_with_confirmation(PubSubMessage msg, ref string conf_id) {
// var bytes = msg.to_bytes();
// send_with_confirmation(bytes, ref conf_id);
// }
public void send_with_confirmation(bts.PubSubClientMessage msg, ref string conf_id, SendConfirmationDelegate del) {
if (_connection == null) {
// quq
}
MemoryStream str = new MemoryStream();
msg.serialize_into_str(str);
var bytes = StreamUtilityMethods.getBytesFromStream(str);
_connection.sendWithConfirmation(bytes, ref conf_id, del);
}
public IEnumerable<bts.PubSubServerMessage> get_updates(TimeSpan timeout, int maxElements) {
List<byte[]> rv_raw = _in_data_queue.dequeueMultipleElements(Convert.ToInt32(timeout.TotalMilliseconds), maxElements);
List<bts.PubSubServerMessage> rv = new List<PubSubServerMessage>();
var i = 0;
foreach (var b in rv_raw) {
PubSubServerMessage ps_msg = new PubSubServerMessage();
ps_msg.consruct_deserialize(b);
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.get_updates downloaded: {ps_msg} msg_no: {i} / {rv_raw.Count}");
rv.Add(ps_msg);
i++;
}
return rv;
}
public string server_url {
get { return _server_address.ToString(); }
}
public string client_url {
get {
string rv = "";
lock (this) {
if (_connection == null) {
rv = "";
} else {
if (PubSubConfig.Instance.IpTranslation.is_null_or_empty()) {
string ip;
int port;
_connection.getSelfAddress(out ip, out port);
rv = new BlutoSubAddress(ip, port).ToString();
} else {
rv = "";
}
}
}
return rv;
}
}
public void register_connection_callback(PubSubServerConnectionStatusChange del) {
_conn_callback = del;
}
public void register_data_callback(PubSubServerDataDelegate del) {
_data_callback = del;
}
public void register_send_confirmation_callback(SendConfirmationDelegate del) {
_on_send_confirm_callback = del;
}
#endregion
#region IDisposable Members
private bool _is_disposed = false;
public void Dispose() {
bts.Log.Gen.info("PubSubServerManagedTCPConnection.Dispose");
//throw new Exception("The method or operation is not implemented.");
if (_connection != null) {
_connection.Dispose();
}
_is_disposed = true;
}
public bool isDisposed {
get {
return _is_disposed;
}
}
#endregion
#region ITCPMessageHandler Members
/// <summary>
/// This method is executed on an arbitrary CLR thread. To avoid blocking it
/// data is written to the queue and method returns. myLastHB being a primitive
/// (long) is safe for multi threaded operations
/// </summary>
/// <param name="message"></param>
public void onData(RemoteMessage message) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData message: {message}");
// TODO check for disconenction
switch (message.messageType) {
case RemoteMessageType.Data:
if (_data_callback != null)
_data_callback(message.remoteConnectionInfo.ToString(), message.message);
else
_in_data_queue.enqueue(message.message);
break;
case RemoteMessageType.Heartbeat:
_last_hb = DateTime.Now;
break;
case RemoteMessageType.Connection:
_conn_callback(_server_address.ToString(), true);
break;
case RemoteMessageType.Disconnection:
if (_conn_callback != null)
_conn_callback(_server_address.ToString(), false);
_connection.Dispose();
_connect_to_ps_server();
break;
}
}
#endregion
#region ITCPConnectionHandler Members
/// will be called on on an rbitrary .Net thread
public void onConnection(ITCPConnection connection) {
string ip;
int port;
connection.getPeerAddress(out ip, out port);
BlutoSubAddress add = new BlutoSubAddress(ip, port);
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onConnection add: {add.ToString()} connection type: {connection.GetType()}");
if (add.ToString() == _server_address.ToString()) {
_last_hb = DateTime.Now;
_new_connection = connection;
}
}
#endregion
void _dispose_and_reconnect_if_missing_hb() {
if (!_connection.isDisposed) {
TimeSpan hb_interval = DateTime.Now - _last_hb;
bool hb_missed = hb_interval > _connection_drop_threshold;
if (hb_missed) {
if (_conn_callback != null)
_conn_callback(_server_address.ToString(), false);
bts.Log.Gen.info("PubSubServerManagedTCPConnection._dispose_and_reconnect_if_missing_hb disposing connecion: {myServerAddress}");
_connection.Dispose();
_connect_to_ps_server();
}
} else {
// already disposed, nothing to do
}
}
void _check_for_new_connection() {
if (_new_connection != null) {
_connection = _new_connection;
_new_connection = null; // since we are using its presence as a marker of nw connections
bts.Log.Gen.info("PubSubServerManagedTCPConnection._check_for_new_connection assigning new connection");
_connection.register(this);
if (_conn_callback != null)
_conn_callback(_server_address.ToString(), true);
if (_on_send_confirm_callback != null) {
var msg_ids = _negative_unsent_confs.dequeueAll();
foreach (var id in msg_ids)
_on_send_confirm_callback(id, false);
}
}
}
#region IWorker Members
/// <summary>
/// should be called on the same thread as the other user functions.
/// the design only allows for onConnection to be on a different
/// thread.
/// </summary>
public void doWork() {
//_dispose_and_reconnect_if_missing_hb();
//try {
_check_for_new_connection();
// } catch (Exception ex) {
// bts.Log.Gen.warn($"PubsSubServerManagedTCPConnection.doWork ex: {ex}");
// }
}
#endregion
// private void myOnSendConfirm(string messageId, bool confirmed) {
// _negative_confs.enqueue(new Pair<string, bool>(messageId, confirmed));
// }
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
//using BCG.Utilities;
//using BCG.Utilities.General;
using System.Threading;
using mbts;
using bts;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Bts.PubSub;
using Microsoft.Win32;
using System.ComponentModel;
namespace BCG {
/// <summary>
/// Keeps an ITCPConnection for talking to the server. It also monitors heartbeats
/// from the server, and in case of missing hbs, informs its clients, and tries to
/// restablish the connection.
/// Threads :
/// its assumed that IPubSubServerConnection functions (including doWork) will
/// be called from the same thread. ITCPMessageHandler.onData and
/// ITCPConnectionHandler.onConnection are called on an arbitrary thread.
/// _conn_callback is called from within doWork, and _data_callback is called grom
// an arbitrary data thread
/// </summary>
public class PubSubServerManagedTCPConnection : IPubSubServerConnection,// external facing interface to communicate msgs to Pubsubserver
ITCPMessageHandler, // to get messages from ITCPCOnnection
ITCPConnectionHandler { // to get connections from AsyncTCPConnector_APM
private ITCPConnection _connection;
private readonly RemoteConnectionInfo _server_rc_info;
private readonly bool _is_sub;
// if _data_callback is not subscribed to , the user of this class can poll updates,
// in which case this queue will be used
private SyncQueue<byte[]> _in_data_queue = new SyncQueue<byte[]>();
private DateTime _last_hb = DateTime.Now;
private PubSubServerConnectionStatusChange _conn_callback;
private PubSubServerDataDelegate _data_callback;
private readonly TimeSpan _connection_drop_threshold = PubSubConfig.Instance.ConnectionDropThreshold();
private ThreadSafeQueue<ConnectionStatusChange> _conn_cb_queue = new ThreadSafeQueue<ConnectionStatusChange>();
// the callbacks for connection, comes from the ITCPConnection, when a connection is broken,
// and from AsyncTCPConnector whne a connection is established. ALl that info is assembled here and
// enqueued, deuqued oin the doWork and acted on
private class ConnectionStatusChange {
public enum Status {
CONNECTED,
DISCONNECTED
}
public readonly Status connection_satus;
public readonly ITCPConnection new_connection = null;
public ConnectionStatusChange(Status connection_satus_, ITCPConnection new_connection_) {
connection_satus = connection_satus_;
new_connection = new_connection_;
}
public override string ToString() {
return connection_satus.ToString();
}
}
public PubSubServerManagedTCPConnection(RemoteConnectionInfo server_address, bool is_sub) {
Log.Gen.info("PubSubServerManagedTCPConnection.cons server_address: {server_address} is_sub: {is_sub}");
_server_rc_info = server_address;
_is_sub = is_sub;
// this is where it tries to connect to the pubsub server, and gets a callback on onConnection
_connect_to_ps_server();
}
private void _connect_to_ps_server() {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._connect_to_ps_server server _server_rc_info: {_server_rc_info} is_sub: {_is_sub}");
// onConnection will be called on an arbitrary thread
AsyncTCPConnector_AsyncWrapper.connect_to(_server_rc_info, this);
}
#region IPubSubServerConnection Members
private void _send(byte[] data) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection._send server: {_server_rc_info} data: {data.Length} is_sub: {_is_sub} _connection : {_connection != null}");
if (_connection != null) {
_connection.send(data);
bts.Log.Gen.info("PubSubServerManagedTCPConnection.send, data is sent, server: " + _server_rc_info + "data: " + data.Length);
} else {
bts.Log.Gen.warn($"PubSubServerManagedTCPConnection._send, could not send data, server: {_server_rc_info} data: {data.Length} is_sub: {_is_sub} _connection : {_connection != null} ");
}
}
public void send(bts.PubSubClientMessage ps_msg) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_rc_info} ps_msg: {ps_msg}");
// whys it constructed again?
var msg_bytes = ps_msg.serialize_into_bytes();
// PubSubClientMessage msg_retrv = new PubSubClientMessage();
// msg_retrv.consruct_deserialize(msg_bytes);
// bts.Log.Gen.info($"PubSubServerManagedTCPConnection.send server: {_server_rc_info} msg_retrv: {msg_retrv}");
_send(msg_bytes);
}
public IEnumerable<bts.PubSubServerMessage> get_updates(TimeSpan timeout, int maxElements) {
List<byte[]> rv_raw = _in_data_queue.dequeueMultipleElements(Convert.ToInt32(timeout.TotalMilliseconds), maxElements);
List<bts.PubSubServerMessage> rv = new List<PubSubServerMessage>();
var i = 0;
foreach (var b in rv_raw) {
PubSubServerMessage ps_msg = new PubSubServerMessage();
ps_msg.consruct_deserialize(b);
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.get_updates downloaded: {ps_msg} msg_no: {i} / {rv_raw.Count}");
rv.Add(ps_msg);
i++;
}
return rv;
}
public string server_url {
get { return _server_rc_info.ToString(); }
}
public string client_url {
get {
if (_connection == null)
return RemoteConnectionInfo.null_instance.ToString();
return _connection.get_self_address().ToString();
}
}
public void register_connection_callback(PubSubServerConnectionStatusChange del) {
_conn_callback = del;
}
public void register_data_callback(PubSubServerDataDelegate del) {
_data_callback = del;
}
#endregion
#region IDisposable Members
private bool _is_disposed = false;
public void Dispose() {
if (isDisposed)
return;
bts.Log.Gen.info("PubSubServerManagedTCPConnection.Dispose");
if (_connection != null) {
_connection.Dispose();
}
_is_disposed = true;
}
public bool isDisposed {
get {
return _is_disposed;
}
}
#endregion
#region ITCPMessageHandler Members
/// <summary>
/// This method is executed on an arbitrary CLR thread.
/// </summary>
/// <param name="message"></param>
public void onData(RemoteMessage message) {
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData message: {message}");
// TODO check for disconenction
switch (message.messageType) {
case RemoteMessageType.Data:
if (_data_callback != null)
_data_callback(message.remoteConnectionInfo.ToString(), message.message);
else
_in_data_queue.enqueue(message.message);
break;
case RemoteMessageType.Heartbeat:
_last_hb = DateTime.Now;
break;
case RemoteMessageType.Connection:
// since this is called from the connection, this condition will never hit, ssince
//new connections are detected only by AsyncTCPConnector
Log.assert(false);
break;
case RemoteMessageType.Disconnection:
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onData case RemoteMessageType.Disconnection: message: {message}");
_conn_cb_queue.enqueue(new ConnectionStatusChange(ConnectionStatusChange.Status.DISCONNECTED, null));
break;
}
}
#endregion
#region ITCPConnectionHandler Members
/// will be called on on an arbitrary .Net thread
public void onConnection(ITCPConnection connection) {
var server_rci = connection.get_peer_address();
bts.Log.Gen.info($"PubSubServerManagedTCPConnection.onConnection connection: {_connection_txt(connection)}");
if (_server_rc_info.Equals(server_rci)) {
_conn_cb_queue.enqueue(new ConnectionStatusChange(ConnectionStatusChange.Status.CONNECTED, connection));
// _last_hb = DateTime.Now;
// _new_connection = connection;
}
}
#endregion
void _check_missing_hb() {
if (!_connection.isDisposed) {
TimeSpan hb_interval = DateTime.Now - _last_hb;
bool hb_missed = hb_interval > _connection_drop_threshold;
if (hb_missed) {
bts.Log.Gen.warn("PubSubServerManagedTCPConnection._dispose_and_reconnect_if_missing_hb disposing connecion: {myServerAddress}");
ConnectionStatusChange ci = new ConnectionStatusChange(ConnectionStatusChange.Status.DISCONNECTED, null);
_conn_cb_queue.enqueue(ci);
}
} else {
// already disposed, nothing to do
}
}
private static string _connection_txt(ITCPConnection conn) {
if (conn != null) {
return $"conn_type: {conn.GetType()} server: {conn.get_peer_address()} self: {conn.get_self_address()}";
}
return "NULL";
}
#region IWorker Members
/// <summary>
/// should be called on the same thread as the other user functions.
/// the design only allows for onConnection to be on a different
/// thread.
/// </summary>
public void doWork() {
//_dispose_and_reconnect_if_missing_hb();
if (_conn_cb_queue.getCount() > 0) {
var css = _conn_cb_queue.dequeueAll();
foreach (var c in css) {
Log.Gen.info($"PubSubServerManagedTCPConnection.doWork c: {c}");
switch (c.connection_satus) {
case ConnectionStatusChange.Status.CONNECTED: {
Log.assert(c.new_connection != null);
c.new_connection.register(this);
_connection = c.new_connection;
_last_hb = DateTime.Now;
if (_conn_callback != null)
_conn_callback(_server_rc_info.ToString(), true);
break;
}
case ConnectionStatusChange.Status.DISCONNECTED: {
_connection.Dispose();
_connect_to_ps_server();
if (_conn_callback != null)
_conn_callback(_server_rc_info.ToString(), false);
break;
}
}
}
}
}
#endregion
}
}
@@ -3,55 +3,38 @@ using System.Collections.Generic;
using System.Text;
//using BCG.Utilities;
namespace BCG
{
namespace BCG {
/// <summary>
/// Every instance of PublisherCore and SubscriberCore will have its
/// factory. Rather than have once singelton factory, this approach
/// is preffered since multiple pub/sub core can connect to the same
/// connection and make it difficultt o manage connections.
/// </summary>
public class PubSubServerConnectionFactory : IDisposable
{
private bool myIsSub;
private Dictionary<string, IPubSubServerConnection> myConnections = new Dictionary<string, IPubSubServerConnection>();
public class PubSubServerConnectionFactory : IDisposable {
private Dictionary<RemoteConnectionInfo, IPubSubServerConnection> _conn_map =
new Dictionary<RemoteConnectionInfo, IPubSubServerConnection>();
private readonly bool _is_sub;
internal PubSubServerConnectionFactory (bool isSub)
{
myIsSub = isSub;
internal PubSubServerConnectionFactory(bool is_sub) {
_is_sub = is_sub;
}
public IPubSubServerConnection getConnection(string url)
{
if (!myConnections.ContainsKey(url))
myConnections.Add(url, myBuildConnection(url));
return myConnections[url];
public IPubSubServerConnection get_connection(RemoteConnectionInfo server_rci) {
IPubSubServerConnection rv = null;
if (!_conn_map.TryGetValue(server_rci, out rv)) {
rv = _build_connection(server_rci);
_conn_map.Add(server_rci, rv);
}
return rv;
}
private IPubSubServerConnection myBuildConnection(string url)
{
if (url.StartsWith(MSMQSubAddress.prefix))
{
// TODO, no more MSMQ
//Diagnostics.assert(false);
return null;
// MSMQSubAddress serverAdd = new MSMQSubAddress(url);
// return new PubSubServerMSMQConnection(serverAdd.ToString(), myIsSub);
}
else if (url.StartsWith(BlutoSubAddress.prefix))
{
return new PubSubServerManagedTCPConnection(url);
}
else
{
// BlueEventLog.logAssert(false, "Unknown transport, only msmq and blutoTcp allowed");
return null;
}
private IPubSubServerConnection _build_connection(RemoteConnectionInfo server_rci) {
return new PubSubServerManagedTCPConnection(server_rci, _is_sub);
}
#region IDisposable Members
public void Dispose() {}
public void Dispose() { }
#endregion
}
@@ -124,7 +124,14 @@ namespace bts {
public long publish_time_epoch_ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public byte[] data_to_publish;
public void sanity_check() {
Log.assert(!String.IsNullOrEmpty(tag_type));
Log.assert(!String.IsNullOrEmpty(tag));
Log.assert(!String.IsNullOrEmpty(connection));
}
public void serialize_into_str(Stream str) {
sanity_check();
BinaryWriter bw = new BinaryWriter(str);
bw.write_string_cpp(connection);
bw.write_string_cpp(publishing_app);
@@ -24,6 +24,7 @@ namespace bts {
}
private static Dictionary<string, TagHandlerEntry> _config_map = new Dictionary<string, TagHandlerEntry>()
{
{String.Empty, new TagHandlerEntry(DSTagManager.DataStreamTagType , "DataStreamCore", "bts.PubsubServerStreamTagHandler")},
{DSTagManager.DataStreamTagType, new TagHandlerEntry(DSTagManager.DataStreamTagType , "DataStreamCore", "bts.PubsubServerStreamTagHandler")},
{"System_Sub", new TagHandlerEntry("System_Sub", "PubSub", "BCG.SystemSubscriptionMapPublisher")},
{"System_Stats", new TagHandlerEntry("System_Stats", "PubSub", "BCG.SystemStatsPublisher")}
@@ -8,11 +8,12 @@ namespace BCG {
public interface IPubSubRouter {
event PubSubTagURLChangeDelegate onSubURLTagRouteChange;
event PubSubTagURLChangeDelegate onPubURLTagRouteChange;
List<string> get_all_pubsub_sub_urls();
List<string> get_all_pubsub_pub_urlss();
string get_sub_url_for_tag(string tag);
string get_pub_url_for_tag(string tag);
// event PubSubTagURLChangeDelegate onSubURLTagRouteChange;
// event PubSubTagURLChangeDelegate onPubURLTagRouteChange;
// List<string> get_all_pubsub_sub_urls();
// List<string> get_all_pubsub_pub_urlss();
RemoteConnectionInfo get_sub_route_for_tag(string tag);
RemoteConnectionInfo get_pub_route_for_tag(string tag);
}
}
@@ -5,43 +5,38 @@ using System.Text.RegularExpressions;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Runtime.InteropServices;
namespace BCG {
[JsonConverter(typeof(PubSubRouteJsonConverter))]
public class PubSubRoute : IComparable<PubSubRoute> {
public string serverAddress;
public string tagRegExp;
public string server_address;
public string tag_reg_exp;
//route names are used in intermediary code (i.e. while substations are being deployed)
//so that MC Hammer can advertise them.
public string name;
private Regex myRegex = null;
private Regex _regex = null;
public PubSubRoute() { }
public PubSubRoute(string theServerAddress, string theTagRegExp) {
serverAddress = theServerAddress;
tagRegExp = theTagRegExp;
public PubSubRoute(string the_server_address, string the_tag_reg_exp) {
server_address = the_server_address;
tag_reg_exp = the_tag_reg_exp;
}
// public PubSubRoute()
// {
// // serverAddress = string.Format("bluto://{0}:{1}", cfg.serverAddress, cfg.serverPort);
// // tagRegExp = cfg.tagsRegex;
// }
public string[] getAllPubSubs() {
return serverAddress.Split(';');
return server_address.Split(';');
}
public Regex getRegex() {
return myRegex ?? new Regex(tagRegExp);
public Regex get_regex() {
return _regex ?? new Regex(tag_reg_exp);
}
#region IComparable<PubSubRoute> Members
public int CompareTo(PubSubRoute other) {
return serverAddress == other.serverAddress ? tagRegExp.CompareTo(other.tagRegExp)
: serverAddress.CompareTo(other.serverAddress);
return server_address == other.server_address ? tag_reg_exp.CompareTo(other.tag_reg_exp)
: server_address.CompareTo(other.server_address);
}
#endregion
@@ -51,8 +46,8 @@ namespace BCG {
return false;
else {
PubSubRoute other = obj as PubSubRoute;
return serverAddress.Equals(other.serverAddress) &&
tagRegExp.Equals(other.tagRegExp);
return server_address.Equals(other.server_address) &&
tag_reg_exp.Equals(other.tag_reg_exp);
}
}
@@ -63,27 +58,31 @@ namespace BCG {
public static PubSubRoute get_default_route() {
return new PubSubRoute("bluto://127.0.0.1:12345", ".*");
}
public override string ToString() {
return $"tag_reg_exp: {tag_reg_exp} server_address: {server_address}";
}
}
public static class PubSubRouteExtensions {
public static bool IsMatch(this PubSubRoute route, string tag) =>
route.getRegex().IsMatch(tag);
route.get_regex().IsMatch(tag);
}
public class PubSubRouteJsonConverter : JsonConverter<PubSubRoute> {
public override PubSubRoute? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
var jsonObj = JsonSerializer.Deserialize<JsonObject>(ref reader);
if (jsonObj is null) {
var json_obj = JsonSerializer.Deserialize<JsonObject>(ref reader);
if (json_obj is null) {
return null;
}
var rv = new PubSubRoute();
ReadString("name", ref rv.name);
ReadString("server_address", ref rv.serverAddress);
ReadString("tag", ref rv.tagRegExp);
ReadString("server_address", ref rv.server_address);
ReadString("tag", ref rv.tag_reg_exp);
return rv;
void ReadString(string key, ref string valueOut) {
if (jsonObj.TryGetPropertyValue(key, out var valueJson)) {
if (json_obj.TryGetPropertyValue(key, out var valueJson)) {
var valueStr = valueJson?.GetValue<string>();
// Only (over)write valueOut if non-null
if (valueStr is not null) {
@@ -96,8 +95,8 @@ namespace BCG {
public override void Write(Utf8JsonWriter writer, PubSubRoute value, JsonSerializerOptions options) {
var jsonObj = new JsonObject {
["name"] = value.name,
["server_address"] = value.serverAddress,
["tag"] = value.tagRegExp,
["server_address"] = value.server_address,
["tag"] = value.tag_reg_exp,
};
JsonSerializer.Serialize(writer, jsonObj);
}
@@ -1,97 +1,79 @@
using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using BCG;
using Bts.PubSub;
using bts;
using System.Linq;
//using BCG.Utilities;
//using bts;
namespace BCG {
public class PubSubRouter : IPubSubRouter {
private Regex[] myPubRouteRegExps;
private Regex[] mySubRouteRegExps;
private PubSubRoute[] myPubRoutes;
private PubSubRoute[] mySubRoutes;
public PubSubRouter() : this(
PubSubConfig.Instance.SubscriberRoutes?.ToArray()
?? throw new InvalidOperationException("Subscriber routes are not configured"),
PubSubConfig.Instance.PublisherRoutes?.ToArray()
?? throw new InvalidOperationException("Publisher routes are not configured")) { }
public PubSubRouter(params PubSubRoute[] routes) : this(routes, routes) { }
public PubSubRouter(PubSubRoute[] subRoutes, PubSubRoute[] pubRoutes) {
mySubRouteRegExps = new Regex[subRoutes.Length];
myPubRouteRegExps = new Regex[pubRoutes.Length];
mySubRoutes = subRoutes;
myPubRoutes = pubRoutes;
for (int i = 0; i < subRoutes.Length; ++i)
mySubRouteRegExps[i] = new Regex(subRoutes[i].tagRegExp);
for (int i = 0; i < pubRoutes.Length; ++i)
myPubRouteRegExps[i] = new Regex(pubRoutes[i].tagRegExp);
}
private int myGetRouteIndex(string forTag, PubSubRoute[] routes, Regex[] regexes) {
for (int i = 0; i < routes.Length; i++)
if (regexes[i].IsMatch(forTag))
return i;
throw new PubSubRouteNotFound(String.Format("No route found for {0}", forTag));
}
#region IPubSubRouter methods
private string myPickAServer(string tag, string[] urls) {
if (urls.Length == 1)
return urls[0];
else {
uint hc = (uint)tag.GetHashCode();
return urls[hc % urls.Length];
}
}
public string get_pub_url_for_tag(string tag) {
if (!myPubRoutes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) {
throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag));
}
Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}");
return route.serverAddress;
}
public string get_sub_url_for_tag(string tag) {
if (!mySubRoutes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) {
throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag));
}
Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}");
return route.serverAddress;
}
public List<string> get_all_pubsub_sub_urls() =>
mySubRoutes.Select(r => r.serverAddress).ToList();
public List<string> get_all_pubsub_pub_urlss() =>
myPubRoutes.Select(r => r.serverAddress).ToList();
public event PubSubTagURLChangeDelegate onSubURLTagRouteChange;
public event PubSubTagURLChangeDelegate onPubURLTagRouteChange;
#endregion
//this function is put here so that the events are used, in order to prevent build errors.
private void myNeverCallThisFunction() {
if (onPubURLTagRouteChange == null || onSubURLTagRouteChange == null) {
int aVar = 2;
aVar = aVar + 2;
}
}
}
}
using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using BCG;
using Bts.PubSub;
using bts;
using System.Linq;
//using BCG.Utilities;
//using bts;
namespace BCG {
public class PubSubRouter : IPubSubRouter {
// private Regex[] mySubRouteRegExps;
private PubSubRoute[] _pub_routes;
private PubSubRoute[] _sub_routes;
public PubSubRouter() : this(
PubSubConfig.Instance.SubscriberRoutes?.ToArray()
?? throw new InvalidOperationException("Subscriber routes are not configured"),
PubSubConfig.Instance.PublisherRoutes?.ToArray()
?? throw new InvalidOperationException("Publisher routes are not configured")) { }
public PubSubRouter(params PubSubRoute[] routes) : this(routes, routes) { }
public PubSubRouter(PubSubRoute[] sub_routes, PubSubRoute[] pub_routes) {
string log_msg = String.Empty;
foreach (var route in sub_routes) {
log_msg += $" sub_route: {route}";
}
foreach (var route in pub_routes) {
log_msg += $" pub_route: {route}";
}
Log.Gen.info($"PubSubRouter routes: {log_msg}");
_sub_routes = sub_routes;
_pub_routes = pub_routes;
}
#region IPubSubRouter methods
public RemoteConnectionInfo get_pub_route_for_tag(string tag) {
if (!_pub_routes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) {
throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag));
}
Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}");
return RemoteConnectionInfo.parse_url(route.server_address);
}
public RemoteConnectionInfo get_sub_route_for_tag(string tag) {
if (!_sub_routes.TryGetFirst(r => r?.IsMatch(tag) ?? false, out var route)) {
throw new ArgumentException($"Failed to find route for tag '{tag}'", nameof(tag));
}
Log.Gen.info($"PubSubRouter.get_sub_url_for_tag. tag: {tag} route: {route}");
return RemoteConnectionInfo.parse_url(route.server_address);
}
public List<string> get_all_pubsub_sub_urls() =>
_sub_routes.Select(r => r.server_address).ToList();
public List<string> get_all_pubsub_pub_urlss() =>
_pub_routes.Select(r => r.server_address).ToList();
public event PubSubTagURLChangeDelegate onSubURLTagRouteChange;
public event PubSubTagURLChangeDelegate onPubURLTagRouteChange;
#endregion
//this function is put here so that the events are used, in order to prevent build errors.
private void myNeverCallThisFunction() {
if (onPubURLTagRouteChange == null || onSubURLTagRouteChange == null) {
int aVar = 2;
aVar = aVar + 2;
}
}
}
}
+29 -29
View File
@@ -1,31 +1,31 @@
using System;
using BCG;
//using BCG.Utilities;
// using System;
// using BCG;
// //using BCG.Utilities;
namespace BCG
{
public class InvalidSubAddress : Exception
{
public InvalidSubAddress(string msg) : base (msg){}
}
// namespace BCG
// {
// public class InvalidSubAddress : Exception
// {
// public InvalidSubAddress(string msg) : base (msg){}
// }
public abstract class SubAddress
{
public static SubAddress decode (string s)
{
//if (s.StartsWith(TcpSubAddress.prefix))
// return new TcpSubAddress(s);
//else if (s.StartsWith(SuperSocketAddress.prefix))
// return new SuperSocketAddress(s);
if (s.StartsWith(MSMQSubAddress.prefix))
return new MSMQSubAddress(s);
else if (s.StartsWith(BlutoSubAddress.prefix))
return new BlutoSubAddress(s);
else
{
//BlueEventLog.logAssert(false, "Unknown pubsub transport for : " + s);
return null;
}
}
}
}
// public abstract class SubAddress
// {
// public static SubAddress decode (string s)
// {
// //if (s.StartsWith(TcpSubAddress.prefix))
// // return new TcpSubAddress(s);
// //else if (s.StartsWith(SuperSocketAddress.prefix))
// // return new SuperSocketAddress(s);
// if (s.StartsWith(MSMQSubAddress.prefix))
// return new MSMQSubAddress(s);
// else if (s.StartsWith(BlutoSubAddress.prefix))
// return new BlutoSubAddress(s);
// else
// {
// //BlueEventLog.logAssert(false, "Unknown pubsub transport for : " + s);
// return null;
// }
// }
// }
// }