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

Add coffee disable and coffee enable Commands #240

Merged
merged 4 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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 coffee_cmd/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ pub enum CoffeeCommand {
/// tipping a plugins developer.
#[clap(arg_required_else_help = false)]
Tip { plugin: String, amount_msat: u64 },
/// Disable a plugin
#[clap(arg_required_else_help = true)]
Disable { plugin: String },
/// Enable a plugin
#[clap(arg_required_else_help = true)]
Enable { plugin: String },
vincenzopalazzo marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Debug, Subcommand)]
Expand Down Expand Up @@ -114,6 +120,8 @@ impl From<&CoffeeCommand> for coffee_core::CoffeeOperation {
plugin,
amount_msat,
} => Self::Tip(plugin.to_owned(), amount_msat.clone()),
CoffeeCommand::Disable { plugin } => Self::Disable(plugin.to_owned()),
CoffeeCommand::Enable { plugin } => Self::Enable(plugin.to_owned()),
}
}
}
Expand Down
11 changes: 10 additions & 1 deletion coffee_cmd/src/coffee_term/command_show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,31 @@ pub fn show_list(coffee_list: Result<CoffeeList, CoffeeError>) -> Result<(), Cof

term::println(
term::format::bold("●"),
term::format::tertiary("Plugin installed"),
term::format::tertiary("Plugins installed"),
);
let mut table = radicle_term::Table::new(TableOptions::bordered());
table.push([
term::format::dim(String::from("●")),
term::format::bold(String::from("Language")),
term::format::bold(String::from("Name")),
term::format::bold(String::from("Enabled")),
term::format::bold(String::from("Exec path")),
]);
table.divider();

for plugin in &remotes.plugins {
// Get whether the plugin is enabled
// If enabled is None, it means the plugin is enabled by default for backward compatibility.
let enabled = plugin.enabled.unwrap_or(true);
table.push([
term::format::positive("●").into(),
term::format::highlight(plugin.lang.to_string()),
term::format::bold(plugin.name()),
if enabled {
term::format::positive("yes").into()
} else {
term::format::negative("no").into()
},
term::format::highlight(plugin.exec_path.to_owned()),
])
}
Expand Down
8 changes: 8 additions & 0 deletions coffee_cmd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ async fn run(args: CoffeeArgs, mut coffee: CoffeeManager) -> Result<(), CoffeeEr
let tip_result = coffee.tip(&plugin, amount_msat).await?;
coffee_term::show_tips(&tip_result)?;
}
CoffeeCommand::Disable { plugin } => {
coffee.disable(&plugin).await?;
term::success!("Plugin {plugin} disabled");
}
CoffeeCommand::Enable { plugin } => {
coffee.enable(&plugin).await?;
term::success!("Plugin {plugin} enabled");
}
};
Ok(())
}
Expand Down
64 changes: 64 additions & 0 deletions coffee_core/src/coffee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,8 @@ impl PluginManager for CoffeeManager {
let path = plugin.configure(verbose).await?;
log::debug!("runnable plugin path {path}");
if !try_dynamic {
// mark the plugin enabled
plugin.enabled = Some(true);
self.config.plugins.push(plugin);
log::debug!("path coffee conf: {}", self.coffee_cln_config.path);
self.coffee_cln_config
Expand Down Expand Up @@ -595,6 +597,68 @@ impl PluginManager for CoffeeManager {
.await?;
Ok(tip)
}

async fn disable(&mut self, plugin: &str) -> Result<(), CoffeeError> {
log::debug!("disabling plugin: {plugin}");

let plugin = self
.config
.plugins
.iter_mut()
.find(|repo_plugin| plugin == repo_plugin.name())
.ok_or(error!(
"No plugin with name `{plugin}` found in the plugins installed"
))?;
log::debug!("plugin: {:?}", plugin);
if plugin.enabled == Some(false) {
return Err(error!("Plugin `{plugin}` is already disabled"));
}
self.coffee_cln_config
.add_conf("disable-plugin", &plugin.exec_path)
.map_err(|err| error!("{}", err.cause))?;
log::debug!(
"Plugin {} was removed from CLN configuration successfully",
plugin.name()
);
plugin.enabled = Some(false);

self.flush().await?;
self.update_conf().await?;

Ok(())
}

async fn enable(&mut self, plugin: &str) -> Result<(), CoffeeError> {
log::debug!("enabling plugin: {plugin}");

let plugin = self
.config
.plugins
.iter_mut()
.find(|repo_plugin| plugin == repo_plugin.name())
.ok_or(error!(
"No plugin with name `{plugin}` found in the plugins installed"
))?;
log::debug!("plugin: {:?}", plugin);
if plugin.enabled.is_none() || plugin.enabled == Some(true) {
return Err(error!(
"Plugin `{plugin}` is already enabled or enabled by default"
));
}
self.coffee_cln_config
.rm_conf("disable-plugin", Some(&plugin.exec_path))
.map_err(|err| error!("{}", err.cause))?;
log::debug!(
"Plugin {} was added to CLN configuration successfully",
plugin.name()
);
plugin.enabled = Some(true);

self.flush().await?;
self.update_conf().await?;

Ok(())
}
}

// FIXME: we need to move on but this is not safe and with the coffee
Expand Down
4 changes: 4 additions & 0 deletions coffee_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ pub enum CoffeeOperation {
///
/// (plugin_name, amount_msat)
Tip(String, u64),
/// Disable a plugin(plugin name)
Disable(String),
/// Enable a plugin(plugin name)
Enable(String),
}

#[derive(Clone, Debug)]
Expand Down
3 changes: 3 additions & 0 deletions coffee_github/src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ impl Github {
plugin_lang,
conf.clone(),
commit_id.clone(),
// The plugin for now is not installed, so it's
// neither enabled or disabled
None,
);

debug!("new plugin: {:?}", plugin);
Expand Down
30 changes: 30 additions & 0 deletions coffee_httpd/src/httpd/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ pub async fn run_httpd<T: ToSocketAddrs>(
.service(coffee_show)
.service(coffee_search)
.service(coffee_list_plugins_in_remote)
.service(coffee_disable)
.service(coffee_enable)
.with_json_spec_at("/api/v1")
.build()
})
Expand Down Expand Up @@ -198,6 +200,34 @@ async fn coffee_search(
handle_httpd_response!(result)
}

#[api_v2_operation]
#[post("/disable")]
async fn coffee_disable(
data: web::Data<AppState>,
body: Json<Disable>,
) -> Result<HttpResponse, Error> {
let plugin = &body.plugin;

let mut coffee = data.coffee.lock().await;
let result = coffee.disable(plugin).await;

handle_httpd_response!(result, "Plugin '{plugin}' disabled successfully")
}

#[api_v2_operation]
#[post("/enable")]
async fn coffee_enable(
data: web::Data<AppState>,
body: Json<Enable>,
) -> Result<HttpResponse, Error> {
let plugin = &body.plugin;

let mut coffee = data.coffee.lock().await;
let result = coffee.enable(plugin).await;

handle_httpd_response!(result, "Plugin '{plugin}' enabled successfully")
}

// this is just a hack to support swagger UI with https://paperclip-rs.github.io/paperclip/
// and the raw html is taken from https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md#unpkg
#[get("/")]
Expand Down
5 changes: 5 additions & 0 deletions coffee_lib/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ pub struct Plugin {
conf: Option<Conf>,
/// FIXME: this field shouldn't be optional
pub commit: Option<String>,
// Optional for now to be backward compatible
/// If the plugin is enabled or not
pub enabled: Option<bool>,
}

impl Plugin {
Expand All @@ -115,6 +118,7 @@ impl Plugin {
plugin_lang: PluginLang,
config: Option<Conf>,
commit_id: Option<String>,
enabled: Option<bool>,
) -> Self {
Plugin {
name: name.to_owned(),
Expand All @@ -123,6 +127,7 @@ impl Plugin {
lang: plugin_lang,
conf: config,
commit: commit_id,
enabled,
}
}

Expand Down
6 changes: 6 additions & 0 deletions coffee_lib/src/plugin_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,10 @@ pub trait PluginManager {
///
/// P.S: only Bitcoin ofc
async fn tip(&mut self, plugin: &str, amount_msat: u64) -> Result<CoffeeTip, CoffeeError>;

/// disable a plugin by name
async fn disable(&mut self, plugin: &str) -> Result<(), CoffeeError>;

/// enable a plugin by name
async fn enable(&mut self, plugin: &str) -> Result<(), CoffeeError>;
}
12 changes: 12 additions & 0 deletions coffee_lib/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ pub mod request {
pub struct Search {
pub plugin: String,
}

#[cfg(feature = "open-api")]
#[derive(Debug, Deserialize, Apiv2Schema, Serialize)]
pub struct Disable {
pub plugin: String,
}

#[cfg(feature = "open-api")]
#[derive(Debug, Deserialize, Apiv2Schema, Serialize)]
pub struct Enable {
pub plugin: String,
}
}

// Definition of the response types.
Expand Down
50 changes: 39 additions & 11 deletions docs/docs-book/src/using-coffee.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ include /home/alice/.coffee/testnet/coffee.conf
In addition there are the following additional option that you can specify:

- `--network`: by default set to `bitcoin`, but if you want to specify the network
that Core Lightning is using, you must ensure that the flag is set to
the correct network.
that Core Lightning is using, you must ensure that the flag is set to
the correct network.
- `--data-dir`: by default set to `/home/alice/.coffee`, you may want to set
this option if you are looking to specify a different directory for the
Coffee home.
this option if you are looking to specify a different directory for the
Coffee home.
- `--skip-verify`: Use this option to bypass `coffee`'s validation process, which checks for conflicts between its configuration and the local storage.

### Add a Plugin Repository
Expand Down Expand Up @@ -66,7 +66,7 @@ To list plugin repositories, simply run the following command.
> ✅ Implemented

```bash
coffee remote list
coffee remote list
```

To list available plugins in a specific remote repository
Expand Down Expand Up @@ -114,10 +114,34 @@ To remove an installed plugin, you simply have to run the following command.
coffee remove <plugin_name>
```

### Disabling a Plugin

> ✅ Implemented

Disabling a plugin means that the plugin will not be loaded with CLN but it will still be installed and can be enabled at any time.

To disable a plugin, run:

```bash
coffee disable <plugin_name>
```

### Enabling a Plugin

> ✅ Implemented

To enable a plugin, run:

```bash
coffee enable <plugin_name>
```

### Upgrade a Plugin

Coffee tightly integrates with git, allowing you to easily upgrade your plugins through the command line interface (CLI). This eliminates the need for tedious tasks such as downloading the latest updates and creating new versions of plugins. To upgrade a plugin, all you need to do is run.

> ✅ Implemented

```bash
coffee upgrade <repo_name>
```
Expand All @@ -138,7 +162,7 @@ coffee list
coffee show <plugin_name>
```

### Searching for a plugin in remote repositories
### Searching for a plugin in remote repositories

> ✅ Implemented

Expand All @@ -153,12 +177,15 @@ coffee search <plugin_name>
```bash
coffee nurse
```

Additionally, if you wish to perform a verification of coffee without making any changes, you can use the `--verify` flag:

```bash
coffee nurse --verify
```
_________

---

### Tipping a plugin in Bitcoin

> ✅ Implemented
Expand All @@ -167,7 +194,8 @@ _________
coffee tip <plugin_name> <millisatoshi>
```

------
---

## Running coffee as a server

To run Coffee as a server, you can use the `coffee_httpd` binary.
Expand All @@ -178,8 +206,8 @@ Please note that the server runs on `localhost` with port `8080` where you can f

To start the Coffee server, run the following command:

```shell
coffee_httpd --cln-path <core_lightning_path> --network <network>
```
```shell
coffee_httpd --cln-path <core_lightning_path> --network <network>
```

Make sure the `coffee_httpd` binary is in your system PATH or in the current working directory.
Loading