From 14b72407863fdabe491efd68b96fbf86e9081931 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 31 Jan 2023 03:55:30 +0100 Subject: [PATCH 01/15] update mongodm --- .../BeehiveManager.Domain.csproj | 2 +- .../IBeehiveDbContext.cs | 6 ++-- .../BeehiveDbContext.cs | 10 +++--- .../ModelMaps/BeeNodeMap.cs | 26 ++++++-------- .../ModelMaps/EtherAddressConfigMap.cs | 2 +- .../ModelMaps/ModelBaseMap.cs | 8 ++--- .../ModelMaps/NodeLogMap.cs | 4 +-- ...ctionRepository.cs => DomainRepository.cs} | 8 ++--- .../BeehiveManager.Services.csproj | 2 +- src/BeehiveManager/BeehiveManager.csproj | 4 +-- .../Configs/ApplicationSettings.cs | 25 -------------- src/BeehiveManager/Configs/AssemblyVersion.cs | 34 ------------------- src/BeehiveManager/Program.cs | 6 ---- .../Helpers/DbContextMockHelper.cs | 7 ++-- 14 files changed, 37 insertions(+), 107 deletions(-) rename src/BeehiveManager.Persistence/Repositories/{DomainCollectionRepository.cs => DomainRepository.cs} (93%) delete mode 100644 src/BeehiveManager/Configs/ApplicationSettings.cs delete mode 100644 src/BeehiveManager/Configs/AssemblyVersion.cs diff --git a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj index f179331..28e7a73 100644 --- a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj +++ b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/BeehiveManager.Domain/IBeehiveDbContext.cs b/src/BeehiveManager.Domain/IBeehiveDbContext.cs index 3083c8c..d2fb4b5 100644 --- a/src/BeehiveManager.Domain/IBeehiveDbContext.cs +++ b/src/BeehiveManager.Domain/IBeehiveDbContext.cs @@ -21,9 +21,9 @@ namespace Etherna.BeehiveManager.Domain { public interface IBeehiveDbContext : IDbContext { - ICollectionRepository BeeNodes { get; } - ICollectionRepository EtherAddressConfigs { get; } - ICollectionRepository NodeLogs { get; } + IRepository BeeNodes { get; } + IRepository EtherAddressConfigs { get; } + IRepository NodeLogs { get; } IEventDispatcher EventDispatcher { get; } } diff --git a/src/BeehiveManager.Persistence/BeehiveDbContext.cs b/src/BeehiveManager.Persistence/BeehiveDbContext.cs index 2b6d8da..898e752 100644 --- a/src/BeehiveManager.Persistence/BeehiveDbContext.cs +++ b/src/BeehiveManager.Persistence/BeehiveDbContext.cs @@ -48,8 +48,8 @@ public BeehiveDbContext( // Properties. //repositories - public ICollectionRepository BeeNodes { get; } = new DomainCollectionRepository( - new CollectionRepositoryOptions("beeNodes") + public IRepository BeeNodes { get; } = new DomainRepository( + new RepositoryOptions("beeNodes") { IndexBuilders = new[] { @@ -59,15 +59,15 @@ public BeehiveDbContext( .Ascending(n => n.Hostname), new CreateIndexOptions { Unique = true }) } }); - public ICollectionRepository EtherAddressConfigs { get; } = new DomainCollectionRepository( - new CollectionRepositoryOptions("etherAddressConfigs") + public IRepository EtherAddressConfigs { get; } = new DomainRepository( + new RepositoryOptions("etherAddressConfigs") { IndexBuilders = new[] { (Builders.IndexKeys.Ascending(a => a.Address), new CreateIndexOptions { Unique = true }), } }); - public ICollectionRepository NodeLogs { get; } = new DomainCollectionRepository("nodeLogs"); + public IRepository NodeLogs { get; } = new DomainRepository("nodeLogs"); //other properties public IEventDispatcher EventDispatcher { get; } diff --git a/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs b/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs index 638e5ea..08593c9 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs @@ -25,45 +25,41 @@ class BeeNodeMap : IModelMapsCollector { public void Register(IDbContext dbContext) { - dbContext.SchemaRegistry.AddModelMapsSchema("6b94df32-034f-46f9-a5c1-239905ad5d07"); + dbContext.MapRegistry.AddModelMap("6b94df32-034f-46f9-a5c1-239905ad5d07"); } /// /// A minimal serializer with only id /// public static ReferenceSerializer ReferenceSerializer( - IDbContext dbContext, - bool useCascadeDelete = false) => + IDbContext dbContext) => new(dbContext, config => { - config.UseCascadeDelete = useCascadeDelete; - config.AddModelMapsSchema("e5d93371-e1a7-4ff3-b947-a4862c40d938"); - config.AddModelMapsSchema("a48cf8b2-1b18-450d-afc1-4094ce23ba78", mm => { }); - config.AddModelMapsSchema>("1a7fb389-fd58-4ad6-82b5-b687273bc5ab", mm => + config.AddModelMap("e5d93371-e1a7-4ff3-b947-a4862c40d938"); + config.AddModelMap("a48cf8b2-1b18-450d-afc1-4094ce23ba78", mm => { }); + config.AddModelMap>("1a7fb389-fd58-4ad6-82b5-b687273bc5ab", mm => { mm.MapIdMember(m => m.Id); mm.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId)); }); - config.AddModelMapsSchema("28d5e30d-c205-4440-9ba6-80505409ef8d", mm => { }); + config.AddModelMap("28d5e30d-c205-4440-9ba6-80505409ef8d", mm => { }); }); /// /// A serializer with connection info to node /// public static ReferenceSerializer ConnectionInfoSerializer( - IDbContext dbContext, - bool useCascadeDelete = false) => + IDbContext dbContext) => new(dbContext, config => { - config.UseCascadeDelete = useCascadeDelete; - config.AddModelMapsSchema("148b3991-63da-4966-a781-30295c71fcae"); - config.AddModelMapsSchema("774d614c-2bd2-4a51-83a7-6d0df1942216", mm => { }); - config.AddModelMapsSchema>("959def90-ddab-48a7-9a0e-1917be419171", mm => + config.AddModelMap("148b3991-63da-4966-a781-30295c71fcae"); + config.AddModelMap("774d614c-2bd2-4a51-83a7-6d0df1942216", mm => { }); + config.AddModelMap>("959def90-ddab-48a7-9a0e-1917be419171", mm => { mm.MapIdMember(n => n.Id); mm.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId)); }); - config.AddModelMapsSchema("a833d25f-4613-4cbc-b36a-4cdfa62501f4", mm => + config.AddModelMap("a833d25f-4613-4cbc-b36a-4cdfa62501f4", mm => { mm.MapMember(n => n.ConnectionScheme); mm.MapMember(n => n.DebugPort); diff --git a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs b/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs index a92d209..10c9319 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs @@ -23,7 +23,7 @@ class EtherAddressConfigMap : IModelMapsCollector { public void Register(IDbContext dbContext) { - dbContext.SchemaRegistry.AddModelMapsSchema("e7e7bb6a-17c2-444b-bd7d-6fc84f57da3c", mm => + dbContext.MapRegistry.AddModelMap("e7e7bb6a-17c2-444b-bd7d-6fc84f57da3c", mm => { mm.AutoMap(); diff --git a/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs b/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs index 5e965f2..20676f4 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs @@ -25,11 +25,9 @@ class ModelBaseMap : IModelMapsCollector { public void Register(IDbContext dbContext) { - dbContext.SchemaRegistry.AddModelMapsSchema("7653dfab-f715-42d1-8d3d-bbca69755399"); - - dbContext.SchemaRegistry.AddModelMapsSchema("5cddcc0c-1a61-443c-bb72-98d1344cafb4"); - - dbContext.SchemaRegistry.AddModelMapsSchema>("3d7b0f5d-d490-495e-af05-6114e8f8d2f4", modelMap => + dbContext.MapRegistry.AddModelMap("7653dfab-f715-42d1-8d3d-bbca69755399"); + dbContext.MapRegistry.AddModelMap("5cddcc0c-1a61-443c-bb72-98d1344cafb4"); + dbContext.MapRegistry.AddModelMap>("3d7b0f5d-d490-495e-af05-6114e8f8d2f4", modelMap => { modelMap.AutoMap(); diff --git a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs b/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs index 13b8f76..2b9d120 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs @@ -23,14 +23,14 @@ class NodeLogMap : IModelMapsCollector { public void Register(IDbContext dbContext) { - dbContext.SchemaRegistry.AddModelMapsSchema("a1c4d182-b3b2-4d49-8fe1-91d723c1188c", mm => + dbContext.MapRegistry.AddModelMap("a1c4d182-b3b2-4d49-8fe1-91d723c1188c", mm => { mm.AutoMap(); // Set members with custom serializers. mm.SetMemberSerializer(l => l.Node, BeeNodeMap.ReferenceSerializer(dbContext)); }); - dbContext.SchemaRegistry.AddModelMapsSchema("625838e6-4290-42e4-a6d5-a6b0e5cf1660"); + dbContext.MapRegistry.AddModelMap("625838e6-4290-42e4-a6d5-a6b0e5cf1660"); } } } diff --git a/src/BeehiveManager.Persistence/Repositories/DomainCollectionRepository.cs b/src/BeehiveManager.Persistence/Repositories/DomainRepository.cs similarity index 93% rename from src/BeehiveManager.Persistence/Repositories/DomainCollectionRepository.cs rename to src/BeehiveManager.Persistence/Repositories/DomainRepository.cs index 589a64f..3d24d49 100644 --- a/src/BeehiveManager.Persistence/Repositories/DomainCollectionRepository.cs +++ b/src/BeehiveManager.Persistence/Repositories/DomainRepository.cs @@ -25,16 +25,16 @@ namespace Etherna.BeehiveManager.Persistence.Repositories { - public class DomainCollectionRepository : - CollectionRepository + public class DomainRepository : + Repository where TModel : EntityModelBase { // Constructors and initialization. - public DomainCollectionRepository(string name) + public DomainRepository(string name) : base(name) { } - public DomainCollectionRepository(CollectionRepositoryOptions options) + public DomainRepository(RepositoryOptions options) : base(options) { } diff --git a/src/BeehiveManager.Services/BeehiveManager.Services.csproj b/src/BeehiveManager.Services/BeehiveManager.Services.csproj index e5aeb46..08e923a 100644 --- a/src/BeehiveManager.Services/BeehiveManager.Services.csproj +++ b/src/BeehiveManager.Services/BeehiveManager.Services.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/BeehiveManager/BeehiveManager.csproj b/src/BeehiveManager/BeehiveManager.csproj index e1f68c2..a183a5d 100644 --- a/src/BeehiveManager/BeehiveManager.csproj +++ b/src/BeehiveManager/BeehiveManager.csproj @@ -21,8 +21,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/src/BeehiveManager/Configs/ApplicationSettings.cs b/src/BeehiveManager/Configs/ApplicationSettings.cs deleted file mode 100644 index d0a3e89..0000000 --- a/src/BeehiveManager/Configs/ApplicationSettings.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Etherna.BeehiveManager.Configs -{ - public class ApplicationSettings - { - // Fields. - string? _assemblyVersion; - - // Properties. - public string AssemblyVersion { get => _assemblyVersion ?? "1.0.0"; set => _assemblyVersion = value; } - } -} diff --git a/src/BeehiveManager/Configs/AssemblyVersion.cs b/src/BeehiveManager/Configs/AssemblyVersion.cs deleted file mode 100644 index d02975f..0000000 --- a/src/BeehiveManager/Configs/AssemblyVersion.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; -using System.Reflection; - -namespace Etherna.BeehiveManager.Configs -{ - public class AssemblyVersion - { - public AssemblyVersion(Assembly assembly) - { - if (assembly is null) - throw new ArgumentNullException(nameof(assembly)); - - Version = assembly.GetCustomAttribute()?.InformationalVersion ?? "1.0.0"; - SimpleVersion = Version.Split('+')[0]; - } - - public string SimpleVersion { get; } - public string Version { get; } - } -} diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index 525fcca..4324a07 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -185,11 +185,6 @@ private static void ConfigureServices(WebApplicationBuilder builder) }); // Configure setting. - var assemblyVersion = new AssemblyVersion(typeof(Program).GetTypeInfo().Assembly); - services.Configure(options => - { - options.AssemblyVersion = assemblyVersion.Version; - }); services.Configure(config.GetSection(SeedDbSettings.ConfigPosition)); // Configure Hangfire and persistence. @@ -216,7 +211,6 @@ private static void ConfigureServices(WebApplicationBuilder builder) }, options => { - options.DocumentSemVer.CurrentVersion = assemblyVersion.SimpleVersion; options.ConnectionString = config["ConnectionStrings:BeehiveManagerDb"]; }); diff --git a/test/BeehiveManager.Persistence.Tests/Helpers/DbContextMockHelper.cs b/test/BeehiveManager.Persistence.Tests/Helpers/DbContextMockHelper.cs index e69e640..f4d9624 100644 --- a/test/BeehiveManager.Persistence.Tests/Helpers/DbContextMockHelper.cs +++ b/test/BeehiveManager.Persistence.Tests/Helpers/DbContextMockHelper.cs @@ -24,6 +24,7 @@ using Etherna.MongODM.Core.Serialization.Mapping; using Etherna.MongODM.Core.Serialization.Modifiers; using Etherna.MongODM.Core.Utility; +using Microsoft.Extensions.Logging; using Moq; using System; using System.Collections.Generic; @@ -50,9 +51,9 @@ public static void InitializeDbContextMock(DbContext dbContext, Mock d.DbMigrationManager).Returns(new Mock().Object); dbDependenciesMock.Setup(d => d.DiscriminatorRegistry).Returns(new DiscriminatorRegistry()); dbDependenciesMock.Setup(d => d.ExecutionContext).Returns(execContext); - dbDependenciesMock.Setup(d => d.ProxyGenerator).Returns(new ProxyGenerator(new Castle.DynamicProxy.ProxyGenerator())); + dbDependenciesMock.Setup(d => d.MapRegistry).Returns(new MapRegistry()); + dbDependenciesMock.Setup(d => d.ProxyGenerator).Returns(new ProxyGenerator(new Mock().Object, new Castle.DynamicProxy.ProxyGenerator())); dbDependenciesMock.Setup(d => d.RepositoryRegistry).Returns(new RepositoryRegistry()); - dbDependenciesMock.Setup(d => d.SchemaRegistry).Returns(new SchemaRegistry()); dbDependenciesMock.Setup(d => d.SerializerModifierAccessor).Returns(new SerializerModifierAccessor(execContext)); // Setup Mongo client. @@ -81,7 +82,7 @@ public static void InitializeDbContextMock(DbContext dbContext, Mock> SetupCollectionMock( Mock mongoDatabaseMock, - ICollectionRepository collection) + IRepository collection) where TModel : class, IEntityModel { if (mongoDatabaseMock is null) From 66b1bdbf9d6709429b7f3f94c26376869f6c6e2c Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 31 Jan 2023 04:00:18 +0100 Subject: [PATCH 02/15] update dependencies --- src/BeehiveManager.Domain/BeehiveManager.Domain.csproj | 2 +- src/BeehiveManager.Services/BeehiveManager.Services.csproj | 2 +- .../Utilities/Models/BeeNodeLiveInstance.cs | 4 ++-- src/BeehiveManager/BeehiveManager.csproj | 6 +++--- .../BeehiveManager.Persistence.Tests.csproj | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj index 28e7a73..40f7c77 100644 --- a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj +++ b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/BeehiveManager.Services/BeehiveManager.Services.csproj b/src/BeehiveManager.Services/BeehiveManager.Services.csproj index 08e923a..c0cd811 100644 --- a/src/BeehiveManager.Services/BeehiveManager.Services.csproj +++ b/src/BeehiveManager.Services/BeehiveManager.Services.csproj @@ -13,7 +13,7 @@ - + diff --git a/src/BeehiveManager.Services/Utilities/Models/BeeNodeLiveInstance.cs b/src/BeehiveManager.Services/Utilities/Models/BeeNodeLiveInstance.cs index c66ad00..8d5b175 100644 --- a/src/BeehiveManager.Services/Utilities/Models/BeeNodeLiveInstance.cs +++ b/src/BeehiveManager.Services/Utilities/Models/BeeNodeLiveInstance.cs @@ -142,12 +142,12 @@ public async Task TryRefreshStatusAsync(bool forceFullRefresh = false) */ var currentGatewayApiVersion = healthResult.ApiVersion switch { - "3.2.0" => GatewayApiVersion.v3_2_0, + "4.0.0" => GatewayApiVersion.v4_0_0, _ => Enum.GetValues().OrderByDescending(e => e.ToString()).First() }; var currentDebugApiVersion = healthResult.DebugApiVersion switch { - "3.2.0" => DebugApiVersion.v3_2_0, + "4.0.0" => DebugApiVersion.v4_0_0, _ => Enum.GetValues().OrderByDescending(e => e.ToString()).First() }; diff --git a/src/BeehiveManager/BeehiveManager.csproj b/src/BeehiveManager/BeehiveManager.csproj index a183a5d..afe5e2d 100644 --- a/src/BeehiveManager/BeehiveManager.csproj +++ b/src/BeehiveManager/BeehiveManager.csproj @@ -16,18 +16,18 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + diff --git a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj index 404eb81..668f401 100644 --- a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj +++ b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj @@ -15,8 +15,8 @@ - - + + all From 0656dce52a27474cbaefbbdc5e2e63b7910f6b9f Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 18:54:45 +0100 Subject: [PATCH 03/15] update dependencies --- src/BeehiveManager.Domain/BeehiveManager.Domain.csproj | 2 +- src/BeehiveManager.Services/Domain/BeeNodeService.cs | 4 +--- src/BeehiveManager/BeehiveManager.csproj | 2 +- .../BeehiveManager.Persistence.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj index 40f7c77..77fb1a1 100644 --- a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj +++ b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/BeehiveManager.Services/Domain/BeeNodeService.cs b/src/BeehiveManager.Services/Domain/BeeNodeService.cs index 52175e4..ab5a44d 100644 --- a/src/BeehiveManager.Services/Domain/BeeNodeService.cs +++ b/src/BeehiveManager.Services/Domain/BeeNodeService.cs @@ -58,10 +58,8 @@ public async Task GetPreferredSocBeeNodeAsync(string socOwnerAddress) public async Task SelectRandomHealthyNodeAsync() { - var instance = await beeNodeLiveManager.TrySelectHealthyNodeAsync(BeeNodeSelectionMode.Random); - if (instance is null) + var instance = await beeNodeLiveManager.TrySelectHealthyNodeAsync(BeeNodeSelectionMode.Random) ?? throw new InvalidOperationException("Can't select a valid healthy node"); - return await dbContext.BeeNodes.FindOneAsync(instance.Id); } } diff --git a/src/BeehiveManager/BeehiveManager.csproj b/src/BeehiveManager/BeehiveManager.csproj index afe5e2d..476bc6e 100644 --- a/src/BeehiveManager/BeehiveManager.csproj +++ b/src/BeehiveManager/BeehiveManager.csproj @@ -26,7 +26,7 @@ - + diff --git a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj index 668f401..1785b7d 100644 --- a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj +++ b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj @@ -15,7 +15,7 @@ - + From 1081d6937f754c8bc0e5858e162cce8b5e0f9975 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 19:02:10 +0100 Subject: [PATCH 04/15] fix returned error code --- .../Areas/Api/Services/NodesControllerService.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/BeehiveManager/Areas/Api/Services/NodesControllerService.cs b/src/BeehiveManager/Areas/Api/Services/NodesControllerService.cs index f896042..b03e0c7 100644 --- a/src/BeehiveManager/Areas/Api/Services/NodesControllerService.cs +++ b/src/BeehiveManager/Areas/Api/Services/NodesControllerService.cs @@ -17,6 +17,7 @@ using Etherna.BeehiveManager.Domain; using Etherna.BeehiveManager.Domain.Models; using Etherna.BeehiveManager.Services.Utilities; +using Etherna.BeeNet.Exceptions; using Etherna.MongoDB.Driver; using Etherna.MongODM.Core.Extensions; using MongoDB.Driver; @@ -112,8 +113,15 @@ public async Task> GetPinsByNodeAsync(string id) public async Task GetPostageBatchDetailsAsync(string id, string batchId) { var beeNodeInstance = await beeNodeLiveManager.GetBeeNodeLiveInstanceAsync(id); - var postageBatch = await beeNodeInstance.Client.DebugClient!.GetPostageBatchAsync(batchId); - return new PostageBatchDto(postageBatch); + try + { + var postageBatch = await beeNodeInstance.Client.DebugClient!.GetPostageBatchAsync(batchId); + return new PostageBatchDto(postageBatch); + } + catch (BeeNetDebugApiException ex) when (ex.StatusCode == 400) + { + throw new KeyNotFoundException(); + } } public async Task> GetPostageBatchesByNodeAsync(string id) From c2a39db6ac1b0698302cc7e2cfdcea9bbbb4d070 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 19:07:45 +0100 Subject: [PATCH 05/15] fix serilog config --- src/BeehiveManager/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index 4324a07..e10d2e8 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -97,6 +97,7 @@ private static void ConfigureLogging() var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{environment}.json", optional: true) + .AddEnvironmentVariables() .Build(); Log.Logger = new LoggerConfiguration() From 1eef6c9b2e197507162355cc60fc04fcbd813895 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 19:22:13 +0100 Subject: [PATCH 06/15] migrate to .net7 --- BeehiveManager.sln | 9 +-------- Dockerfile | 4 ++-- src/BeehiveManager.Domain/BeehiveManager.Domain.csproj | 2 +- .../BeehiveManager.Persistence.csproj | 2 +- src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs | 2 +- .../ModelMaps/EtherAddressConfigMap.cs | 2 +- src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs | 2 +- src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs | 2 +- .../BeehiveManager.Services.csproj | 2 +- .../OnBeeNodeCreatedThenAddNodeStatusHandler.cs | 2 +- .../OnBeeNodeDeletedThenRemoveNodeStatusHandler.cs | 2 +- .../Utilities/BeeNodeLiveManager.cs | 9 +++++---- src/BeehiveManager/BeehiveManager.csproj | 2 +- src/BeehiveManager/Program.cs | 8 ++++---- .../BeehiveManager.Persistence.Tests.csproj | 2 +- 15 files changed, 23 insertions(+), 29 deletions(-) diff --git a/BeehiveManager.sln b/BeehiveManager.sln index 81f5aa8..de7e151 100644 --- a/BeehiveManager.sln +++ b/BeehiveManager.sln @@ -19,12 +19,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1CD13F83-9A79-4873-A8E3-77A2D432D706}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{9297C969-7E18-4B8E-831F-F770DA1805F4}" - ProjectSection(SolutionItems) = preProject - .github\workflows\stable-release.yml = .github\workflows\stable-release.yml - .github\workflows\unstable-release.yml = .github\workflows\unstable-release.yml - EndProjectSection -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{873FF005-8941-4971-A051-55D8434DC8F9}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "infrastructure", "infrastructure", "{11FCB662-8945-484F-9459-C2C5823045E7}" @@ -45,7 +39,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docker-beehive-sample", "do EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{CE10A1ED-2695-44EC-97F1-CB91FC5412D8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BeehiveManager.Persistence.Tests", "test\BeehiveManager.Persistence.Tests\BeehiveManager.Persistence.Tests.csproj", "{74F4D982-085D-42F4-9E61-C288B25E64CB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BeehiveManager.Persistence.Tests", "test\BeehiveManager.Persistence.Tests\BeehiveManager.Persistence.Tests.csproj", "{74F4D982-085D-42F4-9E61-C288B25E64CB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -79,7 +73,6 @@ Global EndGlobalSection GlobalSection(NestedProjects) = preSolution {E14D105A-A294-4F67-BC95-58C5178E2818} = {1CD13F83-9A79-4873-A8E3-77A2D432D706} - {9297C969-7E18-4B8E-831F-F770DA1805F4} = {61C3814F-A839-44D7-8335-0F365D3FFA8C} {873FF005-8941-4971-A051-55D8434DC8F9} = {1CD13F83-9A79-4873-A8E3-77A2D432D706} {11FCB662-8945-484F-9459-C2C5823045E7} = {1CD13F83-9A79-4873-A8E3-77A2D432D706} {125AB1B7-31FD-4BA5-8282-6AC48C3522BB} = {873FF005-8941-4971-A051-55D8434DC8F9} diff --git a/Dockerfile b/Dockerfile index f0c7318..29ac24d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src COPY . . RUN dotnet restore "BeehiveManager.sln" diff --git a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj index 77fb1a1..a585d7f 100644 --- a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj +++ b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 Etherna.BeehiveManager.Domain Etherna Sagl diff --git a/src/BeehiveManager.Persistence/BeehiveManager.Persistence.csproj b/src/BeehiveManager.Persistence/BeehiveManager.Persistence.csproj index 0028640..b50066e 100644 --- a/src/BeehiveManager.Persistence/BeehiveManager.Persistence.csproj +++ b/src/BeehiveManager.Persistence/BeehiveManager.Persistence.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 Etherna.BeehiveManager.Persistence Etherna Sagl diff --git a/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs b/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs index 08593c9..b4f9a65 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/BeeNodeMap.cs @@ -21,7 +21,7 @@ namespace Etherna.BeehiveManager.Persistence.ModelMaps { - class BeeNodeMap : IModelMapsCollector + internal sealed class BeeNodeMap : IModelMapsCollector { public void Register(IDbContext dbContext) { diff --git a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs b/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs index 10c9319..77c1e77 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs @@ -19,7 +19,7 @@ namespace Etherna.BeehiveManager.Persistence.ModelMaps { - class EtherAddressConfigMap : IModelMapsCollector + internal sealed class EtherAddressConfigMap : IModelMapsCollector { public void Register(IDbContext dbContext) { diff --git a/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs b/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs index 20676f4..2e0a222 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/ModelBaseMap.cs @@ -21,7 +21,7 @@ namespace Etherna.BeehiveManager.Persistence.ModelMaps { - class ModelBaseMap : IModelMapsCollector + internal sealed class ModelBaseMap : IModelMapsCollector { public void Register(IDbContext dbContext) { diff --git a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs b/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs index 2b9d120..6d44ab9 100644 --- a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs +++ b/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs @@ -19,7 +19,7 @@ namespace Etherna.BeehiveManager.Persistence.ModelMaps { - class NodeLogMap : IModelMapsCollector + internal sealed class NodeLogMap : IModelMapsCollector { public void Register(IDbContext dbContext) { diff --git a/src/BeehiveManager.Services/BeehiveManager.Services.csproj b/src/BeehiveManager.Services/BeehiveManager.Services.csproj index c0cd811..3a29b7a 100644 --- a/src/BeehiveManager.Services/BeehiveManager.Services.csproj +++ b/src/BeehiveManager.Services/BeehiveManager.Services.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 Etherna.BeehiveManager.Services Etherna Sagl diff --git a/src/BeehiveManager.Services/EventHandlers/OnBeeNodeCreatedThenAddNodeStatusHandler.cs b/src/BeehiveManager.Services/EventHandlers/OnBeeNodeCreatedThenAddNodeStatusHandler.cs index cc283c1..d591390 100644 --- a/src/BeehiveManager.Services/EventHandlers/OnBeeNodeCreatedThenAddNodeStatusHandler.cs +++ b/src/BeehiveManager.Services/EventHandlers/OnBeeNodeCreatedThenAddNodeStatusHandler.cs @@ -20,7 +20,7 @@ namespace Etherna.BeehiveManager.Services.EventHandlers { - class OnBeeNodeCreatedThenAddNodeStatusHandler : EventHandlerBase> + internal sealed class OnBeeNodeCreatedThenAddNodeStatusHandler : EventHandlerBase> { // Fields. private readonly IBeeNodeLiveManager beeNodeLiveManager; diff --git a/src/BeehiveManager.Services/EventHandlers/OnBeeNodeDeletedThenRemoveNodeStatusHandler.cs b/src/BeehiveManager.Services/EventHandlers/OnBeeNodeDeletedThenRemoveNodeStatusHandler.cs index 068ee24..84da7c6 100644 --- a/src/BeehiveManager.Services/EventHandlers/OnBeeNodeDeletedThenRemoveNodeStatusHandler.cs +++ b/src/BeehiveManager.Services/EventHandlers/OnBeeNodeDeletedThenRemoveNodeStatusHandler.cs @@ -20,7 +20,7 @@ namespace Etherna.BeehiveManager.Services.EventHandlers { - class OnBeeNodeDeletedThenRemoveNodeStatusHandler : EventHandlerBase> + internal sealed class OnBeeNodeDeletedThenRemoveNodeStatusHandler : EventHandlerBase> { // Fields. private readonly IBeeNodeLiveManager beeNodeLiveManager; diff --git a/src/BeehiveManager.Services/Utilities/BeeNodeLiveManager.cs b/src/BeehiveManager.Services/Utilities/BeeNodeLiveManager.cs index def1745..87163cf 100644 --- a/src/BeehiveManager.Services/Utilities/BeeNodeLiveManager.cs +++ b/src/BeehiveManager.Services/Utilities/BeeNodeLiveManager.cs @@ -32,7 +32,7 @@ namespace Etherna.BeehiveManager.Services.Utilities /// /// Manage live instances of bee nodes /// - class BeeNodeLiveManager : IBeeNodeLiveManager, IDisposable + internal sealed class BeeNodeLiveManager : IBeeNodeLiveManager, IDisposable { // Consts. private const int HeartbeatPeriod = 10000; //10s @@ -75,8 +75,8 @@ public async Task AddBeeNodeAsync(BeeNode beeNode) public async Task GetBeeNodeLiveInstanceAsync(string nodeId) { - if (beeNodeInstances.ContainsKey(nodeId)) - return beeNodeInstances[nodeId]; + if (beeNodeInstances.TryGetValue(nodeId, out var instance)) + return instance; var beeNode = await dbContext.BeeNodes.FindOneAsync(nodeId); return await AddBeeNodeAsync(beeNode); @@ -151,7 +151,8 @@ public void StopHealthHeartbeat() => { var lastSelectedNodeWithIndexList = beeNodeInstances.Values .Select((node, index) => new { index, node }) - .Where(g => g.node == lastSelectedNodesRoundRobin[selectionContext]); + .Where(g => g.node == lastSelectedNodesRoundRobin[selectionContext]) + .ToList(); if (lastSelectedNodeWithIndexList.Any()) //if prev node still exists { diff --git a/src/BeehiveManager/BeehiveManager.csproj b/src/BeehiveManager/BeehiveManager.csproj index 476bc6e..36954c6 100644 --- a/src/BeehiveManager/BeehiveManager.csproj +++ b/src/BeehiveManager/BeehiveManager.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 Etherna.BeehiveManager Etherna Sagl diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index e10d2e8..e0bd77b 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -116,7 +116,7 @@ private static ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot { string assemblyName = Assembly.GetExecutingAssembly().GetName().Name!.ToLower(CultureInfo.InvariantCulture).Replace(".", "-", StringComparison.InvariantCulture); string envName = environment.ToLower(CultureInfo.InvariantCulture).Replace(".", "-", StringComparison.InvariantCulture); - return new ElasticsearchSinkOptions(configuration.GetSection("Elastic:Urls").Get().Select(u => new Uri(u))) + return new ElasticsearchSinkOptions((configuration.GetSection("Elastic:Urls").Get() ?? throw new ServiceConfigurationException()).Select(u => new Uri(u))) { AutoRegisterTemplate = true, IndexFormat = $"{assemblyName}-{envName}-{DateTime.UtcNow:yyyy-MM}" @@ -131,7 +131,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) // Configure Asp.Net Core framework services. services.AddDataProtection() - .PersistKeysToDbContext(new DbContextOptions { ConnectionString = config["ConnectionStrings:DataProtectionDb"] }); + .PersistKeysToDbContext(new DbContextOptions { ConnectionString = config["ConnectionStrings:DataProtectionDb"] ?? throw new ServiceConfigurationException() }); services.AddCors(); services.AddRazorPages(); @@ -191,7 +191,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) // Configure Hangfire and persistence. services.AddMongODMWithHangfire(configureHangfireOptions: options => { - options.ConnectionString = config["ConnectionStrings:HangfireDb"]; + options.ConnectionString = config["ConnectionStrings:HangfireDb"] ?? throw new ServiceConfigurationException(); options.StorageOptions = new MongoStorageOptions { MigrationOptions = new MongoMigrationOptions //don't remove, could throw exception @@ -212,7 +212,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) }, options => { - options.ConnectionString = config["ConnectionStrings:BeehiveManagerDb"]; + options.ConnectionString = config["ConnectionStrings:BeehiveManagerDb"] ?? throw new ServiceConfigurationException(); }); services.AddMongODMAdminDashboard(new MongODM.AspNetCore.UI.DashboardOptions diff --git a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj index 1785b7d..a92777e 100644 --- a/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj +++ b/test/BeehiveManager.Persistence.Tests/BeehiveManager.Persistence.Tests.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 Etherna.BeehiveManager.Persistence Etherna Sagl From 05a9e8105d1289802c35851e6ba373ae755bf5bd Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 19:30:22 +0100 Subject: [PATCH 07/15] use EthernaAcrDebugPages --- src/BeehiveManager/BeehiveManager.csproj | 1 + src/BeehiveManager/Program.cs | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/BeehiveManager/BeehiveManager.csproj b/src/BeehiveManager/BeehiveManager.csproj index 36954c6..fa582c3 100644 --- a/src/BeehiveManager/BeehiveManager.csproj +++ b/src/BeehiveManager/BeehiveManager.csproj @@ -16,6 +16,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index e0bd77b..26a2f21 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Etherna.ACR.Middlewares.DebugPages; using Etherna.BeehiveManager.Configs; using Etherna.BeehiveManager.Configs.Hangfire; using Etherna.BeehiveManager.Configs.Swagger; @@ -226,7 +227,14 @@ private static void ConfigureServices(WebApplicationBuilder builder) private static void ConfigureApplication(WebApplication app) { - app.UseDeveloperExceptionPage(); + var env = app.Environment; + + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + app.UseEthernaAcrDebugPages(); + } + app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); @@ -236,12 +244,6 @@ private static void ConfigureApplication(WebApplication app) CommonConsts.HangfireAdminPath, new Hangfire.DashboardOptions { Authorization = new[] { new AllowAllFilter() } }); - // Register cron tasks. - RecurringJob.AddOrUpdate( - CashoutAllNodesTask.TaskId, - task => task.RunAsync(), - "0 5 * * *"); //at 05:00 every day - // Add Swagger and SwaggerUI. var apiProvider = app.Services.GetRequiredService(); app.UseSwagger(); @@ -256,9 +258,15 @@ private static void ConfigureApplication(WebApplication app) } }); - // Add controllers. + // Add pages and controllers. app.MapControllers(); app.MapRazorPages(); + + // Register cron tasks. + RecurringJob.AddOrUpdate( + CashoutAllNodesTask.TaskId, + task => task.RunAsync(), + "0 5 * * *"); //at 05:00 every day } } } From c71c8f93ef669f526de569780e10520fa8a5b338 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 19:33:49 +0100 Subject: [PATCH 08/15] add support to nullable enum --- src/BeehiveManager/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index 26a2f21..3352b13 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -176,6 +176,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) services.AddSwaggerGen(options => { options.SupportNonNullableReferenceTypes(); + options.UseInlineDefinitionsForEnums(); //add a custom operation filter which sets default values options.OperationFilter(); From 15588351f89ea2b07f9fcc4984419b11aa467822 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 20:21:44 +0100 Subject: [PATCH 09/15] set filter allowall to mongodm admin page --- .../Configs/MongODM/AllowAllFilter.cs | 25 +++++++++++++++++++ src/BeehiveManager/Program.cs | 1 + 2 files changed, 26 insertions(+) create mode 100644 src/BeehiveManager/Configs/MongODM/AllowAllFilter.cs diff --git a/src/BeehiveManager/Configs/MongODM/AllowAllFilter.cs b/src/BeehiveManager/Configs/MongODM/AllowAllFilter.cs new file mode 100644 index 0000000..1ccfeb6 --- /dev/null +++ b/src/BeehiveManager/Configs/MongODM/AllowAllFilter.cs @@ -0,0 +1,25 @@ +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Etherna.MongODM.AspNetCore.UI.Auth.Filters; +using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; + +namespace Etherna.BeehiveManager.Configs.MongODM +{ + public class AllowAllFilter : IDashboardAuthFilter + { + public Task AuthorizeAsync(HttpContext? context) => Task.FromResult(true); + } +} diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index 3352b13..0807340 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -219,6 +219,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) services.AddMongODMAdminDashboard(new MongODM.AspNetCore.UI.DashboardOptions { + AuthFilters = new[] { new Configs.MongODM.AllowAllFilter() }, BasePath = CommonConsts.DatabaseAdminPath }); From 696e970b7c498c61af8e5b53af62e3b5dec59016 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 20:27:52 +0100 Subject: [PATCH 10/15] update github actions --- .github/workflows/stable-release.yml | 10 +++++----- .github/workflows/unstable-release.yml | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index 0259adb..ae43659 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -11,13 +11,13 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - name: Docker meta id: meta - uses: docker/metadata-action@v3 + uses: docker/metadata-action@v4 with: images: etherna/beehive-manager tags: | @@ -26,16 +26,16 @@ jobs: type=semver,pattern=v{{version}} - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 + uses: docker/setup-buildx-action@v2 - name: Login to DockerHub - uses: docker/login-action@v1 + uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push - uses: docker/build-push-action@v2 + uses: docker/build-push-action@v4 with: context: . push: true diff --git a/.github/workflows/unstable-release.yml b/.github/workflows/unstable-release.yml index 2d376cf..200675e 100644 --- a/.github/workflows/unstable-release.yml +++ b/.github/workflows/unstable-release.yml @@ -11,29 +11,29 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 with: fetch-depth: 0 - name: Docker meta id: meta - uses: docker/metadata-action@v3 + uses: docker/metadata-action@v4 with: images: etherna/beehive-manager tags: | type=ref,event=branch - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 + uses: docker/setup-buildx-action@v2 - name: Login to DockerHub - uses: docker/login-action@v1 + uses: docker/login-action@v2 with: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} - name: Build and push - uses: docker/build-push-action@v2 + uses: docker/build-push-action@v4 with: context: . push: true From 278ea6b592a68f2ba7efe898cdec0174a54d60ee Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 21:10:30 +0100 Subject: [PATCH 11/15] remove soc preferred node logic --- .../IBeehiveDbContext.cs | 1 - .../Models/EtherAddressConfig.cs | 38 ----------- .../BeehiveDbContext.cs | 8 --- .../ModelMaps/EtherAddressConfigMap.cs | 35 ---------- .../Domain/BeeNodeService.cs | 33 --------- .../Domain/IBeeNodeService.cs | 1 - .../Controllers/EtherAddressesController.cs | 24 ++----- .../Api/Controllers/LoadBalancerController.cs | 6 +- .../Api/Controllers/PostageController.cs | 6 +- .../Areas/Api/DtoModels/EtherAddressDto.cs | 15 ++--- .../EtherAddressesControllerService.cs | 47 ------------- .../IEtherAddressesControllerService.cs | 11 --- .../ILoadBalancerControllerService.cs | 2 +- .../Api/Services/IPostageControllerService.cs | 3 +- .../Services/LoadBalancerControllerService.cs | 10 +-- .../Api/Services/PostageControllerService.cs | 24 +------ .../BeehiveDbContextDeserializationTest.cs | 67 ------------------- 17 files changed, 21 insertions(+), 310 deletions(-) delete mode 100644 src/BeehiveManager.Domain/Models/EtherAddressConfig.cs delete mode 100644 src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs delete mode 100644 src/BeehiveManager/Areas/Api/Services/EtherAddressesControllerService.cs delete mode 100644 src/BeehiveManager/Areas/Api/Services/IEtherAddressesControllerService.cs diff --git a/src/BeehiveManager.Domain/IBeehiveDbContext.cs b/src/BeehiveManager.Domain/IBeehiveDbContext.cs index d2fb4b5..4b559ba 100644 --- a/src/BeehiveManager.Domain/IBeehiveDbContext.cs +++ b/src/BeehiveManager.Domain/IBeehiveDbContext.cs @@ -22,7 +22,6 @@ namespace Etherna.BeehiveManager.Domain public interface IBeehiveDbContext : IDbContext { IRepository BeeNodes { get; } - IRepository EtherAddressConfigs { get; } IRepository NodeLogs { get; } IEventDispatcher EventDispatcher { get; } diff --git a/src/BeehiveManager.Domain/Models/EtherAddressConfig.cs b/src/BeehiveManager.Domain/Models/EtherAddressConfig.cs deleted file mode 100644 index c964dd3..0000000 --- a/src/BeehiveManager.Domain/Models/EtherAddressConfig.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using Nethereum.Util; -using System; - -namespace Etherna.BeehiveManager.Domain.Models -{ - public class EtherAddressConfig : EntityModelBase - { - // Consturctor. - public EtherAddressConfig(string address) - { - if (!address.IsValidEthereumAddressHexFormat()) - throw new ArgumentException("Is not a valid ethereum address", nameof(address)); - - Address = address.ConvertToEthereumChecksumAddress(); - } -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - protected EtherAddressConfig() { } -#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - - // Properties. - public virtual string Address { get; protected set; } - public virtual BeeNode? PreferredSocNode { get; set; } - } -} diff --git a/src/BeehiveManager.Persistence/BeehiveDbContext.cs b/src/BeehiveManager.Persistence/BeehiveDbContext.cs index 898e752..0230ebc 100644 --- a/src/BeehiveManager.Persistence/BeehiveDbContext.cs +++ b/src/BeehiveManager.Persistence/BeehiveDbContext.cs @@ -59,14 +59,6 @@ public BeehiveDbContext( .Ascending(n => n.Hostname), new CreateIndexOptions { Unique = true }) } }); - public IRepository EtherAddressConfigs { get; } = new DomainRepository( - new RepositoryOptions("etherAddressConfigs") - { - IndexBuilders = new[] - { - (Builders.IndexKeys.Ascending(a => a.Address), new CreateIndexOptions { Unique = true }), - } - }); public IRepository NodeLogs { get; } = new DomainRepository("nodeLogs"); //other properties diff --git a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs b/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs deleted file mode 100644 index 77c1e77..0000000 --- a/src/BeehiveManager.Persistence/ModelMaps/EtherAddressConfigMap.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using Etherna.BeehiveManager.Domain.Models; -using Etherna.MongODM.Core; -using Etherna.MongODM.Core.Extensions; -using Etherna.MongODM.Core.Serialization; - -namespace Etherna.BeehiveManager.Persistence.ModelMaps -{ - internal sealed class EtherAddressConfigMap : IModelMapsCollector - { - public void Register(IDbContext dbContext) - { - dbContext.MapRegistry.AddModelMap("e7e7bb6a-17c2-444b-bd7d-6fc84f57da3c", mm => - { - mm.AutoMap(); - - // Set members with custom serializers. - mm.SetMemberSerializer(a => a.PreferredSocNode!, BeeNodeMap.ConnectionInfoSerializer(dbContext)); - }); - } - } -} diff --git a/src/BeehiveManager.Services/Domain/BeeNodeService.cs b/src/BeehiveManager.Services/Domain/BeeNodeService.cs index ab5a44d..ab47225 100644 --- a/src/BeehiveManager.Services/Domain/BeeNodeService.cs +++ b/src/BeehiveManager.Services/Domain/BeeNodeService.cs @@ -2,7 +2,6 @@ using Etherna.BeehiveManager.Domain.Models; using Etherna.BeehiveManager.Services.Utilities; using Etherna.BeehiveManager.Services.Utilities.Models; -using Nethereum.Util; using System; using System.Threading.Tasks; @@ -24,38 +23,6 @@ public BeeNodeService( } // Methods. - public async Task GetPreferredSocBeeNodeAsync(string socOwnerAddress) - { - socOwnerAddress = socOwnerAddress.ConvertToEthereumChecksumAddress(); - - // Try to find ether address configuration. - var etherAddressConfig = await dbContext.EtherAddressConfigs.TryFindOneAsync(a => a.Address == socOwnerAddress); - - // If configuration doesn't exist, create it. - if (etherAddressConfig is null) - { - //select a random healthy node - var selectedNode = await SelectRandomHealthyNodeAsync(); - - //create configuration with selected node as preferred - etherAddressConfig = new EtherAddressConfig(socOwnerAddress) { PreferredSocNode = selectedNode }; - await dbContext.EtherAddressConfigs.CreateAsync(etherAddressConfig); - } - - // Else, if there is no preferred soc node, select one random and update config. - else if (etherAddressConfig.PreferredSocNode is null) - { - //select a random healthy node - var selectedNode = await SelectRandomHealthyNodeAsync(); - - //update configuration with selected node as preferred - etherAddressConfig.PreferredSocNode = selectedNode; - await dbContext.SaveChangesAsync(); - } - - return etherAddressConfig.PreferredSocNode; - } - public async Task SelectRandomHealthyNodeAsync() { var instance = await beeNodeLiveManager.TrySelectHealthyNodeAsync(BeeNodeSelectionMode.Random) ?? diff --git a/src/BeehiveManager.Services/Domain/IBeeNodeService.cs b/src/BeehiveManager.Services/Domain/IBeeNodeService.cs index 69af767..96acd59 100644 --- a/src/BeehiveManager.Services/Domain/IBeeNodeService.cs +++ b/src/BeehiveManager.Services/Domain/IBeeNodeService.cs @@ -5,7 +5,6 @@ namespace Etherna.BeehiveManager.Services.Domain { public interface IBeeNodeService { - Task GetPreferredSocBeeNodeAsync(string socOwnerAddress); Task SelectRandomHealthyNodeAsync(); } } \ No newline at end of file diff --git a/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs b/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs index da21772..f699c7d 100644 --- a/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs +++ b/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs @@ -1,27 +1,19 @@ using Etherna.BeehiveManager.Areas.Api.DtoModels; -using Etherna.BeehiveManager.Areas.Api.Services; using Etherna.BeehiveManager.Attributes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace Etherna.BeehiveManager.Areas.Api.Controllers { + [Obsolete("This is a dropped feature")] [ApiController] [ApiVersion("0.3")] [Route("api/v{api-version:apiVersion}/[controller]")] public class EtherAddressesController : ControllerBase { - // Fields. - private readonly IEtherAddressesControllerService service; - - // Constructor. - public EtherAddressesController(IEtherAddressesControllerService service) - { - this.service = service; - } - // Get. /// @@ -34,24 +26,20 @@ public EtherAddressesController(IEtherAddressesControllerService service) [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public Task FindEtherAddressConfigAsync([Required]string address) => - service.FindEtherAddressConfigAsync(address); + public Task FindEtherAddressConfigAsync([Required] string address) => + Task.FromResult(new EtherAddressDto(address)); // Patch. /// /// Set preferred SOC node for address /// - /// The ethereum address - /// The Bee node id [HttpGet("{address}/socnode/{nodeId}")] [SimpleExceptionFilter] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public Task SetPreferredSocNodeAsync( - [Required] string address, - [Required] string nodeId) => - service.SetPreferredSocNodeAsync(address, nodeId); + public Task SetPreferredSocNodeAsync() => + Task.CompletedTask; } } diff --git a/src/BeehiveManager/Areas/Api/Controllers/LoadBalancerController.cs b/src/BeehiveManager/Areas/Api/Controllers/LoadBalancerController.cs index 4499a50..6ec3a42 100644 --- a/src/BeehiveManager/Areas/Api/Controllers/LoadBalancerController.cs +++ b/src/BeehiveManager/Areas/Api/Controllers/LoadBalancerController.cs @@ -66,16 +66,14 @@ public async Task SelectDownloadNodeAsync( /// /// Select best node for download a specific content /// - /// Reference hash of the content /// Selected Bee node [HttpGet("soc/{address}")] [SimpleExceptionFilter] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - public async Task SelectSocNodeAsync( - [Required] string address) + public async Task SelectSocNodeAsync() { - var beeNode = await service.SelectSocNodeAsync(address); + var beeNode = await service.SelectSocNodeAsync(); // Copy response in headers (Nginx optimization). HttpContext.Response.Headers.Add("bee-node-id", beeNode.Id); diff --git a/src/BeehiveManager/Areas/Api/Controllers/PostageController.cs b/src/BeehiveManager/Areas/Api/Controllers/PostageController.cs index f9f4719..5b7a365 100644 --- a/src/BeehiveManager/Areas/Api/Controllers/PostageController.cs +++ b/src/BeehiveManager/Areas/Api/Controllers/PostageController.cs @@ -76,7 +76,6 @@ public async Task FindBeeNodeOwnerOfPostageBatchAsync( /// Is batch immutable /// An optional label for this batch /// Bee node Id - /// The optional ethereum address of the owner /// Postage batch id [HttpPost("batches")] [SimpleExceptionFilter] @@ -89,9 +88,8 @@ public Task BuyPostageBatchAsync( long? gasPrice = null, bool immutable = false, string? label = null, - string? nodeId = null, - string? ownerAddress = null) => - service.BuyPostageBatchAsync(amount, depth, gasPrice, immutable, label, nodeId, ownerAddress); + string? nodeId = null) => + service.BuyPostageBatchAsync(amount, depth, gasPrice, immutable, label, nodeId); // Put. diff --git a/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs b/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs index 346d638..50540b4 100644 --- a/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs +++ b/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs @@ -1,21 +1,16 @@ -using Etherna.BeehiveManager.Domain.Models; -using System; +using System; namespace Etherna.BeehiveManager.Areas.Api.DtoModels { + [Obsolete("This is a dropped feature")] public class EtherAddressDto { - public EtherAddressDto(EtherAddressConfig etherAddressConfig) + public EtherAddressDto(string address) { - if (etherAddressConfig is null) - throw new ArgumentNullException(nameof(etherAddressConfig)); - - Address = etherAddressConfig.Address; - if (etherAddressConfig.PreferredSocNode is not null) - PreferredSocNode = new BeeNodeDto(etherAddressConfig.PreferredSocNode); + Address = address; } public string Address { get; } - public BeeNodeDto? PreferredSocNode { get; } + public BeeNodeDto? PreferredSocNode => null; } } diff --git a/src/BeehiveManager/Areas/Api/Services/EtherAddressesControllerService.cs b/src/BeehiveManager/Areas/Api/Services/EtherAddressesControllerService.cs deleted file mode 100644 index c883488..0000000 --- a/src/BeehiveManager/Areas/Api/Services/EtherAddressesControllerService.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Etherna.BeehiveManager.Areas.Api.DtoModels; -using Etherna.BeehiveManager.Domain; -using Etherna.BeehiveManager.Domain.Models; -using Nethereum.Util; -using System.Threading.Tasks; - -namespace Etherna.BeehiveManager.Areas.Api.Services -{ - public class EtherAddressesControllerService : IEtherAddressesControllerService - { - // Fields. - private readonly IBeehiveDbContext dbContext; - - // Constructor. - public EtherAddressesControllerService( - IBeehiveDbContext dbContext) - { - this.dbContext = dbContext; - } - - // Methods. - public async Task FindEtherAddressConfigAsync(string address) - { - address = address.ConvertToEthereumChecksumAddress(); - var etherAddressConfig = await dbContext.EtherAddressConfigs.TryFindOneAsync(a => a.Address == address); - return new EtherAddressDto(etherAddressConfig ?? new EtherAddressConfig(address)); - } - - public async Task SetPreferredSocNodeAsync(string address, string nodeId) - { - address = address.ConvertToEthereumChecksumAddress(); - var etherAddressConfig = await dbContext.EtherAddressConfigs.TryFindOneAsync(a => a.Address == address); - var node = await dbContext.BeeNodes.FindOneAsync(nodeId); - - if (etherAddressConfig is null) - { - etherAddressConfig = new EtherAddressConfig(address) { PreferredSocNode = node }; - await dbContext.EtherAddressConfigs.CreateAsync(etherAddressConfig); - } - else - { - etherAddressConfig.PreferredSocNode = node; - await dbContext.SaveChangesAsync(); - } - } - } -} diff --git a/src/BeehiveManager/Areas/Api/Services/IEtherAddressesControllerService.cs b/src/BeehiveManager/Areas/Api/Services/IEtherAddressesControllerService.cs deleted file mode 100644 index bef2f23..0000000 --- a/src/BeehiveManager/Areas/Api/Services/IEtherAddressesControllerService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Etherna.BeehiveManager.Areas.Api.DtoModels; -using System.Threading.Tasks; - -namespace Etherna.BeehiveManager.Areas.Api.Services -{ - public interface IEtherAddressesControllerService - { - Task FindEtherAddressConfigAsync(string address); - Task SetPreferredSocNodeAsync(string address, string nodeId); - } -} \ No newline at end of file diff --git a/src/BeehiveManager/Areas/Api/Services/ILoadBalancerControllerService.cs b/src/BeehiveManager/Areas/Api/Services/ILoadBalancerControllerService.cs index f83b45b..3f245a9 100644 --- a/src/BeehiveManager/Areas/Api/Services/ILoadBalancerControllerService.cs +++ b/src/BeehiveManager/Areas/Api/Services/ILoadBalancerControllerService.cs @@ -20,6 +20,6 @@ namespace Etherna.BeehiveManager.Areas.Api.Services public interface ILoadBalancerControllerService { Task SelectDownloadNodeAsync(string hash); - Task SelectSocNodeAsync(string address); + Task SelectSocNodeAsync(); } } \ No newline at end of file diff --git a/src/BeehiveManager/Areas/Api/Services/IPostageControllerService.cs b/src/BeehiveManager/Areas/Api/Services/IPostageControllerService.cs index 978cdc6..e344922 100644 --- a/src/BeehiveManager/Areas/Api/Services/IPostageControllerService.cs +++ b/src/BeehiveManager/Areas/Api/Services/IPostageControllerService.cs @@ -25,8 +25,7 @@ Task BuyPostageBatchAsync( long? gasPrice, bool immutable, string? label, - string? nodeId, - string? ownerAddress); + string? nodeId); Task DilutePostageBatchAsync(string batchId, int depth); Task FindBeeNodeOwnerOfPostageBatchAsync(string batchId); Task TopUpPostageBatchAsync(string batchId, long amount); diff --git a/src/BeehiveManager/Areas/Api/Services/LoadBalancerControllerService.cs b/src/BeehiveManager/Areas/Api/Services/LoadBalancerControllerService.cs index 1599be5..68f49f8 100644 --- a/src/BeehiveManager/Areas/Api/Services/LoadBalancerControllerService.cs +++ b/src/BeehiveManager/Areas/Api/Services/LoadBalancerControllerService.cs @@ -68,14 +68,10 @@ public async Task SelectDownloadNodeAsync(string hash) throw new InvalidOperationException("Can't select a valid node"); } - public async Task SelectSocNodeAsync(string address) + public async Task SelectSocNodeAsync() { - // Get preferred soc node. - var selectedNode = await beeNodeService.GetPreferredSocBeeNodeAsync(address); - - // If preferred soc node is not healthy, select another random. - if (!(await beeNodeLiveManager.GetBeeNodeLiveInstanceAsync(selectedNode.Id)).Status.IsAlive) - selectedNode = await beeNodeService.SelectRandomHealthyNodeAsync(); + // Get random node. + var selectedNode = await beeNodeService.SelectRandomHealthyNodeAsync(); return new BeeNodeDto(selectedNode); } diff --git a/src/BeehiveManager/Areas/Api/Services/PostageControllerService.cs b/src/BeehiveManager/Areas/Api/Services/PostageControllerService.cs index 815d77c..fe1786f 100644 --- a/src/BeehiveManager/Areas/Api/Services/PostageControllerService.cs +++ b/src/BeehiveManager/Areas/Api/Services/PostageControllerService.cs @@ -26,17 +26,14 @@ public class PostageControllerService : IPostageControllerService { // Fields. private readonly IBeeNodeLiveManager beeNodeLiveManager; - private readonly IBeeNodeService beeNodeService; private readonly IBeehiveDbContext dbContext; // Constructor. public PostageControllerService( IBeeNodeLiveManager beeNodeLiveManager, - IBeeNodeService beeNodeService, IBeehiveDbContext dbContext) { this.beeNodeLiveManager = beeNodeLiveManager; - this.beeNodeService = beeNodeService; this.dbContext = dbContext; } @@ -47,8 +44,7 @@ public async Task BuyPostageBatchAsync( long? gasPrice, bool immutable, string? label, - string? nodeId, - string? ownerAddress) + string? nodeId) { // Select node. BeeNodeLiveInstance? beeNodeInstance = null; @@ -57,24 +53,6 @@ public async Task BuyPostageBatchAsync( if (nodeId is not null) beeNodeInstance = await beeNodeLiveManager.GetBeeNodeLiveInstanceAsync(nodeId); - /* else, if exists an owner address, take its preferred soc node. - * This is necessary because postage batches are still binded to specific owning node. - * If a node purchase a postage batch, only this node can sign with it. - * Because we should try to always upload soc/feeds on preferred soc node, - * also postage batches should be purchased on the same node. - * Because we can't discriminate postage batches for soc or not-soc use, always try to - * purchase on preferred soc node, until postagebatch->node binding can be overcome. - */ - else if(ownerAddress is not null) - { - var selectedBeeNode = await beeNodeService.GetPreferredSocBeeNodeAsync(ownerAddress); - - //select instance only if is healthy - var selectedBeeNodeInstance = await beeNodeLiveManager.GetBeeNodeLiveInstanceAsync(selectedBeeNode.Id); - if (selectedBeeNodeInstance.Status.IsAlive) - beeNodeInstance = selectedBeeNodeInstance; - } - //if still null, try to select a random healthy node beeNodeInstance ??= await beeNodeLiveManager.TrySelectHealthyNodeAsync(BeeNodeSelectionMode.RoundRobin, "buyPostageBatch"); diff --git a/test/BeehiveManager.Persistence.Tests/ModelMaps/BeehiveDbContextDeserializationTest.cs b/test/BeehiveManager.Persistence.Tests/ModelMaps/BeehiveDbContextDeserializationTest.cs index 6fc3c37..bf2e8db 100644 --- a/test/BeehiveManager.Persistence.Tests/ModelMaps/BeehiveDbContextDeserializationTest.cs +++ b/test/BeehiveManager.Persistence.Tests/ModelMaps/BeehiveDbContextDeserializationTest.cs @@ -86,48 +86,6 @@ public static IEnumerable BeeNodeDeserializationTests } } - public static IEnumerable EtherAddressConfigDeserializationTests - { - get - { - var tests = new List>(); - - // "e7e7bb6a-17c2-444b-bd7d-6fc84f57da3c" - v0.3.11 - { - var sourceDocument = - @"{ - ""_id"" : ObjectId(""633c703c867c5a05f708070d""), - ""_m"" : ""e7e7bb6a-17c2-444b-bd7d-6fc84f57da3c"", - ""CreationDateTime"" : ISODate(""2022-10-04T17:41:16.522+0000""), - ""Address"" : ""0x974caA59E52682cdA0ad1bBEA2083919A2eCC400"", - ""PreferredSocNode"" : { - ""_m"" : ""a833d25f-4613-4cbc-b36a-4cdfa62501f4"", - ""_id"" : ObjectId(""632dcea61b6694a5ab78bdac""), - ""ConnectionScheme"" : ""http"", - ""DebugPort"" : NumberInt(1635), - ""GatewayPort"" : NumberInt(1633), - ""Hostname"" : ""bee0"" - } - }"; - - var expectedEtherAddressMock = new Mock(); - expectedEtherAddressMock.Setup(n => n.Id).Returns("633c703c867c5a05f708070d"); - expectedEtherAddressMock.Setup(n => n.CreationDateTime).Returns(new DateTime(2022, 10, 04, 17, 41, 16, 522)); - expectedEtherAddressMock.Setup(n => n.Address).Returns("0x974caA59E52682cdA0ad1bBEA2083919A2eCC400"); - { - var beeNodeMock = new Mock(); - beeNodeMock.Setup(n => n.Id).Returns("632dcea61b6694a5ab78bdac"); - - expectedEtherAddressMock.Setup(a => a.PreferredSocNode).Returns(beeNodeMock.Object); - } - - tests.Add(new DeserializationTestElement(sourceDocument, expectedEtherAddressMock.Object)); - } - - return tests.Select(t => new object[] { t }); - } - } - // Tests. [Theory, MemberData(nameof(BeeNodeDeserializationTests))] public void BeeNodeDeserialization(DeserializationTestElement testElement) @@ -156,30 +114,5 @@ public void BeeNodeDeserialization(DeserializationTestElement testEleme Assert.NotNull(result.ConnectionScheme); Assert.NotNull(result.Hostname); } - - [Theory, MemberData(nameof(EtherAddressConfigDeserializationTests))] - public void EtherAddressConfigDeserialization(DeserializationTestElement testElement) - { - if (testElement is null) - throw new ArgumentNullException(nameof(testElement)); - - // Setup. - using var documentReader = new JsonReader(testElement.SourceDocument); - var modelMapSerializer = new ModelMapSerializer(dbContext); - var deserializationContext = BsonDeserializationContext.CreateRoot(documentReader); - testElement.SetupAction(mongoDatabaseMock, dbContext); - - // Action. - using var dbExecutionContext = new DbExecutionContextHandler(dbContext); //run into a db execution context - var result = modelMapSerializer.Deserialize(deserializationContext); - - // Assert. - Assert.Equal(testElement.ExpectedModel.Id, result.Id); - Assert.Equal(testElement.ExpectedModel.CreationDateTime, result.CreationDateTime); - Assert.Equal(testElement.ExpectedModel.Address, result.Address); - Assert.Equal(testElement.ExpectedModel.PreferredSocNode?.Id, result.PreferredSocNode?.Id); - Assert.NotNull(result.Id); - Assert.NotNull(result.Address); - } } } From 4d5f24c8e39c04bdd7ef26a2b47e7f523a863989 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Tue, 28 Feb 2023 23:06:22 +0100 Subject: [PATCH 12/15] log with logger instead of domain --- .../IBeehiveDbContext.cs | 1 - .../Models/CashoutNodeLog.cs | 38 ------------------- .../Models/NodeLogBase.cs | 31 --------------- .../BeehiveDbContext.cs | 1 - .../ModelMaps/NodeLogMap.cs | 36 ------------------ .../Extensions/LoggerExtensions.cs | 31 +++++++++++++++ .../Tasks/CashoutAllNodesTask.cs | 12 +++--- 7 files changed, 38 insertions(+), 112 deletions(-) delete mode 100644 src/BeehiveManager.Domain/Models/CashoutNodeLog.cs delete mode 100644 src/BeehiveManager.Domain/Models/NodeLogBase.cs delete mode 100644 src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs create mode 100644 src/BeehiveManager.Services/Extensions/LoggerExtensions.cs diff --git a/src/BeehiveManager.Domain/IBeehiveDbContext.cs b/src/BeehiveManager.Domain/IBeehiveDbContext.cs index 4b559ba..76f0f8b 100644 --- a/src/BeehiveManager.Domain/IBeehiveDbContext.cs +++ b/src/BeehiveManager.Domain/IBeehiveDbContext.cs @@ -22,7 +22,6 @@ namespace Etherna.BeehiveManager.Domain public interface IBeehiveDbContext : IDbContext { IRepository BeeNodes { get; } - IRepository NodeLogs { get; } IEventDispatcher EventDispatcher { get; } } diff --git a/src/BeehiveManager.Domain/Models/CashoutNodeLog.cs b/src/BeehiveManager.Domain/Models/CashoutNodeLog.cs deleted file mode 100644 index 7c8bb74..0000000 --- a/src/BeehiveManager.Domain/Models/CashoutNodeLog.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System.Collections.Generic; - -namespace Etherna.BeehiveManager.Domain.Models -{ - public class CashoutNodeLog : NodeLogBase - { - // Constructors. - public CashoutNodeLog( - BeeNode beeNode, - IEnumerable txs, - long totalCashout) - : base(beeNode) - { - Txs = txs; - TotalCashout = totalCashout; - } - protected CashoutNodeLog() { } - - - // Properties. - public virtual long TotalCashout { get; protected set; } - public virtual IEnumerable Txs { get; protected set; } = default!; - } -} diff --git a/src/BeehiveManager.Domain/Models/NodeLogBase.cs b/src/BeehiveManager.Domain/Models/NodeLogBase.cs deleted file mode 100644 index aa0971d..0000000 --- a/src/BeehiveManager.Domain/Models/NodeLogBase.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using System; - -namespace Etherna.BeehiveManager.Domain.Models -{ - public abstract class NodeLogBase : EntityModelBase - { - // Constructors. - protected NodeLogBase(BeeNode node) - { - Node = node ?? throw new ArgumentNullException(nameof(node)); - } - protected NodeLogBase() { } - - // Properties. - public virtual BeeNode Node { get; protected set; } = default!; - } -} diff --git a/src/BeehiveManager.Persistence/BeehiveDbContext.cs b/src/BeehiveManager.Persistence/BeehiveDbContext.cs index 0230ebc..5c44e1f 100644 --- a/src/BeehiveManager.Persistence/BeehiveDbContext.cs +++ b/src/BeehiveManager.Persistence/BeehiveDbContext.cs @@ -59,7 +59,6 @@ public BeehiveDbContext( .Ascending(n => n.Hostname), new CreateIndexOptions { Unique = true }) } }); - public IRepository NodeLogs { get; } = new DomainRepository("nodeLogs"); //other properties public IEventDispatcher EventDispatcher { get; } diff --git a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs b/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs deleted file mode 100644 index 6d44ab9..0000000 --- a/src/BeehiveManager.Persistence/ModelMaps/NodeLogMap.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021-present Etherna Sagl -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -using Etherna.BeehiveManager.Domain.Models; -using Etherna.MongODM.Core; -using Etherna.MongODM.Core.Extensions; -using Etherna.MongODM.Core.Serialization; - -namespace Etherna.BeehiveManager.Persistence.ModelMaps -{ - internal sealed class NodeLogMap : IModelMapsCollector - { - public void Register(IDbContext dbContext) - { - dbContext.MapRegistry.AddModelMap("a1c4d182-b3b2-4d49-8fe1-91d723c1188c", mm => - { - mm.AutoMap(); - - // Set members with custom serializers. - mm.SetMemberSerializer(l => l.Node, BeeNodeMap.ReferenceSerializer(dbContext)); - }); - dbContext.MapRegistry.AddModelMap("625838e6-4290-42e4-a6d5-a6b0e5cf1660"); - } - } -} diff --git a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs new file mode 100644 index 0000000..8268f69 --- /dev/null +++ b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs @@ -0,0 +1,31 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; + +namespace Etherna.BeehiveManager.Services.Extensions +{ + /* + * Always group similar log delegates by type, always use incremental event ids. + * Last event id is: 0 + */ + public static class LoggerExtensions + { + // Fields. + //*** DEBUG LOGS *** + + //*** INFORMATION LOGS *** + private static readonly Action, Exception> _nodeCashedOut = + LoggerMessage.Define>( + LogLevel.Information, + new EventId(0, nameof(NodeCashedOut)), + "Node '{BeeNodeId}' cashed out {TotalCashedOut} with tx hashes {TxHashes}"); + + //*** WARNING LOGS *** + + //*** ERROR LOGS *** + + // Methods. + public static void NodeCashedOut(this ILogger logger, string beeNodeId, long totalCashedOut, IEnumerable txHashes) => + _nodeCashedOut(logger, beeNodeId, totalCashedOut, txHashes, null!); + } +} diff --git a/src/BeehiveManager.Services/Tasks/CashoutAllNodesTask.cs b/src/BeehiveManager.Services/Tasks/CashoutAllNodesTask.cs index e080c5e..e1b0a44 100644 --- a/src/BeehiveManager.Services/Tasks/CashoutAllNodesTask.cs +++ b/src/BeehiveManager.Services/Tasks/CashoutAllNodesTask.cs @@ -14,9 +14,11 @@ using Etherna.BeehiveManager.Domain; using Etherna.BeehiveManager.Domain.Models; +using Etherna.BeehiveManager.Services.Extensions; using Etherna.BeehiveManager.Services.Utilities; using Etherna.BeeNet.Exceptions; using Etherna.MongoDB.Driver; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Net.Http; @@ -33,14 +35,17 @@ public class CashoutAllNodesTask : ICashoutAllNodesTask // Fields. private readonly IBeeNodeLiveManager beeNodeLiveManager; private readonly IBeehiveDbContext context; + private readonly ILogger logger; // Constructors. public CashoutAllNodesTask( IBeeNodeLiveManager beeNodeLiveManager, - IBeehiveDbContext context) + IBeehiveDbContext context, + ILogger logger) { this.beeNodeLiveManager = beeNodeLiveManager; this.context = context; + this.logger = logger; } // Methods. @@ -92,10 +97,7 @@ await context.BeeNodes.AccessToCollectionAsync(collection => collection // Add log. if (totalCashedout > 0) - { - var log = new CashoutNodeLog(node, txs, totalCashedout); - await context.NodeLogs.CreateAsync(log); - } + logger.NodeCashedOut(node.Id, totalCashedout, txs); })); } } From 00c3ef6763930ba284d288497d3ba8eaab150019 Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Wed, 1 Mar 2023 02:36:14 +0100 Subject: [PATCH 13/15] implementing funding task --- .../Extensions/LoggerExtensions.cs | 39 ++++++- .../ServiceCollectionExtensions.cs | 1 + .../Settings/FundNodesSettings.cs | 27 +++++ .../Tasks/FundNodesTask.cs | 104 ++++++++++++++++++ .../Tasks/IFundNodesTask.cs | 11 ++ src/BeehiveManager/Program.cs | 8 ++ .../{Configs => Settings}/SeedDbSettings.cs | 2 +- .../appsettings.Development.json | 10 ++ 8 files changed, 199 insertions(+), 3 deletions(-) create mode 100644 src/BeehiveManager.Services/Settings/FundNodesSettings.cs create mode 100644 src/BeehiveManager.Services/Tasks/FundNodesTask.cs create mode 100644 src/BeehiveManager.Services/Tasks/IFundNodesTask.cs rename src/BeehiveManager/{Configs => Settings}/SeedDbSettings.cs (97%) diff --git a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs index 8268f69..cde86da 100644 --- a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs +++ b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs @@ -1,12 +1,14 @@ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Globalization; +using System.Numerics; namespace Etherna.BeehiveManager.Services.Extensions { /* * Always group similar log delegates by type, always use incremental event ids. - * Last event id is: 0 + * Last event id is: 4 */ public static class LoggerExtensions { @@ -18,14 +20,47 @@ public static class LoggerExtensions LoggerMessage.Define>( LogLevel.Information, new EventId(0, nameof(NodeCashedOut)), - "Node '{BeeNodeId}' cashed out {TotalCashedOut} with tx hashes {TxHashes}"); + "Node {BeeNodeId} cashed out {TotalCashedOut} with tx hashes {TxHashes}"); + + private static readonly Action _succededToFundBzzOnNode = + LoggerMessage.Define( + LogLevel.Information, + new EventId(1, nameof(SuccededToFundBzzOnNode)), + "Node {BeeNodeId} funded with {PlurFunded} PLUR to final {PlurFinal} PLUR"); + + private static readonly Action _succededToFundXDaiOnNode = + LoggerMessage.Define( + LogLevel.Information, + new EventId(3, nameof(SuccededToFundXDaiOnNode)), + "Node {BeeNodeId} funded with {WeiFunded} xDai Wei to final {WeiFinal} xDai Wei"); //*** WARNING LOGS *** //*** ERROR LOGS *** + private static readonly Action _failedToFundBzzOnNode = + LoggerMessage.Define(LogLevel.Error, + new EventId(2, nameof(FailedToFundBzzOnNode)), + "Funding on node {BeeNodeId} failed with tx of {PlurAmount} PLUR"); + + private static readonly Action _failedToFundXDaiOnNode = + LoggerMessage.Define(LogLevel.Error, + new EventId(2, nameof(FailedToFundXDaiOnNode)), + "Funding on node {BeeNodeId} failed with tx of {WeiAmount} xDai Wei"); // Methods. + public static void FailedToFundBzzOnNode(this ILogger logger, string nodeId, BigInteger plurFundAmount, Exception? exception) => + _failedToFundBzzOnNode(logger, nodeId, plurFundAmount.ToString(CultureInfo.InvariantCulture), exception!); + + public static void FailedToFundXDaiOnNode(this ILogger logger, string nodeId, BigInteger weiFundAmount, Exception? exception) => + _failedToFundXDaiOnNode(logger, nodeId, weiFundAmount.ToString(CultureInfo.InvariantCulture), exception!); + public static void NodeCashedOut(this ILogger logger, string beeNodeId, long totalCashedOut, IEnumerable txHashes) => _nodeCashedOut(logger, beeNodeId, totalCashedOut, txHashes, null!); + + public static void SuccededToFundBzzOnNode(this ILogger logger, string nodeId, BigInteger plurFunded, BigInteger plurFinal) => + _succededToFundBzzOnNode(logger, nodeId, plurFunded.ToString(CultureInfo.InvariantCulture), plurFinal.ToString(CultureInfo.InvariantCulture), null!); + + public static void SuccededToFundXDaiOnNode(this ILogger logger, string nodeId, BigInteger weiFunded, BigInteger weiFinal) => + _succededToFundXDaiOnNode(logger, nodeId, weiFunded.ToString(CultureInfo.InvariantCulture), weiFinal.ToString(CultureInfo.InvariantCulture), null!); } } diff --git a/src/BeehiveManager.Services/ServiceCollectionExtensions.cs b/src/BeehiveManager.Services/ServiceCollectionExtensions.cs index 2a27ac8..074d77f 100644 --- a/src/BeehiveManager.Services/ServiceCollectionExtensions.cs +++ b/src/BeehiveManager.Services/ServiceCollectionExtensions.cs @@ -51,6 +51,7 @@ where t.GetInterfaces().Contains(typeof(IEventHandler)) // Tasks. services.AddTransient(); + services.AddTransient(); services.AddTransient(); } } diff --git a/src/BeehiveManager.Services/Settings/FundNodesSettings.cs b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs new file mode 100644 index 0000000..624a791 --- /dev/null +++ b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs @@ -0,0 +1,27 @@ +namespace Etherna.BeehiveManager.Services.Settings +{ + public class FundNodesSettings + { + // Consts. + public const string ConfigPosition = "FundNodes"; + + // Properties. + public long? ChainId { get; set; } + public string? ChestPrivateKey { get; set; } + public int? BzzMinTrigger { get; set; } + public int? BzzTargetAmount { get; set; } + public string? RPCEndpoint { get; set; } + public bool RunBzzFunding => ChainId.HasValue && + ChestPrivateKey is not null && + RPCEndpoint is not null && + BzzMinTrigger.HasValue && + BzzTargetAmount > BzzMinTrigger; + public bool RunXdaiFunding => ChainId.HasValue && + ChestPrivateKey is not null && + RPCEndpoint is not null && + XDaiMinTrigger.HasValue && + XDaiTargetAmount > XDaiMinTrigger; + public int? XDaiMinTrigger { get; set; } + public int? XDaiTargetAmount { get; set; } + } +} diff --git a/src/BeehiveManager.Services/Tasks/FundNodesTask.cs b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs new file mode 100644 index 0000000..01f459d --- /dev/null +++ b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs @@ -0,0 +1,104 @@ +using Etherna.BeehiveManager.Services.Extensions; +using Etherna.BeehiveManager.Services.Settings; +using Etherna.BeehiveManager.Services.Utilities; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Nethereum.Web3.Accounts; +using System; +using System.Numerics; +using System.Threading.Tasks; + +namespace Etherna.BeehiveManager.Services.Tasks +{ + public class FundNodesTask : IFundNodesTask + { + // Consts. + public const string TaskId = "fundNodesTask"; + + // Fields. + private readonly IBeeNodeLiveManager liveManager; + private readonly ILogger logger; + private readonly FundNodesSettings options; + + // Constructor. + public FundNodesTask( + IBeeNodeLiveManager liveManager, + ILogger logger, + IOptions options) + { + if (options is null) + throw new ArgumentNullException(nameof(options)); + + this.liveManager = liveManager; + this.logger = logger; + this.options = options.Value; + } + + // Methods. + public async Task RunAsync() + { + if (!options.RunBzzFunding && !options.RunXdaiFunding) + return; + + var chestAccount = new Account(options.ChestPrivateKey, options.ChainId); + + // For each node, even if actually offline. + foreach (var node in liveManager.AllNodes) + { + // Bzz funding. + if (options.RunBzzFunding) + { + // Get node amount. + BigInteger nodeAmount = 0; + //TODO + + // Fund node. + if (nodeAmount < options.BzzMinTrigger) + { + BigInteger funded = 0; + try + { + //TODO + + logger.SuccededToFundBzzOnNode(node.Id, funded, nodeAmount + funded); + } + catch (Exception ex) //TODO + { + + + logger.FailedToFundBzzOnNode(node.Id, funded, ex); + } + } + + } + + // xDai funding. + if (options.RunXdaiFunding) + { + // Get node amount. + BigInteger nodeAmount = 0; + //TODO + + // Fund node. + if (nodeAmount < options.XDaiMinTrigger) + { + BigInteger funded = 0; + try + { + //TODO + + logger.SuccededToFundXDaiOnNode(node.Id, funded, nodeAmount + funded); + } + catch (Exception ex) //TODO + { + + + logger.FailedToFundXDaiOnNode(node.Id, funded, ex); + } + } + + } + } + } + } +} diff --git a/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs b/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs new file mode 100644 index 0000000..99fa76f --- /dev/null +++ b/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs @@ -0,0 +1,11 @@ +using Hangfire; +using System.Threading.Tasks; + +namespace Etherna.BeehiveManager.Services.Tasks +{ + public interface IFundNodesTask + { + [Queue(Queues.NODE_MAINTENANCE)] + Task RunAsync(); + } +} \ No newline at end of file diff --git a/src/BeehiveManager/Program.cs b/src/BeehiveManager/Program.cs index 0807340..6131783 100644 --- a/src/BeehiveManager/Program.cs +++ b/src/BeehiveManager/Program.cs @@ -22,7 +22,9 @@ using Etherna.BeehiveManager.Extensions; using Etherna.BeehiveManager.Persistence; using Etherna.BeehiveManager.Services; +using Etherna.BeehiveManager.Services.Settings; using Etherna.BeehiveManager.Services.Tasks; +using Etherna.BeehiveManager.Settings; using Etherna.DomainEvents; using Etherna.MongODM; using Etherna.MongODM.AspNetCore.UI; @@ -188,6 +190,7 @@ private static void ConfigureServices(WebApplicationBuilder builder) }); // Configure setting. + services.Configure(config.GetSection(FundNodesSettings.ConfigPosition)); services.Configure(config.GetSection(SeedDbSettings.ConfigPosition)); // Configure Hangfire and persistence. @@ -265,6 +268,11 @@ private static void ConfigureApplication(WebApplication app) app.MapRazorPages(); // Register cron tasks. + RecurringJob.AddOrUpdate( + FundNodesTask.TaskId, + task => task.RunAsync(), + "5 * * * *"); //at 05 every hour + RecurringJob.AddOrUpdate( CashoutAllNodesTask.TaskId, task => task.RunAsync(), diff --git a/src/BeehiveManager/Configs/SeedDbSettings.cs b/src/BeehiveManager/Settings/SeedDbSettings.cs similarity index 97% rename from src/BeehiveManager/Configs/SeedDbSettings.cs rename to src/BeehiveManager/Settings/SeedDbSettings.cs index 8031a57..8688145 100644 --- a/src/BeehiveManager/Configs/SeedDbSettings.cs +++ b/src/BeehiveManager/Settings/SeedDbSettings.cs @@ -14,7 +14,7 @@ using System; -namespace Etherna.BeehiveManager.Configs +namespace Etherna.BeehiveManager.Settings { #pragma warning disable CA1034 // Nested types should not be visible #pragma warning disable CA1819 // Properties should not return arrays diff --git a/src/BeehiveManager/appsettings.Development.json b/src/BeehiveManager/appsettings.Development.json index 568659e..b187a4f 100644 --- a/src/BeehiveManager/appsettings.Development.json +++ b/src/BeehiveManager/appsettings.Development.json @@ -9,6 +9,16 @@ "Urls": [ "http://localhost:9200" ] + }, + + "FundNodes": { + "ChainId": 100, //Gnosis + "ChestPrivateKey": "", + "BzzMinTrigger": 50, + "BzzTargetAmount": 250, + "RPCEndpoint": "localhost", + "XDaiMinTrigger": 5, + "XDaiTargetAmount": 25 } //"SeedDb": { From ea208bf58e075157f1e7483f7ce6fff4f7c7d4fd Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Wed, 1 Mar 2023 21:41:39 +0100 Subject: [PATCH 14/15] implement task --- .../BeehiveManager.Domain.csproj | 2 +- .../BeehiveManager.Services.csproj | 1 + .../Extensions/LoggerExtensions.cs | 42 +++--- .../Settings/FundNodesSettings.cs | 19 +-- .../Tasks/FundNodesTask.cs | 127 ++++++++++++++---- .../appsettings.Development.json | 22 +-- .../appsettings.Production.json | 5 + 7 files changed, 149 insertions(+), 69 deletions(-) diff --git a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj index a585d7f..2c247d8 100644 --- a/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj +++ b/src/BeehiveManager.Domain/BeehiveManager.Domain.csproj @@ -15,7 +15,7 @@ - + diff --git a/src/BeehiveManager.Services/BeehiveManager.Services.csproj b/src/BeehiveManager.Services/BeehiveManager.Services.csproj index 3a29b7a..4e8aeee 100644 --- a/src/BeehiveManager.Services/BeehiveManager.Services.csproj +++ b/src/BeehiveManager.Services/BeehiveManager.Services.csproj @@ -16,6 +16,7 @@ + diff --git a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs index cde86da..7d8d324 100644 --- a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs +++ b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs @@ -1,8 +1,6 @@ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; -using System.Globalization; -using System.Numerics; namespace Etherna.BeehiveManager.Services.Extensions { @@ -22,45 +20,45 @@ public static class LoggerExtensions new EventId(0, nameof(NodeCashedOut)), "Node {BeeNodeId} cashed out {TotalCashedOut} with tx hashes {TxHashes}"); - private static readonly Action _succededToFundBzzOnNode = - LoggerMessage.Define( + private static readonly Action _succededToFundBzzOnNode = + LoggerMessage.Define( LogLevel.Information, new EventId(1, nameof(SuccededToFundBzzOnNode)), - "Node {BeeNodeId} funded with {PlurFunded} PLUR to final {PlurFinal} PLUR"); + "Node {BeeNodeId} funded with {BzzFunded} BZZ to total {BzzTotal} BZZ. Tx hash {TxHash}"); - private static readonly Action _succededToFundXDaiOnNode = - LoggerMessage.Define( + private static readonly Action _succededToFundXDaiOnNode = + LoggerMessage.Define( LogLevel.Information, new EventId(3, nameof(SuccededToFundXDaiOnNode)), - "Node {BeeNodeId} funded with {WeiFunded} xDai Wei to final {WeiFinal} xDai Wei"); + "Node {BeeNodeId} funded with {XDaiFunded} xDai to total {XDaiTotal} xDai. Tx hash {TxHash}"); //*** WARNING LOGS *** //*** ERROR LOGS *** - private static readonly Action _failedToFundBzzOnNode = - LoggerMessage.Define(LogLevel.Error, + private static readonly Action _failedToFundBzzOnNode = + LoggerMessage.Define(LogLevel.Error, new EventId(2, nameof(FailedToFundBzzOnNode)), - "Funding on node {BeeNodeId} failed with tx of {PlurAmount} PLUR"); + "Funding on node {BeeNodeId} failed with {BzzAmount} BZZ. Tx hash {TxHash}"); - private static readonly Action _failedToFundXDaiOnNode = - LoggerMessage.Define(LogLevel.Error, + private static readonly Action _failedToFundXDaiOnNode = + LoggerMessage.Define(LogLevel.Error, new EventId(2, nameof(FailedToFundXDaiOnNode)), - "Funding on node {BeeNodeId} failed with tx of {WeiAmount} xDai Wei"); + "Funding on node {BeeNodeId} failed with {XDaiAmount} xDai. Tx hash {TxHash}"); // Methods. - public static void FailedToFundBzzOnNode(this ILogger logger, string nodeId, BigInteger plurFundAmount, Exception? exception) => - _failedToFundBzzOnNode(logger, nodeId, plurFundAmount.ToString(CultureInfo.InvariantCulture), exception!); + public static void FailedToFundBzzOnNode(this ILogger logger, string nodeId, decimal bzzFundAmount, string? txHash, Exception? exception) => + _failedToFundBzzOnNode(logger, nodeId, bzzFundAmount, txHash, exception!); - public static void FailedToFundXDaiOnNode(this ILogger logger, string nodeId, BigInteger weiFundAmount, Exception? exception) => - _failedToFundXDaiOnNode(logger, nodeId, weiFundAmount.ToString(CultureInfo.InvariantCulture), exception!); + public static void FailedToFundXDaiOnNode(this ILogger logger, string nodeId, decimal xDaiFundAmount, string? txHash, Exception? exception) => + _failedToFundXDaiOnNode(logger, nodeId, xDaiFundAmount, txHash, exception!); public static void NodeCashedOut(this ILogger logger, string beeNodeId, long totalCashedOut, IEnumerable txHashes) => _nodeCashedOut(logger, beeNodeId, totalCashedOut, txHashes, null!); - public static void SuccededToFundBzzOnNode(this ILogger logger, string nodeId, BigInteger plurFunded, BigInteger plurFinal) => - _succededToFundBzzOnNode(logger, nodeId, plurFunded.ToString(CultureInfo.InvariantCulture), plurFinal.ToString(CultureInfo.InvariantCulture), null!); + public static void SuccededToFundBzzOnNode(this ILogger logger, string nodeId, decimal bzzFunded, decimal bzzTotal, string txHash) => + _succededToFundBzzOnNode(logger, nodeId, bzzFunded, bzzTotal, txHash, null!); - public static void SuccededToFundXDaiOnNode(this ILogger logger, string nodeId, BigInteger weiFunded, BigInteger weiFinal) => - _succededToFundXDaiOnNode(logger, nodeId, weiFunded.ToString(CultureInfo.InvariantCulture), weiFinal.ToString(CultureInfo.InvariantCulture), null!); + public static void SuccededToFundXDaiOnNode(this ILogger logger, string nodeId, decimal xDaiFunded, decimal xDaiTotal, string txHash) => + _succededToFundXDaiOnNode(logger, nodeId, xDaiFunded, xDaiTotal, txHash, null!); } } diff --git a/src/BeehiveManager.Services/Settings/FundNodesSettings.cs b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs index 624a791..3b0dd43 100644 --- a/src/BeehiveManager.Services/Settings/FundNodesSettings.cs +++ b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs @@ -6,22 +6,25 @@ public class FundNodesSettings public const string ConfigPosition = "FundNodes"; // Properties. + public string? BzzContractAddress { get; set; } + public decimal? BzzMinTrigger { get; set; } + public decimal? BzzTargetAmount { get; set; } public long? ChainId { get; set; } public string? ChestPrivateKey { get; set; } - public int? BzzMinTrigger { get; set; } - public int? BzzTargetAmount { get; set; } public string? RPCEndpoint { get; set; } - public bool RunBzzFunding => ChainId.HasValue && + public bool RunBzzFunding => BzzContractAddress is not null && + ChainId.HasValue && ChestPrivateKey is not null && - RPCEndpoint is not null && + (RPCEndpoint is not null || WebsocketEndpoint is not null) && BzzMinTrigger.HasValue && BzzTargetAmount > BzzMinTrigger; - public bool RunXdaiFunding => ChainId.HasValue && + public bool RunXDaiFunding => ChainId.HasValue && ChestPrivateKey is not null && - RPCEndpoint is not null && + (RPCEndpoint is not null || WebsocketEndpoint is not null) && XDaiMinTrigger.HasValue && XDaiTargetAmount > XDaiMinTrigger; - public int? XDaiMinTrigger { get; set; } - public int? XDaiTargetAmount { get; set; } + public decimal? XDaiMinTrigger { get; set; } + public decimal? XDaiTargetAmount { get; set; } + public string? WebsocketEndpoint { get; set; } } } diff --git a/src/BeehiveManager.Services/Tasks/FundNodesTask.cs b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs index 01f459d..d584f0e 100644 --- a/src/BeehiveManager.Services/Tasks/FundNodesTask.cs +++ b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs @@ -3,22 +3,34 @@ using Etherna.BeehiveManager.Services.Utilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Nethereum.Contracts.Standards.ERC20.ContractDefinition; +using Nethereum.JsonRpc.Client; +using Nethereum.JsonRpc.WebSocketClient; +using Nethereum.RPC.Eth.DTOs; +using Nethereum.Web3; using Nethereum.Web3.Accounts; using System; +using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Threading.Tasks; namespace Etherna.BeehiveManager.Services.Tasks { - public class FundNodesTask : IFundNodesTask + public class FundNodesTask : IFundNodesTask, IDisposable { // Consts. public const string TaskId = "fundNodesTask"; + private const int BzzDecimalPlaces = 16; + // Fields. + private bool disposed; + private readonly bool isEnabled; private readonly IBeeNodeLiveManager liveManager; private readonly ILogger logger; private readonly FundNodesSettings options; + private readonly Web3? tresureChestWeb3; + private readonly WebSocketClient? websocketClient; // Constructor. public FundNodesTask( @@ -32,71 +44,130 @@ public FundNodesTask( this.liveManager = liveManager; this.logger = logger; this.options = options.Value; + + if (this.options.RunBzzFunding || this.options.RunXDaiFunding) + { + isEnabled = true; + if (this.options.WebsocketEndpoint is not null) + { + websocketClient = new WebSocketClient(this.options.WebsocketEndpoint); + tresureChestWeb3 = new Web3(new Account(this.options.ChestPrivateKey, this.options.ChainId), websocketClient); + } + else if (this.options.RPCEndpoint is not null) + { + var rpcClient = new RpcClient(new Uri(this.options.RPCEndpoint)); + tresureChestWeb3 = new Web3(new Account(this.options.ChestPrivateKey, this.options.ChainId), rpcClient); + } + else throw new InvalidOperationException(); + } + else isEnabled = false; + } + + // Dispose. + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposed) return; + + // Dispose managed resources. + if (disposing) + websocketClient?.Dispose(); + + disposed = true; } // Methods. + [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Each exception needs to be catched and logged without stop task")] public async Task RunAsync() { - if (!options.RunBzzFunding && !options.RunXdaiFunding) + if (!isEnabled) return; - var chestAccount = new Account(options.ChestPrivateKey, options.ChainId); - // For each node, even if actually offline. foreach (var node in liveManager.AllNodes) { + if (node.Status.Addresses is null) + continue; + // Bzz funding. if (options.RunBzzFunding) { // Get node amount. - BigInteger nodeAmount = 0; - //TODO + decimal? bzzNodeAmount = null; + try + { + var balanceOfFunctionMessage = new BalanceOfFunction() + { + Owner = node.Status.Addresses.Ethereum + }; + var balanceHandler = tresureChestWeb3!.Eth.GetContractQueryHandler(); + var plurBalance = await balanceHandler.QueryAsync(options.BzzContractAddress, balanceOfFunctionMessage); + bzzNodeAmount = Web3.Convert.FromWei(plurBalance, 16); + } + catch { } // Fund node. - if (nodeAmount < options.BzzMinTrigger) + if (bzzNodeAmount < options.BzzMinTrigger) { - BigInteger funded = 0; + var bzzFundAmount = options.BzzTargetAmount!.Value - bzzNodeAmount.Value; try { - //TODO - - logger.SuccededToFundBzzOnNode(node.Id, funded, nodeAmount + funded); + var transferHandler = tresureChestWeb3!.Eth.GetContractTransactionHandler(); + var transferFunctionMessage = new TransferFunction() + { + To = node.Status.Addresses.Ethereum, + Value = Web3.Convert.ToWei(bzzFundAmount, BzzDecimalPlaces) + }; + var tx = await transferHandler.SendRequestAndWaitForReceiptAsync(options.BzzContractAddress, transferFunctionMessage); + + if (tx.Succeeded()) + logger.SuccededToFundBzzOnNode(node.Id, bzzFundAmount, bzzNodeAmount.Value + bzzFundAmount, tx.TransactionHash); + else + logger.FailedToFundBzzOnNode(node.Id, bzzFundAmount, tx.TransactionHash, null); } - catch (Exception ex) //TODO + catch (Exception ex) { - - - logger.FailedToFundBzzOnNode(node.Id, funded, ex); + logger.FailedToFundBzzOnNode(node.Id, bzzFundAmount, null, ex); } } - } // xDai funding. - if (options.RunXdaiFunding) + if (options.RunXDaiFunding) { // Get node amount. - BigInteger nodeAmount = 0; - //TODO + decimal? xDaiNodeAmount = null; + try + { + var weiBalance = await tresureChestWeb3!.Eth.GetBalance.SendRequestAsync(node.Status.Addresses.Ethereum); + xDaiNodeAmount = Web3.Convert.FromWei(weiBalance); + } + catch { } // Fund node. - if (nodeAmount < options.XDaiMinTrigger) + if (xDaiNodeAmount < options.XDaiMinTrigger) { - BigInteger funded = 0; + var xDaiFundAmount = options.XDaiTargetAmount!.Value - xDaiNodeAmount.Value; try { - //TODO + var tx = await tresureChestWeb3!.Eth.GetEtherTransferService() + .TransferEtherAndWaitForReceiptAsync(node.Status.Addresses.Ethereum, xDaiFundAmount); - logger.SuccededToFundXDaiOnNode(node.Id, funded, nodeAmount + funded); + if (tx.Succeeded()) + logger.SuccededToFundXDaiOnNode(node.Id, xDaiFundAmount, xDaiNodeAmount.Value + xDaiFundAmount, tx.TransactionHash); + else + logger.FailedToFundXDaiOnNode(node.Id, xDaiFundAmount, tx.TransactionHash, null); } - catch (Exception ex) //TODO + catch (Exception ex) { - - - logger.FailedToFundXDaiOnNode(node.Id, funded, ex); + logger.FailedToFundXDaiOnNode(node.Id, xDaiFundAmount, null, ex); } } - } } } diff --git a/src/BeehiveManager/appsettings.Development.json b/src/BeehiveManager/appsettings.Development.json index b187a4f..f39a8a8 100644 --- a/src/BeehiveManager/appsettings.Development.json +++ b/src/BeehiveManager/appsettings.Development.json @@ -9,18 +9,20 @@ "Urls": [ "http://localhost:9200" ] - }, - - "FundNodes": { - "ChainId": 100, //Gnosis - "ChestPrivateKey": "", - "BzzMinTrigger": 50, - "BzzTargetAmount": 250, - "RPCEndpoint": "localhost", - "XDaiMinTrigger": 5, - "XDaiTargetAmount": 25 } + //"FundNodes": { + // "ChainId": 100, //Gnosis + // "ChestPrivateKey": "", + // "BzzContractAddress": "0xdbf3ea6f5bee45c02255b2c26a16f300502f68da", //Gnosis + // "BzzMinTrigger": 2, + // "BzzTargetAmount": 3, + // //"RPCEndpoint": "http://localhost:8545", //use as alternative of WS + // "XDaiMinTrigger": 1, + // "XDaiTargetAmount": 2, + // "WebsocketEndpoint": "ws://localhost:8546" + //} + //"SeedDb": { // "BeeNodes": [ // { diff --git a/src/BeehiveManager/appsettings.Production.json b/src/BeehiveManager/appsettings.Production.json index 2905b51..62fbfe4 100644 --- a/src/BeehiveManager/appsettings.Production.json +++ b/src/BeehiveManager/appsettings.Production.json @@ -1,4 +1,9 @@ { + "FundNodes": { + "ChainId": 100, //Gnosis + "BzzContractAddress": "0xdbf3ea6f5bee45c02255b2c26a16f300502f68da" //Gnosis + }, + "Elastic": { "Urls": [ "http://elastic00:9200", From 46b75635d70ba28182d0e30dfbc3762a2f86cd4a Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Wed, 1 Mar 2023 21:44:41 +0100 Subject: [PATCH 15/15] add license headers --- .../Domain/BeeNodeService.cs | 16 +++++++++++++++- .../Domain/IBeeNodeService.cs | 16 +++++++++++++++- .../Extensions/LoggerExtensions.cs | 16 +++++++++++++++- .../Settings/FundNodesSettings.cs | 16 +++++++++++++++- .../Tasks/FundNodesTask.cs | 16 +++++++++++++++- .../Tasks/IFundNodesTask.cs | 16 +++++++++++++++- .../Api/Controllers/EtherAddressesController.cs | 16 +++++++++++++++- .../Areas/Api/DtoModels/EtherAddressDto.cs | 16 +++++++++++++++- src/BeehiveManager/Pages/Index.cshtml | 17 ++++++++++++++++- src/BeehiveManager/Pages/Index.cshtml.cs | 16 +++++++++++++++- src/BeehiveManager/Pages/Shared/_Layout.cshtml | 17 ++++++++++++++++- .../Shared/_ValidationScriptsPartial.cshtml | 17 ++++++++++++++++- src/BeehiveManager/Pages/_ViewImports.cshtml | 17 ++++++++++++++++- src/BeehiveManager/Pages/_ViewStart.cshtml | 17 ++++++++++++++++- 14 files changed, 215 insertions(+), 14 deletions(-) diff --git a/src/BeehiveManager.Services/Domain/BeeNodeService.cs b/src/BeehiveManager.Services/Domain/BeeNodeService.cs index ab47225..470afdc 100644 --- a/src/BeehiveManager.Services/Domain/BeeNodeService.cs +++ b/src/BeehiveManager.Services/Domain/BeeNodeService.cs @@ -1,4 +1,18 @@ -using Etherna.BeehiveManager.Domain; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Etherna.BeehiveManager.Domain; using Etherna.BeehiveManager.Domain.Models; using Etherna.BeehiveManager.Services.Utilities; using Etherna.BeehiveManager.Services.Utilities.Models; diff --git a/src/BeehiveManager.Services/Domain/IBeeNodeService.cs b/src/BeehiveManager.Services/Domain/IBeeNodeService.cs index 96acd59..d6cb8ae 100644 --- a/src/BeehiveManager.Services/Domain/IBeeNodeService.cs +++ b/src/BeehiveManager.Services/Domain/IBeeNodeService.cs @@ -1,4 +1,18 @@ -using Etherna.BeehiveManager.Domain.Models; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Etherna.BeehiveManager.Domain.Models; using System.Threading.Tasks; namespace Etherna.BeehiveManager.Services.Domain diff --git a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs index 7d8d324..ac63ab3 100644 --- a/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs +++ b/src/BeehiveManager.Services/Extensions/LoggerExtensions.cs @@ -1,4 +1,18 @@ -using Microsoft.Extensions.Logging; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; diff --git a/src/BeehiveManager.Services/Settings/FundNodesSettings.cs b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs index 3b0dd43..f24959b 100644 --- a/src/BeehiveManager.Services/Settings/FundNodesSettings.cs +++ b/src/BeehiveManager.Services/Settings/FundNodesSettings.cs @@ -1,4 +1,18 @@ -namespace Etherna.BeehiveManager.Services.Settings +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Etherna.BeehiveManager.Services.Settings { public class FundNodesSettings { diff --git a/src/BeehiveManager.Services/Tasks/FundNodesTask.cs b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs index d584f0e..4940dce 100644 --- a/src/BeehiveManager.Services/Tasks/FundNodesTask.cs +++ b/src/BeehiveManager.Services/Tasks/FundNodesTask.cs @@ -1,4 +1,18 @@ -using Etherna.BeehiveManager.Services.Extensions; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Etherna.BeehiveManager.Services.Extensions; using Etherna.BeehiveManager.Services.Settings; using Etherna.BeehiveManager.Services.Utilities; using Microsoft.Extensions.Logging; diff --git a/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs b/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs index 99fa76f..63a1f60 100644 --- a/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs +++ b/src/BeehiveManager.Services/Tasks/IFundNodesTask.cs @@ -1,4 +1,18 @@ -using Hangfire; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Hangfire; using System.Threading.Tasks; namespace Etherna.BeehiveManager.Services.Tasks diff --git a/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs b/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs index f699c7d..d612ed5 100644 --- a/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs +++ b/src/BeehiveManager/Areas/Api/Controllers/EtherAddressesController.cs @@ -1,4 +1,18 @@ -using Etherna.BeehiveManager.Areas.Api.DtoModels; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Etherna.BeehiveManager.Areas.Api.DtoModels; using Etherna.BeehiveManager.Attributes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; diff --git a/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs b/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs index 50540b4..6f2c6d0 100644 --- a/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs +++ b/src/BeehiveManager/Areas/Api/DtoModels/EtherAddressDto.cs @@ -1,4 +1,18 @@ -using System; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using System; namespace Etherna.BeehiveManager.Areas.Api.DtoModels { diff --git a/src/BeehiveManager/Pages/Index.cshtml b/src/BeehiveManager/Pages/Index.cshtml index aed10b2..6e0441b 100644 --- a/src/BeehiveManager/Pages/Index.cshtml +++ b/src/BeehiveManager/Pages/Index.cshtml @@ -1,4 +1,19 @@ -@page +@* Copyright 2021-present Etherna Sagl + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *@ + +@page @using Etherna.BeehiveManager.Configs @model IndexModel @{ diff --git a/src/BeehiveManager/Pages/Index.cshtml.cs b/src/BeehiveManager/Pages/Index.cshtml.cs index 96f3295..b1f66ca 100644 --- a/src/BeehiveManager/Pages/Index.cshtml.cs +++ b/src/BeehiveManager/Pages/Index.cshtml.cs @@ -1,4 +1,18 @@ -using Microsoft.AspNetCore.Mvc.RazorPages; +// Copyright 2021-present Etherna Sagl +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +using Microsoft.AspNetCore.Mvc.RazorPages; namespace Etherna.BeehiveManager.Pages { diff --git a/src/BeehiveManager/Pages/Shared/_Layout.cshtml b/src/BeehiveManager/Pages/Shared/_Layout.cshtml index 05bc694..a3aee45 100644 --- a/src/BeehiveManager/Pages/Shared/_Layout.cshtml +++ b/src/BeehiveManager/Pages/Shared/_Layout.cshtml @@ -1,4 +1,19 @@ - +@* Copyright 2021-present Etherna Sagl + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *@ + + diff --git a/src/BeehiveManager/Pages/Shared/_ValidationScriptsPartial.cshtml b/src/BeehiveManager/Pages/Shared/_ValidationScriptsPartial.cshtml index 5a16d80..dc5d586 100644 --- a/src/BeehiveManager/Pages/Shared/_ValidationScriptsPartial.cshtml +++ b/src/BeehiveManager/Pages/Shared/_ValidationScriptsPartial.cshtml @@ -1,2 +1,17 @@ - +@* Copyright 2021-present Etherna Sagl + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *@ + + diff --git a/src/BeehiveManager/Pages/_ViewImports.cshtml b/src/BeehiveManager/Pages/_ViewImports.cshtml index b982504..ec1302f 100644 --- a/src/BeehiveManager/Pages/_ViewImports.cshtml +++ b/src/BeehiveManager/Pages/_ViewImports.cshtml @@ -1,3 +1,18 @@ -@using Etherna.BeehiveManager +@* Copyright 2021-present Etherna Sagl + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *@ + +@using Etherna.BeehiveManager @namespace Etherna.BeehiveManager.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/BeehiveManager/Pages/_ViewStart.cshtml b/src/BeehiveManager/Pages/_ViewStart.cshtml index a5f1004..edd85d1 100644 --- a/src/BeehiveManager/Pages/_ViewStart.cshtml +++ b/src/BeehiveManager/Pages/_ViewStart.cshtml @@ -1,3 +1,18 @@ -@{ +@* Copyright 2021-present Etherna Sagl + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *@ + +@{ Layout = "_Layout"; }