public IActionResult GetScopesAsTreeView() { List <DHCPv6ScopeTreeViewItem> result = new List <DHCPv6ScopeTreeViewItem>(); foreach (var item in _rootScope.GetRootScopes()) { GenerateScopeTree(item, result); } return(base.Ok(result)); }
public void GetLeaseById() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(3, 10); HashSet <Guid> existingIds = new HashSet <Guid>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), }); existingIds.Add(leaseId); } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); foreach (Guid leaseId in existingIds) { DHCPv6Lease lease = scope.Leases.GetLeaseById(leaseId); Assert.True(lease != DHCPv6Lease.Empty); } Int32 notExisitngAmount = random.Next(30, 100); for (int i = 0; i < notExisitngAmount; i++) { Guid id = Guid.NewGuid(); if (existingIds.Contains(id) == true) { continue; } DHCPv6Lease lease = scope.Leases.GetLeaseById(id); Assert.True(lease == DHCPv6Lease.Empty); } }
public void IsActive() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(10, 30); Dictionary <Guid, Boolean> expectedResults = new Dictionary <Guid, bool>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), }); Boolean addressIsActive = random.NextDouble() > 0.5; if (addressIsActive == true) { events.Add(new DHCPv6LeaseActivatedEvent(leaseId)); } expectedResults.Add(leaseId, addressIsActive); } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); foreach (var item in expectedResults) { DHCPv6Lease lease = scope.Leases.GetLeaseById(item.Key); Boolean actual = lease.IsActive(); Assert.Equal(item.Value, actual); } }
public void GetSuspenedAddresses() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(30, 60); List <IPv6Address> expectedUsedAddress = new List <IPv6Address>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); IPv6Address address = random.GetIPv6Address(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = address, ClientIdentifier = new UUIDDUID(random.NextGuid()), }); Boolean shouldBeSuspended = random.NextDouble() > 0.5; if (shouldBeSuspended == true) { events.Add(new DHCPv6AddressSuspendedEvent( leaseId, address, DateTime.UtcNow.AddHours(12))); expectedUsedAddress.Add(address); } } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); List <IPv6Address> actualAddresses = scope.Leases.GetSuspendedAddresses().ToList(); Assert.Equal(expectedUsedAddress.OrderBy(x => x), actualAddresses.OrderBy(x => x)); }
public void LimitLeasesPerClient() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); DUID clientIdentifier = new UUIDDUID(random.NextGuid()); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(20, 40); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = clientIdentifier }); events.Add(new DHCPv6LeaseActivatedEvent { ScopeId = scopeId, EntityId = leaseId, }); events.Add(new DHCPv6LeaseRevokedEvent { ScopeId = scopeId, EntityId = leaseId, }); } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); var leases = scope.Leases.GetAllLeases(); Assert.Empty(leases); }
public async Task Handle() { Random random = new Random(); String name = random.GetAlphanumericString(); String description = random.GetAlphanumericString(); IPv6Address start = random.GetIPv6Address(); IPv6Address end = start + 100; String resolverName = random.GetAlphanumericString(); Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(); scopeResolverMock.Setup(x => x.IsResolverInformationValid(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(true).Verifiable(); scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(Mock.Of <IScopeResolver <DHCPv6Packet, IPv6Address> >()).Verifiable(); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >()); DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict); storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable(); var command = new CreateDHCPv6ScopeCommand(name, description, null, new DHCPv6ScopeAddressPropertyReqest { Start = start.ToString(), End = end.ToString(), ExcludedAddresses = Array.Empty <String>(), AcceptDecline = random.NextBoolean(), AddressAllocationStrategy = DHCPv6ScopeAddressPropertyReqest.AddressAllocationStrategies.Next, InformsAreAllowd = random.NextBoolean(), RapitCommitEnabled = random.NextBoolean(), ReuseAddressIfPossible = random.NextBoolean(), SupportDirectUnicast = random.NextBoolean(), PreferredLifeTime = TimeSpan.FromDays(0.5), ValidLifeTime = TimeSpan.FromDays(1), PrefixDelgationInfo = new DHCPv6PrefixDelgationInfoRequest { AssingedPrefixLength = 80, Prefix = "fe80::0", PrefixLength = 64 }, T1 = 0.3, T2 = 0.65, }, new CreateScopeResolverRequest { PropertiesAndValues = new Dictionary <String, String>(), Typename = resolverName, }, new[] { new DHCPv6AddressListScopePropertyRequest { OptionCode = 24, Type = Beer.DaAPI.Core.Scopes.DHCPv6.ScopeProperties.DHCPv6ScopePropertyType.AddressList, Addresses = random.GetIPv6Addresses().Select(x => x.ToString()).ToArray(), }, new DHCPv6AddressListScopePropertyRequest { OptionCode = 64, MarkAsRemovedInInheritance = true, } } ); var handler = new CreateDHCPv6ScopeCommandHandler(storageMock.Object, rootScope, Mock.Of <ILogger <CreateDHCPv6ScopeCommandHandler> >()); Guid?result = await handler.Handle(command, CancellationToken.None); Assert.True(result.HasValue); var scope = rootScope.GetRootScopes().First(); Assert.True(scope.Properties.IsMarkedAsRemovedFromInheritance(64)); Assert.False(scope.Properties.IsMarkedAsRemovedFromInheritance(24)); scopeResolverMock.Verify(); storageMock.Verify(); }
public async Task Handle(Boolean storeResult, Boolean useDynamicTime) { Random random = new Random(); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); String name = random.GetAlphanumericString(); String description = random.GetAlphanumericString(); IPv6Address start = random.GetIPv6Address(); IPv6Address end = start + 100; String resolverName = random.GetAlphanumericString(); Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); resolverMock.Setup(x => x.GetValues()).Returns(new Dictionary <string, string>()); Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(); scopeResolverMock.Setup(x => x.IsResolverInformationValid(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(true).Verifiable(); scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(resolverMock.Object).Verifiable(); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >()); DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); rootScope.Load(new DomainEvent[] { new DHCPv6ScopeAddedEvent { Instructions = new DHCPv6ScopeCreateInstruction { Name = random.GetAlphanumericString(), Description = random.GetAlphanumericString(), Id = scopeId, ParentId = null, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, ScopeProperties = new DHCPv6ScopeProperties(), AddressProperties = DHCPv6ScopeAddressProperties.Empty, } }, new DHCPv6LeaseCreatedEvent { EntityId = leaseId, Address = start - 100, ScopeId = scopeId, HasPrefixDelegation = true, PrefixLength = 64, ClientIdentifier = new UUIDDUID(random.NextGuid()), IdentityAssocationIdForPrefix = random.NextUInt32(), DelegatedNetworkAddress = IPv6Address.FromString("fc70::0"), }, new DHCPv6LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, } }); Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict); storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(storeResult).Verifiable(); var command = new UpdateDHCPv6ScopeCommand(scopeId, name, description, null, useDynamicTime == false ? new DHCPv6ScopeAddressPropertyReqest { Start = start.ToString(), End = end.ToString(), ExcludedAddresses = Array.Empty <String>(), AcceptDecline = random.NextBoolean(), AddressAllocationStrategy = DHCPv6ScopeAddressPropertyReqest.AddressAllocationStrategies.Next, InformsAreAllowd = random.NextBoolean(), RapitCommitEnabled = random.NextBoolean(), ReuseAddressIfPossible = random.NextBoolean(), SupportDirectUnicast = random.NextBoolean(), PreferredLifeTime = TimeSpan.FromDays(0.5), ValidLifeTime = TimeSpan.FromDays(1), PrefixDelgationInfo = new DHCPv6PrefixDelgationInfoRequest { AssingedPrefixLength = 80, Prefix = "fe80::0", PrefixLength = 64 }, T1 = 0.3, T2 = 0.65, } : new DHCPv6ScopeAddressPropertyReqest { Start = start.ToString(), End = end.ToString(), ExcludedAddresses = Array.Empty <String>(), AcceptDecline = random.NextBoolean(), AddressAllocationStrategy = DHCPv6ScopeAddressPropertyReqest.AddressAllocationStrategies.Next, InformsAreAllowd = random.NextBoolean(), RapitCommitEnabled = random.NextBoolean(), ReuseAddressIfPossible = random.NextBoolean(), SupportDirectUnicast = random.NextBoolean(), PrefixDelgationInfo = new DHCPv6PrefixDelgationInfoRequest { AssingedPrefixLength = 80, Prefix = "fe80::0", PrefixLength = 64 }, DynamicRenewTime = new DHCPv6DynamicRenewTimeRequest { Hours = 5, Minutes = 10, MinutesToEndOfLife = 45, MinutesToRebound = 35, }, }, new CreateScopeResolverRequest { PropertiesAndValues = new Dictionary <String, String>(), Typename = resolverName, }, new[] { new DHCPv6AddressListScopePropertyRequest { OptionCode = 24, Type = Beer.DaAPI.Core.Scopes.DHCPv6.ScopeProperties.DHCPv6ScopePropertyType.AddressList, Addresses = random.GetIPv6Addresses().Select(x => x.ToString()).ToArray(), }, new DHCPv6AddressListScopePropertyRequest { OptionCode = 64, MarkAsRemovedInInheritance = true, } } ); var serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict); serviceBusMock.Setup(x => x.Publish(It.Is <NewTriggerHappendMessage>(y => y.Triggers.Count() == 1 && ((PrefixEdgeRouterBindingUpdatedTrigger)y.Triggers.First()).OldBinding.Prefix == IPv6Address.FromString("fc70::0") ))).Returns(Task.CompletedTask); var handler = new UpdateDHCPv6ScopeCommandHandler(storageMock.Object, serviceBusMock.Object, rootScope, Mock.Of <ILogger <UpdateDHCPv6ScopeCommandHandler> >()); Boolean result = await handler.Handle(command, CancellationToken.None); Assert.Equal(storeResult, result); var scope = rootScope.GetRootScopes().First(); Assert.Equal(name, scope.Name); Assert.Equal(description, scope.Description); Assert.NotNull(scope.Resolver); Assert.Equal(start, scope.AddressRelatedProperties.Start); Assert.True(scope.Properties.IsMarkedAsRemovedFromInheritance(64)); Assert.False(scope.Properties.IsMarkedAsRemovedFromInheritance(24)); if (useDynamicTime == true) { Assert.True(scope.AddressRelatedProperties.UseDynamicRewnewTime); Assert.Equal(5, scope.AddressRelatedProperties.DynamicRenewTime.Hour); } else { Assert.False(scope.AddressRelatedProperties.UseDynamicRewnewTime); } scopeResolverMock.Verify(); storageMock.Verify(); if (storeResult == true) { serviceBusMock.Verify(); Assert.Empty(rootScope.GetTriggers()); } else { Assert.Single(rootScope.GetTriggers()); } }
public void IsAddressActive() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(30, 60); Dictionary <IPv6Address, Boolean> expectedUsedAddress = new Dictionary <IPv6Address, bool>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); IPv6Address address = random.GetIPv6Address(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = address, ClientIdentifier = new UUIDDUID(random.NextGuid()), }); Boolean addressIsInUse = random.NextDouble() > 0.5; if (addressIsInUse == true) { events.Add(new DHCPv6LeaseActivatedEvent(leaseId)); } expectedUsedAddress.Add(address, addressIsInUse); } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); foreach (var item in expectedUsedAddress) { Boolean actual = scope.Leases.IsAddressActive(item.Key); Assert.Equal(item.Value, actual); } Int32 notExistingAddressesAmount = random.Next(30, 50); for (int i = 0; i < notExistingAddressesAmount; i++) { IPv6Address notExisitingAddress = random.GetIPv6Address(); if (expectedUsedAddress.ContainsKey(notExisitingAddress) == true) { continue; } Boolean actual = scope.Leases.IsAddressActive(notExisitingAddress); Assert.False(actual); } }
public void GetUsedAddresses() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(30, 60); List <IPv6Address> expectedUsedAddress = new List <IPv6Address>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); IPv6Address address = random.GetIPv6Address(); events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = address, ClientIdentifier = new UUIDDUID(random.NextGuid()), }); DomainEvent eventToAdd = null; Boolean addressIsInUse = true; Double randomValue = random.NextDouble(); Double possiblities = 5.0; if (randomValue < 1 / possiblities) { eventToAdd = new DHCPv6LeaseReleasedEvent(leaseId, false); addressIsInUse = false; } else if (randomValue < 2 / possiblities) { eventToAdd = new DHCPv6LeaseRevokedEvent(leaseId); addressIsInUse = false; } else if (randomValue < 3 / possiblities) { eventToAdd = new DHCPv6AddressSuspendedEvent(leaseId, random.GetIPv6Address(), DateTime.UtcNow.AddHours(12)); addressIsInUse = false; } if (eventToAdd != null) { events.Add(eventToAdd); } if (addressIsInUse == true) { expectedUsedAddress.Add(address); } } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); List <IPv6Address> actualAddresses = scope.Leases.GetUsedAddresses().ToList(); Assert.Equal(expectedUsedAddress, actualAddresses); }
public void GetScopesAsTreeView() { Random random = new Random(); var events = new List <DomainEvent>(); Int32 rootScopeAmount = random.Next(10, 30); List <Guid> rootScopeIds = new List <Guid>(rootScopeAmount); for (int i = 0; i < rootScopeAmount; i++) { Guid scopeId = Guid.NewGuid(); IPv6Address start = random.GetIPv6Address(); IPv6Address end = start + 100; events.Add(new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, Name = random.GetAlphanumericString(), AddressProperties = new DHCPv6ScopeAddressProperties(start, end), })); rootScopeIds.Add(scopeId); GenerateScopeTree( random.NextDouble(), random, new List <Guid> { scopeId }, events); } var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(It.IsAny <CreateScopeResolverInformation>())).Returns(Mock.Of <IScopeResolver <DHCPv6Packet, IPv6Address> >()); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >()); DHCPv6RootScope rootScope = new DHCPv6RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); rootScope.Load(events); var controller = new DHCPv6ScopeController( Mock.Of <IMediator>(MockBehavior.Strict), Mock.Of <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict), rootScope); var actionResult = controller.GetScopesAsTreeView(); var result = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6ScopeTreeViewItem> >(true); Assert.Equal(rootScopeAmount, result.Count()); Int32 index = 0; foreach (var item in rootScope.GetRootScopes()) { var scope = result.ElementAt(index); CheckTreeItem(item, scope); index++; } }
public void AddressesAreInUse() { Random random = new Random(123); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); rootScope.Load(new[] { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }) }); Int32 leaseAmount = random.Next(10, 30); Dictionary <DHCPv6Lease, Boolean> expectedResults = new(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); rootScope.Load(new[] { new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), } }); DHCPv6Lease lease = rootScope.GetRootScopes().First().Leases.GetLeaseById(leaseId); DomainEvent eventToAdd = null; Boolean addressIsInUse = true; Double randomValue = random.NextDouble(); Double possiblities = 5.0; if (randomValue < 1 / possiblities) { eventToAdd = new DHCPv6LeaseReleasedEvent(leaseId, false); addressIsInUse = false; } else if (randomValue < 2 / possiblities) { eventToAdd = new DHCPv6LeaseRevokedEvent(leaseId); addressIsInUse = false; } else if (randomValue < 3 / possiblities) { eventToAdd = new DHCPv6AddressSuspendedEvent(leaseId, random.GetIPv6Address(), DateTime.UtcNow.AddHours(12)); addressIsInUse = false; } else if (randomValue < 4 / possiblities) { eventToAdd = new DHCPv6LeaseCanceledEvent(leaseId, LeaseCancelReasons.NotSpecified); addressIsInUse = false; } if (eventToAdd != null) { rootScope.Load(new[] { eventToAdd }); } expectedResults.Add(lease, addressIsInUse); } foreach (var item in expectedResults) { DHCPv6Lease lease = item.Key; Boolean actual = lease.AddressIsInUse(); Assert.Equal(item.Value, actual); } }
public void CanBeExtended() { Random random = new Random(1345); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); rootScope.Load(new[] { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }); Int32 leaseAmount = random.Next(10, 30); Dictionary <DHCPv6Lease, Boolean> expectedResults = new(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); rootScope.Load(new[] { new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), } }); DHCPv6Lease lease = rootScope.GetRootScopes().First().Leases.GetLeaseById(leaseId); Boolean shouldBeExtentable = random.NextBoolean(); DomainEvent @event = null; if (shouldBeExtentable == true) { Int32 nextValue = random.Next(0, 4); switch (nextValue) { case 0: @event = new DHCPv6LeaseActivatedEvent(leaseId); break; case 1: @event = new DHCPv6LeaseReleasedEvent(leaseId, false); break; case 2: @event = new DHCPv6LeaseRenewedEvent(leaseId, DateTime.UtcNow.AddHours(3), TimeSpan.FromHours(1), TimeSpan.FromHours(2), false, false); break; case 3: @event = new DHCPv6LeaseExpiredEvent(leaseId); break; default: break; } } else { Int32 nextValue = random.Next(0, 3); switch (nextValue) { case 0: @event = new DHCPv6LeaseCanceledEvent(leaseId); break; case 1: @event = new DHCPv6LeaseRevokedEvent(leaseId); break; case 2: @event = new DHCPv6AddressSuspendedEvent(leaseId, random.GetIPv6Address(), DateTime.UtcNow.AddHours(3)); break; default: break; } } rootScope.Load(new[] { @event }); expectedResults.Add(lease, shouldBeExtentable); } foreach (var item in expectedResults) { DHCPv6Lease lease = item.Key; Boolean actual = lease.CanBeExtended(); Assert.Equal(item.Value, actual); } }
public void MatchesUniqueIdentiifer() { Random random = new Random(); DHCPv6RootScope rootScope = GetRootScope(); Guid scopeId = Guid.NewGuid(); Byte[] uniqueIdentifier = random.NextBytes(10); List <DomainEvent> events = new List <DomainEvent> { new DHCPv6ScopeAddedEvent(new DHCPv6ScopeCreateInstruction { Id = scopeId, }), }; Int32 leaseAmount = random.Next(3, 10); Dictionary <Guid, Boolean> expectedResults = new Dictionary <Guid, bool>(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = Guid.NewGuid(); Byte[] identifier = null; Boolean matches = false; Double randomValue = random.NextDouble(); if (randomValue > 0.75) { identifier = uniqueIdentifier; matches = true; } else if (randomValue > 0.5) { identifier = random.NextBytes(12); } else if (randomValue > 0.25) { identifier = new byte[0]; } events.Add(new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, UniqueIdentiifer = identifier, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), }); expectedResults.Add(leaseId, matches); } rootScope.Load(events); DHCPv6Scope scope = rootScope.GetRootScopes().First(); foreach (var item in expectedResults) { DHCPv6Lease lease = scope.Leases.GetLeaseById(item.Key); Boolean actual = lease.MatchesUniqueIdentiifer(uniqueIdentifier); Assert.Equal(item.Value, actual); } }
public static Dictionary <DHCPv6Lease, Boolean> AddEventsForCancelableLeases( Random random, Guid scopeId, DHCPv6RootScope rootScope) { Dictionary <LeaseStates, Func <Guid, DHCPv6ScopeRelatedEvent> > cancalableStateBuilder = new Dictionary <LeaseStates, Func <Guid, DHCPv6ScopeRelatedEvent> > { { LeaseStates.Pending, (id) => null }, { LeaseStates.Active, (id) => new DHCPv6LeaseActivatedEvent(id) }, }; Dictionary <LeaseStates, Func <Guid, DHCPv6ScopeRelatedEvent> > nonCancalableStateBuilder = new Dictionary <LeaseStates, Func <Guid, DHCPv6ScopeRelatedEvent> > { //{ LeaseStates.Inactive, (id) => new DHCPv6LeaseExpiredEvent(id) }, //{ LeaseStates.Canceled, (id) => new DHCPv6LeaseCanceledEvent(id) }, { LeaseStates.Released, (id) => new DHCPv6LeaseReleasedEvent(id, false) }, { LeaseStates.Revoked, (id) => new DHCPv6LeaseRevokedEvent(id) }, }; Int32 leaseAmount = random.Next(20, 40); Dictionary <DHCPv6Lease, Boolean> expectedCancallations = new(); for (int i = 0; i < leaseAmount; i++) { Guid leaseId = random.NextGuid(); rootScope.Load(new[] { new DHCPv6LeaseCreatedEvent { ScopeId = scopeId, EntityId = leaseId, Address = random.GetIPv6Address(), ClientIdentifier = new UUIDDUID(random.NextGuid()), } }); DHCPv6Lease lease = rootScope.GetRootScopes().First().Leases.GetLeaseById(leaseId); Boolean shouldBeCancelable = random.NextDouble() > 0.5; Dictionary <LeaseStates, Func <Guid, DHCPv6ScopeRelatedEvent> > eventCreatorDict = null; if (shouldBeCancelable == true) { eventCreatorDict = cancalableStateBuilder; } else { eventCreatorDict = nonCancalableStateBuilder; } var entry = eventCreatorDict.ElementAt(random.Next(0, eventCreatorDict.Count)); DHCPv6ScopeRelatedEvent stateChangingEvent = entry.Value(leaseId); if (stateChangingEvent != null) { stateChangingEvent.ScopeId = scopeId; rootScope.Load(new[] { stateChangingEvent }); } expectedCancallations.Add(lease, shouldBeCancelable); } return(expectedCancallations); }
public async Task SaveAndHydrateRootScope_AddAndRemoveLeases() { Random random = new Random(); await ExecuteWithStreamErase(random, async (eventStore) => { Mock <IDHCPv6ServerPropertiesResolver> propertyResolverMock; DHCPv6StorageEngine engine; PrepareEngine(random, eventStore, out propertyResolverMock, out engine); DHCPv6RootScope initialRootScope = await engine.GetRootScope(); Guid rootScopeId = random.NextGuid(); initialRootScope.AddScope(new DHCPv6ScopeCreateInstruction { AddressProperties = new DHCPv6ScopeAddressProperties( IPv6Address.FromString("fe80::0"), IPv6Address.FromString("fe80::ff"), new List <IPv6Address> { IPv6Address.FromString("fe80::1") }, preferredLifeTime: TimeSpan.FromDays(0.5), validLifeTime: TimeSpan.FromDays(1), rapitCommitEnabled: true, informsAreAllowd: true, supportDirectUnicast: false, reuseAddressIfPossible: false, acceptDecline: true, t1: DHCPv6TimeScale.FromDouble(0.6), t2: DHCPv6TimeScale.FromDouble(0.8), addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next), ScopeProperties = DHCPv6ScopeProperties.Empty, ResolverInformation = new CreateScopeResolverInformation { Typename = nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver), PropertiesAndValues = new Dictionary <String, String> { { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.EnterpriseNumber), random.NextUInt16().ToString() }, { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() }, } }, Name = "Testscope", Id = rootScopeId, }); var clientDuid = new UUIDDUID(random.NextGuid()); DHCPv6Packet solicitPacket = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption> { new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.Zero, TimeSpan.Zero, new List <DHCPv6PacketSuboption>()), }); DHCPv6RelayPacket outerSolicitPacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(random.GetIPv6Address(), random.GetIPv6Address()), true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[] { new DHCPv6PacketRemoteIdentifierOption(random.NextUInt16(), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }), }, solicitPacket); initialRootScope.HandleSolicit(outerSolicitPacket, propertyResolverMock.Object); var firstLease = initialRootScope.GetRootScopes().First().Leases.GetAllLeases().First(); await engine.Save(initialRootScope); initialRootScope = await engine.GetRootScope(); DHCPv6Packet releasePacket = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.RELEASE, new List <DHCPv6PacketOption> { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] { new DHCPv6PacketIdentityAssociationAddressSuboption(firstLease.Address, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), Array.Empty <DHCPv6PacketSuboption>()) }) }); DHCPv6RelayPacket outerreleasePacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(random.GetIPv6Address(), random.GetIPv6Address()), true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[] { new DHCPv6PacketRemoteIdentifierOption(random.NextUInt16(), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }), }, releasePacket); firstLease = initialRootScope.GetRootScopes().First().Leases.GetAllLeases().First(); initialRootScope.HandleRelease(outerreleasePacket, propertyResolverMock.Object); Assert.Equal(LeaseStates.Released, firstLease.State); Assert.Empty(initialRootScope.GetRootScopes().First().Leases.GetAllLeases()); await engine.Save(initialRootScope); await Task.Delay(1000); initialRootScope.DropUnusedLeasesOlderThan(DateTime.Now); Assert.Empty(initialRootScope.GetRootScopes().First().Leases.GetAllLeases()); await engine.Save(initialRootScope); var rehydratedRootScope = await engine.GetRootScope(); Assert.Empty(rehydratedRootScope.GetRootScopes().First().Leases.GetAllLeases()); }); }
public async Task SaveAndHydrateRootScope_AddChangeAndRemoveScopes() { Random random = new Random(); await ExecuteWithStreamErase(random, async (eventStore) => { Mock <IDHCPv6ServerPropertiesResolver> propertyResolverMock; DHCPv6StorageEngine engine; PrepareEngine(random, eventStore, out propertyResolverMock, out engine); DHCPv6RootScope initialRootScope = await engine.GetRootScope(); Guid rootScopeId = random.NextGuid(); Guid firstChildScopeId = random.NextGuid(); Guid secondChildScopeId = random.NextGuid(); initialRootScope.AddScope(new DHCPv6ScopeCreateInstruction { AddressProperties = new DHCPv6ScopeAddressProperties( IPv6Address.FromString("fe80::0"), IPv6Address.FromString("fe80::ff"), new List <IPv6Address> { IPv6Address.FromString("fe80::1") }, preferredLifeTime: TimeSpan.FromDays(0.5), validLifeTime: TimeSpan.FromDays(1), rapitCommitEnabled: true, informsAreAllowd: true, supportDirectUnicast: true, reuseAddressIfPossible: false, acceptDecline: true, t1: DHCPv6TimeScale.FromDouble(0.6), t2: DHCPv6TimeScale.FromDouble(0.8), addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next), ScopeProperties = DHCPv6ScopeProperties.Empty, ResolverInformation = new CreateScopeResolverInformation { Typename = nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver), PropertiesAndValues = new Dictionary <String, String> { { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.EnterpriseNumber), random.NextUInt16().ToString() }, { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() }, } }, Name = "Testscope", Id = rootScopeId, }); initialRootScope.AddScope(new DHCPv6ScopeCreateInstruction { AddressProperties = new DHCPv6ScopeAddressProperties( IPv6Address.FromString("fe80::0"), IPv6Address.FromString("fe80::ff"), new List <IPv6Address> { IPv6Address.FromString("fe80::1") }), ScopeProperties = DHCPv6ScopeProperties.Empty, ResolverInformation = new CreateScopeResolverInformation { Typename = nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver), PropertiesAndValues = new Dictionary <String, String> { { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.EnterpriseNumber), random.NextUInt16().ToString() }, { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() }, } }, Name = "First Child Testscope", Id = firstChildScopeId, ParentId = rootScopeId, }); initialRootScope.AddScope(new DHCPv6ScopeCreateInstruction { AddressProperties = new DHCPv6ScopeAddressProperties( IPv6Address.FromString("fe80::0"), IPv6Address.FromString("fe80::ff"), new List <IPv6Address> { IPv6Address.FromString("fe80::1") }), ScopeProperties = DHCPv6ScopeProperties.Empty, ResolverInformation = new CreateScopeResolverInformation { Typename = nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver), PropertiesAndValues = new Dictionary <String, String> { { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.EnterpriseNumber), random.NextUInt16().ToString() }, { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() }, } }, Name = "Second child Testscope", Id = secondChildScopeId, ParentId = firstChildScopeId, }); initialRootScope.UpdateParent(firstChildScopeId, null); initialRootScope.DeleteScope(firstChildScopeId, true); Assert.Single(initialRootScope.GetRootScopes()); await engine.Save(initialRootScope); var rehydratedRoot = await engine.GetRootScope(); Assert.Single(rehydratedRoot.GetRootScopes()); var rehydratedRootScope = rehydratedRoot.GetRootScopes().First(); Assert.Empty(rehydratedRootScope.GetChildScopes()); }); }