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
329
330
331
//! FCGI process management
//!
//! ```md
//! ┌────────────────────┐         ┌─────────────────┐
//! │FcgiDispatcher      │         │FcgiProcessPool  │
//! │ ┌────────────────┐ │ socket1 │ ┌─────────────┐ │
//! │ │ FcgiClientPool ├─┼─────────┤►│ FcgiProcess │ │
//! │ └────────────────┘ │         │ └─────────────┘ │
//! │                    │         │                 │
//! │ ┌────────────────┐ │ socket2 │ ┌─────────────┐ │
//! │ │ FcgiClientPool ├─┼─────────┤►│ FcgiProcess │ │
//! │ └────────────────┘ │         │ └─────────────┘ │
//! │                    │         │                 │
//! └────────────────────┘         └─────────────────┘
//! ```

use crate::config::MapServiceCfg;
use crate::dispatcher::{DispatchConfig, Dispatcher};
use crate::wms_fcgi_backend::FcgiBackendType;
use async_process::{Child as ChildProcess, Command, Stdio};
use async_trait::async_trait;
use bbox_core::config::Loglevel;
use bufstream::BufStream;
use fastcgi_client::Client;
use log::{debug, error, info, warn};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tempfile::TempDir;

// --- FCGI Process ---

/// Child process with FCGI communication
struct FcgiProcess {
    child: ChildProcess,
    socket_path: String,
}

impl FcgiProcess {
    pub async fn spawn(
        fcgi_bin: &str,
        base_dir: Option<&PathBuf>,
        envs: &[(&str, &str)],
        socket_path: &str,
    ) -> std::io::Result<Self> {
        let child = FcgiProcess::spawn_process(fcgi_bin, base_dir, envs, socket_path)?;
        Ok(FcgiProcess {
            child,
            socket_path: socket_path.to_string(),
        })
    }

    pub async fn respawn(
        &mut self,
        fcgi_bin: &str,
        base_dir: Option<&PathBuf>,
        envs: &[(&str, &str)],
    ) -> std::io::Result<()> {
        self.child = FcgiProcess::spawn_process(fcgi_bin, base_dir, envs, &self.socket_path)?;
        Ok(())
    }

    fn spawn_process(
        fcgi_bin: &str,
        base_dir: Option<&PathBuf>,
        envs: &[(&str, &str)],
        socket_path: &str,
    ) -> std::io::Result<ChildProcess> {
        debug!("Spawning {fcgi_bin} on {socket_path}");
        let socket = Path::new(socket_path);
        if socket.exists() {
            std::fs::remove_file(socket)?;
        }
        let listener = UnixListener::bind(socket)?;
        let fd = listener.into_raw_fd();
        let fcgi_io = unsafe { Stdio::from_raw_fd(fd) };

        let mut cmd = Command::new(fcgi_bin);
        cmd.stdin(fcgi_io);
        cmd.kill_on_drop(true);
        if let Some(dir) = base_dir {
            cmd.current_dir(dir);
        }
        cmd.envs(envs.to_vec());
        let child = cmd.spawn()?;

        Ok(child)
    }

    pub fn is_running(&mut self) -> std::io::Result<bool> {
        Ok(self.child.try_status()?.is_none())
    }
}

impl Drop for FcgiProcess {
    fn drop(&mut self) {
        let socket = Path::new(&self.socket_path);
        if socket.exists() {
            debug!("Removing socket {}", &self.socket_path);
            let _ = std::fs::remove_file(socket);
        }
    }
}

// --- FCGI Process Pool ---

/// Collection of processes for one FCGI application
pub struct FcgiProcessPool {
    fcgi_bin: String,
    base_dir: Option<PathBuf>,
    envs: Vec<(String, String)>,
    backend_name: String,
    pub(crate) suffixes: Vec<FcgiSuffixUrl>,
    num_processes: usize,
    socket_dir: TempDir,
    processes: Vec<FcgiProcess>,
}

#[derive(Clone)]
pub struct FcgiSuffixUrl {
    pub suffix: String,
    pub url_base: String,
}

impl FcgiProcessPool {
    pub fn new(
        fcgi_bin: String,
        base_dir: Option<PathBuf>,
        backend: &dyn FcgiBackendType,
        loglevel: &Option<Loglevel>,
        num_processes: usize,
    ) -> Self {
        // We use the system temp path, but according to FHS /run would be correct
        let socket_dir = TempDir::with_prefix("bbox-").expect("TempDir creation");
        FcgiProcessPool {
            fcgi_bin,
            base_dir,
            envs: backend.envs(loglevel),
            backend_name: backend.name().to_string(),
            suffixes: backend
                .project_files()
                .iter()
                .flat_map(|s| {
                    backend.url_base(s).map(|b| FcgiSuffixUrl {
                        suffix: s.to_string(),
                        url_base: b.to_string(),
                    })
                })
                .collect(),
            socket_dir,
            num_processes,
            processes: Vec::new(),
        }
    }
    /// Constant socket path over application lifetime
    fn socket_path(&self, process_no: usize) -> String {
        self.socket_dir
            .path()
            .join(format!("fcgi_{}_{process_no}.sock", self.backend_name))
            .to_string_lossy()
            .to_string()
    }
    pub async fn spawn_processes(&mut self) -> std::io::Result<()> {
        let envs: Vec<_> = self
            .envs
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        for no in 0..self.num_processes {
            let socket_path = self.socket_path(no);
            let process =
                FcgiProcess::spawn(&self.fcgi_bin, self.base_dir.as_ref(), &envs, &socket_path)
                    .await?;
            self.processes.push(process)
        }
        info!(
            "Spawned {} FCGI processes '{}'",
            self.processes.len(),
            &self.fcgi_bin
        );
        Ok(())
    }

    /// Create client pool for each process and return dispatcher
    pub fn client_dispatcher(&self, wms_config: &MapServiceCfg) -> FcgiDispatcher {
        debug!("Creating {} FcgiDispatcher", self.backend_name);
        let config = DispatchConfig::new();
        let pools = (0..self.num_processes)
            .map(|no| {
                let socket_path = self.socket_path(no);
                let handler = FcgiClientHandler { socket_path };
                FcgiClientPool::builder(handler)
                    .max_size(wms_config.fcgi_client_pool_size)
                    .runtime(deadpool::Runtime::Tokio1)
                    .wait_timeout(wms_config.wait_timeout.map(Duration::from_millis))
                    .create_timeout(wms_config.create_timeout.map(Duration::from_millis))
                    .recycle_timeout(wms_config.recycle_timeout.map(Duration::from_millis))
                    .build()
                    .expect("FcgiClientPool::builder")
            })
            .collect();
        let dispatcher = Dispatcher::new(&config, &pools);
        FcgiDispatcher {
            backend_name: self.backend_name.clone(),
            pools,
            dispatcher,
            suffixes: self.suffixes.clone(),
        }
    }

    async fn check_process(&mut self, no: usize) -> std::io::Result<()> {
        if let Some(p) = self.processes.get_mut(no) {
            match p.is_running() {
                Ok(true) => {} // ok
                Ok(false) => {
                    warn!("process[{no}] not running - restarting...");
                    let envs: Vec<_> = self
                        .envs
                        .iter()
                        .map(|(k, v)| (k.as_str(), v.as_str()))
                        .collect();
                    if let Err(e) = p
                        .respawn(&self.fcgi_bin, self.base_dir.as_ref(), &envs)
                        .await
                    {
                        warn!("process[{no}] restarting error: {e}");
                    }
                }
                Err(e) => debug!("process[{no}].is_running(): {e}"),
            }
        } else {
            error!("process[{no}] does not exist");
        }
        Ok(())
    }

    pub async fn watchdog_loop(&mut self) {
        loop {
            // debug!("Checking process pool");
            for no in 0..self.processes.len() {
                let _ = self.check_process(no).await;
            }
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    }
}

// --- FCGI Client ---

#[derive(Clone)]
pub struct FcgiClientHandler {
    socket_path: String,
}

impl FcgiClientHandler {
    fn fcgi_client(&self) -> std::io::Result<FcgiClient> {
        let stream = UnixStream::connect(&self.socket_path)?;
        // let stream = TcpStream::connect(("127.0.0.1", 9000)).unwrap();
        let fcgi_client = Client::new(stream, true);
        Ok(fcgi_client)
    }
}

pub type FcgiClient = fastcgi_client::Client<BufStream<UnixStream>>;

// --- FCGI Client Pool ---

pub type FcgiClientPoolError = std::io::Error;

#[async_trait]
impl deadpool::managed::Manager for FcgiClientHandler {
    type Type = FcgiClient;
    type Error = FcgiClientPoolError;
    async fn create(&self) -> Result<FcgiClient, FcgiClientPoolError> {
        debug!("deadpool::managed::Manager::create {}", &self.socket_path);
        let client = self.fcgi_client();
        if let Err(ref e) = client {
            debug!("Failed to create client {}: {e}", &self.socket_path);
        }
        client
    }
    async fn recycle(
        &self,
        _fcgi: &mut FcgiClient,
    ) -> deadpool::managed::RecycleResult<FcgiClientPoolError> {
        debug!("deadpool::managed::Manager::recycle {}", &self.socket_path);
        Ok(())
        // Err(deadpool::managed::RecycleError::Message(
        //     "client invalid".to_string(),
        // ))
    }
}

pub type FcgiClientPool = deadpool::managed::Pool<FcgiClientHandler>;

// --- FCGI Dispatching ---

/// FCGI client dispatcher
pub struct FcgiDispatcher {
    backend_name: String,
    /// Client pool for each FCGI process
    pools: Vec<FcgiClientPool>,
    /// Mode-dependent dispatcher
    dispatcher: Dispatcher,
    /// Suffix info for endpoint registration
    pub(crate) suffixes: Vec<FcgiSuffixUrl>,
}

impl FcgiDispatcher {
    pub fn backend_name(&self) -> &str {
        &self.backend_name
    }
    /// Select FCGI process
    /// Returns process index and FCGI client pool
    pub fn select(&self, query_str: &str) -> (usize, &FcgiClientPool) {
        let poolno = self.dispatcher.select(query_str);
        let pool = &self.pools[poolno];
        debug!("selected pool {poolno}: client {:?}", pool.status());
        (poolno, pool)
    }
    /// Remove possibly broken client
    pub fn remove(&self, fcgi_client: deadpool::managed::Object<FcgiClientHandler>) {
        // Can't call with `&mut self` from web service thread
        debug!("Removing Client from FcgiClientPool");
        let _obj = deadpool::managed::Object::take(fcgi_client);
        // TODO: remove all clients with same socket path
        // Possible implementation:
        // Return error in FcgiClientHandler::recycle when self.socket_path is younger than FcgiClient
    }
}