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

getdozer / dozer / 6011409031

29 Aug 2023 11:05AM UTC coverage: 76.616% (-1.5%) from 78.07%
6011409031

push

github

web-flow
Change command to run_all to `dozer run` (#1935)

40 of 40 new or added lines in 1 file covered. (100.0%)

48982 of 63932 relevant lines covered (76.62%)

48381.5 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::serde::Deserialize;
14
use dozer_types::tracing::{error, info};
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
#[serde(crate = "dozer_types::serde")]
46
struct DozerPackage {
47
    #[serde(rename(deserialize = "latestVersion"))]
48
    pub latest_version: String,
49
    #[serde(rename(deserialize = "availableAssets"))]
50
    pub _available_assets: Vec<String>,
51
    pub link: String,
52
}
53

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

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

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

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

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

×
85
    let mut printed = false;
×
86

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

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

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

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

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

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

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

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

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

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

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

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

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

199
            match cloud.command.clone() {
200
                CloudCommands::Deploy(deploy) => dozer.deploy(cloud, deploy, cli.config_paths),
201
                CloudCommands::Api(api) => dozer.api(cloud, api),
202
                CloudCommands::Login {
203
                    organisation_slug,
204
                    profile_name,
205
                    client_id,
206
                    client_secret,
207
                } => dozer.login(
208
                    cloud,
209
                    organisation_slug,
210
                    profile_name,
211
                    client_id,
212
                    client_secret,
213
                ),
214
                CloudCommands::Secrets(command) => dozer.execute_secrets_command(cloud, command),
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
}
×
242

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

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

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

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

×
287
                    let mut command = Cli::command();
×
288
                    command = command.about(format!("\n\n\n{} \n {}", LOGO, description));
×
289

×
290
                    println!("{}", command.render_help());
×
291
                }
×
292

×
293
                error!("{}", e);
×
294
                Err(e)
×
295
            }
×
296
        }
×
297
    })
×
298
}
×
299

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

×
306
        error!("{}", description);
×
307
    } else {
×
308
        error!("{}", e);
×
309
    }
×
310
}
×
311

×
312
struct Telemetry();
×
313

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

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