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

adds support for updating & deleting instance on tembo-cloud #411

Merged
merged 5 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
8 changes: 8 additions & 0 deletions tembo-cli/src/cli/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ pub fn tembo_credentials_file_path() -> String {
tembo_home_dir() + "/credentials"
}

pub fn dot_tembo_folder() -> String {
".tembo".to_string()
Copy link
Contributor

@DarrenBaldwin07 DarrenBaldwin07 Dec 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cant these just be something like const DOT_TEMBO_FOLDER: String = String::from(".tembo.io")?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, good catch. Changed it.

}

pub fn tembo_state_file_path() -> String {
dot_tembo_folder() + "/tembo.state"
}

pub fn list_context() -> Result<Context> {
let filename = tembo_context_file_path();

Expand Down
134 changes: 109 additions & 25 deletions tembo-cli/src/cmd/apply.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
use crate::{
cli::{
context::{get_current_context, Environment, Target},
context::{get_current_context, tembo_state_file_path, Environment, Target},
tembo_config,
},
Result,
};
use clap::{ArgMatches, Command};
use std::io::Write;
use std::{
collections::HashMap,
fs::{self},
fs::{self, OpenOptions},
str::FromStr,
};
use temboclient::{
apis::{configuration::Configuration, instance_api::create_instance},
apis::{
configuration::Configuration,
instance_api::{create_instance, put_instance},
},
models::{
Cpu, CreateInstance, Extension, ExtensionInstallLocation, Memory, PgConfig, StackType,
Storage, TrunkInstall,
Storage, TrunkInstall, UpdateInstance,
},
};
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -86,39 +90,97 @@ fn execute_docker() -> Result<()> {
pub fn execute_tembo_cloud(env: Environment) -> Result<()> {
let instance_settings: HashMap<String, InstanceSettings> = get_instance_settings()?;

let profile = env.selected_profile.unwrap();
let profile = env.clone().selected_profile.unwrap();
let config = Configuration {
base_path: profile.tembo_host,
bearer_access_token: Some(profile.tembo_access_token),
..Default::default()
};

let mut instance: CreateInstance;

for (_key, value) in instance_settings.iter() {
instance = get_instance(value);

let v = Runtime::new().unwrap().block_on(create_instance(
&config,
env.org_id.clone().unwrap().as_str(),
instance,
));

match v {
Ok(result) => {
println!(
"Instance creation started for Instance Name: {}",
result.instance_name
)
}
Err(error) => eprintln!("Error creating instance: {}", error),
};
let instance_id = get_instance_id_from_state(value.instance_name.clone())?;
if let Some(env_instance_id) = instance_id {
update_existing_instance(env_instance_id, value, &config, env.clone());
} else {
create_new_instance(value, &config, env.clone());
}
}

Ok(())
}

fn get_instance(instance_settings: &InstanceSettings) -> CreateInstance {
pub fn get_instance_id_from_state(instance_name: String) -> Result<Option<String>> {
let contents = fs::read_to_string(tembo_state_file_path())?;

let tembo_state_map: HashMap<String, String> = toml::from_str(&contents)?;

let tembo_state = tembo_state_map.get(&instance_name);
if tembo_state.is_none() {
Ok(None)
} else {
let instance_id = tembo_state.unwrap().clone();
Ok(Some(instance_id))
}
}

fn update_existing_instance(
instance_id: String,
value: &InstanceSettings,
config: &Configuration,
env: Environment,
) {
let instance = get_update_instance(value);

let v = Runtime::new().unwrap().block_on(put_instance(
config,
env.org_id.clone().unwrap().as_str(),
&instance_id,
instance,
));

match v {
Ok(result) => {
println!(
"Instance update started for Instance Id: {}",
result.instance_id
)
}
Err(error) => eprintln!("Error updating instance: {}", error),
};
}

fn create_new_instance(value: &InstanceSettings, config: &Configuration, env: Environment) {
let instance = get_create_instance(value);

let v = Runtime::new().unwrap().block_on(create_instance(
config,
env.org_id.clone().unwrap().as_str(),
instance,
));

match v {
Ok(result) => {
println!(
"Instance creation started for instance_name: {} with instance_id: {}",
result.instance_name, result.instance_id
);

let mut state_file = OpenOptions::new()
.append(true)
.open(tembo_state_file_path())
.expect("cannot open file");

let state = format!("{} = \"{}\"\n", result.instance_name, result.instance_id);

state_file
.write_all(state.as_bytes())
.expect("write failed");
}
Err(error) => eprintln!("Error creating instance: {}", error),
};
}

fn get_create_instance(instance_settings: &InstanceSettings) -> CreateInstance {
return CreateInstance {
cpu: Cpu::from_str(instance_settings.cpu.as_str()).unwrap(),
memory: Memory::from_str(instance_settings.memory.as_str()).unwrap(),
Expand All @@ -142,6 +204,28 @@ fn get_instance(instance_settings: &InstanceSettings) -> CreateInstance {
};
}

fn get_update_instance(instance_settings: &InstanceSettings) -> UpdateInstance {
return UpdateInstance {
cpu: Cpu::from_str(instance_settings.cpu.as_str()).unwrap(),
memory: Memory::from_str(instance_settings.memory.as_str()).unwrap(),
environment: temboclient::models::Environment::from_str(
instance_settings.environment.as_str(),
)
.unwrap(),
storage: Storage::from_str(instance_settings.storage.as_str()).unwrap(),
replicas: instance_settings.replicas,
app_services: None,
connection_pooler: None,
extensions: Some(Some(get_extensions(instance_settings.extensions.clone()))),
extra_domains_rw: None,
ip_allow_list: None,
trunk_installs: Some(Some(get_trunk_installs(
instance_settings.extensions.clone(),
))),
postgres_configs: Some(Some(get_postgres_config_cloud(instance_settings))),
};
}

fn get_postgres_config_cloud(instance_settings: &InstanceSettings) -> Vec<PgConfig> {
let mut pg_configs: Vec<PgConfig> = vec![];

Expand Down
58 changes: 56 additions & 2 deletions tembo-cli/src/cmd/delete.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,67 @@
use crate::{cli::docker::Docker, Result};
use std::collections::HashMap;

use crate::{
cli::{
context::{get_current_context, Environment, Target},
docker::Docker,
tembo_config::InstanceSettings,
},
Result,
};
use clap::{ArgMatches, Command};
use core::result::Result::Ok;
use temboclient::apis::{configuration::Configuration, instance_api::delete_instance};
use tokio::runtime::Runtime;

use super::apply::{get_instance_id_from_state, get_instance_settings};

// Create init subcommand arguments
pub fn make_subcommand() -> Command {
Command::new("delete").about("Deletes database instance locally & on tembo cloud")
}

pub fn execute(_args: &ArgMatches) -> Result<()> {
Docker::stop_remove("tembo-pg")?;
let env = get_current_context()?;

if env.target == Target::Docker.to_string() {
Docker::stop_remove("tembo-pg")?;
} else if env.target == Target::TemboCloud.to_string() {
return execute_tembo_cloud(env);
}

Ok(())
}

fn execute_tembo_cloud(env: Environment) -> Result<()> {
let instance_settings: HashMap<String, InstanceSettings> = get_instance_settings()?;

let profile = env.clone().selected_profile.unwrap();
let config = Configuration {
base_path: profile.tembo_host,
bearer_access_token: Some(profile.tembo_access_token),
..Default::default()
};

for (_key, value) in instance_settings.iter() {
let instance_id = get_instance_id_from_state(value.instance_name.clone())?;
if let Some(env_instance_id) = instance_id {
let v = Runtime::new().unwrap().block_on(delete_instance(
&config,
env.org_id.clone().unwrap().as_str(),
&env_instance_id,
));

match v {
Ok(result) => {
println!(
"Instance delete started for Instance Id: {}",
result.instance_id
)
}
Err(error) => eprintln!("Error deleting instance: {}", error),
};
}
}

Ok(())
}
24 changes: 23 additions & 1 deletion tembo-cli/src/cmd/init.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::Result;
use crate::{
cli::context::{dot_tembo_folder, tembo_state_file_path},
Result,
};
use clap::{ArgMatches, Command};

use crate::cli::{
Expand Down Expand Up @@ -66,5 +69,24 @@ pub fn execute(_args: &ArgMatches) -> Result<()> {
}
}

match FileUtils::create_dir(".tembo directory".to_string(), dot_tembo_folder()) {
Ok(t) => t,
Err(e) => {
return Err(e);
}
}

match FileUtils::create_file(
tembo_state_file_path(),
tembo_state_file_path(),
"".to_string(),
false,
) {
Ok(t) => t,
Err(e) => {
return Err(e);
}
}

Ok(())
}
Loading