add some log

This commit is contained in:
Gui.H 2022-11-06 13:00:57 +08:00
parent 7dc0859cd0
commit ba69f423d5
5 changed files with 128 additions and 92 deletions

View File

@ -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();
}

View File

@ -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<FastTunnelForwarderHttpClientFactory> logger;
readonly FastTunnelServer fastTunnelServer;
private readonly IHttpContextAccessor _httpContextAccessor;
static int connectionCount;
public FastTunnelForwarderHttpClientFactory(
ILogger<FastTunnelForwarderHttpClientFactory> logger,
IHttpContextAccessor httpContextAccessor, FastTunnelServer fastTunnelServer)
{
readonly ILogger<FastTunnelForwarderHttpClientFactory> logger;
readonly FastTunnelServer fastTunnelServer;
private readonly IHttpContextAccessor _httpContextAccessor;
this.fastTunnelServer = fastTunnelServer;
this.logger = logger;
_httpContextAccessor = httpContextAccessor;
}
public FastTunnelForwarderHttpClientFactory(
ILogger<FastTunnelForwarderHttpClientFactory> logger,
IHttpContextAccessor httpContextAccessor, FastTunnelServer fastTunnelServer)
protected override void ConfigureHandler(ForwarderHttpClientContext context, SocketsHttpHandler handler)
{
base.ConfigureHandler(context, handler);
handler.ConnectCallback = ConnectCallback;
}
private async ValueTask<Stream> ConnectCallback(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
{
var host = context.InitialRequestMessage.RequestUri.Host;
var contextRequest = _httpContextAccessor.HttpContext;
//var lifetime = contextRequest.Features.Get<IConnectionLifetimeFeature>()!;
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<Stream> ConnectCallback(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
finally
{
var host = context.InitialRequestMessage.RequestUri.Host;
var contextRequest = _httpContextAccessor.HttpContext;
//var lifetime = contextRequest.Features.Get<IConnectionLifetimeFeature>()!;
try
{
var res = await proxyAsync(host, context, contextRequest.RequestAborted);
return res;
}
catch (Exception)
{
throw;
}
}
public async ValueTask<Stream> 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<Stream> 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<Stream> 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<Stream> 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<Stream> 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<Stream> 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));
}
}

View File

@ -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<FastTunnelClientHandler> 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)
{

View File

@ -16,6 +16,9 @@ namespace FastTunnel.Core.Forwarder.MiddleWare
{
ILogger<FastTunnelClientHandler> logger;
FastTunnelServer fastTunnelServer;
static int connectionCount;
public static int ConnectionCount => connectionCount;
public FastTunnelSwapHandler(ILogger<FastTunnelClientHandler> logger, FastTunnelServer fastTunnelServer)
{
@ -25,6 +28,8 @@ namespace FastTunnel.Core.Forwarder.MiddleWare
public async Task Handle(HttpContext context, Func<Task> 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}");
}
}
}
}

View File

@ -18,6 +18,7 @@ namespace FastTunnel.Core.Handlers.Client
public class SwapHandler : IClientHandler
{
readonly ILogger<SwapHandler> _logger;
static int connectionCount;
public SwapHandler(ILogger<SwapHandler> 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}");
}
}