• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use crate::http_server::http_handlers::{create_filename_hash_set, handle_connection};
16 
17 use crate::http_server::thread_pool::ThreadPool;
18 use log::{info, warn};
19 use std::net::TcpListener;
20 use std::sync::Arc;
21 use std::thread;
22 
23 const DEFAULT_HTTP_PORT: u16 = 7681;
24 
25 /// Start the HTTP Server.
26 
run_http_server(instance_num: u16) -> u1627 pub fn run_http_server(instance_num: u16) -> u16 {
28     let http_port = DEFAULT_HTTP_PORT + instance_num - 1;
29     let _ = thread::Builder::new().name("http_server".to_string()).spawn(move || {
30         let listener = match TcpListener::bind(format!("127.0.0.1:{}", http_port)) {
31             Ok(listener) => listener,
32             Err(e) => {
33                 warn!("bind error in netsimd frontend http server. {}", e);
34                 return;
35             }
36         };
37         let pool = ThreadPool::new(4);
38         info!("Frontend http server is listening on http://localhost:{}", http_port);
39         let valid_files = Arc::new(create_filename_hash_set());
40         for stream in listener.incoming() {
41             let stream = stream.unwrap();
42             let valid_files = valid_files.clone();
43             pool.execute(move || {
44                 handle_connection(stream, valid_files);
45             });
46         }
47         info!("Shutting down frontend http server.");
48     });
49     http_port
50 }
51