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

getdozer / dozer / 5829357348

pending completion
5829357348

Pull #1839

github

aaryaattrey
typo
Pull Request #1839: load config from stdin

37 of 37 new or added lines in 4 files covered. (100.0%)

45551 of 59108 relevant lines covered (77.06%)

39686.65 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::{set_ctrl_handler, set_panic_hook, shutdown};
12
use dozer_types::models::telemetry::TelemetryConfig;
13
use dozer_types::tracing::{error, info};
14
use serde::Deserialize;
15
use tokio::time;
16

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

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

26
fn main() {
×
27
    set_panic_hook();
×
28

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

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

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

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

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

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

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

×
78
    let request_url = "https://metadata.dev.getdozer.io/";
×
79

×
80
    let client = reqwest::Client::new();
×
81

×
82
    let mut printed = false;
×
83

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

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

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

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

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

126
    let cli = parse_and_generate()?;
×
127
    if cli.ignore_pipe {
×
128
        std::env::set_var("ENABLE_PIPES", "true");
×
129
    }
×
130
    let mut dozer = init_orchestrator(&cli)?;
×
131

×
132
    let (shutdown_sender, shutdown_receiver) = shutdown::new(&dozer.runtime);
×
133
    set_ctrl_handler(shutdown_sender);
×
134

×
135
    // Now we have access to telemetry configuration. Telemetry must be initialized in tokio runtime.
×
136
    let app_name = dozer.config.app_name.clone();
×
137
    let app_id = dozer
×
138
        .config
×
139
        .cloud
×
140
        .as_ref()
×
141
        .map(|cloud| cloud.app_id.clone().unwrap_or(app_name));
×
142
    let _telemetry = dozer
×
143
        .runtime
×
144
        .block_on(async { Telemetry::new(app_id.as_deref(), dozer.config.telemetry.clone()) });
×
145

×
146
    if let Some(cmd) = cli.cmd {
×
147
        // run individual servers
×
148
        match cmd {
×
149
            Commands::Run(run) => match run.command {
×
150
                RunCommands::Api => {
151
                    render_logo();
×
152

×
153
                    dozer.run_api(shutdown_receiver)
×
154
                }
×
155
                RunCommands::App => {
156
                    render_logo();
×
157

×
158
                    dozer.run_apps(shutdown_receiver, None, None)
×
159
                }
×
160
            },
×
161
            Commands::Security(security) => match security.command {
×
162
                SecurityCommands::GenerateToken => {
163
                    let token = dozer.generate_token()?;
×
164
                    info!("token: {:?} ", token);
×
165
                    Ok(())
×
166
                }
×
167
            },
×
168
            Commands::Build(build) => {
×
169
                let force = build.force.is_some();
×
170

×
171
                dozer.build(force)
×
172
            }
×
173
            Commands::Connectors(ConnectorCommand { filter }) => list_sources(
×
174
                cli.config_paths,
×
175
                cli.config_token,
×
176
                cli.config_overrides,
×
177
                filter,
×
178
            ),
×
179
            Commands::Clean => dozer.clean(),
×
180
            #[cfg(feature = "cloud")]
181
            Commands::Cloud(cloud) => {
182
                render_logo();
183

184
                match cloud.command.clone() {
185
                    CloudCommands::Deploy(deploy) => dozer.deploy(cloud, deploy, cli.config_paths),
186
                    CloudCommands::Api(api) => dozer.api(cloud, api),
187
                    CloudCommands::Login {
188
                        organisation_slug,
189
                        profile_name,
190
                        client_id,
191
                        client_secret,
192
                    } => dozer.login(
193
                        cloud,
194
                        organisation_slug,
195
                        profile_name,
196
                        client_id,
197
                        client_secret,
198
                    ),
199
                    CloudCommands::Secrets(command) => {
200
                        dozer.execute_secrets_command(cloud, command)
201
                    }
202
                    CloudCommands::Delete => dozer.delete(cloud),
203
                    CloudCommands::Status => dozer.status(cloud),
204
                    CloudCommands::Monitor => dozer.monitor(cloud),
205
                    CloudCommands::Logs(logs) => dozer.trace_logs(cloud, logs),
206
                    CloudCommands::Version(version) => dozer.version(cloud, version),
207
                    CloudCommands::List(list) => dozer.list(cloud, list),
208
                    CloudCommands::SetApp { app_id } => {
209
                        CloudAppContext::save_app_id(app_id.clone())?;
210
                        info!("Using \"{app_id}\" app");
211
                        Ok(())
212
                    }
×
213
                }
214
            }
215
            Commands::Init => {
×
216
                panic!("This should not happen as it is handled in parse_and_generate");
×
217
            }
×
218
        }
219
    } else {
220
        render_logo();
×
221

×
222
        dozer.run_all(shutdown_receiver, None)
×
223
    }
×
224
}
×
225

×
226
// Some commands dont need to initialize the orchestrator
227
// This function is used to run those commands
228
fn parse_and_generate() -> Result<Cli, OrchestrationError> {
×
229
    dozer_tracing::init_telemetry_closure(None, None, || -> Result<Cli, OrchestrationError> {
×
230
        let cli = Cli::parse();
×
231

×
232
        if let Some(Commands::Init) = cli.cmd {
×
233
            Telemetry::new(None, None);
×
234
            if let Err(e) = generate_config_repl() {
×
235
                error!("{}", e);
×
236
                Err(e)
×
237
            } else {
×
238
                // We need to exit here, otherwise the orchestrator will be initialized
239
                process::exit(0);
×
240
            }
×
241
        } else {
242
            Ok(cli)
×
243
        }
×
244
    })
×
245
}
×
246

×
247
fn init_orchestrator(cli: &Cli) -> Result<SimpleOrchestrator, CliError> {
×
248
    dozer_tracing::init_telemetry_closure(None, None, || -> Result<SimpleOrchestrator, CliError> {
×
249
        let res = init_dozer(
×
250
            cli.config_paths.clone(),
×
251
            cli.config_token.clone(),
×
252
            cli.config_overrides.clone(),
×
253
        );
×
254

×
255
        match res {
×
256
            Ok(dozer) => {
×
257
                dozer.runtime.spawn(check_update());
×
258
                Ok(dozer)
×
259
            }
×
260
            Err(e) => {
×
261
                if let CliError::FailedToFindConfigurationFiles(_) = &e {
×
262
                    let description = "Dozer was not able to find configuration files. \n\n\
×
263
                    Please use \"dozer init\" to create project or \"dozer -c {path}\" with path to your configuration.\n\
×
264
                    Configuration documentation can be found in https://getdozer.io/docs/configuration";
×
265

×
266
                    let mut command = Cli::command();
×
267
                    command = command.about(format!("\n\n\n{} \n {}", LOGO, description));
×
268

×
269
                    println!("{}", command.render_help());
×
270
                }
×
271

×
272
                error!("{}", e);
×
273
                Err(e)
×
274
            }
×
275
        }
276
    })
×
277
}
×
278

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

×
285
        error!("{}", description);
×
286
    } else {
×
287
        error!("{}", e);
×
288
    }
×
289
}
×
290

×
291
struct Telemetry();
292

293
impl Telemetry {
294
    fn new(app_name: Option<&str>, config: Option<TelemetryConfig>) -> Self {
×
295
        dozer_tracing::init_telemetry(app_name, config);
×
296
        Self()
×
297
    }
×
298
}
×
299

300
impl Drop for Telemetry {
301
    fn drop(&mut self) {
×
302
        dozer_tracing::shutdown_telemetry();
×
303
    }
×
304
}
×
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