public static void Main() { log.Info("Server is starting!"); //Load configuration file log.Config("Loading configuration file"); Settings = Config.loadConfig(); if (Settings == null) { log.Fatal("The server failed to start because of an invalid configuration setting. Please check the server configuration!"); log.Fatal("Press the any key to exit..."); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } if (Settings.ContainsKey("logSettings")) { JObject logSettings = (JObject)Settings["logSettings"]; if (logSettings.ContainsKey("logLevel")) { var logLevel = (Level)typeof(Level).GetFields().First(x => x.Name.ToLower() == ((string)logSettings["logLevel"]).ToLower()).GetValue(null); if (logLevel != null) { log.LogLevel = logLevel; } } if (logSettings.ContainsKey("format")) { log.Format = (string)logSettings["format"]; } } log.Config("Setting up files and directories..."); try { IOSetup(); } catch (IOException e) { log.Fatal("Failed to set up files and directories."); log.Fatal(e.Message); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } log.OutputStreams.Add(new AdvancingWriter(Logs("latest.log")) { Compression = true, CompressOnClose = false, Archive = Logs("{0:dd-MM-yyyy}.{2}.zip") }); //Get local IP address, if autodetect is enabled in settings. List <string> addresses = Settings["connectionSettings"]["serverAddresses"].ToObject <List <string> >(); if ((bool)Settings["connectionSettings"]["autodetect"]) { string address; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; address = endPoint.Address.ToString(); addresses.Add(address); } log.Info("Detected IPv4 address to be " + address); } //Create request queue var requestQueue = new BlockingCollection <HttpListenerContext>(); // Create listener thingy. HttpListener listener = new HttpListener(); foreach (string address in addresses) { listener.Prefixes.Add("http://" + address + "/"); } ListenerThread = new Listener(listener, requestQueue, "ListenerThread", log); try { ListenerThread.Start(); } catch (HttpListenerException e) { log.Fatal("Failed to create Listener. Are you running the server in Administrator mode?."); log.Fatal(e.Message); Console.ReadKey(); Console.WriteLine(); log.Close(); return; } //Create console command thread ConsoleThread = new Thread(() => API.Threads.ConsoleCommand.main(log)) { IsBackground = true }; ConsoleThread.Start(); //Create worker threads log.Config("Creating worker threads..."); int threadCount = (int)Settings["performanceSettings"]["workerThreadCount"]; RequestWorkers = new RequestWorker[threadCount]; for (int i = 0; i < threadCount; i++) { try { var worker = new RequestWorker(CreateConnection(), requestQueue, "RequestWorker" + (i + 1), log); worker.Start(); RequestWorkers[i] = worker; } catch (MySqlException e) { log.Error("Failed to create connection for RequestWorker" + (i + 1)); log.Error(e.Message); } } log.Info("Finished setup"); // Wait until all threads are terminated foreach (var worker in RequestWorkers.Where(x => x != null)) { worker.Join(); log.Fine($"Stopped '{worker}'"); } // Exit main thread log.Info("Exiting program..."); log.Close(); }
public static void Main() { //Initialize logger LogTab Tab = new LogTab("General"); Log = Tab.GetLogger(); RequestWorker.RequestLoggerTab = new LogTab("Workers"); Log.Info("Server is starting!"); //Create default config Log.Info("Loading configuration files..."); Config.AddConfig(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Webserver.DefaultConfig.json"))); Config.SaveDefaultConfig(); //Load the configuration file Dictionary <string, List <string> > Missing = Config.LoadConfig(); //Display all missing and/or invalid config settings, if any. if (Missing == null) { Log.Fatal("The config file could not be read. Ensure that it is a valid JSON file. Press any key to exit."); Console.ReadKey(); return; } else if (Missing.Count > 0) { Log.Fatal("Found one or more invalid or missing configuration settings;"); foreach (string Key in Missing.Keys) { if (Missing[Key].Count == 0) { Console.Write(Key); } foreach (string Key2 in Missing[Key]) { Log.Fatal(Key + "." + Key2); } } Log.Fatal("Please check the configuration file. Press any key to exit."); Console.ReadKey(); return; } //Check CORS addresses CORSAddresses = Utils.ParseAddresses(Config.GetValue("ConnectionSettings.AccessControl").ToObject <List <string> >()); List <string> Addresses = Utils.ParseAddresses(Configurator.Config.GetValue("ConnectionSettings.ServerAddresses").ToObject <List <string> >()); CORSAddresses = CORSAddresses.Concat(Addresses).ToList(); //Run inits SQLiteConnection Connection = Database.Init(); WebFiles.Init(); Redirect.Init(); //Find all API endpoints DiscoverEndpoints(); //Create Queue and launch listener Thread ListenerThread = new Thread(() => Listener.Run()); ListenerThread.Start(); //Create performance tab + watchers MonitorTab pTab = new MonitorTab("PerfMon"); RequestWorker.RequestTimeWatcher = pTab.CreateNumWatcher("Request time", ShowMin: true, ShowAverage: true, ShowMax: true); Listener.QueueSizeWatcher = pTab.CreateNumWatcher("Queue size", ShowMax: true); //Launch worker threads List <Thread> WorkerThreads = new List <Thread>(); for (int i = 0; i < (int)Config.GetValue("PerformanceSettings.WorkerThreadCount"); i++) { RequestWorker Worker = new RequestWorker((SQLiteConnection)Connection.Clone()); Thread WorkerThread = new Thread(new ThreadStart(Worker.Run)) { Name = "RequestWorker" + i }; WorkerThread.Start(); WorkerThreads.Add(WorkerThread); } //Launch maintenance thread Timer Maintenance = new Timer(new MaintenanceThread { Log = Log }.Run, null, 0, 3600 * 1000); //Wait for an exit command, then exit. foreach (Thread Worker in WorkerThreads) { Worker.Join(); } }