• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

getdozer / dozer / 5923958356

21 Aug 2023 08:34AM UTC coverage: 74.672%. First build
5923958356

Pull #1880

github

supergi0
Merge branch 'fix/include-disable-live-flag'
Pull Request #1880: chore: Add flag to disable live ui for local development

21 of 21 new or added lines in 3 files covered. (100.0%)

46083 of 61714 relevant lines covered (74.67%)

39663.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/dozer-cli/src/main.rs
1
use clap::Parser;
2
#[cfg(feature = "cloud")]
3
use dozer_cli::cli::cloud::CloudCommands;
4
use dozer_cli::cli::generate_config_repl;
5
use dozer_cli::cli::types::{Cli, Commands, ConnectorCommand, RunCommands, SecurityCommands};
6
use dozer_cli::cli::{init_dozer, list_sources, LOGO};
7
use dozer_cli::errors::{CliError, CloudError, OrchestrationError};
8
use dozer_cli::simple::SimpleOrchestrator;
9
#[cfg(feature = "cloud")]
10
use dozer_cli::CloudOrchestrator;
11
use dozer_cli::{live, set_ctrl_handler, set_panic_hook, shutdown};
12
use dozer_types::models::telemetry::{TelemetryConfig, TelemetryMetricsConfig};
13
use dozer_types::tracing::{error, info};
14
use serde::Deserialize;
15
use tokio::runtime::Runtime;
16
use tokio::time;
17

18
use clap::CommandFactory;
19
#[cfg(feature = "cloud")]
20
use dozer_cli::cloud_app_context::CloudAppContext;
21
use std::cmp::Ordering;
22
use std::sync::Arc;
23

24
use dozer_types::log::{debug, warn};
25
use std::time::Duration;
26
use std::{env, process};
27

28
fn main() {
×
29
    set_panic_hook();
×
30

31
    if let Err(e) = run() {
×
32
        display_error(&e);
×
33
        process::exit(1);
×
34
    }
×
35
}
×
36

37
fn render_logo() {
×
38
    const VERSION: &str = env!("CARGO_PKG_VERSION");
×
39

×
40
    println!("{LOGO}");
×
41
    println!("\nDozer Version: {VERSION}\n");
×
42
}
×
43

44
#[derive(Deserialize, Debug)]
×
45
struct DozerPackage {
46
    #[serde(rename(deserialize = "latestVersion"))]
47
    pub latest_version: String,
48
    #[serde(rename(deserialize = "availableAssets"))]
49
    pub _available_assets: Vec<String>,
50
    pub link: String,
51
}
52

53
fn version_to_vector(version: &str) -> Vec<i32> {
×
54
    version.split('.').map(|s| s.parse().unwrap()).collect()
×
55
}
×
56

57
fn compare_versions(v1: Vec<i32>, v2: Vec<i32>) -> bool {
×
58
    for i in 0..v1.len() {
×
59
        match v1.get(i).cmp(&v2.get(i)) {
×
60
            Ordering::Greater => return true,
×
61
            Ordering::Less => return false,
×
62
            Ordering::Equal => continue,
×
63
        }
64
    }
65
    false
×
66
}
×
67

68
async fn check_update() {
×
69
    const VERSION: &str = env!("CARGO_PKG_VERSION");
×
70
    let dozer_env = std::env::var("DOZER_ENV").unwrap_or("local".to_string());
×
71
    let dozer_dev = std::env::var("DOZER_DEV").unwrap_or("ext".to_string());
×
72
    let query = vec![
×
73
        ("version", VERSION),
×
74
        ("build", std::env::consts::ARCH),
×
75
        ("os", std::env::consts::OS),
×
76
        ("env", &dozer_env),
×
77
        ("dev", &dozer_dev),
×
78
    ];
×
79

×
80
    let request_url = "https://metadata.dev.getdozer.io/";
×
81

×
82
    let client = reqwest::Client::new();
×
83

×
84
    let mut printed = false;
×
85

86
    loop {
87
        let response = client
×
88
            .get(&request_url.to_string())
×
89
            .query(&query)
×
90
            .send()
×
91
            .await;
×
92

93
        match response {
×
94
            Ok(r) => {
×
95
                if !printed {
×
96
                    let package: DozerPackage = r.json().await.unwrap();
×
97
                    let current = version_to_vector(VERSION);
×
98
                    let remote = version_to_vector(&package.latest_version);
×
99

×
100
                    if compare_versions(remote, current) {
×
101
                        info!("A new version of Dozer is available.");
×
102
                        info!(
×
103
                            "You can download v{}, from {}.",
×
104
                            package.latest_version, package.link
×
105
                        );
×
106
                        printed = true;
×
107
                    }
×
108
                }
×
109
            }
110
            Err(e) => {
×
111
                // We dont show error if error is connection error, because mostly it happens
×
112
                // when main thread is shutting down before request completes.
×
113
                if !e.is_connect() {
×
114
                    warn!("Unable to fetch the latest metadata");
×
115
                }
×
116

117
                debug!("Updates check error: {}", e);
×
118
            }
119
        }
120
        time::sleep(Duration::from_secs(2 * 60 * 60)).await;
×
121
    }
122
}
123

124
fn run() -> Result<(), OrchestrationError> {
×
125
    // Reloading trace layer seems impossible, so we are running Cli::parse in a closure
126
    // and then initializing it after reading the configuration. This is a hacky workaround, but it works.
127

128
    let cli = parse_and_generate()?;
×
129
    let mut dozer = init_orchestrator(&cli)?;
×
130
    let (shutdown_sender, shutdown_receiver) = shutdown::new(&dozer.runtime);
×
131
    set_ctrl_handler(shutdown_sender);
×
132

×
133
    // Now we have access to telemetry configuration. Telemetry must be initialized in tokio runtime.
×
134
    let app_name = dozer.config.app_name.clone();
×
135
    let app_id = dozer
×
136
        .config
×
137
        .cloud
×
138
        .as_ref()
×
139
        .map(|cloud| cloud.app_id.clone().unwrap_or(app_name));
×
140

141
    // We always enable telemetry when running live.
142
    let telemetry_config = if matches!(cli.cmd, Some(Commands::Live(_))) {
×
143
        Some(TelemetryConfig {
×
144
            trace: None,
×
145
            metrics: Some(TelemetryMetricsConfig::Prometheus(())),
×
146
        })
×
147
    } else {
148
        dozer.config.telemetry.clone()
×
149
    };
150

151
    let _telemetry = dozer
×
152
        .runtime
×
153
        .block_on(async { Telemetry::new(app_id.as_deref(), telemetry_config) });
×
154

155
    if let Some(cmd) = cli.cmd {
×
156
        // run individual servers
157
        match cmd {
×
158
            Commands::Run(run) => match run.command {
×
159
                RunCommands::Api => {
160
                    render_logo();
×
161

×
162
                    dozer.run_api(shutdown_receiver)
×
163
                }
164
                RunCommands::App => {
165
                    render_logo();
×
166

×
167
                    dozer.run_apps(shutdown_receiver, None)
×
168
                }
169
            },
170
            Commands::Security(security) => match security.command {
×
171
                SecurityCommands::GenerateToken => {
172
                    let token = dozer.generate_token()?;
×
173
                    info!("token: {:?} ", token);
×
174
                    Ok(())
×
175
                }
176
            },
177
            Commands::Build(build) => {
×
178
                let force = build.force.is_some();
×
179

×
180
                dozer.build(force, shutdown_receiver)
×
181
            }
182
            Commands::Connectors(ConnectorCommand { filter }) => {
×
183
                dozer.runtime.block_on(list_sources(
×
184
                    dozer.runtime.clone(),
×
185
                    cli.config_paths,
×
186
                    cli.config_token,
×
187
                    cli.config_overrides,
×
188
                    cli.ignore_pipe,
×
189
                    filter,
×
190
                ))
×
191
            }
192
            Commands::Clean => dozer.clean(),
×
193
            #[cfg(feature = "cloud")]
194
            Commands::Cloud(cloud) => {
195
                render_logo();
196

197
                match cloud.command.clone() {
198
                    CloudCommands::Deploy(deploy) => dozer.deploy(cloud, deploy, cli.config_paths),
199
                    CloudCommands::Api(api) => dozer.api(cloud, api),
200
                    CloudCommands::Login {
201
                        organisation_slug,
202
                        profile_name,
203
                        client_id,
204
                        client_secret,
205
                    } => dozer.login(
206
                        cloud,
207
                        organisation_slug,
208
                        profile_name,
209
                        client_id,
210
                        client_secret,
211
                    ),
212
                    CloudCommands::Secrets(command) => {
213
                        dozer.execute_secrets_command(cloud, command)
214
                    }
215
                    CloudCommands::Delete => dozer.delete(cloud),
216
                    CloudCommands::Status => dozer.status(cloud),
217
                    CloudCommands::Monitor => dozer.monitor(cloud),
218
                    CloudCommands::Logs(logs) => dozer.trace_logs(cloud, logs),
219
                    CloudCommands::Version(version) => dozer.version(cloud, version),
220
                    CloudCommands::List(list) => dozer.list(cloud, list),
221
                    CloudCommands::SetApp { app_id } => {
222
                        CloudAppContext::save_app_id(app_id.clone())?;
223
                        info!("Using \"{app_id}\" app");
224
                        Ok(())
225
                    }
226
                }
227
            }
228
            Commands::Init => {
229
                panic!("This should not happen as it is handled in parse_and_generate");
×
230
            }
231
            Commands::Live(live_flags) => {
×
232
                render_logo();
×
233
                dozer.runtime.block_on(live::start_live_server(
×
234
                    &dozer.runtime,
×
235
                    shutdown_receiver,
×
236
                    live_flags,
×
237
                ))?;
×
238
                Ok(())
×
239
            }
240
        }
×
241
    } else {
×
242
        render_logo();
×
243

×
244
        dozer.run_all(shutdown_receiver)
×
245
    }
246
}
×
247

248
// Some commands dont need to initialize the orchestrator
×
249
// This function is used to run those commands
×
250
fn parse_and_generate() -> Result<Cli, OrchestrationError> {
×
251
    dozer_tracing::init_telemetry_closure(None, None, || -> Result<Cli, OrchestrationError> {
×
252
        let cli = Cli::parse();
×
253

×
254
        if let Some(Commands::Init) = cli.cmd {
×
255
            Telemetry::new(None, None);
×
256
            if let Err(e) = generate_config_repl() {
×
257
                error!("{}", e);
×
258
                Err(e)
×
259
            } else {
×
260
                // We need to exit here, otherwise the orchestrator will be initialized
261
                process::exit(0);
×
262
            }
×
263
        } else {
264
            Ok(cli)
×
265
        }
×
266
    })
×
267
}
×
268

×
269
fn init_orchestrator(cli: &Cli) -> Result<SimpleOrchestrator, CliError> {
×
270
    dozer_tracing::init_telemetry_closure(None, None, || -> Result<SimpleOrchestrator, CliError> {
×
271
        let runtime = Arc::new(Runtime::new().map_err(CliError::FailedToCreateTokioRuntime)?);
×
272
        let res = runtime.block_on(init_dozer(
×
273
            runtime.clone(),
×
274
            cli.config_paths.clone(),
×
275
            cli.config_token.clone(),
×
276
            cli.config_overrides.clone(),
×
277
            cli.ignore_pipe,
×
278
            cli.enable_progress,
×
279
        ));
×
280

×
281
        match res {
×
282
            Ok(dozer) => {
×
283
                dozer.runtime.spawn(check_update());
×
284
                Ok(dozer)
×
285
            }
×
286
            Err(e) => {
×
287
                if let CliError::FailedToFindConfigurationFiles(_) = &e {
×
288
                    let description = "Dozer was not able to find configuration files. \n\n\
×
289
                    Please use \"dozer init\" to create project or \"dozer -c {path}\" with path to your configuration.\n\
×
290
                    Configuration documentation can be found in https://getdozer.io/docs/configuration";
×
291

×
292
                    let mut command = Cli::command();
×
293
                    command = command.about(format!("\n\n\n{} \n {}", LOGO, description));
×
294

×
295
                    println!("{}", command.render_help());
×
296
                }
×
297

×
298
                error!("{}", e);
×
299
                Err(e)
×
300
            }
×
301
        }
×
302
    })
×
303
}
×
304

×
305
fn display_error(e: &OrchestrationError) {
×
306
    if let OrchestrationError::CloudError(CloudError::ApplicationNotFound) = &e {
×
307
        let description = "Dozer cloud service was not able to find application. \n\n\
×
308
        Please check your application id in `dozer-config.cloud.yaml` file.\n\
×
309
        To change it, you can manually update file or use \"dozer cloud set-app {app_id}\".";
×
310

×
311
        error!("{}", description);
×
312
    } else {
313
        error!("{}", e);
×
314
    }
315
}
×
316

317
struct Telemetry();
318

×
319
impl Telemetry {
×
320
    fn new(app_name: Option<&str>, config: Option<TelemetryConfig>) -> Self {
×
321
        dozer_tracing::init_telemetry(app_name, config);
×
322
        Self()
×
323
    }
×
324
}
325

×
326
impl Drop for Telemetry {
×
327
    fn drop(&mut self) {
×
328
        dozer_tracing::shutdown_telemetry();
×
329
    }
×
330
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc