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
use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;

use hyper::http::header;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response};
use hyper::{Server, StatusCode};
use rand::Rng;

use crate::channel::{bounded, Sender};
use crate::core::cluster::StdResponse;
use crate::utils::fs::read_binary;
use crate::utils::http::server::{as_ok_json, page_not_found};
use crate::utils::thread::async_runtime_multi;

pub(crate) fn web_launch(context: Arc<crate::runtime::context::Context>) -> String {
    let (tx, rx) = bounded(1);

    std::thread::Builder::new()
        .name("WebUI".to_string())
        .spawn(move || {
            async_runtime_multi("web", 2).block_on(async move {
                let ip = context.bind_ip.clone();
                let web_context = Arc::new(WebContext { context });
                serve_with_rand_port(web_context, ip, tx).await;
            });
        })
        .unwrap();

    let bind_addr: SocketAddr = rx.recv().unwrap();
    format!("http://{}", bind_addr.to_string())
}

struct WebContext {
    context: Arc<crate::runtime::context::Context>,
}

async fn serve_with_rand_port(
    web_context: Arc<WebContext>,
    bind_id: String,
    bind_addr_tx: Sender<SocketAddr>,
) {
    let mut rng = rand::thread_rng();
    for _ in 0..30 {
        let port = rng.gen_range(10000..30000);
        let address = format!("{}:{}", bind_id.as_str(), port);
        let socket_addr = SocketAddr::from_str(address.as_str()).unwrap();

        let serve_result = serve(web_context.clone(), &socket_addr, bind_addr_tx.clone()).await;
        match serve_result {
            Ok(_) => error!("server stop"),
            Err(e) => info!("try bind failure> {}", e),
        }
    }

    error!("no port can be bound");
}

async fn serve(
    web_context: Arc<WebContext>,
    bind_addr: &SocketAddr,
    bind_addr_tx: Sender<SocketAddr>,
) -> anyhow::Result<()> {
    // And a MakeService to handle each connection...
    let make_service = make_service_fn(move |_conn| {
        let web_context = web_context.clone();
        async move {
            Ok::<_, Infallible>(service_fn(move |req| {
                let web_context = web_context.clone();
                route(req, web_context)
            }))
        }
    });

    // Then bind and serve...
    let server = Server::try_bind(bind_addr)?.serve(make_service);

    bind_addr_tx.send(bind_addr.clone()).unwrap();

    // And run forever...
    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }

    Ok(())
}

async fn route(req: Request<Body>, web_context: Arc<WebContext>) -> anyhow::Result<Response<Body>> {
    let path = req.uri().path();
    let method = req.method();

    if path.starts_with("/api/") {
        if Method::GET.eq(method) {
            match path {
                "/api/threads" => get_thread_infos(req, web_context).await,
                "/api/client/log/enable" => enable_client_log(req, web_context).await,
                "/api/client/log/disable" => disable_client_log(req, web_context).await,
                "/api/server/log/enable" => enable_server_log(req, web_context).await,
                "/api/server/log/disable" => disable_server_log(req, web_context).await,
                _ => page_not_found().await,
            }
        } else {
            page_not_found().await
        }
    } else {
        if Method::GET.eq(method) {
            static_file(req, web_context).await
        } else {
            page_not_found().await
        }
    }
}

async fn enable_client_log(
    _req: Request<Body>,
    _context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    crate::pub_sub::network::client::enable_log();
    as_ok_json(&StdResponse::ok(Some(true)))
}

async fn disable_client_log(
    _req: Request<Body>,
    _context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    crate::pub_sub::network::client::disable_log();
    as_ok_json(&StdResponse::ok(Some(false)))
}

async fn enable_server_log(
    _req: Request<Body>,
    _context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    crate::pub_sub::network::server::enable_log();
    as_ok_json(&StdResponse::ok(Some(true)))
}

async fn disable_server_log(
    _req: Request<Body>,
    _context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    crate::pub_sub::network::server::disable_log();
    as_ok_json(&StdResponse::ok(Some(false)))
}

async fn get_thread_infos(
    _req: Request<Body>,
    _context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    let c = crate::utils::thread::get_thread_infos();
    as_ok_json(&StdResponse::ok(Some(c)))
}

async fn static_file(
    req: Request<Body>,
    context: Arc<WebContext>,
) -> anyhow::Result<Response<Body>> {
    let path = {
        let mut path = req.uri().path();
        if path.is_empty() || "/".eq(path) {
            path = "/index.html";
        };

        &path[1..path.len()]
    };

    let static_file_path = {
        let path = PathBuf::from_str(path)?;

        let dashboard_path = context.context.dashboard_path.as_str();
        let base_path = PathBuf::from_str(dashboard_path)?;

        let n = base_path.join(path);
        n
    };

    let ext = {
        let ext_pos = path.rfind(".").ok_or(anyhow!("file ext name not found"))?;
        &path[ext_pos + 1..path.len()]
    };

    let context_type = match ext {
        "html" => "text/html; charset=utf-8",
        "js" => "application/javascript",
        "css" => "text/css",
        "ico" => "image/x-icon",
        "gif" => "image/gif",
        "png" => "image/png",
        "svg" => "image/svg+xml",
        "woff" => "application/font-woff",
        _ => "",
    };

    match read_binary(&static_file_path) {
        Ok(context) => Response::builder()
            .header(header::CONTENT_TYPE, context_type)
            .status(StatusCode::OK)
            .body(Body::from(context))
            .map_err(|e| anyhow!(e)),
        Err(e) => {
            error!(
                "static file not found. file path: {:?}, error: {}",
                static_file_path, e
            );
            page_not_found().await
        }
    }
}