nazara 0.2.1

A CLI application to create and update machines and VMs in NetBox.
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! # Nazara
//!
//! Nazara is an experimental Rust program that automates the collection of system information for
//! NetBox.
//! It enables the automatic creation of new machines in NetBox or population of information fields
//! for existing ones.
//!
//! > Note: Nazara is currently in an alpha state. Bugs are bound to happen. If you encounter any,
//!> please [report them](https://codeberg.org/nazara-project/Nazara/issues)
//! >
//! > Furthermore, *Nazara currently does not fully support custom fields for any NetBox object*.
//!> Though this is the next item on our agenda.
//!
//! # Installation
//!
//! ## Building from source
//!
//! To use Nazara, you will need to have the Rust programming language and `cargo` installed. If you do not have them
//! installed already, you can follow the instructions provided in the [official Rust documentation](https://www.rust-lang.org/tools/install).
//!
//! *Please note that this program only works on Linux systems.*
//!
//! Once you have everything installed, you can clone this repository and build the program by running the following commands:
//!
//! ```bash
//! git clone https://codeberg.org/nazara-project/Nazara.git
//! cd Nazara
//! cargo build --release
//! ```
//!
//! This will create an executable file in the `target/release` directory.
//!
//! ### Installation via `crates.io`
//!
//! Nazara is published on `crates.io`. If your operating system permits cargo to install packages globally, simply run `cargo install nazara` to install it.
//!
//! # Usage
//!
//! To use Nazara, you will need to configure the URL of your NetBox API and provide an API token to the program by
//! configuring all of these parameters inside the [configuration file](#configuring-via-nazaraconfigtomlfile).
//!
//! After that, simply run
//!
//! ```bash
//!  nazara register
//! ```
//!
//! to register a new machine, or run
//!
//! ```bash
//!  nazara update $MACHINE_ID
//! ```
//!
//! to update an existing one.
//!
//!
//! in your terminal. Nazara will automatically collect all required system information and decide whether to create a new device, or update an existing entry.
//!
//! # Configuration
//!
//! Nazara supports two ways of providing configuration parameters: CLI arguments and a configuration file.
//!
//! Nazara requires two parameters from you:
//!
//! - `API_URL`: The URL of your NetBox API
//! - `API_TOKEN`: The authentication token for the NetBox API
//!
//! ## Configuring via CLI
//!
//! Here is an example for passing these parameters on using the CLI:
//!
//! ```bash
//! sudo ./target/release/Nazara --uri <API_URL> --token <API_TOKEN>
//! ```
//!
//! ## Configuring via `$HOME/.config/nazara/config.toml`file.
//!
//! Nazara's configuration must be located in the root user's home directory at `$HOME/.config/nazara/config.toml`.
//!
//! Aside from the NetBox system parameters, configuration via the `config.toml` also allows you to add certain
//! custom fields to your system information that cannot be automatically selected. A great example would be the
//! `System Location` entry. To specify that, simply add the parameter under the `[system]` block in your configuration file.
//!
//! A default configuration file looks like this:
//!
//! ```toml
#![doc = include_str!("configuration/config_template.toml")]
//! ```
//!
//! ### The `config` commands
//!
//! Nazara provides you with several commands to manage your configuration files:
//!
//! - `write-config`: Write a new config file or overwrite an existing one.
//! - `check-config`: Validate if your config is still valid.
//! - `view-config`: Print config to console.
//!
//! The `write-config` allows you to change individual parameters, or perform a bulk update by passing a `JSON` structure
//! via CLI. **These options are exclusive. Passing both is disallowed.**
//!
//! For further information on how to configure Nazara, run `nazara --help` or visit [our documentation](https://the-nazara-project.github.io/Nazara/users/configuration.html).
//!
//! *Please note that this section is still a work in progress and all information is subject to change.*
//!
//! ## Configuring custom fields using user plugins
//!
//! Users are able to fill `custom_fields` parameters in their NetBox objects using custom bash scripts.
//! These scripts should be placed inside the `$HOME/.config/nazara/scripts/` directory.
//!
//! These scripts can collect the desired information and output *a valid JSON representation* to `stdout`.
//! Nazara then reads this output, validates it, and attempts to parse it to a `HashMap` of values.
//!
//! If everything works out, this will populate all of your custom fields no matter what fields you specified, as long as your script
//! is correct.
//!
//! > Warning:
//! >
//! > Users must make sure that the output of their scripts matches the name of their desired custom fields they specified
//! > in NetBox.
//! >
//! > Currently, **we only support text fields** as all the other field types would require smart parsing on our end.
//! > We are currently investigating on how to achieve this.
//!
//!# Contributing
//!
//! If you would like to contribute to Nazara, feel free to check the [contributing guide](./CONTRIBUTING.md) for
//! information on our workflow and check the issues section for any open issue.
//!
//! # License
//!
//! Nazara is released under the terms of the [GPL-v3.0](./LICENSE).

#[macro_use]
pub mod output;

pub mod collectors;
pub mod configuration;
pub mod constants;
pub mod error;
pub mod investigator;
pub mod publisher;

use clap::{Parser, Subcommand, ValueEnum};
use collectors::{
    dmi::{self, DmiInformation},
    network::{self, NetworkInformation},
    plugin::execute,
};
use configuration::parser::{
    check_config_file, set_up_configuration, view_config_file, write_config_file,
};
use investigator::check_environment;
use publisher::{
    auto_register_or_update_machine, register_machine, test_connection, update_machine,
};
use reqwest::blocking::Client;
use serde_json::Value;
use std::collections::HashMap;
use thanix_client::util::ThanixClient;

use crate::configuration::parser::ConfigData;
use crate::error::*;

use std::sync::OnceLock;

// ================================================
// =========NAZARA INFORMATION STATE===============
// ================================================

/// Represent application state.
///
/// # Fields
/// * `args: Args` - Command line arguments
/// * `config: Option<ConfigData>` - Application configuration
/// * `client: Option<ThanixClient>` - API client instance.
pub struct Nazara {
    args: Args,
    config: Option<ConfigData>,
    client: Option<ThanixClient>,
}

#[derive(PartialEq, PartialOrd, ValueEnum, Clone, Debug)]
pub enum LogLevelList {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
    Fatal,
}

//pub static LOG_LEVEL: LogLevelList = LogLevelList::Debug; //
pub static LOG_LEVEL: OnceLock<LogLevelList> = OnceLock::new();

/// This struct represents your machine.
/// It holds all information collected and allows for sharing this
/// information between Nazara's modules.
///
/// It is used in places where it is necessary to have access to various
/// pieces of collected information from a single source of truth.
/// It will also be translated into the proper API type by the translator.
#[derive(Debug)]
pub struct Machine {
    /// The name of the system to register. Read from the CLI.
    pub name: Option<String>,
    /// Information collected by `dmidecode`.
    pub dmi_information: DmiInformation,
    /// List of network interfaces.
    pub network_information: Vec<NetworkInformation>,
    /// Custom fields read from config file or via plugins.
    pub custom_information: Option<HashMap<String, Value>>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum IpAssignmentMode {
    /// Fully manage IPs in NetBox (default)
    Static,
    /// Do not create or update IP addresses; only interfaces. (DHCP managed externally)
    DhcpIgnore,
    /// Register all IP Addresses the machine currently has, even though they're managed by DHCP.
    DhcpObserved,
}

impl Nazara {
    /// Create a new `Nazara` instance representing the entire
    /// application state.
    ///
    /// # Returns
    ///
    /// A `Nazara` instance or a `NazaraError`.
    pub fn new() -> NazaraResult<Self> {
        let args = Args::parse();
        Ok(Self {
            args,
            config: None,
            client: None,
        })
    }

    /// Run the application.
    ///
    /// 1. If any `config` command has been given, their operation is executed
    /// 2. Collect machine data
    /// 3. Parse and set up the configuration
    /// 4. Set up an API client instance
    /// 5. Execute the specified operation
    ///
    /// # Returns
    /// Returns a `NazaraResult`, escalating any errors to the top, or
    /// returning an empty `Ok(())`.
    pub fn run(&mut self) -> NazaraResult<()> {
        LOG_LEVEL.set(self.args.log_level.clone()).unwrap();
        Self::print_banner();

        if let Some(_) = self.handle_config_commands()? {
            return Ok(());
        }

        let machine = self.prepare_machine()?;

        self.config = Some(set_up_configuration(
            self.args.uri.as_deref(),
            self.args.token.as_deref(),
        )?);
        self.client = Some(self.prepare_client()?);

        self.execute_operation(machine)?;

        success!("All done, have a nice day!");
        Ok(())
    }

    /// Print the welcome banner.
    fn print_banner() -> () {
        const ASCII_ART: &str = r#"
    ███╗   ██╗ █████╗ ███████╗ █████╗ ██████╗  █████╗
    ████╗  ██║██╔══██╗╚══███╔╝██╔══██╗██╔══██╗██╔══██╗
    ██╔██╗ ██║███████║  ███╔╝ ███████║██████╔╝███████║
    ██║╚██╗██║██╔══██║ ███╔╝  ██╔══██║██╔══██╗██╔══██║
    ██║ ╚████║██║  ██║███████╗██║  ██║██║  ██║██║  ██║
    ╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝
    (c) Tiara Hock aka BytePaws. (codeberg.org/BytePaws)

    Licensed under the terms of the GPL-v3.0 License.
    Check https://codeberg.org/nazara-project/Nazara/src/branch/main/LICENSE for more info.
"#;
        println!("{ASCII_ART}");
    }

    /// Parse the config subcommands.
    fn handle_config_commands(&self) -> NazaraResult<Option<()>> {
        match &self.args.command {
            Commands::WriteConfig {
                uri,
                token,
                name,
                description,
                comments,
                status,
                primary_ip4,
                primary_ip6,
                device_type,
                tenant,
                location,
                rack,
                platform,
                site,
                role,
                cluster_id,
                force,
                json,
            } => {
                status!("Writing configuration file...");
                if json.is_some() {
                    write_config_file(
                        uri,   // ignored in JSON mode
                        token, // ignored in JSON mode
                        name,
                        description,
                        comments,
                        status,
                        primary_ip4,
                        primary_ip6,
                        device_type,
                        tenant,
                        location,
                        rack,
                        platform,
                        role,
                        site,
                        cluster_id,
                        force,
                        json,
                    )?;
                } else {
                    write_config_file(
                        uri,
                        token,
                        name,
                        description,
                        comments,
                        status,
                        primary_ip4,
                        primary_ip6,
                        device_type,
                        tenant,
                        location,
                        rack,
                        platform,
                        role,
                        site,
                        cluster_id,
                        force,
                        &None,
                    )?;
                }
                success!("Configuration written successfully.");
                return Ok(Some(()));
            }
            Commands::CheckConfig => {
                check_config_file()?;
                return Ok(Some(()));
            }
            Commands::ViewConfig => {
                view_config_file()?;
                return Ok(Some(()));
            }
            Commands::PrepareEnvironment => {
                let config =
                    set_up_configuration(self.args.uri.as_deref(), self.args.token.as_deref())?;
                let client = ThanixClient {
                    base_url: config.get_netbox_uri().to_string(),
                    authentication_token: config.get_api_token().to_string(),
                    client: Client::new(),
                };
                test_connection(&client)?;
                check_environment(&client, &config, true)?;
                return Ok(Some(()));
            }
            _ => Ok(None),
        }
    }

    /// Prepare machine information by starting the dmi and network collectors.
    ///
    /// # Exits
    ///
    /// If `--dry-run` has been passed, prints the collected information
    /// to the terminal and exits the programm with exit code `0`.
    fn prepare_machine(&self) -> NazaraResult<Machine> {
        let machine = start_collection(self.args.plugin.clone())?;

        // Passing a name in any way is mandatory for a virtual machine.
        if machine.dmi_information.system_information.is_virtual && machine.name.is_none() {
            return Err(NazaraError::Other(
            "No name has been provided for this virtual machine! Providing a name as search parameter is mandatory for virtual machines.".into(),
        ));
        }

        // If we only want to do a dry run, we only have to print the collected information.
        //? should this be an `info!` or should it remain a println?
        if self.args.dry_run {
            println!("Dry run results:");
            dbg!(&machine);
            std::process::exit(0)
        }
        Ok(machine)
    }

    /// Prepare `ThanixClient` instance for use,
    fn prepare_client(&self) -> NazaraResult<ThanixClient> {
        let config = set_up_configuration(self.args.uri.as_deref(), self.args.token.as_deref())?;

        let client = ThanixClient {
            base_url: config.get_netbox_uri().to_string(),
            authentication_token: config.get_api_token().to_string(),
            client: Client::new(),
        };
        status!("Testing connection...");
        test_connection(&client)?;
        Ok(client)
    }

    /// Execute specified operation (register/update)
    fn execute_operation(&self, machine: Machine) -> NazaraResult<()> {
        let client = self
            .client
            .as_ref()
            .ok_or_else(|| NazaraError::Other("Client not initialized".into()))?;
        let config = self
            .config
            .as_ref()
            .ok_or_else(|| NazaraError::Other("Configuration not initialized".into()))?;

        match &self.args.command {
            Commands::Register {
                ip_mode,
                prepare_environment,
            } => {
                check_environment(client, config, *prepare_environment)?;
                let mode = ip_mode.unwrap_or(IpAssignmentMode::Static);
                register_machine(client, machine, config.clone(), mode)?
            }
            Commands::Update {
                id,
                ip_mode,
                prepare_environment,
            } => {
                check_environment(client, config, *prepare_environment)?;
                let mode = ip_mode.unwrap_or(IpAssignmentMode::Static);
                update_machine(client, machine, config.clone(), id.to_owned(), mode)?
            }
            Commands::Auto { ip_mode } => {
                warn_auto_deprecated();
                let mode = ip_mode.unwrap_or(IpAssignmentMode::Static);
                auto_register_or_update_machine(client, machine, config.clone(), mode)?;
            }
            _ => {}
        }

        Ok(())
    }
}

pub fn warn_auto_deprecated() {
    let msg = "
\x1b[33m[WARNING] +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [WARNING]\x1b[0m
\x1b[33m[WARNING] Running Nazara in 'Auto' mode is deprecated. Please use 'register' or 'update' subcommands instead. [WARNING]\x1b[0m
\x1b[33m[WARNING] +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [WARNING]\x1b[0m
";
    println!("{}", msg);
}

/// Collect machine information.
///
/// Stubs the collector to start putting together all information about the machine.
///
/// # Parameters
///
/// * `plugin: Option<String>` - The path to a plugin. (optional)
///
/// # Returns
///
/// Either a `Machine` instance or a `NazaraError`, if collection failed.
pub fn start_collection(plugin: Option<String>) -> NazaraResult<Machine> {
    Ok(Machine {
        name: None,
        dmi_information: dmi::construct_dmi_information()?,
        network_information: network::construct_network_information()?,
        custom_information: Some(execute(plugin)?),
    })
}

// ================================================
// =========COMMAND LINE INTERFACE=================
// ================================================

#[derive(Debug, Subcommand)]
enum Commands {
    /// Register a new machine.
    // Any future arguments for this command into its block.
    Register {
        /// IP assignment mode. (default: static)
        #[arg(long, value_enum, default_value = "static")]
        ip_mode: Option<IpAssignmentMode>,

        /// Create missing NetBox entities (tags) instead of failing.
        #[arg(long)]
        prepare_environment: bool,
    },
    /// Update a given machine by ID.
    Update {
        /// The ID of the machine in NetBox.
        #[arg(long)]
        id: i64,
        /// IP assignment mode. (default: static)
        #[arg(long, value_enum, default_value = "static")]
        ip_mode: Option<IpAssignmentMode>,

        /// Create missing NetBox entities (tags) instead of failing.
        #[arg(long)]
        prepare_environment: bool,
    },
    /// Attempt to detect whether an update or new registration is necessary. (DEPRECATED, old default behaviour)
    Auto {
        /// IP assignment mode. (default: static)
        #[arg(long, value_enum, default_value = "static")]
        ip_mode: Option<IpAssignmentMode>,
    },
    /// Write new config file or overwrite existing one with new values. Pass JSON for bulk changes.
    WriteConfig {
        /// The URI of your NetBox instance. Required if not using '--json'.
        #[arg(short, long, conflicts_with = "json")]
        uri: Option<String>,

        /// Your NetBox authentication token. Required if not using '--json'.
        #[arg(short, long, conflicts_with = "json")]
        token: Option<String>,

        /// The machine's name. (Optional; default: hostname)
        #[arg(short, long, conflicts_with = "json")]
        name: Option<String>,

        /// A description of the machine. (Optional)
        #[arg(short, long, conflicts_with = "json")]
        description: Option<String>,

        /// A comment for the entry. (Optional; default: 'Automatically registered by Nazara')
        #[arg(short, long, conflicts_with = "json")]
        comments: Option<String>,

        /// The status of the machine. (Optional; defaults: 'active')
        #[arg(short, long, conflicts_with = "json")]
        status: Option<String>,

        /// Device type ID. (if this is a physical device)
        #[arg(long, conflicts_with = "json")]
        device_type: Option<i64>,

        /// Tenant of this device or VM
        #[arg(long, conflicts_with = "json")]
        tenant: Option<i64>,

        /// ID of the platform of this device or VM
        #[arg(long, conflicts_with = "json")]
        platform: Option<i64>,

        /// Location of this device or VM
        #[arg(long, conflicts_with = "json")]
        location: Option<i64>,

        /// ID of the rack of this device
        #[arg(long, conflicts_with = "json")]
        rack: Option<i64>,

        /// Device role ID.
        #[arg(long, conflicts_with = "json")]
        role: Option<i64>,

        /// Site ID. (for physical devices)
        #[arg(long, conflicts_with = "json")]
        site: Option<i64>,

        /// Cluster ID. (for VMs)
        #[arg(long, conflicts_with = "json")]
        cluster_id: Option<i64>,

        /// Primary IPv4 address (optional)
        #[arg(long, conflicts_with = "json")]
        primary_ip4: Option<String>,

        /// Primary IPv6 address (optional)
        #[arg(long, conflicts_with = "json")]
        primary_ip6: Option<String>,

        /// Forces a new config file, overwriting any existing configs
        #[arg(long)]
        force: bool,

        /// JSON of your configuration parameters. (Optional; exclusive with other options.)
        #[arg(long, conflicts_with_all = &[
            "uri", "token", "name", "description", "comments",
            "status", "primary_ipv4", "primary_ipv6", "device_type", "role", "site", "cluster_id"
        ])]
        json: Option<String>,
    },
    /// Validate configuration file.
    CheckConfig,
    /// Print currently active config options.
    ViewConfig,
    /// Create any NetBox entity that does not already exist
    PrepareEnvironment,
}

/// The arguments that Nazara expects to get via the cli.
///
/// Arguments can be passed like this:
///
/// ```
/// nazara --uri <NETBOX_URI> --token <NETBOX_TOKEN> register
/// ```
///
/// These arguments override the ones defined in the `$HOME/.config/nazara/config.toml`.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about=None)]
struct Args {
    /// Only prints collected information to stdout.
    #[arg(short, long)]
    dry_run: bool,

    /// Temporarily overwrite the url to your NetBox instance.
    #[arg(short, long)]
    uri: Option<String>,

    /// Temporarily use a different authentication token for NetBox.
    #[arg(short, long)]
    token: Option<String>,

    /// The Path to a plugin script you want to run.
    #[arg(short, long)]
    plugin: Option<String>,

    ///Output level, defaults to Debug
    #[arg(long, default_value = "debug", value_enum)]
    log_level: LogLevelList,

    /// Subcommands.
    #[command(subcommand)]
    command: Commands,
}