/// <summary> /// Initializes a new instance. /// </summary> /// <param name="createModel">Creates the model that should be checked.</param> /// <param name="output">The callback that should be used to output messages.</param> /// <param name="configuration">The analysis configuration that should be used.</param> internal ModelTraverser(Func<AnalysisModel> createModel, Action<string> output, AnalysisConfiguration configuration) { Requires.NotNull(createModel, nameof(createModel)); Requires.NotNull(output, nameof(output)); TransitionCollection.ValidateTransitionSizes(); var tasks = new Task[configuration.CpuCount]; var stacks = new StateStack[configuration.CpuCount]; _loadBalancer = new LoadBalancer(stacks); Context = new TraversalContext(_loadBalancer, configuration, output); _workers = new Worker[configuration.CpuCount]; for (var i = 0; i < configuration.CpuCount; ++i) { var index = i; tasks[i] = Task.Factory.StartNew(() => { stacks[index] = new StateStack(configuration.StackCapacity); _workers[index] = new Worker(index, Context, stacks[index], createModel()); }); } Task.WaitAll(tasks); _states = new StateStorage(_workers[0].Model.StateVectorSize, configuration.StateCapacity); Context.States = _states; }
public void Basics() { Server server; this.balancer = new LoadBalancer<Server>(); bool result = this.balancer.TryGetServer(out server); Assert.IsFalse(result); result = this.balancer.TryAddServer(this.servers[0], FeedbackLevel.Highest); Assert.IsTrue(result); result = this.balancer.TryAddServer(this.servers[0], FeedbackLevel.Highest); Assert.IsFalse(result); result = this.balancer.TryGetServer(out server); Assert.IsFalse(result); result = this.balancer.TryUpdateServer(this.servers[0], FeedbackLevel.Normal); Assert.IsTrue(result); result = this.balancer.TryGetServer(out server); Assert.IsTrue(result); Assert.AreSame(this.servers[0], server); result = this.balancer.TryRemoveServer(this.servers[0]); Assert.IsTrue(result); result = this.balancer.TryRemoveServer(this.servers[0]); Assert.IsFalse(result); }
protected string GetLoadBalancerType(LoadBalancer b) { if (b != null && b.FrontendIPConfiguration != null) { return b.FrontendIPConfiguration.Type; } return null; }
public LoadBalancerProperties(CloudLoadBalancerProvider provider, LoadBalancer loadBalancer) { if (provider == null) throw new ArgumentNullException("provider"); if (loadBalancer == null) throw new ArgumentNullException("loadBalancer"); _provider = provider; _loadBalancer = loadBalancer; }
public GameApplication(string applicationId, LoadBalancer<IncomingGameServerPeer> loadBalancer) { if (log.IsDebugEnabled) { log.DebugFormat("Creating application: appId={0}", applicationId); } this.ApplicationId = applicationId; this.LoadBalancer = loadBalancer; this.PlayerOnlineCache = new PlayerCache(); this.LobbyFactory = new LobbyFactory(this); }
public void overloaded_calls_should_throw_exception() { var agent1 = new Agent("A1"); var agent2 = new Agent("A2"); var agents = new ConcurrentQueue<Agent>(new[] { agent1, agent2 }); var loadBalancer = new LoadBalancer(); loadBalancer.AssignInteraction(new CallInteraction("12345"), agents); loadBalancer.AssignInteraction(new CallInteraction("23456"), agents); loadBalancer.AssignInteraction(new CallInteraction("34567"), agents); }
public AppLobby(LoadBalancer<IncomingGameServerPeer> loadBalancer, int maxPlayersDefault, TimeSpan joinTimeOut) { this.MaxPlayersDefault = maxPlayersDefault; this.JoinTimeOut = joinTimeOut; this.ExecutionFiber = new PoolFiber(); this.ExecutionFiber.Start(); this.LoadBalancer = loadBalancer; this.GameList = new GameList(); this.ExecutionFiber.Schedule(this.CheckJoinTimeOuts, (long)joinTimeOut.TotalMilliseconds / 2); }
public void Setup() { LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance); XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config")); this.balancer = new LoadBalancer<Server>(); this.servers = new List<Server>(); for (int i = 0; i < 5; i++) { this.servers.Add(new Server { Name = "Server" + i }); } }
public async Task FarmDisconnectRaisesUncleanDisconnects() { // Each node shares the same bus but are independent servers const int nodeCount = 3; var counters = new Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); configurationManager.DisconnectTimeout = TimeSpan.FromSeconds(6); using (EnableDisposableTracing()) using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) using (var loadBalancer = new LoadBalancer(nodeCount)) { var broadcasters = new List<IConnection>(); var disconnectCounter = new DisconnectCounter(); loadBalancer.Configure(app => { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(IMessageBus), () => bus); resolver.Register(typeof(IConfigurationManager), () => configurationManager); resolver.Register(typeof(FarmConnection), () => new FarmConnection(disconnectCounter)); var connectionManager = resolver.Resolve<IConnectionManager>(); broadcasters.Add(connectionManager.GetConnectionContext<FarmConnection>().Connection); app.MapSignalR<FarmConnection>("/echo", new ConnectionConfiguration { Resolver = resolver }); }); var transport = new Client.Transports.LongPollingTransport(loadBalancer); var connection = new Client.Connection("http://goo/echo"); await connection.Start(transport); for (int i = 0; i < nodeCount; i++) { broadcasters[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)).Wait(); await Task.Delay(TimeSpan.FromSeconds(1)); } ((Client.IConnection)connection).Disconnect(); await Task.Delay(TimeSpan.FromTicks(TimeSpan.FromSeconds(5).Ticks * nodeCount)); Assert.Equal(0, disconnectCounter.CleanDisconnectCount); Assert.Equal(3, disconnectCounter.UncleanDisconnectCount); } }
public void RequestResponse() { using (var lb = new LoadBalancer("tcp://*:5557", "tcp://*:5558")) using (var client = new Client("tcp://localhost:5557")) using (var worker = new Worker(new Handler(), "tcp://localhost:5558")) { worker.Register("Hello"); // Wait for the lb to process the register Thread.Sleep(100); var reply = (string)client.SendRequestAsync("Hello", "World").Result; Assert.That(reply == "Welcome"); } }
public static LoadBalancer GetLoadBalancer() { // Support multithreaded applications through 'Double checked locking' pattern // which (once the instance exists) avoids locking each time the method is invoked if (_instance == null) { lock (syncLock) { if (_instance == null) { _instance = new LoadBalancer(); } } } return _instance; }
// Methods public static LoadBalancer GetLoadBalancer() { // Support multithreaded applications through // "Double checked locking" pattern which avoids // locking every time the method is invoked if( balancer == null ) { // Only one thread can obtain a mutex Mutex mutex = new Mutex(); mutex.WaitOne(); if( balancer == null ) balancer = new LoadBalancer(); mutex.Close(); } return balancer; }
public void Basics() { Server server; this.balancer = new LoadBalancer<Server>(); this.TryGetServer(out server, false); this.TryUpdateServer(this.servers[0], FeedbackLevel.Low, false); this.TryAddServer(this.servers[0], FeedbackLevel.Highest); this.TryGetServer(out server, false); this.TryAddServer(this.servers[1], FeedbackLevel.Highest); this.TryGetServer(out server, false); this.TryUpdateServer(this.servers[0], FeedbackLevel.Normal); this.TryGetServer(out server); Assert.AreSame(this.servers[0], server); this.TryRemoveServer(this.servers[0]); this.TryRemoveServer(this.servers[0], false); }
public void adding_interactions_should_be_balanced_between_agents() { var agent1 = new Agent("A1"); var agent2 = new Agent("A2"); var agents = new ConcurrentQueue<Agent>(new[] { agent1, agent2 }); var loadBalancer = new LoadBalancer(); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); agent1.Emails.Count.Should().Be(5); agent2.Emails.Count.Should().Be(4); }
public void interactions_should_be_added_to_agents() { var agent1 = new Agent("A1"); var agent2 = new Agent("A2"); var call = new CallInteraction("12345"); var email = new EmailInteraction("*****@*****.**"); var agents = new ConcurrentQueue<Agent>(new [] {agent1, agent2}); var loadBalancer = new LoadBalancer(); var callAgent = loadBalancer.AssignInteraction(call, agents); var emailAgent = loadBalancer.AssignInteraction(email, agents); callAgent.Should().Be(agent1); callAgent.Calls.Count.Should().Be(1); callAgent.Calls.First().Should().Be(call); emailAgent.Should().Be(agent2); emailAgent.Emails.Count.Should().Be(1); emailAgent.Emails.First().Should().Be(email); }
public GameApplication(string applicationId, string version, LoadBalancer<IncomingGameServerPeer> loadBalancer) { if (log.IsDebugEnabled) { log.DebugFormat("Creating application: appId={0}", applicationId); } this.ApplicationId = applicationId; this.LoadBalancer = loadBalancer; this.Version = version; this.PlayerOnlineCache = new PlayerCache(); this.LobbyFactory = new LobbyFactory(this); this.LobbyFactory.Initialize(); this.LobbyStatsPublisher = new LobbyStatsPublisher( this.LobbyFactory, MasterServerSettings.Default.LobbyStatsPublishInterval, MasterServerSettings.Default.LobbyStatsLimit); this.fiber = new PoolFiber(); this.fiber.Start(); if (MasterServerSettings.Default.PersistentGameExpiryMinute != 0) { var checkTime = MasterServerSettings.Default.GameExpiryCheckPeriod * 60000; this.expiryCheckDisposable = this.fiber.Schedule(this.CheckExpiredGames, checkTime); } this.SetupTokenCreator(); this.UpdatePluginTraits(); if (!this.ConnectToRedis()) { return; } this.PopulateGameListFromRedis(); }
public async Task FarmDisconnectOnlyRaisesUncleanDisconnects() { EnableTracing(); // Each node shares the same bus but are indepenent servers var counters = new SignalR.Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); var protectedData = new DefaultProtectedData(); using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) { var nodeCount = 3; var nodes = new List<ServerNode>(); for (int i = 0; i < nodeCount; i++) { nodes.Add(new ServerNode(bus)); } var timeout = TimeSpan.FromSeconds(5); foreach (var node in nodes) { var config = node.Resolver.Resolve<IConfigurationManager>(); config.DisconnectTimeout = TimeSpan.FromSeconds(6); IDependencyResolver resolver = node.Resolver; node.Server.Configure(app => { app.MapSignalR<FarmConnection>("/echo", new ConnectionConfiguration { Resolver = resolver }); resolver.Register(typeof(IProtectedData), () => protectedData); }); } var loadBalancer = new LoadBalancer(nodes.Select(f => f.Server).ToArray()); var transport = new Client.Transports.LongPollingTransport(loadBalancer); var connection = new Client.Connection("http://goo/echo"); await connection.Start(transport); for (int i = 0; i < nodes.Count; i++) { nodes[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)); await Task.Delay(TimeSpan.FromSeconds(1)); } ((Client.IConnection)connection).Disconnect(); await Task.Delay(TimeSpan.FromTicks(timeout.Ticks * nodes.Count)); Assert.Equal(0, FarmConnection.OldOnDisconnectedCalls); Assert.Equal(0, FarmConnection.CleanDisconnectCount); Assert.Equal(3, FarmConnection.UncleanDisconnectCount); } }
public void FarmDisconnectOnlyRaisesEventOnce() { // Each node shares the same bus but are indepenent servers var counters = new SignalR.Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) { var nodeCount = 3; var nodes = new List<ServerNode>(); for (int i = 0; i < nodeCount; i++) { nodes.Add(new ServerNode(bus)); } var timeout = TimeSpan.FromSeconds(5); foreach (var node in nodes) { var config = node.Resolver.Resolve<IConfigurationManager>(); config.DisconnectTimeout = TimeSpan.FromSeconds(6); IDependencyResolver resolver = node.Resolver; node.Server.Configure(app => { app.MapConnection<FarmConnection>("/echo", new ConnectionConfiguration { Resolver = resolver }); }); } var loadBalancer = new LoadBalancer(nodes.Select(f => f.Server).ToArray()); var transport = new Client.Transports.LongPollingTransport(loadBalancer); var connection = new Client.Connection("http://goo/echo"); connection.Start(transport).Wait(); for (int i = 0; i < nodes.Count; i++) { nodes[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)); Thread.Sleep(TimeSpan.FromSeconds(1)); } connection.Disconnect(); Thread.Sleep(TimeSpan.FromTicks(timeout.Ticks * nodes.Count)); Assert.Equal(1, nodes.Sum(n => n.Connection.DisconnectCount)); } }
public NodeRegistry() { Nodes = new LoadBalancer <string>(10000); }
public void LoadSpreadAfterConfigChange() { const int Count = 100000; var configPath = "LoadBalancer.config"; this.balancer = new LoadBalancer<Server>(configPath); for (int i = 0; i < this.servers.Count; i++) { bool result = this.balancer.TryAddServer(this.servers[i], FeedbackLevel.Lowest); Assert.IsTrue(result); } // 5 servers with a load level of lowest // every server should get about 20 percent of the assigments this.AssignServerLoop(Count); for (int i = 0; i < this.servers.Count; i++) { this.CheckServer(this.servers[i], Count, 20, 5); } this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.High); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 25, 5); this.CheckServer(this.servers[1], Count, 25, 5); this.CheckServer(this.servers[2], Count, 25, 5); this.CheckServer(this.servers[3], Count, 25, 5); this.CheckServer(this.servers[4], Count, 0, 0); File.Copy("LoadBalancer.config", "LoadBalancer.config.bak", true); File.Delete("LoadBalancer.config"); // wait a bit until the update is done: Thread.Sleep(1000); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 40, 5); this.CheckServer(this.servers[1], Count, 30, 5); this.CheckServer(this.servers[2], Count, 20, 5); this.CheckServer(this.servers[3], Count, 10, 5); this.CheckServer(this.servers[4], Count, 0, 0); File.Copy("LoadBalancer.config.bak", "LoadBalancer.config", true); // wait a bit until the update is done: Thread.Sleep(1000); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 25, 5); this.CheckServer(this.servers[1], Count, 25, 5); this.CheckServer(this.servers[2], Count, 25, 5); this.CheckServer(this.servers[3], Count, 25, 5); this.CheckServer(this.servers[4], Count, 0, 0); }
public void FarmDisconnectOnlyRaisesEventOnce() { // Each node shares the same bus but are indepenent servers var bus = new InProcessMessageBus(new TraceManager(), garbageCollectMessages: false); var nodeCount = 3; var nodes = new List<ServerNode>(); for (int i = 0; i < nodeCount; i++) { nodes.Add(new ServerNode(bus)); } var timeout = TimeSpan.FromSeconds(5); foreach (var node in nodes) { node.Server.Configuration.HeartBeatInterval = timeout; node.Server.Configuration.DisconnectTimeout = TimeSpan.Zero; node.Server.MapConnection<FarmConnection>("/echo"); } var loadBalancer = new LoadBalancer(nodes.Select(f => f.Server).ToArray()); var transport = new Client.Transports.LongPollingTransport(loadBalancer); var connection = new Client.Connection("http://goo/echo"); connection.Start(transport).Wait(); for (int i = 0; i < nodes.Count; i++) { nodes[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)); Thread.Sleep(TimeSpan.FromSeconds(1)); } Thread.Sleep(TimeSpan.FromTicks(timeout.Ticks * nodes.Count)); Assert.Equal(1, nodes.Sum(n => n.Connection.DisconnectCount)); }
public async Task <Module> UpdateHealthStatus(Guid moduleId, int readyReplicas, IEnumerable <ReplicaStatus> replicaStatuses, LoadBalancer loadBalancer) { return(await Collection().FindOneAndUpdateAsync(t => t.Id == moduleId, Update .Set(t => t.CurrentReadyReplicas, readyReplicas) .Set(t => t.ReplicaLogs, replicaStatuses) .Set(t => t.LoadBalancer, loadBalancer))); }
private VirtualMachineScaleSetNetworkProfile CreateNetworkResource(VirtualMachineScaleSetNetworkConfiguration existingNetworkConfig) { var suffix = $"{this.Name.ToLower()}-{this.NodeType.ToLower()}"; var publicAddressName = $"LBIP-{suffix}"; var dnsLabel = $"dns-{suffix}"; var lbName = $"LB-{suffix}"; var nicName = $"NIC-{suffix}"; var ipconfigName = $"IpCfg-{suffix}"; var ipConfiguration = existingNetworkConfig.IpConfigurations.FirstOrDefault(); if (ipConfiguration == null) { throw new PSInvalidOperationException(ServiceFabricProperties.Resources.InvalidVmssNetworkConfiguration); } this.addressPrefix = GetSubnetAddressPrefix(ipConfiguration); var publicIp = NetworkManagementClient.PublicIPAddresses.CreateOrUpdate( this.ResourceGroupName, publicAddressName, new PublicIPAddress() { PublicIPAllocationMethod = "Dynamic", Location = GetLocation(), DnsSettings = new PublicIPAddressDnsSettings(dnsLabel) }); var backendAddressPoolName = "LoadBalancerBEAddressPool"; var frontendIpConfigurationName = "LoadBalancerIPConfig"; var probeName = "FabricGatewayProbe"; var probeHTTPName = "FabricHttpGatewayProbe"; var inboundNatPoolName = "LoadBalancerBEAddressNatPool"; var newLoadBalancerId = string.Format( LoadBalancerIdFormat, this.NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName); var newLoadBalancer = new LoadBalancer(newLoadBalancerId, lbName) { Location = GetLocation(), FrontendIPConfigurations = new List <FrontendIPConfiguration>() { new FrontendIPConfiguration() { Name = frontendIpConfigurationName, PublicIPAddress = new PublicIPAddress() { Id = publicIp.Id } } }, BackendAddressPools = new List <BackendAddressPool>() { new BackendAddressPool() { Name = backendAddressPoolName } }, LoadBalancingRules = new List <LoadBalancingRule>() { new LoadBalancingRule() { Name = "LBRule", BackendAddressPool = new Management.Network.Models.SubResource() { Id = string.Format( BackendAddressIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, backendAddressPoolName) }, BackendPort = Constants.DefaultTcpPort, EnableFloatingIP = false, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPort = Constants.DefaultTcpPort, IdleTimeoutInMinutes = 5, Protocol = "tcp", Probe = new Management.Network.Models.SubResource() { Id = string.Format( ProbeIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, probeName) } }, new LoadBalancingRule() { Name = "LBHttpRule", BackendAddressPool = new Management.Network.Models.SubResource() { Id = string.Format( BackendAddressIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, backendAddressPoolName) }, BackendPort = Constants.DefaultHttpPort, EnableFloatingIP = false, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPort = Constants.DefaultHttpPort, IdleTimeoutInMinutes = 5, Protocol = "tcp", Probe = new Management.Network.Models.SubResource() { Id = string.Format( ProbeIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, probeHTTPName) } } }, Probes = new List <Probe>() { new Probe() { Name = probeName, IntervalInSeconds = 5, NumberOfProbes = 2, Port = Constants.DefaultTcpPort }, new Probe() { Name = probeHTTPName, IntervalInSeconds = 5, NumberOfProbes = 2, Port = Constants.DefaultHttpPort }, }, InboundNatPools = new List <InboundNatPool>() { new InboundNatPool() { Name = inboundNatPoolName, BackendPort = Constants.DefaultBackendPort, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPortRangeStart = Constants.DefaultFrontendPortRangeStart, FrontendPortRangeEnd = Constants.DefaultFrontendPortRangeEnd, Protocol = "tcp" } } }; NetworkManagementClient.LoadBalancers.BeginCreateOrUpdate( this.ResourceGroupName, lbName, newLoadBalancer); newLoadBalancer = NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, lbName); return(new VirtualMachineScaleSetNetworkProfile() { NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>() { new VirtualMachineScaleSetNetworkConfiguration() { IpConfigurations = new List <VirtualMachineScaleSetIPConfiguration>() { new VirtualMachineScaleSetIPConfiguration() { Name = ipconfigName, LoadBalancerBackendAddressPools = newLoadBalancer.BackendAddressPools.Select( b => new Management.Compute.Models.SubResource() { Id = b.Id } ).ToList(), LoadBalancerInboundNatPools = newLoadBalancer.InboundNatPools.Select( p => new Management.Compute.Models.SubResource() { Id = p.Id } ).ToList(), Subnet = new ApiEntityReference() { Id = ipConfiguration.Subnet.Id } } }, Name = nicName, Primary = true } } }); }
public async Task ExpandResourceTest() { string resourceGroupName = Recording.GenerateAssetName("csmrg"); string location = await NetworkManagementTestUtilities.GetResourceLocation(ResourceManagementClient, "Microsoft.Network/loadBalancers"); await ResourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroup(location)); // Create lbPublicIP string lbPublicIpName = Recording.GenerateAssetName("azsmnet"); string lbDomaingNameLabel = Recording.GenerateAssetName("azsmnet"); PublicIPAddress lbPublicIp = await CreateDefaultPublicIpAddress( lbPublicIpName, resourceGroupName, lbDomaingNameLabel, location, NetworkManagementClient); // Create Vnet string vnetName = Recording.GenerateAssetName("azsmnet"); string subnetName = Recording.GenerateAssetName("azsmnet"); VirtualNetwork vnet = await CreateVirtualNetwork(vnetName, subnetName, resourceGroupName, location, NetworkManagementClient); // Create Nics string nic1name = Recording.GenerateAssetName("azsmnet"); string nic2name = Recording.GenerateAssetName("azsmnet"); string nic3name = Recording.GenerateAssetName("azsmnet"); NetworkInterface nic1 = await CreateNetworkInterface( nic1name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", NetworkManagementClient); NetworkInterface nic2 = await CreateNetworkInterface( nic2name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", NetworkManagementClient); NetworkInterface nic3 = await CreateNetworkInterface( nic3name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", NetworkManagementClient); // Create the LoadBalancer var lbName = Recording.GenerateAssetName("azsmnet"); var frontendIpConfigName = Recording.GenerateAssetName("azsmnet"); var backEndAddressPoolName = Recording.GenerateAssetName("azsmnet"); var loadBalancingRuleName = Recording.GenerateAssetName("azsmnet"); var probeName = Recording.GenerateAssetName("azsmnet"); var inboundNatRule1Name = Recording.GenerateAssetName("azsmnet"); var inboundNatRule2Name = Recording.GenerateAssetName("azsmnet"); // Populate the loadBalancerCreateOrUpdateParameter LoadBalancer loadBalancer = new LoadBalancer() { Location = location, FrontendIPConfigurations = { new FrontendIPConfiguration() { Name = frontendIpConfigName, PublicIPAddress = new PublicIPAddress() { Id = lbPublicIp.Id } } }, BackendAddressPools = { new BackendAddressPool() { Name = backEndAddressPoolName, } }, LoadBalancingRules = { new LoadBalancingRule() { Name = loadBalancingRuleName, FrontendIPConfiguration = new SubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 80, BackendPort = 80, EnableFloatingIP = false, IdleTimeoutInMinutes = 15, BackendAddressPool = new SubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "backendAddressPools", backEndAddressPoolName) }, Probe = new SubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "probes", probeName) } } }, Probes = { new Probe() { Name = probeName, Protocol = ProbeProtocol.Http, Port = 80, RequestPath = "healthcheck.aspx", IntervalInSeconds = 10, NumberOfProbes = 2 } }, InboundNatRules = { new InboundNatRule() { Name = inboundNatRule1Name, FrontendIPConfiguration = new SubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3389, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false }, new InboundNatRule() { Name = inboundNatRule2Name, FrontendIPConfiguration = new SubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3390, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false, } } }; // Create the loadBalancer Operation <LoadBalancer> putLoadBalancerOperation = await NetworkManagementClient.LoadBalancers.StartCreateOrUpdateAsync(resourceGroupName, lbName, loadBalancer); await WaitForCompletionAsync(putLoadBalancerOperation); Response <LoadBalancer> getLoadBalancer = await NetworkManagementClient.LoadBalancers.GetAsync(resourceGroupName, lbName); // Associate the nic with LB nic1.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(getLoadBalancer.Value.BackendAddressPools.First()); nic1.IpConfigurations.First().LoadBalancerInboundNatRules.Add(getLoadBalancer.Value.InboundNatRules.First()); nic2.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(getLoadBalancer.Value.BackendAddressPools.First()); nic3.IpConfigurations.First().LoadBalancerInboundNatRules.Add(getLoadBalancer.Value.InboundNatRules[1]); // Put Nics NetworkInterfacesCreateOrUpdateOperation createOrUpdateOperation1 = await NetworkManagementClient.NetworkInterfaces.StartCreateOrUpdateAsync(resourceGroupName, nic1name, nic1); await WaitForCompletionAsync(createOrUpdateOperation1); NetworkInterfacesCreateOrUpdateOperation createOrUpdateOperation2 = await NetworkManagementClient.NetworkInterfaces.StartCreateOrUpdateAsync(resourceGroupName, nic2name, nic2); await WaitForCompletionAsync(createOrUpdateOperation2); NetworkInterfacesCreateOrUpdateOperation createOrUpdateOperation3 = await NetworkManagementClient.NetworkInterfaces.StartCreateOrUpdateAsync(resourceGroupName, nic3name, nic3); await WaitForCompletionAsync(createOrUpdateOperation3); // Get Nics await NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, nic1name); await NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, nic2name); await NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, nic3name); // Get lb with expanded nics from nat rules getLoadBalancer = await NetworkManagementClient.LoadBalancers.GetAsync(resourceGroupName, lbName, "InboundNatRules/backendIPConfiguration"); foreach (InboundNatRule natRule in getLoadBalancer.Value.InboundNatRules) { Assert.NotNull(natRule.BackendIPConfiguration); Assert.NotNull(natRule.BackendIPConfiguration.Id); Assert.NotNull(natRule.BackendIPConfiguration.Name); Assert.NotNull(natRule.BackendIPConfiguration.Etag); Assert.AreEqual(natRule.Id, natRule.BackendIPConfiguration.LoadBalancerInboundNatRules[0].Id); } // Get lb with expanded nics from pools getLoadBalancer = await NetworkManagementClient.LoadBalancers.GetAsync(resourceGroupName, lbName, "BackendAddressPools/backendIPConfigurations"); foreach (BackendAddressPool pool in getLoadBalancer.Value.BackendAddressPools) { foreach (NetworkInterfaceIPConfiguration ipconfig in getLoadBalancer.Value.BackendAddressPools.First().BackendIPConfigurations) { Assert.NotNull(ipconfig.Id); Assert.NotNull(ipconfig.Name); Assert.NotNull(ipconfig.Etag); Assert.AreEqual(pool.Id, ipconfig.LoadBalancerBackendAddressPools[0].Id); } } // Get lb with expanded publicip getLoadBalancer = await NetworkManagementClient.LoadBalancers.GetAsync(resourceGroupName, lbName, "FrontendIPConfigurations/PublicIPAddress"); foreach (FrontendIPConfiguration ipconfig in getLoadBalancer.Value.FrontendIPConfigurations) { Assert.NotNull(ipconfig.PublicIPAddress); Assert.NotNull(ipconfig.PublicIPAddress.Id); Assert.NotNull(ipconfig.PublicIPAddress.Name); Assert.NotNull(ipconfig.PublicIPAddress.Etag); Assert.AreEqual(ipconfig.Id, ipconfig.PublicIPAddress.IpConfiguration.Id); } // Get NIC with expanded subnet nic1 = await NetworkManagementClient.NetworkInterfaces.GetAsync(resourceGroupName, nic1name, "IPConfigurations/Subnet"); foreach (NetworkInterfaceIPConfiguration ipconfig in nic1.IpConfigurations) { Assert.NotNull(ipconfig.Subnet); Assert.NotNull(ipconfig.Subnet.Id); Assert.NotNull(ipconfig.Subnet.Name); Assert.NotNull(ipconfig.Subnet.Etag); Assert.IsNotEmpty(ipconfig.Subnet.IpConfigurations); } // Get subnet with expanded ipconfigurations Response <Subnet> subnet = await NetworkManagementClient.Subnets.GetAsync( resourceGroupName, vnetName, subnetName, "IPConfigurations"); foreach (IPConfiguration ipconfig in subnet.Value.IpConfigurations) { Assert.NotNull(ipconfig.Name); Assert.NotNull(ipconfig.Id); Assert.NotNull(ipconfig.Etag); Assert.NotNull(ipconfig.PrivateIPAddress); } // Get publicIPAddress with expanded ipconfigurations Response <PublicIPAddress> publicip = await NetworkManagementClient.PublicIPAddresses.GetAsync( resourceGroupName, lbPublicIpName, "IPConfiguration"); Assert.NotNull(publicip.Value.IpConfiguration); Assert.NotNull(publicip.Value.IpConfiguration.Id); Assert.NotNull(publicip.Value.IpConfiguration.Name); Assert.NotNull(publicip.Value.IpConfiguration.Etag); // Delete LoadBalancer LoadBalancersDeleteOperation deleteOperation = await NetworkManagementClient.LoadBalancers.StartDeleteAsync(resourceGroupName, lbName); await WaitForCompletionAsync(deleteOperation); // Verify Delete AsyncPageable <LoadBalancer> listLoadBalancerAP = NetworkManagementClient.LoadBalancers.ListAsync(resourceGroupName); List <LoadBalancer> listLoadBalancer = await listLoadBalancerAP.ToEnumerableAsync(); Assert.IsEmpty(listLoadBalancer); // Delete all NetworkInterfaces await NetworkManagementClient.NetworkInterfaces.StartDeleteAsync(resourceGroupName, nic1name); await NetworkManagementClient.NetworkInterfaces.StartDeleteAsync(resourceGroupName, nic2name); await NetworkManagementClient.NetworkInterfaces.StartDeleteAsync(resourceGroupName, nic3name); // Delete all PublicIPAddresses await NetworkManagementClient.PublicIPAddresses.StartDeleteAsync(resourceGroupName, lbPublicIpName); }
/// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <LoadBalancer> > BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("loadBalancerName", loadBalancerName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <LoadBalancer>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <LoadBalancer>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task <AzureOperationResponse <LoadBalancer> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse <LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false)); }
public static AvailabilityGroupListener CreateAGListener(SqlVirtualMachineTestContext context, string agListenerName, string groupName) { MockClient client = context.client; string domainName = Constants.domainName; string adminLogin = Constants.adminLogin; string adminPassword = Constants.adminPassword; // Create domain NetworkSecurityGroup nsg = CreateNsg(context); VirtualNetwork vnet = CreateVirtualNetwork(context, networkSecurityGroup: nsg); NetworkInterface nic = CreateNetworkInterface(context, virtualNetwork: vnet, networkSecurityGroup: nsg); VirtualMachine vm = CreateVM(context, nic: nic); VirtualMachineExtension domain = CreateDomain(context, vm, domainName, adminLogin, adminPassword); Assert.NotNull(domain); // Update DNS Subnet subnet = vnet.Subnets[0]; UpdateVnetDNS(context, vnet, nsg, nic, subnet); // Create SqlVirtualMachineGroup StorageAccount storageAccount = CreateStorageAccount(context); StorageAccountListKeysResult storageAccountKeys = client.storageClient.StorageAccounts.ListKeys(context.resourceGroup.Name, storageAccount.Name); IEnumerator <StorageAccountKey> iter = storageAccountKeys.Keys.GetEnumerator(); iter.MoveNext(); string key = iter.Current.Value; WsfcDomainProfile profile = new WsfcDomainProfile() { ClusterBootstrapAccount = getUsername(adminLogin, domainName), ClusterOperatorAccount = getUsername(adminLogin, domainName), SqlServiceAccount = getUsername(Constants.sqlService, domainName), StorageAccountUrl = "https://" + storageAccount.Name + ".blob.core.windows.net/", StorageAccountPrimaryKey = key, DomainFqdn = domainName + ".com", OuPath = "" }; SqlVirtualMachineGroup group = CreateSqlVirtualMachineGroup(context, storageAccount, groupName: groupName, profile: profile); // Create availability set AvailabilitySet availabilitySet = client.computeClient.AvailabilitySets.CreateOrUpdate(context.resourceGroup.Name, context.generateResourceName(), new AvailabilitySet() { Location = context.location, PlatformFaultDomainCount = 3, PlatformUpdateDomainCount = 2, Sku = new Microsoft.Azure.Management.Compute.Models.Sku { Name = "Aligned" } }); // Create two sql virtual machines NetworkInterface nic1 = CreateNetworkInterface(context, virtualNetwork: vnet); NetworkInterface nic2 = CreateNetworkInterface(context, virtualNetwork: vnet); VirtualMachine vm1 = CreateVM(context, nic: nic1, availabilitySet: availabilitySet); VirtualMachine vm2 = CreateVM(context, nic: nic2, availabilitySet: availabilitySet); SqlVirtualMachineModel sqlVM1 = prepareMachine(context, group, vm1, domainName, adminLogin, adminPassword); SqlVirtualMachineModel sqlVM2 = prepareMachine(context, group, vm2, domainName, adminLogin, adminPassword); // Create load balancer LoadBalancer loadBalancer = client.networkClient.LoadBalancers.CreateOrUpdate(context.resourceGroup.Name, context.generateResourceName(), new LoadBalancer() { Location = context.location, Sku = new LoadBalancerSku("Basic"), FrontendIPConfigurations = new List <FrontendIPConfiguration> (new FrontendIPConfiguration[] { new FrontendIPConfiguration() { Name = "LoadBalancerFrontEnd", PrivateIPAllocationMethod = "Dynamic", Subnet = subnet } }) }); // Run deployment to create an availability group with the two machines created string AgName = "AvGroup"; VirtualMachineExtension availabilityGroup = context.client.computeClient.VirtualMachineExtensions.CreateOrUpdate(context.resourceGroup.Name, vm1.Name, "agCreation", new VirtualMachineExtension(context.location, name: AgName) { VirtualMachineExtensionType = "CustomScriptExtension", Publisher = "Microsoft.Compute", TypeHandlerVersion = "1.9", AutoUpgradeMinorVersion = true, Settings = new CustomScriptExtensionSettings { FileUris = new List <string>(new string[] { "https://agtemplatestorage.blob.core.windows.net/templates/Deploy.ps1", "https://agtemplatestorage.blob.core.windows.net/templates/sqlvm6.sql", "https://agtemplatestorage.blob.core.windows.net/templates/sqlvm7.sql", "https://agtemplatestorage.blob.core.windows.net/templates/sqlvm8.sql", "https://agtemplatestorage.blob.core.windows.net/test/sqlvm9.sql", "https://agtemplatestorage.blob.core.windows.net/templates/sqlvm10.sql" }), CommandToExecute = "powershell -ExecutionPolicy Unrestricted -File Deploy.ps1 " + AgName + " " + vm1.Name + " " + vm2.Name + " " + Constants.sqlLogin + " " + adminPassword + " " + domainName + "\\" + Constants.sqlService, ContentVersion = "1.0.0.0" } }); // Create availability group listener return(context.getSqlClient().AvailabilityGroupListeners.CreateOrUpdate(context.resourceGroup.Name, group.Name, agListenerName, new AvailabilityGroupListener() { LoadBalancerConfigurations = new List <LoadBalancerConfiguration>(new LoadBalancerConfiguration[] { new LoadBalancerConfiguration() { PrivateIpAddress = new PrivateIPAddress(ipAddress: "10.0.0.11", subnetResourceId: subnet.Id), ProbePort = 59999, LoadBalancerResourceId = loadBalancer.Id, SqlVirtualMachineInstances = new List <string>() { sqlVM1.Id, sqlVM2.Id } } }), AvailabilityGroupName = AgName, Port = 1433 })); }
public Push(Ctx parent, int threadId, int socketId) : base(parent, threadId, socketId) { m_options.SocketType = ZmqSocketType.Push; m_loadBalancer = new LoadBalancer(); }
public virtual LoadBalancersCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (loadBalancerName == null) { throw new ArgumentNullException(nameof(loadBalancerName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("LoadBalancersOperations.StartCreateOrUpdate"); scope.Start(); try { var originalResponse = RestClient.CreateOrUpdate(resourceGroupName, loadBalancerName, parameters, cancellationToken); return(new LoadBalancersCreateOrUpdateOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateRequest(resourceGroupName, loadBalancerName, parameters).Request, originalResponse)); } catch (Exception e) { scope.Failed(e); throw; } }
public GameApplication(string applicationId, string version, LoadBalancer <GameServerContext> loadBalancer) : this(new PoolFiber(), new PoolFiber(), applicationId, version, loadBalancer) { }
public async Task FarmGroupAddCompletesSuccessfully(TransportType transportType) { // https://github.com/SignalR/SignalR/issues/3337 // Each node shares the same bus but are independent servers const int nodeCount = 2; var counters = new Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); // Ensure /send and /connect requests get handled by different servers Func<string, int> scheduler = url => url.Contains("/send") ? 0 : 1; using (EnableDisposableTracing()) using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) using (var loadBalancer = new LoadBalancer(nodeCount, scheduler)) { loadBalancer.Configure(app => { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(IMessageBus), () => bus); app.MapSignalR(new HubConfiguration { Resolver = resolver }); }); using (var connection = new HubConnection("http://goo/")) { var proxy = connection.CreateHubProxy("FarmGroupHub"); const string group = "group"; const string message = "message"; var mre = new AsyncManualResetEvent(); proxy.On<string>("message", m => { if (m == message) { mre.Set(); } }); Client.Transports.IClientTransport transport; switch (transportType) { case TransportType.LongPolling: transport = new Client.Transports.LongPollingTransport(loadBalancer); break; case TransportType.ServerSentEvents: transport = new Client.Transports.ServerSentEventsTransport(loadBalancer); break; default: throw new ArgumentException("transportType"); } await connection.Start(transport); await proxy.Invoke("JoinGroup", group); await proxy.Invoke("SendToGroup", group, message); Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(5))); } } }
public async Task <bool> TrySendItem(object item) { return(await LoadBalancer.SendItemAsync(item)); }
public void LoadSpread() { const int Count = 100000; var loadLevelWeights = new int[] { 50, // FeedbackLevel.Lowest 30, // FeedbackLevel.Low 15, // FeedbackLevel.Normal 5, // FeedbackLevel.High 0 // FeedbackLevel.Highest }; this.balancer = new LoadBalancer<Server>(loadLevelWeights, 42); for (int i = 0; i < this.servers.Count; i++) { bool result = this.balancer.TryAddServer(this.servers[i], FeedbackLevel.Lowest); Assert.IsTrue(result); } // 5 servers with a load level of lowest // every server should get about 20 percent of the assigments this.AssignServerLoop(Count); for (int i = 0; i < this.servers.Count; i++) { this.CheckServer(this.servers[i], Count, 20, 5); } this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.High); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 50, 5); this.CheckServer(this.servers[1], Count, 30, 5); this.CheckServer(this.servers[2], Count, 15, 5); this.CheckServer(this.servers[3], Count, 5, 5); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Low); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 36, 5); this.CheckServer(this.servers[1], Count, 21, 5); this.CheckServer(this.servers[2], Count, 21, 5); this.CheckServer(this.servers[3], Count, 11, 5); this.CheckServer(this.servers[4], Count, 11, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Normal); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 33, 5); this.CheckServer(this.servers[1], Count, 17, 5); this.CheckServer(this.servers[2], Count, 17, 5); this.CheckServer(this.servers[3], Count, 17, 5); this.CheckServer(this.servers[4], Count, 17, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Highest); this.UpdateServer(this.servers[2], FeedbackLevel.Highest); this.UpdateServer(this.servers[3], FeedbackLevel.Highest); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 100, 0); this.CheckServer(this.servers[1], Count, 0, 0); this.CheckServer(this.servers[2], Count, 0, 0); this.CheckServer(this.servers[3], Count, 0, 0); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Highest); Server server; Assert.IsFalse(this.balancer.TryGetServer(out server)); }
private static void UseScaleout(int nodes, out MemoryHost[] hosts, out IHttpClient client) { hosts = new MemoryHost[nodes]; var eventBus = new EventBus(); for (var i = 0; i < nodes; ++i) { var host = new MemoryHost(); host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; var bus = new DelayedMessageBus(host.InstanceName, eventBus, config.Resolver, TimeSpan.Zero); config.Resolver.Register(typeof(IMessageBus), () => bus); app.MapHubs(config); }); hosts[i] = host; } client = new LoadBalancer(hosts); }
public AppLobby(LoadBalancer<IncomingGameServerPeer> loadBalancer) : this(loadBalancer, 0, TimeSpan.FromSeconds(5)) { }
public async Task FarmGroupAddCompletesSuccessfully(TransportType transportType) { // https://github.com/SignalR/SignalR/issues/3337 // Each node shares the same bus but are independent servers const int nodeCount = 2; var counters = new Infrastructure.PerformanceCounterManager(); var configurationManager = new DefaultConfigurationManager(); // Ensure /send and /connect requests get handled by different servers Func <string, int> scheduler = url => url.Contains("/send") ? 0 : 1; using (EnableDisposableTracing()) using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000)) using (var loadBalancer = new LoadBalancer(nodeCount, scheduler)) { loadBalancer.Configure(app => { var resolver = new DefaultDependencyResolver(); resolver.Register(typeof(IMessageBus), () => bus); app.MapSignalR(new HubConfiguration { Resolver = resolver }); }); using (var connection = new HubConnection("http://goo/")) { var proxy = connection.CreateHubProxy("FarmGroupHub"); const string group = "group"; const string message = "message"; var mre = new AsyncManualResetEvent(); proxy.On <string>("message", m => { if (m == message) { mre.Set(); } }); Client.Transports.IClientTransport transport; switch (transportType) { case TransportType.LongPolling: transport = new Client.Transports.LongPollingTransport(loadBalancer); break; case TransportType.ServerSentEvents: transport = new Client.Transports.ServerSentEventsTransport(loadBalancer); break; default: throw new ArgumentException("transportType"); } await connection.Start(transport); await proxy.Invoke("JoinGroup", group); await proxy.Invoke("SendToGroup", group, message); Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(5))); } } }
public void Fail_Login_Through_LoadBalancer() { Assert.AreEqual("false", LoadBalancer.Login("notUsername")); }
/// <summary> /// The Put LoadBalancer operation creates/updates a LoadBalancer /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.ILoadBalancerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// Required. The name of the loadBalancer. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/delete LoadBalancer /// operation /// </param> /// <returns> /// Response of a PUT Load Balancer operation /// </returns> public static LoadBalancerPutResponse BeginCreateOrUpdating(this ILoadBalancerOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters) { return(Task.Factory.StartNew((object s) => { return ((ILoadBalancerOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, loadBalancerName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
public void Pass_Login_Through_LoadBalancer() { Assert.AreEqual("true", LoadBalancer.Login("test0")); }
/// <summary> /// The Put LoadBalancer operation creates/updates a LoadBalancer /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.ILoadBalancerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// Required. The name of the loadBalancer. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/delete LoadBalancer /// operation /// </param> /// <returns> /// Response of a PUT Load Balancer operation /// </returns> public static Task <LoadBalancerPutResponse> BeginCreateOrUpdatingAsync(this ILoadBalancerOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters) { return(operations.BeginCreateOrUpdatingAsync(resourceGroupName, loadBalancerName, parameters, CancellationToken.None)); }
public static void Scaleout(int nodes, int clients) { var hosts = new MemoryHost[nodes]; var random = new Random(); var eventBus = new EventBus(); for (var i = 0; i < nodes; ++i) { var host = new MemoryHost(); host.Configure(app => { var config = new HubConfiguration() { Resolver = new DefaultDependencyResolver() }; var delay = i % 2 == 0 ? TimeSpan.Zero : TimeSpan.FromSeconds(1); var bus = new DelayedMessageBus(host.InstanceName, eventBus, config.Resolver, delay); config.Resolver.Register(typeof(IMessageBus), () => bus); app.MapHubs(config); }); hosts[i] = host; } var client = new LoadBalancer(hosts); var wh = new ManualResetEventSlim(); for (int i = 0; i < clients; i++) { Task.Run(() => RunLoop(client, wh)); } wh.Wait(); }
public void ExpandResourceTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/loadBalancers"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = location }); // Create lbPublicIP string lbPublicIpName = TestUtilities.GenerateName(); string lbDomaingNameLabel = TestUtilities.GenerateName(); var lbPublicIp = TestHelper.CreateDefaultPublicIpAddress( lbPublicIpName, resourceGroupName, lbDomaingNameLabel, location, networkManagementClient); // Create Vnet string vnetName = TestUtilities.GenerateName(); string subnetName = TestUtilities.GenerateName(); var vnet = TestHelper.CreateVirtualNetwork(vnetName, subnetName, resourceGroupName, location, networkManagementClient); // Create Nics string nic1name = TestUtilities.GenerateName(); string nic2name = TestUtilities.GenerateName(); string nic3name = TestUtilities.GenerateName(); var nic1 = TestHelper.CreateNetworkInterface( nic1name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", networkManagementClient); var nic2 = TestHelper.CreateNetworkInterface( nic2name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", networkManagementClient); var nic3 = TestHelper.CreateNetworkInterface( nic3name, resourceGroupName, null, vnet.Subnets[0].Id, location, "ipconfig", networkManagementClient); // Create the LoadBalancer var lbName = TestUtilities.GenerateName(); var frontendIpConfigName = TestUtilities.GenerateName(); var backEndAddressPoolName = TestUtilities.GenerateName(); var loadBalancingRuleName = TestUtilities.GenerateName(); var probeName = TestUtilities.GenerateName(); var inboundNatRule1Name = TestUtilities.GenerateName(); var inboundNatRule2Name = TestUtilities.GenerateName(); // Populate the loadBalancerCreateOrUpdateParameter var loadBalancer = new LoadBalancer() { Location = location, FrontendIPConfigurations = new List <FrontendIPConfiguration>() { new FrontendIPConfiguration() { Name = frontendIpConfigName, PublicIPAddress = new PublicIPAddress() { Id = lbPublicIp.Id } } }, BackendAddressPools = new List <BackendAddressPool>() { new BackendAddressPool() { Name = backEndAddressPoolName, } }, LoadBalancingRules = new List <LoadBalancingRule>() { new LoadBalancingRule() { Name = loadBalancingRuleName, FrontendIPConfiguration = new Microsoft.Azure.Management.Network.Models.SubResource() { Id = TestHelper.GetChildLbResourceId(networkManagementClient.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 80, BackendPort = 80, EnableFloatingIP = false, IdleTimeoutInMinutes = 15, BackendAddressPool = new Microsoft.Azure.Management.Network.Models.SubResource() { Id = TestHelper.GetChildLbResourceId(networkManagementClient.SubscriptionId, resourceGroupName, lbName, "backendAddressPools", backEndAddressPoolName) }, Probe = new Microsoft.Azure.Management.Network.Models.SubResource() { Id = TestHelper.GetChildLbResourceId(networkManagementClient.SubscriptionId, resourceGroupName, lbName, "probes", probeName) } } }, Probes = new List <Probe>() { new Probe() { Name = probeName, Protocol = ProbeProtocol.Http, Port = 80, RequestPath = "healthcheck.aspx", IntervalInSeconds = 10, NumberOfProbes = 2 } }, InboundNatRules = new List <InboundNatRule>() { new InboundNatRule() { Name = inboundNatRule1Name, FrontendIPConfiguration = new Microsoft.Azure.Management.Network.Models.SubResource() { Id = TestHelper.GetChildLbResourceId(networkManagementClient.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3389, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false }, new InboundNatRule() { Name = inboundNatRule2Name, FrontendIPConfiguration = new Microsoft.Azure.Management.Network.Models.SubResource() { Id = TestHelper.GetChildLbResourceId(networkManagementClient.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3390, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false, } } }; // Create the loadBalancer var putLoadBalancer = networkManagementClient.LoadBalancers.CreateOrUpdate(resourceGroupName, lbName, loadBalancer); var getLoadBalancer = networkManagementClient.LoadBalancers.Get(resourceGroupName, lbName); // Associate the nic with LB nic1.IpConfigurations.First().LoadBalancerBackendAddressPools = new List <BackendAddressPool> { getLoadBalancer.BackendAddressPools.First() }; nic1.IpConfigurations.First().LoadBalancerInboundNatRules = new List <InboundNatRule> { getLoadBalancer.InboundNatRules.First() }; nic2.IpConfigurations.First().LoadBalancerBackendAddressPools = new List <BackendAddressPool> { getLoadBalancer.BackendAddressPools.First() }; nic3.IpConfigurations.First().LoadBalancerInboundNatRules = new List <InboundNatRule> { getLoadBalancer.InboundNatRules[1] }; // Put Nics networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nic1name, nic1); networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nic2name, nic2); networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nic3name, nic3); // Get Nics nic1 = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, nic1name); nic2 = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, nic2name); nic3 = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, nic3name); // Get lb with expanded nics from nat rules getLoadBalancer = networkManagementClient.LoadBalancers.Get(resourceGroupName, lbName, "InboundNatRules/backendIPConfiguration"); foreach (var natRule in getLoadBalancer.InboundNatRules) { Assert.NotNull(natRule.BackendIPConfiguration); Assert.NotNull(natRule.BackendIPConfiguration.Id); Assert.NotNull(natRule.BackendIPConfiguration.Name); Assert.NotNull(natRule.BackendIPConfiguration.Etag); Assert.Equal(natRule.Id, natRule.BackendIPConfiguration.LoadBalancerInboundNatRules[0].Id); } // Get lb with expanded nics from pools getLoadBalancer = networkManagementClient.LoadBalancers.Get(resourceGroupName, lbName, "BackendAddressPools/backendIPConfigurations"); foreach (var pool in getLoadBalancer.BackendAddressPools) { foreach (var ipconfig in getLoadBalancer.BackendAddressPools.First().BackendIPConfigurations) { Assert.NotNull(ipconfig.Id); Assert.NotNull(ipconfig.Name); Assert.NotNull(ipconfig.Etag); Assert.Equal(pool.Id, ipconfig.LoadBalancerBackendAddressPools[0].Id); } } // Get lb with expanded publicip getLoadBalancer = networkManagementClient.LoadBalancers.Get(resourceGroupName, lbName, "FrontendIPConfigurations/PublicIPAddress"); foreach (var ipconfig in getLoadBalancer.FrontendIPConfigurations) { Assert.NotNull(ipconfig.PublicIPAddress); Assert.NotNull(ipconfig.PublicIPAddress.Id); Assert.NotNull(ipconfig.PublicIPAddress.Name); Assert.NotNull(ipconfig.PublicIPAddress.Etag); Assert.Equal(ipconfig.Id, ipconfig.PublicIPAddress.IpConfiguration.Id); } // Get NIC with expanded subnet nic1 = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, nic1name, "IPConfigurations/Subnet"); foreach (var ipconfig in nic1.IpConfigurations) { Assert.NotNull(ipconfig.Subnet); Assert.NotNull(ipconfig.Subnet.Id); Assert.NotNull(ipconfig.Subnet.Name); Assert.NotNull(ipconfig.Subnet.Etag); Assert.NotEmpty(ipconfig.Subnet.IpConfigurations); } // Get subnet with expanded ipconfigurations var subnet = networkManagementClient.Subnets.Get( resourceGroupName, vnetName, subnetName, "IPConfigurations"); foreach (var ipconfig in subnet.IpConfigurations) { Assert.NotNull(ipconfig.Name); Assert.NotNull(ipconfig.Id); Assert.NotNull(ipconfig.Etag); Assert.NotNull(ipconfig.PrivateIPAddress); } // Get publicIPAddress with expanded ipconfigurations var publicip = networkManagementClient.PublicIPAddresses.Get( resourceGroupName, lbPublicIpName, "IPConfiguration"); Assert.NotNull(publicip.IpConfiguration); Assert.NotNull(publicip.IpConfiguration.Id); Assert.NotNull(publicip.IpConfiguration.Name); Assert.NotNull(publicip.IpConfiguration.Etag); // Delete LoadBalancer networkManagementClient.LoadBalancers.Delete(resourceGroupName, lbName); // Verify Delete var listLoadBalancer = networkManagementClient.LoadBalancers.List(resourceGroupName); Assert.Empty(listLoadBalancer); // Delete all NetworkInterfaces networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nic1name); networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nic2name); networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nic3name); // Delete all PublicIPAddresses networkManagementClient.PublicIPAddresses.Delete(resourceGroupName, lbPublicIpName); } }
public async Task<Uri> GetDeviceResourceUri(LoadBalancer loadBalancer, CancellationToken cancellationToken) { UriTemplate template = new UriTemplate("loadbalancers/{loadBalancerId}"); Uri baseAddress = await GetBaseUriAsync(cancellationToken); return template.BindByName(baseAddress, new Dictionary<string, string> { { "loadBalancerId", loadBalancer.Id.Value } }); }
public void Properties() { // FeedbackLevel.Lowest value = 0, weight = 40 // FeedbackLevel.Low value = 1, weight = 30 // FeedbackLevel.Normal value = 2, weight = 20 // FeedbackLevel.High value = 3, weight = 10 // FeedbackLevel.Highest value = 4, weight = 0 this.balancer = new LoadBalancer<Server>(); this.CheckLoadBalancerProperties(0, 0, 0); this.TryAddServer(this.servers[0], FeedbackLevel.Lowest); this.CheckLoadBalancerProperties(0, 40, 0); this.TryAddServer(this.servers[1], FeedbackLevel.Lowest); this.CheckLoadBalancerProperties(0, 80, 0); this.TryUpdateServer(this.servers[0], FeedbackLevel.Normal); this.CheckLoadBalancerProperties(2, 60, 25); this.TryUpdateServer(this.servers[1], FeedbackLevel.Normal); this.CheckLoadBalancerProperties(4, 40, 50); this.TryUpdateServer(this.servers[0], FeedbackLevel.Highest); this.CheckLoadBalancerProperties(6, 20, 75); this.TryUpdateServer(this.servers[1], FeedbackLevel.Highest); this.CheckLoadBalancerProperties(8, 0, 100); this.TryRemoveServer(this.servers[1]); this.CheckLoadBalancerProperties(4, 0, 100); this.TryRemoveServer(this.servers[0]); this.CheckLoadBalancerProperties(0, 0, 0); }
private void BuildFoodLoadBalancer() { var frontEndConfig = new LoadBalancerFrontendIpConfigurationArgs { Name = "frontendconfig", SubnetId = _Subnets["Food"].Id, PrivateIpAddressAllocation = "Dynamic", PrivateIpAddressVersion = "IPv4" }; var lb = new LoadBalancer("foodLb", new LoadBalancerArgs { ResourceGroupName = _ResourceGroup.Name, Location = _ResourceGroup.Location, Name = "foodLb", Sku = "Basic", // Standard FrontendIpConfigurations = frontEndConfig }); var healthProbe1 = new FrontdoorBackendPoolHealthProbeArgs { Name = "Probe1", Enabled = true, IntervalInSeconds = 5, Protocol = "TCP" }; var backendpool = new BackendAddressPool("Pool1", new BackendAddressPoolArgs { Name = "Pool1", ResourceGroupName = _ResourceGroup.Name, LoadbalancerId = lb.Id }); new NetworkInterfaceBackendAddressPoolAssociation("association1", new NetworkInterfaceBackendAddressPoolAssociationArgs { BackendAddressPoolId = backendpool.Id, NetworkInterfaceId = _foodVmNics[0].Id, IpConfigurationName = "Ipconfig1" }); new NetworkInterfaceBackendAddressPoolAssociation("association2", new NetworkInterfaceBackendAddressPoolAssociationArgs { BackendAddressPoolId = backendpool.Id, NetworkInterfaceId = _foodVmNics[1].Id, IpConfigurationName = "Ipconfig1" }); var lbRule = new Rule("rule1", new RuleArgs { Name = "rule1", ResourceGroupName = _ResourceGroup.Name, LoadbalancerId = lb.Id, Protocol = "TCP", FrontendPort = 80, BackendPort = 80, FrontendIpConfigurationName = frontEndConfig.Name, ProbeId = healthProbe1.Id, BackendAddressPoolId = backendpool.Id }); }
public AppLobby(LoadBalancer <IncomingGameServerPeer> loadBalancer, IGameList gameList) : this(loadBalancer, gameList, 0, TimeSpan.FromSeconds(15)) { }
public void overloaded_emails_should_throw_exception() { var agent1 = new Agent("A1"); var agent2 = new Agent("A2"); var agents = new ConcurrentQueue<Agent>(new[] { agent1, agent2 }); var loadBalancer = new LoadBalancer(); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); loadBalancer.AssignInteraction(new EmailInteraction("*****@*****.**"), agents); }
public override void Init() { m_loadBalancer = new LoadBalancer <ISmtpMessage>(this.Receivers); }
private VirtualMachineScaleSetNetworkProfile CreateNetworkResource(VirtualMachineScaleSetNetworkConfiguration existingNetworkConfig) { var subsetName = string.Format("Subnet-{0}", this.NodeType); var ipConfiguration = existingNetworkConfig.IpConfigurations.FirstOrDefault(); if (ipConfiguration == null) { throw new PSInvalidOperationException(ServiceFabricProperties.Resources.InvalidVmssConfiguration); } var subNetId = ipConfiguration.Subnet.Id; const string virtualNetworks = "Microsoft.Network/virtualNetworks/"; var virtualNetwork = string.Empty; int index = -1; if ((index = subNetId.IndexOf(virtualNetworks, StringComparison.OrdinalIgnoreCase)) != -1) { var end = subNetId.IndexOf("/", index + virtualNetworks.Length); virtualNetwork = subNetId.Substring(index + virtualNetworks.Length, end - index - virtualNetworks.Length); } if (string.IsNullOrEmpty(virtualNetwork)) { throw new InvalidOperationException(); } var network = NetworkManagementClient.VirtualNetworks.Get(this.ResourceGroupName, virtualNetwork); var start = 1; Subnet subnet = null; var retry = 5; while (retry-- >= 0) { try { subnet = NetworkManagementClient.Subnets.CreateOrUpdate( this.ResourceGroupName, virtualNetwork, string.Format("{0}-{1}", subsetName, start), new Subnet() { AddressPrefix = string.Format("10.0.{0}.0/24", start++) }); network.Subnets.Add(subnet); network = NetworkManagementClient.VirtualNetworks.CreateOrUpdate( this.ResourceGroupName, virtualNetwork, network); this.addressPrefix = subnet.AddressPrefix; break; } catch (Rest.Azure.CloudException ex) { if (ex.Body.Code == "NetcfgInvalidSubnet" || ex.Body.Code == "InUseSubnetCannotBeUpdated") { network.Subnets.Remove(subnet); continue; } if (ex.Body.Code == "InvalidRequestFormat") { if (ex.Body.Details != null) { var details = ex.Body.Details.Where(d => d.Code == "DuplicateResourceName"); if (details.Any()) { network.Subnets.Remove(subnet); continue; } } } throw; } } var publicAddressName = string.Format("LBIP-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index); var dnsLable = string.Format("{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index); var lbName = string.Format("LB-{0}-{1}{2}", this.Name.ToLower(), this.NodeType.ToLower(), index); var publicIp = NetworkManagementClient.PublicIPAddresses.CreateOrUpdate( this.ResourceGroupName, publicAddressName, new PublicIPAddress() { PublicIPAllocationMethod = "Dynamic", Location = GetLocation(), DnsSettings = new PublicIPAddressDnsSettings(dnsLable) }); var backendAdressPollName = "LoadBalancerBEAddressPool"; var frontendIpConfigurationName = "LoadBalancerIPConfig"; var probeName = "FabricGatewayProbe"; var probeHTTPName = "FabricHttpGatewayProbe"; var inboundNatPoolsName = "LoadBalancerBEAddressNatPool"; var newLoadBalancerId = string.Format( LoadBalancerIdFormat, this.NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName); var newLoadBalancer = new LoadBalancer(newLoadBalancerId, lbName) { Location = GetLocation(), FrontendIPConfigurations = new List <FrontendIPConfiguration>() { new FrontendIPConfiguration() { Name = frontendIpConfigurationName, PublicIPAddress = new PublicIPAddress() { Id = publicIp.Id } } }, BackendAddressPools = new List <BackendAddressPool>() { new BackendAddressPool() { Name = backendAdressPollName } }, LoadBalancingRules = new List <LoadBalancingRule>() { new LoadBalancingRule() { Name = "LBRule", BackendAddressPool = new Management.Network.Models.SubResource() { Id = string.Format( BackendAddressIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, backendAdressPollName) }, BackendPort = Constants.DefaultTcpPort, EnableFloatingIP = false, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIDFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPort = Constants.DefaultTcpPort, IdleTimeoutInMinutes = 5, Protocol = "tcp", Probe = new Management.Network.Models.SubResource() { Id = string.Format( ProbeIDFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, probeName) } }, new LoadBalancingRule() { Name = "LBHttpRule", BackendAddressPool = new Management.Network.Models.SubResource() { Id = string.Format( BackendAddressIdFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, backendAdressPollName) }, BackendPort = Constants.DefaultHttpPort, EnableFloatingIP = false, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIDFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPort = Constants.DefaultHttpPort, IdleTimeoutInMinutes = 5, Protocol = "tcp", Probe = new Management.Network.Models.SubResource() { Id = string.Format( ProbeIDFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, probeHTTPName) } } }, Probes = new List <Probe>() { new Probe() { Name = probeName, IntervalInSeconds = 5, NumberOfProbes = 2, Port = Constants.DefaultTcpPort }, new Probe() { Name = probeHTTPName, IntervalInSeconds = 5, NumberOfProbes = 2, Port = Constants.DefaultHttpPort }, }, InboundNatPools = new List <InboundNatPool>() { new InboundNatPool() { Name = inboundNatPoolsName, BackendPort = Constants.DefaultBackendPort, FrontendIPConfiguration = new Management.Network.Models.SubResource() { Id = string.Format( FrontendIDFormat, NetworkManagementClient.SubscriptionId, this.ResourceGroupName, lbName, frontendIpConfigurationName) }, FrontendPortRangeStart = Constants.DefaultFrontendPortRangeStart, FrontendPortRangeEnd = Constants.DefaultFrontendPortRangeEnd, Protocol = "tcp" } } }; NetworkManagementClient.LoadBalancers.BeginCreateOrUpdate( this.ResourceGroupName, lbName, newLoadBalancer); newLoadBalancer = NetworkManagementClient.LoadBalancers.Get(this.ResourceGroupName, lbName); return(new VirtualMachineScaleSetNetworkProfile() { NetworkInterfaceConfigurations = new List <VirtualMachineScaleSetNetworkConfiguration>() { new VirtualMachineScaleSetNetworkConfiguration() { IpConfigurations = new List <VirtualMachineScaleSetIPConfiguration>() { new VirtualMachineScaleSetIPConfiguration() { Name = string.Format("Nic-{0}", start), LoadBalancerBackendAddressPools = newLoadBalancer.BackendAddressPools.Select( b => new Management.Compute.Models.SubResource() { Id = b.Id } ).ToList(), LoadBalancerInboundNatPools = newLoadBalancer.InboundNatPools.Select( p => new Management.Compute.Models.SubResource() { Id = p.Id } ).ToList(), Subnet = new ApiEntityReference() { Id = subnet.Id } } }, Name = string.Format("NIC-{0}-{1}", this.NodeType, start), Primary = true } } }); }
/// <summary> /// A dummy routine in order to test cell dynamic load balancing /// (**not** a good balancing, but triggers redistribution). /// </summary> protected override int[] ComputeNewCellDistribution(int TimeStepNo, double physTime) { if (!DynamicBalance || MPISize <= 1) { return(null); } //if(MPIRank == 0) // Debugger.Launch(); int J = this.GridData.iLogicalCells.NoOfLocalUpdatedCells; int[] NewPart; int[] PerformanceClasses = new int[J]; var CC = this.LsTrk.Regions.GetCutCellMask(); foreach (int j in CC.ItemEnum) { PerformanceClasses[j] = 1; } int NoCutCells = CC.NoOfItemsLocally.MPISum(); Console.WriteLine("Number of cut cells: " + NoCutCells); if (balancer == null) { balancer = new LoadBalancer( new List <Func <IApplication, int, ICellCostEstimator> >() { cellCostEstimatorFactory } ); } NewPart = balancer.GetNewPartitioning( this, 2, PerformanceClasses, TimeStepNo, GridPartType.none, "", imbalanceThreshold: 0.0, Period: 3, redistributeAtStartup: false, TimestepNoRestart: null); /* * * if (MPISize == 4 && TimeStepNo > 5) { * NewPart = new int[J]; * * double speed = this.GridData.Cells.h_maxGlobal / 0.3; * for (int j = 0; j < J; j++) { * double[] X = this.GridData.Cells.CellCenter.GetRow(j); * double x = X[0]; * double y = X[1]; * * int px = x < Math.Min(physTime * speed, 2) ? 0 : 1; * int py = y < 0 ? 0 : 1; * * NewPart[j] = px * 2 + py; * } * * //return Part; * } else if (MPISize == 2) { * NewPart = new int[J]; * * double speed = this.GridData.Cells.h_maxGlobal / 0.3; * * for (int j = 0; j < J; j++) { * double[] X = this.GridData.Cells.CellCenter.GetRow(j); * double x = X[0]; * double y = X[1]; * * int px = x < Math.Min(physTime * speed, 2) ? 0 : 1; * int py = y < 0 ? 0 : 1; * * NewPart[j] = px; * } * * //return null; * //return Part; * } else if (MPISize == 1) { * * return null; * } else { * return null; * } * * //*/ if (NewPart != null) { int myRank = this.MPIRank; foreach (int tr in NewPart) { if (tr != myRank) { m_NoOfReparts++; } } } return(NewPart); }
public Func <RegionalContext, IRegionalEndpoint> BuildVMScaleSetApp(GlobalContext context) { var options = CustomResourceOptions.Merge(context.Options, new CustomResourceOptions { DeleteBeforeReplace = true }); var file = File.ReadAllText("./vm/vmCustomData.yaml"); return((RegionalContext region) => { var location = region.Location; var domainName = $"rnddnplm{location}"; //TODO: random var publicIp = new PublicIp($"pip-{location}", new PublicIpArgs { ResourceGroupName = resourceGroup.Name, Location = location, AllocationMethod = "Static", DomainNameLabel = domainName, }, options); var loadBalancer = new LoadBalancer($"lb-{location}", new LoadBalancerArgs { ResourceGroupName = resourceGroup.Name, Location = location, FrontendIpConfigurations = { new LoadBalancerFrontendIpConfigurationsArgs { Name = "PublicIPAddress", PublicIpAddressId = publicIp.Id, } } }, options); var bpepool = new BackendAddressPool($"bap-{location}", new BackendAddressPoolArgs { ResourceGroupName = resourceGroup.Name, LoadbalancerId = loadBalancer.Id, }, options); var probe = new Probe($"ssh-probe-{location}".Truncate(16), new ProbeArgs { ResourceGroupName = resourceGroup.Name, LoadbalancerId = loadBalancer.Id, Port = 80, }, options); var rule = new Rule($"rule-{location}", new RuleArgs { ResourceGroupName = resourceGroup.Name, BackendAddressPoolId = bpepool.Id, BackendPort = 80, FrontendIpConfigurationName = "PublicIPAddress", FrontendPort = 80, LoadbalancerId = loadBalancer.Id, ProbeId = probe.Id, Protocol = "Tcp", }, options); var vnet = new VirtualNetwork($"vnet-{location}", new VirtualNetworkArgs { ResourceGroupName = resourceGroup.Name, Location = location, AddressSpaces = { "10.0.0.0/16" }, }, options); var subnet = new Subnet($"subnet-{location}", new SubnetArgs { ResourceGroupName = resourceGroup.Name, AddressPrefix = "10.0.2.0/24", VirtualNetworkName = vnet.Name, }, options); var customData = Output.All <string>(context.CosmosAccount.Endpoint, context.CosmosAccount.PrimaryMasterKey, context.Database.Name, context.Container.Name) .Apply(values => { return file.Replace("${ENDPOINT}", values[0]) .Replace("${MASTER_KEY}", values[1]) .Replace("${DATABASE}", values[2]) .Replace("${COLLECTION}", values[3]) .Replace("${LOCATION}", location); }); var scaleSet = new ScaleSet($"vmss-{location}", new ScaleSetArgs { ResourceGroupName = resourceGroup.Name, Location = location, NetworkProfiles = { new ScaleSetNetworkProfilesArgs { IpConfigurations = { new ScaleSetNetworkProfilesIpConfigurationsArgs { LoadBalancerBackendAddressPoolIds ={ bpepool.Id }, Name = "IPConfiguration", Primary = true, SubnetId = subnet.Id, } }, Name = "networkprofile", Primary = true, } }, OsProfile = new ScaleSetOsProfileArgs { AdminUsername = "******", AdminPassword = "******", ComputerNamePrefix = "lab", CustomData = customData, }, OsProfileLinuxConfig = new ScaleSetOsProfileLinuxConfigArgs { DisablePasswordAuthentication = false }, Sku = new ScaleSetSkuArgs { Capacity = 1, Name = "Standard_DS1_v2", Tier = "Standard", }, StorageProfileDataDisks = { new ScaleSetStorageProfileDataDisksArgs { Caching = "ReadWrite", CreateOption = "Empty", DiskSizeGb = 10, Lun = 0, } }, StorageProfileImageReference = new ScaleSetStorageProfileImageReferenceArgs { Offer = "UbuntuServer", Publisher = "Canonical", Sku = "18.04-LTS", Version = "latest", }, StorageProfileOsDisk = new ScaleSetStorageProfileOsDiskArgs { Caching = "ReadWrite", CreateOption = "FromImage", ManagedDiskType = "Standard_LRS", Name = "", }, UpgradePolicyMode = "Automatic", }, CustomResourceOptions.Merge(options, new CustomResourceOptions { DependsOn = { bpepool, rule } })); var autoscale = new AutoscaleSetting($"as-{location}", new AutoscaleSettingArgs { ResourceGroupName = resourceGroup.Name, Location = location, Notification = new AutoscaleSettingNotificationArgs { Email = new AutoscaleSettingNotificationEmailArgs { CustomEmails = { "*****@*****.**" }, SendToSubscriptionAdministrator = true, SendToSubscriptionCoAdministrator = true, }, }, Profiles = { new AutoscaleSettingProfilesArgs { Capacity = new AutoscaleSettingProfilesCapacityArgs { Default = 1, Maximum = 10, Minimum = 1, }, Name = "defaultProfile", Rules = { new AutoscaleSettingProfilesRulesArgs { MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs { MetricName = "Percentage CPU", MetricResourceId = scaleSet.Id, Operator = "GreaterThan", Statistic = "Average", Threshold = 75, TimeAggregation = "Average", TimeGrain = "PT1M", TimeWindow = "PT5M", }, ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs { Cooldown = "PT1M", Direction = "Increase", Type = "ChangeCount", Value = 1, }, }, new AutoscaleSettingProfilesRulesArgs { MetricTrigger = new AutoscaleSettingProfilesRulesMetricTriggerArgs { MetricName = "Percentage CPU", MetricResourceId = scaleSet.Id, Operator = "LessThan", Statistic = "Average", Threshold = 25, TimeAggregation = "Average", TimeGrain = "PT1M", TimeWindow = "PT5M", }, ScaleAction = new AutoscaleSettingProfilesRulesScaleActionArgs { Cooldown = "PT1M", Direction = "Decrease", Type = "ChangeCount", Value = 1, }, }, } } }, TargetResourceId = scaleSet.Id, }, options); return new AzureEndpoint(publicIp.Id); }); }
/// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> public static LoadBalancer BeginCreateOrUpdate(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters) { return(operations.BeginCreateOrUpdateAsync(resourceGroupName, loadBalancerName, parameters).GetAwaiter().GetResult()); }
static int Main(string[] args) { var webFarmName = args.FirstOrDefault(); if (string.IsNullOrEmpty(webFarmName)) { Console.WriteLine("Please specify web farm name:"); webFarmName = Console.ReadLine(); } var config = StingrayLoadBalancer.Properties.Settings.Default.StingrayConfiguration .Where(x => x.WebFarmName == webFarmName) .FirstOrDefault(); if (config == null) { Console.Error.WriteLine("Configuration not found for web farm name '{0}'.", webFarmName); return((int)ExitCode.InvalidWebFarmName); } var cmd = "list"; while (!string.IsNullOrEmpty(cmd)) { try { if (!string.IsNullOrEmpty(cmd)) { var pars = cmd.Split(' '); switch (pars[0]) { case "add": LoadBalancer.AddNode(config, pars[1]); break; case "remove": LoadBalancer.RemoveNode(config, pars[1]); break; case "enable": LoadBalancer.EnableNode(config, pars[1]); break; case "disable": LoadBalancer.DisableNode(config, pars[1]); break; case "drain": LoadBalancer.DrainNode(config, pars[1]); break; case "list": { Console.WriteLine("Listing nodes in pool {0}.", config.PoolName); var nodes = StingrayLoadBalancer.LoadBalancer.GetNodes(config).OrderBy(x => x.Name); Console.WriteLine("{0} nodes in pool {1}.", nodes.Count(), config.PoolName); foreach (var node in nodes) { Console.WriteLine(node.ToString()); } } break; default: Console.Error.WriteLine("Unknown command."); break; } } } catch (Exception e) { Console.Error.WriteLine("Command failed! ({0})", e.Message); } Console.WriteLine("\nEnter command (exit, add <nodename>, remove <nodename>, enable <nodename>, disable <nodename>, drain <nodename>, list): "); cmd = Console.ReadLine(); } return((int)ExitCode.Success); }
/// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <LoadBalancer> BeginCreateOrUpdateAsync(this ILoadBalancersOperations operations, string resourceGroupName, string loadBalancerName, LoadBalancer parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public void LoadSpreadFromConfig() { const int Count = 100000; var configPath = "LoadBalancer.config"; this.balancer = new LoadBalancer<Server>(configPath); for (int i = 0; i < this.servers.Count; i++) { bool result = this.balancer.TryAddServer(this.servers[i], FeedbackLevel.Lowest); Assert.IsTrue(result); } // 5 servers with a load level of lowest // every server should get about 20 percent of the assigments this.AssignServerLoop(Count); for (int i = 0; i < this.servers.Count; i++) { this.CheckServer(this.servers[i], Count, 20, 5); } this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.High); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 25, 5); this.CheckServer(this.servers[1], Count, 25, 5); this.CheckServer(this.servers[2], Count, 25, 5); this.CheckServer(this.servers[3], Count, 25, 5); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Low); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 20, 5); this.CheckServer(this.servers[1], Count, 20, 5); this.CheckServer(this.servers[2], Count, 20, 5); this.CheckServer(this.servers[3], Count, 20, 5); this.CheckServer(this.servers[4], Count, 20, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Normal); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 20, 5); this.CheckServer(this.servers[1], Count, 20, 5); this.CheckServer(this.servers[2], Count, 20, 5); this.CheckServer(this.servers[3], Count, 20, 5); this.CheckServer(this.servers[4], Count, 20, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Highest); this.UpdateServer(this.servers[2], FeedbackLevel.Highest); this.UpdateServer(this.servers[3], FeedbackLevel.Highest); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 100, 0); this.CheckServer(this.servers[1], Count, 0, 0); this.CheckServer(this.servers[2], Count, 0, 0); this.CheckServer(this.servers[3], Count, 0, 0); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Highest); Server server; Assert.IsFalse(this.balancer.TryGetServer(out server)); }
public ValidationController() { _client = new HttpClient(); _balancer = LoadBalancer.GetInstance(); _link = _balancer.GetHost(); }
public async Task ExpandResourceTest() { string resourceGroupName = Recording.GenerateAssetName("csmrg"); string location = TestEnvironment.Location; var resourceGroup = await CreateResourceGroup(resourceGroupName); // Create lbPublicIP string lbPublicIpName = Recording.GenerateAssetName("azsmnet"); string lbDomaingNameLabel = Recording.GenerateAssetName("azsmnet"); PublicIPAddress lbPublicIp = await CreateDefaultPublicIpAddress( lbPublicIpName, lbDomaingNameLabel, location, resourceGroup.GetPublicIPAddresses()); // Create Vnet string vnetName = Recording.GenerateAssetName("azsmnet"); string subnetName = Recording.GenerateAssetName("azsmnet"); VirtualNetwork vnet = await CreateVirtualNetwork(vnetName, subnetName, location, resourceGroup.GetVirtualNetworks()); // Create Nics string nic1name = Recording.GenerateAssetName("azsmnet"); string nic2name = Recording.GenerateAssetName("azsmnet"); string nic3name = Recording.GenerateAssetName("azsmnet"); NetworkInterface nic1 = await CreateNetworkInterface( nic1name, null, vnet.Data.Subnets[0].Id, location, "ipconfig", resourceGroup.GetNetworkInterfaces()); NetworkInterface nic2 = await CreateNetworkInterface( nic2name, null, vnet.Data.Subnets[0].Id, location, "ipconfig", resourceGroup.GetNetworkInterfaces()); NetworkInterface nic3 = await CreateNetworkInterface( nic3name, null, vnet.Data.Subnets[0].Id, location, "ipconfig", resourceGroup.GetNetworkInterfaces()); // Create the LoadBalancer var lbName = Recording.GenerateAssetName("azsmnet"); var frontendIpConfigName = Recording.GenerateAssetName("azsmnet"); var backEndAddressPoolName = Recording.GenerateAssetName("azsmnet"); var loadBalancingRuleName = Recording.GenerateAssetName("azsmnet"); var probeName = Recording.GenerateAssetName("azsmnet"); var inboundNatRule1Name = Recording.GenerateAssetName("azsmnet"); var inboundNatRule2Name = Recording.GenerateAssetName("azsmnet"); // Populate the loadBalancerCreateOrUpdateParameter var loadBalancerData = new LoadBalancerData() { Location = location, FrontendIPConfigurations = { new FrontendIPConfigurationData() { Name = frontendIpConfigName, PublicIPAddress = new PublicIPAddressData() { Id = lbPublicIp.Id } } }, BackendAddressPools = { new BackendAddressPoolData() { Name = backEndAddressPoolName, } }, LoadBalancingRules = { new LoadBalancingRuleData() { Name = loadBalancingRuleName, FrontendIPConfiguration = new WritableSubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 80, BackendPort = 80, EnableFloatingIP = false, IdleTimeoutInMinutes = 15, BackendAddressPool = new WritableSubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "backendAddressPools", backEndAddressPoolName) }, Probe = new WritableSubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "probes", probeName) } } }, Probes = { new ProbeData() { Name = probeName, Protocol = ProbeProtocol.Http, Port = 80, RequestPath = "healthcheck.aspx", IntervalInSeconds = 10, NumberOfProbes = 2 } }, InboundNatRules = { new InboundNatRuleData() { Name = inboundNatRule1Name, FrontendIPConfiguration = new WritableSubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3389, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false }, new InboundNatRuleData() { Name = inboundNatRule2Name, FrontendIPConfiguration = new WritableSubResource() { Id = GetChildLbResourceId(TestEnvironment.SubscriptionId, resourceGroupName, lbName, "FrontendIPConfigurations", frontendIpConfigName) }, Protocol = TransportProtocol.Tcp, FrontendPort = 3390, BackendPort = 3389, IdleTimeoutInMinutes = 15, EnableFloatingIP = false, } } }; // Create the loadBalancer var loadBalancerCollection = resourceGroup.GetLoadBalancers(); LoadBalancer loadBalancer = (await loadBalancerCollection.CreateOrUpdateAsync(true, lbName, loadBalancerData)).Value; // Associate the nic with LB //nic1.GetNetworkInterfaceIPConfigurations().List().First().` // TODO: where do we have the following? //nic1.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(getLoadBalancer.Value.BackendAddressPools.First()); //nic1.IpConfigurations.First().LoadBalancerInboundNatRules.Add(getLoadBalancer.Value.InboundNatRules.First()); //nic2.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(getLoadBalancer.Value.BackendAddressPools.First()); //nic3.IpConfigurations.First().LoadBalancerInboundNatRules.Add(getLoadBalancer.Value.InboundNatRules[1]); nic1.Data.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(loadBalancer.Data.BackendAddressPools.First()); nic1.Data.IpConfigurations.First().LoadBalancerInboundNatRules.Add(loadBalancer.Data.InboundNatRules[0]); nic2.Data.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(loadBalancer.Data.BackendAddressPools.First()); nic2.Data.IpConfigurations.First().LoadBalancerInboundNatRules.Add(loadBalancer.Data.InboundNatRules[1]); nic3.Data.IpConfigurations.First().LoadBalancerBackendAddressPools.Add(loadBalancer.Data.BackendAddressPools.First()); // Put Nics var networkInterfaceCollection = resourceGroup.GetNetworkInterfaces(); var createOrUpdateOperation1 = await networkInterfaceCollection.CreateOrUpdateAsync(true, nic1name, nic1.Data); await createOrUpdateOperation1.WaitForCompletionAsync(); var createOrUpdateOperation2 = await networkInterfaceCollection.CreateOrUpdateAsync(true, nic2name, nic2.Data); await createOrUpdateOperation2.WaitForCompletionAsync(); var createOrUpdateOperation3 = await networkInterfaceCollection.CreateOrUpdateAsync(true, nic3name, nic3.Data); await createOrUpdateOperation3.WaitForCompletionAsync(); // Get Nics await networkInterfaceCollection.GetAsync(nic1name); await networkInterfaceCollection.GetAsync(nic2name); await networkInterfaceCollection.GetAsync(nic3name); // Get lb with expanded nics from nat rules loadBalancer = await loadBalancerCollection.GetAsync(lbName, "InboundNatRules/backendIPConfiguration"); foreach (var natRule in loadBalancer.GetInboundNatRules()) { Assert.NotNull(natRule.Data.BackendIPConfiguration); Assert.NotNull(natRule.Data.BackendIPConfiguration.Id); //Assert.NotNull(natRule.Data.BackendIPConfiguration.Name); //Assert.NotNull(natRule.Data.BackendIPConfiguration.Etag); //Assert.AreEqual(natRule.Id, natRule.Data.BackendIPConfiguration.LoadBalancerInboundNatRules[0].Id); } // Get lb with expanded nics from pools loadBalancer = await loadBalancerCollection.GetAsync(lbName, "BackendAddressPools/backendIPConfigurations"); foreach (var pool in loadBalancer.GetBackendAddressPools()) { foreach (var ipconfig in loadBalancer.GetBackendAddressPools().First().Data.BackendIPConfigurations) { Assert.NotNull(ipconfig.Id); //Assert.NotNull(ipconfig.Name); //Assert.NotNull(ipconfig.Etag); //Assert.AreEqual(pool.Id, ipconfig.LoadBalancerBackendAddressPools[0].Id); } } // Get lb with expanded publicip loadBalancer = await loadBalancerCollection.GetAsync(lbName, "FrontendIPConfigurations/PublicIPAddress"); foreach (var ipconfig in loadBalancer.Data.FrontendIPConfigurations) { Assert.NotNull(ipconfig.PublicIPAddress); Assert.NotNull(ipconfig.PublicIPAddress.Id); Assert.NotNull(ipconfig.PublicIPAddress.Name); Assert.NotNull(ipconfig.PublicIPAddress.Etag); Assert.AreEqual(ipconfig.Id, ipconfig.PublicIPAddress.IpConfiguration.Id); } // Get NIC with expanded subnet nic1 = await networkInterfaceCollection.GetAsync(nic1name, "IPConfigurations/Subnet"); foreach (NetworkInterfaceIPConfiguration ipconfig in nic1.GetNetworkInterfaceIPConfigurations()) { Assert.NotNull(ipconfig.Data.Subnet); Assert.NotNull(ipconfig.Data.Subnet.Id); //Assert.NotNull(ipconfig.Subnet.Name); //Assert.NotNull(ipconfig.Subnet.Etag); //Assert.IsNotEmpty(ipconfig.Subnet.IpConfigurations); } // Get subnet with expanded ipconfigurations Response <Subnet> subnet = await resourceGroup.GetVirtualNetworks().Get(vnetName).Value.GetSubnets().GetAsync( subnetName, "IPConfigurations"); foreach (IPConfiguration ipconfig in subnet.Value.Data.IpConfigurations) { Assert.NotNull(ipconfig.Id); //Assert.NotNull(ipconfig.Name); //Assert.NotNull(ipconfig.Etag); Assert.NotNull(ipconfig.PrivateIPAddress); } // Get publicIPAddress with expanded ipconfigurations Response <PublicIPAddress> publicip = await resourceGroup.GetPublicIPAddresses().GetAsync( lbPublicIpName, "IPConfiguration"); Assert.NotNull(publicip.Value.Data.IpConfiguration); Assert.NotNull(publicip.Value.Data.IpConfiguration.Id); //Assert.NotNull(publicip.Value.Data.IpConfiguration.Name); //Assert.NotNull(publicip.Value.Data.IpConfiguration.Etag); // Delete LoadBalancer Operation deleteOperation = await loadBalancerCollection.Get(lbName).Value.DeleteAsync(true); await deleteOperation.WaitForCompletionResponseAsync(); // Verify Delete AsyncPageable <LoadBalancer> listLoadBalancerAP = loadBalancerCollection.GetAllAsync(); List <LoadBalancer> listLoadBalancer = await listLoadBalancerAP.ToEnumerableAsync(); Assert.IsEmpty(listLoadBalancer); // Delete all NetworkInterfaces await networkInterfaceCollection.Get(nic1name).Value.DeleteAsync(true); await networkInterfaceCollection.Get(nic2name).Value.DeleteAsync(true); await networkInterfaceCollection.Get(nic3name).Value.DeleteAsync(true); // Delete all PublicIPAddresses await resourceGroup.GetPublicIPAddresses().Get(lbPublicIpName).Value.DeleteAsync(true); }
public async Task TestCreatePtrRecords() { string domainName = CreateRandomDomainName(); string loadBalancerName = UserLoadBalancerTests.CreateRandomLoadBalancerName(); IDnsService provider = CreateProvider(); ILoadBalancerService loadBalancerProvider = UserLoadBalancerTests.CreateProvider(); using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(60)))) { IEnumerable <LoadBalancingProtocol> protocols = await loadBalancerProvider.ListProtocolsAsync(cancellationTokenSource.Token); LoadBalancingProtocol httpProtocol = protocols.First(i => i.Name.Equals("HTTP", StringComparison.OrdinalIgnoreCase)); LoadBalancerConfiguration loadBalancerConfiguration = new LoadBalancerConfiguration( name: loadBalancerName, nodes: null, protocol: httpProtocol, virtualAddresses: new[] { new LoadBalancerVirtualAddress(LoadBalancerVirtualAddressType.Public) }, algorithm: LoadBalancingAlgorithm.RoundRobin); LoadBalancer loadBalancer = await loadBalancerProvider.CreateLoadBalancerAsync(loadBalancerConfiguration, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); Assert.IsNotNull(loadBalancer.VirtualAddresses); Assert.IsTrue(loadBalancer.VirtualAddresses.Count > 0); string originalData = loadBalancer.VirtualAddresses[0].Address.ToString(); string originalName = string.Format("www.{0}", domainName); string updatedName = string.Format("www2.{0}", domainName); string originalCommentValue = "Integration test record"; string updatedCommentValue = "Integration test record 2"; TimeSpan?originalTimeToLive; TimeSpan?updatedTimeToLive = TimeSpan.FromMinutes(12); DnsDomainRecordConfiguration[] recordConfigurations = { new DnsDomainRecordConfiguration( type: DnsRecordType.Ptr, name: string.Format("www.{0}",domainName), data: originalData, timeToLive: null, comment: originalCommentValue, priority: null) }; string serviceName = "cloudLoadBalancers"; Uri deviceResourceUri = await((UserLoadBalancerTests.TestCloudLoadBalancerProvider)loadBalancerProvider).GetDeviceResourceUri(loadBalancer, cancellationTokenSource.Token); DnsJob <DnsRecordsList> recordsResponse = await provider.AddPtrRecordsAsync(serviceName, deviceResourceUri, recordConfigurations, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); Assert.IsNotNull(recordsResponse.Response); Assert.IsNotNull(recordsResponse.Response.Records); DnsRecord[] records = recordsResponse.Response.Records.ToArray(); Assert.AreEqual(recordConfigurations.Length, records.Length); originalTimeToLive = records[0].TimeToLive; Assert.AreNotEqual(originalTimeToLive, updatedTimeToLive); Assert.AreEqual(originalData, records[0].Data); Assert.AreEqual(originalTimeToLive, records[0].TimeToLive); Assert.AreEqual(originalCommentValue, records[0].Comment); foreach (var record in records) { Console.WriteLine(); Console.WriteLine("Record: {0} ({1})", record.Name, record.Id); Console.WriteLine(); Console.WriteLine(await JsonConvert.SerializeObjectAsync(record, Formatting.Indented)); } // update the comment and verify nothing else changed DnsDomainRecordUpdateConfiguration recordUpdateConfiguration = new DnsDomainRecordUpdateConfiguration(records[0], originalName, originalData, comment: updatedCommentValue); await provider.UpdatePtrRecordsAsync(serviceName, deviceResourceUri, new[] { recordUpdateConfiguration }, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); DnsRecord updatedRecord = await provider.ListPtrRecordDetailsAsync(serviceName, deviceResourceUri, records[0].Id, cancellationTokenSource.Token); Assert.IsNotNull(updatedRecord); Assert.AreEqual(originalData, updatedRecord.Data); Assert.AreEqual(originalName, updatedRecord.Name); Assert.AreEqual(originalTimeToLive, updatedRecord.TimeToLive); Assert.AreEqual(updatedCommentValue, updatedRecord.Comment); // update the TTL and verify nothing else changed recordUpdateConfiguration = new DnsDomainRecordUpdateConfiguration(records[0], originalName, originalData, timeToLive: updatedTimeToLive); await provider.UpdatePtrRecordsAsync(serviceName, deviceResourceUri, new[] { recordUpdateConfiguration }, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); updatedRecord = await provider.ListPtrRecordDetailsAsync(serviceName, deviceResourceUri, records[0].Id, cancellationTokenSource.Token); Assert.IsNotNull(updatedRecord); Assert.AreEqual(originalData, updatedRecord.Data); Assert.AreEqual(originalName, updatedRecord.Name); Assert.AreEqual(updatedTimeToLive, updatedRecord.TimeToLive); Assert.AreEqual(updatedCommentValue, updatedRecord.Comment); // update the name and verify nothing else changed recordUpdateConfiguration = new DnsDomainRecordUpdateConfiguration(records[0], updatedName, originalData); await provider.UpdatePtrRecordsAsync(serviceName, deviceResourceUri, new[] { recordUpdateConfiguration }, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); updatedRecord = await provider.ListPtrRecordDetailsAsync(serviceName, deviceResourceUri, records[0].Id, cancellationTokenSource.Token); Assert.IsNotNull(updatedRecord); Assert.AreEqual(originalData, updatedRecord.Data); Assert.AreEqual(updatedName, updatedRecord.Name); Assert.AreEqual(updatedTimeToLive, updatedRecord.TimeToLive); Assert.AreEqual(updatedCommentValue, updatedRecord.Comment); // remove the PTR record // TODO: verify result? await provider.RemovePtrRecordsAsync(serviceName, deviceResourceUri, loadBalancer.VirtualAddresses[0].Address, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); /* Cleanup */ await loadBalancerProvider.RemoveLoadBalancerAsync(loadBalancer.Id, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null); } }
public void LoadSpreadByDefault() { const int Count = 100000; // default, as per DefaultConfiguration.GetDefaultWeights: /* var loadLevelWeights = new int[] { 40, // FeedbackLevel.Lowest 30, // FeedbackLevel.Low 20, // FeedbackLevel.Normal 10, // FeedbackLevel.High 0 // FeedbackLevel.Highest }; */ this.balancer = new LoadBalancer<Server>(); for (int i = 0; i < this.servers.Count; i++) { bool result = this.balancer.TryAddServer(this.servers[i], FeedbackLevel.Lowest); Assert.IsTrue(result); } // 5 servers with a load level of lowest // every server should get about 20 percent of the assigments this.AssignServerLoop(Count); for (int i = 0; i < this.servers.Count; i++) { this.CheckServer(this.servers[i], Count, 20, 5); } this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.High); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 40, 5); this.CheckServer(this.servers[1], Count, 30, 5); this.CheckServer(this.servers[2], Count, 20, 5); this.CheckServer(this.servers[3], Count, 10, 5); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Lowest); this.UpdateServer(this.servers[1], FeedbackLevel.Low); this.UpdateServer(this.servers[2], FeedbackLevel.Low); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 28, 5); this.CheckServer(this.servers[1], Count, 21, 5); this.CheckServer(this.servers[2], Count, 21, 5); this.CheckServer(this.servers[3], Count, 14, 5); this.CheckServer(this.servers[4], Count, 14, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Normal); this.UpdateServer(this.servers[2], FeedbackLevel.Normal); this.UpdateServer(this.servers[3], FeedbackLevel.Normal); this.UpdateServer(this.servers[4], FeedbackLevel.Normal); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 27, 5); this.CheckServer(this.servers[1], Count, 18, 5); this.CheckServer(this.servers[2], Count, 18, 5); this.CheckServer(this.servers[3], Count, 18, 5); this.CheckServer(this.servers[4], Count, 18, 5); this.UpdateServer(this.servers[0], FeedbackLevel.Low); this.UpdateServer(this.servers[1], FeedbackLevel.Highest); this.UpdateServer(this.servers[2], FeedbackLevel.Highest); this.UpdateServer(this.servers[3], FeedbackLevel.Highest); this.UpdateServer(this.servers[4], FeedbackLevel.Highest); this.AssignServerLoop(Count); this.CheckServer(this.servers[0], Count, 100, 0); this.CheckServer(this.servers[1], Count, 0, 0); this.CheckServer(this.servers[2], Count, 0, 0); this.CheckServer(this.servers[3], Count, 0, 0); this.CheckServer(this.servers[4], Count, 0, 0); this.UpdateServer(this.servers[0], FeedbackLevel.Highest); Server server; Assert.IsFalse(this.balancer.TryGetServer(out server)); }
private bool ValidateBaseResourceTenant(LoadBalancer tenant) { return(tenant != null && tenant.SubscriptionId == null && tenant.TenantResourceUri != null); }