├── .gitignore ├── README.md ├── Servermore.Cli ├── .config │ └── dotnet-tools.json ├── Program.cs └── Servermore.Cli.csproj ├── Servermore.Contracts ├── EndpointFunctionAttribute.cs ├── FunctionAttribute.cs ├── FunctionServiceConfigurationAttribute.cs └── Servermore.Contracts.csproj ├── Servermore.Sdk ├── IFunctionLogger.cs └── Servermore.Sdk.csproj ├── Servermore.Server ├── Controllers │ └── OrchestrationController.cs ├── Loader │ ├── EndpointFunctionLoader.cs │ ├── FunctionLoadContext.cs │ └── FunctionLoaderExtensions.cs ├── Models │ └── FunctionInfo.cs ├── OrchestratorStartup.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Servermore.Server.csproj ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── Servermore.sln └── samples ├── Sample.QuickApi ├── Quickie.cs └── Sample.QuickApi.csproj └── Servermore.ApiSample ├── ExampleFunctions.cs ├── IMetricsCollector.cs └── Servermore.ApiSample.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc 262 | /obj/ 263 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Servermore 2 | A Serverless framework written in .NET Core. Spoiler alert, it needs a server 3 | -------------------------------------------------------------------------------- /Servermore.Cli/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "servermore.cli": { 6 | "version": "1.0.2", 7 | "commands": [ 8 | "servermore" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Servermore.Cli/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text.Json; 6 | using System.Text.Json.Serialization; 7 | using System.Threading.Tasks; 8 | 9 | namespace Servermore.Cli 10 | { 11 | class Program 12 | { 13 | static async Task Main(string[] args) 14 | { 15 | //TODO commands 16 | 17 | //1. dotnet servermore pack 18 | // - Build the project 19 | // - Pick the artifacts and the dependency dlls 20 | // - Package them up in a zip 21 | 22 | //2. dotnet servermore deploy --local 23 | // - Will pack and paste the zip at the specified directory 24 | 25 | //3. dotnet servermore deploy --remote 26 | // - Will pack and upload the zip at the specified Servermore server 27 | 28 | //Testing around 29 | 30 | var command = args[0]; 31 | var url = args[1]; 32 | 33 | var httpClient = new HttpClient(); 34 | switch (command) 35 | { 36 | case "deploy": 37 | { 38 | var functionName = args[2]; 39 | Console.WriteLine($"Deploying Servermore function {functionName}"); 40 | await using var fileStream = File.OpenRead($"F:\\lab\\Servermore\\samples\\{functionName}\\bin\\Debug\\netcoreapp3.1\\{functionName}.dll"); 41 | await httpClient.PostAsync($"{url}/orchestrator/upload?functionName={WebUtility.UrlEncode(functionName)}", new StreamContent(fileStream)); 42 | Console.WriteLine($"{functionName} function deployed successfully"); 43 | break; 44 | } 45 | case "unload": 46 | var functionNameToUnload = args[2]; 47 | Console.WriteLine($"Unloading Servermore function {functionNameToUnload}"); 48 | await httpClient.GetAsync($"{url}/orchestrator/unload?functionName={WebUtility.UrlEncode(functionNameToUnload)}"); 49 | Console.WriteLine($"{functionNameToUnload} function unloaded successfully"); 50 | break; 51 | case "ls": 52 | var response = await httpClient.GetStringAsync($"{url}/orchestrator/functions"); 53 | var desir = JsonSerializer.Deserialize(response); 54 | 55 | Console.WriteLine(JsonSerializer.Serialize(desir, new JsonSerializerOptions 56 | { 57 | WriteIndented = true 58 | })); 59 | break; 60 | default: 61 | return; 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Servermore.Cli/Servermore.Cli.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | 1.0.2 6 | netcoreapp3.1 7 | true 8 | servermore 9 | ./nupkg 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Servermore.Contracts/EndpointFunctionAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace Servermore.Contracts 2 | { 3 | public class EndpointFunctionAttribute : FunctionAttribute 4 | { 5 | public string Route { get; } 6 | 7 | public EndpointFunctionAttribute(string functionName, string route) : base(functionName) 8 | { 9 | Route = route; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Servermore.Contracts/FunctionAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Servermore.Contracts 4 | { 5 | [AttributeUsage(AttributeTargets.Method)] 6 | public class FunctionAttribute : Attribute 7 | { 8 | public string Name { get; } 9 | 10 | public FunctionAttribute(string functionName) 11 | { 12 | Name = functionName; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Servermore.Contracts/FunctionServiceConfigurationAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Servermore.Contracts 4 | { 5 | [AttributeUsage(AttributeTargets.Method)] 6 | public class FunctionServiceConfigurationAttribute : Attribute 7 | { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Servermore.Contracts/Servermore.Contracts.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Servermore.Sdk/IFunctionLogger.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | 3 | namespace Servermore.Sdk 4 | { 5 | public interface IFunctionLogger 6 | { 7 | void Log(string message); 8 | } 9 | 10 | public class FunctionLogger : IFunctionLogger 11 | { 12 | private readonly ILogger _logger; 13 | 14 | public FunctionLogger(ILogger logger) 15 | { 16 | _logger = logger; 17 | } 18 | 19 | public void Log(string message) 20 | { 21 | _logger.LogInformation(message); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Servermore.Sdk/Servermore.Sdk.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Servermore.Server/Controllers/OrchestrationController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.NetworkInformation; 7 | using System.Reflection; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | using Microsoft.AspNetCore.Mvc; 11 | using Microsoft.Extensions.Configuration; 12 | using Microsoft.Extensions.DependencyInjection; 13 | using Microsoft.Extensions.Hosting; 14 | using Servermore.Contracts; 15 | using Servermore.Server.Loader; 16 | using Servermore.Server.Models; 17 | 18 | namespace Servermore.Server.Controllers 19 | { 20 | public class OrchestrationController : ControllerBase 21 | { 22 | // private readonly IHost _functionRunnerHost; 23 | // 24 | // public OrchestrationController(IHost functionRunnerHost) 25 | // { 26 | // _functionRunnerHost = functionRunnerHost; 27 | // } 28 | 29 | [HttpGet("orchestrator/restart")] 30 | public async Task RestartFunctionRunner() 31 | { 32 | //TODO inject this 33 | await Program.FunctionRunnerHost.StopAsync(); 34 | await Program.FunctionRunnerHost.WaitForShutdownAsync(); 35 | // while (!Program.ArePortsAvailable(5000, 5001)) 36 | // { 37 | // await Task.Delay(500); 38 | // } 39 | Program.FunctionRunnerHost = Program.CreateServerHostBuilder(Program.Args).Build(); 40 | await Program.FunctionRunnerHost.StartAsync(); 41 | return Ok(); 42 | } 43 | 44 | [HttpPost("orchestrator/upload")] 45 | public async Task UploadFunction([FromQuery] string functionName) 46 | { 47 | var configuration = HttpContext.RequestServices.GetRequiredService(); 48 | 49 | await using var ms = new MemoryStream(); 50 | await HttpContext.Request.Body.CopyToAsync(ms); 51 | await System.IO.File.WriteAllBytesAsync( 52 | Path.Combine(configuration.GetValue("FunctionLoader:FunctionDirectory"), functionName, $"{functionName}.dll"), 53 | ms.ToArray()); 54 | //TODO inject this 55 | await Program.FunctionRunnerHost.StopAsync(); 56 | await Program.FunctionRunnerHost.WaitForShutdownAsync(); 57 | 58 | // while (!Program.ArePortsAvailable(5000, 5001)) 59 | // { 60 | // await Task.Delay(500); 61 | // } 62 | 63 | // await Task.Delay(5000); 64 | Program.FunctionRunnerHost = Program.CreateServerHostBuilder(Program.Args).Build(); 65 | await Program.FunctionRunnerHost.StartAsync(); 66 | return Ok(); 67 | } 68 | 69 | [HttpGet("orchestrator/unload")] 70 | public async Task UnloadFunction([FromQuery] string functionName) 71 | { 72 | var configuration = HttpContext.RequestServices.GetRequiredService(); 73 | var path = Path.Combine(configuration.GetValue("FunctionLoader:FunctionDirectory"), 74 | functionName, $"{functionName}.dll"); 75 | 76 | System.IO.File.Delete(path); 77 | 78 | //TODO inject this 79 | await Program.FunctionRunnerHost.StopAsync(); 80 | await Program.FunctionRunnerHost.WaitForShutdownAsync(); 81 | // while (!Program.ArePortsAvailable(5000, 5001)) 82 | // { 83 | // await Task.Delay(500); 84 | // } 85 | Program.FunctionRunnerHost = Program.CreateServerHostBuilder(Program.Args).Build(); 86 | await Program.FunctionRunnerHost.StartAsync(); 87 | return Ok(); 88 | } 89 | 90 | [HttpGet("orchestrator/functions")] 91 | public IActionResult GetLoadedFunctions() 92 | { 93 | //TODO inject this 94 | var loadedFunctions = FunctionLoaderExtensions.LoadedFunctionMethods.Select(x => new FunctionInfo 95 | { 96 | MethodName = x.Name, 97 | FunctionName = x.GetCustomAttribute()!.Name, 98 | TypeName = x.GetCustomAttribute()!.GetType().Name, 99 | AssemblyLocation = x.Module.Assembly.FullName 100 | }).ToList(); 101 | return Ok(loadedFunctions); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Servermore.Server/Loader/EndpointFunctionLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Text.Json; 8 | using System.Threading.Tasks; 9 | using Microsoft.AspNetCore.Builder; 10 | using Microsoft.AspNetCore.Http; 11 | using Microsoft.AspNetCore.Mvc; 12 | using Microsoft.Extensions.DependencyInjection; 13 | using Servermore.Contracts; 14 | 15 | namespace Servermore.Server.Loader 16 | { 17 | public class EndpointFunctionLoader 18 | { 19 | public static void Load(IApplicationBuilder applicationBuilder, List functionAttributeMethods, 20 | Type functionClassType) 21 | { 22 | var endpointFunctionMethods = 23 | functionAttributeMethods.Where(x => x.GetCustomAttribute() != null).ToList(); 24 | 25 | foreach (var endpointFunctionMethod in endpointFunctionMethods) 26 | { 27 | var endpointInfo = endpointFunctionMethod.GetCustomAttribute(); 28 | var shouldAwaitMethod = endpointFunctionMethod.ReturnType.BaseType == typeof(Task); 29 | 30 | //check for duplicate routes here? 31 | var route = endpointInfo!.Route.StartsWith('/') ? endpointInfo!.Route : $"/{endpointInfo!.Route}"; 32 | applicationBuilder.Map(route, builder => 33 | { 34 | builder.Run(async context => 35 | { 36 | var activatedFunctionClass = ActivatorUtilities.CreateInstance(applicationBuilder.ApplicationServices, functionClassType); 37 | var response = endpointFunctionMethod.GetParameters().Length switch 38 | { 39 | 0 => await InvokeFunctionAppropriately(activatedFunctionClass, shouldAwaitMethod, endpointFunctionMethod, null), 40 | //TODO expand on this with more types 41 | 1 when endpointFunctionMethod.GetParameters()[0].ParameterType == typeof(HttpContext) => 42 | await InvokeFunctionAppropriately(activatedFunctionClass, shouldAwaitMethod, endpointFunctionMethod, new[] {context}), 43 | _ => null 44 | }; 45 | 46 | switch (response) 47 | { 48 | case IActionResult actionResult: 49 | await ExecuteResultFromActionResult(actionResult, context); 50 | return; 51 | case null: 52 | await WriteNullFallbackResponse(context); 53 | return; 54 | } 55 | 56 | await WriteDefaultResponse(context, response); 57 | }); 58 | }); 59 | } 60 | 61 | async Task InvokeFunctionAppropriately(object functionClassInstance, bool shouldAwaitMethod, MethodInfo endpointFunctionMethod, object?[] parameters) 62 | { 63 | return shouldAwaitMethod 64 | ? await ((dynamic) endpointFunctionMethod.Invoke(functionClassInstance, parameters))! 65 | : endpointFunctionMethod.Invoke(functionClassInstance, parameters); 66 | } 67 | } 68 | 69 | private static async Task ExecuteResultFromActionResult(IActionResult actionResult, HttpContext context) 70 | { 71 | await actionResult.ExecuteResultAsync(new ActionContext 72 | { 73 | HttpContext = context 74 | }); 75 | } 76 | 77 | private static async Task WriteDefaultResponse(HttpContext context, object response) 78 | { 79 | context.Response.StatusCode = 200; 80 | context.Response.ContentType = "application/json; charset=utf-8"; 81 | //TODO potentially check if it's primitive 82 | await context.Response.WriteAsync(JsonSerializer.Serialize(response), Encoding.UTF8); 83 | } 84 | 85 | private static async Task WriteNullFallbackResponse(HttpContext context) 86 | { 87 | context.Response.StatusCode = 200; 88 | context.Response.ContentType = "application/json; charset=utf-8"; 89 | await context.Response.WriteAsync(string.Empty, Encoding.UTF8); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Servermore.Server/Loader/FunctionLoadContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Runtime.Loader; 5 | 6 | namespace Servermore.Server.Loader 7 | { 8 | public class FunctionLoadContext : AssemblyLoadContext 9 | { 10 | private readonly AssemblyDependencyResolver _resolver; 11 | 12 | public FunctionLoadContext(string pluginPath) 13 | { 14 | _resolver = new AssemblyDependencyResolver(pluginPath); 15 | } 16 | 17 | protected override Assembly Load(AssemblyName assemblyName) 18 | { 19 | var assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); 20 | if (assemblyPath == null) 21 | { 22 | return null; 23 | }; 24 | 25 | using var fileStream = File.OpenRead(assemblyPath); 26 | return LoadFromStream(fileStream); 27 | } 28 | 29 | protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) 30 | { 31 | var libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); 32 | return libraryPath != null ? LoadUnmanagedDllFromPath(libraryPath) : IntPtr.Zero; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Servermore.Server/Loader/FunctionLoaderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Runtime.Loader; 7 | using Microsoft.AspNetCore.Builder; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Servermore.Contracts; 11 | 12 | namespace Servermore.Server.Loader 13 | { 14 | public static class FunctionLoaderExtensions 15 | { 16 | public static List LoadedAssemblies = new List(); 17 | public static List LoadedFunctionMethods = new List(); 18 | 19 | public static IApplicationBuilder UseServermore(this IApplicationBuilder applicationBuilder, IConfiguration configuration) 20 | { 21 | LoadedFunctionMethods = new List(); 22 | var exportedTypes = LoadedAssemblies.SelectMany(x => x.ExportedTypes).ToList(); 23 | 24 | foreach (var exportedType in exportedTypes) 25 | { 26 | var functionAttributeMethods = exportedType.GetMethods() 27 | .Where(x => x.GetCustomAttribute() != null) 28 | .ToList(); 29 | 30 | if (functionAttributeMethods.Count == 0) 31 | { 32 | continue; 33 | } 34 | 35 | LoadedFunctionMethods.AddRange(functionAttributeMethods); 36 | 37 | EndpointFunctionLoader.Load(applicationBuilder, functionAttributeMethods, exportedType); 38 | } 39 | return applicationBuilder; 40 | } 41 | 42 | public static IServiceCollection AddServermore(this IServiceCollection services, string functionLoadPath) 43 | { 44 | var exportedTypes = LoadedAssemblies.SelectMany(x => x.ExportedTypes).ToList(); 45 | 46 | foreach (var exportedType in exportedTypes) 47 | { 48 | ConfigureFunctionServices(services, exportedType); 49 | } 50 | 51 | return services; 52 | } 53 | 54 | private static void ConfigureFunctionServices(IServiceCollection services, Type exportedType) 55 | { 56 | var serviceConfigurationMethods = exportedType.GetMethods() 57 | .Where(x => x.GetCustomAttribute() != null && x.IsStatic) 58 | .ToList(); 59 | 60 | if (serviceConfigurationMethods.Count == 0) 61 | { 62 | return; 63 | } 64 | 65 | serviceConfigurationMethods.ForEach(info => { info.Invoke(null, new [] {services}); }); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Servermore.Server/Models/FunctionInfo.cs: -------------------------------------------------------------------------------- 1 | namespace Servermore.Server.Models 2 | { 3 | public class FunctionInfo 4 | { 5 | public string MethodName { get; set; } 6 | 7 | public string FunctionName { get; set; } 8 | 9 | public string TypeName { get; set; } 10 | 11 | public object Details { get; set; } 12 | 13 | public string AssemblyLocation { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Servermore.Server/OrchestratorStartup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | 7 | namespace Servermore.Server 8 | { 9 | public class OrchestratorStartup 10 | { 11 | public OrchestratorStartup(IConfiguration configuration) 12 | { 13 | Configuration = configuration; 14 | } 15 | 16 | public IConfiguration Configuration { get; } 17 | 18 | // This method gets called by the runtime. Use this method to add services to the container. 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | //services.AddSingleton(Program.FunctionRunnerHost); 22 | services.AddControllers(); 23 | } 24 | 25 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 26 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 27 | { 28 | if (env.IsDevelopment()) 29 | { 30 | app.UseDeveloperExceptionPage(); 31 | } 32 | 33 | app.UseHttpsRedirection(); 34 | 35 | app.UseRouting(); 36 | 37 | app.UseAuthorization(); 38 | 39 | app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Servermore.Server/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Diagnostics; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.NetworkInformation; 7 | using System.Threading.Tasks; 8 | using Microsoft.AspNetCore.Hosting; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Hosting; 12 | 13 | namespace Servermore.Server 14 | { 15 | public class Program 16 | { 17 | //I hate this as much as you do. I'm just messing around 18 | public static IHost FunctionRunnerHost; 19 | public static string[] Args; 20 | 21 | public static async Task Main(string[] args) 22 | { 23 | Args = args; 24 | FunctionRunnerHost = CreateServerHostBuilder(args).Build(); 25 | await FunctionRunnerHost.StartAsync(); 26 | 27 | MonitorDirectory(FunctionRunnerHost.Services.GetRequiredService().GetValue("FunctionLoader:FunctionDirectory")); 28 | 29 | await CreateOrchestratorHostBuilder(args) 30 | .Build().StartAsync(); 31 | 32 | Process.GetCurrentProcess().WaitForExit(); 33 | } 34 | 35 | private static void MonitorDirectory(string path) 36 | { 37 | var fileSystemWatcher = new FileSystemWatcher 38 | { 39 | Path = path, 40 | IncludeSubdirectories = true 41 | }; 42 | fileSystemWatcher.Created += async (sender, args) => { await RestartServer(); }; 43 | fileSystemWatcher.Deleted += async (sender, args) => { await RestartServer(); }; 44 | fileSystemWatcher.EnableRaisingEvents = false; 45 | 46 | static async Task RestartServer() 47 | { 48 | await FunctionRunnerHost.StopAsync(); 49 | await FunctionRunnerHost.WaitForShutdownAsync(); 50 | // while (!ArePortsAvailable(5000, 5001)) 51 | // { 52 | // await Task.Delay(500); 53 | // } 54 | FunctionRunnerHost = CreateServerHostBuilder(Args).Build(); 55 | await FunctionRunnerHost.StartAsync(); 56 | } 57 | } 58 | 59 | public static IHostBuilder CreateServerHostBuilder(string[] args) => 60 | Host.CreateDefaultBuilder(args) 61 | .ConfigureWebHostDefaults(webBuilder => 62 | { 63 | webBuilder.UseStartup(); 64 | }); 65 | 66 | public static IHostBuilder CreateOrchestratorHostBuilder(string[] args) => 67 | Host.CreateDefaultBuilder(args) 68 | .ConfigureWebHostDefaults(webBuilder => 69 | { 70 | webBuilder.UseStartup() 71 | .UseUrls("https://localhost:5300"); 72 | }); 73 | 74 | 75 | public static bool ArePortsAvailable(params int[] ports) 76 | { 77 | var portsToCheck = ports.ToList(); 78 | 79 | IPEndPoint[] endPoints; 80 | var portArray = new List(); 81 | 82 | var properties = IPGlobalProperties.GetIPGlobalProperties(); 83 | 84 | if (properties.GetActiveTcpConnections().Any(x => portsToCheck.Contains(x.LocalEndPoint.Port))) 85 | { 86 | return false; 87 | } 88 | 89 | if (properties.GetActiveTcpListeners().Any(x => portsToCheck.Contains(x.Port))) 90 | { 91 | return false; 92 | } 93 | 94 | if (properties.GetActiveUdpListeners().Any(x => portsToCheck.Contains(x.Port))) 95 | { 96 | return false; 97 | } 98 | 99 | return true; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Servermore.Server/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "Servermore.Server": { 5 | "commandName": "Project", 6 | "launchBrowser": false, 7 | "launchUrl": "", 8 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Servermore.Server/Servermore.Server.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Servermore.Server/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Reflection; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using Servermore.Sdk; 11 | using Servermore.Server.Loader; 12 | 13 | namespace Servermore.Server 14 | { 15 | public class Startup 16 | { 17 | public Startup(IConfiguration configuration) 18 | { 19 | Configuration = configuration; 20 | FunctionLoaderExtensions.LoadedAssemblies = LoadFunctionAssemblies(configuration.GetValue("FunctionLoader:FunctionDirectory")); 21 | } 22 | 23 | private static List LoadFunctionAssemblies(string rootPath) 24 | { 25 | var list = new List(); 26 | 27 | var dlls = Directory.EnumerateFiles(rootPath, "*.dll", SearchOption.AllDirectories); 28 | 29 | foreach (var dll in dlls) 30 | { 31 | Console.WriteLine($"Loading functions from: {dll}"); 32 | var loader = new FunctionLoadContext(dll); 33 | list.Add(loader.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(dll)))); 34 | } 35 | 36 | return list; 37 | } 38 | 39 | public IConfiguration Configuration { get; } 40 | 41 | // This method gets called by the runtime. Use this method to add services to the container. 42 | public void ConfigureServices(IServiceCollection services) 43 | { 44 | services.AddSingleton(); 45 | services.AddServermore(Configuration.GetValue("FunctionLoader:FunctionDirectory")); 46 | services.AddMvcCore(); 47 | } 48 | 49 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 50 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 51 | { 52 | if (env.IsDevelopment()) 53 | { 54 | app.UseDeveloperExceptionPage(); 55 | } 56 | 57 | app.UseHttpsRedirection(); 58 | app.UseServermore(Configuration); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Servermore.Server/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "FunctionLoader": { 10 | "FunctionDirectory": "F:/lab/Servermore/Servermore.Server/bin/loadcation" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Servermore.Server/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /Servermore.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Servermore.Server", "Servermore.Server\Servermore.Server.csproj", "{FACD6041-AE02-4180-A04C-518250D6E7A9}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Servermore.Sdk", "Servermore.Sdk\Servermore.Sdk.csproj", "{85FE680E-E2E8-430F-A745-6CCBE403A3E6}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Servermore.Contracts", "Servermore.Contracts\Servermore.Contracts.csproj", "{C14F32DF-661E-4714-BAF9-459DE2C95B5E}" 8 | EndProject 9 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{383E18BF-82AA-49F8-906B-12CC68E95395}" 10 | EndProject 11 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Servermore.ApiSample", "samples\Servermore.ApiSample\Servermore.ApiSample.csproj", "{A1C3768D-1F6B-4B69-BE8A-D474F942A602}" 12 | EndProject 13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Servermore.Cli", "Servermore.Cli\Servermore.Cli.csproj", "{0A7B4A0C-78ED-4E58-8D0B-5AE8B30C9BC5}" 14 | EndProject 15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.QuickApi", "samples\Sample.QuickApi\Sample.QuickApi.csproj", "{638CEDF3-BFCF-4A35-AAFE-DBC47F86670B}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {FACD6041-AE02-4180-A04C-518250D6E7A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {FACD6041-AE02-4180-A04C-518250D6E7A9}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {FACD6041-AE02-4180-A04C-518250D6E7A9}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {FACD6041-AE02-4180-A04C-518250D6E7A9}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {85FE680E-E2E8-430F-A745-6CCBE403A3E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {85FE680E-E2E8-430F-A745-6CCBE403A3E6}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {85FE680E-E2E8-430F-A745-6CCBE403A3E6}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {85FE680E-E2E8-430F-A745-6CCBE403A3E6}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {C14F32DF-661E-4714-BAF9-459DE2C95B5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {C14F32DF-661E-4714-BAF9-459DE2C95B5E}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {C14F32DF-661E-4714-BAF9-459DE2C95B5E}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {C14F32DF-661E-4714-BAF9-459DE2C95B5E}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {A1C3768D-1F6B-4B69-BE8A-D474F942A602}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {A1C3768D-1F6B-4B69-BE8A-D474F942A602}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {A1C3768D-1F6B-4B69-BE8A-D474F942A602}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {A1C3768D-1F6B-4B69-BE8A-D474F942A602}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {0A7B4A0C-78ED-4E58-8D0B-5AE8B30C9BC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {0A7B4A0C-78ED-4E58-8D0B-5AE8B30C9BC5}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {0A7B4A0C-78ED-4E58-8D0B-5AE8B30C9BC5}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {0A7B4A0C-78ED-4E58-8D0B-5AE8B30C9BC5}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {638CEDF3-BFCF-4A35-AAFE-DBC47F86670B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {638CEDF3-BFCF-4A35-AAFE-DBC47F86670B}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {638CEDF3-BFCF-4A35-AAFE-DBC47F86670B}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {638CEDF3-BFCF-4A35-AAFE-DBC47F86670B}.Release|Any CPU.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | GlobalSection(NestedProjects) = preSolution 49 | {A1C3768D-1F6B-4B69-BE8A-D474F942A602} = {383E18BF-82AA-49F8-906B-12CC68E95395} 50 | {638CEDF3-BFCF-4A35-AAFE-DBC47F86670B} = {383E18BF-82AA-49F8-906B-12CC68E95395} 51 | EndGlobalSection 52 | EndGlobal 53 | -------------------------------------------------------------------------------- /samples/Sample.QuickApi/Quickie.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Servermore.Contracts; 4 | 5 | namespace Sample.QuickApi 6 | { 7 | public class Quickie 8 | { 9 | [EndpointFunction("Testpoint", "tryme")] 10 | public IActionResult SimpleSync(HttpContext httpContext) 11 | { 12 | return new OkObjectResult(new 13 | { 14 | Name = $"Your query string was: {httpContext.Request.QueryString}" 15 | }); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /samples/Sample.QuickApi/Sample.QuickApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | true 6 | 7 | 8 | 9 | 10 | false 11 | runtime 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /samples/Servermore.ApiSample/ExampleFunctions.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using LanguageExt; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Servermore.Contracts; 7 | using Servermore.Sdk; 8 | 9 | namespace Servermore.ApiSample 10 | { 11 | public class ExampleFunctions 12 | { 13 | private readonly IFunctionLogger _logger; 14 | private readonly IMetricsCollector _metrics; 15 | 16 | public ExampleFunctions(IFunctionLogger logger, IMetricsCollector metrics) 17 | { 18 | _logger = logger; 19 | _metrics = metrics; 20 | } 21 | 22 | [EndpointFunction("TestingServiceLifetime", "api/metric")] 23 | public Task GetMetric() 24 | { 25 | _metrics.Increment("Test"); 26 | return Task.FromResult(new OkObjectResult(new 27 | { 28 | MetricVal = $"Test metric: {_metrics.GetValue("Test")}" 29 | })); 30 | } 31 | 32 | [FunctionServiceConfiguration] 33 | public static void ConfigureServices(IServiceCollection services) 34 | { 35 | services.AddSingleton(); 36 | } 37 | 38 | [EndpointFunction("SimpleGetEndpoint", "api/test")] 39 | public async Task GetEndpointTest() 40 | { 41 | _logger.Log("Endpoint called"); 42 | return new OkObjectResult(new { Text = "Did this work?"}); 43 | } 44 | 45 | [EndpointFunction("SimpleGetEndpoint", "api/oneof")] 46 | public async Task TestDepsEndpoint() 47 | { 48 | var opt = new Some("work"); 49 | return new OkObjectResult(new { Text = $"Did this {opt.Value}?"}); 50 | } 51 | 52 | [EndpointFunction("SimpleGetEndpoint2", "api/test2")] 53 | public async Task GetEndpointTest2(HttpContext httpContext) 54 | { 55 | _logger.Log($"Endpoint called with query string {httpContext.Request.QueryString}"); 56 | return new OkObjectResult(new { Text = $"Did this work? {httpContext.Request.QueryString}"}); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /samples/Servermore.ApiSample/IMetricsCollector.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Collections.Generic; 3 | 4 | namespace Servermore.ApiSample 5 | { 6 | public interface IMetricsCollector 7 | { 8 | void Increment(string metricName); 9 | 10 | int GetValue(string metricName); 11 | } 12 | 13 | public class MetricsCollector : IMetricsCollector 14 | { 15 | private readonly ConcurrentDictionary _metrics = new ConcurrentDictionary(); 16 | 17 | public void Increment(string metricName) 18 | { 19 | if (!_metrics.ContainsKey(metricName)) 20 | { 21 | _metrics.TryAdd(metricName, 1); 22 | return; 23 | } 24 | 25 | _metrics[metricName]++; 26 | } 27 | 28 | public int GetValue(string metricName) 29 | { 30 | return _metrics.GetValueOrDefault(metricName, 0); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /samples/Servermore.ApiSample/Servermore.ApiSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | true 6 | 7 | 8 | 9 | 10 | false 11 | runtime 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | --------------------------------------------------------------------------------