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

getdozer / dozer / 5888798292

17 Aug 2023 08:51AM UTC coverage: 76.025% (-1.4%) from 77.415%
5888798292

push

github

web-flow
feat: implement graph on live ui (#1847)

* feat: implement progress

* feat: implement enable progress flag

* feat: implement progress in live

* chore: fix clippy

* chore: always use telemetry metrics

* fix: Only run build once

---------

Co-authored-by: sagar <sagar@getdozer.io>
Co-authored-by: chubei <914745487@qq.com>

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

46101 of 60639 relevant lines covered (76.03%)

40410.07 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)
×
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 => {
×
232
                render_logo();
×
233
                dozer
×
234
                    .runtime
×
235
                    .block_on(live::start_live_server(&dozer.runtime, shutdown_receiver))?;
×
236
                Ok(())
×
237
            }
×
238
        }
×
239
    } else {
240
        render_logo();
×
241

×
242
        dozer.run_all(shutdown_receiver)
×
243
    }
244
}
×
245

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

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

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

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

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

×
293
                    println!("{}", command.render_help());
×
294
                }
×
295

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

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

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

315
struct Telemetry();
316

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

324
impl Drop for Telemetry {
325
    fn drop(&mut self) {
×
326
        dozer_tracing::shutdown_telemetry();
×
327
    }
×
328
}
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

© 2026 Coveralls, Inc