public async Task <Boolean> Handle(UpdateDHCPv4ScopeParentCommand request, CancellationToken cancellationToken) { _logger.LogDebug("Handle started"); var scope = _rootScope.GetScopeById(request.ScopeId); if (scope == DHCPv4Scope.NotFound) { return(false); } if (request.ParentScopeId.HasValue == true) { if (_rootScope.GetScopeById(request.ParentScopeId.Value) == DHCPv4Scope.NotFound) { return(false); } } Boolean moveResult = _rootScope.UpdateParent(request.ScopeId, request.ParentScopeId); if (moveResult == true) { Boolean result = await _store.Save(_rootScope); return(result); } return(false); }
protected static DHCPv4Lease CheckLease( Int32 index, Int32 expectedAmount, IPv4Address expectedAdress, Guid scopeId, DHCPv4RootScope rootScope, DateTime expectedCreationData, Boolean checkExpires = true, Byte[] uniqueIdentifier = null, Boolean shouldBePending = true) { DHCPv4Scope scope = rootScope.GetScopeById(scopeId); var leases = scope.Leases.GetAllLeases(); Assert.Equal(expectedAmount, leases.Count()); DHCPv4Lease lease = leases.ElementAt(index); Assert.NotNull(lease); Assert.Equal(expectedAdress, lease.Address); if (checkExpires == true) { Int32 expiresInMinutes = (Int32)(lease.End - DateTime.UtcNow).TotalMinutes; Assert.True(expiresInMinutes >= 60 * 24 - 4 && expiresInMinutes <= 60 * 24); } Assert.True((expectedCreationData - lease.Start).TotalMinutes < 2); Assert.Equal(shouldBePending, lease.IsPending()); if (uniqueIdentifier == null) { Assert.Empty(lease.UniqueIdentifier); } else { Assert.NotNull(lease.UniqueIdentifier); Assert.Equal(uniqueIdentifier, lease.UniqueIdentifier); } return(lease); }
public async Task <Boolean> Handle(UpdateDHCPv4ScopeCommand request, CancellationToken cancellationToken) { _logger.LogDebug("Handle started"); var scope = _rootScope.GetScopeById(request.ScopeId); if (scope == DHCPv4Scope.NotFound) { return(false); } Guid?parentId = scope.HasParentScope() == false ? new Guid?() : scope.ParentScope.Id; var properties = GetScopeProperties(request); var addressProperties = GetScopeAddressProperties(request); if (request.Name != scope.Name) { _rootScope.UpdateScopeName(request.ScopeId, ScopeName.FromString(request.Name)); } if (request.Description != scope.Description) { _rootScope.UpdateScopeDescription(request.ScopeId, ScopeDescription.FromString(request.Description)); } if (request.ParentId != parentId) { _rootScope.UpdateParent(request.ScopeId, request.ParentId); } _rootScope.UpdateScopeResolver(request.ScopeId, GetResolverInformation(request)); if (addressProperties != scope.AddressRelatedProperties) { _rootScope.UpdateAddressProperties(request.ScopeId, addressProperties); } if (properties != scope.Properties) { _rootScope.UpdateScopeProperties(request.ScopeId, properties); } Boolean result = await _store.Save(_rootScope); if (result == true) { var triggers = _rootScope.GetTriggers(); if (triggers.Any() == true) { await _serviceBus.Publish(new NewTriggerHappendMessage(triggers)); _rootScope.ClearTriggers(); } } return(result); }
public async Task <IActionResult> GetHandledDHCPv4PacketByScopeId([FromRoute(Name = "id")] Guid scopeId, [Range(1, 1000)][FromQuery] Int32 amount = 100) { if (_rootScope.GetScopeById(scopeId) == DHCPv4Scope.NotFound) { return(NotFound("scope not found")); } var entries = await _storage.GetHandledDHCPv4PacketByScopeId(scopeId, amount); return(base.Ok(entries)); }
public async Task <Boolean> Handle(DeleteDHCPv4ScopeCommand request, CancellationToken cancellationToken) { if (rootScope.GetScopeById(request.ScopeId) == DHCPv4Scope.NotFound) { logger.LogInformation("unable to delete the scope {scopeId}. Scope not found"); return(false); } rootScope.DeleteScope(request.ScopeId, request.IncludeChildren); Boolean result = await storageEngine.Save(rootScope); if (result == false) { logger.LogError("unable to delete the scope {scopeId}. Saving changes failed", request.ScopeId); } return(result); }
protected static void CheckLeaseCreatedEvent( Int32 index, byte[] clientMacAdress, Guid scopeId, DHCPv4RootScope rootScope, IPv4Address expectedAdress, DHCPv4Lease lease, Byte[] uniqueIdentifier = null, Boolean checkRenewTimes = true ) { IEnumerable <DomainEvent> changes = rootScope.GetChanges(); Assert.NotNull(changes); Assert.IsAssignableFrom <DHCPv4LeaseCreatedEvent>(changes.ElementAt(index)); DHCPv4LeaseCreatedEvent createdEvent = (DHCPv4LeaseCreatedEvent)changes.ElementAt(index); Assert.NotNull(createdEvent); Assert.Equal(scopeId, createdEvent.ScopeId); Assert.Equal(expectedAdress, createdEvent.Address); var clientIdentifier = DHCPv4ClientIdentifier.FromOptionData(createdEvent.ClientIdenfier); Assert.Equal(clientMacAdress, clientIdentifier.HwAddress); Assert.Equal(lease.Id, createdEvent.EntityId); if (uniqueIdentifier == null) { Assert.Null(createdEvent.UniqueIdentifier); } else { Assert.Equal(uniqueIdentifier, createdEvent.UniqueIdentifier); } Assert.Equal(lease.Start, createdEvent.StartedAt); Assert.Equal(lease.End, createdEvent.ValidUntil); var addressProperties = rootScope.GetScopeById(scopeId).AddressRelatedProperties; if (checkRenewTimes == true) { Assert.Equal(addressProperties.RenewalTime.Value, createdEvent.RenewalTime); Assert.Equal(addressProperties.PreferredLifetime.Value, createdEvent.PreferredLifetime); } }
public void DHCPv4Scope_GetChildScopes() { Random random = new Random(); GenerateScopeTree(random, out Dictionary <Guid, List <Guid> > directChildRelations, out Dictionary <Guid, List <Guid> > allChildRelations, out List <DomainEvent> events); DHCPv4RootScope rootScope = GetRootScope(); rootScope.Load(events); foreach (var item in directChildRelations) { DHCPv4Scope scope = rootScope.GetScopeById(item.Key); IEnumerable <DHCPv4Scope> childScopes = scope.GetChildScopes(); List <Guid> childScopesId = childScopes.Select(x => x.Id).ToList(); Assert.Equal(item.Value.OrderBy(x => x), childScopesId.OrderBy(x => x)); } }
public void DHCPv4Scope_GetChildIds() { Random random = new Random(); GenerateScopeTree(random, out Dictionary <Guid, List <Guid> > directChildRelations, out Dictionary <Guid, List <Guid> > allChildRelations, out List <DomainEvent> events); DHCPv4RootScope rootScope = GetRootScope(); rootScope.Load(events); foreach (var item in directChildRelations) { DHCPv4Scope scope = rootScope.GetScopeById(item.Key); IEnumerable <Guid> actualDirectIds = scope.GetChildIds(true); Assert.Equal(item.Value.OrderBy(x => x), actualDirectIds.OrderBy(x => x)); IEnumerable <Guid> allChildIds = scope.GetChildIds(false); Assert.Equal(allChildRelations[item.Key].OrderBy(x => x), allChildIds.OrderBy(x => x)); } }
protected void CheckPacketOptions(Guid scopeId, DHCPv4RootScope rootScope, DHCPv4Packet result) { var scope = rootScope.GetScopeById(scopeId); if (scope.Properties != null) { foreach (var item in scope.Properties.Properties) { } } var subnetOption = result.GetOptionByIdentifier((Byte)DHCPv4OptionTypes.SubnetMask) as DHCPv4PacketAddressOption; if (result.YourIPAdress == IPv4Address.Empty) { Assert.Null(subnetOption); } else { Assert.NotNull(subnetOption); Assert.True(ByteHelper.AreEqual(subnetOption.Address.GetBytes(), scope.AddressRelatedProperties.Mask.GetBytes())); } }
public IActionResult GetLeasesByScope([FromRoute(Name = "id")] Guid scopeId, [FromQuery(Name = "includeChildren")] Boolean includeChildren = false) { _logger.LogDebug("GetLeasesByScope"); var scope = _rootScope.GetScopeById(scopeId); if (scope == DHCPv4Scope.NotFound) { return(NotFound($"no scope with id {scopeId} found")); } List <DHCPv4LeaseOverview> result; if (includeChildren == false) { result = scope.Leases.GetAllLeases().Select(x => GetLeaseOverview(x, scope)).ToList(); } else { result = new List <DHCPv4LeaseOverview>(); GetAllLesesRecursivly(result, scope); } return(base.Ok(result.OrderBy(x => x.State).ThenBy(x => x.Address).ToList())); }
public async Task Handle_WithChildren(Boolean requestedToDeleteChildrenAsWell) { Random random = new Random(); Guid grantParentId = random.NextGuid(); Guid parentId = random.NextGuid(); Guid childId = random.NextGuid(); String resolverName = random.GetAlphanumericString(); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(); scopeResolverMock.Setup(x => x.InitializeResolver(It.Is <CreateScopeResolverInformation>(y => y.Typename == resolverName ))).Returns(Mock.Of <IScopeResolver <DHCPv4Packet, IPv4Address> >()).Verifiable(); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv4RootScope> >()); DHCPv4RootScope rootScope = new DHCPv4RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); rootScope.Load(new[] { new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Id = grantParentId, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.1"), IPv4Address.FromString("192.168.0.20")), } }, new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Id = parentId, ParentId = grantParentId, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.5"), IPv4Address.FromString("192.168.0.8")), } }, new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Id = childId, ParentId = parentId, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, AddressProperties = new DHCPv4ScopeAddressProperties(IPv4Address.FromString("192.168.0.7"), IPv4Address.FromString("192.168.0.7")), } }, }); Mock <IDHCPv4StorageEngine> storageMock = new Mock <IDHCPv4StorageEngine>(MockBehavior.Strict); storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable(); var command = new DeleteDHCPv4ScopeCommand(parentId, requestedToDeleteChildrenAsWell); var handler = new DeleteDHCPv4ScopeCommandHandler(storageMock.Object, rootScope, Mock.Of <ILogger <DeleteDHCPv4ScopeCommandHandler> >()); Boolean result = await handler.Handle(command, CancellationToken.None); Assert.True(result); var changes = rootScope.GetChanges(); if (requestedToDeleteChildrenAsWell == true) { Assert.Null(rootScope.GetScopeById(childId)); Assert.Equal(2, changes.Count()); var firstEvent = changes.ElementAt(0) as DHCPv4ScopeDeletedEvent; Assert.Equal(childId, firstEvent.EntityId); var secondEvent = changes.ElementAt(1) as DHCPv4ScopeDeletedEvent; Assert.Equal(parentId, secondEvent.EntityId); } else { Assert.Single(changes); } Assert.Null(rootScope.GetScopeById(parentId)); Assert.NotNull(rootScope.GetScopeById(grantParentId)); storageMock.Verify(); }
public void DHCPv4Scope_AddressPropertiesInherientce() { Random random = new Random(); for (int i = 0; i < 100; i++) { IPv4Address grantParentStart = random.GetIPv4Address(); IPv4Address grantParentEnd = random.GetIPv4AddressGreaterThan(grantParentStart); List <IPv4Address> grantParentExcludedAddresses = random.GetIPv4AddressesBetween(grantParentStart, grantParentEnd); TimeSpan grantParentValidLifeTime = TimeSpan.FromMinutes(random.Next()); TimeSpan grantParentPrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); TimeSpan grantParentRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); Boolean grantParentReuseAddressIfPossible = random.NextBoolean(); DHCPv4ScopeAddressProperties.AddressAllocationStrategies grantParentAllocationStrategy = DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Next; Boolean grantParentSupportDirectUnicast = random.NextBoolean(); Boolean grantParentAcceptDecline = random.NextBoolean(); Boolean grantParentInformsAreAllowd = random.NextBoolean(); Byte grantParentSubnetMask = (Byte)random.Next(18, 25); DHCPv4ScopeAddressProperties grantParentProperties = new DHCPv4ScopeAddressProperties( grantParentStart, grantParentEnd, grantParentExcludedAddresses, grantParentRenewalTimePrefferedValidLifeTime, grantParentPrefferedValidLifeTime, grantParentValidLifeTime, grantParentSubnetMask, grantParentReuseAddressIfPossible, grantParentAllocationStrategy, grantParentInformsAreAllowd, grantParentAcceptDecline, grantParentInformsAreAllowd); IPv4Address parentStart = random.GetIPv4Address(); IPv4Address parentEnd = random.GetIPv4AddressGreaterThan(parentStart); List <IPv4Address> parentExcludedAddresses = random.GetIPv4AddressesBetween(parentStart, parentEnd); TimeSpan?parentValidLifeTime = null; TimeSpan?parentPrefferedValidLifeTime = null; TimeSpan?parentRenewalTimePrefferedValidLifeTime = null; Byte?parentSubnetMask = null; Boolean?parentReuseAddressIfPossible = null; DHCPv4ScopeAddressProperties.AddressAllocationStrategies?parentAllocationStrategy = null; Boolean?parentSupportDirectUnicast = null; Boolean?parentAcceptDecline = null; Boolean?parentInformsAreAllowd = null; if (random.NextBoolean() == true) { parentValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { parentPrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { parentRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { parentSubnetMask = (Byte)random.Next(18, 25); } if (random.NextBoolean() == true) { parentReuseAddressIfPossible = random.NextBoolean(); } if (random.NextBoolean() == true) { parentAllocationStrategy = DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Random; } if (random.NextBoolean() == true) { parentSupportDirectUnicast = random.NextBoolean(); } if (random.NextBoolean() == true) { parentAcceptDecline = random.NextBoolean(); } if (random.NextBoolean() == true) { parentInformsAreAllowd = random.NextBoolean(); } DHCPv4ScopeAddressProperties parentProperties = new DHCPv4ScopeAddressProperties( parentStart, parentEnd, parentExcludedAddresses, parentRenewalTimePrefferedValidLifeTime, parentPrefferedValidLifeTime, parentValidLifeTime, parentSubnetMask, parentReuseAddressIfPossible, parentAllocationStrategy, parentInformsAreAllowd, parentAcceptDecline, parentInformsAreAllowd); IPv4Address childStart = random.GetIPv4Address(); IPv4Address childEnd = random.GetIPv4AddressGreaterThan(childStart); List <IPv4Address> childExcludedAddresses = random.GetIPv4AddressesBetween(childStart, childEnd); TimeSpan?childValidLifeTime = null; TimeSpan?childPrefferedValidLifeTime = null; TimeSpan?childRenewalTimePrefferedValidLifeTime = null; Byte?childSubnetMask = null; Boolean?childReuseAddressIfPossible = null; DHCPv4ScopeAddressProperties.AddressAllocationStrategies?childAllocationStrategy = null; Boolean?childSupportDirectUnicast = random.NextDouble() > 0.5; Boolean?childAcceptDecline = random.NextDouble() > 0.5; Boolean?childInformsAreAllowd = random.NextDouble() > 0.5; if (random.NextBoolean() == true) { childValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { childPrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { childRenewalTimePrefferedValidLifeTime = TimeSpan.FromMinutes(random.Next()); } if (random.NextBoolean() == true) { childSubnetMask = (Byte)random.Next(18, 25); } if (random.NextBoolean() == true) { childReuseAddressIfPossible = random.NextBoolean(); } if (random.NextBoolean() == true) { childAllocationStrategy = DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Random; } if (random.NextBoolean() == true) { childSupportDirectUnicast = random.NextBoolean(); } if (random.NextBoolean() == true) { childAcceptDecline = random.NextBoolean(); } if (random.NextBoolean() == true) { childInformsAreAllowd = random.NextBoolean(); } DHCPv4ScopeAddressProperties childProperties = new DHCPv4ScopeAddressProperties( childStart, childEnd, childExcludedAddresses, childRenewalTimePrefferedValidLifeTime, childPrefferedValidLifeTime, childValidLifeTime, childSubnetMask, childReuseAddressIfPossible, childAllocationStrategy, childSupportDirectUnicast, childAcceptDecline, childInformsAreAllowd); Guid grantParentId = Guid.NewGuid(); Guid parentId = Guid.NewGuid(); Guid childId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = grantParentId, AddressProperties = grantParentProperties, }), new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = parentId, ParentId = grantParentId, AddressProperties = parentProperties, }), new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = childId, ParentId = parentId, AddressProperties = childProperties, }), }; DHCPv4RootScope rootScope = GetRootScope(); rootScope.Load(events); DHCPv4Scope scope = rootScope.GetScopeById(childId); DHCPv4ScopeAddressProperties actualProperties = scope.GetAddressProperties(); DHCPv4ScopeAddressProperties expectedProperties = new DHCPv4ScopeAddressProperties( childStart, childEnd, grantParentExcludedAddresses.Union(parentExcludedAddresses).Union(childExcludedAddresses).Where(x => x.IsBetween(childStart, childEnd)), childRenewalTimePrefferedValidLifeTime.HasValue == true ? childRenewalTimePrefferedValidLifeTime.Value : (parentRenewalTimePrefferedValidLifeTime.HasValue == true ? parentRenewalTimePrefferedValidLifeTime.Value : grantParentRenewalTimePrefferedValidLifeTime), childPrefferedValidLifeTime.HasValue == true ? childPrefferedValidLifeTime.Value : (parentPrefferedValidLifeTime.HasValue == true ? parentPrefferedValidLifeTime.Value : grantParentPrefferedValidLifeTime), childValidLifeTime.HasValue == true ? childValidLifeTime.Value : (parentValidLifeTime.HasValue == true ? parentValidLifeTime.Value : grantParentValidLifeTime), childSubnetMask.HasValue == true ? childSubnetMask.Value : (parentSubnetMask.HasValue == true ? parentSubnetMask.Value : grantParentSubnetMask), childReuseAddressIfPossible.HasValue == true ? childReuseAddressIfPossible.Value : (parentReuseAddressIfPossible.HasValue == true ? parentReuseAddressIfPossible.Value : grantParentReuseAddressIfPossible), childAllocationStrategy.HasValue == true ? childAllocationStrategy.Value : (parentAllocationStrategy.HasValue == true ? parentAllocationStrategy.Value : grantParentAllocationStrategy), childSupportDirectUnicast.HasValue == true ? childSupportDirectUnicast.Value : (parentSupportDirectUnicast.HasValue == true ? parentSupportDirectUnicast.Value : grantParentSupportDirectUnicast), childAcceptDecline.HasValue == true ? childAcceptDecline.Value : (parentAcceptDecline.HasValue == true ? parentAcceptDecline.Value : grantParentAcceptDecline), childInformsAreAllowd.HasValue == true ? childInformsAreAllowd.Value : (parentInformsAreAllowd.HasValue == true ? parentInformsAreAllowd.Value : grantParentInformsAreAllowd) ); Assert.Equal(expectedProperties, actualProperties); } }
public void HandleRelease_LeaseExists_AddressIsActive() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10"); IPv4HeaderInformation headerInformation = new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1")); Byte[] clientMacAdress = random.NextBytes(6); DHCPv4Packet requestPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Unicast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release) ); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.1"), IPv4Address.FromString("192.168.178.255"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.1") }, leaseTime: TimeSpan.FromDays(1) ), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(clientMacAdress).GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, new DHCPv4LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, }, }); DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); DHCPv4Packet result = rootScope.HandleRelease(requestPacket); Assert.Equal(DHCPv4Packet.Empty, result); CheckIfLeaseIsRelease(lease); CheckEventAmount(2, rootScope); CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId); CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope); }
public void HandleRelease_LeaseExists_AddressIsActive_NotSentDiscover() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10"); IPv4HeaderInformation headerInformation = new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1")); Byte[] clientMacAdress = random.NextBytes(6); DHCPv4Packet requestPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Unicast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release) ); DHCPv4Packet discoverPacket = new DHCPv4Packet( headerInformation, clientMacAdress, (UInt32)random.Next(), IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Broadcast, new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover), new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("random test client")) ); Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); resolverMock.Setup(x => x.PacketMeetsCondition(discoverPacket)).Returns(true); resolverMock.SetupGet(x => x.HasUniqueIdentifier).Returns(false); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.1"), IPv4Address.FromString("192.168.178.255"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.1") }, leaseTime: TimeSpan.FromDays(1), renewalTime: TimeSpan.FromHours(12), preferredLifetime: TimeSpan.FromHours(18), reuseAddressIfPossible: true, acceptDecline: true, addressAllocationStrategy: DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Next, supportDirectUnicast: true, maskLength: 24 ), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromIdentifierValue("random test client").GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, new DHCPv4LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, }, }); DHCPv4Lease existingLease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); DHCPv4Packet releaseResult = rootScope.HandleRelease(requestPacket); Assert.Equal(DHCPv4Packet.Empty, releaseResult); CheckIfLeaseIsRelease(existingLease); CheckEventAmount(2, rootScope); CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId); CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope); DHCPv4Packet discoveryResult = rootScope.HandleDiscover(discoverPacket); IPv4Address newAssignedAddress = IPv4Address.FromString("192.168.178.2"); Assert.Equal(newAssignedAddress, discoveryResult.YourIPAdress); }
public void HandleDecline_AcceptDecline_RequesAddressExits_LeaseExists_LeaseIsPending_AddressIsNotSuspended() { Random random = new Random(); IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.3"); DHCPv4Packet requestPacket = GetDeclinePacket(random, leasedAddress); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); var resolverInformations = new CreateScopeResolverInformation { Typename = nameof(DHCPv4RelayAgentSubnetResolver), }; Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); DateTime leaseCreatedAt = DateTime.UtcNow.AddHours(-1); DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock); rootScope.Load(new List <DomainEvent> { new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent( new DHCPv4ScopeCreateInstruction { AddressProperties = new DHCPv4ScopeAddressProperties( IPv4Address.FromString("192.168.178.0"), IPv4Address.FromString("192.168.178.100"), new List <IPv4Address> { IPv4Address.FromString("192.168.178.0") }, leaseTime: TimeSpan.FromDays(1), acceptDecline: true), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv4LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdenfier = DHCPv4ClientIdentifier.FromHwAddress(requestPacket.ClientHardwareAddress).GetBytes(), ScopeId = scopeId, UniqueIdentifier = null, StartedAt = leaseCreatedAt, ValidUntil = DateTime.UtcNow.AddDays(1), }, }); DHCPv4Packet result = rootScope.HandleDecline(requestPacket); Assert.Equal(DHCPv4Packet.Empty, result); DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId); Assert.Equal(LeaseStates.Suspended, lease.State); CheckEventAmount(2, rootScope); CheckDeclineEvent(0, leaseId, leasedAddress, scopeId, rootScope); CheckDeclinedEvent(1, DeclineErros.NoError, requestPacket, rootScope, scopeId); }
public void DHCPv4Scope_ScopePropertiesInherientce() { Random random = new Random(); Byte onylGrandParentOptionIdentifier = 47; Byte onlyParentOptionIdentifier = 55; Byte onlyChildOptionIdentifier = 90; Byte overridenByParentOptionIdentifier = 100; Byte overridenByChildOptionIdentifier = 110; Dictionary <Byte, IPv4Address> inputs = new Dictionary <byte, IPv4Address> { { onylGrandParentOptionIdentifier, random.GetIPv4Address() }, { onlyParentOptionIdentifier, random.GetIPv4Address() }, { onlyChildOptionIdentifier, random.GetIPv4Address() }, { overridenByParentOptionIdentifier, random.GetIPv4Address() }, { overridenByChildOptionIdentifier, random.GetIPv4Address() }, }; DHCPv4ScopeProperties grantParentProperties = new DHCPv4ScopeProperties( new DHCPv4AddressScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]), new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, random.GetIPv4Address()), new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, random.GetIPv4Address()) ); DHCPv4ScopeProperties parentProperties = new DHCPv4ScopeProperties( new DHCPv4AddressScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]), new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier]) ); DHCPv4ScopeProperties childProperties = new DHCPv4ScopeProperties( new DHCPv4AddressScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]), new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier]) ); DHCPv4ScopeProperties expectedProperties = new DHCPv4ScopeProperties( new DHCPv4AddressScopeProperty(onylGrandParentOptionIdentifier, inputs[onylGrandParentOptionIdentifier]), new DHCPv4AddressScopeProperty(onlyParentOptionIdentifier, inputs[onlyParentOptionIdentifier]), new DHCPv4AddressScopeProperty(onlyChildOptionIdentifier, inputs[onlyChildOptionIdentifier]), new DHCPv4AddressScopeProperty(overridenByParentOptionIdentifier, inputs[overridenByParentOptionIdentifier]), new DHCPv4AddressScopeProperty(overridenByChildOptionIdentifier, inputs[overridenByChildOptionIdentifier]) ); Guid grantParentId = Guid.NewGuid(); Guid parentId = Guid.NewGuid(); Guid childId = Guid.NewGuid(); List <DomainEvent> events = new List <DomainEvent> { new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = grantParentId, ScopeProperties = grantParentProperties, }), new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = parentId, ParentId = grantParentId, ScopeProperties = parentProperties, }), new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction { Id = childId, ParentId = parentId, ScopeProperties = childProperties, }), }; DHCPv4RootScope rootScope = GetRootScope(); rootScope.Load(events); DHCPv4Scope scope = rootScope.GetScopeById(childId); DHCPv4ScopeProperties actualProperties = scope.GetScopeProperties(); Assert.Equal(expectedProperties, actualProperties); }
public async Task Handle_WithParentId(Boolean storeResult) { Random random = new (); Guid scopeId = random.NextGuid(); Guid parentId = random.NextGuid(); String name = random.GetAlphanumericString(); String description = random.GetAlphanumericString(); String resolverName = random.GetAlphanumericString(); Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict); Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(); 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 <DHCPv4RootScope> >()); DHCPv4RootScope rootScope = new DHCPv4RootScope(random.NextGuid(), scopeResolverMock.Object, factoryMock.Object); rootScope.Load(new DomainEvent[] { new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Name = random.GetAlphanumericString(), Description = random.GetAlphanumericString(), Id = parentId, ParentId = null, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, ScopeProperties = new DHCPv4ScopeProperties(), AddressProperties = DHCPv4ScopeAddressProperties.Empty, } }, new DHCPv4ScopeAddedEvent { Instructions = new DHCPv4ScopeCreateInstruction { Name = random.GetAlphanumericString(), Description = random.GetAlphanumericString(), Id = scopeId, ParentId = null, ResolverInformation = new CreateScopeResolverInformation { Typename = resolverName, }, ScopeProperties = new DHCPv4ScopeProperties(), AddressProperties = DHCPv4ScopeAddressProperties.Empty, } }, }); Mock <IDHCPv4StorageEngine> storageMock = new Mock <IDHCPv4StorageEngine>(MockBehavior.Strict); storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(storeResult).Verifiable(); var command = new UpdateDHCPv4ScopeParentCommand(scopeId, parentId); var handler = new UpdateDHCPv4ScopeParentCommandHandler(storageMock.Object, rootScope, Mock.Of <ILogger <UpdateDHCPv4ScopeParentCommandHandler> >()); Boolean result = await handler.Handle(command, CancellationToken.None); Assert.Equal(storeResult, result); var parentScope = rootScope.GetScopeById(parentId); var childIds = parentScope.GetChildIds(true); Assert.Single(childIds); Assert.Equal(scopeId, childIds.First()); scopeResolverMock.Verify(); storageMock.Verify(); }