Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tembo Import #908

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions tembo-cli/src/cmd/import.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
use crate::cli::context::get_current_context;
use anyhow::{Context, Result};
use clap::Args;
use serde::Deserialize;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
use temboclient::apis::configuration::Configuration;
use toml::Value;

#[derive(Args)]
pub struct ImportCommand {
org_id: String,
instance_id: String,
}

#[derive(Deserialize)]
struct TemboTomlResponse {
#[serde(rename = "tembo.toml")]
tembo_toml: String,
}

pub fn execute(import_cmd: ImportCommand) -> Result<()> {
let env = get_current_context()?;
let org_id = import_cmd.org_id;
let instance_id = import_cmd.instance_id;

let profile = env
.selected_profile
.as_ref()
.with_context(|| "Expected [environment] to have a selected profile")?;
let config = Configuration {
base_path: profile.get_tembo_host(),
bearer_access_token: Some(profile.tembo_access_token.clone()),
..Default::default()
};

let rt = tokio::runtime::Runtime::new()?;
let toml_content = rt.block_on(fetch_toml(&org_id, &instance_id, &config))?;

let toml_content = preprocess_toml(&toml_content);

let mut toml_value: Value =
toml::from_str(&toml_content).context("Failed to parse instance information from TOML")?;

let instance_name = toml_value
.as_table()
.and_then(|table| table.keys().next().cloned())
.ok_or_else(|| anyhow::anyhow!("Failed to extract instance name from TOML"))?;

let toml_path = Path::new("tembo.toml");

if toml_path.exists() {
let existing_toml_content = fs::read_to_string(toml_path)?;
let mut existing_toml_value: Value = toml::from_str(&existing_toml_content)?;

if let Some(existing_table) = existing_toml_value.as_table_mut() {
if let Some(instance_table) = toml_value.as_table_mut() {
if let Some((_, instance_data)) = instance_table.iter().next() {
existing_table.insert(instance_name.clone(), instance_data.clone());
}
}
}

let new_toml_content = toml::to_string(&existing_toml_value)?;
fs::write(toml_path, new_toml_content)?;
} else {
let mut file = File::create(toml_path)?;
let mut new_toml_value = toml::value::Table::new();
if let Some(instance_table) = toml_value.as_table_mut() {
if let Some((_, instance_data)) = instance_table.iter().next() {
new_toml_value.insert(instance_name.clone(), instance_data.clone());
}
}

let new_toml_string = toml::to_string(&Value::Table(new_toml_value))?;
file.write_all(new_toml_string.as_bytes())?;
}

println!("Instance imported successfully.");

Ok(())
}

// Move it to tembo client
async fn fetch_toml(org_id: &str, instance_id: &str, config: &Configuration) -> Result<String> {
let client = reqwest::Client::new();
let url = format!(
"http://localhost:8080/api/v1/orgs/{}/instances/{}/toml",
joshuajerin marked this conversation as resolved.
Show resolved Hide resolved
org_id, instance_id
);

let bearer_token = config
.bearer_access_token
.clone()
.ok_or_else(|| anyhow::anyhow!("Missing bearer access token"))?;

let response: TemboTomlResponse = client
.get(&url)
.header("accept", "application/json")
.header("Authorization", format!("Bearer {}", bearer_token))
.send()
.await
.context("Failed to send request")?
.json()
.await
.context("Failed to parse JSON response")?;

Ok(response.tembo_toml)
}

fn preprocess_toml(toml_content: &str) -> String {
toml_content.replace("Some(\"", "").replace("\")", "")
}
1 change: 1 addition & 0 deletions tembo-cli/src/cmd/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod apply;
pub mod context;
pub mod delete;
pub mod import;
pub mod init;
pub mod login;
pub mod logs;
Expand Down
7 changes: 6 additions & 1 deletion tembo-cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::cmd::delete::DeleteCommand;
use crate::cmd::validate::ValidateCommand;
use crate::cmd::{apply, context, delete, init, login, logs, top, validate};
use crate::cmd::{apply, context, delete, import, init, login, logs, top, validate};
use clap::{crate_authors, crate_version, Args, Parser, Subcommand};
use cmd::apply::ApplyCommand;
use cmd::context::{ContextCommand, ContextSubCommand};
use cmd::import::ImportCommand;
use cmd::init::InitCommand;
use cmd::login::LoginCommand;
use cmd::logs::LogsCommand;
Expand Down Expand Up @@ -37,6 +38,7 @@ enum SubCommands {
Logs(LogsCommand),
Login(LoginCommand),
Top(TopCommand),
Import(ImportCommand),
}

#[derive(Args)]
Expand Down Expand Up @@ -87,6 +89,9 @@ fn main() -> Result<(), anyhow::Error> {
SubCommands::Top(_top_cmd) => {
top::execute(app.global_opts.verbose, _top_cmd)?;
}
SubCommands::Import(_import_cmd) => {
import::execute(_import_cmd)?;
}
}

Ok(())
Expand Down
Loading