public void Initalize() { NetTrace.Start(); NetTrace.Enable(DnsResolver.TraceSubSystem, 0); DnsResolver.Bind(); }
public void _Trace(MsgRouter router, int detail, string tEvent, string summaryAppend, params string[] args) { StringBuilder sb; string summary; string details; sb = new StringBuilder(120); _TraceSummary(router, sb); summary = sb.ToString(); if (summaryAppend != null) { summary += summaryAppend; } sb = new StringBuilder(512); _TraceDetails(router, sb); details = sb.ToString(); for (int i = 0; i < args.Length; i++) { sb.Append(args[i] + "\r\n"); } NetTrace.Write(MsgRouter.TraceSubsystem, detail, tEvent + ": [" + this.GetType().Name + "]", summary, details); }
/// <summary> /// Processes the packet within the context. Returns true whether the packet was processed or throttled. /// </summary> /// <param name="channel">The through which the packet is coming/going out.</param> /// <param name="context">The packet context for this operation.</param> /// <returns>True whether the packet was processed or throttled, false otherwise.</returns> public static ProcessingState Process(Emitter.Connection channel, ProcessingContext context) { // Only process precompiled buffer var inputBuffer = context.Buffer; if (inputBuffer == null) { return(ProcessingState.Failure); } // Get the length & reserve new buffer var length = inputBuffer.Length; var buffer = context.BufferReserve(length + 2); // Wrap in between 0 and 255 buffer.Array[buffer.Offset] = Start; Memory.Copy(inputBuffer.Array, inputBuffer.Offset, buffer.Array, buffer.Offset + 1, length); buffer.Array[buffer.Offset + length + 1] = End; // Switch to the new buffer context.SwitchBuffer(buffer); // Trace a websocket event NetTrace.WriteLine("Draft76 frame [" + buffer.Length + "] encoded", channel, NetTraceCategory.WebSocket); return(ProcessingState.Success); }
public void NetTrace_Default_Config() { _NetTraceSink sink; NetTracePacket packet; try { sink = new _NetTraceSink(); Config.SetConfig(null); NetTrace.Start(); NetTrace.Enable("subsystem", 10); NetTraceSink.Start(new NetTraceSinkDelegate(sink.OnReceive)); NetTrace.Write("subsystem", 10, "event", "summary", "details"); sink.Wait(1); packet = sink.Dequeue(); Assert.AreEqual("subsystem", packet.Subsystem); Assert.AreEqual(10, packet.Detail); Assert.AreEqual("event", packet.Event); Assert.AreEqual("summary", packet.Summary); Assert.AreEqual("details", packet.Details); } finally { NetTrace.Stop(); } }
/// <summary> /// Binds a channel to this <see cref="IClient"/> object instance. /// </summary> /// <param name="channel">The channel to bind to this client.</param> public void BindChannel(Emitter.Connection channel) { lock (this.Lock) { // Should we dispatch the event? var dispatchEvent = (this.Channel == null && !this.ConnectInvoked); // If we don't have a transport yet, mark this as TCP if (this.Transport == null) { this.Transport = new TcpTransport(); } // Set the channel within the transport this.Transport.Channel = channel; this.ConnectionId = channel.ConnectionId; NetTrace.WriteLine("Binding to client " + this, channel, NetTraceCategory.Channel); // Dispatch the event once we have the transport bound if (dispatchEvent) { // Flag as done this.ConnectInvoked = true; // Invoke connected, on first connection only Service.InvokeClientConnect(new ClientConnectEventArgs(this)); // Fire the connected event locally this.Connect?.Invoke(this); } } }
public void _Trace(MsgRouter router, Exception e) { const string format = @"Exception: {0} Message: {1} Stack: "; StringBuilder sb; string summary; string details; sb = new StringBuilder(120); _TraceSummary(router, sb); summary = sb.ToString(); sb = new StringBuilder(512); sb.AppendFormat(null, format, e.GetType().ToString(), e.Message); sb.AppendFormat(e.StackTrace); sb.Append("----------\r\n"); _TraceDetails(router, sb); details = sb.ToString(); NetTrace.Write(MsgRouter.TraceSubsystem, 0, "Exception: [" + this.GetType().Name + "]", summary, details); }
public void NetTrace_Setting_Config() { _NetTraceSink sink; NetTracePacket packet; try { sink = new _NetTraceSink(); Config.SetConfig(@" Diagnostics.TraceEP = 231.222.0.77:44411 Diagnostics.TraceAdapter = $(ip-address) Diagnostics.TraceEnable[0] = 255:subsystem "); NetTrace.Start(); NetTraceSink.Start(new NetTraceSinkDelegate(sink.OnReceive)); NetTrace.Write("subsystem", 255, "event", "summary", "details"); sink.Wait(1); packet = sink.Dequeue(); Assert.AreEqual("subsystem", packet.Subsystem); Assert.AreEqual(255, packet.Detail); Assert.AreEqual("event", packet.Event); Assert.AreEqual("summary", packet.Summary); Assert.AreEqual("details", packet.Details); Assert.AreEqual(44411, packet.SourceEP.Port); } finally { NetTrace.Stop(); } }
/// <summary> /// Unbinds a channel from this <see cref="IClient"/> object instance. /// </summary> /// <param name="channel">The channel to unbind from this client.</param> public void UnbindChannel(Emitter.Connection channel) { // If the channel is not bound, ignore the unbind if (this.Transport.Channel != channel) { return; } NetTrace.WriteLine("Unbinding from client " + this, channel, NetTraceCategory.Channel); lock (this.Lock) { // Set the channel if (this.Transport != null) { this.Transport.Channel = null; } } // As this is a single connection client, we simply dispose it when the connection is unbound switch (this.TransportType) { case ITransportType.Tcp: this.Dispose(); break; } }
/// <summary> /// Gets the tcp channel or creates a new client connection. /// </summary> /// <param name="endpoint">The endpoint to connect to.</param> /// <param name="binding">The mesh binding to use.</param> /// <returns>The channel representing the connection</returns> internal async Task TryConnect(IPEndPoint endpoint, IBinding binding) { try { // The binding must be set prior to the connect if (binding == null) { throw new ArgumentNullException("binding"); } // Get the peer IPEndPoint peer; if (!TrackedPeers.TryGetValue(endpoint.ToString(), out peer)) { return; } // Do we have the node in our mesh? MeshMember node; if (Registry.TryGetValue(peer.ToIdentifier(), out node)) { // If the connection is up and running already, skip the connection. if (node.State == ServerState.Online) { return; } } // Create a new connection var channel = await Connection.ConnectAsync(Service.Mesh.Binding.Context, endpoint); // If it's a new channel, start it and handshake if (channel == null) { return; } // Dead? Attempt to reconnect NetTrace.WriteLine("Connected to peer " + peer + "...", channel, NetTraceCategory.Mesh); // Send the mesh handshake once we're connected channel.SendMeshHandshake(); // Wait for the handshake for a few seconds await Task.Delay(TimeSpan.FromSeconds(5)); // If we haven't received an ack yet, shutdown the connection MeshMember registered; if (Registry.TryGetValue(peer.ToIdentifier(), out registered) && registered.Channel == channel) { return; } channel.Close(); } catch (Exception) { // Service.Logger.Log(LogLevel.Warning, "Unable to connect to Mesh node: " + endpoint); } }
public void Initialize() { NetTrace.Start(); NetTrace.Enable(MsgRouter.TraceSubsystem, 1); AsyncTracker.Enable = false; AsyncTracker.Start(); }
public void Initialize() { NetTrace.Start(); Helper.SetLocalGuidMode(GuidMode.CountUp); NetTrace.Enable(MsgRouter.TraceSubsystem, 255); NetTrace.Enable(ParallelQuerySession.TraceSubsystem, 255); }
protected void Application_Start(object sender, EventArgs args) { LillTek.Web.WebHelper.PlatformInitialize(Assembly.GetExecutingAssembly()); NetTrace.Start(); //router = new LeafRouter(); //router.Start(); }
public void Cleanup() { ReliableTransferSession.ClearCachedSettings(); Config.SetConfig(null); NetTrace.Stop(); clientWait.Close(); }
public void Initialize() { NetTrace.Start(); NetTrace.Enable(MsgRouter.TraceSubsystem, 2); TimedLock.FullDiagnostics = false; AsyncTracker.Enable = false; AsyncTracker.Start(); }
internal void Trace(int detail, string summary, string details) { if (details == null) { details = string.Empty; } NetTrace.Write(TraceSubsystem, detail, "ParallelQuery", summary, details); }
/// <summary> /// Starts the service, associating it with an <see cref="IServiceHost" /> instance. /// </summary> /// <param name="serviceHost">The service user interface.</param> /// <param name="args">Command line arguments.</param> public void Start(IServiceHost serviceHost, string[] args) { lock (syncLock) { if (router != null) { return; // Already started } // Global initialization NetTrace.Start(); Program.Config = new Config("LillTek.Datacenter.RouterService"); Program.PerfCounters = null; // $todo(jeff.lill): new PerfCounterSet(true,Const.RouterServicePerf,Const.RouterServiceName); // Service initialization this.serviceHost = serviceHost; try { RootRouter rootRouter; HubRouter hubRouter; switch (Program.Config.Get("Mode", "HUB").ToUpper()) { case "ROOT": SysLog.LogInformation("Router Service v{0}: Starting as ROOT", Helper.GetVersionString()); router = rootRouter = new RootRouter(); rootRouter.Start(); break; case "HUB": default: SysLog.LogInformation("Router Service v{0}: Starting as HUB", Helper.GetVersionString()); router = hubRouter = new HubRouter(); hubRouter.Start(); break; } state = ServiceState.Running; } catch (Exception e) { if (router != null) { router.Stop(); router = null; } SysLog.LogException(e); throw; } } }
public void Initialize() { NetTrace.Start(); NetTrace.Enable(MsgRouter.TraceSubsystem, 1); AsyncTracker.Enable = false; AsyncTracker.Start(); broadcastServer = new UdpBroadcastServer(new UdpBroadcastServerSettings(), null, null); }
/// <summary> /// Adds a peer to the tracking mechanism. /// </summary> /// <param name="ep"></param> public bool TrackPeer(IPEndPoint ep) { if (TrackedPeers.TryAdd(ep.ToString(), ep)) { NetTrace.WriteLine("Tracking Peer: " + ep.ToString(), null, NetTraceCategory.Mesh); return(true); } return(false); }
public void Initialize() { ReliableTransferSession.ClearCachedSettings(); NetTrace.Start(); NetTrace.Enable(ReliableTransferSession.TraceSubsystem, 0); // NetTrace.Enable(MsgRouter.TraceSubsystem,255); clientWait = new AutoResetEvent(false); }
public void Cleanup() { if (broadcastServer != null) { broadcastServer.Close(); broadcastServer = null; } NetTrace.Stop(); AsyncTracker.Stop(); }
/// <summary> /// Processes the packet within the context. Returns true whether the packet was processed or throttled. /// </summary> /// <param name="channel">The through which the packet is coming/going out.</param> /// <param name="context">The packet context for this operation.</param> /// <returns>True whether the packet was processed or throttled, false otherwise.</returns> public static ProcessingState Process(Emitter.Connection channel, ProcessingContext context) { var buffer = context.Buffer; if (buffer == null) { return(ProcessingState.Failure); } // Get the buffer pointer var pBuffer = buffer.AsBytePointer(); var offset = 0; var length = buffer.Length; // Decode the frame var queue = new Queue <BufferSegment>(); int index; bool isFinal; BufferSegment decoded; do { //var trace = (context.Buffer.ViewAsHybi13 == "(Invalid: Hybi13)" ? context.Buffer.ViewAsBytes : context.Buffer.ViewAsHybi13); var result = DecodeFrame(context, pBuffer, length, out index, out isFinal, out decoded); //Console.WriteLine(trace + " -> " + result); if (result != ProcessingState.Success) { return(result); } pBuffer += index; offset += index; length -= index; queue.Enqueue(decoded); } while (!isFinal); // Merge the queue decoded = queue.Dequeue(); while (queue.Count > 0) { decoded = decoded.Join(queue.Dequeue()); } // Throttle the rest if (offset < buffer.Length) { context.Throttle(offset); } // Swap the buffer context.SwitchBuffer(decoded); NetTrace.WriteLine("Hybi13 frame decoded", channel, NetTraceCategory.WebSocket); return(ProcessingState.Success); }
public void Cleanup() { Config.SetConfig(null); if (router != null) { router.Stop(); } NetTrace.Stop(); Helper.DeleteFile(tempFolder, true); }
public void Cleanup() { Helper.SetLocalGuidMode(GuidMode.Normal); Config.SetConfig(null); if (router != null) { router.Stop(); } NetTrace.Stop(); }
/// <summary> /// Removes a peer from the tracking mechanism. /// </summary> /// <param name="ep"></param> public bool ForgetPeer(IPEndPoint ep) { IPEndPoint peer; if (TrackedPeers.TryRemove(ep.ToString(), out peer)) { // Forget the peer NetTrace.WriteLine("Forgetting Peer: " + ep.ToString(), null, NetTraceCategory.Mesh); return(true); } return(false); }
public void Cleanup() { if (handler != null) { handler.Stop(); } if (router != null) { router.Stop(); } NetTrace.Stop(); }
/// <summary> /// Removes the logical routes associated with a logical endpoint set /// from the table. /// </summary> /// <param name="logicalEndpointSetID">The logical endpoint set ID.</param> public void Flush(Guid logicalEndpointSetID) { var physicalRoutes = new Dictionary <string, PhysicalRoute>(); int cDelete = 0; List <LogicalRoute> rebuild; using (TimedLock.Lock(router.SyncRoot)) { foreach (var physRoute in router.PhysicalRoutes) { physicalRoutes.Add(physRoute.ToString(), physRoute); } // Mark the routes to be deleted. for (int i = 0; i < routes.Count; i++) { routes[i].IsMarked = routes[i].PhysicalRoute.LogicalEndpointSetID == logicalEndpointSetID; if (routes[i].IsMarked) { cDelete++; } } // Rebuild the route table if necessary if (cDelete > 0) { rebuild = new List <LogicalRoute>(routes.Count - cDelete); for (int i = 0; i < routes.Count; i++) { if (!routes[i].IsMarked) { rebuild.Add(routes[i]); } #if TRACE else { NetTrace.Write(MsgRouter.TraceSubsystem, 0, "Logical Set Flush *******", this.GetType().Name + ": router=" + router.RouterEP.ToString(), "LogicalEP=" + routes[i].LogicalEP.ToString() + "\r\n" + "PhysicalEP=" + routes[i].PhysicalRoute.RouterEP.ToString()); } #endif } routes = rebuild; changeID++; } } }
/// <summary> /// Generates a diagnostic trace of the message passed. /// </summary> /// <param name="title">The trace title.</param> /// <param name="message">The message.</param> public static void Trace(string title, SipMessage message) { StringBuilder sb = new StringBuilder(1024); SipRequest request; SipResponse response; string summary; string contentType; SipCSeqValue vCSeq; string cseqMethod; string cseqNumber; vCSeq = message.GetHeader <SipCSeqValue>(SipHeader.CSeq); if (vCSeq == null) { cseqMethod = "????"; cseqNumber = "CSeq:????"; } else { cseqMethod = vCSeq.Method; cseqNumber = "CSeq:" + vCSeq.Number.ToString(); } request = message as SipRequest; if (request != null) { summary = string.Format("{0} Request: {1} {2}", request.MethodText, request.Uri, cseqNumber); } else { response = (SipResponse)message; summary = string.Format("{0} Response: {1} ({2}) {3}", cseqMethod, response.StatusCode, response.ReasonPhrase, cseqNumber); } sb.AppendLine(title); sb.AppendLine(); sb.Append(message.ToString()); contentType = message.GetHeaderText(SipHeader.ContentType); if (message.ContentLength > 0 && message.HasContentType(SipHelper.SdpMimeType)) { sb.AppendLine(Helper.FromUTF8(message.Contents)); } else { sb.AppendLine(Helper.HexDump(message.Contents, 16, HexDumpOption.ShowAll)); } NetTrace.Write(SipHelper.TraceSubsystem, 0, "SIP: " + title, summary, sb.ToString()); }
/// <summary> /// Upgrades the connection to the particular protocol. Handles the handshake. /// </summary> /// <param name="context"><see cref="ProcessingContext"/> for the current connection.</param> /// <param name="httpContext"><see cref="HttpContext"/> for the current connection.</param> /// <returns>The handlers that have been inserted in the pipeline.</returns> public WebSocketPipeline Upgrade(ProcessingContext context, HttpContext httpContext) { var request = httpContext.Request; var builder = new StringBuilder(); builder.Append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"); builder.Append("Upgrade: WebSocket\r\n"); builder.Append("Connection: Upgrade\r\n"); builder.AppendFormat("Sec-WebSocket-Origin: {0}\r\n", request.Headers["Origin"]); //builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", secure ? "wss" : "ws", request.Headers["Host"], request.Path); builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", "ws", request.Headers["Host"], request.Path); if (request.Headers["Sec-WebSocket-Protocol"] != null) { builder.AppendFormat("Sec-WebSocket-Protocol: {0}\r\n", request.Headers["Sec-WebSocket-Protocol"]); } builder.Append("\r\n"); var key1 = request.Headers["Sec-WebSocket-Key1"]; var key2 = request.Headers["Sec-WebSocket-Key2"]; // Get last bytes byte[] challenge = request.Body; // Compile the body var part1 = Encoding.ASCII.GetBytes(builder.ToString()); var part2 = CalculateAnswerBytes(key1, key2, challenge); var buffer = new byte[part1.Length + part2.Length]; Memory.Copy(part1, 0, buffer, 0, part1.Length); Memory.Copy(part2, 0, buffer, part1.Length, part2.Length); // Prepare the response packet var response = BytePacket.Acquire(buffer); // Get the channel var channel = httpContext.Connection; // Send the handshake response channel.Send(response); // Set the encoder & the decoder for this websocket handler channel.Encoding.PipelineAddLast(Encode.WebSocketDraft76); channel.Decoding.PipelineAddFirst(Decode.WebSocketDraft76); // Trace a websocket event NetTrace.WriteLine("Upgraded to Draft76 ", channel, NetTraceCategory.WebSocket); return(new WebSocketPipeline(Encode.WebSocketDraft76, Decode.WebSocketDraft76)); }
/// <summary> /// Starts the service, associating it with an <see cref="IServiceHost" /> instance. /// </summary> /// <param name="serviceHost">The service user interface.</param> /// <param name="args">Command line arguments.</param> public void Start(IServiceHost serviceHost, string[] args) { lock (syncLock) { if (router != null) { return; // Already started } // Global initialization NetTrace.Start(); Program.Config = new Config(MsgQueueHandler.ConfigPrefix); Program.InstallPerfCounters(); // Service initialization this.serviceHost = serviceHost; SysLog.LogInformation("Message Queue v{0} Start", Helper.GetVersionString()); try { router = new LeafRouter(); router.Start(); handler = new MsgQueueHandler(); handler.Start(router, null, Program.PerfCounters, null); state = ServiceState.Running; } catch (Exception e) { if (handler != null) { handler.Stop(); handler = null; } if (router != null) { router.Stop(); router = null; } SysLog.LogException(e); throw; } } }
static void Main() { Helper.InitializeApp(Assembly.GetExecutingAssembly()); Config.SetConfigPath(Helper.GetEntryAssembly()); NetTrace.Start(); NativeSysLogProvider.CreateLogs("MessagingTest"); SysLog.LogProvider = new NativeSysLogProvider("MessagingTest"); Msg.LoadTypes(Assembly.GetExecutingAssembly()); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); }