Beispiel #1
0
        public async Task SaveAndGetEventsInChunks()
        {
            Random random = new Random();

            Guid id = random.NextGuid();
            PseudoAggregateRoot aggregateRoot = PseudoAggregateRoot.Create(id, "my name");

            Int32 amount = 10_000;

            for (int i = 0; i < amount; i++)
            {
                aggregateRoot.ChangeName($"iteration {i}");
            }

            var settings = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");
            var client   = new EventStoreClient(settings);

            String prefix = random.GetAlphanumericString();

            EventStoreBasedStore store = new(new EventStoreBasedStoreConnenctionOptions(client, prefix));

            try
            {
                await store.Save(aggregateRoot);

                var events = await store.GetEvents <PseudoAggregateRoot>(id, 10);

                Assert.Equal(amount + 1, events.Count());
                Assert.Equal($"iteration {amount - 1}", ((PseudoAggregateRootNameChangedEvent)events.Last()).SecondName);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(prefix, settings);
            }
        }
Beispiel #2
0
        public async Task LifeCylce()
        {
            Random random     = new Random();
            String firstname  = random.GetAlphanumericString();
            String secondName = random.GetAlphanumericString();
            Guid   id         = random.NextGuid();

            PseudoAggregateRoot aggregateRoot = PseudoAggregateRoot.Create(id, firstname);

            aggregateRoot.ChangeName(secondName);

            var    settings            = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");
            var    client              = new EventStoreClient(settings);
            String prefix              = random.GetAlphanumericString();
            EventStoreBasedStore store = new EventStoreBasedStore(new EventStoreBasedStoreConnenctionOptions(client, prefix));

            try
            {
                Boolean firstExistResult = await store.CheckIfAggrerootExists <PseudoAggregateRoot>(id);

                Assert.False(firstExistResult);

                Boolean saveResult = await store.Save(aggregateRoot);

                Assert.True(saveResult);

                Boolean secondExistResult = await store.CheckIfAggrerootExists <PseudoAggregateRoot>(id);

                Assert.True(secondExistResult);

                var hydratedVersion = new PseudoAggregateRoot(id);
                await store.HydrateAggragate(hydratedVersion);

                Assert.Equal(firstname, hydratedVersion.InitialName);
                Assert.Equal(secondName, hydratedVersion.SecondName);

                Boolean deleteResult = await store.DeleteAggregateRoot <PseudoAggregateRoot>(id);

                Assert.True(deleteResult);

                Boolean thirdExistResult = await store.CheckIfAggrerootExists <PseudoAggregateRoot>(id);

                Assert.False(thirdExistResult);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(prefix, settings);
            }
        }
Beispiel #3
0
        private async Task ExecuteWithStreamErase(Random random, Func <EventStoreBasedStore, Task> executor)
        {
            String prefix   = random.GetAlphanumericString();
            var    settings = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");

            try
            {
                var client = new EventStoreClient(settings);

                EventStoreBasedStore store = new EventStoreBasedStore(new EventStoreBasedStoreConnenctionOptions(client, prefix));

                await executor(store);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(prefix, settings);
            }
        }
Beispiel #4
0
        //[Fact]
        public async Task SendAndReceive()
        {
            Random random = new Random();

            String dbName = $"mydb-{random.Next()}";
            String prefix = random.GetAlphanumericString();

            try
            {
                UInt32 enterpriseNumber = (UInt32)random.Next();

                StorageContext initicalContext = DatabaseTestingUtility.GetTestDatabaseContext(dbName);

                await initicalContext.Database.MigrateAsync();

                await initicalContext.SaveInitialServerConfiguration(new DHCPv6ServerProperties { ServerDuid = new UUIDDUID(new Guid()) });

                initicalContext.Dispose();

                IPv6Address expectedAdress = IPv6Address.FromString("fe80::0");

                var services = new ServiceCollection();
                services.AddScoped <ServiceFactory>(p => p.GetService);

                services.AddSingleton <DHCPv6RootScope>(sp =>
                {
                    var storageEngine = sp.GetRequiredService <IDHCPv6StorageEngine>();
                    var scope         = storageEngine.GetRootScope().GetAwaiter().GetResult();
                    return(scope);
                });

                services.AddTransient <IDHCPv6ServerPropertiesResolver, DatabaseDHCPv6ServerPropertiesResolver>();
                services.AddSingleton <ISerializer, JSONBasedSerializer>();
                services.AddSingleton <IScopeResolverManager <DHCPv6Packet, IPv6Address>, DHCPv6ScopeResolverManager>();
                services.AddSingleton <IServiceBus, MediaRBasedServiceBus>();
                services.AddSingleton <IDHCPv6PacketFilterEngine, SimpleDHCPv6PacketFilterEngine>();
                services.AddSingleton <IDHCPv6InterfaceEngine, DHCPv6InterfaceEngine>();
                services.AddSingleton <IDHCPv6LeaseEngine, DHCPv6LeaseEngine>();
                services.AddSingleton <IDHCPv6StorageEngine, DHCPv6StorageEngine>();
                services.AddSingleton <IDHCPv6ReadStore, StorageContext>();
                services.AddSingleton(new EventStoreBasedStoreConnenctionOptions(new EventStoreClient(EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false")), prefix));
                services.AddSingleton <IDHCPv6EventStore, EventStoreBasedStore>();
                services.AddSingleton(DatabaseTestingUtility.GetTestDbContextOptions(dbName));

                services.AddTransient <INotificationHandler <DHCPv6PacketArrivedMessage> >(sp => new DHCPv6PacketArrivedMessageHandler(
                                                                                               sp.GetRequiredService <IServiceBus>(), sp.GetRequiredService <IDHCPv6PacketFilterEngine>(), sp.GetService <ILogger <DHCPv6PacketArrivedMessageHandler> >()));

                services.AddTransient <INotificationHandler <ValidDHCPv6PacketArrivedMessage> >(sp => new ValidDHCPv6PacketArrivedMessageHandler(
                                                                                                    sp.GetRequiredService <IServiceBus>(), sp.GetRequiredService <IDHCPv6LeaseEngine>(), sp.GetService <ILogger <ValidDHCPv6PacketArrivedMessageHandler> >()));

                services.AddTransient <INotificationHandler <DHCPv6PacketReadyToSendMessage> >(sp => new DHCPv6PacketReadyToSendMessageHandler(
                                                                                                   sp.GetRequiredService <IDHCPv6InterfaceEngine>(), sp.GetService <ILogger <DHCPv6PacketReadyToSendMessageHandler> >()));

                services.AddTransient <DHCPv6RateLimitBasedFilter>();
                services.AddTransient <DHCPv6PacketConsistencyFilter>();
                services.AddTransient <DHCPv6PacketServerIdentifierFilter>((sp) => new DHCPv6PacketServerIdentifierFilter(
                                                                               new UUIDDUID(new Guid()), sp.GetService <ILogger <DHCPv6PacketServerIdentifierFilter> >()));

                services.AddLogging();

                var provider = services.BuildServiceProvider();

                DHCPv6RootScope initialRootScope = provider.GetService <DHCPv6RootScope>();

                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), enterpriseNumber.ToString() },
                            { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() },
                        }
                    },
                    Name = "Testscope",
                    Id   = Guid.NewGuid(),
                });

                IDHCPv6PacketFilterEngine packetFilterEngine = provider.GetService <IDHCPv6PacketFilterEngine>();
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6RateLimitBasedFilter>());
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6PacketConsistencyFilter>());
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6PacketServerIdentifierFilter>());


                IDHCPv6InterfaceEngine interfaceEngine = provider.GetService <IDHCPv6InterfaceEngine>();
                var possibleListener = interfaceEngine.GetPossibleListeners();

                var listener = possibleListener.First();

                interfaceEngine.OpenListener(listener);

                IPAddress  address        = new IPAddress(listener.Address.GetBytes());
                IPEndPoint ownEndPoint    = new IPEndPoint(address, 546);
                IPEndPoint serverEndPoint = new IPEndPoint(address, 547);

                UdpClient client = new UdpClient(ownEndPoint);

                DHCPv6Packet packet = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>
                {
                    new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
                    new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(Guid.NewGuid())),
                    new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.Zero, TimeSpan.Zero, new List <DHCPv6PacketSuboption>()),
                });

                DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(listener.Address, listener.Address),
                                                                               true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[]
                {
                    new DHCPv6PacketRemoteIdentifierOption(enterpriseNumber, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }),
                }, packet);

                byte[] packetStream = outerPacket.GetAsStream();
                await client.SendAsync(packetStream, packetStream.Length, serverEndPoint);

                await Task.Delay(2000);

                var content = await client.ReceiveAsync();

                Byte[]       receivedBytes = content.Buffer;
                DHCPv6Packet response      = DHCPv6Packet.FromByteArray(receivedBytes, new IPv6HeaderInformation(listener.Address, listener.Address));

                var iaOption = response.GetInnerPacket().GetNonTemporaryIdentiyAssocation(15);
                Assert.NotNull(iaOption);
                Assert.Single(iaOption.Suboptions);
                Assert.IsAssignableFrom <DHCPv6PacketIdentityAssociationAddressSuboption>(iaOption.Suboptions.First());
                Assert.Equal(expectedAdress, ((DHCPv6PacketIdentityAssociationAddressSuboption)iaOption.Suboptions.First()).Address);
            }
            finally
            {
                await DatabaseTestingUtility.DeleteDatabase(dbName);

                await EventStoreClientDisposer.CleanUp(prefix, null);
            }
        }
Beispiel #5
0
        public async Task FullCycle()
        {
            Random random = new Random();

            String dbName           = $"{random.Next()}";
            String eventStorePrefix = random.GetAlphanumericString();

            var serviceInteractions = GetTestClient(dbName, eventStorePrefix);

            Guid scopeId = Guid.Parse("7ec8da2e-73a8-4205-9dd8-9bde4be5434a");

            try
            {
                var firstResponse = await serviceInteractions.Client.PostAsync("/api/notifications/pipelines/", GetContent(new
                {
                    name = "my first pipeline",
                    description = "my first pipeline description",
                    triggerName = "PrefixEdgeRouterBindingUpdatedTrigger",
                    condtionName = "DHCPv6ScopeIdNotificationCondition",
                    conditionProperties = new Dictionary <String, String> {
                        { "includesChildren", JsonConvert.SerializeObject(true) }, { "scopeIds", JsonConvert.SerializeObject(new[] { scopeId }) }
                    },
                    actorName = "NxOsStaticRouteUpdaterNotificationActor",
                    actorProperties = new Dictionary <String, String> {
                        { "url", "https://192.168.1.1" }, { "username", "5353535" }, { "password", "36363636" }
                    },
                }));

                Guid firstId = await IsObjectResult <Guid>(firstResponse);

                Assert.NotEqual(Guid.Empty, firstId);

                var secondResponse = await serviceInteractions.Client.PostAsync("/api/notifications/pipelines/", GetContent(new
                {
                    name = "my second pipeline",
                    description = "my second pipeline description",
                    triggerName = "PrefixEdgeRouterBindingUpdatedTrigger",
                    condtionName = "DHCPv6ScopeIdNotificationCondition",
                    conditionProperties = new Dictionary <String, String> {
                        { "includesChildren", JsonConvert.SerializeObject(true) }, { "scopeIds", JsonConvert.SerializeObject(new[] { scopeId }) }
                    },
                    actorName = "NxOsStaticRouteUpdaterNotificationActor",
                    actorProperties = new Dictionary <String, String> {
                        { "url", "https://192.168.1.1" }, { "username", "5353535" }, { "password", "36363636" }
                    },
                }));

                Guid secondId = await IsObjectResult <Guid>(secondResponse);

                Assert.NotEqual(Guid.Empty, secondId);

                var thirdresponse = await serviceInteractions.Client.DeleteAsync($"/api/notifications/pipelines/{firstId}");
                await IsEmptyResult(thirdresponse);

                serviceInteractions.Client.Dispose();
                serviceInteractions = GetTestClient(dbName, eventStorePrefix);

                var resultResponse = await serviceInteractions.Client.GetAsync("/api/notifications/pipelines/");

                var result = await IsObjectResult <IEnumerable <NotificationPipelineReadModel> >(resultResponse);

                Assert.Single(result);
                Assert.Equal(secondId, result.First().Id);

                var newPrefix = new PrefixBinding(IPv6Address.FromString("fe80:1000::"), new IPv6SubnetMaskIdentifier(32), IPv6Address.FromString("fe80::2"));

                var actorServiceMock = serviceInteractions.ActorServiceMock;

                Int32 actorFired = 0;;
                actorServiceMock.Setup(x => x.Connect("https://192.168.1.1", "5353535", "36363636")).ReturnsAsync(true).Verifiable();
                actorServiceMock.Setup(x => x.AddIPv6StaticRoute(newPrefix.Prefix, newPrefix.Mask.Identifier, newPrefix.Host)).ReturnsAsync(true).Callback(() => actorFired++).Verifiable();

                await serviceInteractions.ServiceBus.Publish(new NewTriggerHappendMessage(new[] { PrefixEdgeRouterBindingUpdatedTrigger.WithNewBinding(scopeId, newPrefix) }));

                Int32 triesLeft = 10;
                while (triesLeft-- > 0)
                {
                    await Task.Delay(1000);

                    if (actorFired > 0)
                    {
                        break;
                    }
                }

                actorServiceMock.Verify();
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(eventStorePrefix, null);

                await DatabaseTestingUtility.DeleteDatabase(dbName);
            }
        }
Beispiel #6
0
        public async Task SendAndReceive()
        {
            Random random = new Random();

            String dbName           = $"{random.Next()}";
            String eventStorePrefix = random.GetAlphanumericString();

            var serviceInteractions = GetTestClient(dbName, eventStorePrefix);

            Byte[] opt82Value = random.NextBytes(10);

            try
            {
                //Get and Add Interface
                var interfacesResult = await serviceInteractions.GetAsync("/api/interfaces/dhcpv4/");

                var interfaces = await IsObjectResult <DHCPv4InterfaceOverview>(interfacesResult);

                DHCPv4InterfaceEntry usedInterface = null;
                foreach (var item in interfaces.Entries)
                {
                    try
                    {
                        var createInterfaceResult = await serviceInteractions.PostAsync("/api/interfaces/dhcpv4/", GetContent(new
                        {
                            name = "my test interface",
                            ipv4Address = item.IPv4Address,
                            interfaceId = item.PhysicalInterfaceId
                        }));

                        Guid interfaceDaAPIId = await IsObjectResult <Guid>(createInterfaceResult);

                        Assert.NotEqual(Guid.Empty, interfaceDaAPIId);
                        usedInterface = item;
                        break;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                Assert.NotNull(usedInterface);

                var interfaceAddress = IPv4Address.FromString(usedInterface.IPv4Address);

                //Create scope

                var createScopeResult = await serviceInteractions.PostAsync("/api/scopes/dhcpv4/", GetContent(new
                {
                    name = "Testscope",
                    id = Guid.NewGuid(),
                    addressProperties = new
                    {
                        start = "192.168.10.1",
                        end = "192.168.10.254",
                        excludedAddresses = new[] { "192.168.10.1" },
                        preferredLifetime = TimeSpan.FromDays(0.8),
                        leaseTime = TimeSpan.FromDays(1),
                        renewalTime = TimeSpan.FromDays(0.5),
                        maskLength = 24,
                        supportDirectUnicast = true,
                        acceptDecline = true,
                        informsAreAllowd = true,
                        reuseAddressIfPossible = true,
                        addressAllocationStrategy = Beer.DaAPI.Shared.Requests.DHCPv4ScopeRequests.V1.DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next
                    },
                    resolver = new
                    {
                        typename = nameof(DHCPv4Option82Resolver),
                        propertiesAndValues = new Dictionary <String, String>
                        {
                            { nameof(DHCPv4Option82Resolver.Value), System.Text.Json.JsonSerializer.Serialize(opt82Value) },
                        }
                    }
                }));

                Guid scopeId = await IsObjectResult <Guid>(createScopeResult);

                Assert.NotEqual(Guid.Empty, scopeId);

                IPAddress  address        = new IPAddress(interfaceAddress.GetBytes());
                IPEndPoint ownEndPoint    = new IPEndPoint(address, 68);
                IPEndPoint serverEndPoint = new IPEndPoint(address, 67);

                UdpClient client = new UdpClient(ownEndPoint);

                IPv4HeaderInformation headerInformation =
                    new IPv4HeaderInformation(IPv4Address.FromString(address.ToString()), IPv4Address.Broadcast);

                DHCPv4Packet discoverPacket = new DHCPv4Packet(
                    headerInformation, random.NextBytes(6), (UInt32)random.Next(),
                    IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Broadcast,
                    new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover),
                    new DHCPv4PacketRawByteOption(82, opt82Value),
                    new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("my custom client")));

                byte[] discoverPacketStream = discoverPacket.GetAsStream();
                await client.SendAsync(discoverPacketStream, discoverPacketStream.Length, serverEndPoint);

                await Task.Delay(2000);

                var content = await client.ReceiveAsync();

                Byte[]       receivedBytes = content.Buffer;
                DHCPv4Packet response      = DHCPv4Packet.FromByteArray(receivedBytes, new IPv4HeaderInformation(interfaceAddress, interfaceAddress));

                Assert.NotNull(response);
                Assert.True(response.IsValid);

                var serverIdentifierOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.ServerIdentifier) as DHCPv4PacketAddressOption;
                Assert.NotNull(serverIdentifierOption);
                Assert.Equal(interfaceAddress, serverIdentifierOption.Address);

                var subnetOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.SubnetMask) as DHCPv4PacketAddressOption;
                Assert.NotNull(subnetOption);
                Assert.Equal(IPv4Address.FromString("255.255.255.0"), subnetOption.Address);

                var clientIdentifierOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.ClientIdentifier) as DHCPv4PacketClientIdentifierOption;
                Assert.NotNull(clientIdentifierOption);
                Assert.Equal("my custom client", clientIdentifierOption.Identifier.IdentifierValue);
                Assert.Equal(DUID.Empty, clientIdentifierOption.Identifier.DUID);
                Assert.Equal((UInt32)0, clientIdentifierOption.Identifier.IaId);
                Assert.Empty(clientIdentifierOption.Identifier.HwAddress);

                var incoming82Option = response.GetOptionByIdentifier(DHCPv4OptionTypes.Option82) as DHCPv4PacketRawByteOption;
                Assert.NotNull(incoming82Option);
                Assert.Equal(opt82Value, incoming82Option.OptionData);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(eventStorePrefix, null);

                await DatabaseTestingUtility.DeleteDatabase(dbName);
            }
        }