From 18f7659e79f9928bbf8997ee9f728da22c4afcfc Mon Sep 17 00:00:00 2001 From: Peter Neuroth Date: Mon, 24 Jul 2023 21:00:48 +0200 Subject: [PATCH] datastore: Add key to datastoreusage command {Key} is the entry point from which we begin to traverse the datastore. Signed-off-by: Peter Neuroth --- lightningd/datastore.c | 44 ++++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/lightningd/datastore.c b/lightningd/datastore.c index 31c1743fb164..56cfa055ff9e 100644 --- a/lightningd/datastore.c +++ b/lightningd/datastore.c @@ -298,34 +298,40 @@ static struct command_result *json_datastoreusage(struct command *cmd, const char **k, **key = NULL; struct db_stmt *stmt; const u8 *data; - u64 gen; - u64 total = 0; + u64 gen, total_bytes = 0; - if (!param(cmd, buffer, params, NULL)) + if (!param(cmd, buffer, params, + p_opt("key", param_list_or_string, &key), + NULL)) return command_param_failed(); + // We ignore an empty key string or key array. + if (key && *key[0] == '\0') + key = NULL; + response = json_stream_success(cmd); - json_array_start(response, "usage"); - - for (stmt = wallet_datastore_first(cmd, cmd->ld->wallet, key, + json_object_start(response, "datastoreusage"); + json_add_string(response, "key", datastore_key_fmt(tmpctx, key)); + + for (stmt = wallet_datastore_first(cmd, cmd->ld->wallet, key, &k, &data, &gen); stmt; - stmt = wallet_datastore_next(cmd, cmd->ld->wallet, stmt, + stmt = wallet_datastore_next(cmd, key, stmt, &k, &data, &gen)) { - - json_object_start(response, NULL); - json_array_start(response, "key"); - for (size_t i = 0; i < tal_count(k); i++) - json_add_string(response, NULL, k[i]); - json_array_end(response); - json_add_u64(response, "size", tal_bytelen(data)); - json_object_end(response); - total = tal_bytelen(data) + total; + + u64 self_bytes = tal_bytelen(data); + + // We use the formatted datastore key to calculate the size of + // the key to account for the delimiter byte in the database. + self_bytes += strlen(datastore_key_fmt(tmpctx, k)) - 2; + + total_bytes += self_bytes; }; tal_free(stmt); - json_array_end(response); - json_add_u64(response, "total", total); + json_add_u64(response, "total_bytes", total_bytes); + json_object_end(response); + return command_success(cmd, response); } @@ -357,6 +363,6 @@ static const struct json_command datastoreusage_command = { "datastoreusage", "utility", json_datastoreusage, - "List the datastore usage, similar to unix du", + "List the datastore usage, starting from an optional {key}", }; AUTODATA(json_command, &datastoreusage_command);