From ba69f423d5e478da23ecf1f2e3be0c4e8742d968 Mon Sep 17 00:00:00 2001 From: "Gui.H" Date: Sun, 6 Nov 2022 13:00:57 +0800 Subject: [PATCH] add some log --- FastTunnel.Core/Client/FastTunnelServer.cs | 5 +- .../FastTunnelForwarderHttpClientFactory.cs | 186 +++++++++--------- .../MiddleWare/FastTunnelClientHandler.cs | 15 +- .../MiddleWare/FastTunnelSwapHandler.cs | 10 + .../Handlers/Client/SwapHandler.cs | 4 + 5 files changed, 128 insertions(+), 92 deletions(-) diff --git a/FastTunnel.Core/Client/FastTunnelServer.cs b/FastTunnel.Core/Client/FastTunnelServer.cs index ebb5184..2ac3b29 100644 --- a/FastTunnel.Core/Client/FastTunnelServer.cs +++ b/FastTunnel.Core/Client/FastTunnelServer.cs @@ -15,6 +15,7 @@ using Microsoft.Extensions.Options; using System.IO; using Yarp.ReverseProxy.Configuration; using System.Collections.Generic; +using FastTunnel.Core.Forwarder.MiddleWare; namespace FastTunnel.Core.Client { @@ -51,7 +52,7 @@ namespace FastTunnel.Core.Client internal void ClientLogin(TunnelClient client) { Interlocked.Increment(ref ConnectedClientCount); - logger.LogInformation($"客户端连接 {client.RemoteIpAddress} 当前在线数:{ConnectedClientCount}"); + logger.LogInformation($"客户端连接 {client.RemoteIpAddress} 当前在线数:{ConnectedClientCount},统计CLIENT连接数:{FastTunnelClientHandler.ConnectionCount}"); Clients.Add(client); } @@ -63,7 +64,7 @@ namespace FastTunnel.Core.Client internal void ClientLogout(TunnelClient client) { Interlocked.Decrement(ref ConnectedClientCount); - logger.LogInformation($"客户端关闭 {client.RemoteIpAddress} 当前在线数:{ConnectedClientCount}"); + logger.LogInformation($"客户端关闭 {client.RemoteIpAddress} 当前在线数:{ConnectedClientCount},统计CLIENT连接数:{FastTunnelClientHandler.ConnectionCount}"); Clients.Remove(client); client.Logout(); } diff --git a/FastTunnel.Core/Forwarder/FastTunnelForwarderHttpClientFactory.cs b/FastTunnel.Core/Forwarder/FastTunnelForwarderHttpClientFactory.cs index 06b9209..04fa957 100644 --- a/FastTunnel.Core/Forwarder/FastTunnelForwarderHttpClientFactory.cs +++ b/FastTunnel.Core/Forwarder/FastTunnelForwarderHttpClientFactory.cs @@ -1,6 +1,8 @@ -// Copyright (c) 2019-2022 Gui.H. https://github.com/FastTunnel/FastTunnel -// The FastTunnel licenses this file to you under the Apache License Version 2.0. -// For more details,You may obtain License file at: https://github.com/FastTunnel/FastTunnel/blob/v2/LICENSE +// 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 +// https://github.com/FastTunnel/FastTunnel/edit/v2/LICENSE +// Copyright (c) 2019 Gui.H using FastTunnel.Core.Client; using FastTunnel.Core.Extensions; @@ -22,100 +24,106 @@ using System.Threading.Tasks; using System.Xml.Linq; using Yarp.ReverseProxy.Forwarder; -namespace FastTunnel.Core.Forwarder +namespace FastTunnel.Core.Forwarder; + +public class FastTunnelForwarderHttpClientFactory : ForwarderHttpClientFactory { - public class FastTunnelForwarderHttpClientFactory : ForwarderHttpClientFactory + readonly ILogger logger; + readonly FastTunnelServer fastTunnelServer; + private readonly IHttpContextAccessor _httpContextAccessor; + static int connectionCount; + + public FastTunnelForwarderHttpClientFactory( + ILogger logger, + IHttpContextAccessor httpContextAccessor, FastTunnelServer fastTunnelServer) { - readonly ILogger logger; - readonly FastTunnelServer fastTunnelServer; - private readonly IHttpContextAccessor _httpContextAccessor; + this.fastTunnelServer = fastTunnelServer; + this.logger = logger; + _httpContextAccessor = httpContextAccessor; + } - public FastTunnelForwarderHttpClientFactory( - ILogger logger, - IHttpContextAccessor httpContextAccessor, FastTunnelServer fastTunnelServer) + protected override void ConfigureHandler(ForwarderHttpClientContext context, SocketsHttpHandler handler) + { + base.ConfigureHandler(context, handler); + handler.ConnectCallback = ConnectCallback; + } + + private async ValueTask ConnectCallback(SocketsHttpConnectionContext context, CancellationToken cancellationToken) + { + var host = context.InitialRequestMessage.RequestUri.Host; + + var contextRequest = _httpContextAccessor.HttpContext; + //var lifetime = contextRequest.Features.Get()!; + + try { - this.fastTunnelServer = fastTunnelServer; - this.logger = logger; - _httpContextAccessor = httpContextAccessor; + Interlocked.Increment(ref connectionCount); + var res = await proxyAsync(host, context, contextRequest.RequestAborted); + return res; } - - protected override void ConfigureHandler(ForwarderHttpClientContext context, SocketsHttpHandler handler) + catch (Exception) { - base.ConfigureHandler(context, handler); - handler.ConnectCallback = ConnectCallback; + throw; } - - private async ValueTask ConnectCallback(SocketsHttpConnectionContext context, CancellationToken cancellationToken) + finally { - var host = context.InitialRequestMessage.RequestUri.Host; - - var contextRequest = _httpContextAccessor.HttpContext; - //var lifetime = contextRequest.Features.Get()!; - - try - { - var res = await proxyAsync(host, context, contextRequest.RequestAborted); - return res; - } - catch (Exception) - { - throw; - } - } - - public async ValueTask proxyAsync(string host, SocketsHttpConnectionContext context, CancellationToken cancellation) - { - WebInfo web; - if (!fastTunnelServer.WebList.TryGetValue(host, out web)) - { - // 客户端已离线 - return await OfflinePage(host, context); - } - - var msgId = Guid.NewGuid().ToString().Replace("-", ""); - - TaskCompletionSource tcs = new(); - logger.LogDebug($"[Http]Swap开始 {msgId}|{host}=>{web.WebConfig.LocalIp}:{web.WebConfig.LocalPort}"); - - cancellation.Register(() => - { - logger.LogDebug($"[Proxy TimeOut]:{msgId}"); - tcs.TrySetCanceled(); - }); - - fastTunnelServer.ResponseTasks.TryAdd(msgId, (tcs, cancellation)); - - try - { - // 发送指令给客户端,等待建立隧道 - await web.Socket.SendCmdAsync(MessageType.SwapMsg, $"{msgId}|{web.WebConfig.LocalIp}:{web.WebConfig.LocalPort}", cancellation); - var res = await tcs.Task.WaitAsync(cancellation); - - logger.LogDebug($"[Http]Swap OK {msgId}"); - return res; - } - catch (WebSocketException) - { - // 通讯异常,返回客户端离线 - return await OfflinePage(host, context); - } - catch (Exception) - { - throw; - } - finally - { - fastTunnelServer.ResponseTasks.TryRemove(msgId, out _); - } - } - - - private async ValueTask OfflinePage(string host, SocketsHttpConnectionContext context) - { - var bytes = Encoding.UTF8.GetBytes( - $"HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\n\r\n{TunnelResource.Page_Offline}\r\n"); - - return await Task.FromResult(new ResponseStream(bytes)); + Interlocked.Increment(ref connectionCount); + logger.LogDebug($"统计YARP连接数:{connectionCount}"); } } + + public async ValueTask proxyAsync(string host, SocketsHttpConnectionContext context, CancellationToken cancellation) + { + WebInfo web; + if (!fastTunnelServer.WebList.TryGetValue(host, out web)) + { + // 客户端已离线 + return await OfflinePage(host, context); + } + + var msgId = Guid.NewGuid().ToString().Replace("-", ""); + + TaskCompletionSource tcs = new(); + logger.LogDebug($"[Http]Swap开始 {msgId}|{host}=>{web.WebConfig.LocalIp}:{web.WebConfig.LocalPort}"); + + cancellation.Register(() => + { + logger.LogDebug($"[Proxy TimeOut]:{msgId}"); + tcs.TrySetCanceled(); + }); + + fastTunnelServer.ResponseTasks.TryAdd(msgId, (tcs, cancellation)); + + try + { + // 发送指令给客户端,等待建立隧道 + await web.Socket.SendCmdAsync(MessageType.SwapMsg, $"{msgId}|{web.WebConfig.LocalIp}:{web.WebConfig.LocalPort}", cancellation); + var res = await tcs.Task.WaitAsync(cancellation); + + logger.LogDebug($"[Http]Swap OK {msgId}"); + return res; + } + catch (WebSocketException) + { + // 通讯异常,返回客户端离线 + return await OfflinePage(host, context); + } + catch (Exception) + { + throw; + } + finally + { + fastTunnelServer.ResponseTasks.TryRemove(msgId, out _); + } + } + + + private async ValueTask OfflinePage(string host, SocketsHttpConnectionContext context) + { + var bytes = Encoding.UTF8.GetBytes( + $"HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\n\r\n{TunnelResource.Page_Offline}\r\n"); + + return await Task.FromResult(new ResponseStream(bytes)); + } } diff --git a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs index 85711e9..8ee32db 100644 --- a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs +++ b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelClientHandler.cs @@ -24,6 +24,10 @@ namespace FastTunnel.Core.Forwarder.MiddleWare readonly Version serverVersion; readonly ILoginHandler loginHandler; + static int connectionCount; + + public static int ConnectionCount => connectionCount; + public FastTunnelClientHandler( ILogger logger, FastTunnelServer fastTunnelServer, ILoginHandler loginHandler) { @@ -44,7 +48,16 @@ namespace FastTunnel.Core.Forwarder.MiddleWare return; }; - await handleClient(context, version); + Interlocked.Increment(ref connectionCount); + + try + { + await handleClient(context, version); + } + finally + { + Interlocked.Decrement(ref connectionCount); + } } catch (Exception ex) { diff --git a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs index 9920118..a5a53e2 100644 --- a/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs +++ b/FastTunnel.Core/Forwarder/MiddleWare/FastTunnelSwapHandler.cs @@ -16,6 +16,9 @@ namespace FastTunnel.Core.Forwarder.MiddleWare { ILogger logger; FastTunnelServer fastTunnelServer; + static int connectionCount; + + public static int ConnectionCount => connectionCount; public FastTunnelSwapHandler(ILogger logger, FastTunnelServer fastTunnelServer) { @@ -25,6 +28,8 @@ namespace FastTunnel.Core.Forwarder.MiddleWare public async Task Handle(HttpContext context, Func next) { + Interlocked.Increment(ref connectionCount); + try { if (context.Request.Method != "PROXY") @@ -77,6 +82,11 @@ namespace FastTunnel.Core.Forwarder.MiddleWare { logger.LogError(ex); } + finally + { + Interlocked.Decrement(ref connectionCount); + logger.LogDebug($"统计SWAP连接数:{ConnectionCount}"); + } } } } diff --git a/FastTunnel.Core/Handlers/Client/SwapHandler.cs b/FastTunnel.Core/Handlers/Client/SwapHandler.cs index 4e078f2..2319528 100644 --- a/FastTunnel.Core/Handlers/Client/SwapHandler.cs +++ b/FastTunnel.Core/Handlers/Client/SwapHandler.cs @@ -18,6 +18,7 @@ namespace FastTunnel.Core.Handlers.Client public class SwapHandler : IClientHandler { readonly ILogger _logger; + static int connectionCount; public SwapHandler(ILogger logger) { @@ -37,6 +38,7 @@ namespace FastTunnel.Core.Handlers.Client { try { + Interlocked.Increment(ref connectionCount); _logger.LogDebug($"======Swap {requestId} Start======"); using (Stream serverStream = await createRemote(requestId, cleint, cancellationToken)) using (Stream localStream = await createLocal(requestId, address, cancellationToken)) @@ -53,7 +55,9 @@ namespace FastTunnel.Core.Handlers.Client } finally { + Interlocked.Decrement(ref connectionCount); _logger.LogDebug($"======Swap {requestId} End======"); + _logger.LogDebug($"统计SwapHandler连接数:{connectionCount}"); } }