Ejemplo n.º 1
0
        public async Task <DHCPv6RootScope> GetRootScope()
        {
            DHCPv6RootScope rootScope = new DHCPv6RootScope(_rootScopeid, Provider.GetRequiredService <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(), Provider.GetRequiredService <ILoggerFactory>());

            PseudoDHCPv6RootScope pseudoRootScope = new PseudoDHCPv6RootScope();
            await EventStore.HydrateAggragate(pseudoRootScope);

            List <DomainEvent> eventsToApply = new();

            foreach (var scopeId in pseudoRootScope.ScopeIds)
            {
                var events = await EventStore.GetEvents <PseudoDHCPv6Scope>(scopeId, 100);

                eventsToApply.AddRange(events);
            }

            foreach (var leaseId in pseudoRootScope.LeaseIds)
            {
                var events = await EventStore.GetEvents <PseudoDHCPv6Lease>(leaseId, 100);

                eventsToApply.AddRange(events);
            }

            rootScope.Load(eventsToApply.OrderBy(x => x.Timestamp));
            return(rootScope);
        }
Ejemplo n.º 2
0
        protected static void CheckLeaseRenewdEvent(
            Guid scopeId,
            DHCPv6RootScope rootScope, DHCPv6Lease lease, Boolean expectReset, Boolean expectedPrefixReset)
        {
            IEnumerable <DomainEvent> changes = rootScope.GetChanges();

            Assert.NotNull(changes);
            Assert.Equal(2, changes.Count());

            Assert.IsAssignableFrom <DHCPv6LeaseRenewedEvent>(changes.First());

            DHCPv6LeaseRenewedEvent createdEvent = (DHCPv6LeaseRenewedEvent)changes.First();

            Assert.NotNull(createdEvent);

            Assert.Equal(scopeId, createdEvent.ScopeId);
            Assert.NotEqual(Guid.Empty, lease.Id);

            Assert.Equal(lease.Id, createdEvent.EntityId);
            Assert.Equal(expectReset, createdEvent.Reset);

            Assert.Equal(expectedPrefixReset, createdEvent.ResetPrefix);

            Assert.Equal(lease.End, createdEvent.End);

            var addressProperties = rootScope.GetScopeById(scopeId).AddressRelatedProperties;

            Assert.True(Math.Abs(((addressProperties.T1.Value * addressProperties.ValidLeaseTime.Value) - createdEvent.RenewSpan).TotalSeconds) < 20);
            Assert.True(Math.Abs(((addressProperties.T2.Value * addressProperties.ValidLeaseTime.Value) - createdEvent.ReboundSpan).TotalSeconds) < 20);
        }
Ejemplo n.º 3
0
        public async Task GetIncomingDHCPv6PacketTypes()
        {
            Random random = new Random();

            DHCPv6RootScope rootScope = GetRootScope();

            var      response = new Dictionary <DateTime, IDictionary <DHCPv6PacketTypes, Int32> >();
            DateTime start    = DateTime.UtcNow.AddHours(-random.Next(5, 10));
            DateTime end      = DateTime.UtcNow.AddHours(-random.Next(1, 2));
            GroupStatisticsResultBy groupBy = random.GetEnumValue <GroupStatisticsResultBy>();

            Mock <IDHCPv6ReadStore> readStoreMock = new Mock <IDHCPv6ReadStore>(MockBehavior.Strict);

            readStoreMock.Setup(x => x.GetIncomingDHCPv6PacketTypes(start, end, groupBy)).ReturnsAsync(response).Verifiable();

            var controller   = new DHCPv6StatisticsController(rootScope, readStoreMock.Object);
            var actionResult = await controller.GetIncomingDHCPv6PacketTypes(new GroupedTimeSeriesFilterRequest
            {
                Start    = start,
                End      = end,
                GroupbBy = groupBy,
            });

            var result = actionResult.EnsureOkObjectResult <IDictionary <DateTime, IDictionary <DHCPv6PacketTypes, Int32> > >(true);

            Assert.NotNull(result);
            Assert.Equal(response, result);

            readStoreMock.Verify();
        }
Ejemplo n.º 4
0
        public async Task GetHandledDHCPv6PacketByScopeId()
        {
            Random random = new Random();

            Guid  scopeId = random.NextGuid();
            Int32 amount  = random.Next(10, 250);
            List <DHCPv6PacketHandledEntry> response = new List <DHCPv6PacketHandledEntry>();

            DHCPv6RootScope rootScope = GetRootScope();

            rootScope.Load(new[] { new DHCPv6ScopeAddedEvent {
                                       Instructions = new DHCPv6ScopeCreateInstruction
                                       {
                                           Id = scopeId,
                                       }
                                   } });

            Mock <IDHCPv6ReadStore> readStoreMock = new Mock <IDHCPv6ReadStore>(MockBehavior.Strict);

            readStoreMock.Setup(x => x.GetHandledDHCPv6PacketByScopeId(scopeId, amount)).ReturnsAsync(response).Verifiable();

            var controller   = new DHCPv6StatisticsController(rootScope, readStoreMock.Object);
            var actionResult = await controller.GetHandledDHCPv6PacketByScopeId(scopeId, amount);

            var result = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6PacketHandledEntry> >(true);

            Assert.NotNull(result);
            Assert.Equal(response, result);

            readStoreMock.Verify();
        }
Ejemplo n.º 5
0
        public async Task GetErrorCodesPerDHCPV6RequestType()
        {
            Random          random    = new Random();
            DHCPv6RootScope rootScope = GetRootScope();

            var               response   = new Dictionary <Int32, Int32>();
            DateTime          start      = DateTime.UtcNow.AddHours(-random.Next(5, 10));
            DateTime          end        = DateTime.UtcNow.AddHours(-random.Next(1, 2));
            DHCPv6PacketTypes packetType = random.GetEnumValue <DHCPv6PacketTypes>();

            Mock <IDHCPv6ReadStore> readStoreMock = new Mock <IDHCPv6ReadStore>(MockBehavior.Strict);

            readStoreMock.Setup(x => x.GetErrorCodesPerDHCPV6RequestType(start, end, packetType)).ReturnsAsync(response).Verifiable();

            var controller   = new DHCPv6StatisticsController(rootScope, readStoreMock.Object);
            var actionResult = await controller.GetErrorCodesPerDHCPV6RequestType(new DHCPv6PacketTypeBasedTimeSeriesFilterRequest
            {
                Start      = start,
                End        = end,
                PacketType = packetType,
            });

            var result = actionResult.EnsureOkObjectResult <IDictionary <Int32, Int32> >(true);

            Assert.NotNull(result);
            Assert.Equal(response, result);

            readStoreMock.Verify();
        }
Ejemplo n.º 6
0
        public void GetScopesAsList()
        {
            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.GetScopesAsList();
            var result       = actionResult.EnsureOkObjectResult <IEnumerable <DHCPv6ScopeItem> >(true);

            Assert.Equal(events.Count, result.Count());
            for (int i = 0; i < events.Count; i++)
            {
                var scope  = result.ElementAt(i);
                var @event = (DHCPv6ScopeAddedEvent)events[i];
                Assert.Equal(@event.Instructions.Name, scope.Name);
                Assert.Equal(@event.Instructions.Id, scope.Id);
                Assert.Equal(@event.Instructions.AddressProperties.Start.ToString(), scope.StartAddress);
                Assert.Equal(@event.Instructions.AddressProperties.End.ToString(), scope.EndAddress);
            }
        }
Ejemplo n.º 7
0
 public DHCPv6StatisticsController(
     DHCPv6RootScope rootScope,
     IDHCPv6ReadStore storage)
 {
     _rootScope = rootScope ?? throw new ArgumentNullException(nameof(rootScope));
     _storage   = storage ?? throw new ArgumentNullException(nameof(storage));
 }
Ejemplo n.º 8
0
        public void HandleRequest_ScopeNotFound(Boolean withPrefixDelegation)
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(20, 60);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = Array.Empty <DHCPv6PacketOption>();
            if (withPrefixDelegation == true)
            {
                options = new DHCPv6PacketOption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                        new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
                    })
                };
            }

            var packet = GetRequestPacket(random, out _, out DUID _, out UInt32 _, true, options);

            GetMockupResolver(DHCPv6Packet.Empty, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            DHCPv6Packet result = rootScope.HandleRequest(packet, GetServerPropertiesResolver());

            Assert.Equal(DHCPv6Packet.Empty, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, null, DHCPv6RequestHandledEvent.RequestErrors.ScopeNotFound);
        }
Ejemplo n.º 9
0
        public async Task HandlePacket_Solicit()
        {
            Random random = new Random();

            DHCPv6RootScope rootScope = GetRootScope(random, out DHCPv6Packet request);

            Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict);

            storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable();

            Mock <IDHCPv6ServerPropertiesResolver> propertyResolver = new Mock <IDHCPv6ServerPropertiesResolver>(MockBehavior.Strict);

            propertyResolver.Setup(x => x.GetServerDuid()).Returns(new UUIDDUID(Guid.NewGuid())).Verifiable();

            Mock <IServiceBus> serviceBusMock = new Mock <IServiceBus>();

            serviceBusMock.Setup(x => x.Publish(It.Is <NewTriggerHappendMessage>(y =>
                                                                                 y.Triggers.Count() == 1))).Returns(Task.FromResult(true));

            DHCPv6LeaseEngine engine = new DHCPv6LeaseEngine(
                storageMock.Object,
                rootScope,
                propertyResolver.Object,
                serviceBusMock.Object,
                Mock.Of <ILogger <DHCPv6LeaseEngine> >());

            var response = await engine.HandlePacket(request);

            Assert.NotEqual(DHCPv6Packet.Empty, response);

            storageMock.Verify();
            propertyResolver.Verify();
            serviceBusMock.Verify();
        }
Ejemplo n.º 10
0
        public void HandleRequest_OnlyPrefix_LeaseFound_LeaseIsPending()
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(20, 60);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            var packet = GetRequestPacket(random, out IPv6Address leasedAddress, out DUID clientDuid, out UInt32 iaId, false, new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
            }));

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    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),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = clientDuid,
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = DateTime.UtcNow,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = true,
                    PrefixLength                  = prefixLength,
                    IdentityAssocationIdForPrefix = prefixId,
                    DelegatedNetworkAddress       = prefixNetworkAddress,
                },
            });

            DHCPv6Packet result = rootScope.HandleRequest(packet, GetServerPropertiesResolver());

            CheckErrorPacket(packet, leasedAddress, 0, result, DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId), DHCPv6StatusCodes.NoAddrsAvail);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6RequestHandledEvent.RequestErrors.LeasePendingButOnlyPrefixRequested);
        }
Ejemplo n.º 11
0
 public CreateDHCPv6ScopeCommandHandler(
     IDHCPv6StorageEngine store, DHCPv6RootScope rootScope,
     ILogger <CreateDHCPv6ScopeCommandHandler> logger)
 {
     _store     = store;
     _rootScope = rootScope;
     _logger    = logger;
 }
Ejemplo n.º 12
0
 public DHCPv6ScopeController(
     IMediator mediator,
     IScopeResolverManager <DHCPv6Packet, IPv6Address> resolverManager,
     DHCPv6RootScope rootScope)
 {
     this._mediator        = mediator;
     this._resolverManager = resolverManager;
     _rootScope            = rootScope;
 }
Ejemplo n.º 13
0
 public DHCPv6ScopeIdNotificationCondition(
     DHCPv6RootScope rootScope,
     ISerializer serializer,
     ILogger <DHCPv6ScopeIdNotificationCondition> logger)
 {
     this._rootScope = rootScope;
     _serializer     = serializer;
     this._logger    = logger;
 }
Ejemplo n.º 14
0
 public UpdateDHCPv6ScopeParentCommandHandler(
     IDHCPv6StorageEngine store,
     DHCPv6RootScope rootScope,
     ILogger <UpdateDHCPv6ScopeParentCommandHandler> logger)
 {
     _store     = store;
     _rootScope = rootScope;
     _logger    = logger;
 }
Ejemplo n.º 15
0
        public async Task UpdateScope(Boolean mediatorResultShouldBeSuccessful)
        {
            Random random = new Random();

            Guid   id          = random.NextGuid();
            String name        = random.GetAlphanumericString();
            String description = random.GetAlphanumericString();
            Guid?  parentId    = random.NextBoolean() == true?random.NextGuid() : new Guid?();

            var addressProperties = new DHCPv6ScopeAddressPropertyReqest();
            var resolverInfo      = new CreateScopeResolverRequest
            {
                Typename            = random.GetAlphanumericString(),
                PropertiesAndValues = new Dictionary <String, String>()
            };

            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(), Mock.Of <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict), factoryMock.Object);

            Mock <IMediator> mediatorMock = new Mock <IMediator>(MockBehavior.Strict);

            mediatorMock.Setup(x => x.Send(It.Is <UpdateDHCPv6ScopeCommand>(y =>
                                                                            y.ScopeId == id &&
                                                                            y.Name == name && y.Description == description && y.ParentId == parentId &&
                                                                            y.AddressProperties == addressProperties && y.Resolver == resolverInfo
                                                                            ), It.IsAny <CancellationToken>())).ReturnsAsync(mediatorResultShouldBeSuccessful).Verifiable();

            var request = new CreateOrUpdateDHCPv6ScopeRequest
            {
                Name              = name,
                Description       = description,
                AddressProperties = addressProperties,
                ParentId          = parentId,
                Resolver          = resolverInfo,
            };

            var controller = new DHCPv6ScopeController(mediatorMock.Object,
                                                       Mock.Of <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict),
                                                       rootScope);

            var actionResult = await controller.UpdateScope(request, id);

            if (mediatorResultShouldBeSuccessful == true)
            {
                actionResult.EnsureNoContentResult();
            }
            else
            {
                actionResult.EnsureBadRequestObjectResult("unable to execute service operation");
            }

            mediatorMock.Verify();
        }
Ejemplo n.º 16
0
        public void HandleConfirm_LeaseNotFound(Boolean withAddress, Boolean withPrefix)
        {
            Random random = new Random();

            var packet = GetRelayedConfirmPacket(random, out IPv6Address leasedAddress, out DUID _, out UInt32 iaId, out DHCPv6PrefixDelegation prefix, withAddress, withPrefix);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid     scopeId        = random.NextGuid();
            Guid     leaseId        = random.NextGuid();
            DateTime leaseCreatedAt = DateTime.UtcNow;

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        t1: DHCPv6TimeScale.FromDouble(0.5),
                        t2: DHCPv6TimeScale.FromDouble(0.75),
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: true),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv6LeaseCreatedEvent
                {
                    EntityId                      = leaseId,
                    Address                       = leasedAddress,
                    ClientIdentifier              = new UUIDDUID(random.NextGuid()),
                    IdentityAssocationId          = iaId,
                    ScopeId                       = scopeId,
                    StartedAt                     = leaseCreatedAt,
                    ValidUntil                    = DateTime.UtcNow.AddDays(1),
                    HasPrefixDelegation           = withPrefix,
                    PrefixLength                  = withPrefix == false ? (Byte)0 : prefix.Mask.Identifier,
                    DelegatedNetworkAddress       = withPrefix == false ? IPv6Address.Empty :  prefix.NetworkAddress,
                    IdentityAssocationIdForPrefix = withPrefix == false ? 0 : prefix.IdentityAssociation,
                },
            });

            DHCPv6Packet result = rootScope.HandleConfirm(packet, GetServerPropertiesResolver());

            Assert.Equal(DHCPv6Packet.Empty, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6ConfirmHandledEvent.ConfirmErrors.LeaseNotFound);
        }
Ejemplo n.º 17
0
        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);
            }
        }
Ejemplo n.º 18
0
        protected DHCPv6RootScope GetDHCPv6RootScope()
        {
            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >());

            var scope = new DHCPv6RootScope(Guid.NewGuid(), Mock.Of <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(), factoryMock.Object);

            return(scope);
        }
Ejemplo n.º 19
0
 public DeleteDHCPv6ScopeCommandHandler(
     IDHCPv6StorageEngine storageEngine,
     DHCPv6RootScope rootScope,
     ILogger <DeleteDHCPv6ScopeCommandHandler> logger
     )
 {
     this.rootScope     = rootScope;
     this.storageEngine = storageEngine;
     this.logger        = logger;
 }
Ejemplo n.º 20
0
        protected static void DHCPv6ScopeAddressesAreExhaustedEvent(int index, DHCPv6RootScope rootScope, Guid scopeId)
        {
            IEnumerable <DomainEvent> changes = rootScope.GetChanges();

            Assert.IsAssignableFrom <DHCPv6ScopeAddressesAreExhaustedEvent>(changes.ElementAt(index));

            DHCPv6ScopeAddressesAreExhaustedEvent castedEvent = (DHCPv6ScopeAddressesAreExhaustedEvent)changes.ElementAt(index);

            Assert.Equal(castedEvent.EntityId, scopeId);
        }
Ejemplo n.º 21
0
 public UpdateDHCPv6ScopeCommandHandler(
     IDHCPv6StorageEngine store,
     IServiceBus serviceBus,
     DHCPv6RootScope rootScope,
     ILogger <UpdateDHCPv6ScopeCommandHandler> logger)
 {
     _store           = store;
     this._serviceBus = serviceBus;
     _rootScope       = rootScope;
     _logger          = logger;
 }
Ejemplo n.º 22
0
 public DashboardController(
     DHCPv6RootScope rootScope,
     DHCPv4RootScope dhcpv4RootScope,
     IDHCPv6ReadStore storage,
     INotificationEngine notificationEngine)
 {
     _rootScope          = rootScope ?? throw new ArgumentNullException(nameof(rootScope));
     _dhcpv4RootScope    = dhcpv4RootScope ?? throw new ArgumentNullException(nameof(dhcpv4RootScope));
     _storage            = storage ?? throw new ArgumentNullException(nameof(storage));
     _notificationEngine = notificationEngine ?? throw new ArgumentNullException(nameof(notificationEngine));
 }
Ejemplo n.º 23
0
        public void HandleRenew_OnlyPrefix(Boolean isUnicast)
        {
            Random random = new Random();

            UInt32      prefixId             = random.NextUInt32();
            Byte        prefixLength         = (Byte)random.Next(34, 64);
            IPv6Address prefixNetworkAddress = IPv6Address.FromString("fd01::0");

            DHCPv6PacketOption[] options = new DHCPv6PacketOption[] {
                new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] {
                    new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), prefixLength, prefixNetworkAddress, Array.Empty <DHCPv6PacketSuboption>())
                })
            };

            var packet = isUnicast == true?
                         GetRenewPacket(random, out IPv6Address _, out DUID _, out UInt32 _, false, options) :
                             GetRelayedRenewPacket(random, out IPv6Address _, out DUID _, out UInt32 _, false, options);

            var resolverInformations = GetMockupResolver(packet, out Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock);

            Guid scopeId = random.NextGuid();

            DHCPv6RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent(
                    new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::01"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::02")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        reuseAddressIfPossible: false,
                        prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(IPv6Address.FromString("2140:1::0"), new IPv6SubnetMaskIdentifier(32), new IPv6SubnetMaskIdentifier(prefixLength)),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
            });

            DHCPv6Packet result = rootScope.HandleRenew(packet, GetServerPropertiesResolver());

            CheckErrorPacket(packet, IPv6Address.Empty, 0, result, DHCPv6PrefixDelegation.FromValues(prefixNetworkAddress, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(prefixLength)), prefixId), DHCPv6StatusCodes.NoBinding);
            CheckEventAmount(1, rootScope);

            CheckHandeledEvent(0, packet, result, rootScope, scopeId, DHCPv6RenewHandledEvent.RenewErrors.OnlyPrefixIsNotAllowed);
        }
Ejemplo n.º 24
0
        public async Task Handle_ScopeNotFound()
        {
            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 <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict);

            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            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                  = parentId,
                        ParentId            = null,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        },
                        ScopeProperties   = new DHCPv6ScopeProperties(),
                        AddressProperties = DHCPv6ScopeAddressProperties.Empty,
                    }
                },
            });

            var     command = new UpdateDHCPv6ScopeParentCommand(scopeId, parentId);
            var     handler = new UpdateDHCPv6ScopeParentCommandHandler(Mock.Of <IDHCPv6StorageEngine>(MockBehavior.Strict), rootScope, Mock.Of <ILogger <UpdateDHCPv6ScopeParentCommandHandler> >());
            Boolean result  = await handler.Handle(command, CancellationToken.None);

            Assert.False(result);

            scopeResolverMock.Verify();
        }
Ejemplo n.º 25
0
        public async Task Handle_HasNoChildren(Boolean requestedToDeleteChildrenAsWell)
        {
            Random random = new Random();

            Guid id = random.NextGuid();

            String resolverName = random.GetAlphanumericString();

            Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> > scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >();

            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);

            rootScope.Load(new[] {
                new DHCPv6ScopeAddedEvent
                {
                    Instructions = new DHCPv6ScopeCreateInstruction
                    {
                        Id = id,
                        ResolverInformation = new CreateScopeResolverInformation
                        {
                            Typename = resolverName,
                        }
                    }
                }
            });


            Mock <IDHCPv6StorageEngine> storageMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict);

            storageMock.Setup(x => x.Save(rootScope)).ReturnsAsync(true).Verifiable();

            var command = new DeleteDHCPv6ScopeCommand(id, requestedToDeleteChildrenAsWell);

            var handler = new DeleteDHCPv6ScopeCommandHandler(storageMock.Object, rootScope,
                                                              Mock.Of <ILogger <DeleteDHCPv6ScopeCommandHandler> >());

            Boolean result = await handler.Handle(command, CancellationToken.None);

            Assert.True(result);

            Assert.Single(rootScope.GetChanges());

            storageMock.Verify();
        }
Ejemplo n.º 26
0
        protected static DHCPv6Lease CheckLease(
            Int32 index, Int32 expectedAmount, IPv6Address expectedAdress,
            Guid scopeId, DHCPv6RootScope rootScope, DateTime expectedCreationData,
            DUID clientDuid, UInt32 iaId, Boolean shouldBePending, Boolean shouldHavePrefix, Byte[] uniqueIdentifier = null, Boolean checkExpire = true)
        {
            DHCPv6Scope scope  = rootScope.GetScopeById(scopeId);
            var         leases = scope.Leases.GetAllLeases();

            Assert.Equal(expectedAmount, leases.Count());

            DHCPv6Lease lease = leases.ElementAt(index);

            Assert.NotNull(lease);
            Assert.Equal(expectedAdress, lease.Address);
            if (checkExpire == 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);
            if (shouldBePending == true)
            {
                Assert.True(lease.IsPending());
            }
            else
            {
                Assert.True(lease.IsActive());
            }

            Assert.Equal(clientDuid, lease.ClientDUID);
            Assert.Equal(iaId, lease.IdentityAssocicationId);


            if (uniqueIdentifier == null)
            {
                Assert.Empty(lease.UniqueIdentifier);
            }
            else
            {
                Assert.NotNull(lease.UniqueIdentifier);
                Assert.Equal(uniqueIdentifier, lease.UniqueIdentifier);
            }

            if (shouldHavePrefix == false)
            {
                Assert.Equal(DHCPv6PrefixDelegation.None, lease.PrefixDelegation);
            }

            return(lease);
        }
Ejemplo n.º 27
0
        protected static void CheckLeaseCreatedEvent(
            Int32 index, DUID clientDuid, UInt32 iaId,
            Guid scopeId, DHCPv6RootScope rootScope,
            IPv6Address expectedAdress, DHCPv6Lease lease,
            Byte[] uniqueIdentifier = null,
            Guid?ancestorId         = null,
            Boolean checkLeaseTimes = true
            )
        {
            IEnumerable <DomainEvent> changes = rootScope.GetChanges();

            Assert.NotNull(changes);

            Assert.IsAssignableFrom <DHCPv6LeaseCreatedEvent>(changes.ElementAt(index));

            DHCPv6LeaseCreatedEvent createdEvent = (DHCPv6LeaseCreatedEvent)changes.ElementAt(index);

            Assert.NotNull(createdEvent);

            Assert.Equal(scopeId, createdEvent.ScopeId);
            Assert.Equal(expectedAdress, createdEvent.Address);
            Assert.Equal(clientDuid, createdEvent.ClientIdentifier);
            Assert.Equal(iaId, createdEvent.IdentityAssocationId);
            Assert.Equal(lease.Id, createdEvent.EntityId);
            Assert.Equal(ancestorId, createdEvent.AncestorId);
            if (uniqueIdentifier == null)
            {
                Assert.Null(createdEvent.UniqueIdentiifer);
            }
            else
            {
                Assert.Equal(uniqueIdentifier, createdEvent.UniqueIdentiifer);
            }
            Assert.Equal(lease.Start, createdEvent.StartedAt);
            Assert.Equal(lease.End, createdEvent.ValidUntil);

            var addressProperties = rootScope.GetScopeById(scopeId).AddressRelatedProperties;

            if (checkLeaseTimes == true)
            {
                Assert.Equal(addressProperties.T1.Value * addressProperties.ValidLeaseTime.Value, createdEvent.RenewalTime);
                Assert.Equal(addressProperties.T2.Value * addressProperties.ValidLeaseTime.Value, createdEvent.PreferredLifetime);
            }

            if (lease.PrefixDelegation == DHCPv6PrefixDelegation.None)
            {
                Assert.Equal(IPv6Address.Empty, createdEvent.DelegatedNetworkAddress);
                Assert.Equal(0, createdEvent.PrefixLength);
                Assert.False(createdEvent.HasPrefixDelegation);
            }
        }
Ejemplo n.º 28
0
        public async Task GetHandledDHCPv6PacketByScopeId_NotFound()
        {
            Random random = new Random();

            Guid  scopeId = random.NextGuid();
            Int32 amount  = random.Next(10, 250);

            DHCPv6RootScope rootScope = GetRootScope();

            var controller   = new DHCPv6StatisticsController(rootScope, Mock.Of <IDHCPv6ReadStore>(MockBehavior.Strict));
            var actionResult = await controller.GetHandledDHCPv6PacketByScopeId(scopeId, amount);

            actionResult.EnsureNotFoundObjectResult("scope not found");
        }
Ejemplo n.º 29
0
        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);
            }
        }
Ejemplo n.º 30
0
        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));
        }