Skip to content

Commit

Permalink
Add multi-server load balancing
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Jul 21, 2024
1 parent ad1a1f8 commit 25f3fc3
Show file tree
Hide file tree
Showing 14 changed files with 206 additions and 24 deletions.
8 changes: 4 additions & 4 deletions v2rayN/v2rayN/Handler/ConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1066,11 +1066,11 @@ private static int RemoveProfileItem(Config config, string indexId)
return 0;
}

public static int AddCustomServer4Multiple(Config config, List<ProfileItem> selecteds, out string indexId)
public static int AddCustomServer4Multiple(Config config, List<ProfileItem> selecteds, ECoreType coreType, out string indexId)
{
indexId = Utils.GetMD5(Global.CoreMultipleLoadConfigFileName);
string configPath = Utils.GetConfigPath(Global.CoreMultipleLoadConfigFileName);
if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, out string msg) != 0)
if (CoreConfigHandler.GenerateClientMultipleLoadConfig(config, configPath, selecteds, coreType, out string msg) != 0)
{
return -1;
}
Expand All @@ -1083,10 +1083,10 @@ public static int AddCustomServer4Multiple(Config config, List<ProfileItem> sele

var profileItem = LazyConfig.Instance.GetProfileItem(indexId) ?? new();
profileItem.indexId = indexId;
profileItem.remarks = "Multi-server Config";
profileItem.remarks = coreType == ECoreType.sing_box ? Resx.ResUI.menuSetDefaultMultipleServer : Resx.ResUI.menuSetDefaultLoadBalanceServer;
profileItem.address = Global.CoreMultipleLoadConfigFileName;
profileItem.configType = EConfigType.Custom;
profileItem.coreType = ECoreType.sing_box;
profileItem.coreType = coreType;

AddServerCommon(config, profileItem, true);

Expand Down
20 changes: 16 additions & 4 deletions v2rayN/v2rayN/Handler/CoreConfig/CoreConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,25 @@ public static int GenerateClientSpeedtestConfig(Config config, string fileName,
return 0;
}

public static int GenerateClientMultipleLoadConfig(Config config, string fileName, List<ProfileItem> selecteds, out string msg)
public static int GenerateClientMultipleLoadConfig(Config config, string fileName, List<ProfileItem> selecteds, ECoreType coreType, out string msg)
{
if (new CoreConfigSingbox(config).GenerateClientMultipleLoadConfig(selecteds, out SingboxConfig? singboxConfig, out msg) != 0)
msg = ResUI.CheckServerSettings;
if (coreType == ECoreType.sing_box)
{
return -1;
if (new CoreConfigSingbox(config).GenerateClientMultipleLoadConfig(selecteds, out SingboxConfig? singboxConfig, out msg) != 0)
{
return -1;
}
JsonUtils.ToFile(singboxConfig, fileName, false);
}
else if (coreType == ECoreType.Xray)
{
if (new CoreConfigV2ray(config).GenerateClientMultipleLoadConfig(selecteds, out V2rayConfig? v2rayConfig, out msg) != 0)
{
return -1;
}
JsonUtils.ToFile(v2rayConfig, fileName, false);
}
JsonUtils.ToFile(singboxConfig, fileName, false);

return 0;
}
Expand Down
130 changes: 128 additions & 2 deletions v2rayN/v2rayN/Handler/CoreConfig/CoreConfigV2ray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,130 @@ public int GenerateClientConfigContent(ProfileItem node, out V2rayConfig? v2rayC
return 0;
}

public int GenerateClientMultipleLoadConfig(List<ProfileItem> selecteds, out V2rayConfig? v2rayConfig, out string msg)
{
v2rayConfig = null;
try
{
if (_config == null)
{
msg = ResUI.CheckServerSettings;
return -1;
}

msg = ResUI.InitialConfiguration;

string result = Utils.GetEmbedText(Global.V2raySampleClient);
string txtOutbound = Utils.GetEmbedText(Global.V2raySampleOutbound);
if (Utils.IsNullOrEmpty(result) || txtOutbound.IsNullOrEmpty())
{
msg = ResUI.FailedGetDefaultConfiguration;
return -1;
}

v2rayConfig = JsonUtils.Deserialize<V2rayConfig>(result);
if (v2rayConfig == null)
{
msg = ResUI.FailedGenDefaultConfiguration;
return -1;
}

GenLog(v2rayConfig);
GenInbounds(v2rayConfig);
GenRouting(v2rayConfig);
GenDns(null, v2rayConfig);
GenStatistic(v2rayConfig);
v2rayConfig.outbounds.RemoveAt(0);

var tagProxy = new List<string>();
foreach (var it in selecteds)
{
if (it.configType == EConfigType.Custom)
{
continue;
}
if (it.configType is EConfigType.Hysteria2 or EConfigType.Tuic or EConfigType.Wireguard)
{
continue;
}
if (it.port <= 0)
{
continue;
}
var item = LazyConfig.Instance.GetProfileItem(it.indexId);
if (item is null)
{
continue;
}
if (it.configType is EConfigType.VMess or EConfigType.VLESS)
{
if (Utils.IsNullOrEmpty(item.id) || !Utils.IsGuidByParse(item.id))
{
continue;
}
}
if (item.configType == EConfigType.Shadowsocks
&& !Global.SsSecuritiesInSingbox.Contains(item.security))
{
continue;
}
if (item.configType == EConfigType.VLESS && !Global.Flows.Contains(item.flow))
{
continue;
}

//outbound
var outbound = JsonUtils.Deserialize<Outbounds4Ray>(txtOutbound);
GenOutbound(item, outbound);
outbound.tag = $"{Global.ProxyTag}-{tagProxy.Count + 1}";
v2rayConfig.outbounds.Add(outbound);
tagProxy.Add(outbound.tag);
}
if (tagProxy.Count <= 0)
{
msg = ResUI.FailedGenDefaultConfiguration;
return -1;
}

//add balancers
var balancer = new BalancersItem4Ray
{
selector = [Global.ProxyTag],
strategy = new() { type = "roundRobin" },
tag = $"{Global.ProxyTag}-round",
};
v2rayConfig.routing.balancers = [balancer];

//add rule
var rules = v2rayConfig.routing.rules.Where(t => t.outboundTag == Global.ProxyTag).ToList();
if (rules?.Count > 0)
{
foreach (var rule in rules)
{
rule.outboundTag = null;
rule.balancerTag = balancer.tag;
}
}
else
{
v2rayConfig.routing.rules.Add(new()
{
network = "tcp,udp",
balancerTag = balancer.tag,
type = "field"
});
}

return 0;
}
catch (Exception ex)
{
Logging.SaveLog(ex.Message, ex);
msg = ResUI.FailedGenDefaultConfiguration;
return -1;
}
}

public int GenerateClientSpeedtestConfig(List<ServerTestItem> selecteds, out V2rayConfig? v2rayConfig, out string msg)
{
v2rayConfig = null;
Expand Down Expand Up @@ -897,7 +1021,7 @@ private int GenBoundStreamSettings(ProfileItem node, StreamSettings4Ray streamSe
return 0;
}

private int GenDns(ProfileItem node, V2rayConfig v2rayConfig)
private int GenDns(ProfileItem? node, V2rayConfig v2rayConfig)
{
try
{
Expand Down Expand Up @@ -960,8 +1084,10 @@ private int GenDns(ProfileItem node, V2rayConfig v2rayConfig)
return 0;
}

private int GenDnsDomains(ProfileItem node, JsonNode dns)
private int GenDnsDomains(ProfileItem? node, JsonNode dns)
{
if (node == null)
{ return 0; }
var servers = dns["servers"];
if (servers != null)
{
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/v2rayN/Models/ProfileItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public string GetSummary()
switch (configType)
{
case EConfigType.Custom:
summary += string.Format("{0}", remarks);
summary += string.Format("[{1}]{0}", remarks, coreType.ToString());
break;

default:
Expand Down
16 changes: 16 additions & 0 deletions v2rayN/v2rayN/Models/V2rayConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,8 @@ public class Routing4Ray
///
/// </summary>
public List<RulesItem4Ray> rules { get; set; }

public List<BalancersItem4Ray>? balancers { get; set; }
}

[Serializable]
Expand All @@ -406,13 +408,27 @@ public class RulesItem4Ray

public string? outboundTag { get; set; }

public string? balancerTag { get; set; }

public List<string>? ip { get; set; }

public List<string>? domain { get; set; }

public List<string>? protocol { get; set; }
}

public class BalancersItem4Ray
{
public List<string>? selector { get; set; }
public BalancersStrategy4Ray? strategy { get; set; }
public string? tag { get; set; }
}

public class BalancersStrategy4Ray
{
public string? type { get; set; }
}

public class StreamSettings4Ray
{
/// <summary>
Expand Down
11 changes: 10 additions & 1 deletion v2rayN/v2rayN/Resx/ResUI.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion v2rayN/v2rayN/Resx/ResUI.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1247,9 +1247,12 @@
<value>Default domain strategy for outbound</value>
</data>
<data name="menuSetDefaultMultipleServer" xml:space="preserve">
<value>Multi-server set to active</value>
<value>Multi-Server Preferred Latency</value>
</data>
<data name="TbSettingsMainGirdOrientation" xml:space="preserve">
<value>Main layout orientation(Require restart)</value>
</data>
<data name="menuSetDefaultLoadBalanceServer" xml:space="preserve">
<value>Multi-server load balancing</value>
</data>
</root>
5 changes: 4 additions & 1 deletion v2rayN/v2rayN/Resx/ResUI.zh-Hans.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1244,9 +1244,12 @@
<value>Outbound默认解析策略</value>
</data>
<data name="menuSetDefaultMultipleServer" xml:space="preserve">
<value>多服务器设为活动(多选)</value>
<value>多服务器优选延迟 (多选)</value>
</data>
<data name="TbSettingsMainGirdOrientation" xml:space="preserve">
<value>主界面布局方向(需重启)</value>
</data>
<data name="menuSetDefaultLoadBalanceServer" xml:space="preserve">
<value>多服务器负载均衡 (多选)</value>
</data>
</root>
4 changes: 2 additions & 2 deletions v2rayN/v2rayN/ViewModels/ClashProxiesViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ private void GetClashProxies(bool refreshUI)
{
ClashApiHandler.Instance.GetClashProxies(_config, (it, it2) =>
{
UpdateHandler(false, "Refresh Clash Proxies");
//UpdateHandler(false, "Refresh Clash Proxies");
proxies = it?.proxies;
providers = it2?.providers;
Expand Down Expand Up @@ -413,7 +413,7 @@ public void SetActiveProxy()

private void ProxiesDelayTest(bool blAll)
{
UpdateHandler(false, "Clash Proxies Latency Test");
//UpdateHandler(false, "Clash Proxies Latency Test");

ClashApiHandler.Instance.ClashProxiesDelayTest(blAll, _proxyDetails.ToList(), (item, result) =>
{
Expand Down
12 changes: 9 additions & 3 deletions v2rayN/v2rayN/ViewModels/ProfilesViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public class ProfilesViewModel : ReactiveObject
public ReactiveCommand<Unit, Unit> SetDefaultServerCmd { get; }
public ReactiveCommand<Unit, Unit> ShareServerCmd { get; }
public ReactiveCommand<Unit, Unit> SetDefaultMultipleServerCmd { get; }
public ReactiveCommand<Unit, Unit> SetDefaultLoadBalanceServerCmd { get; }

//servers move
public ReactiveCommand<Unit, Unit> MoveTopCmd { get; }
Expand Down Expand Up @@ -170,8 +171,13 @@ public ProfilesViewModel(Action<EViewAction> updateView)
}, canEditRemove);
SetDefaultMultipleServerCmd = ReactiveCommand.Create(() =>
{
SetDefaultMultipleServer();
SetDefaultMultipleServer(ECoreType.sing_box);
}, canEditRemove);
SetDefaultLoadBalanceServerCmd = ReactiveCommand.Create(() =>
{
SetDefaultMultipleServer(ECoreType.Xray);
}, canEditRemove);

//servers move
MoveTopCmd = ReactiveCommand.Create(() =>
{
Expand Down Expand Up @@ -612,14 +618,14 @@ public async void ShareServer()
await DialogHost.Show(dialog, "RootDialog");
}

private void SetDefaultMultipleServer()
private void SetDefaultMultipleServer(ECoreType coreType)
{
if (GetProfileItems(out List<ProfileItem> lstSelecteds, true) < 0)
{
return;
}

if (ConfigHandler.AddCustomServer4Multiple(_config, lstSelecteds, out string indexId) != 0)
if (ConfigHandler.AddCustomServer4Multiple(_config, lstSelecteds, coreType, out string indexId) != 0)
{
_noticeHandler?.Enqueue(ResUI.OperationFailed);
return;
Expand Down
4 changes: 2 additions & 2 deletions v2rayN/v2rayN/Views/ClashConnectionsView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<ComboBox
x:Name="cmbSorting"
Width="100"
Margin="8"
Margin="8,0"
Style="{StaticResource DefComboBox}">
<ComboBoxItem Content="{x:Static resx:ResUI.TbSortingUpSpeed}" />
<ComboBoxItem Content="{x:Static resx:ResUI.TbSortingDownSpeed}" />
Expand All @@ -55,7 +55,7 @@
Text="{x:Static resx:ResUI.TbAutoRefresh}" />
<ToggleButton
x:Name="togAutoRefresh"
Margin="8"
Margin="8,0"
HorizontalAlignment="Left" />
</WrapPanel>

Expand Down
Loading

0 comments on commit 25f3fc3

Please sign in to comment.