aboutsummaryrefslogtreecommitdiff
path: root/plugins/ObjectCacheServer/src/NodeConfig.cs
blob: 3a2e10eda22283f1dc7869432dd7d3f4a807487b (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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: ObjectCacheServer
* File: NodeConfig.cs 
*
* NodeConfig.cs is part of ObjectCacheServer which is part of the larger 
* VNLib collection of libraries and utilities.
*
* ObjectCacheServer is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* ObjectCacheServer 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

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

using VNLib.Plugins;
using VNLib.Utils.Logging;
using VNLib.Utils.Extensions;
using VNLib.Plugins.Extensions.Loading;
using VNLib.Data.Caching.Extensions.Clustering;


namespace VNLib.Data.Caching.ObjectCache.Server
{
    [ConfigurationName("cluster")]
    internal sealed class NodeConfig 
    {
        //Default path for the well known endpoint
        const string DefaultPath = "/.well-known/vncache";

        public CacheNodeConfiguration Config { get; }

        public CacheAuthKeyStore KeyStore { get; }

        public TimeSpan DiscoveryInterval { get; }

        public TimeSpan EventQueuePurgeInterval { get; }

        public int MaxQueueDepth { get; }

        public string? DiscoveryPath { get; }

        public string ConnectPath { get; }

        public string WellKnownPath { get; }

        public bool VerifyIp { get; }

        /// <summary>
        /// The maximum number of peer connections to allow
        /// </summary>
        public uint MaxPeerConnections { get; } = 10;

        public NodeConfig(PluginBase plugin, IConfigScope config)
        { 
            //Get the port of the primary webserver
            int port;
            bool usingTls;
            {
                //Get the port number of the first virtual host
                JsonElement firstHost = plugin.HostConfig.GetProperty("virtual_hosts")
                                            .EnumerateArray()
                                            .First();

                port = firstHost.GetProperty("interface")
                        .GetProperty("port")
                        .GetInt32();

                //If the ssl element is present, ssl is enabled for the server
                usingTls = firstHost.TryGetProperty("ssl", out _);
            }
            string hostname = Dns.GetHostName();

            //Server id is just dns name for now
            string nodeId = $"{hostname}:{port}";
           
            //Init key store
            KeyStore = new(plugin);


            DiscoveryInterval = config["discovery_interval_sec"].GetTimeSpan(TimeParseType.Seconds);

            //Get the event queue purge interval
            EventQueuePurgeInterval = config["queue_purge_interval_sec"].GetTimeSpan(TimeParseType.Seconds);

            //Get the max queue depth
            MaxQueueDepth = (int)config["max_queue_depth"].GetUInt32();


            //Get the connect path
            ConnectPath = config["connect_path"].GetString() ?? throw new KeyNotFoundException("Missing required key 'connect_path' in cluster config");

            //Get the verify ip setting
            VerifyIp = config["verify_ip"].GetBoolean();

            Uri connectEp = BuildUri(usingTls, hostname, port, ConnectPath);
            Uri? discoveryEp = null;

            Config = new();

            //Setup cache node config
            Config.WithCacheEndpoint(connectEp)
                    .WithNodeId(nodeId)
                    .WithAuthenticator(KeyStore)
                    .WithTls(usingTls);

            //Get the discovery path (optional)
            if (config.TryGetValue("discovery_path", out JsonElement discoveryPathEl))
            {
                DiscoveryPath = discoveryPathEl.GetString();

                //Enable advertisment if a discovery path is present
                if (!string.IsNullOrEmpty(DiscoveryPath))
                {
                    //Build the discovery endpoint, it must be an absolute uri
                    discoveryEp = BuildUri(usingTls, hostname, port, DiscoveryPath);
                    Config.EnableAdvertisment(discoveryEp);
                }
            }

            //Allow custom well-known path
            if(config.TryGetValue("well_known_path", out JsonElement wkEl))
            {
                WellKnownPath = wkEl.GetString() ?? DefaultPath;
            }
            //Default if not set
            WellKnownPath ??= DefaultPath;

            //Get the max peer connections
            if (config.TryGetValue("max_peers", out JsonElement maxPeerEl))
            {
                MaxPeerConnections = maxPeerEl.GetUInt32();
            }

            const string CacheConfigTemplate =
@"
Cluster Configuration:
    Node Id: {id}
    TlsEndabled: {tls}
    Verify Ip: {vi}
    Well-Known: {wk}
    Cache Endpoint: {ep}
    Discovery Endpoint: {dep}
    Discovery Interval: {di}
    Max Peer Connections: {mpc}    
    Max Queue Depth: {mqd}
    Event Queue Purge Interval: {eqpi}
";

            //log the config
            plugin.Log.Information(CacheConfigTemplate,
                nodeId,
                usingTls,
                VerifyIp,
                WellKnownPath,
                connectEp,
                discoveryEp,
                DiscoveryInterval,
                MaxPeerConnections,
                MaxQueueDepth,
                EventQueuePurgeInterval
            );
        }

        private static Uri BuildUri(bool tls, string host, int port, string path)
        {
            return new UriBuilder
            {
                Scheme = tls ? "https" : "http",
                Host = host,
                Port = port,
                Path = path
            }.Uri;
        }
    }
}