cloudpub-client 3.0.2

CloudPub CLI client for secure tunnel and service publishing
Documentation
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use crate::service::{ServiceConfig, ServiceManager as ServiceManagerTrait, ServiceStatus};
use anyhow::{anyhow, Result};
use cloudpub_common::protocol::message::Message;
use cloudpub_common::protocol::Stop;
use std::ffi::OsString;
use std::io::Error;
use std::time::Duration;
use tokio::sync::broadcast;
use tracing::{debug, error, info, warn};

use windows_service::service::{
    ServiceAccess, ServiceControl, ServiceControlAccept, ServiceErrorControl, ServiceExitCode,
    ServiceInfo, ServiceStartType, ServiceState, ServiceStatus as WinServiceStatus, ServiceType,
};
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
use windows_service::{define_windows_service, service_dispatcher};

define_windows_service!(ffi_service_main, service_main);

pub struct WindowsServiceManager {
    config: ServiceConfig,
}

impl WindowsServiceManager {
    pub fn new(config: ServiceConfig) -> Self {
        Self { config }
    }

    #[cfg(windows)]
    fn get_service_info(&self) -> ServiceInfo {
        ServiceInfo {
            name: OsString::from(&self.config.name),
            display_name: OsString::from(&self.config.display_name),
            service_type: ServiceType::OWN_PROCESS,
            start_type: ServiceStartType::AutoStart,
            error_control: ServiceErrorControl::Normal,
            executable_path: self.config.executable_path.clone(),
            launch_arguments: self.config.args.iter().map(|s| s.into()).collect(),
            dependencies: vec![],
            account_name: None,
            account_password: None,
        }
    }
}

impl ServiceManagerTrait for WindowsServiceManager {
    fn install(&self) -> Result<()> {
        debug!("Installing Windows service '{}'...", self.config.name);
        debug!(
            "Service executable: {}",
            self.config.executable_path.display()
        );
        debug!("Service args: {:?}", self.config.args);

        let manager = ServiceManager::local_computer(
            None::<&str>,
            ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE,
        )
        .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
        debug!("Connected to Windows service manager with CREATE_SERVICE access");

        let service_info = self.get_service_info();
        debug!(
            "Service info prepared: display_name={}",
            self.config.display_name
        );

        manager
            .create_service(
                &service_info,
                ServiceAccess::QUERY_STATUS | ServiceAccess::START | ServiceAccess::STOP,
            )
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to create service: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to create service '{}': {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;
        info!(
            "Windows service '{}' created successfully",
            self.config.name
        );

        // Copy config to system location
        debug!("Copying config to system location...");
        self.config.copy_config_to_system()?;
        debug!("Config copied to system location");

        Ok(())
    }

    fn uninstall(&self) -> Result<()> {
        debug!("Uninstalling Windows service '{}'...", self.config.name);

        // First, try to stop the service if it's running
        // We need a separate connection for stop operation
        let stop_manager =
            ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT).map_err(
                |e| {
                    let os_error = Error::last_os_error();
                    error!(
                "Failed to connect to Windows Service Manager for stop: {} (Windows error: {})",
                e, os_error
            );
                    anyhow!(
                        "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                        e,
                        os_error
                    )
                },
            )?;
        debug!("Connected to Windows service manager for stop operation");

        // Try to stop the service first
        if let Ok(service) = stop_manager.open_service(
            &self.config.name,
            ServiceAccess::STOP | ServiceAccess::QUERY_STATUS,
        ) {
            let service_status = service.query_status()?;
            debug!("Current service state: {:?}", service_status.current_state);

            if service_status.current_state != ServiceState::Stopped {
                debug!("Stopping service before deletion...");
                service.stop().map_err(|e| {
                    let os_error = Error::last_os_error();
                    warn!(
                        "Failed to stop service during uninstall: {} (Windows error: {})",
                        e, os_error
                    );
                    e
                })?;

                // Wait for the service to stop
                for i in 0..10 {
                    let status = service.query_status()?;
                    debug!(
                        "Waiting for service to stop, attempt {} - state: {:?}",
                        i + 1,
                        status.current_state
                    );
                    if status.current_state == ServiceState::Stopped {
                        debug!("Service stopped successfully");
                        break;
                    }
                    std::thread::sleep(Duration::from_secs(1));
                }
            }
        }

        // Now delete the service
        let delete_manager =
            ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT).map_err(
                |e| {
                    let os_error = Error::last_os_error();
                    error!(
                "Failed to connect to Windows Service Manager for delete: {} (Windows error: {})",
                e, os_error
            );
                    anyhow!(
                        "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                        e,
                        os_error
                    )
                },
            )?;
        debug!("Connected to Windows service manager for delete operation");

        let service = delete_manager
            .open_service(&self.config.name, ServiceAccess::DELETE)
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to open service for deletion: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to open service '{}' for deletion: {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;
        debug!("Opened service '{}' for deletion", self.config.name);

        service.delete().map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to delete service: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to delete service '{}': {} (Windows error: {})",
                self.config.name,
                e,
                os_error
            )
        })?;
        info!(
            "Windows service '{}' uninstalled successfully",
            self.config.name
        );
        Ok(())
    }

    fn start(&self) -> Result<()> {
        debug!("Starting Windows service '{}'...", self.config.name);

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
        debug!("Connected to Windows service manager");

        // First check if service is already running
        let query_service = manager
            .open_service(&self.config.name, ServiceAccess::QUERY_STATUS)
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to open service for status query: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to open service '{}' for status query: {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;

        let service_status = query_service.query_status()?;
        debug!("Current service state: {:?}", service_status.current_state);

        if service_status.current_state == ServiceState::Running {
            debug!("Service is already running");
            return Ok(());
        }

        // Now open for START access
        let service = manager
            .open_service(&self.config.name, ServiceAccess::START)
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to open service for start: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to open service '{}' for start: {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;
        debug!("Opened service '{}' for starting", self.config.name);

        debug!("Starting service...");
        service.start::<&str>(&[]).map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to start service: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to start service '{}': {} (Windows error: {})",
                self.config.name,
                e,
                os_error
            )
        })?;
        info!(
            "Windows service '{}' start command sent successfully",
            self.config.name
        );
        Ok(())
    }

    fn stop(&self) -> Result<()> {
        debug!("Stopping Windows service '{}'...", self.config.name);

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
        debug!("Connected to Windows service manager");

        // First check if service is already stopped
        let query_service = manager
            .open_service(&self.config.name, ServiceAccess::QUERY_STATUS)
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to open service for status query: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to open service '{}' for status query: {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;

        let service_status = query_service.query_status()?;
        debug!("Current service state: {:?}", service_status.current_state);

        if service_status.current_state == ServiceState::Stopped {
            debug!("Service is already stopped");
            return Ok(());
        }

        // Now open for STOP access
        let service = manager
            .open_service(&self.config.name, ServiceAccess::STOP)
            .map_err(|e| {
                let os_error = Error::last_os_error();
                error!(
                    "Failed to open service for stop: {} (Windows error: {})",
                    e, os_error
                );
                anyhow!(
                    "Failed to open service '{}' for stop: {} (Windows error: {})",
                    self.config.name,
                    e,
                    os_error
                )
            })?;
        debug!("Opened service '{}' for stopping", self.config.name);

        debug!("Stopping service...");
        service.stop().map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to stop service: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to stop service '{}': {} (Windows error: {})",
                self.config.name,
                e,
                os_error
            )
        })?;
        info!(
            "Windows service '{}' stop command sent successfully",
            self.config.name
        );
        Ok(())
    }

    fn status(&self) -> Result<ServiceStatus> {
        debug!(
            "Querying status of Windows service '{}'...",
            self.config.name
        );

        let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
            .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to connect to Windows Service Manager: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
        debug!("Connected to Windows service manager");

        let service = match manager.open_service(&self.config.name, ServiceAccess::QUERY_STATUS) {
            Ok(service) => service,
            Err(e) => {
                debug!(
                    "Service '{}' not found or inaccessible: {}",
                    self.config.name, e
                );
                return Ok(ServiceStatus::NotInstalled);
            }
        };

        let service_status = service.query_status()?;
        debug!("Service state: {:?}", service_status.current_state);

        let status = match service_status.current_state {
            ServiceState::Running => ServiceStatus::Running,
            ServiceState::Stopped => ServiceStatus::Stopped,
            _ => ServiceStatus::Unknown,
        };

        debug!("Service '{}' status: {:?}", self.config.name, status);
        Ok(status)
    }
}

// Service main function that will be called by the Windows service manager
fn service_main(arguments: Vec<OsString>) {
    debug!(
        "Windows service main function called with arguments: {:?}",
        arguments
    );
    if let Err(e) = run_service() {
        error!("Service failed to run: {}", e);
    }
}

fn run_service() -> Result<()> {
    debug!("Starting Windows service run loop");

    // Create a channel for sending stop commands
    let (stop_tx, _) = broadcast::channel::<()>(1);
    let stop_tx_clone = stop_tx.clone();

    // Set up the service control handler
    let event_handler = move |control_event| -> ServiceControlHandlerResult {
        match control_event {
            ServiceControl::Stop => {
                debug!("Received STOP control event from Windows Service Manager");
                // Send stop signal through the channel
                let _ = stop_tx_clone.send(());
                ServiceControlHandlerResult::NoError
            }
            ServiceControl::Interrogate => {
                debug!("Received INTERROGATE control event from Windows Service Manager");
                ServiceControlHandlerResult::NoError
            }
            _ => {
                debug!("Received unhandled control event: {:?}", control_event);
                ServiceControlHandlerResult::NotImplemented
            }
        }
    };

    debug!("Registering service control handler");
    let status_handle =
        service_control_handler::register("cloudpub", event_handler).map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to register service control handler: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to register service control handler: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
    debug!("Service control handler registered successfully");

    // Tell the service manager that the service is running
    debug!("Setting service status to RUNNING");
    status_handle
        .set_service_status(WinServiceStatus {
            service_type: ServiceType::OWN_PROCESS,
            current_state: ServiceState::Running,
            controls_accepted: ServiceControlAccept::STOP,
            exit_code: ServiceExitCode::Win32(0),
            checkpoint: 0,
            wait_hint: Duration::default(),
            process_id: None,
        })
        .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to set service status to RUNNING: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to set service status to RUNNING: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
    info!("Windows service status set to RUNNING");

    // Run the application with stop signal
    debug!("Starting main application loop");
    run_app(stop_tx);

    // When done, update the service status to stopped
    debug!("Setting service status to STOPPED");
    status_handle
        .set_service_status(WinServiceStatus {
            service_type: ServiceType::OWN_PROCESS,
            current_state: ServiceState::Stopped,
            controls_accepted: ServiceControlAccept::empty(),
            exit_code: ServiceExitCode::Win32(0),
            checkpoint: 0,
            wait_hint: Duration::default(),
            process_id: None,
        })
        .map_err(|e| {
            let os_error = Error::last_os_error();
            error!(
                "Failed to set service status to STOPPED: {} (Windows error: {})",
                e, os_error
            );
            anyhow!(
                "Failed to set service status to STOPPED: {} (Windows error: {})",
                e,
                os_error
            )
        })?;
    info!("Windows service status set to STOPPED");

    Ok(())
}

// Function to be called when running as a Windows service
pub fn run_as_service() -> Result<()> {
    debug!("Starting Windows service dispatcher for 'cloudpub'");
    service_dispatcher::start("cloudpub", ffi_service_main).map_err(|e| {
        error!("Failed to start service dispatcher: {:?}", e);
        anyhow!("Failed to start service dispatcher: {:?}", e)
    })
}

#[tokio::main]
pub async fn run_app(stop_tx: broadcast::Sender<()>) {
    use crate::base::{init, main_loop, Cli};
    use crate::commands::Commands;
    use crate::service::ServiceConfig;
    use anyhow::Context;
    use tokio::sync::mpsc;

    debug!("Windows service run_app started");

    // Use system config path for service
    let config_path = ServiceConfig::get_system_config_path()
        .to_str()
        .unwrap()
        .to_string();
    debug!("Using config path: {}", config_path);

    let cli: Cli = Cli {
        command: Commands::Run {
            run_as_service: true,
        },
        conf: Some(config_path.clone()),
        verbose: false,
        readonly: false,
        log_level: "debug".to_string(),
    };

    debug!("Initializing service with config: {}", config_path);
    let (_guard, config) = match init(&cli).context("Failed to initialize config") {
        Ok(r) => {
            debug!("Service initialization successful");
            r
        }
        Err(err) => {
            error!("Failed to initialize service: {:?}", err);
            return;
        }
    };

    let (command_tx, command_rx) = mpsc::channel(1024);
    debug!("Command channels created");

    // Create a task to handle the stop signal
    let command_tx_clone = command_tx.clone();
    let mut stop_rx = stop_tx.subscribe();

    debug!("Spawning stop signal handler task");
    let stop_handler = tokio::spawn(async move {
        if stop_rx.recv().await.is_ok() {
            debug!("Stop signal received, sending Stop message");
            // Send stop command when service stop signal is received
            let _ = command_tx_clone.send(Message::Stop(Stop {})).await;
            debug!("Stop message sent");
        }
    });

    // Run the main loop
    info!("Starting main service loop");
    if let Err(err) = main_loop(cli, config, command_tx, command_rx).await {
        error!("Error running main loop: {}", err);
    }

    // Make sure the stop handler is terminated
    debug!("Aborting stop handler task");
    stop_handler.abort();
    debug!("Windows service run_app completed");
}