aboutsummaryrefslogtreecommitdiff
path: root/apps/VNLib.WebServer/src/Bootstrap/ReleaseWebserver.cs
blob: 543cbe5aa6ee3ecbfba5570e326c6aeb8fabcd09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.WebServer
* File: ReleaseWebserver.cs 
*
* ReleaseWebserver.cs is part of VNLib.WebServer which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.WebServer is free software: you can redistribute it and/or modify 
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* VNLib.WebServer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with VNLib.WebServer. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;

using VNLib.Utils.Logging;
using VNLib.Net.Http;
using VNLib.Plugins.Runtime;

using VNLib.WebServer.Config;
using VNLib.WebServer.Config.Model;
using VNLib.WebServer.Plugins;
using VNLib.WebServer.Compression;
using VNLib.WebServer.Middlewares;
using VNLib.WebServer.RuntimeLoading;
using static VNLib.WebServer.Entry;

namespace VNLib.WebServer.Bootstrap
{

    /*
     * This class represents a normally loaded "Relase" webserver to allow 
     * for module webserver use-cases. It relies on a system configuration
     * file and command line arguments to configure the server.
     */

    internal class ReleaseWebserver(ServerLogger logger, IServerConfig config, ProcessArguments procArgs)
        : WebserverBase(logger, config, procArgs)
    {

        const string PLUGIN_DATA_TEMPLATE =
@"
----------------------------------
 |      Plugin configuration:
 | Enabled: {enabled}
 | Directory: {dir}
 | Hot Reload: {hr}
 | Reload Delay: {delay}s
----------------------------------";

        private readonly ProcessArguments args = procArgs;

        ///<inheritdoc/>
        protected override PluginStackBuilder? ConfigurePlugins()
        {
            //do not load plugins if disabled
            if (args.HasArgument("--no-plugins"))
            {
                logger.AppLog.Information("Plugin loading disabled via command-line flag");
                return null;
            }

            JsonElement confEl = config.GetDocumentRoot();           

            if (!confEl.TryGetProperty(PLUGINS_CONFIG_PROP_NAME, out JsonElement plCfg))
            {
                logger.AppLog.Debug("No plugin configuration found");
                return null;
            }

            ServerPluginConfig? conf = plCfg.DeserializeElement<ServerPluginConfig>();
            Validate.EnsureNotNull(conf, "Your plugin configuration object is null or malformatted");

            if (!conf.Enabled)
            {
                logger.AppLog.Information("Plugin loading disabled via configuration flag");
                return null;
            }

            Validate.EnsureNotNull(conf.Path, "If plugins are enabled, you must specify a directory to load them from");

            //Init new plugin stack builder
            PluginStackBuilder pluginBuilder = PluginStackBuilder.Create()
                                    .WithDebugLog(logger.AppLog)
                                    .WithSearchDirectories([ conf.Path ])
                                    .WithLoaderFactory(PluginAsemblyLoading.Create);

            //Setup plugin config data
            if (!string.IsNullOrWhiteSpace(conf.ConfigDir))
            {
                pluginBuilder.WithJsonConfigDir(confEl, new(conf.ConfigDir));
            }
            else
            {
                pluginBuilder.WithLocalJsonConfig(confEl);
            }
            
            if (conf.HotReload)
            {
                Validate.EnsureRange(conf.ReloadDelaySec, 1, 120);

                pluginBuilder.EnableHotReload(TimeSpan.FromSeconds(conf.ReloadDelaySec));
            }

            logger.AppLog.Information(
                PLUGIN_DATA_TEMPLATE,
                true,
                conf.Path,
                conf.HotReload,
                conf.ReloadDelaySec
            );

            if (conf.HotReload)
            {
                logger.AppLog.Warn("Plugin hot-reload is not recommended for production deployments!");
            }
           
            return pluginBuilder;
        }       

        ///<inheritdoc/>
        protected override HttpConfig GetHttpConfig()
        {
            JsonElement rootEl = config.GetDocumentRoot();

            try
            {
                HttpGlobalConfig? gConf = rootEl.GetProperty("http").DeserializeElement<HttpGlobalConfig>();
                Validate.EnsureNotNull(gConf, "Missing required HTTP configuration variables");

                gConf.ValidateConfig();

                //Attempt to load the compressor manager, if null, compression is disabled
                IHttpCompressorManager? compressorManager = HttpCompressor.LoadOrDefaultCompressor(procArgs, gConf.Compression, config, logger.AppLog);

                IHttpMemoryPool memPool = MemoryPoolManager.GetHttpPool(procArgs.ZeroAllocations);

                HttpConfig conf = new(Encoding.ASCII)
                {
                    ActiveConnectionRecvTimeout     = gConf.RecvTimeoutMs,
                    CompressorManager               = compressorManager,
                    ConnectionKeepAlive             = TimeSpan.FromMilliseconds(gConf.KeepAliveMs),
                    CompressionLimit                = gConf.Compression.CompressionMax,                    
                    CompressionMinimum              = gConf.Compression.CompressionMin,
                    DebugPerformanceCounters        = procArgs.HasArgument("--http-counters"),
                    DefaultHttpVersion              = HttpHelpers.ParseHttpVersion(gConf.DefaultHttpVersion),
                    MaxFormDataUploadSize           = gConf.MultipartMaxSize,
                    MaxUploadSize                   = gConf.MaxEntitySize,
                    MaxRequestHeaderCount           = gConf.MaxRequestHeaderCount,                    
                    MaxOpenConnections              = gConf.MaxConnections,                    
                    MaxUploadsPerRequest            = gConf.MaxUploadsPerRequest,
                    SendTimeout                     = gConf.SendTimeoutMs,
                    ServerLog                       = logger.AppLog,
                    MemoryPool                      = memPool,

                    RequestDebugLog                 = procArgs.LogHttp ? logger.AppLog : null,

                    //Buffer config update
                    BufferConfig = new()
                    {
                        RequestHeaderBufferSize = gConf.HeaderBufSize,
                        ResponseHeaderBufferSize = gConf.ResponseHeaderBufSize,
                        FormDataBufferSize = gConf.MultipartMaxBufSize,

                        //Align response buffer size with transport buffer to avoid excessive copy
                        ResponseBufferSize = TcpConfig.TcpTxBufferSize, 

                        /*
                         * Chunk buffers are written to the transport when they are fully accumulated. These buffers
                         * should be aligned with the transport sizes. It should also be large enough not to put too much
                         * back pressure on compressors. This buffer will be segmented into smaller buffers if it has to
                         * at the transport level, but we should avoid that if possible due to multiple allocations and 
                         * copies.
                         * 
                         * Aligning chunk buffer to the transport buffer size is the easiest solution to avoid excessive
                         * copyies
                         */
                        ChunkedResponseAccumulatorSize = compressorManager != null ? TcpConfig.TcpTxBufferSize : 0
                    },
                   
                };

                Validate.Assert(
                    condition: conf.DefaultHttpVersion != HttpVersion.None,
                    message: "Your default HTTP version is invalid, specify an RFC formatted http version 'HTTP/x.x'"
                );

                return conf;
            }
            catch (KeyNotFoundException kne)
            {
                logger.AppLog.Error("Missing required HTTP configuration variables {var}", kne.Message);
                throw new ServerConfigurationException("Missing required http variables. Cannot continue");
            }
        }

        ///<inheritdoc/>
        protected override VirtualHostConfig[] GetAllVirtualHosts()
        {
            ILogProvider log = logger.AppLog;

            LinkedList<VirtualHostConfig> configs = new();

            try
            {
                int index = 0;

                //Enumerate all virtual host configurations
                foreach (VirtualHostServerConfig vhConfig in GetVirtualHosts())
                {
               
                    VirtualHostConfig conf = new JsonWebConfigBuilder(vhConfig, log).GetBaseConfig();

                    //Configure event hooks
                    conf.EventHooks = new VirtualHostHooks(conf);

                    //Init middleware stack
                    conf.CustomMiddleware.Add(new MainServerMiddlware(log, conf, vhConfig.ForcePortCheck));

                    /*
                     * In benchmark mode, skip other middleware that might slow connections down
                     */
                    if (vhConfig.Benchmark?.Enabled == true)
                    {
                        conf.CustomMiddleware.Add(new BenchmarkMiddleware(vhConfig.Benchmark));
                        log.Information("BENCHMARK: Enabled for virtual host {vh}", conf.Hostnames);
                    }
                    else
                    {
                        /*
                         * We only enable cors if the configuration has a value for the allow cors property.
                         * The user may disable cors totally, deny cors requests, or enable cors with a whitelist
                         * 
                         * Only add the middleware if the confg has a value for the allow cors property
                         */
                        if (vhConfig.Cors?.Enabled == true)
                        {
                            conf.CustomMiddleware.Add(new CORSMiddleware(log, vhConfig.Cors));
                        }

                        //Add whitelist middleware if the configuration has a whitelist
                        if (conf.WhiteList != null)
                        {
                            conf.CustomMiddleware.Add(new IpWhitelistMiddleware(log, conf.WhiteList));
                        }

                        //Add blacklist middleware if the configuration has a blacklist
                        if (conf.BlackList != null)
                        {
                            conf.CustomMiddleware.Add(new IpBlacklistMiddleware(log, conf.BlackList));
                        }

                        //Add tracing middleware if enabled
                        if (vhConfig.RequestTrace)
                        {
                            conf.CustomMiddleware.Add(new ConnectionLogMiddleware(log));
                        }
                    }

                    if (!conf.RootDir.Exists)
                    {
                        conf.RootDir.Create();
                    }

                    configs.AddLast(conf);

                    index++;
                }
            }
            catch (KeyNotFoundException kne)
            {
                throw new ServerConfigurationException("Missing required configuration varaibles", kne);
            }
            catch (FormatException fe)
            {
                throw new ServerConfigurationException("Failed to parse IP address", fe);
            }

            return configs.ToArray();
        }

        private VirtualHostServerConfig[] GetVirtualHosts()
        {
            JsonElement rootEl = config.GetDocumentRoot();
            ILogProvider log = logger.AppLog;

            if (!rootEl.TryGetProperty("virtual_hosts", out _))
            {
                log.Warn("No virtual hosts array was defined. Continuing without hosts");
                return [];
            }

            return rootEl.GetProperty("virtual_hosts")
                .EnumerateArray()
                .Select(GetVhConfig)
                .ToArray();


            static VirtualHostServerConfig GetVhConfig(JsonElement rootEl)
            {
                VirtualHostServerConfig? conf = rootEl.DeserializeElement<VirtualHostServerConfig>();

                Validate.EnsureNotNull(conf, "Empty virtual host configuration, check your virtual hosts array for an empty element");
                Validate.EnsureNotNull(conf.DirPath, "A virtual host was defined without a root directory property: 'dirPath'");
                Validate.EnsureNotNull(conf.Hostnames, "A virtual host was defined without a hostname property: 'hostnames'");
                Validate.EnsureNotNull(conf.Interfaces, "An interface configuration is required for every virtual host");

                return conf;
            }
        }
    }
}