upend/cli/src/main.rs

557 lines
18 KiB
Rust
Raw Normal View History

2020-08-27 00:11:50 +02:00
#[macro_use]
2023-06-25 15:29:52 +02:00
extern crate upend_db;
2024-01-26 22:41:43 +01:00
use crate::common::{REQWEST_ASYNC_CLIENT, WEBUI_PATH};
2023-06-25 15:29:52 +02:00
use crate::config::UpEndConfig;
use actix_web::HttpServer;
use anyhow::Result;
ci: switch to Earthly Squashed commit of the following: commit 06baa23fc82f1f723bbfb1ab69c97802d28efa19 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:10:19 2023 +0200 ci, fix: forgot push commit 6494be49d282368dd7c4aa78f56ccb33acac3eaa Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:01:14 2023 +0200 fix, ci: docker tag arg commit 38682ba930abfeec5bf7facffbd0b94f6d61af9e Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:54:45 2023 +0200 ci: parallelize push steps commit 5eeab18aa0d3fa3a7ef88e71cb5e9b5be5e7b9df Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:52:37 2023 +0200 ci, fix: docker login commit ce10d0d04a55282cb4d95136e695705f95f11a86 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:52 2023 +0200 ci: remove earthly verbose commit ff9b84296868bd18f004bdfcc23832acadeac388 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:23 2023 +0200 ci, fix: typo commit df80ee061006c5eaa9b729a69818fd8bd273865c Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:06:47 2023 +0200 ci, refactor: better step names commit 80093f8964cfd4cfa9e8b5ce4b6854c5c48060e4 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:05:03 2023 +0200 ci, fix: earthly config for publish:appimage step commit 650824df99495afcc3feb4fcaa3e336b691d3008 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:04:50 2023 +0200 ci, refactor: only explicitly copy AppImages in sign target commit 3b53e2dc6475e55f64fa9d00a2f2d31f07a9d8bb Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 08:01:43 2023 +0200 ci: EARTHLY_VERBOSE=1 commit cec95ea29a4f207fe1b7790b70562b1eeabee195 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:10:09 2023 +0200 ci: earthly bootstrap after conf commit 7afe653d575a8ff76488d8fe3a93bc5e679124e5 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:04:08 2023 +0200 ci, fix: remove ssh_key secret commit b549d891ed789743066d3c29e12b6b82fcab35a3 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 22:02:01 2023 +0200 ci, fix: missing gpg-agent commit 47938c71474ec39b0d989742f9e1446b6df94bca Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 20:55:15 2023 +0200 ci, fix: unify earthly config commit 7b89ea7ef4957a9925c4250c662bdd4d204b53dd Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 19:59:37 2023 +0200 ci: publishing docker, appimage, nightlies commit f4f94d98644c7cc1506103538a30db241108b589 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 18:19:00 2023 +0200 ci: add lint & test step commit be180ed59b216cfc85953ac5841eb11933a3a000 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:13:03 2023 +0200 ci, wip: earthly integration commit 39db638cbdaaf5a436de8d531da2f68f85264430 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:12:21 2023 +0200 ci: use `upend --version` for AppImage, move get_version.sh logic to cli commit 5188336c7eca877c0174ffa655893b287bc97baa Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 12:30:47 2023 +0200 ci: refix AppImage, switch to appimage-builder, build docker commit 27f7941020bcf2e103d1e476038a6bc65f4153ea Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:55:03 2023 +0200 wip: remote woodpecker CI config for the time being commit 53e775b85d2408060b034c2eff76e81b30b3dae5 Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:59 2023 +0200 wip: delete .env it's interpreted by Earthly and I'm not sure it's necessary anyway commit 26bec328036c03dcb9a1917f9cf531bf7d10bb7d Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:32 2023 +0200 wip: initial somewhat functional Earthfile
2023-08-23 12:13:24 +02:00
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use filebuffer::FileBuffer;
use rand::{thread_rng, Rng};
2023-05-04 19:16:01 +02:00
use regex::Captures;
use regex::Regex;
use reqwest::Url;
use serde_json::json;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use tracing::trace;
use tracing::{debug, error, info, warn};
2022-08-07 12:13:12 +02:00
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
2023-06-25 15:29:52 +02:00
use upend_base::addressing::Address;
use upend_base::entry::EntryValue;
2023-06-29 14:29:38 +02:00
use upend_base::hash::{sha256hash, UpMultihash};
2023-06-25 15:29:52 +02:00
use upend_db::jobs::JobContainer;
use upend_db::stores::fs::FsStore;
use upend_db::stores::UpStore;
use upend_db::{BlobMode, UpEndDatabase};
use crate::util::exec::block_background;
2023-05-24 11:20:13 +02:00
mod common;
2023-06-25 15:29:52 +02:00
mod config;
2020-08-27 01:07:25 +02:00
mod routes;
mod serve;
2020-09-14 21:18:53 +02:00
mod util;
2020-08-27 00:11:50 +02:00
mod extractors;
mod previews;
#[derive(Debug, Parser)]
ci: switch to Earthly Squashed commit of the following: commit 06baa23fc82f1f723bbfb1ab69c97802d28efa19 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:10:19 2023 +0200 ci, fix: forgot push commit 6494be49d282368dd7c4aa78f56ccb33acac3eaa Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:01:14 2023 +0200 fix, ci: docker tag arg commit 38682ba930abfeec5bf7facffbd0b94f6d61af9e Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:54:45 2023 +0200 ci: parallelize push steps commit 5eeab18aa0d3fa3a7ef88e71cb5e9b5be5e7b9df Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:52:37 2023 +0200 ci, fix: docker login commit ce10d0d04a55282cb4d95136e695705f95f11a86 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:52 2023 +0200 ci: remove earthly verbose commit ff9b84296868bd18f004bdfcc23832acadeac388 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:23 2023 +0200 ci, fix: typo commit df80ee061006c5eaa9b729a69818fd8bd273865c Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:06:47 2023 +0200 ci, refactor: better step names commit 80093f8964cfd4cfa9e8b5ce4b6854c5c48060e4 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:05:03 2023 +0200 ci, fix: earthly config for publish:appimage step commit 650824df99495afcc3feb4fcaa3e336b691d3008 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:04:50 2023 +0200 ci, refactor: only explicitly copy AppImages in sign target commit 3b53e2dc6475e55f64fa9d00a2f2d31f07a9d8bb Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 08:01:43 2023 +0200 ci: EARTHLY_VERBOSE=1 commit cec95ea29a4f207fe1b7790b70562b1eeabee195 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:10:09 2023 +0200 ci: earthly bootstrap after conf commit 7afe653d575a8ff76488d8fe3a93bc5e679124e5 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:04:08 2023 +0200 ci, fix: remove ssh_key secret commit b549d891ed789743066d3c29e12b6b82fcab35a3 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 22:02:01 2023 +0200 ci, fix: missing gpg-agent commit 47938c71474ec39b0d989742f9e1446b6df94bca Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 20:55:15 2023 +0200 ci, fix: unify earthly config commit 7b89ea7ef4957a9925c4250c662bdd4d204b53dd Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 19:59:37 2023 +0200 ci: publishing docker, appimage, nightlies commit f4f94d98644c7cc1506103538a30db241108b589 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 18:19:00 2023 +0200 ci: add lint & test step commit be180ed59b216cfc85953ac5841eb11933a3a000 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:13:03 2023 +0200 ci, wip: earthly integration commit 39db638cbdaaf5a436de8d531da2f68f85264430 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:12:21 2023 +0200 ci: use `upend --version` for AppImage, move get_version.sh logic to cli commit 5188336c7eca877c0174ffa655893b287bc97baa Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 12:30:47 2023 +0200 ci: refix AppImage, switch to appimage-builder, build docker commit 27f7941020bcf2e103d1e476038a6bc65f4153ea Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:55:03 2023 +0200 wip: remote woodpecker CI config for the time being commit 53e775b85d2408060b034c2eff76e81b30b3dae5 Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:59 2023 +0200 wip: delete .env it's interpreted by Earthly and I'm not sure it's necessary anyway commit 26bec328036c03dcb9a1917f9cf531bf7d10bb7d Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:32 2023 +0200 wip: initial somewhat functional Earthfile
2023-08-23 12:13:24 +02:00
#[command(name = "upend", author)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Perform a query against an UpEnd server instance.
Query {
/// URL of the UpEnd instance to query.
2023-04-25 19:33:57 +02:00
#[arg(short, long, default_value = "http://localhost:8093")]
url: Url,
2023-05-04 19:47:45 +02:00
/// The query itself, in L-expression format; prefix a filepath by `@=` to insert its hash in its place.
query: String,
/// Output format
#[arg(short, long, default_value = "tsv")]
format: OutputFormat,
},
Get {
/// URL of the UpEnd instance to query.
#[arg(short, long, default_value = "http://localhost:8093")]
url: Url,
/// The address of the entity; prefix a filepath by `=` to insert its hash.
entity: String,
/// The attribute to get the value(s) of. Optional.
attribute: Option<String>,
/// Output format
#[arg(short, long, default_value = "tsv")]
format: OutputFormat,
},
2023-05-04 19:47:45 +02:00
/// Insert an entry into an UpEnd server instance.
Insert {
/// URL of the UpEnd instance to query.
#[arg(short, long, default_value = "http://localhost:8093")]
url: Url,
/// The address of the entity; prefix a filepath by `=` to insert its hash.
entity: String,
2023-05-04 19:47:45 +02:00
/// The attribute of the entry.
attribute: String,
2023-05-04 19:47:45 +02:00
/// The value; its type will be heurestically determined.
2023-05-04 18:54:17 +02:00
value: String,
/// Output format
#[arg(short, long, default_value = "tsv")]
format: OutputFormat,
},
2023-05-04 19:47:45 +02:00
/// Get the address of a file, attribute, or URL.
Address {
/// Type of input to be addressed
_type: AddressType,
/// Path to a file, hash...
input: String,
/// Output format
#[arg(short, long, default_value = "tsv")]
format: OutputFormat,
},
/// Start an UpEnd server instance.
Serve(ServeArgs),
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
enum OutputFormat {
2023-05-04 19:47:45 +02:00
/// JSON
Json,
2023-05-04 19:47:45 +02:00
/// Tab Separated Values
Tsv,
2023-05-04 19:47:45 +02:00
/// Raw, as received from the server
Raw,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
enum AddressType {
/// Hash a file and output its address.
File,
/// Compute an address from the output of `sha256sum`
Sha256sum,
}
#[derive(Debug, Args)]
struct ServeArgs {
/// Directory to serve a vault from.
#[arg()]
directory: PathBuf,
/// Address and port to bind the Web interface on.
#[arg(long, default_value = "127.0.0.1:8093")]
bind: String,
/// Path to blob store ($VAULT_PATH by default).
#[arg(long)]
store_path: Option<PathBuf>,
/// Do not open a web browser with the UI.
#[arg(long)]
no_browser: bool,
/// Disable desktop features (web browser, native file opening).
#[arg(long, env = "UPEND_NO_DESKTOP")]
no_desktop: bool,
/// Trust the vault, and open local executable files.
#[arg(long)]
trust_executables: bool,
/// Do not serve the web UI.
#[arg(long)]
no_ui: bool,
/// Do not run a database update on start.
#[arg(long)]
no_initial_update: bool,
/// Which mode to use for rescanning the vault.
#[arg(long)]
rescan_mode: Option<BlobMode>,
/// Clean up temporary files (e.g. previews) on start.
#[arg(long)]
clean: bool,
/// Delete and initialize database, if it exists already.
#[arg(long)]
reinitialize: bool,
/// Name of the vault.
#[arg(long, env = "UPEND_VAULT_NAME")]
vault_name: Option<String>,
/// Secret to use for authentication.
#[arg(long, env = "UPEND_SECRET")]
secret: Option<String>,
/// Authentication key users must supply.
#[arg(long, env = "UPEND_KEY")]
key: Option<String>,
/// Allowed host/domain name the API can serve.
#[arg(long, env = "UPEND_ALLOW_HOST")]
allow_host: Vec<String>,
}
#[actix_web::main]
async fn main() -> Result<()> {
2023-10-22 21:18:00 +02:00
let command = Cli::command().version(crate::common::get_version());
ci: switch to Earthly Squashed commit of the following: commit 06baa23fc82f1f723bbfb1ab69c97802d28efa19 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:10:19 2023 +0200 ci, fix: forgot push commit 6494be49d282368dd7c4aa78f56ccb33acac3eaa Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 11:01:14 2023 +0200 fix, ci: docker tag arg commit 38682ba930abfeec5bf7facffbd0b94f6d61af9e Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:54:45 2023 +0200 ci: parallelize push steps commit 5eeab18aa0d3fa3a7ef88e71cb5e9b5be5e7b9df Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:52:37 2023 +0200 ci, fix: docker login commit ce10d0d04a55282cb4d95136e695705f95f11a86 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:52 2023 +0200 ci: remove earthly verbose commit ff9b84296868bd18f004bdfcc23832acadeac388 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:41:23 2023 +0200 ci, fix: typo commit df80ee061006c5eaa9b729a69818fd8bd273865c Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:06:47 2023 +0200 ci, refactor: better step names commit 80093f8964cfd4cfa9e8b5ce4b6854c5c48060e4 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:05:03 2023 +0200 ci, fix: earthly config for publish:appimage step commit 650824df99495afcc3feb4fcaa3e336b691d3008 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 10:04:50 2023 +0200 ci, refactor: only explicitly copy AppImages in sign target commit 3b53e2dc6475e55f64fa9d00a2f2d31f07a9d8bb Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 08:01:43 2023 +0200 ci: EARTHLY_VERBOSE=1 commit cec95ea29a4f207fe1b7790b70562b1eeabee195 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:10:09 2023 +0200 ci: earthly bootstrap after conf commit 7afe653d575a8ff76488d8fe3a93bc5e679124e5 Author: Tomáš Mládek <t@mldk.cz> Date: Wed Aug 23 07:04:08 2023 +0200 ci, fix: remove ssh_key secret commit b549d891ed789743066d3c29e12b6b82fcab35a3 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 22:02:01 2023 +0200 ci, fix: missing gpg-agent commit 47938c71474ec39b0d989742f9e1446b6df94bca Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 20:55:15 2023 +0200 ci, fix: unify earthly config commit 7b89ea7ef4957a9925c4250c662bdd4d204b53dd Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 19:59:37 2023 +0200 ci: publishing docker, appimage, nightlies commit f4f94d98644c7cc1506103538a30db241108b589 Author: Tomáš Mládek <t@mldk.cz> Date: Tue Aug 22 18:19:00 2023 +0200 ci: add lint & test step commit be180ed59b216cfc85953ac5841eb11933a3a000 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:13:03 2023 +0200 ci, wip: earthly integration commit 39db638cbdaaf5a436de8d531da2f68f85264430 Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 16:12:21 2023 +0200 ci: use `upend --version` for AppImage, move get_version.sh logic to cli commit 5188336c7eca877c0174ffa655893b287bc97baa Author: Tomáš Mládek <t@mldk.cz> Date: Mon Aug 21 12:30:47 2023 +0200 ci: refix AppImage, switch to appimage-builder, build docker commit 27f7941020bcf2e103d1e476038a6bc65f4153ea Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:55:03 2023 +0200 wip: remote woodpecker CI config for the time being commit 53e775b85d2408060b034c2eff76e81b30b3dae5 Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:59 2023 +0200 wip: delete .env it's interpreted by Earthly and I'm not sure it's necessary anyway commit 26bec328036c03dcb9a1917f9cf531bf7d10bb7d Author: Tomáš Mládek <t@mldk.cz> Date: Sat Aug 19 18:47:32 2023 +0200 wip: initial somewhat functional Earthfile
2023-08-23 12:13:24 +02:00
let args = Cli::from_arg_matches(&command.get_matches())?;
2022-08-07 12:13:12 +02:00
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
2020-08-27 00:11:50 +02:00
match args.command {
Commands::Query { url, query, format } => {
2023-05-04 19:16:01 +02:00
let re = Regex::new(r#"@(="([^"]+)"|=([^ ]+))"#).unwrap();
let query = re
.replace_all(&query, |caps: &Captures| {
if let Some(filepath_match) = caps.get(2).or_else(|| caps.get(3)) {
let address = hash_path(filepath_match.as_str()).unwrap();
format!("@{}", address)
} else {
panic!("Error preprocessing query. Captures: {:?}", caps)
}
})
.to_string();
let api_url = url.join("/api/query")?;
debug!("Querying \"{}\": {}", api_url, query);
let response = REQWEST_ASYNC_CLIENT
.post(api_url)
.body(query)
.send()
.await?;
response.error_for_status_ref()?;
print_response_entries(response, format).await?;
Ok(())
}
Commands::Get {
url,
entity,
attribute,
format,
} => {
let response = if let Some(attribute) = attribute {
let api_url = url.join("/api/query")?;
let entity = match entity {
entity if entity.starts_with('=') => hash_path(&entity[1..])?.to_string(),
entity if entity.starts_with("http") => {
Address::Url(entity.parse()?).to_string()
}
_ => entity,
};
let query = format!("(matches @{} \"{}\" ?)", entity, attribute);
debug!("Querying \"{}\": {}", api_url, query);
REQWEST_ASYNC_CLIENT
.post(api_url)
.body(query)
.send()
.await?
} else {
let entity = match entity {
entity if entity.starts_with('=') => hash_path(&entity[1..])?.to_string(),
_ => todo!("Only GETting blobs (files) is implemented."),
};
let api_url = url.join(&format!("/api/obj/{entity}"))?;
debug!("Getting object \"{}\" from {}", entity, api_url);
REQWEST_ASYNC_CLIENT.get(api_url).send().await?
};
response.error_for_status_ref()?;
print_response_entries(response, format).await?;
Ok(())
}
Commands::Insert {
url,
entity,
attribute,
value,
format: _,
} => {
let api_url = url.join("/api/obj")?;
let entity = match entity {
2023-05-04 18:48:00 +02:00
entity if entity.starts_with('=') => hash_path(&entity[1..])?.to_string(),
entity if entity.starts_with("http") => Address::Url(entity.parse()?).to_string(),
_ => entity,
};
2023-05-04 18:54:17 +02:00
let value = EntryValue::guess_from(value);
let body = json!({
"entity": entity,
"attribute": attribute,
"value": value
});
debug!("Inserting {:?} at \"{}\"", body, api_url);
let response = REQWEST_ASYNC_CLIENT.put(api_url).json(&body).send().await?;
2020-08-27 00:11:50 +02:00
match response.error_for_status_ref() {
Ok(_) => {
let data: Vec<String> = response.json().await?;
Ok(println!("{}", data[0]))
}
Err(err) => {
error!("{}", response.text().await?);
2023-04-25 19:33:57 +02:00
Err(err.into())
}
}
}
Commands::Address {
_type,
input,
format,
} => {
let address = match _type {
2023-05-04 18:48:00 +02:00
AddressType::File => hash_path(&input)?,
AddressType::Sha256sum => {
let digest = multibase::Base::Base16Lower.decode(input)?;
2023-06-29 15:17:06 +02:00
Address::Hash(UpMultihash::from_sha256(digest).unwrap())
}
};
2020-08-27 00:11:50 +02:00
match format {
OutputFormat::Json => Ok(println!("\"{}\"", address)),
OutputFormat::Tsv | OutputFormat::Raw => Ok(println!("{}", address)),
}
}
Commands::Serve(args) => {
2023-06-25 15:29:52 +02:00
info!("Starting UpEnd {}...", common::build::PKG_VERSION);
2020-08-27 00:11:50 +02:00
2023-06-08 19:38:56 +02:00
let term_now = Arc::new(std::sync::atomic::AtomicBool::new(false));
for sig in signal_hook::consts::TERM_SIGNALS {
signal_hook::flag::register_conditional_shutdown(*sig, 1, Arc::clone(&term_now))?;
signal_hook::flag::register(*sig, Arc::clone(&term_now))?;
}
let job_container = JobContainer::new();
let vault_path = args.directory;
2022-02-03 16:26:57 +01:00
let open_result = UpEndDatabase::open(&vault_path, args.reinitialize)
.expect("failed to open database!");
let upend = Arc::new(open_result.db);
let store = Arc::new(Box::new(
FsStore::from_path(args.store_path.unwrap_or_else(|| vault_path.clone())).unwrap(),
) as Box<dyn UpStore + Send + Sync>);
2024-01-26 22:41:43 +01:00
let webui_enabled = if args.no_ui {
false
} else {
let exists = WEBUI_PATH.exists();
2024-01-26 22:41:43 +01:00
if !exists {
warn!(
"Couldn't locate Web UI directory ({:?}), disabling...",
WEBUI_PATH.to_owned()
);
}
2024-01-26 22:41:43 +01:00
exists
};
2024-01-26 22:41:43 +01:00
let browser_enabled = !args.no_desktop && webui_enabled && !args.no_browser;
let preview_path = upend.path.join("previews");
#[cfg(feature = "previews")]
let preview_store = Some(Arc::new(crate::previews::PreviewStore::new(
preview_path.clone(),
store.clone(),
)));
#[cfg(feature = "previews")]
let preview_thread_pool = Some(Arc::new(
rayon::ThreadPoolBuilder::new()
.num_threads(num_cpus::get() / 2)
.build()
.unwrap(),
));
if args.clean {
info!("Cleaning temporary directories...");
if preview_path.exists() {
std::fs::remove_dir_all(&preview_path).unwrap();
debug!("Removed {preview_path:?}");
} else {
debug!("No preview path exists, continuing...");
}
}
2021-12-27 11:58:01 +01:00
#[cfg(not(feature = "previews"))]
let preview_store = None;
#[cfg(not(feature = "previews"))]
let preview_thread_pool = None;
let mut bind: SocketAddr = args.bind.parse().expect("Incorrect bind format.");
let secret = args.secret.unwrap_or_else(|| {
warn!("No secret supplied, generating one at random.");
thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(32)
.map(char::from)
.collect()
});
let state = routes::State {
upend: upend.clone(),
store,
job_container: job_container.clone(),
preview_store,
preview_thread_pool,
config: UpEndConfig {
vault_name: Some(args.vault_name.unwrap_or_else(|| {
vault_path
.iter()
.last()
.unwrap()
.to_string_lossy()
.into_owned()
})),
desktop_enabled: !args.no_desktop,
trust_executables: args.trust_executables,
key: args.key,
secret,
},
};
// Start HTTP server
let mut cnt = 0;
let server = loop {
let state = state.clone();
let allowed_origins = args.allow_host.clone();
let server = HttpServer::new(move || {
2024-01-26 22:41:43 +01:00
serve::get_app(webui_enabled, allowed_origins.clone(), state.clone())
});
let bind_result = server.bind(&bind);
if let Ok(server) = bind_result {
break server;
} else {
warn!("Failed to bind at {:?}, trying next port number...", bind);
bind.set_port(bind.port() + 1);
}
2021-12-27 11:58:01 +01:00
if cnt > 32 {
panic!("Couldn't start server.")
} else {
cnt += 1;
}
};
2024-01-17 23:48:48 +01:00
if !args.no_initial_update && (!open_result.new || args.rescan_mode.is_some()) {
info!("Running update...");
block_background::<_, _, anyhow::Error>(move || {
let connection: upend_db::UpEndConnection = upend.connection()?;
let tree_mode = if let Some(rescan_mode) = args.rescan_mode {
connection.set_vault_options(upend_db::VaultOptions {
blob_mode: Some(rescan_mode.clone()),
})?;
rescan_mode
} else {
2024-01-17 23:48:48 +01:00
connection
.get_vault_options()
.unwrap()
.blob_mode
.unwrap_or_default()
};
2024-01-17 23:48:48 +01:00
let _ = state.store.update(
&upend,
job_container.clone(),
upend_db::stores::UpdateOptions {
initial: false,
tree_mode,
},
);
let _ = extractors::extract_all(upend, state.store, job_container);
Ok(())
});
}
#[cfg(feature = "desktop")]
{
2024-01-26 22:41:43 +01:00
if browser_enabled {
let ui_result = webbrowser::open(&format!("http://localhost:{}", bind.port()));
if ui_result.is_err() {
warn!("Could not open UI in browser!");
}
}
2021-12-19 20:09:44 +01:00
}
info!("Starting server at: {}", &bind);
server.run().await?;
Ok(())
2020-08-30 16:45:42 +02:00
}
}
2020-08-27 00:11:50 +02:00
}
2023-05-04 18:48:00 +02:00
type Entries = HashMap<String, serde_json::Value>;
async fn print_response_entries(response: reqwest::Response, format: OutputFormat) -> Result<()> {
match format {
OutputFormat::Json | OutputFormat::Raw => println!("{}", response.text().await?),
OutputFormat::Tsv => {
let mut entries = if response.url().path().contains("/obj/") {
#[derive(serde::Deserialize)]
struct ObjResponse {
entries: Entries,
}
response.json::<ObjResponse>().await?.entries
} else {
response.json::<Entries>().await?
}
.into_iter()
.peekable();
if entries.peek().is_some() {
eprintln!("entity\tattribute\tvalue\ttimestamp\tprovenance");
entries.for_each(|(_, entry)| {
println!(
"{}\t{}\t{}\t{}\t{}",
entry
.get("entity")
.and_then(|e| e.as_str())
.unwrap_or("???"),
entry
.get("attribute")
.and_then(|a| a.as_str())
.unwrap_or("???"),
entry
.get("value")
.and_then(|v| v.get("c"))
.map(|c| format!("{c}"))
.unwrap_or("???".to_string()),
entry
.get("timestamp")
.and_then(|t| t.as_str())
.unwrap_or("???"),
entry
.get("provenance")
.and_then(|p| p.as_str())
.unwrap_or("???"),
)
})
}
}
}
Ok(())
}
2023-05-04 18:48:00 +02:00
fn hash_path<P: AsRef<Path>>(filepath: P) -> Result<Address> {
let filepath = filepath.as_ref();
debug!("Hashing {:?}...", filepath);
let fbuffer = FileBuffer::open(filepath)?;
2023-06-29 14:29:38 +02:00
let hash = sha256hash(&fbuffer)?;
2023-05-04 18:48:00 +02:00
trace!("Finished hashing {:?}...", filepath);
2023-06-29 14:29:38 +02:00
Ok(Address::Hash(hash))
2023-05-04 18:48:00 +02:00
}