id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,771
|
delayed_shutdown_timer.cpp
|
canonical_multipass/src/daemon/delayed_shutdown_timer.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/delayed_shutdown_timer.h>
#include <multipass/exceptions/ssh_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/top_catch_all.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
template <typename T>
bool num_plural(const T& num)
{
return num != T{1}; // use plural for 0 and 2+
}
void attempt_ssh_exec(mp::VirtualMachine& vm, const std::string& cmd)
{
try
{
vm.ssh_exec(cmd);
}
catch (const mp::SSHException& e)
{
mpl::log(mpl::Level::info, vm.vm_name, fmt::format("Could not broadcast shutdown message in VM: {}", e.what()));
}
}
void write_shutdown_message(mp::VirtualMachine& vm, const std::chrono::milliseconds& time_left)
{
if (time_left > std::chrono::milliseconds::zero())
{
auto minutes_left = std::chrono::duration_cast<std::chrono::minutes>(time_left).count();
attempt_ssh_exec(vm,
fmt::format("wall \"The system is going down for poweroff in {} minute{}, use 'multipass stop "
"--cancel {}' to cancel the shutdown.\"",
minutes_left,
num_plural(minutes_left) ? "s" : "",
vm.vm_name));
}
else
{
attempt_ssh_exec(vm, "wall The system is going down for poweroff now");
}
}
} // namespace
mp::DelayedShutdownTimer::DelayedShutdownTimer(VirtualMachine* virtual_machine, const StopMounts& stop_mounts)
: virtual_machine{virtual_machine}, stop_mounts{stop_mounts}, time_remaining{0}
{
}
mp::DelayedShutdownTimer::~DelayedShutdownTimer()
{
mp::top_catch_all(virtual_machine->vm_name, [this] {
if (shutdown_timer.isActive())
{
shutdown_timer.stop();
mpl::log(mpl::Level::info, virtual_machine->vm_name, "Cancelling delayed shutdown");
virtual_machine->state = VirtualMachine::State::running;
attempt_ssh_exec(*virtual_machine, "wall The system shutdown has been cancelled");
}
});
}
void mp::DelayedShutdownTimer::start(const std::chrono::milliseconds delay)
{
if (virtual_machine->state == VirtualMachine::State::stopped ||
virtual_machine->state == VirtualMachine::State::off)
return;
if (delay > decltype(delay)(0))
{
auto minutes_left = std::chrono::duration_cast<std::chrono::minutes>(delay).count();
mpl::log(mpl::Level::info,
virtual_machine->vm_name,
fmt::format("Shutdown request delayed for {} minute{}", // TODO say "under a minute" if < 1 minute
minutes_left,
num_plural(minutes_left) ? "s" : ""));
write_shutdown_message(*virtual_machine, delay);
time_remaining = delay;
std::chrono::minutes time_elapsed{1};
QObject::connect(&shutdown_timer, &QTimer::timeout, [this, delay, time_elapsed]() mutable {
time_remaining = delay - time_elapsed;
if (time_remaining <= std::chrono::minutes(5) ||
time_remaining % std::chrono::minutes(5) == std::chrono::minutes::zero())
{
write_shutdown_message(*virtual_machine, time_remaining);
}
if (time_elapsed >= delay)
{
shutdown_timer.stop();
shutdown_instance();
}
else
{
time_elapsed += std::chrono::minutes(1);
}
});
virtual_machine->state = VirtualMachine::State::delayed_shutdown;
shutdown_timer.start(delay < std::chrono::minutes(1) ? delay : std::chrono::minutes(1));
}
else
{
write_shutdown_message(*virtual_machine, std::chrono::milliseconds::zero());
shutdown_instance();
}
}
std::chrono::seconds mp::DelayedShutdownTimer::get_time_remaining()
{
return std::chrono::duration_cast<std::chrono::minutes>(time_remaining);
}
void mp::DelayedShutdownTimer::shutdown_instance()
{
stop_mounts(virtual_machine->vm_name);
virtual_machine->shutdown();
emit finished();
}
| 4,846
|
C++
|
.cpp
| 127
| 30.692913
| 120
| 0.622926
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,772
|
cli.cpp
|
canonical_multipass/src/daemon/cli.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "cli.h"
#include <multipass/logging/standard_logger.h>
#include <multipass/platform.h>
#include <multipass/utils.h>
#include <multipass/format.h>
#include <QCommandLineOption>
#include <QCommandLineParser>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
multipass::logging::Level to_logging_level(const QString& value)
{
auto value_lower = value.toLower();
if (value_lower == "error")
return mpl::Level::error;
if (value_lower == "warning")
return mpl::Level::warning;
if (value_lower == "info")
return mpl::Level::info;
if (value_lower == "debug")
return mpl::Level::debug;
if (value_lower == "trace")
return mpl::Level::trace;
throw std::runtime_error(fmt::format("invalid logging verbosity: {}. "
"Valid levels are: error|warning|info|debug|trace.",
value));
}
} // namespace
mp::DaemonConfigBuilder mp::cli::parse(const QCoreApplication& app)
{
QCommandLineParser parser;
parser.setApplicationDescription("multipass service daemon");
auto help_option = parser.addHelpOption();
auto version_option = parser.addVersionOption();
QCommandLineOption logger_option{"logger", "specifies which logger to use", "platform|stderr"};
QCommandLineOption verbosity_option{
{"V", "verbosity"}, "specifies the logging verbosity level", "error|warning|info|debug|trace"};
QCommandLineOption address_option{"address",
"specifies which address to use for the multipassd service;"
" a socket can be specified using unix:<socket_file>",
"server_name:port"};
parser.addOption(logger_option);
parser.addOption(verbosity_option);
parser.addOption(address_option);
parser.process(app);
DaemonConfigBuilder builder;
if (parser.isSet(verbosity_option))
builder.verbosity_level = to_logging_level(parser.value(verbosity_option));
if (parser.isSet(logger_option))
{
auto logger = parser.value(logger_option);
if (logger == "platform")
builder.logger = platform::make_logger(builder.verbosity_level);
else if (logger == "stderr")
builder.logger = std::make_unique<mpl::StandardLogger>(builder.verbosity_level);
else
throw std::runtime_error(fmt::format("invalid logger option '{}'", logger));
}
if (parser.isSet(address_option))
{
auto address = parser.value(address_option).toStdString();
mp::utils::validate_server_address(address);
builder.server_address = address;
}
return builder;
}
| 3,395
|
C++
|
.cpp
| 83
| 34.072289
| 103
| 0.668892
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,773
|
snapshot_settings_handler.cpp
|
canonical_multipass/src/daemon/snapshot_settings_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "snapshot_settings_handler.h"
#include "multipass/exceptions/snapshot_exceptions.h"
#include "multipass/utils.h"
#include <multipass/constants.h>
#include <multipass/format.h>
#include <QString>
namespace mp = multipass;
namespace
{
constexpr auto name_suffix = "name";
constexpr auto comment_suffix = "comment";
constexpr auto common_exception_msg = "Cannot access snapshot settings";
QRegularExpression make_key_regex()
{
const auto instance_pattern = QStringLiteral("(?<instance>.+)");
const auto snapshot_pattern = QStringLiteral("(?<snapshot>.+)");
const auto property_template = QStringLiteral("(?<property>%1)");
const auto either_prop = QStringList{name_suffix, comment_suffix}.join("|");
const auto property_pattern = property_template.arg(either_prop);
const auto key_template = QStringLiteral(R"(%1\.%2\.%3\.%4)");
const auto key_pattern =
key_template.arg(mp::daemon_settings_root, instance_pattern, snapshot_pattern, property_pattern);
return QRegularExpression{QRegularExpression::anchoredPattern(key_pattern)};
}
std::tuple<std::string, QString, std::string> parse_key(const QString& key)
{
static const auto key_regex = make_key_regex();
auto match = key_regex.match(key);
if (match.hasMatch())
{
auto instance = match.captured("instance");
auto snapshot = match.captured("snapshot");
auto property = match.captured("property");
assert(!instance.isEmpty() && !snapshot.isEmpty() && !property.isEmpty());
return {instance.toStdString(), snapshot, property.toStdString()};
}
throw mp::UnrecognizedSettingException{key};
}
} // namespace
mp::SnapshotSettingsException::SnapshotSettingsException(const std::string& missing_instance, const std::string& detail)
: SettingsException{fmt::format("{}; instance: {}; reason: {}", common_exception_msg, missing_instance, detail)}
{
}
mp::SnapshotSettingsException::SnapshotSettingsException(const std::string& detail)
: SettingsException{fmt::format("{}; reason: {}", common_exception_msg, detail)}
{
}
mp::SnapshotSettingsHandler::SnapshotSettingsHandler(
std::unordered_map<std::string, VirtualMachine::ShPtr>& operative_instances,
const std::unordered_map<std::string, VirtualMachine::ShPtr>& deleted_instances,
const std::unordered_set<std::string>& preparing_instances) noexcept
: operative_instances{operative_instances},
deleted_instances{deleted_instances},
preparing_instances{preparing_instances}
{
}
std::set<QString> mp::SnapshotSettingsHandler::keys() const
{
static const auto key_template = QStringLiteral("%1.%2.%3.%4").arg(daemon_settings_root);
std::set<QString> ret;
const auto& const_operative_instances = operative_instances;
for (const auto* instance_map : {&const_operative_instances, &deleted_instances})
for (const auto& [vm_name, vm] : *instance_map)
for (const auto& snapshot : vm->view_snapshots())
for (const auto* suffix : {name_suffix, comment_suffix})
ret.insert(key_template.arg(vm_name.c_str(), snapshot->get_name().c_str(), suffix));
return ret;
}
QString mp::SnapshotSettingsHandler::get(const QString& key) const
{
auto [instance_name, snapshot_name, property] = parse_key(key);
auto snapshot = find_snapshot(instance_name, snapshot_name.toStdString());
if (property == name_suffix)
return snapshot_name; // not very useful, but for completeness
assert(property == comment_suffix);
return QString::fromStdString(snapshot->get_comment());
}
void mp::SnapshotSettingsHandler::set(const QString& key, const QString& val)
{
auto [instance_name, snapshot_name, property] = parse_key(key);
auto snapshot_name_stdstr = snapshot_name.toStdString();
auto val_stdstr = val.toStdString();
if (property == name_suffix)
{
if (snapshot_name == val)
{
find_snapshot(instance_name, snapshot_name_stdstr); // fail if it ain't there
return;
}
if (val_stdstr.empty() || !mp::utils::valid_hostname(val_stdstr))
throw mp::InvalidSettingException{key, val, "Invalid snapshot name."};
modify_instance(instance_name)->rename_snapshot(snapshot_name_stdstr, val_stdstr);
}
else
{
assert(property == comment_suffix);
auto snapshot = modify_snapshot(instance_name, snapshot_name_stdstr);
snapshot->set_comment(val_stdstr);
}
}
auto mp::SnapshotSettingsHandler::find_snapshot(const std::string& instance_name,
const std::string& snapshot_name,
bool deleted_ok) const -> std::shared_ptr<const Snapshot>
{
try
{
return find_instance(instance_name, deleted_ok)->get_snapshot(snapshot_name);
}
catch (const NoSuchSnapshotException& e)
{
throw SnapshotSettingsException{e.what()};
}
}
auto mp::SnapshotSettingsHandler::find_instance(const std::string& instance_name, bool deleted_ok) const
-> std::shared_ptr<const VirtualMachine>
{
if (preparing_instances.find(instance_name) != preparing_instances.end())
throw SnapshotSettingsException{instance_name, "instance is being prepared"};
try
{
return operative_instances.at(instance_name);
}
catch (std::out_of_range&)
{
std::string error{"No such instance"};
try
{
const auto& del = deleted_instances.at(instance_name);
if (deleted_ok)
return del;
error = "Instance is deleted";
}
catch (std::out_of_range&)
{
}
throw SnapshotSettingsException{instance_name, error};
}
}
auto mp::SnapshotSettingsHandler::modify_instance(const std::string& instance_name) -> std::shared_ptr<VirtualMachine>
{
return std::const_pointer_cast<VirtualMachine>(find_instance(instance_name, /*deleted_ok=*/false));
}
auto mp::SnapshotSettingsHandler::modify_snapshot(const std::string& instance_name, const std::string& snapshot_name)
-> std::shared_ptr<Snapshot>
{
return std::const_pointer_cast<Snapshot>(find_snapshot(instance_name, snapshot_name, /*deleted_ok=*/false));
}
| 6,924
|
C++
|
.cpp
| 163
| 36.92638
| 120
| 0.694321
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,774
|
runtime_instance_info_helper.cpp
|
canonical_multipass/src/daemon/runtime_instance_info_helper.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "runtime_instance_info_helper.h"
#include <multipass/format.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine.h>
#include <yaml-cpp/yaml.h>
#include <array>
namespace mp = multipass;
namespace
{
struct Keys
{
public:
static constexpr auto loadavg_key = "loadavg";
static constexpr auto mem_usage_key = "mem_usage";
static constexpr auto mem_total_key = "mem_total";
static constexpr auto disk_usage_key = "disk_usage";
static constexpr auto disk_total_key = "disk_total";
static constexpr auto cpus_key = "cpus";
static constexpr auto cpu_times_key = "cpu_times";
static constexpr auto uptime_key = "uptime";
static constexpr auto current_release_key = "current_release";
};
struct Cmds
{
private:
static constexpr auto key_val_cmd = R"-(echo {}: "$(eval "{}")")-";
static constexpr std::array key_cmds_pairs{
std::pair{Keys::loadavg_key, "cat /proc/loadavg | cut -d ' ' -f1-3"},
std::pair{Keys::mem_usage_key, R"(free -b | grep 'Mem:' | awk '{printf \$3}')"},
std::pair{Keys::mem_total_key, R"(free -b | grep 'Mem:' | awk '{printf \$2}')"},
std::pair{Keys::disk_usage_key, "df -t ext4 -t vfat --total -B1 --output=used | tail -n 1"},
std::pair{Keys::disk_total_key, "df -t ext4 -t vfat --total -B1 --output=size | tail -n 1"},
std::pair{Keys::cpus_key, "nproc"},
std::pair{Keys::cpu_times_key, "head -n1 /proc/stat"},
std::pair{Keys::uptime_key, "uptime -p | tail -c+4"},
std::pair{Keys::current_release_key, R"(cat /etc/os-release | grep 'PRETTY_NAME' | cut -d \\\" -f2)"}};
inline static const std::array cmds = [] {
constexpr auto n = key_cmds_pairs.size();
std::array<std::string, key_cmds_pairs.size()> ret;
for (std::size_t i = 0; i < n; ++i)
{
const auto [key, cmd] = key_cmds_pairs[i];
ret[i] = fmt::format(key_val_cmd, key, cmd);
}
return ret;
}();
public:
inline static const std::string sequential_composite_cmd = fmt::to_string(fmt::join(cmds, "; "));
inline static const std::string parallel_composite_cmd = fmt::format("{} & wait", fmt::join(cmds, "& "));
};
} // namespace
void mp::RuntimeInstanceInfoHelper::populate_runtime_info(mp::VirtualMachine& vm,
mp::DetailedInfoItem* info,
mp::InstanceDetails* instance_info,
const std::string& original_release,
bool parallelize)
{
const auto& cmd = parallelize ? Cmds::parallel_composite_cmd : Cmds::sequential_composite_cmd;
auto results = YAML::Load(vm.ssh_exec(cmd, /* whisper = */ true));
instance_info->set_load(results[Keys::loadavg_key].as<std::string>());
instance_info->set_memory_usage(results[Keys::mem_usage_key].as<std::string>());
info->set_memory_total(results[Keys::mem_total_key].as<std::string>());
instance_info->set_disk_usage(results[Keys::disk_usage_key].as<std::string>());
info->set_disk_total(results[Keys::disk_total_key].as<std::string>());
info->set_cpu_count(results[Keys::cpus_key].as<std::string>());
instance_info->set_cpu_times(results[Keys::cpu_times_key].as<std::string>());
// In some older versions of Ubuntu, "uptime -p" prints only "up" right after startup. In those cases,
// results[Keys::uptime_key] is null.
instance_info->set_uptime(results[Keys::uptime_key].as<std::string>(/* fallback = */ "0 minutes"));
auto current_release = results[Keys::current_release_key].as<std::string>();
instance_info->set_current_release(!current_release.empty() ? current_release : original_release);
std::string management_ip = vm.management_ipv4();
auto all_ipv4 = vm.get_all_ipv4();
if (MP_UTILS.is_ipv4_valid(management_ip))
instance_info->add_ipv4(management_ip);
else if (all_ipv4.empty())
instance_info->add_ipv4("N/A");
for (const auto& extra_ipv4 : all_ipv4)
if (extra_ipv4 != management_ip)
instance_info->add_ipv4(extra_ipv4);
}
| 4,892
|
C++
|
.cpp
| 98
| 43
| 111
| 0.636383
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,775
|
daemon_rpc.cpp
|
canonical_multipass/src/daemon/daemon_rpc.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "daemon_rpc.h"
#include "daemon_config.h"
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/utils.h>
#include <chrono>
#include <stdexcept>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "rpc";
bool check_is_server_running(const std::string& address)
{
auto channel = grpc::CreateChannel(address, grpc::InsecureChannelCredentials());
auto stub = mp::Rpc::NewStub(channel);
grpc::ClientContext context;
auto deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(100); // should be enough...
context.set_deadline(deadline);
mp::PingRequest request;
mp::PingReply server;
return stub->ping(&context, request, &server).ok();
}
auto make_server(const std::string& server_address, const mp::CertProvider& cert_provider, mp::Rpc::Service* service)
{
grpc::ServerBuilder builder;
std::shared_ptr<grpc::ServerCredentials> creds;
grpc::SslServerCredentialsOptions opts(GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY);
opts.pem_key_cert_pairs.push_back({cert_provider.PEM_signing_key(), cert_provider.PEM_certificate()});
creds = grpc::SslServerCredentials(opts);
builder.AddListeningPort(server_address, creds);
builder.RegisterService(service);
std::unique_ptr<grpc::Server> server{builder.BuildAndStart()};
if (server == nullptr)
{
auto detail = check_is_server_running(server_address) ? " A multipass daemon is already running there." : "";
throw std::runtime_error(
fmt::format("Failed to start multipass gRPC service at {}.{}", server_address, detail));
}
return server;
}
auto server_socket_type_for(const std::string& server_address)
{
if (server_address.find("unix") == 0)
{
return mp::ServerSocketType::unix;
}
return mp::ServerSocketType::tcp;
}
template <typename OperationSignal>
grpc::Status emit_signal_and_wait_for_result(OperationSignal operation_signal)
{
std::promise<grpc::Status> status_promise;
auto status_future = status_promise.get_future();
emit operation_signal(&status_promise);
return status_future.get();
}
std::string client_cert_from(grpc::ServerContext* context)
{
std::string client_cert;
auto client_certs{context->auth_context()->FindPropertyValues("x509_pem_cert")};
if (!client_certs.empty())
{
client_cert = client_certs.front().data();
}
return client_cert;
}
void handle_socket_restrictions(const std::string& server_address, const bool restricted)
{
try
{
MP_PLATFORM.set_server_socket_restrictions(server_address, restricted);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::error, category,
fmt::format("Fatal error: Cannot set server socket restrictions: {}", e.what()));
MP_UTILS.exit(EXIT_FAILURE);
}
}
void accept_cert(mp::CertStore* client_cert_store, const std::string& client_cert, const std::string& server_address)
{
client_cert_store->add_cert(client_cert);
handle_socket_restrictions(server_address, false);
}
} // namespace
mp::DaemonRpc::DaemonRpc(const std::string& server_address, const CertProvider& cert_provider,
CertStore* client_cert_store)
: server_address{server_address},
server{make_server(server_address, cert_provider, this)},
server_socket_type{server_socket_type_for(server_address)},
client_cert_store{client_cert_store}
{
handle_socket_restrictions(server_address, client_cert_store->empty());
mpl::log(mpl::Level::info, category, fmt::format("gRPC listening on {}", server_address));
}
void mp::DaemonRpc::shutdown_and_wait()
{
server->Shutdown();
server->Wait();
}
grpc::Status mp::DaemonRpc::create(grpc::ServerContext* context,
grpc::ServerReaderWriter<CreateReply, CreateRequest>* server)
{
CreateRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_create, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::launch(grpc::ServerContext* context,
grpc::ServerReaderWriter<LaunchReply, LaunchRequest>* server)
{
LaunchRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_launch, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::purge(grpc::ServerContext* context,
grpc::ServerReaderWriter<PurgeReply, PurgeRequest>* server)
{
PurgeRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_purge, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::find(grpc::ServerContext* context, grpc::ServerReaderWriter<FindReply, FindRequest>* server)
{
FindRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_find, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::info(grpc::ServerContext* context, grpc::ServerReaderWriter<InfoReply, InfoRequest>* server)
{
InfoRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_info, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::list(grpc::ServerContext* context, grpc::ServerReaderWriter<ListReply, ListRequest>* server)
{
ListRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_list, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::clone(grpc::ServerContext* context,
grpc::ServerReaderWriter<CloneReply, CloneRequest>* server)
{
CloneRequest request;
server->Read(&request);
auto adapted_on_clone = [this, &request, server](auto&& arg) -> void {
this->on_clone(&request, server, std::forward<decltype(arg)>(arg));
};
return verify_client_and_dispatch_operation(adapted_on_clone, client_cert_from(context));
}
grpc::Status mp::DaemonRpc::networks(grpc::ServerContext* context,
grpc::ServerReaderWriter<NetworksReply, NetworksRequest>* server)
{
NetworksRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_networks, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::mount(grpc::ServerContext* context,
grpc::ServerReaderWriter<MountReply, MountRequest>* server)
{
MountRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_mount, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::recover(grpc::ServerContext* context,
grpc::ServerReaderWriter<RecoverReply, RecoverRequest>* server)
{
RecoverRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_recover, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::ssh_info(grpc::ServerContext* context,
grpc::ServerReaderWriter<SSHInfoReply, SSHInfoRequest>* server)
{
SSHInfoRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_ssh_info, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::start(grpc::ServerContext* context,
grpc::ServerReaderWriter<StartReply, StartRequest>* server)
{
StartRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_start, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::stop(grpc::ServerContext* context, grpc::ServerReaderWriter<StopReply, StopRequest>* server)
{
StopRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_stop, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::suspend(grpc::ServerContext* context,
grpc::ServerReaderWriter<SuspendReply, SuspendRequest>* server)
{
SuspendRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_suspend, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::restart(grpc::ServerContext* context,
grpc::ServerReaderWriter<RestartReply, RestartRequest>* server)
{
RestartRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_restart, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::delet(grpc::ServerContext* context,
grpc::ServerReaderWriter<DeleteReply, DeleteRequest>* server)
{
DeleteRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_delete, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::umount(grpc::ServerContext* context,
grpc::ServerReaderWriter<UmountReply, UmountRequest>* server)
{
UmountRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_umount, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::version(grpc::ServerContext* context,
grpc::ServerReaderWriter<VersionReply, VersionRequest>* server)
{
VersionRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_version, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::ping(grpc::ServerContext* context, const PingRequest* request, PingReply* server)
{
auto client_cert = client_cert_from(context);
if (!client_cert.empty() && client_cert_store->verify_cert(client_cert))
{
return grpc::Status::OK;
}
return grpc::Status{grpc::StatusCode::UNAUTHENTICATED, ""};
}
grpc::Status mp::DaemonRpc::get(grpc::ServerContext* context, grpc::ServerReaderWriter<GetReply, GetRequest>* server)
{
GetRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_get, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::authenticate(grpc::ServerContext* context,
grpc::ServerReaderWriter<AuthenticateReply, AuthenticateRequest>* server)
{
AuthenticateRequest request;
server->Read(&request);
auto status = emit_signal_and_wait_for_result(
std::bind(&DaemonRpc::on_authenticate, this, &request, server, std::placeholders::_1));
if (status.ok())
{
try
{
accept_cert(client_cert_store, client_cert_from(context), server_address);
}
catch (const std::exception& e)
{
return grpc::Status{grpc::StatusCode::INTERNAL, e.what()};
}
}
return status;
}
grpc::Status mp::DaemonRpc::set(grpc::ServerContext* context, grpc::ServerReaderWriter<SetReply, SetRequest>* server)
{
SetRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_set, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::keys(grpc::ServerContext* context, grpc::ServerReaderWriter<KeysReply, KeysRequest>* server)
{
KeysRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_keys, this, &request, server, std::placeholders::_1), client_cert_from(context));
}
grpc::Status mp::DaemonRpc::snapshot(grpc::ServerContext* context,
grpc::ServerReaderWriter<SnapshotReply, SnapshotRequest>* server)
{
SnapshotRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_snapshot, this, &request, server, std::placeholders::_1),
client_cert_from(context));
}
grpc::Status mp::DaemonRpc::restore(grpc::ServerContext* context,
grpc::ServerReaderWriter<RestoreReply, RestoreRequest>* server)
{
RestoreRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_restore, this, &request, server, std::placeholders::_1),
client_cert_from(context));
}
grpc::Status mp::DaemonRpc::daemon_info(grpc::ServerContext* context,
grpc::ServerReaderWriter<DaemonInfoReply, DaemonInfoRequest>* server)
{
DaemonInfoRequest request;
server->Read(&request);
return verify_client_and_dispatch_operation(
std::bind(&DaemonRpc::on_daemon_info, this, &request, server, std::placeholders::_1),
client_cert_from(context));
}
template <typename OperationSignal>
grpc::Status mp::DaemonRpc::verify_client_and_dispatch_operation(OperationSignal signal, const std::string& client_cert)
{
if (server_socket_type == mp::ServerSocketType::unix && client_cert_store->empty())
{
try
{
accept_cert(client_cert_store, client_cert, server_address);
}
catch (const std::exception& e)
{
return grpc::Status{grpc::StatusCode::INTERNAL, e.what()};
}
}
else if (!client_cert_store->verify_cert(client_cert))
{
return grpc::Status{grpc::StatusCode::UNAUTHENTICATED,
"The client is not authenticated with the Multipass service.\n"
"Please use 'multipass authenticate' before proceeding."};
}
return emit_signal_and_wait_for_result(signal);
}
| 15,572
|
C++
|
.cpp
| 359
| 37.147632
| 120
| 0.689938
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,776
|
instance_settings_handler.cpp
|
canonical_multipass/src/daemon/instance_settings_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "instance_settings_handler.h"
#include <multipass/cli/prompters.h>
#include <multipass/constants.h>
#include <multipass/exceptions/invalid_memory_size_exception.h>
#include <multipass/settings/bool_setting_spec.h>
#include <QRegularExpression>
#include <QStringList>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto cpus_suffix = "cpus";
constexpr auto mem_suffix = "memory";
constexpr auto disk_suffix = "disk";
constexpr auto bridged_suffix = "bridged";
enum class Operation
{
Obtain,
Modify
};
std::string operation_msg(Operation op)
{
return op == Operation::Obtain ? "Cannot obtain instance settings" : "Cannot update instance settings";
}
QRegularExpression make_key_regex()
{
const auto instance_pattern = QStringLiteral("(?<instance>.+)");
const auto prop_template = QStringLiteral("(?<property>%1)");
const auto either_prop = QStringList{cpus_suffix, mem_suffix, disk_suffix, bridged_suffix}.join("|");
const auto prop_pattern = prop_template.arg(either_prop);
const auto key_template = QStringLiteral(R"(%1\.%2\.%3)");
const auto key_pattern = key_template.arg(mp::daemon_settings_root, instance_pattern, prop_pattern);
return QRegularExpression{QRegularExpression::anchoredPattern(key_pattern)};
}
std::pair<std::string, std::string> parse_key(const QString& key)
{
static const auto key_regex = make_key_regex();
auto match = key_regex.match(key);
if (match.hasMatch())
{
auto instance = match.captured("instance");
auto property = match.captured("property");
assert(!instance.isEmpty() && !property.isEmpty());
return {instance.toStdString(), property.toStdString()};
}
throw mp::UnrecognizedSettingException{key};
}
template <typename InstanceMap>
typename InstanceMap::mapped_type&
pick_instance(InstanceMap& instances, const std::string& instance_name, Operation operation,
const std::unordered_map<std::string, mp::VirtualMachine::ShPtr>& deleted = {})
{
try
{
return instances.at(instance_name);
}
catch (std::out_of_range&)
{
const auto is_deleted = deleted.find(instance_name) != deleted.end();
const auto reason = is_deleted ? "Instance is deleted" : "No such instance";
assert(!is_deleted || operation == Operation::Modify); // obtaining info from deleted instances is fine
throw mp::InstanceSettingsException{operation_msg(operation), instance_name, reason};
}
}
void check_state_for_update(mp::VirtualMachine& instance)
{
auto st = instance.current_state();
if (st != mp::VirtualMachine::State::stopped && st != mp::VirtualMachine::State::off)
throw mp::InstanceSettingsException{operation_msg(Operation::Modify), instance.vm_name,
"Instance must be stopped for modification"};
}
mp::MemorySize get_memory_size(const QString& key, const QString& val)
{
try
{
auto ret = mp::MemorySize{val.toStdString()};
if (ret.in_bytes() == 0)
throw mp::InvalidSettingException{key, val, "Need a positive size."};
return ret;
}
catch (const mp::InvalidMemorySizeException& e)
{
throw mp::InvalidSettingException{key, val, e.what()};
}
}
void update_cpus(const QString& key, const QString& val, mp::VirtualMachine& instance, mp::VMSpecs& spec)
{
bool converted_ok = false;
if (auto cpus = val.toInt(&converted_ok); !converted_ok || cpus < std::stoi(mp::min_cpu_cores))
throw mp::InvalidSettingException{
key, val, QString("Need a positive integer (in decimal format) of minimum %1").arg(mp::min_cpu_cores)};
else if (cpus != spec.num_cores) // NOOP if equal
{
instance.update_cpus(cpus);
spec.num_cores = cpus;
}
}
void update_mem(const QString& key, const QString& val, mp::VirtualMachine& instance, mp::VMSpecs& spec,
const mp::MemorySize& size)
{
if (size < mp::MemorySize{mp::min_memory_size})
throw mp::InvalidSettingException{key, val,
QString("Memory less than %1 minimum not allowed").arg(mp::min_memory_size)};
else if (size != spec.mem_size) // NOOP if equal
{
instance.resize_memory(size);
spec.mem_size = size;
}
}
void update_disk(const QString& key, const QString& val, mp::VirtualMachine& instance, mp::VMSpecs& spec,
const mp::MemorySize& size)
{
if (size < spec.disk_space)
throw mp::InvalidSettingException{key, val, "Disk can only be expanded"};
else if (size > spec.disk_space) // NOOP if equal
{
instance.resize_disk(size);
spec.disk_space = size;
}
}
void update_bridged(const QString& key,
const QString& val,
const std::string& instance_name,
std::function<bool(const std::string&)> is_bridged,
std::function<void(const std::string&)> add_interface)
{
auto want_bridged = mp::BoolSettingSpec{key, "false"}.interpret(val) == "true";
if (!want_bridged)
{
if (is_bridged(instance_name)) // inspects host networks once
throw mp::InvalidSettingException{key, val, "Removing the bridged network is currently not supported"};
}
else
add_interface(instance_name); // if already bridged, this merely warns
}
} // namespace
mp::InstanceSettingsException::InstanceSettingsException(const std::string& reason, const std::string& instance,
const std::string& detail)
: SettingsException{fmt::format("{}; instance: {}; reason: {}", reason, instance, detail)}
{
}
mp::InstanceSettingsHandler::InstanceSettingsHandler(
std::unordered_map<std::string, VMSpecs>& vm_instance_specs,
std::unordered_map<std::string, VirtualMachine::ShPtr>& operative_instances,
const std::unordered_map<std::string, VirtualMachine::ShPtr>& deleted_instances,
const std::unordered_set<std::string>& preparing_instances,
std::function<void()> instance_persister,
std::function<bool(const std::string&)> is_bridged,
std::function<void(const std::string&)> add_interface)
: vm_instance_specs{vm_instance_specs},
operative_instances{operative_instances},
deleted_instances{deleted_instances},
preparing_instances{preparing_instances},
instance_persister{std::move(instance_persister)},
is_bridged{is_bridged},
add_interface{add_interface}
{
}
std::set<QString> mp::InstanceSettingsHandler::keys() const
{
static const auto key_template = QStringLiteral("%1.%2.%3").arg(daemon_settings_root);
std::set<QString> ret;
for (const auto& item : vm_instance_specs)
for (const auto& suffix : {cpus_suffix, mem_suffix, disk_suffix, bridged_suffix})
ret.insert(key_template.arg(item.first.c_str()).arg(suffix));
return ret;
}
QString mp::InstanceSettingsHandler::get(const QString& key) const
{
auto [instance_name, property] = parse_key(key);
const auto& spec = find_spec(instance_name);
if (property == bridged_suffix)
{
return is_bridged(instance_name) ? "true" : "false";
}
if (property == cpus_suffix)
return QString::number(spec.num_cores);
if (property == mem_suffix)
return QString::fromStdString(spec.mem_size.human_readable()); /* TODO return in bytes when --raw
(need unmarshall capability, w/ flag) */
assert(property == disk_suffix);
return QString::fromStdString(spec.disk_space.human_readable()); // TODO idem
}
void mp::InstanceSettingsHandler::set(const QString& key, const QString& val)
{
auto [instance_name, property] = parse_key(key);
if (preparing_instances.find(instance_name) != preparing_instances.end())
throw InstanceSettingsException{operation_msg(Operation::Modify), instance_name, "instance is being prepared"};
auto& instance = modify_instance(instance_name); // we need this first, to refuse updating deleted instances
auto& spec = modify_spec(instance_name);
check_state_for_update(instance);
if (property == cpus_suffix)
update_cpus(key, val, instance, spec);
else if (property == bridged_suffix)
{
update_bridged(key, val, instance_name, is_bridged, add_interface);
}
else
{
auto size = get_memory_size(key, val);
if (property == mem_suffix)
update_mem(key, val, instance, spec, size);
else
{
assert(property == disk_suffix);
update_disk(key, val, instance, spec, size);
}
}
instance_persister();
}
auto mp::InstanceSettingsHandler::modify_instance(const std::string& instance_name) -> VirtualMachine&
{
auto ret = pick_instance(operative_instances, instance_name, Operation::Modify, deleted_instances);
assert(ret && "can't have null instance");
return *ret;
}
auto mp::InstanceSettingsHandler::modify_spec(const std::string& instance_name) -> VMSpecs&
{
return pick_instance(vm_instance_specs, instance_name, Operation::Modify);
}
auto mp::InstanceSettingsHandler::find_spec(const std::string& instance_name) const -> const VMSpecs&
{
return pick_instance(vm_instance_specs, instance_name, Operation::Obtain);
}
| 10,059
|
C++
|
.cpp
| 240
| 36.05
| 119
| 0.679211
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,777
|
ubuntu_image_host.cpp
|
canonical_multipass/src/daemon/ubuntu_image_host.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ubuntu_image_host.h"
#include <multipass/constants.h>
#include <multipass/platform.h>
#include <multipass/query.h>
#include <multipass/settings/settings.h>
#include <multipass/simple_streams_index.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/exceptions/manifest_exceptions.h>
#include <multipass/exceptions/unsupported_image_exception.h>
#include <multipass/exceptions/unsupported_remote_exception.h>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <algorithm>
#include <unordered_set>
namespace mp = multipass;
namespace
{
constexpr auto index_path = "streams/v1/index.json";
auto download_manifest(const QString& host_url, mp::URLDownloader* url_downloader,
const bool is_force_update_from_network)
{
auto json_index = url_downloader->download({host_url + index_path}, is_force_update_from_network);
auto index = mp::SimpleStreamsIndex::fromJson(json_index);
auto json_manifest = url_downloader->download({host_url + index.manifest_path}, is_force_update_from_network);
return json_manifest;
}
mp::VMImageInfo with_location_fully_resolved(const QString& host_url, const mp::VMImageInfo& info)
{
return {info.aliases,
info.os,
info.release,
info.release_title,
info.release_codename,
info.supported,
host_url + info.image_location,
info.id,
info.stream_location,
info.version,
info.size,
info.verify};
}
auto key_from(const std::string& search_string)
{
auto key = QString::fromStdString(search_string);
if (key.isEmpty())
key = "default";
return key;
}
} // namespace
mp::UbuntuVMImageHost::UbuntuVMImageHost(std::vector<std::pair<std::string, UbuntuVMImageRemote>> remotes,
URLDownloader* downloader)
: url_downloader{downloader}, remotes{std::move(remotes)}
{
}
std::optional<mp::VMImageInfo> mp::UbuntuVMImageHost::info_for(const Query& query)
{
auto images = all_info_for(query);
if (images.size() == 0)
return std::nullopt;
auto key = key_from(query.release);
auto image_id = images.front().second.id;
// If a partial hash query matches more than once, throw an exception
if (images.size() > 1 && key != image_id && image_id.startsWith(key))
throw std::runtime_error(fmt::format("Too many images matching \"{}\"", query.release));
// It's not a hash match, so choose the first one no matter what
return images.front().second;
}
std::vector<std::pair<std::string, mp::VMImageInfo>> mp::UbuntuVMImageHost::all_info_for(const Query& query)
{
auto key = key_from(query.release);
check_alias_is_supported(key.toStdString(), query.remote_name);
std::vector<std::string> remotes_to_search;
if (!query.remote_name.empty())
{
remotes_to_search.push_back(query.remote_name);
}
else
{
remotes_to_search = std::vector<std::string>{release_remote, daily_remote};
}
std::vector<std::pair<std::string, mp::VMImageInfo>> images;
mp::SimpleStreamsManifest* manifest;
for (const auto& remote_name : remotes_to_search)
{
try
{
manifest = manifest_from(remote_name);
}
catch (const mp::UnsupportedRemoteException&)
{
if (query.remote_name.empty())
continue;
throw;
}
const auto* info = match_alias(key, *manifest);
if (info)
{
if (!info->supported && !query.allow_unsupported)
throw mp::UnsupportedImageException(query.release);
images.push_back(std::make_pair(
remote_name,
with_location_fully_resolved(QString::fromStdString(remote_url_from(remote_name)), *info)));
}
else
{
std::unordered_set<std::string> found_hashes;
for (const auto& entry : manifest->products)
{
if (entry.id.startsWith(key) && (entry.supported || query.allow_unsupported) &&
found_hashes.find(entry.id.toStdString()) == found_hashes.end())
{
images.push_back(std::make_pair(
remote_name,
with_location_fully_resolved(QString::fromStdString(remote_url_from(remote_name)), entry)));
found_hashes.insert(entry.id.toStdString());
}
}
}
}
return images;
}
mp::VMImageInfo mp::UbuntuVMImageHost::info_for_full_hash_impl(const std::string& full_hash)
{
for (const auto& manifest : manifests)
{
for (const auto& product : manifest.second->products)
{
if (product.id.toStdString() == full_hash)
{
return with_location_fully_resolved(QString::fromStdString(remote_url_from(manifest.first)), product);
}
}
}
// TODO: Throw a specific exception type here so callers can be more specific about what to catch
// and what to allow through.
throw std::runtime_error(fmt::format("Unable to find an image matching hash \"{}\"", full_hash));
}
std::vector<mp::VMImageInfo> mp::UbuntuVMImageHost::all_images_for(const std::string& remote_name,
const bool allow_unsupported)
{
std::vector<mp::VMImageInfo> images;
auto manifest = manifest_from(remote_name);
for (const auto& entry : manifest->products)
{
if ((entry.supported || allow_unsupported) && alias_verifies_image_is_supported(entry.aliases, remote_name))
{
images.push_back(with_location_fully_resolved(QString::fromStdString(remote_url_from(remote_name)), entry));
}
}
if (images.empty())
throw std::runtime_error(fmt::format("Unable to find images for remote \"{}\"", remote_name));
return images;
}
void mp::UbuntuVMImageHost::for_each_entry_do_impl(const Action& action)
{
for (const auto& manifest : manifests)
{
for (const auto& product : manifest.second->products)
{
if (alias_verifies_image_is_supported(product.aliases, manifest.first))
{
action(manifest.first,
with_location_fully_resolved(QString::fromStdString(remote_url_from(manifest.first)), product));
}
}
}
}
std::vector<std::string> mp::UbuntuVMImageHost::supported_remotes()
{
std::vector<std::string> supported_remotes;
for (const auto& [remote_name, _] : remotes)
{
supported_remotes.push_back(remote_name);
}
return supported_remotes;
}
void mp::UbuntuVMImageHost::fetch_manifests(const bool is_force_update_from_network)
{
auto fetch_one_remote =
[this, is_force_update_from_network](const std::pair<std::string, UbuntuVMImageRemote>& remote_pair)
-> std::pair<std::string, std::unique_ptr<SimpleStreamsManifest>> {
const auto& [remote_name, remote_info] = remote_pair;
try
{
check_remote_is_supported(remote_name);
auto official_site = remote_info.get_official_url();
auto manifest_bytes_from_official =
download_manifest(official_site, url_downloader, is_force_update_from_network);
auto mirror_site = remote_info.get_mirror_url();
std::optional<QByteArray> manifest_bytes_from_mirror = std::nullopt;
if (mirror_site)
{
auto bytes = download_manifest(mirror_site.value(), url_downloader, is_force_update_from_network);
manifest_bytes_from_mirror = std::make_optional(bytes);
}
auto manifest = mp::SimpleStreamsManifest::fromJson(
manifest_bytes_from_official, manifest_bytes_from_mirror, mirror_site.value_or(official_site));
return std::make_pair(remote_name, std::move(manifest));
}
catch (mp::EmptyManifestException& /* e */)
{
on_manifest_empty(fmt::format("Did not find any supported products in \"{}\"", remote_name));
}
catch (mp::GenericManifestException& e)
{
on_manifest_update_failure(e.what());
}
catch (mp::DownloadException& e)
{
throw e;
}
catch (const mp::UnsupportedRemoteException&)
{
}
return {};
};
auto local_manifests = mp::utils::parallel_transform(remotes, fetch_one_remote);
// append local_manifests to manifests
manifests.insert(manifests.end(), std::make_move_iterator(local_manifests.begin()),
std::make_move_iterator(local_manifests.end()));
}
void mp::UbuntuVMImageHost::clear()
{
manifests.clear();
}
mp::SimpleStreamsManifest* mp::UbuntuVMImageHost::manifest_from(const std::string& remote)
{
check_remote_is_supported(remote);
const auto it =
std::find_if(manifests.cbegin(), manifests.cend(),
[&remote](const std::pair<std::string, std::unique_ptr<SimpleStreamsManifest>>& element) {
return element.first == remote;
});
if (it == manifests.cend())
throw std::runtime_error(fmt::format(
"Remote \"{}\" is unknown or unreachable. If image mirror is enabled, please confirm it is valid.",
remote));
return it->second.get();
}
const mp::VMImageInfo* mp::UbuntuVMImageHost::match_alias(const QString& key,
const mp::SimpleStreamsManifest& manifest) const
{
auto it = manifest.image_records.find(key);
if (it != manifest.image_records.end())
{
return it.value();
}
return nullptr;
}
std::string mp::UbuntuVMImageHost::remote_url_from(const std::string& remote_name)
{
std::string url;
auto it = std::find_if(remotes.cbegin(), remotes.cend(),
[&remote_name](const std::pair<std::string, UbuntuVMImageRemote>& element) {
return element.first == remote_name;
});
if (it != remotes.cend())
{
url = it->second.get_url().toStdString();
}
return url;
}
mp::UbuntuVMImageRemote::UbuntuVMImageRemote(std::string official_host, std::string uri,
std::optional<QString> mirror_key)
: official_host(std::move(official_host)), uri(std::move(uri)), mirror_key(std::move(mirror_key))
{
}
const QString mp::UbuntuVMImageRemote::get_url() const
{
return get_mirror_url().value_or(get_official_url());
}
const QString mp::UbuntuVMImageRemote::get_official_url() const
{
auto host = official_host;
host.append(uri);
return QString::fromStdString(host);
}
const std::optional<QString> mp::UbuntuVMImageRemote::get_mirror_url() const
{
if (mirror_key)
{
auto mirror = MP_SETTINGS.get(mirror_key.value());
if (!mirror.isEmpty())
{
auto url = mirror.toStdString();
url.append(uri);
return std::make_optional(QString::fromStdString(url));
}
}
return std::nullopt;
}
| 12,038
|
C++
|
.cpp
| 310
| 30.925806
| 120
| 0.631556
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,778
|
daemon_init_settings.cpp
|
canonical_multipass/src/daemon/daemon_init_settings.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "daemon_init_settings.h"
#include <multipass/constants.h>
#include <multipass/platform.h>
#include <multipass/settings/basic_setting_spec.h>
#include <multipass/settings/bool_setting_spec.h>
#include <multipass/settings/custom_setting_spec.h>
#include <multipass/settings/persistent_settings_handler.h>
#include <multipass/settings/settings.h>
#include <multipass/utils.h>
#include <QCoreApplication>
#include <QFileSystemWatcher>
#include <QObject>
namespace mp = multipass;
namespace
{
constexpr const int settings_changed_code = 42;
/*
* We make up our own file names to:
* a) avoid unknown org/domain in path;
* b) write daemon config to a central location (rather than user-dependent)
* Example: /root/.config/multipassd/multipassd.conf
*/
QString persistent_settings_filename()
{
static const auto file_pattern = QStringLiteral("%2%1").arg(mp::settings_extension);
static const auto daemon_dir_path = QDir{MP_PLATFORM.daemon_config_home()}; // temporary, replace w/ AppConfigLoc
static const auto path = daemon_dir_path.absoluteFilePath(file_pattern.arg(mp::daemon_name));
return path;
}
QString driver_interpreter(QString val)
{
val = val.toLower();
if (val == QStringLiteral("hyper-v"))
val = QStringLiteral("hyperv");
else if (val == QStringLiteral("vbox"))
val = QStringLiteral("virtualbox");
if (!MP_PLATFORM.is_backend_supported(val))
throw mp::InvalidSettingException(mp::driver_key, val, "Invalid driver");
return val;
}
QString image_mirror_interpreter(QString val)
{
if (val.size() == 0)
{
return val;
}
if (!val.startsWith("https://"))
{
throw mp::InvalidSettingException(mp::mirror_key, val,
"The hostname of mirror must contain protocol name: https");
}
if (!val.endsWith("/"))
{
val.append("/");
}
return val;
}
} // namespace
void mp::daemon::monitor_and_quit_on_settings_change() // temporary
{
static const auto filename = persistent_settings_filename();
mp::utils::check_and_create_config_file(filename); // create if not there
static QFileSystemWatcher monitor{{filename}};
QObject::connect(&monitor, &QFileSystemWatcher::fileChanged, [] { QCoreApplication::exit(settings_changed_code); });
}
void mp::daemon::register_global_settings_handlers()
{
auto settings = MP_PLATFORM.extra_daemon_settings(); // platform settings override inserts with the same key below
settings.insert(std::make_unique<BasicSettingSpec>(bridged_interface_key, ""));
settings.insert(std::make_unique<BoolSettingSpec>(mounts_key, MP_PLATFORM.default_privileged_mounts()));
settings.insert(std::make_unique<CustomSettingSpec>(driver_key, MP_PLATFORM.default_driver(), driver_interpreter));
settings.insert(std::make_unique<CustomSettingSpec>(mp::passphrase_key, "", [](QString val) {
return val.isEmpty() ? val : MP_UTILS.generate_scrypt_hash_for(val);
}));
settings.insert(std::make_unique<CustomSettingSpec>(mp::mirror_key, "", image_mirror_interpreter));
MP_SETTINGS.register_handler(
std::make_unique<PersistentSettingsHandler>(persistent_settings_filename(), std::move(settings)));
}
| 3,883
|
C++
|
.cpp
| 94
| 37.446809
| 120
| 0.723607
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,779
|
custom_image_host.cpp
|
canonical_multipass/src/daemon/custom_image_host.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "custom_image_host.h"
#include <multipass/platform.h>
#include <multipass/query.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/exceptions/unsupported_remote_exception.h>
#include <multipass/format.h>
#include <QMap>
#include <QUrl>
#include <utility>
namespace mp = multipass;
namespace
{
constexpr auto no_remote = "";
struct BaseImageInfo
{
const QString last_modified;
const QString hash;
};
struct CustomImageInfo
{
QString url_prefix;
QStringList aliases;
QString os;
QString release;
QString release_string;
QString release_codename;
};
const QMap<QString, QMap<QString, CustomImageInfo>> multipass_image_info{
{{"x86_64"},
{{{"ubuntu-core-16-amd64.img.xz"},
{"https://cdimage.ubuntu.com/ubuntu-core/16/stable/current/",
{"core", "core16"},
"Ubuntu",
"core-16",
"Core 16",
"Core 16"}},
{{"ubuntu-core-18-amd64.img.xz"},
{"https://cdimage.ubuntu.com/ubuntu-core/18/stable/current/",
{"core18"},
"Ubuntu",
"core-18",
"Core 18",
"Core 18"}},
{{"ubuntu-core-20-amd64.img.xz"},
{"https://cdimage.ubuntu.com/ubuntu-core/20/stable/current/",
{"core20"},
"Ubuntu",
"core-20",
"Core 20",
"Core 20"}},
{{"ubuntu-core-22-amd64.img.xz"},
{"https://cdimage.ubuntu.com/ubuntu-core/22/stable/current/",
{"core22"},
"Ubuntu",
"core-22",
"Core 22",
"Core 22"}},
{{"ubuntu-core-24-amd64.img.xz"},
{"https://cdimage.ubuntu.com/ubuntu-core/24/stable/current/",
{"core24"},
"Ubuntu",
"core-24",
"Core 24",
"Core 24"}}}}};
auto base_image_info_for(mp::URLDownloader* url_downloader, const QString& image_url, const QString& hash_url,
const QString& image_file, const bool is_force_update_from_network = false)
{
const auto last_modified = QLocale::c().toString(url_downloader->last_modified({image_url}), "yyyyMMdd");
const auto sha256_sums = url_downloader->download({hash_url}, is_force_update_from_network).split('\n');
QString hash;
for (const QString line : sha256_sums) // intentional copy
{
if (line.trimmed().endsWith(image_file))
{
hash = line.split(' ').first();
break;
}
}
return BaseImageInfo{last_modified, hash};
}
auto map_aliases_to_vm_info_for(const std::vector<mp::VMImageInfo>& images)
{
std::unordered_map<std::string, const mp::VMImageInfo*> map;
for (const auto& image : images)
{
map[image.id.toStdString()] = ℑ
for (const auto& alias : image.aliases)
{
map[alias.toStdString()] = ℑ
}
}
return map;
}
auto full_image_info_for(const QMap<QString, CustomImageInfo>& custom_image_info, mp::URLDownloader* url_downloader,
const bool is_force_update_from_network = false)
{
auto fetch_one_image_info =
[is_force_update_from_network,
url_downloader](const std::pair<const QString, CustomImageInfo>& image_info_pair) -> mp::VMImageInfo {
const auto& [image_file_name, custom_image_info] = image_info_pair;
const QString image_url{custom_image_info.url_prefix + image_info_pair.first};
const QString hash_url{custom_image_info.url_prefix + QStringLiteral("SHA256SUMS")};
const auto base_image_info =
base_image_info_for(url_downloader, image_url, hash_url, image_file_name, is_force_update_from_network);
return mp::VMImageInfo{custom_image_info.aliases,
custom_image_info.os,
custom_image_info.release,
custom_image_info.release_string,
custom_image_info.release_codename,
true, // supported
image_url, // image_location
base_image_info.hash, // id
"",
base_image_info.last_modified, // version
0,
true};
};
return std::make_unique<mp::CustomManifest>(
mp::utils::parallel_transform(custom_image_info.toStdMap(), fetch_one_image_info));
}
} // namespace
mp::CustomManifest::CustomManifest(std::vector<VMImageInfo>&& images)
: products{std::move(images)}, image_records{map_aliases_to_vm_info_for(products)}
{
}
mp::CustomVMImageHost::CustomVMImageHost(const QString& arch, URLDownloader* downloader)
: arch{arch}, url_downloader{downloader}, custom_image_info{}, remotes{no_remote}
{
}
std::optional<mp::VMImageInfo> mp::CustomVMImageHost::info_for(const Query& query)
{
check_alias_is_supported(query.release, query.remote_name);
auto custom_manifest = manifest_from(query.remote_name);
auto it = custom_manifest->image_records.find(query.release);
if (it == custom_manifest->image_records.end())
return std::nullopt;
return *it->second;
}
std::vector<std::pair<std::string, mp::VMImageInfo>> mp::CustomVMImageHost::all_info_for(const Query& query)
{
std::vector<std::pair<std::string, mp::VMImageInfo>> images;
auto image = info_for(query);
if (image != std::nullopt)
images.push_back(std::make_pair(query.remote_name, *image));
return images;
}
mp::VMImageInfo mp::CustomVMImageHost::info_for_full_hash_impl(const std::string& full_hash)
{
return {};
}
std::vector<mp::VMImageInfo> mp::CustomVMImageHost::all_images_for(const std::string& remote_name,
const bool allow_unsupported)
{
std::vector<mp::VMImageInfo> images;
auto custom_manifest = manifest_from(remote_name);
auto pred = [this, &remote_name](const auto& product) {
return alias_verifies_image_is_supported(product.aliases, remote_name);
};
std::copy_if(custom_manifest->products.begin(), custom_manifest->products.end(), std::back_inserter(images), pred);
return images;
}
void mp::CustomVMImageHost::for_each_entry_do_impl(const Action& action)
{
for (const auto& manifest : custom_image_info)
{
for (const auto& info : manifest.second->products)
{
if (alias_verifies_image_is_supported(info.aliases, manifest.first))
action(manifest.first, info);
}
}
}
std::vector<std::string> mp::CustomVMImageHost::supported_remotes()
{
return remotes;
}
void mp::CustomVMImageHost::fetch_manifests(const bool is_force_update_from_network)
{
for (const auto& spec : {std::make_pair(no_remote, multipass_image_info[arch])})
{
try
{
check_remote_is_supported(spec.first);
std::unique_ptr<mp::CustomManifest> custom_manifest =
full_image_info_for(spec.second, url_downloader, is_force_update_from_network);
custom_image_info.emplace(spec.first, std::move(custom_manifest));
}
catch (mp::DownloadException& e)
{
throw e;
}
catch (const mp::UnsupportedRemoteException&)
{
continue;
}
}
}
void mp::CustomVMImageHost::clear()
{
custom_image_info.clear();
}
mp::CustomManifest* mp::CustomVMImageHost::manifest_from(const std::string& remote_name)
{
check_remote_is_supported(remote_name);
auto it = custom_image_info.find(remote_name);
if (it == custom_image_info.end())
throw std::runtime_error(fmt::format("Remote \"{}\" is unknown or unreachable.", remote_name));
return it->second.get();
}
| 8,494
|
C++
|
.cpp
| 227
| 30.264317
| 119
| 0.633268
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,780
|
alias_dict.cpp
|
canonical_multipass/src/client/common/alias_dict.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/constants.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/json_utils.h>
#include <multipass/standard_paths.h>
#include <multipass/utils.h>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QTemporaryFile>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace
{
void check_working_directory_string(const std::string& dir)
{
if (dir != "map" && dir != "default")
throw std::runtime_error(fmt::format("invalid working_directory string \"{}\"", dir));
}
} // namespace
mp::AliasDict::AliasDict(mp::Terminal* term) : cout(term->cout()), cerr(term->cerr())
{
const auto file_name = QStringLiteral("%1_aliases.json").arg(mp::client_name);
const auto user_config_path = QDir{MP_STDPATHS.writableLocation(mp::StandardPaths::GenericConfigLocation)};
const auto cli_client_dir_path = QDir{user_config_path.absoluteFilePath(mp::client_name)};
aliases_file = cli_client_dir_path.absoluteFilePath(file_name).toStdString();
load_dict();
}
mp::AliasDict::~AliasDict()
{
if (modified)
{
try
{
save_dict();
}
catch (std::runtime_error& e)
{
cerr << fmt::format("Error saving aliases dictionary: {}\n", e.what());
}
}
}
void mp::AliasDict::set_active_context(const std::string& new_active_context)
{
if (new_active_context != active_context)
{
modified = true;
active_context = new_active_context;
}
// When switching active context, make sure that a context associated with the new active context exists.
if (aliases.try_emplace(active_context, mp::AliasContext{}).second)
modified = true;
}
std::string mp::AliasDict::active_context_name() const
{
return active_context;
}
const mp::AliasContext& mp::AliasDict::get_active_context() const
{
try
{
return aliases.at(active_context);
}
catch (const std::out_of_range&)
{
throw std::runtime_error(fmt::format("active context \"{}\" does not exist in dictionary", active_context));
}
}
bool mp::AliasDict::add_alias(const std::string& alias, const mp::AliasDefinition& command)
{
if (aliases[active_context].try_emplace(alias, command).second)
{
modified = true;
return true;
}
return false;
}
bool mp::AliasDict::exists_alias(const std::string& alias) const
{
for (const auto& [_, context_dict] : aliases)
{
if (context_dict.find(alias) != context_dict.cend())
{
return true;
}
}
return false;
}
bool mp::AliasDict::is_alias_unique(const std::string& alias) const
{
return get_alias_from_all_contexts(alias) ? true : false;
}
bool mp::AliasDict::remove_alias(const std::string& alias)
{
if (aliases[active_context].erase(alias) > 0)
{
modified = true;
return true;
}
return false;
}
bool mp::AliasDict::remove_context(const std::string& context)
{
if (aliases.erase(context) > 0)
{
modified = true;
if (active_context == context)
set_active_context(default_context_name);
return true;
}
return false;
}
// This function removes the context called as the instance, and then it iterates through all the remaining contexts
// to see if there are aliases defined for the instance.
std::vector<mp::ContextAliasPair> mp::AliasDict::remove_aliases_for_instance(const std::string& instance)
{
std::vector<mp::ContextAliasPair> removed_aliases;
remove_context(instance);
const auto old_context_name = active_context;
for (auto dict_it = begin(); dict_it != end(); ++dict_it)
{
for (auto context_it = dict_it->second.begin(); context_it != dict_it->second.end(); ++context_it)
{
if (context_it->second.instance == instance)
{
removed_aliases.emplace_back(std::make_pair(dict_it->first, context_it->first));
}
}
}
for (auto [context_from, removed_alias] : removed_aliases)
{
set_active_context(context_from);
remove_alias(removed_alias);
}
active_context = old_context_name;
return removed_aliases;
}
// The argument is an alias name, which can have the forms (i) "alias" or (ii) "context.alias".
// (i): returns <active context name, alias name> if the alias exists in the current context; std::nullopt otherwise.
// (ii): returns <context name, alias name> if the alias exists in the given context; std::nullopt otherwise.
std::optional<mp::ContextAliasPair> mp::AliasDict::get_context_and_alias(const std::string& alias) const
{
// This will never throw because we already checked that the active context exists.
if (aliases.at(active_context).count(alias) > 0)
return std::make_pair(active_context, alias);
std::string::size_type dot_pos = alias.rfind('.');
if (dot_pos == std::string::npos)
return std::nullopt;
std::string context = alias.substr(0, dot_pos);
if (aliases.count(context) == 0)
return std::nullopt;
std::string alias_only = alias.substr(dot_pos + 1);
return (aliases.at(context).count(alias_only) == 0 ? std::nullopt
: std::make_optional(std::make_pair(context, alias_only)));
}
std::optional<mp::AliasDefinition> mp::AliasDict::get_alias_from_current_context(const std::string& alias) const
{
try
{
return aliases.at(active_context).at(alias);
}
catch (const std::out_of_range&)
{
return std::nullopt;
}
}
// Returns an alias definition if:
// - the given alias exists in the current context, or
// - exists in another context and is unique, or
// - is fully qualified (that is, contains a dot) and exists.
// The given alias can be fully qualified or not.
std::optional<mp::AliasDefinition> mp::AliasDict::get_alias(const std::string& alias) const
{
std::optional<mp::AliasDefinition> alias_in_current_context = get_alias_from_current_context(alias);
if (alias_in_current_context)
return alias_in_current_context;
// If the alias is not on the current context, look for it in the rest of the contexts. But make sure there is only
// one existing alias with that name.
auto unique_alias_in_all_contexts = get_alias_from_all_contexts(alias);
if (unique_alias_in_all_contexts)
return unique_alias_in_all_contexts;
// If the alias given was not found, then it is in the form "context.alias": the input string must be split.
// No dot, no alias.
std::string::size_type dot_pos;
if ((dot_pos = alias.find('.')) == std::string::npos)
return std::nullopt;
std::string context = alias.substr(0, dot_pos);
std::string alias_only = alias.substr(dot_pos + 1);
try
{
return aliases.at(context).at(alias_only);
}
catch (const std::out_of_range&)
{
return std::nullopt;
}
}
QJsonObject mp::AliasDict::to_json() const
{
auto alias_to_json = [](const mp::AliasDefinition& alias) -> QJsonObject {
QJsonObject json;
check_working_directory_string(alias.working_directory);
json.insert("instance", QString::fromStdString(alias.instance));
json.insert("command", QString::fromStdString(alias.command));
json.insert("working-directory", QString::fromStdString(alias.working_directory));
return json;
};
QJsonObject dict_json, all_contexts_json;
dict_json.insert("active-context", QString::fromStdString(active_context));
for (const auto& [context_name, context_contents] : aliases)
{
QJsonObject context_json;
for (const auto& [alias_name, alias_definition] : context_contents)
{
context_json.insert(QString::fromStdString(alias_name), alias_to_json(alias_definition));
}
all_contexts_json.insert(QString::fromStdString(context_name), context_json);
}
dict_json.insert(QString("contexts"), all_contexts_json);
return dict_json;
}
void mp::AliasDict::load_dict()
{
QFile db_file{QString::fromStdString(aliases_file)};
aliases.clear();
if (MP_FILEOPS.exists(db_file))
{
if (!MP_FILEOPS.open(db_file, QIODevice::ReadOnly))
throw std::runtime_error(fmt::format("Error opening file '{}'", db_file.fileName()));
}
else
{
active_context = default_context_name;
aliases[default_context_name] = AliasContext();
return;
}
QJsonParseError parse_error;
QJsonDocument doc = QJsonDocument::fromJson(db_file.readAll(), &parse_error);
if (doc.isNull())
{
active_context = default_context_name;
aliases[default_context_name] = AliasContext();
return;
}
QJsonObject records = doc.object();
if (records.isEmpty())
{
active_context = default_context_name;
aliases[default_context_name] = AliasContext();
return;
}
auto records_to_context = [](const QJsonObject& records, AliasContext& context) -> void {
for (auto it = records.constBegin(); it != records.constEnd(); ++it)
{
auto alias = it.key().toStdString();
auto record = it.value().toObject();
if (record.isEmpty())
break;
auto instance = record["instance"].toString().toStdString();
auto command = record["command"].toString().toStdString();
auto read_working_directory = record["working-directory"];
std::string working_directory;
if (read_working_directory.isString() && !read_working_directory.toString().isEmpty())
working_directory = read_working_directory.toString().toStdString();
else
working_directory = "default";
check_working_directory_string(working_directory);
context.emplace(alias, mp::AliasDefinition{instance, command, working_directory});
}
};
// If the JSON does not contain the active-context field, then the file was written by a version of Multipass
// previous than the introduction of alias contexts.
if (records.contains("active-context"))
{
active_context = records["active-context"].toString().toStdString();
auto context_array = records["contexts"].toObject();
for (auto it = context_array.constBegin(); it != context_array.constEnd(); ++it)
{
AliasContext context;
std::string context_name = it.key().toStdString();
records_to_context(it.value().toObject(), context);
aliases.emplace(std::make_pair(context_name, context));
}
}
else
{
// The file with the old format does not contain information about contexts. For that reason, everything
// defined goes into the default context.
active_context = default_context_name;
AliasContext default_context;
records_to_context(records, default_context);
aliases.emplace(std::make_pair(active_context, default_context));
}
db_file.close();
}
void mp::AliasDict::save_dict()
{
sanitize_contexts();
MP_JSONUTILS.write_json(to_json(), QString::fromStdString(aliases_file));
}
// This function removes the contexts which do not contain aliases, except the active context.
void mp::AliasDict::sanitize_contexts()
{
// To avoid invalidating iterators, the function works in two stages. First, the aliases which need to be
// removed are determined and, second, they are effectively removed.
std::vector<std::string> empty_contexts;
for (auto& context : aliases)
{
if (context.first != active_context && context.second.empty())
{
empty_contexts.push_back(context.first);
}
}
if (!empty_contexts.empty())
{
modified = true;
for (const auto& context : empty_contexts)
{
aliases.erase(context);
}
}
}
// Returns an alias definition iff the given alias name is unique across all the contexts. The given alias name cannot
// be fully qualified, that is, it must not be prepended by a context name.
std::optional<mp::AliasDefinition> mp::AliasDict::get_alias_from_all_contexts(const std::string& alias) const
{
const AliasDefinition* ret;
bool found{false};
for (const auto& [_, context_dict] : aliases)
{
auto found_alias = context_dict.find(alias);
if (found_alias != context_dict.cend())
{
if (found) // This means that the alias exists in more than one context.
{
return std::nullopt;
}
else
{
found = true;
ret = &(found_alias->second);
}
}
}
return found ? std::make_optional(*ret) : std::nullopt;
}
| 13,689
|
C++
|
.cpp
| 366
| 31.333333
| 119
| 0.658332
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,781
|
client_common.cpp
|
canonical_multipass/src/client/common/client_common.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/client_common.h>
#include <multipass/constants.h>
#include <multipass/exceptions/autostart_setup_exception.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/logging/standard_logger.h>
#include <multipass/platform.h>
#include <multipass/settings/basic_setting_spec.h>
#include <multipass/settings/bool_setting_spec.h>
#include <multipass/settings/custom_setting_spec.h>
#include <multipass/settings/persistent_settings_handler.h>
#include <multipass/settings/settings.h>
#include <multipass/standard_paths.h>
#include <multipass/utils.h>
#include <fmt/ostream.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
const auto client_root = QStringLiteral("client");
QString petenv_interpreter(QString val)
{
if (!val.isEmpty() && !mp::utils::valid_hostname(val.toStdString()))
throw mp::InvalidSettingException{mp::petenv_key, val, "Invalid hostname"};
return val;
}
mp::ReturnCode return_code_for(const grpc::StatusCode& code)
{
return code == grpc::StatusCode::UNAVAILABLE ? mp::ReturnCode::DaemonFail : mp::ReturnCode::CommandFail;
}
std::string message_box(const std::string& message)
{
std::string::size_type divider_length = 50;
{
std::istringstream m(message);
std::string s;
while (getline(m, s, '\n'))
{
divider_length = std::max(divider_length, s.length());
}
}
const auto divider = std::string(divider_length, '#');
return '\n' + divider + '\n' + message + '\n' + divider + '\n';
}
grpc::SslCredentialsOptions get_ssl_credentials_opts_from(const mp::CertProvider& cert_provider)
{
auto opts = grpc::SslCredentialsOptions();
opts.server_certificate_request = GRPC_SSL_REQUEST_SERVER_CERTIFICATE_BUT_DONT_VERIFY;
opts.pem_cert_chain = cert_provider.PEM_certificate();
opts.pem_private_key = cert_provider.PEM_signing_key();
return opts;
}
bool client_certs_exist(const QString& cert_dir_path)
{
QDir cert_dir{cert_dir_path};
return cert_dir.exists(mp::client_cert_file) && cert_dir.exists(mp::client_key_file);
}
} // namespace
mp::ReturnCode mp::cmd::standard_failure_handler_for(const std::string& command, std::ostream& cerr,
const grpc::Status& status, const std::string& error_details)
{
fmt::print(cerr, "{} failed: {}\n{}", command, status.error_message(),
!error_details.empty() ? fmt::format("{}\n", error_details) : "");
return return_code_for(status.error_code());
}
bool mp::cmd::update_available(const mp::UpdateInfo& update_info)
{
return update_info.version() != "";
}
std::string mp::cmd::update_notice(const mp::UpdateInfo& update_info)
{
return ::message_box(fmt::format("{}\n{}\n\nGo here for more information: {}", update_info.title(),
update_info.description(), update_info.url()));
}
/*
* We make up our own file name to
* a) avoid unknown org/domain in path;
* b) keep settings-file locations consistent among daemon and client
* Example: ${HOME}/.config/multipass/multipass.conf
*/
QString mp::client::persistent_settings_filename()
{
static const auto file_pattern = QStringLiteral("%2%1").arg(mp::settings_extension); // note the order
static const auto user_config_path = QDir{MP_STDPATHS.writableLocation(mp::StandardPaths::GenericConfigLocation)};
static const auto dir_path = QDir{user_config_path.absoluteFilePath(mp::client_name)};
static const auto path = dir_path.absoluteFilePath(file_pattern.arg(mp::client_name));
return path;
}
void mp::client::register_global_settings_handlers()
{
auto settings = MP_PLATFORM.extra_client_settings(); // platform settings override inserts with the same key below
settings.insert(std::make_unique<CustomSettingSpec>(mp::petenv_key, petenv_default, petenv_interpreter));
MP_SETTINGS.register_handler(
std::make_unique<PersistentSettingsHandler>(persistent_settings_filename(), std::move(settings)));
}
std::shared_ptr<grpc::Channel> mp::client::make_channel(const std::string& server_address,
const mp::CertProvider& cert_provider)
{
return grpc::CreateChannel(server_address, grpc::SslCredentials(get_ssl_credentials_opts_from(cert_provider)));
}
std::string mp::client::get_server_address()
{
const auto address = qgetenv("MULTIPASS_SERVER_ADDRESS").toStdString();
if (!address.empty())
{
mp::utils::validate_server_address(address);
return address;
}
return mp::platform::default_server_address();
}
std::unique_ptr<mp::SSLCertProvider> mp::client::get_cert_provider()
{
auto data_location{MP_STDPATHS.writableLocation(StandardPaths::GenericDataLocation)};
auto common_client_cert_dir_path{data_location + common_client_cert_dir};
if (!client_certs_exist(common_client_cert_dir_path))
{
MP_UTILS.make_dir(common_client_cert_dir_path);
}
return std::make_unique<SSLCertProvider>(common_client_cert_dir_path);
}
void mp::client::set_logger()
{
set_logger(mpl::Level::info);
}
void mp::client::set_logger(mpl::Level verbosity)
{
mpl::set_logger(std::make_shared<mpl::StandardLogger>(verbosity));
}
void mp::client::post_setup()
{
platform::sync_winterm_profiles();
}
| 6,074
|
C++
|
.cpp
| 149
| 36.590604
| 118
| 0.711522
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,782
|
prompters.cpp
|
canonical_multipass/src/client/common/prompters.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/client_common.h>
#include <multipass/cli/prompters.h>
#include <multipass/exceptions/cli_exceptions.h>
#include <multipass/format.h>
#include <iostream>
namespace mp = multipass;
namespace
{
auto get_input(std::istream& cin)
{
std::string value;
std::getline(cin, value);
if (!cin.good())
throw mp::PromptException("Failed to read value");
return value;
}
// TODO when we have remote client-daemon communication, we need to get the daemon's platform
constexpr bool on_windows()
{
return
#ifdef MULTIPASS_PLATFORM_WINDOWS
true;
#else
false;
#endif
}
} // namespace
std::string mp::PlainPrompter::prompt(const std::string& text) const
{
term->cout() << text << ": ";
return get_input(term->cin());
}
std::string mp::PassphrasePrompter::prompt(const std::string& text) const
{
ScopedEcholessInput scoped_echoless_input(term);
auto passphrase = PlainPrompter::prompt(text);
term->cout() << "\n";
return passphrase;
}
std::string mp::NewPassphrasePrompter::prompt(const std::string& text) const
{
auto passphrase = PassphrasePrompter::prompt();
// Confirm the passphrase is the same by re-entering it
if (passphrase != PassphrasePrompter::prompt(text))
{
throw PromptException("Passphrases do not match");
}
return passphrase;
}
bool mp::BridgePrompter::bridge_prompt(const std::vector<std::string>& nets_need_bridging) const
{
assert(nets_need_bridging.size()); // precondition
static constexpr auto plural = "Multipass needs to create {} to connect to {}.\nThis will temporarily disrupt "
"connectivity on those interfaces.\n\nDo you want to continue (yes/no)? ";
static constexpr auto singular = "Multipass needs to create a {} to connect to {}.\nThis will temporarily disrupt "
"connectivity on that interface.\n\nDo you want to continue (yes/no)? ";
static constexpr auto nodes = on_windows() ? "switches" : "bridges";
static constexpr auto node = on_windows() ? "switch" : "bridge";
if (term->is_live())
{
if (nets_need_bridging.size() != 1)
fmt::print(term->cout(), plural, nodes, fmt::join(nets_need_bridging, ", "));
else
fmt::print(term->cout(), singular, node, nets_need_bridging[0]);
while (true)
{
std::string answer;
std::getline(term->cin(), answer);
if (std::regex_match(answer, mp::client::yes_answer))
return true;
else if (std::regex_match(answer, mp::client::no_answer))
return false;
else
term->cout() << "Please answer yes/no: ";
}
}
return false;
}
| 3,420
|
C++
|
.cpp
| 94
| 30.957447
| 119
| 0.665053
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,783
|
argparser.cpp
|
canonical_multipass/src/client/cli/argparser.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/argparser.h>
#include <multipass/format.h>
#include <QFileInfo>
#include <QRegularExpression>
#include <algorithm>
/*
* ArgParser - a wrapping of a QCommandLineParser where the concept of a "command"
* is central. It chooses which Command is requested (if any) and allows that Command
* to continue the parsing of the arguments.
*
* This class also manages both the global and Command-specific help text, by massaging
* the natural output of QCommandLineParser::helpText.
*/
namespace mp = multipass;
namespace cmd = multipass::cmd;
namespace
{
const QStringList help_option_names
#ifdef MULTIPASS_PLATFORM_WINDOWS
{"?", "h", "help"};
#else
{"h", "help"};
#endif
auto max_command_string_length(const std::vector<cmd::Command::UPtr>& commands)
{
auto ret = 0ul;
if (!commands.empty())
{
auto string_len_compare = [](const cmd::Command::UPtr& a, const cmd::Command::UPtr& b) {
return a->name().length() < b->name().length();
};
const auto& max_elem = *std::max_element(commands.begin(), commands.end(), string_len_compare);
ret = max_elem->name().length();
}
return ret;
}
auto format_into_column(const std::string& name, std::string::size_type column_size)
{
return fmt::format(" {:<{}} ", name, column_size);
}
QString format_short_help_for(const std::vector<cmd::Command::UPtr>& commands)
{
const auto column_size = max_command_string_length(commands);
QString output;
for (const auto& c : commands)
{
output += QString::fromStdString(format_into_column(c->name(), column_size));
output += c->short_help() + "\n";
}
return output;
}
auto verbosity_level_in(const QStringList& arguments)
{
for (const QString& arg : arguments)
{
if (arg == QStringLiteral("-v") || arg == QStringLiteral("--verbose"))
return 1;
if (arg == QStringLiteral("-vv"))
return 2;
if (arg == QStringLiteral("-vvv"))
return 3;
if (QRegularExpression{"-vvvv+"}.match(arg).hasMatch())
return 4;
}
return 0;
}
} // namespace
mp::ArgParser::ArgParser(const QStringList& arguments, const std::vector<cmd::Command::UPtr>& commands,
std::ostream& cout, std::ostream& cerr)
: arguments(arguments), commands(commands), chosen_command(nullptr), help_requested(false), cout(cout), cerr(cerr)
{
}
mp::ParseCode mp::ArgParser::prepare_alias_execution(const QString& alias)
{
chosen_command = findCommand("exec");
auto pos = arguments.indexOf(alias);
arguments.replace(pos, "exec");
arguments.insert(pos + 1, QString::fromStdString(execute_alias->instance));
arguments.insert(pos + 2, QString::fromStdString(execute_alias->command));
return mp::ParseCode::Ok;
}
mp::ParseCode mp::ArgParser::parse(const std::optional<mp::AliasDict>& aliases)
{
QCommandLineOption help_option(help_option_names, "Displays help on commandline options");
QCommandLineOption verbose_option({"v", "verbose"},
"Increase logging verbosity. Repeat the 'v' in the short option for more detail. "
"Maximum verbosity is obtained with 4 (or more) v's, i.e. -vvvv.");
QCommandLineOption version_option({"V", "version"}, "Show version details");
version_option.setFlags(QCommandLineOption::HiddenFromHelp);
parser.addOption(help_option);
parser.addOption(verbose_option);
parser.addOption(version_option);
// Register "command" as the first positional argument, will need to be removed from all help text later
parser.addPositionalArgument("command", "The command to execute", "<command>");
// First pass parse - only interested in determining the requested command, help or verbosity.
const bool parser_result = parser.parse(arguments);
if (parser.isSet(verbose_option))
{
verbosity_level = verbosity_level_in(arguments);
}
help_requested = parser.isSet(help_option);
if (parser.positionalArguments().isEmpty() && !parser.isSet(version_option))
{
if (!parser_result)
{
cerr << qUtf8Printable(parser.errorText()) << "\n\n";
}
cout << qUtf8Printable(generalHelpText());
return (help_requested) ? ParseCode::HelpRequested : ParseCode::CommandFail;
}
const QString requested_command =
parser.isSet(version_option) ? QStringLiteral("version") : parser.positionalArguments().first();
chosen_command = findCommand(requested_command);
if (chosen_command)
{
return ParseCode::Ok;
}
if (help_requested)
{
cout << qUtf8Printable(generalHelpText());
return ParseCode::HelpRequested;
}
// The given argument is not a command name. Before failing, see if it is an alias.
if (aliases)
{
execute_alias = aliases->get_alias(requested_command.toStdString());
if (execute_alias)
return prepare_alias_execution(requested_command);
}
// Fall through
cout << "Error: Unknown command or alias '" << qUtf8Printable(requested_command)
<< "' (try \"multipass help\" or \"multipass aliases\")\n";
return ParseCode::CommandLineError;
}
// Parse the command line again, this time with a particular Command in mind
mp::ParseCode mp::ArgParser::commandParse(cmd::Command* command)
{
const bool parsedOk = parser.parse(arguments);
if (!parsedOk)
{
cerr << qUtf8Printable(parser.errorText()) << '\n';
return ParseCode::CommandLineError;
}
if (help_requested)
{
cout << qUtf8Printable(helpText(command));
return ParseCode::HelpRequested;
}
return ParseCode::Ok;
}
mp::ReturnCode mp::ArgParser::returnCodeFrom(ParseCode parse_code) const
{
switch (parse_code)
{
case ParseCode::CommandFail:
return ReturnCode::CommandFail;
case ParseCode::CommandLineError:
return ReturnCode::CommandLineError;
default:
return ReturnCode::Ok;
}
}
// This forces help to be printed using "help <command>"
void mp::ArgParser::forceCommandHelp()
{
parser.clearPositionalArguments();
// Need to add this back so helpText() can add the correct command for usage
parser.addPositionalArgument("command", "The command to execute", "<command>");
help_requested = true;
}
void mp::ArgParser::forceGeneralHelp()
{
cout << qUtf8Printable(generalHelpText());
}
// Prints generic help
QString mp::ArgParser::generalHelpText()
{
const QLatin1Char nl('\n');
// The help text generated by QCommandLineParser needs some minor editing:
// 1. Change "Displays this help." to "Display this help".
// 2. Remove path prepended to the multipass executable name.
// 3. remove the useless "Arguments" section listing just "command" (by clearing positional elements)
// 4. compensate by editing the "usage" line to add "command" option back
// 5. append a list of commands and their help text.
parser.clearPositionalArguments();
QString text = parser.helpText();
text = text.replace(QCommandLineParser::tr("Displays this help."), QCommandLineParser::tr("Display this help"));
QString cmd = text.split(' ').at(1);
text = text.replace(cmd, QFileInfo(cmd).baseName());
const int first_line_break_pos = text.indexOf('\n');
text.insert(first_line_break_pos, " <command>");
text += nl + QCommandLineParser::tr("Available commands:") + nl;
text += format_short_help_for(commands);
return text;
}
// Print command-specific help
QString mp::ArgParser::helpText(cmd::Command* command)
{
parser.setApplicationDescription(command->description());
QString text = parser.helpText();
const QLatin1Char nl('\n');
// The help text generated by QCommandLineParser needs some minor editing:
// 1. Change "Displays this help." to "Display this help".
// 2. Remove path prepended to the multipass executable name.
// 3. replace <command> with the command, and swap with the [options] entry
// 4. from the "Arguments" section, remove the "command" entry. Remove the entire
// section if it is empty afterwards.
text = text.replace(QCommandLineParser::tr("Displays this help."), QCommandLineParser::tr("Display this help"));
QString cmd = text.split(' ').at(1);
text = text.replace(cmd, QFileInfo(cmd).baseName());
text = text.replace(QCommandLineParser::tr("[options]") + " <command>",
QString::fromStdString(command->name()) + " " + QCommandLineParser::tr("[options]"));
int start = text.indexOf(QRegularExpression(" command\\s*The command to execute"));
int end = text.indexOf(nl, start);
text = text.replace(start, end - start + 1, "");
if (text.endsWith(QCommandLineParser::tr("Arguments:") + nl))
{
text = text.replace(nl + QCommandLineParser::tr("Arguments:") + nl, "");
}
return text;
}
/* Pass-through methods to the underlying QCommandLineParser */
void mp::ArgParser::setApplicationDescription(const QString& description)
{
parser.setApplicationDescription(description);
}
bool mp::ArgParser::addOption(const QCommandLineOption& command_line_option)
{
return parser.addOption(command_line_option);
}
bool mp::ArgParser::addOptions(const QList<QCommandLineOption>& options)
{
return parser.addOptions(options);
}
void mp::ArgParser::addPositionalArgument(const QString& name, const QString& description, const QString& syntax)
{
parser.addPositionalArgument(name, description, syntax);
}
cmd::Command* mp::ArgParser::chosenCommand() const
{
return chosen_command;
}
cmd::Command* mp::ArgParser::findCommand(const QString& command) const
{
for (const auto& c : commands)
{
for (const auto& alias : c->aliases())
{
if (command.toStdString() == alias)
{
return c.get();
}
}
}
return nullptr;
}
const std::vector<cmd::Command::UPtr>& mp::ArgParser::getCommands() const
{
return commands;
}
bool mp::ArgParser::isSet(const QString& option) const
{
return parser.isSet(option);
}
bool mp::ArgParser::isSet(const QCommandLineOption& option) const
{
return parser.isSet(option);
}
QString mp::ArgParser::value(const QCommandLineOption& option) const
{
return parser.value(option);
}
QString mp::ArgParser::value(const QString& option) const
{
return parser.value(option);
}
QStringList mp::ArgParser::values(const QCommandLineOption& option) const
{
return parser.values(option);
}
QStringList mp::ArgParser::positionalArguments() const
{
// Remove the first "command" positional argument, if there, so calling Command sees just the
// positional arguments it is interested in
auto positionalArguments = parser.positionalArguments();
if (positionalArguments.count() > 0)
{
positionalArguments.pop_front();
}
return positionalArguments;
}
QStringList mp::ArgParser::unknownOptionNames() const
{
return parser.unknownOptionNames();
}
void mp::ArgParser::setVerbosityLevel(int verbosity)
{
if (verbosity > 4 || verbosity < 0)
{
cerr << "Verbosity level is incorrect. Must be between 0 and 4.\n";
}
else if (verbosity_level != verbosity)
{
verbosity_level = verbosity;
}
}
int mp::ArgParser::verbosityLevel() const
{
return verbosity_level;
}
bool mp::ArgParser::containsArgument(const QString& argument) const
{
return arguments.contains(argument);
}
| 12,254
|
C++
|
.cpp
| 330
| 32.421212
| 120
| 0.691374
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,784
|
main.cpp
|
canonical_multipass/src/client/cli/main.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "client.h"
#include <multipass/cli/client_common.h>
#include <multipass/console.h>
#include <multipass/constants.h>
#include <multipass/top_catch_all.h>
#include <QCoreApplication>
namespace mp = multipass;
namespace
{
int main_impl(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName(mp::client_name);
mp::Console::setup_environment();
auto term = mp::Terminal::make_terminal();
mp::client::register_global_settings_handlers();
mp::ClientConfig config{mp::client::get_server_address(), mp::client::get_cert_provider(), term.get()};
mp::Client client{config};
return client.run(QCoreApplication::arguments());
}
} // namespace
int main(int argc, char* argv[])
{
return mp::top_catch_all("client", /* fallback_return = */ EXIT_FAILURE, main_impl, argc, argv);
}
| 1,489
|
C++
|
.cpp
| 41
| 33.829268
| 107
| 0.737135
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,785
|
client.cpp
|
canonical_multipass/src/client/cli/client.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "client.h"
#include "cmd/alias.h"
#include "cmd/aliases.h"
#include "cmd/authenticate.h"
#include "cmd/clone.h"
#include "cmd/delete.h"
#include "cmd/exec.h"
#include "cmd/find.h"
#include "cmd/get.h"
#include "cmd/help.h"
#include "cmd/info.h"
#include "cmd/launch.h"
#include "cmd/list.h"
#include "cmd/mount.h"
#include "cmd/networks.h"
#include "cmd/prefer.h"
#include "cmd/purge.h"
#include "cmd/recover.h"
#include "cmd/remote_settings_handler.h"
#include "cmd/restart.h"
#include "cmd/restore.h"
#include "cmd/set.h"
#include "cmd/shell.h"
#include "cmd/snapshot.h"
#include "cmd/start.h"
#include "cmd/stop.h"
#include "cmd/suspend.h"
#include "cmd/transfer.h"
#include "cmd/umount.h"
#include "cmd/unalias.h"
#include "cmd/version.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/client_common.h>
#include <multipass/cli/client_platform.h>
#include <multipass/constants.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/settings/settings.h>
#include <multipass/top_catch_all.h>
#include <scope_guard.hpp>
#include <algorithm>
#include <memory>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
auto make_handler_unregisterer(mp::SettingsHandler* handler)
{
return sg::make_scope_guard([handler]() noexcept {
mp::top_catch_all("client", [handler] {
MP_SETTINGS.unregister_handler(handler); // trust me clang-format
});
});
}
} // namespace
mp::Client::Client(ClientConfig& config)
: stub{mp::Rpc::NewStub(mp::client::make_channel(config.server_address, *config.cert_provider))},
term{config.term},
aliases{config.term}
{
add_command<cmd::Alias>(aliases);
add_command<cmd::Aliases>(aliases);
add_command<cmd::Authenticate>();
add_command<cmd::Launch>(aliases);
add_command<cmd::Purge>(aliases);
add_command<cmd::Exec>(aliases);
add_command<cmd::Find>();
add_command<cmd::Get>();
add_command<cmd::Help>();
add_command<cmd::Info>();
add_command<cmd::List>();
add_command<cmd::Networks>();
add_command<cmd::Mount>();
add_command<cmd::Prefer>(aliases);
add_command<cmd::Recover>();
add_command<cmd::Restore>();
add_command<cmd::Set>();
add_command<cmd::Shell>();
add_command<cmd::Snapshot>();
add_command<cmd::Start>();
add_command<cmd::Stop>();
add_command<cmd::Suspend>();
add_command<cmd::Transfer>();
add_command<cmd::Unalias>(aliases);
add_command<cmd::Restart>();
add_command<cmd::Delete>(aliases);
add_command<cmd::Umount>();
add_command<cmd::Version>();
add_command<cmd::Clone>();
sort_commands();
MP_CLIENT_PLATFORM.enable_ansi_escape_chars();
}
void mp::Client::sort_commands()
{
auto name_sort = [](cmd::Command::UPtr& a, cmd::Command::UPtr& b) { return a->name() < b->name(); };
std::sort(commands.begin(), commands.end(), name_sort);
}
int mp::Client::run(const QStringList& arguments)
{
QString description("Create, control and connect to Ubuntu instances.\n\n"
"This is a command line utility for multipass, a\n"
"service that manages Ubuntu instances.");
ArgParser parser(arguments, commands, term->cout(), term->cerr());
parser.setApplicationDescription(description);
mp::ReturnCode ret = mp::ReturnCode::Ok;
ParseCode parse_status = parser.parse(aliases);
auto verbosity = parser.verbosityLevel(); // try to respect requested verbosity, even if parsing failed
if (!mpl::get_logger())
mp::client::set_logger(mpl::level_from(verbosity));
{
auto daemon_settings_prefix = QString{daemon_settings_root} + ".";
auto* handler = MP_SETTINGS.register_handler(
std::make_unique<RemoteSettingsHandler>(std::move(daemon_settings_prefix), *stub, term, verbosity));
auto handler_unregisterer = make_handler_unregisterer(handler); // remove handler before its dependencies expire
try
{
ret = parse_status == ParseCode::Ok ? parser.chosenCommand()->run(&parser)
: parser.returnCodeFrom(parse_status);
}
catch (const RemoteHandlerException& e)
{
ret = mp::cmd::standard_failure_handler_for(parser.chosenCommand()->name(), term->cerr(), e.get_status());
}
}
mp::client::post_setup();
return ret;
}
| 5,075
|
C++
|
.cpp
| 143
| 31.181818
| 120
| 0.682743
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,786
|
remote_settings_handler.cpp
|
canonical_multipass/src/client/cli/cmd/remote_settings_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "remote_settings_handler.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include <multipass/cli/command.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/logging/log.h>
#include <cassert>
#include <stdexcept>
#include <utility>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "remote settings";
class InternalCmd : public mp::cmd::Command // TODO feels hacky, better untangle dispatch from commands
{
public:
using mp::cmd::Command::Command;
private: // demote visibility of the following methods
[[noreturn]] mp::ReturnCode run(mp::ArgParser*) override
{
fail();
}
[[noreturn]] std::string name() const override
{
fail();
}
[[noreturn]] QString short_help() const override
{
fail();
}
[[noreturn]] QString description() const override
{
fail();
}
[[noreturn]] static void fail()
{
assert(false);
throw std::logic_error{"shouldn't be here"};
}
};
class RemoteSettingsCmd : public InternalCmd
{
public:
using InternalCmd::InternalCmd;
protected:
[[noreturn]] static mp::ReturnCode on_failure(grpc::Status& status)
{
throw mp::RemoteHandlerException{status};
}
template <typename ReplyType>
static mp::ReturnCode on_success(ReplyType&)
{
return mp::ReturnCode::Ok;
}
};
class RemoteGet : public RemoteSettingsCmd
{
public:
RemoteGet(const QString& key, mp::Rpc::StubInterface& stub, mp::Terminal* term, int verbosity)
: RemoteSettingsCmd{stub, term} // need to ensure refs outlive this
{
mp::GetRequest get_request;
get_request.set_verbosity_level(verbosity);
get_request.set_key(key.toStdString());
auto custom_on_success = [this](mp::GetReply& reply) {
got = QString::fromStdString(reply.value());
return mp::ReturnCode::Ok;
};
[[maybe_unused]] auto ret = dispatch(&RpcMethod::get, get_request, custom_on_success, on_failure);
assert(ret == mp::ReturnCode::Ok && "should have thrown otherwise");
}
public:
QString got = {};
};
class RemoteSet : public RemoteSettingsCmd
{
public:
RemoteSet(const QString& key,
const QString& val,
mp::Rpc::StubInterface& stub,
mp::Terminal* term,
int verbosity,
bool user_authorized)
: RemoteSettingsCmd{stub, term} // need to ensure refs outlive this
{
mp::SetRequest set_request;
set_request.set_verbosity_level(verbosity);
set_request.set_key(key.toStdString());
set_request.set_val(val.toStdString());
set_request.set_authorized(user_authorized);
mp::AnimatedSpinner spinner{cout};
auto streaming_confirmation_callback = mp::make_confirmation_callback<mp::SetRequest, mp::SetReply>(*term, key);
[[maybe_unused]] auto ret = dispatch(&RpcMethod::set,
set_request,
on_success<mp::SetReply>,
on_failure,
streaming_confirmation_callback);
assert(ret == mp::ReturnCode::Ok && "should have thrown otherwise");
}
};
class RemoteKeys : public RemoteSettingsCmd
{
public:
RemoteKeys(mp::Rpc::StubInterface& stub, mp::Terminal* term, int verbosity) : RemoteSettingsCmd{stub, term}
{
mp::KeysRequest keys_request;
keys_request.set_verbosity_level(verbosity);
auto custom_on_success = [this](mp::KeysReply& reply) {
for (auto& key : *reply.mutable_settings_keys())
keys.insert(QString::fromStdString(std::move(key))); // no actual move until QString supports it
return mp::ReturnCode::Ok;
};
auto custom_on_failure = [](grpc::Status& status) {
if (auto code = status.error_code(); code == grpc::NOT_FOUND)
{
mpl::log(mpl::Level::error, category, "Could not reach daemon.");
return mp::ReturnCode::Ok;
}
return on_failure(status);
};
[[maybe_unused]] auto ret = dispatch(&RpcMethod::keys, keys_request, custom_on_success, custom_on_failure);
assert(ret == mp::ReturnCode::Ok && "should have thrown otherwise");
}
public:
std::set<QString> keys = {};
};
} // namespace
mp::RemoteSettingsHandler::RemoteSettingsHandler(QString key_prefix, mp::Rpc::StubInterface& stub,
multipass::Terminal* term, int verbosity)
: key_prefix{std::move(key_prefix)}, stub{stub}, term{term}, verbosity{verbosity}
{
assert(term);
}
QString mp::RemoteSettingsHandler::get(const QString& key) const
{
if (key.startsWith(key_prefix))
{
assert(term);
return RemoteGet{key, stub, term, verbosity}.got;
}
throw mp::UnrecognizedSettingException{key};
}
void mp::RemoteSettingsHandler::set(const QString& key, const QString& val)
{
if (key.startsWith(key_prefix))
{
assert(term);
RemoteSet(key, val, stub, term, verbosity, false);
}
else
throw mp::UnrecognizedSettingException{key};
}
std::set<QString> mp::RemoteSettingsHandler::keys() const
{
assert(term);
return RemoteKeys{stub, term, verbosity}.keys;
}
mp::RemoteHandlerException::RemoteHandlerException(grpc::Status status)
: std::runtime_error{"Error accessing remote setting"}, status{std::move(status)}
{
}
grpc::Status mp::RemoteHandlerException::get_status() const
{
return status;
}
| 6,356
|
C++
|
.cpp
| 182
| 28.417582
| 120
| 0.64956
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,787
|
launch.cpp
|
canonical_multipass/src/client/cli/cmd/launch.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "launch.h"
#include "animated_spinner.h"
#include "common_cli.h"
#include "create_alias.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/client_platform.h>
#include <multipass/cli/prompters.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <multipass/settings/settings.h>
#include <multipass/snap_utils.h>
#include <multipass/standard_paths.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <yaml-cpp/yaml.h>
#include <QDir>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTimeZone>
#include <QUrl>
#include <filesystem>
#include <unordered_map>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace cmd = multipass::cmd;
namespace mcp = multipass::cli::platform;
namespace fs = std::filesystem;
namespace
{
auto checked_mode(const std::string& mode)
{
if (mode == "auto")
return mp::LaunchRequest_NetworkOptions_Mode::LaunchRequest_NetworkOptions_Mode_AUTO;
if (mode == "manual")
return mp::LaunchRequest_NetworkOptions_Mode::LaunchRequest_NetworkOptions_Mode_MANUAL;
else
throw mp::ValidationException{fmt::format("Bad network mode '{}', need 'auto' or 'manual'", mode)};
}
const std::string& checked_mac(const std::string& mac)
{
if (!mpu::valid_mac_address(mac))
throw mp::ValidationException(fmt::format("Invalid MAC address: {}", mac));
return mac;
}
auto net_digest(const QString& options)
{
multipass::LaunchRequest_NetworkOptions net;
QStringList split = options.split(',', Qt::SkipEmptyParts);
for (const auto& key_value_pair : split)
{
QStringList key_value_split = key_value_pair.split('=', Qt::SkipEmptyParts);
if (key_value_split.size() == 2)
{
const auto& key = key_value_split[0].toLower();
const auto& val = key_value_split[1];
if (key == "name")
net.set_id(val.toStdString());
else if (key == "mode")
net.set_mode(checked_mode(val.toLower().toStdString()));
else if (key == "mac")
net.set_mac_address(checked_mac(val.toStdString()));
else
throw mp::ValidationException{fmt::format("Bad network field: {}", key)};
}
// Interpret as "name" the argument when there are no ',' and no '='.
else if (key_value_split.size() == 1 && split.size() == 1)
net.set_id(key_value_split[0].toStdString());
else
throw mp::ValidationException{fmt::format("Bad network field definition: {}", key_value_pair)};
}
if (net.id().empty())
throw mp::ValidationException{fmt::format("Bad network definition, need at least a 'name' field")};
return net;
}
} // namespace
mp::ReturnCode cmd::Launch::run(mp::ArgParser* parser)
{
petenv_name = MP_SETTINGS.get(petenv_key);
if (auto ret = parse_args(parser); ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto ret = request_launch(parser);
if (ret != ReturnCode::Ok)
return ret;
auto got_petenv = instance_name == petenv_name;
if (!got_petenv && mount_routes.empty())
return ret;
if (MP_SETTINGS.get_as<bool>(mounts_key))
{
auto has_home_mount = std::count_if(mount_routes.begin(), mount_routes.end(),
[](const auto& route) { return route.second == home_automount_dir; });
if (got_petenv && !has_home_mount)
{
try
{
mount_routes.emplace_back(QString::fromLocal8Bit(mpu::snap_real_home_dir()), home_automount_dir);
}
catch (const SnapEnvironmentException&)
{
mount_routes.emplace_back(QDir::toNativeSeparators(QDir::homePath()), home_automount_dir);
}
}
for (const auto& [source, target] : mount_routes)
{
auto mount_ret = mount(parser, source, target);
if (ret == ReturnCode::Ok)
{
ret = mount_ret;
}
}
}
else
{
cout << "Skipping mount due to disabled mounts feature\n";
}
return ret;
}
std::string cmd::Launch::name() const
{
return "launch";
}
QString cmd::Launch::short_help() const
{
return QStringLiteral("Create and start an Ubuntu instance");
}
QString cmd::Launch::description() const
{
return QStringLiteral("Create and start a new instance.");
}
mp::ParseCode cmd::Launch::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("image",
"Optional image to launch. If omitted, then the default Ubuntu LTS "
"will be used.\n"
"<remote> can be either ‘release’ or ‘daily‘. If <remote> is omitted, "
"‘release’ will be used.\n"
"<image> can be a partial image hash or an Ubuntu release version, "
"codename or alias.\n"
"<url> is a custom image URL that is in http://, https://, or file:// "
"format.\n",
"[[<remote:>]<image> | <url>]");
QCommandLineOption cpusOption({"c", "cpus"},
QString::fromStdString(fmt::format("Number of CPUs to allocate.\n"
"Minimum: {}, default: {}.",
min_cpu_cores, default_cpu_cores)),
"cpus", default_cpu_cores);
QCommandLineOption diskOption(
{"d", "disk"},
QString::fromStdString(fmt::format("Disk space to allocate. Positive integers, in "
"bytes, or decimals, with K, M, G suffix.\nMinimum: {}, default: {}.",
min_disk_size, default_disk_size)),
"disk", QString::fromUtf8(default_disk_size));
QCommandLineOption memOption(
{"m", "memory"},
QString::fromStdString(fmt::format("Amount of memory to allocate. Positive integers, "
"in bytes, or decimals, with K, M, G suffix.\nMinimum: {}, default: {}.",
min_memory_size, default_memory_size)),
"memory", QString::fromUtf8(default_memory_size)); // In MB's
QCommandLineOption memOptionDeprecated(
"mem", QString::fromStdString("Deprecated memory allocation long option. See \"--memory\"."), "memory",
QString::fromUtf8(default_memory_size));
memOptionDeprecated.setFlags(QCommandLineOption::HiddenFromHelp);
const auto valid_name_desc = QString{"Valid names must consist of letters, numbers, or hyphens, must start with a "
"letter, and must end with an alphanumeric character."};
const auto name_option_desc =
petenv_name.isEmpty()
? QString{"Name for the instance.\n%1"}.arg(valid_name_desc)
: QString{"Name for the instance. If it is '%1' (the configured primary instance name), the user's home "
"directory is mounted inside the newly launched instance, in '%2'.\n%3"}
.arg(petenv_name, mp::home_automount_dir, valid_name_desc);
QCommandLineOption nameOption({"n", "name"}, name_option_desc, "name");
QCommandLineOption cloudInitOption(
"cloud-init", "Path or URL to a user-data cloud-init configuration, or '-' for stdin", "file> | <url");
QCommandLineOption networkOption("network",
"Add a network interface to the instance, where <spec> is in the "
"\"key=value,key=value\" format, with the following keys available:\n"
" name: the network to connect to (required), use the networks command for a "
"list of possible values, or use 'bridged' to use the interface configured via "
"`multipass set local.bridged-network`.\n"
" mode: auto|manual (default: auto)\n"
" mac: hardware address (default: random).\n"
"You can also use a shortcut of \"<name>\" to mean \"name=<name>\".",
"spec");
QCommandLineOption bridgedOption("bridged", "Adds one `--network bridged` network.");
QCommandLineOption mountOption("mount",
"Mount a local directory inside the instance. If <instance-path> is omitted, the "
"mount point will be the same as the absolute path of <local-path>",
"local-path>:<instance-path");
parser->addOptions({cpusOption, diskOption, memOption, memOptionDeprecated, nameOption, cloudInitOption,
networkOption, bridgedOption, mountOption});
mp::cmd::add_timeout(parser);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 1)
{
cerr << "Too many arguments supplied\n";
return ParseCode::CommandLineError;
}
if (!parser->positionalArguments().isEmpty())
{
auto remote_image_name = parser->positionalArguments().first();
if (remote_image_name.startsWith("file://"))
{
// Convert to absolute because the daemon doesn't know where the client is being executed.
auto file_info = QFileInfo(remote_image_name.remove(0, 7));
auto absolute_file_path = file_info.absoluteFilePath();
request.set_image("file://" + absolute_file_path.toStdString());
}
else if (remote_image_name.startsWith("http://") || remote_image_name.startsWith("https://"))
{
request.set_image(remote_image_name.toStdString());
}
else
{
auto colon_count = remote_image_name.count(':');
if (colon_count > 1)
{
cerr << "Invalid remote and source image name supplied\n";
return ParseCode::CommandLineError;
}
else if (colon_count == 1)
{
request.set_remote_name(remote_image_name.section(':', 0, 0).toStdString());
request.set_image(remote_image_name.section(':', 1).toStdString());
}
else
{
request.set_image(remote_image_name.toStdString());
}
}
}
if (parser->isSet(nameOption))
{
request.set_instance_name(parser->value(nameOption).toStdString());
}
if (parser->isSet(cpusOption))
{
bool conversion_pass;
const auto& cpu_text = parser->value(cpusOption);
const int cpu_count = cpu_text.toInt(&conversion_pass); // Base 10 conversion with check.
if (!conversion_pass || cpu_count < 1)
{
fmt::print(cerr, "Error: invalid CPU count '{}', need a positive integer value.\n", cpu_text);
return ParseCode::CommandLineError;
}
request.set_num_cores(cpu_count);
}
if (parser->isSet(memOption) || parser->isSet(memOptionDeprecated))
{
if (parser->isSet(memOption) && parser->isSet(memOptionDeprecated))
{
cerr << "Error: invalid option(s) used for memory allocation. Please use \"--memory\" to specify amount of "
"memory to allocate.\n";
return ParseCode::CommandLineError;
}
if (parser->isSet(memOptionDeprecated))
cerr << "Warning: the \"--mem\" long option is deprecated in favour of \"--memory\". Please update any "
"scripts, etc.\n";
auto arg_mem_size = parser->isSet(memOption) ? parser->value(memOption).toStdString()
: parser->value(memOptionDeprecated).toStdString();
mp::MemorySize{arg_mem_size}; // throw if bad
request.set_mem_size(arg_mem_size);
}
if (parser->isSet(diskOption))
{
auto arg_disk_size = parser->value(diskOption).toStdString();
mp::MemorySize{arg_disk_size}; // throw if bad
request.set_disk_space(arg_disk_size);
}
if (parser->isSet(mountOption))
{
for (const auto& value : parser->values(mountOption))
{
// this is needed so that Windows absolute paths are not split at the colon following the drive letter
auto colon_split = QRegularExpression{R"(^[A-Za-z]:[\\/].*)"}.match(value).hasMatch();
auto mount_source = value.section(':', 0, colon_split);
auto mount_target = value.section(':', colon_split + 1);
mount_target = mount_target.isEmpty() ? mount_source : mount_target;
// Validate source directory of client side mounts
QFileInfo source_dir(mount_source);
if (!MP_FILEOPS.exists(source_dir))
{
cerr << "Mount source path \"" << mount_source.toStdString() << "\" does not exist\n";
return ParseCode::CommandLineError;
}
if (!MP_FILEOPS.isDir(source_dir))
{
cerr << "Mount source path \"" << mount_source.toStdString() << "\" is not a directory\n";
return ParseCode::CommandLineError;
}
if (!MP_FILEOPS.isReadable(source_dir))
{
cerr << "Mount source path \"" << mount_source.toStdString() << "\" is not readable\n";
return ParseCode::CommandLineError;
}
mount_routes.emplace_back(mount_source, mount_target);
}
}
if (parser->isSet(cloudInitOption))
{
constexpr auto err_msg_template = "Could not load cloud-init configuration: {}";
try
{
const QString& cloud_init_file = parser->value(cloudInitOption);
YAML::Node node;
if (cloud_init_file == "-")
{
node = YAML::Load(term->read_all_cin());
}
else if (cloud_init_file.startsWith("http://") || cloud_init_file.startsWith("https://"))
{
URLDownloader downloader{std::chrono::minutes{1}};
auto downloaded_yaml = downloader.download(QUrl(cloud_init_file));
node = YAML::Load(downloaded_yaml.toStdString());
}
else
{
auto cloud_init_file_stdstr = cloud_init_file.toStdString();
auto file_type = fs::status(cloud_init_file_stdstr).type();
if (file_type != fs::file_type::regular && file_type != fs::file_type::fifo)
throw YAML::BadFile{cloud_init_file_stdstr};
node = YAML::LoadFile(cloud_init_file_stdstr);
}
request.set_cloud_init_user_data(YAML::Dump(node));
}
catch (const YAML::BadFile& e)
{
auto err_detail = fmt::format("{}\n{}", e.what(), "Please ensure that Multipass can read it.");
fmt::println(cerr, err_msg_template, err_detail);
return ParseCode::CommandLineError;
}
catch (const YAML::Exception& e)
{
fmt::println(cerr, err_msg_template, e.what());
return ParseCode::CommandLineError;
}
}
if (parser->isSet(bridgedOption))
{
request.mutable_network_options()->Add(net_digest(mp::bridged_network_name));
}
try
{
if (parser->isSet(networkOption))
for (const auto& net : parser->values(networkOption))
request.mutable_network_options()->Add(net_digest(net));
request.set_timeout(mp::cmd::parse_timeout(parser));
}
catch (mp::ValidationException& e)
{
cerr << "error: " << e.what() << "\n";
return ParseCode::CommandLineError;
}
request.set_time_zone(QTimeZone::systemTimeZoneId().toStdString());
request.set_verbosity_level(parser->verbosityLevel());
return status;
}
mp::ReturnCode cmd::Launch::request_launch(const ArgParser* parser)
{
if (!spinner)
spinner = std::make_unique<multipass::AnimatedSpinner>(
cout); // Creating just in time to work around canonical/multipass#2075
if (timer)
timer->resume();
else if (parser->isSet("timeout"))
{
timer = cmd::make_timer(parser->value("timeout").toInt(), spinner.get(), cerr,
"Timed out waiting for instance launch.");
timer->start();
}
auto on_success = [this, &parser](mp::LaunchReply& reply) {
spinner->stop();
if (timer)
timer->pause();
instance_name = QString::fromStdString(request.instance_name().empty() ? reply.vm_instance_name()
: request.instance_name());
std::vector<std::string> warning_aliases;
for (const auto& alias_to_be_created : reply.aliases_to_be_created())
{
AliasDefinition alias_definition{alias_to_be_created.instance(), alias_to_be_created.command(),
alias_to_be_created.working_directory()};
if (create_alias(aliases, alias_to_be_created.name(), alias_definition, cout, cerr,
instance_name.toStdString()) != ReturnCode::Ok)
warning_aliases.push_back(alias_to_be_created.name());
}
if (warning_aliases.size())
cerr << fmt::format("Warning: unable to create {} {}.\n",
warning_aliases.size() == 1 ? "alias" : "aliases",
fmt::join(warning_aliases, ", "));
for (const auto& workspace_to_be_created : reply.workspaces_to_be_created())
{
auto home_dir = mpu::in_multipass_snap() ? QString::fromLocal8Bit(mpu::snap_real_home_dir())
: MP_STDPATHS.writableLocation(StandardPaths::HomeLocation);
auto full_path_str = home_dir + "/multipass/" + QString::fromStdString(workspace_to_be_created);
QDir full_path(full_path_str);
if (full_path.exists())
{
cerr << fmt::format("Folder \"{}\" already exists.\n", full_path_str);
}
else
{
if (!MP_FILEOPS.mkpath(full_path, full_path_str))
{
cerr << fmt::format("Error creating folder {}. Not mounting.\n", full_path_str);
continue;
}
}
if (mount(parser, full_path_str, QString::fromStdString(workspace_to_be_created)) != ReturnCode::Ok)
{
cerr << fmt::format("Error mounting folder {}.\n", full_path_str);
}
}
cout << "Launched: " << reply.vm_instance_name() << "\n";
if (term->is_live() && update_available(reply.update_info()))
{
// TODO: daemon doesn't know if client actually shows this notice. Need to be able
// to tell daemon that the notice will be displayed or not.
cout << update_notice(reply.update_info());
}
return ReturnCode::Ok;
};
auto on_failure = [this, &parser](grpc::Status& status, mp::LaunchReply& reply) {
spinner->stop();
if (timer)
timer->pause();
LaunchError launch_error;
launch_error.ParseFromString(status.error_details());
std::string error_details;
for (const auto& error : launch_error.error_codes())
{
if (error == LaunchError::INVALID_DISK_SIZE)
{
error_details = fmt::format("Invalid disk size value supplied: {}.", request.disk_space());
}
else if (error == LaunchError::INVALID_MEM_SIZE)
{
error_details = fmt::format("Invalid memory size value supplied: {}.", request.mem_size());
}
else if (error == LaunchError::INVALID_HOSTNAME)
{
error_details = fmt::format("Invalid instance name supplied: {}", request.instance_name());
}
else if (error == LaunchError::INVALID_NETWORK)
{
if (reply.nets_need_bridging_size() && ask_bridge_permission(reply))
{
request.set_permission_to_bridge(true);
return request_launch(parser);
}
// TODO: show the option which triggered the error only. This will need a refactor in the
// LaunchError proto.
error_details = "Invalid network options supplied";
}
}
return standard_failure_handler_for(name(), cerr, status, error_details);
};
auto streaming_callback = [this](mp::LaunchReply& reply,
grpc::ClientReaderWriterInterface<LaunchRequest, LaunchReply>* client) {
std::unordered_map<int, std::string> progress_messages{
{LaunchProgress_ProgressTypes_IMAGE, "Retrieving image: "},
{LaunchProgress_ProgressTypes_EXTRACT, "Extracting image: "},
{LaunchProgress_ProgressTypes_VERIFY, "Verifying image: "},
{LaunchProgress_ProgressTypes_WAITING, "Preparing image: "}};
if (!reply.log_line().empty())
{
spinner->print(cerr, reply.log_line());
}
if (reply.create_oneof_case() == mp::LaunchReply::CreateOneofCase::kLaunchProgress)
{
auto& progress_message = progress_messages[reply.launch_progress().type()];
if (reply.launch_progress().percent_complete() != "-1")
{
spinner->stop();
cout << "\r";
cout << progress_message << reply.launch_progress().percent_complete() << "%" << std::flush;
}
else
{
spinner->stop();
spinner->start(progress_message);
}
}
else if (reply.create_oneof_case() == mp::LaunchReply::CreateOneofCase::kCreateMessage)
{
spinner->stop();
spinner->start(reply.create_message());
}
else if (!reply.reply_message().empty())
{
spinner->stop();
spinner->start(reply.reply_message());
}
};
return dispatch(&RpcMethod::launch, request, on_success, on_failure, streaming_callback);
}
auto cmd::Launch::mount(const mp::ArgParser* parser, const QString& mount_source, const QString& mount_target)
-> ReturnCode
{
const auto full_mount_target = QString{"%1:%2"}.arg(instance_name, mount_target);
auto ret = run_cmd({"multipass", "mount", mount_source, full_mount_target}, parser, cout, cerr);
if (ret == Ok)
cout << fmt::format("Mounted '{}' into '{}'\n", mount_source, full_mount_target);
return ret;
}
bool cmd::Launch::ask_bridge_permission(multipass::LaunchReply& reply)
{
std::vector<std::string> nets;
std::copy(reply.nets_need_bridging().cbegin(), reply.nets_need_bridging().cend(), std::back_inserter(nets));
mp::BridgePrompter prompter(term);
return prompter.bridge_prompt(nets);
}
| 24,545
|
C++
|
.cpp
| 535
| 34.44486
| 120
| 0.572647
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,788
|
unalias.cpp
|
canonical_multipass/src/client/cli/cmd/unalias.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "unalias.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/platform.h>
#include <QJsonDocument>
#include <QJsonObject>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Unalias::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto old_active_context = aliases.active_context_name();
for (const auto& [context_from, alias_only] : aliases_to_remove)
{
aliases.set_active_context(context_from);
aliases.remove_alias(alias_only); // We know removal won't fail because the alias exists.
try
{
MP_PLATFORM.remove_alias_script(context_from + "." + alias_only);
if (!aliases.exists_alias(alias_only))
{
MP_PLATFORM.remove_alias_script(alias_only);
}
}
catch (std::runtime_error& e)
{
cerr << fmt::format("Warning: '{}' when removing alias script for {}.{}\n", e.what(), context_from,
alias_only);
}
}
aliases.set_active_context(old_active_context);
return ReturnCode::Ok;
}
std::string cmd::Unalias::name() const
{
return "unalias";
}
QString cmd::Unalias::short_help() const
{
return QStringLiteral("Remove aliases");
}
QString cmd::Unalias::description() const
{
return QStringLiteral("Remove aliases");
}
mp::ParseCode cmd::Unalias::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("name", "Names of aliases to remove", "<name> [<name> ...]");
QCommandLineOption all_option(all_option_name, "Remove all aliases from current context");
parser->addOption(all_option);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr, false);
if (parse_code != ParseCode::Ok)
return parse_code;
std::vector<std::string> bad_aliases;
if (parser->isSet(all_option_name))
{
const auto& active_context_name = aliases.active_context_name();
const auto& active_context = aliases.get_active_context();
for (auto definition_it = active_context.cbegin(); definition_it != active_context.cend(); ++definition_it)
aliases_to_remove.emplace_back(active_context_name, definition_it->first);
}
else
{
for (const auto& arg : parser->positionalArguments())
{
auto arg_str = arg.toStdString();
auto context_and_alias = aliases.get_context_and_alias(arg_str);
if (context_and_alias)
aliases_to_remove.emplace_back(context_and_alias->first, context_and_alias->second);
else
bad_aliases.push_back(arg_str);
}
}
if (!bad_aliases.empty())
{
cerr << fmt::format("Nonexistent {}: {}.\n", bad_aliases.size() == 1 ? "alias" : "aliases",
fmt::join(bad_aliases, ", "));
return ParseCode::CommandLineError;
}
return ParseCode::Ok;
}
| 3,810
|
C++
|
.cpp
| 104
| 30.403846
| 115
| 0.648193
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,789
|
purge.cpp
|
canonical_multipass/src/client/cli/cmd/purge.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "purge.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/platform.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Purge::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](mp::PurgeReply& reply) {
auto size = reply.purged_instances_size();
for (auto i = 0; i < size; ++i)
{
const auto purged_instance = reply.purged_instances(i);
const auto removed_aliases = aliases.remove_aliases_for_instance(purged_instance);
for (const auto& [removal_context, removed_alias_name] : removed_aliases)
{
try
{
MP_PLATFORM.remove_alias_script(removal_context + "." + removed_alias_name);
if (!aliases.exists_alias(removed_alias_name))
{
MP_PLATFORM.remove_alias_script(removed_alias_name);
}
}
catch (const std::runtime_error& e)
{
cerr << fmt::format("Warning: '{}' when removing alias script for {}.{}\n", e.what(),
removal_context, removed_alias_name);
}
}
}
return mp::ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
mp::PurgeRequest request;
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::purge, request, on_success, on_failure);
}
std::string cmd::Purge::name() const
{
return "purge";
}
QString cmd::Purge::short_help() const
{
return QStringLiteral("Purge all deleted instances permanently");
}
QString cmd::Purge::description() const
{
return QStringLiteral("Purge all deleted instances permanently, including all their data.");
}
mp::ParseCode cmd::Purge::parse_args(mp::ArgParser* parser)
{
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 0)
{
cerr << "This command takes no arguments\n";
return ParseCode::CommandLineError;
}
return status;
}
| 3,040
|
C++
|
.cpp
| 85
| 28.788235
| 114
| 0.630361
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,790
|
alias.cpp
|
canonical_multipass/src/client/cli/cmd/alias.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "alias.h"
#include "common_cli.h"
#include "create_alias.h"
#include <multipass/cli/argparser.h>
#include <multipass/platform.h>
#include <QDir>
#include <QtGlobal>
namespace mp = multipass;
namespace cmd = multipass::cmd;
namespace
{
const QString no_alias_dir_mapping_option{"no-map-working-directory"};
} // namespace
mp::ReturnCode cmd::Alias::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
return create_alias(aliases, alias_name, alias_definition, cout, cerr);
}
std::string cmd::Alias::name() const
{
return "alias";
}
QString cmd::Alias::short_help() const
{
return QStringLiteral("Create an alias");
}
QString cmd::Alias::description() const
{
return QStringLiteral("Create an alias to be executed on a given instance.");
}
mp::ParseCode cmd::Alias::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("definition", "Alias definition in the form <instance>:<command>", "<definition>");
parser->addPositionalArgument("name", "Name given to the alias being defined, defaults to <command>", "[<name>]");
QCommandLineOption noAliasDirMappingOption({"n", no_alias_dir_mapping_option},
"Do not automatically map the host execution path to a mounted path");
parser->addOptions({noAliasDirMappingOption});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
// The number of arguments
if (parser->positionalArguments().count() != 1 && parser->positionalArguments().count() != 2)
{
cerr << "Wrong number of arguments given\n";
return ParseCode::CommandLineError;
}
QStringList cl_definition = parser->positionalArguments();
QString definition = cl_definition[0];
auto colon_pos = definition.indexOf(':');
if (colon_pos == -1 || colon_pos == definition.size() - 1)
{
cerr << "No command given\n";
return ParseCode::CommandLineError;
}
if (colon_pos == 0)
{
cerr << "No instance name given\n";
return ParseCode::CommandLineError;
}
auto command = definition.right(definition.size() - colon_pos - 1).toStdString();
if (parser->positionalArguments().count() == 1)
{
alias_name = QFileInfo(QString::fromStdString(command)).fileName().toStdString();
}
else
{
alias_name = cl_definition[1].toStdString();
if (QFileInfo(cl_definition[1]).fileName().toStdString() != alias_name)
{
cerr << "Alias has to be a valid filename" << std::endl;
return ParseCode::CommandLineError;
}
}
auto instance = definition.left(colon_pos).toStdString();
auto working_directory = parser->isSet(no_alias_dir_mapping_option) ? "default" : "map";
info_request.add_instance_snapshot_pairs()->set_instance_name(instance);
info_request.set_verbosity_level(0);
info_request.set_no_runtime_information(true);
auto on_success = [](InfoReply&) { return ReturnCode::Ok; };
auto on_failure = [](grpc::Status& status) {
return status.error_code() == grpc::StatusCode::INVALID_ARGUMENT ? ReturnCode::CommandLineError
: ReturnCode::DaemonFail;
};
auto ret = dispatch(&RpcMethod::info, info_request, on_success, on_failure);
if (ret == ReturnCode::DaemonFail)
{
cerr << "Error retrieving list of instances\n";
return ParseCode::CommandLineError;
}
if (ret == ReturnCode::CommandLineError)
{
cerr << fmt::format("Instance '{}' does not exist\n", instance);
return ParseCode::CommandLineError;
}
if (aliases.get_alias_from_current_context(alias_name))
{
cerr << fmt::format("Alias '{}' already exists in current context\n", alias_name);
return ParseCode::CommandLineError;
}
if (parser->findCommand(QString::fromStdString(alias_name)))
{
cerr << fmt::format("Alias name '{}' clashes with a command name\n", alias_name);
return ParseCode::CommandLineError;
}
alias_definition = AliasDefinition{instance, command, working_directory};
return ParseCode::Ok;
}
| 4,954
|
C++
|
.cpp
| 127
| 33.322835
| 118
| 0.669656
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,791
|
mount.cpp
|
canonical_multipass/src/client/cli/cmd/mount.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mount.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/client_platform.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <QDir>
#include <QFileInfo>
#include <QRegularExpression>
namespace mp = multipass;
namespace mcp = multipass::cli::platform;
namespace mpl = multipass::logging;
namespace cmd = multipass::cmd;
namespace
{
constexpr auto category = "mount cmd";
const QString default_mount_type{"classic"};
const QString native_mount_type{"native"};
auto convert_id_for(const QString& id_string)
{
bool ok;
auto id = id_string.toUInt(&ok);
if (!ok)
throw std::runtime_error(id_string.toStdString() + " is an invalid id");
return id;
}
auto checked_mount_type(const QString& type)
{
if (type == default_mount_type)
return mp::MountRequest_MountType_CLASSIC;
if (type == native_mount_type)
return mp::MountRequest_MountType_NATIVE;
throw mp::ValidationException{fmt::format("Bad mount type '{}' specified, please use '{}' or '{}'", type,
default_mount_type, native_mount_type)};
}
} // namespace
mp::ReturnCode cmd::Mount::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
mp::AnimatedSpinner spinner{cout};
auto on_success = [&spinner](mp::MountReply& reply) {
spinner.stop();
return ReturnCode::Ok;
};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status);
};
auto streaming_callback = make_iterative_spinner_callback<MountRequest, MountReply>(spinner, *term);
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::mount, request, on_success, on_failure, streaming_callback);
}
std::string cmd::Mount::name() const { return "mount"; }
QString cmd::Mount::short_help() const
{
return QStringLiteral("Mount a local directory in the instance");
}
QString cmd::Mount::description() const
{
return QStringLiteral("Mount a local directory inside the instance. If the instance is\n"
"not currently running, the directory will be mounted\n"
"automatically on next boot.");
}
mp::ParseCode cmd::Mount::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("source", "Path of the local directory to mount", "<source>");
parser->addPositionalArgument("target",
"Target mount points, in <name>[:<path>] format, where <name> "
"is an instance name, and optional <path> is the mount point. "
"If omitted, the mount point will be the same as the source's "
"absolute path",
"<target> [<target> ...]");
QCommandLineOption gid_mappings({"g", "gid-map"},
"A mapping of group IDs for use in the mount. File and folder ownership will be "
"mapped from <host> to <instance> inside the instance. Can be used multiple times. "
"Mappings can only be specified as a one-to-one relationship.",
"host>:<instance");
QCommandLineOption uid_mappings({"u", "uid-map"},
"A mapping of user IDs for use in the mount. File and folder ownership will be "
"mapped from <host> to <instance> inside the instance. Can be used multiple times. "
"Mappings can only be specified as a one-to-one relationship.",
"host>:<instance");
QCommandLineOption mount_type_option({"t", "type"},
"Specify the type of mount to use.\n"
"Classic mounts use technology built into Multipass.\n"
"Native mounts use hypervisor and/or platform specific mounts.\n"
"Valid types are: \'classic\' (default) and \'native\'",
"type", default_mount_type);
parser->addOptions({gid_mappings, uid_mappings, mount_type_option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
if (parser->positionalArguments().count() < 2)
{
cerr << "Not enough arguments given\n";
return ParseCode::CommandLineError;
}
QString source_path(parser->positionalArguments().at(0));
// Validate source directory of client side mounts
QFileInfo source_dir(source_path);
if (!source_dir.exists())
{
cerr << "Source path \"" << source_path.toStdString() << "\" does not exist\n";
return ParseCode::CommandLineError;
}
if (!source_dir.isDir())
{
cerr << "Source path \"" << source_path.toStdString() << "\" is not a directory\n";
return ParseCode::CommandLineError;
}
if (!source_dir.isReadable())
{
cerr << "Source path \"" << source_path.toStdString() << "\" is not readable\n";
return ParseCode::CommandLineError;
}
source_path = QDir(source_path).absolutePath();
request.set_source_path(source_path.toStdString());
request.clear_target_paths();
for (auto i = 1; i < parser->positionalArguments().count(); ++i)
{
auto argument = parser->positionalArguments().at(i);
auto instance_name = argument.section(':', 0, 0, QString::SectionSkipEmpty);
auto target_path = argument.section(':', 1, -1, QString::SectionSkipEmpty);
auto entry = request.add_target_paths();
entry->set_instance_name(instance_name.toStdString());
entry->set_target_path(target_path.toStdString());
}
QRegularExpression map_matcher("^([0-9]+[:][0-9]+)$");
request.clear_mount_maps();
auto mount_maps = request.mutable_mount_maps();
if (parser->isSet(uid_mappings))
{
auto uid_maps = parser->values(uid_mappings);
for (const auto& map : uid_maps)
{
if (!map_matcher.match(map).hasMatch())
{
cerr << "Invalid UID map given: " << map.toStdString() << "\n";
return ParseCode::CommandLineError;
}
auto parsed_map = map.split(":");
try
{
auto host_uid = convert_id_for(parsed_map.at(0));
auto instance_uid = convert_id_for(parsed_map.at(1));
auto uid_pair = mount_maps->add_uid_mappings();
uid_pair->set_host_id(host_uid);
uid_pair->set_instance_id(instance_uid);
}
catch (const std::exception& e)
{
cerr << e.what() << "\n";
return ParseCode::CommandLineError;
}
}
}
else
{
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): adding default uid mapping", __FILE__, __LINE__, __FUNCTION__));
auto uid_pair = mount_maps->add_uid_mappings();
uid_pair->set_host_id(mcp::getuid());
uid_pair->set_instance_id(mp::default_id);
}
if (parser->isSet(gid_mappings))
{
auto gid_maps = parser->values(gid_mappings);
for (const auto& map : gid_maps)
{
if (!map_matcher.match(map).hasMatch())
{
cerr << "Invalid GID map given: " << map.toStdString() << "\n";
return ParseCode::CommandLineError;
}
auto parsed_map = map.split(":");
try
{
auto host_gid = convert_id_for(parsed_map.at(0));
auto instance_gid = convert_id_for(parsed_map.at(1));
auto gid_pair = mount_maps->add_gid_mappings();
gid_pair->set_host_id(host_gid);
gid_pair->set_instance_id(instance_gid);
}
catch (const std::exception& e)
{
cerr << e.what() << "\n";
return ParseCode::CommandLineError;
}
}
}
else
{
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): adding default gid mapping", __FILE__, __LINE__, __FUNCTION__));
auto gid_pair = mount_maps->add_gid_mappings();
gid_pair->set_host_id(mcp::getgid());
gid_pair->set_instance_id(mp::default_id);
}
try
{
request.set_mount_type(checked_mount_type(parser->value(mount_type_option).toLower()));
}
catch (mp::ValidationException& e)
{
cerr << "error: " << e.what() << "\n";
return ParseCode::CommandLineError;
}
return ParseCode::Ok;
}
| 9,777
|
C++
|
.cpp
| 232
| 32.469828
| 120
| 0.584834
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,792
|
transfer.cpp
|
canonical_multipass/src/client/cli/cmd/transfer.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "transfer.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/client_platform.h>
#include <multipass/file_ops.h>
#include <multipass/ssh/sftp_utils.h>
#include <fmt/std.h>
#include <QRegularExpression>
namespace mp = multipass;
namespace cmd = multipass::cmd;
namespace mcp = multipass::cli::platform;
namespace fs = mp::fs;
namespace
{
constexpr char streaming_symbol{'-'};
} // namespace
mp::ReturnCode cmd::Transfer::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](mp::SSHInfoReply& reply) {
auto success = true;
for (const auto& [instance_name, ssh_info] : reply.ssh_info())
{
try
{
auto sftp_client = MP_SFTPUTILS.make_SFTPClient(ssh_info.host(), ssh_info.port(), ssh_info.username(),
ssh_info.priv_key_base64());
if (const auto args = std::get_if<InstanceSourcesLocalTarget>(&arguments); args)
{
auto& [sources, target] = *args;
std::error_code err;
if (sources.size() > 1 && !MP_FILEOPS.is_directory(target, err) && !err)
throw std::runtime_error{fmt::format("Target {:?} is not a directory", target)};
else if (err)
throw std::runtime_error{fmt::format("Cannot access {:?}: {}", target, err.message())};
for (auto [s, s_end] = sources.equal_range(instance_name); s != s_end; ++s)
success &= sftp_client->pull(s->second, target, flags);
}
if (const auto args = std::get_if<LocalSourcesInstanceTarget>(&arguments); args)
{
auto& [sources, target] = *args;
if (sources.size() > 1 && !sftp_client->is_remote_dir(target))
throw std::runtime_error{fmt::format("Target {:?} is not a directory", target)};
for (const auto& source : sources)
success &= sftp_client->push(source, target, flags);
}
if (const auto args = std::get_if<FromCin>(&arguments); args)
sftp_client->from_cin(term->cin(), args->target, flags.testFlag(SFTPClient::Flag::MakeParent));
if (const auto args = std::get_if<ToCout>(&arguments); args)
sftp_client->to_cout(args->source, term->cout());
}
catch (const std::exception& e)
{
term->cerr() << e.what() << "\n";
success = false;
}
}
return success ? ReturnCode::Ok : ReturnCode::CommandFail;
};
auto on_failure = [this](grpc::Status& status) {
return standard_failure_handler_for(name(), term->cerr(), status);
};
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::ssh_info, request, on_success, on_failure);
}
std::string cmd::Transfer::name() const
{
return "transfer";
}
std::vector<std::string> cmd::Transfer::aliases() const
{
return {name(), "copy-files"};
}
QString cmd::Transfer::short_help() const
{
return QStringLiteral("Transfer files between the host and instances");
}
QString cmd::Transfer::description() const
{
return QStringLiteral("Copy files and directories between the host and instances.");
}
mp::ParseCode cmd::Transfer::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("source",
"One or more paths to transfer, prefixed with <name:> "
"for paths inside the instance, or '-' for stdin",
"<source> [<source> ...]");
parser->addPositionalArgument("destination",
"The destination path, prefixed with <name:> for "
"a path inside the instance, or '-' for stdout",
"<destination>");
parser->addOption({{"r", "recursive"}, "Recursively copy entire directories"});
parser->addOption({{"p", "parents"}, "Make parent directories as needed"});
if (auto status = parser->commandParse(this); status != ParseCode::Ok)
return status;
flags.setFlag(SFTPClient::Flag::Recursive, parser->isSet("r"));
flags.setFlag(SFTPClient::Flag::MakeParent, parser->isSet("p"));
auto positionalArgs = parser->positionalArguments();
if (positionalArgs.size() < 2)
{
term->cerr() << "Not enough arguments given\n";
return ParseCode::CommandLineError;
}
auto split_args = args_to_instance_and_path(positionalArgs);
auto split_target = std::move(split_args.back());
split_args.pop_back();
auto& split_sources = split_args;
const auto full_target = positionalArgs.takeLast();
const auto& full_sources = positionalArgs;
if (const auto ret_opt = parse_streaming(full_sources, full_target, split_sources, split_target); ret_opt)
return ret_opt.value();
return parse_non_streaming(split_sources, split_target);
}
std::vector<std::pair<std::string, fs::path>> cmd::Transfer::args_to_instance_and_path(const QStringList& args)
{
std::vector<std::pair<std::string, fs::path>> instance_entry_args;
instance_entry_args.reserve(args.size());
for (const auto& entry : args)
{
// this is needed so that Windows absolute paths are not split at the colon following the drive letter
if (QRegularExpression{R"(^[A-Za-z]:\\.*)"}.match(entry).hasMatch())
{
instance_entry_args.emplace_back("", entry.toStdString());
continue;
}
const auto source_components = entry.split(':');
const auto instance_name = source_components.size() == 1 ? "" : source_components.first().toStdString();
const auto file_path = source_components.size() == 1 ? source_components.first() : entry.section(':', 1);
if (!instance_name.empty())
request.add_instance_name()->append(instance_name);
instance_entry_args.emplace_back(instance_name, file_path.isEmpty() ? "." : file_path.toStdString());
}
return instance_entry_args;
}
std::optional<mp::ParseCode>
multipass::cmd::Transfer::parse_streaming(const QStringList& full_sources, const QString& full_target,
std::vector<std::pair<std::string, fs::path>> split_sources,
std::pair<std::string, fs::path> split_target)
{
const auto source_streaming = std::count(full_sources.begin(), full_sources.end(), streaming_symbol);
const auto target_streaming = full_target == streaming_symbol;
if ((target_streaming && source_streaming) || source_streaming > 1)
{
term->cerr() << fmt::format("Only one '{}' allowed\n", streaming_symbol);
return ParseCode::CommandLineError;
}
if ((target_streaming || source_streaming) && full_sources.size() > 1)
{
term->cerr() << fmt::format("Only two arguments allowed when using '{}'\n", streaming_symbol);
return ParseCode::CommandLineError;
}
if (target_streaming)
{
if (split_sources.front().first.empty())
{
term->cerr() << "Source must be from inside an instance\n";
return ParseCode::CommandLineError;
}
arguments = ToCout{std::move(split_sources.front().second)};
return ParseCode::Ok;
}
if (source_streaming)
{
if (split_target.first.empty())
{
term->cerr() << "Target must be inside an instance\n";
return ParseCode::CommandLineError;
}
arguments = FromCin{std::move(split_target).second};
return ParseCode::Ok;
}
return std::nullopt;
}
mp::ParseCode cmd::Transfer::parse_non_streaming(std::vector<std::pair<std::string, fs::path>>& split_sources,
std::pair<std::string, fs::path>& split_target)
{
if (split_target.first.empty())
{
if (request.instance_name_size() == (int)split_sources.size())
{
arguments = InstanceSourcesLocalTarget{{split_sources.begin(), split_sources.end()},
std::move(split_target.second)};
return ParseCode::Ok;
}
term->cerr() << (request.instance_name_size()
? "All sources must be from inside an instance\n"
: "An instance name is needed for either source or destination\n");
return ParseCode::CommandLineError;
}
if (request.instance_name_size() > 1)
{
term->cerr() << "Cannot specify an instance name for both source and destination\n";
return ParseCode::CommandLineError;
}
std::vector<fs::path> source_paths;
source_paths.reserve(split_sources.size());
std::transform(split_sources.begin(), split_sources.end(), std::back_inserter(source_paths),
[](auto& item) { return std::move(item.second); });
arguments = LocalSourcesInstanceTarget{std::move(source_paths), std::move(split_target.second)};
return ParseCode::Ok;
}
| 10,062
|
C++
|
.cpp
| 221
| 36.167421
| 118
| 0.604224
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,793
|
suspend.cpp
|
canonical_multipass/src/client/cli/cmd/suspend.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "suspend.h"
#include "common_cli.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h>
#include <multipass/settings/settings.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Suspend::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [](mp::SuspendReply& reply) { return ReturnCode::Ok; };
AnimatedSpinner spinner{cout};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status);
};
spinner.start(instance_action_message_for(request.instance_names(), "Suspending "));
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::suspend, request, on_success, on_failure,
make_logging_spinner_callback<SuspendRequest, SuspendReply>(spinner, cerr));
}
std::string cmd::Suspend::name() const
{
return "suspend";
}
QString cmd::Suspend::short_help() const
{
return QStringLiteral("Suspend running instances");
}
QString cmd::Suspend::description() const
{
return QStringLiteral("Suspend the named instances, if running. Exits with\n"
"return code 0 if successful.");
}
mp::ParseCode cmd::Suspend::parse_args(mp::ArgParser* parser)
{
const auto petenv_name = MP_SETTINGS.get(petenv_key);
const auto& [description, syntax] =
petenv_name.isEmpty()
? std::make_pair(QString{"Names of instances to suspend."}, QString{"<name> [<name> ...]"})
: std::make_pair(
QString{
"Names of instances to suspend. If omitted, and without the --all option, '%1' will be assumed."}
.arg(petenv_name),
QString{"[<name> ...]"});
parser->addPositionalArgument("name", description, syntax);
QCommandLineOption all_option("all", "Suspend all instances");
parser->addOptions({all_option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr, /*allow_empty=*/!petenv_name.isEmpty());
if (parse_code != ParseCode::Ok)
{
if (petenv_name.isEmpty() && parser->positionalArguments().isEmpty())
fmt::print(cerr, "Note: the primary instance is disabled.\n");
return parse_code;
}
request.mutable_instance_names()->CopyFrom(add_instance_names(parser, /*default_name=*/petenv_name.toStdString()));
return status;
}
| 3,364
|
C++
|
.cpp
| 83
| 35.180723
| 119
| 0.679546
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,794
|
set.cpp
|
canonical_multipass/src/client/cli/cmd/set.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "set.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/prompters.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cli_exceptions.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/platform.h> // temporary
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/settings/settings.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Set::run(mp::ArgParser* parser)
{
auto parse_code = parse_args(parser);
auto ret = parser->returnCodeFrom(parse_code);
if (parse_code == ParseCode::Ok)
{
try
{
if (ret == ReturnCode::Ok)
MP_SETTINGS.set(key, val);
}
catch (const SettingsException& e)
{
cerr << e.what() << "\n";
ret = return_code_from(e);
}
}
return ret;
}
std::string cmd::Set::name() const
{
return "set";
}
QString cmd::Set::short_help() const
{
return QStringLiteral("Set a configuration setting");
}
QString cmd::Set::description() const
{
auto desc = QStringLiteral("Set, to the given value, the configuration setting corresponding to the given key.");
return desc + "\n\n" + describe_common_settings_keys();
}
mp::ParseCode cmd::Set::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("keyval",
"A key, or a key-value pair. The key specifies a path to the setting to configure. "
"The value is its intended value. If only the key is given, "
"the value will be prompted for.",
"<key>[=<value>]");
auto status = parser->commandParse(this);
if (status == ParseCode::Ok)
{
const auto args = parser->positionalArguments();
if (args.size() != 1)
{
cerr << "Need exactly one key-value pair (in <key>=<value> form).\n";
status = ParseCode::CommandLineError;
}
else
{
const auto keyval = args.at(0).split('=', Qt::KeepEmptyParts);
if ((keyval.size() != 1 && keyval.size() != 2) || keyval[0].isEmpty())
{
cerr << "Bad key-value format.\n";
status = ParseCode::CommandLineError;
}
else if (keyval.size() == 2)
{
key = keyval.at(0);
val = keyval.at(1);
}
else
{
key = keyval.at(0);
status = checked_prompt(key);
}
}
}
return status;
}
mp::ParseCode cmd::Set::checked_prompt(const QString& key)
{
try
{
if (key == passphrase_key) // TODO integrate into setting handlers
{
mp::NewPassphrasePrompter prompter(term);
val = QString::fromStdString(prompter.prompt());
}
else
{
mp::PlainPrompter prompter(term);
val = QString::fromStdString(prompter.prompt(key.toStdString()));
}
return ParseCode::Ok;
}
catch (const mp::PromptException& e)
{
cerr << e.what() << std::endl;
return ParseCode::CommandLineError;
}
}
| 3,926
|
C++
|
.cpp
| 120
| 25.316667
| 118
| 0.595044
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,795
|
restore.cpp
|
canonical_multipass/src/client/cli/cmd/restore.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "restore.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/prompters.h>
#include <multipass/exceptions/cli_exceptions.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Restore::run(mp::ArgParser* parser)
{
if (auto ret = parse_args(parser); ret != ParseCode::Ok)
return parser->returnCodeFrom(ret);
AnimatedSpinner spinner{cout};
auto on_success = [this, &spinner](mp::RestoreReply& reply) {
spinner.stop();
fmt::print(cout, "Snapshot restored: {}.{}\n", request.instance(), request.snapshot());
return ReturnCode::Ok;
};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status);
};
using Client = grpc::ClientReaderWriterInterface<RestoreRequest, RestoreReply>;
auto streaming_callback = [this, &spinner](const mp::RestoreReply& reply, Client* client) {
if (!reply.log_line().empty())
spinner.print(cerr, reply.log_line());
if (const auto& msg = reply.reply_message(); !msg.empty())
{
spinner.stop();
spinner.start(msg);
}
if (reply.confirm_destructive())
{
spinner.stop();
RestoreRequest client_response;
if (term->is_live())
client_response.set_destructive(confirm_destruction(request.instance()));
else
throw std::runtime_error("Unable to query client for confirmation. Use '--destructive' to "
"automatically discard current machine state.");
client->Write(client_response);
spinner.start();
}
};
return dispatch(&RpcMethod::restore, request, on_success, on_failure, streaming_callback);
}
std::string cmd::Restore::name() const
{
return "restore";
}
QString cmd::Restore::short_help() const
{
return QStringLiteral("Restore an instance from a snapshot");
}
QString cmd::Restore::description() const
{
return QStringLiteral("Restore an instance to the state of a previously taken snapshot.");
}
mp::ParseCode cmd::Restore::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("instance.snapshot",
"The instance to restore and snapshot to use, in <instance>.<snapshot> format, where "
"<instance> is the name of an instance, and <snapshot> is the name of a snapshot",
"<instance>.<snapshot>");
QCommandLineOption destructive({"d", "destructive"}, "Discard the current state of the instance");
parser->addOption(destructive);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
const auto positional_args = parser->positionalArguments();
const auto num_args = positional_args.count();
if (num_args < 1)
{
cerr << "Need the name of an instance and snapshot to restore.\n";
return ParseCode::CommandLineError;
}
if (num_args > 1)
{
cerr << "Too many arguments supplied.\n";
return ParseCode::CommandLineError;
}
const auto tokens = parser->positionalArguments().at(0).split('.');
if (tokens.size() != 2 || tokens[0].isEmpty() || tokens[1].isEmpty())
{
cerr << "Invalid format. Please specify the instance to restore and snapshot to use in the form "
"<instance>.<snapshot>.\n";
return ParseCode::CommandLineError;
}
request.set_instance(tokens[0].toStdString());
request.set_snapshot(tokens[1].toStdString());
request.set_destructive(parser->isSet(destructive));
request.set_verbosity_level(parser->verbosityLevel());
return ParseCode::Ok;
}
bool cmd::Restore::confirm_destruction(const std::string& instance_name)
{
static constexpr auto prompt_text =
"Do you want to take a snapshot of {} before discarding its current state? (Yes/no)";
static constexpr auto invalid_input = "Please answer Yes/no";
mp::PlainPrompter prompter(term);
auto answer = prompter.prompt(fmt::format(prompt_text, instance_name));
while (!answer.empty() && !std::regex_match(answer, mp::client::yes_answer) &&
!std::regex_match(answer, mp::client::no_answer))
answer = prompter.prompt(invalid_input);
return std::regex_match(answer, mp::client::no_answer);
}
| 5,202
|
C++
|
.cpp
| 123
| 35.666667
| 120
| 0.661718
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,796
|
animated_spinner.cpp
|
canonical_multipass/src/client/cli/cmd/animated_spinner.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "animated_spinner.h"
#include <iomanip>
#include <iostream>
namespace mp = multipass;
namespace
{
void clear_line(std::ostream& out)
{
out << "\x1B[2K\x1B[0A"; // Delete current line
out << "\x1B[0E" << std::flush; // Move cursor to leftmost position of current line
}
}
mp::AnimatedSpinner::AnimatedSpinner(std::ostream& cout) : spinner{'|', '/', '-', '\\'}, cout{cout}, running{false}
{
}
mp::AnimatedSpinner::~AnimatedSpinner()
{
stop();
}
void mp::AnimatedSpinner::start(const std::string& start_message)
{
std::unique_lock<decltype(mutex)> lock{mutex};
if (!running)
{
current_message = start_message;
running = true;
clear_line(cout);
cout << start_message << " " << std::flush;
t = std::thread(&AnimatedSpinner::draw, this);
}
}
void mp::AnimatedSpinner::start()
{
if (!current_message.empty())
start(current_message);
}
void mp::AnimatedSpinner::stop()
{
std::unique_lock<decltype(mutex)> lock{mutex};
if (running)
{
running = false;
cv.notify_one();
lock.unlock();
if (t.joinable())
t.join();
}
clear_line(cout);
}
void mp::AnimatedSpinner::print(std::ostream& stream, const std::string& message)
{
stop();
stream << message;
start();
}
void mp::AnimatedSpinner::draw()
{
std::unique_lock<decltype(mutex)> lock{mutex};
auto it = spinner.begin();
while (running)
{
if (++it == spinner.end())
it = spinner.begin();
cout << "\b" << *it << std::flush;
cv.wait_for(lock, std::chrono::milliseconds(100));
}
cout << "\b"
<< " " << std::flush;
}
| 2,327
|
C++
|
.cpp
| 84
| 23.702381
| 115
| 0.642152
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,797
|
info.cpp
|
canonical_multipass/src/client/cli/cmd/info.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "info.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Info::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](mp::InfoReply& reply) {
cout << chosen_formatter->format(reply);
if (term->is_live() && update_available(reply.update_info()))
cout << update_notice(reply.update_info());
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::info, request, on_success, on_failure);
}
std::string cmd::Info::name() const { return "info"; }
QString cmd::Info::short_help() const
{
return QStringLiteral("Display information about instances or snapshots");
}
QString cmd::Info::description() const
{
return short_help();
}
mp::ParseCode cmd::Info::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("instance/snapshot",
"Names of instances or snapshots to display information about",
"<instance>[.snapshot] [<instance>[.snapshot] ...]");
QCommandLineOption all_option(all_option_name, "Display info for all instances.");
all_option.setFlags(QCommandLineOption::HiddenFromHelp);
QCommandLineOption noRuntimeInfoOption(
"no-runtime-information",
"Retrieve from the daemon only the information obtained without running commands on the instance.");
noRuntimeInfoOption.setFlags(QCommandLineOption::HiddenFromHelp);
QCommandLineOption snapshots_option{"snapshots",
"Display detailed information about the snapshots of specified instances. This "
"option has no effect on snapshot arguments. Omit instance/snapshot arguments "
"to obtain detailed information on all the snapshots of all instances."};
QCommandLineOption format_option(
format_option_name,
"Output info in the requested format.\nValid formats are: table (default), json, csv and yaml.",
format_option_name,
"table");
parser->addOptions({all_option, noRuntimeInfoOption, snapshots_option, format_option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
status = handle_format_option(parser, &chosen_formatter, cerr);
status = check_for_name_and_all_option_conflict(parser, cerr, true);
if (status != ParseCode::Ok)
return status;
if (parser->isSet(all_option_name))
cerr << "Warning: the `--all` flag for the `info` command is deprecated. Please use `info` with no positional "
"arguments for the same effect.\n";
bool instance_found = false, snapshot_found = false;
for (const auto& item : add_instance_and_snapshot_names(parser))
{
if (!item.has_snapshot_name())
instance_found = true;
else
snapshot_found = true;
request.add_instance_snapshot_pairs()->CopyFrom(item);
}
request.set_no_runtime_information(parser->isSet(noRuntimeInfoOption));
const auto& snapshots_only = parser->isSet(snapshots_option);
request.set_snapshots(snapshots_only);
if (instance_found && snapshot_found && parser->value(format_option_name) == "csv" && !snapshots_only)
{
cerr << "Mixed snapshot and instance arguments are not supported with CSV format\n";
return ParseCode::CommandLineError;
}
return status;
}
| 4,481
|
C++
|
.cpp
| 98
| 38.928571
| 120
| 0.679211
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,798
|
restart.cpp
|
canonical_multipass/src/client/cli/cmd/restart.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "restart.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/settings/settings.h>
#include <multipass/timer.h>
#include <chrono>
#include <cstdlib>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Restart::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
return parser->returnCodeFrom(ret);
AnimatedSpinner spinner{cout};
auto on_success = [this, &spinner](mp::RestartReply& reply) {
spinner.stop();
if (term->is_live() && update_available(reply.update_info()))
cout << update_notice(reply.update_info());
return ReturnCode::Ok;
};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status);
};
request.set_verbosity_level(parser->verbosityLevel());
std::unique_ptr<multipass::utils::Timer> timer;
if (parser->isSet("timeout"))
{
timer = cmd::make_timer(parser->value("timeout").toInt(), &spinner, cerr,
"Timed out waiting for instance to restart.");
timer->start();
}
ReturnCode return_code;
auto streaming_callback = make_iterative_spinner_callback<RestartRequest, RestartReply>(spinner, *term);
do
{
spinner.start(instance_action_message_for(request.instance_names(), "Restarting "));
} while ((return_code = dispatch(&RpcMethod::restart, request, on_success, on_failure, streaming_callback)) ==
ReturnCode::Retry);
return return_code;
}
std::string cmd::Restart::name() const
{
return "restart";
}
QString cmd::Restart::short_help() const
{
return QStringLiteral("Restart instances");
}
QString cmd::Restart::description() const
{
return QStringLiteral("Restart the named instances. Exits with return\n"
"code 0 when the instances restart, or with an\n"
"error code if any fail to restart.");
}
mp::ParseCode cmd::Restart::parse_args(mp::ArgParser* parser)
{
const auto petenv_name = MP_SETTINGS.get(petenv_key);
const auto& [description, syntax] =
petenv_name.isEmpty()
? std::make_pair(QString{"Names of instances to restart."}, QString{"<name> [<name> ...]"})
: std::make_pair(
QString{
"Names of instances to restart. If omitted, and without the --all option, '%1' will be assumed."}
.arg(petenv_name),
QString{"[<name> ...]"});
parser->addPositionalArgument("name", description, syntax);
QCommandLineOption all_option(all_option_name, "Restart all instances");
parser->addOption(all_option);
mp::cmd::add_timeout(parser);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
try
{
request.set_timeout(mp::cmd::parse_timeout(parser));
}
catch (const mp::ValidationException& e)
{
cerr << "error: " << e.what() << std::endl;
return ParseCode::CommandLineError;
}
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr, /*allow_empty=*/!petenv_name.isEmpty());
if (parse_code != ParseCode::Ok)
{
if (petenv_name.isEmpty() && parser->positionalArguments().isEmpty())
fmt::print(cerr, "Note: the primary instance is disabled.\n");
return parse_code;
}
request.mutable_instance_names()->CopyFrom(add_instance_names(parser, /*default_name=*/petenv_name.toStdString()));
return status;
}
| 4,433
|
C++
|
.cpp
| 113
| 33.274336
| 119
| 0.662162
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,799
|
find.cpp
|
canonical_multipass/src/client/cli/cmd/find.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "find.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Find::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](FindReply& reply) {
cout << chosen_formatter->format(reply);
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::find, request, on_success, on_failure);
}
std::string cmd::Find::name() const
{
return "find";
}
QString cmd::Find::short_help() const
{
return QStringLiteral("Display available images to create instances from");
}
QString cmd::Find::description() const
{
return QStringLiteral("Lists available images matching <string> for creating instances from.\n"
"With no search string, lists all aliases for supported Ubuntu releases.");
}
mp::ParseCode cmd::Find::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("string",
"An optional value to search for in [<remote:>]<string> format, where "
"<remote> can be either ‘release’ or ‘daily’. If <remote> is omitted, "
"it will search ‘release‘ first, and if no matches are found, it will "
"then search ‘daily‘. <string> can be a partial image hash or an "
"Ubuntu release version, codename or alias.",
"[<remote:>][<string>]");
QCommandLineOption unsupportedOption("show-unsupported", "Show unsupported cloud images as well");
QCommandLineOption imagesOnlyOption("only-images", "Show only images");
QCommandLineOption blueprintsOnlyOption("only-blueprints", "Show only blueprints");
QCommandLineOption formatOption(
"format", "Output list in the requested format.\nValid formats are: table (default), json, csv and yaml",
"format", "table");
const QCommandLineOption force_manifest_network_download("force-update",
"Force the image information to update from the network");
parser->addOptions(
{unsupportedOption, imagesOnlyOption, blueprintsOnlyOption, formatOption, force_manifest_network_download});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->isSet(imagesOnlyOption) && parser->isSet(blueprintsOnlyOption))
{
cerr << "Specify one of \"--only-images\", \"--only-blueprints\" or omit to fetch both\n";
return ParseCode::CommandLineError;
}
if (parser->isSet(force_manifest_network_download) && parser->isSet(blueprintsOnlyOption))
{
cerr << "Force updating blueprints is not currently supported\n";
return ParseCode::CommandLineError;
}
request.set_show_images(!parser->isSet(blueprintsOnlyOption));
request.set_show_blueprints(!parser->isSet(imagesOnlyOption));
if (parser->positionalArguments().count() > 1)
{
cerr << "Wrong number of arguments\n";
return ParseCode::CommandLineError;
}
else if (parser->positionalArguments().count() == 1)
{
auto search_string = parser->positionalArguments().first();
auto colon_count = search_string.count(':');
if (colon_count > 1)
{
cerr << "Invalid remote and search string supplied\n";
return ParseCode::CommandLineError;
}
else if (colon_count == 1)
{
request.set_remote_name(search_string.section(':', 0, 0).toStdString());
request.set_search_string(search_string.section(':', 1).toStdString());
}
else
{
request.set_search_string(search_string.toStdString());
}
}
request.set_allow_unsupported(parser->isSet(unsupportedOption));
request.set_force_manifest_network_download(parser->isSet(force_manifest_network_download));
status = handle_format_option(parser, &chosen_formatter, cerr);
return status;
}
| 5,070
|
C++
|
.cpp
| 115
| 36.478261
| 119
| 0.657718
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,800
|
delete.cpp
|
canonical_multipass/src/client/cli/cmd/delete.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "delete.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/prompters.h>
#include <multipass/platform.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
namespace
{
constexpr auto snapshot_purge_notice_msg = "Snapshots can only be purged (after deletion, they cannot be recovered)";
}
mp::ReturnCode cmd::Delete::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](mp::DeleteReply& reply) {
auto size = reply.purged_instances_size();
for (auto i = 0; i < size; ++i)
{
const auto purged_instance = reply.purged_instances(i);
const auto removed_aliases = aliases.remove_aliases_for_instance(purged_instance);
for (const auto& removed_alias : removed_aliases)
{
const auto& [removal_context, removed_alias_name] = removed_alias;
try
{
MP_PLATFORM.remove_alias_script(removal_context + "." + removed_alias_name);
if (!aliases.exists_alias(removed_alias_name))
{
MP_PLATFORM.remove_alias_script(removed_alias_name);
}
}
catch (const std::runtime_error& e)
{
cerr << fmt::format("Warning: '{}' when removing alias script for {}.{}\n", e.what(),
removal_context, removed_alias_name);
}
}
}
return mp::ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) {
// grpc::StatusCode::FAILED_PRECONDITION matches mp::VMStateInvalidException
return status.error_code() == grpc::StatusCode::FAILED_PRECONDITION
? standard_failure_handler_for(name(), cerr, status, "Use --purge to forcefully delete it.")
: standard_failure_handler_for(name(), cerr, status);
};
using Client = grpc::ClientReaderWriterInterface<DeleteRequest, DeleteReply>;
auto streaming_callback = [this](const mp::DeleteReply& reply, Client* client) {
if (!reply.log_line().empty())
cerr << reply.log_line();
// TODO refactor with bridging and restore prompts
if (reply.confirm_snapshot_purging())
{
DeleteRequest client_response;
if (term->is_live())
client_response.set_purge_snapshots(confirm_snapshot_purge());
else
throw std::runtime_error{generate_snapshot_purge_msg()};
client->Write(client_response);
}
};
return dispatch(&RpcMethod::delet, request, on_success, on_failure, streaming_callback);
}
std::string cmd::Delete::name() const
{
return "delete";
}
QString cmd::Delete::short_help() const
{
return QStringLiteral("Delete instances and snapshots");
}
QString cmd::Delete::description() const
{
return QStringLiteral(
"Delete instances and snapshots. Instances can be purged immediately or later on,\n"
"with the \"purge\" command. Until they are purged, instances can be recovered\n"
"with the \"recover\" command. Snapshots cannot be recovered after deletion and must be purged at once.");
}
mp::ParseCode cmd::Delete::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("name",
"Names of instances and snapshots to delete",
"<instance>[.snapshot] [<instance>[.snapshot] ...]");
QCommandLineOption all_option(all_option_name, "Delete all instances and snapshots");
QCommandLineOption purge_option({"p", "purge"}, "Permanently delete specified instances and snapshots immediately");
parser->addOptions({all_option, purge_option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
status = check_for_name_and_all_option_conflict(parser, cerr);
if (status != ParseCode::Ok)
return status;
request.set_purge(parser->isSet(purge_option));
request.set_verbosity_level(parser->verbosityLevel());
status = parse_instances_snapshots(parser);
return status;
}
mp::ParseCode cmd::Delete::parse_instances_snapshots(mp::ArgParser* parser)
{
for (const auto& item : cmd::add_instance_and_snapshot_names(parser))
{
if (!item.has_snapshot_name())
instance_args.append(fmt::format("{} ", item.instance_name()));
else
snapshot_args.append(fmt::format("{}.{} ", item.instance_name(), item.snapshot_name()));
request.add_instance_snapshot_pairs()->CopyFrom(item);
}
return mp::ParseCode::Ok;
}
// TODO refactor with bridging and restore prompts
bool multipass::cmd::Delete::confirm_snapshot_purge() const
{
static constexpr auto prompt_text = "{}. Are you sure you want to continue? (Yes/no)";
static constexpr auto invalid_input = "Please answer Yes/no";
mp::PlainPrompter prompter{term};
auto answer = prompter.prompt(fmt::format(prompt_text, snapshot_purge_notice_msg));
while (!answer.empty() && !std::regex_match(answer, mp::client::yes_answer) &&
!std::regex_match(answer, mp::client::no_answer))
answer = prompter.prompt(invalid_input);
return std::regex_match(answer, mp::client::yes_answer);
}
std::string multipass::cmd::Delete::generate_snapshot_purge_msg() const
{
const auto no_purge_base_error_msg = fmt::format("{}. Unable to query client for confirmation. Please use the "
"`--purge` flag if that is what you want",
snapshot_purge_notice_msg);
if (!instance_args.empty())
return fmt::format("{}:\n\n\tmultipass delete --purge {}\n\nYou can use a separate command to delete "
"instances without purging them:\n\n\tmultipass delete {}\n",
no_purge_base_error_msg,
snapshot_args,
instance_args);
else
return fmt::format("{}.\n", no_purge_base_error_msg);
}
| 6,930
|
C++
|
.cpp
| 155
| 36.077419
| 120
| 0.630525
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,801
|
recover.cpp
|
canonical_multipass/src/client/cli/cmd/recover.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "recover.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Recover::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [](mp::RecoverReply& reply) {
return mp::ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::recover, request, on_success, on_failure);
}
std::string cmd::Recover::name() const { return "recover"; }
QString cmd::Recover::short_help() const
{
return QStringLiteral("Recover deleted instances");
}
QString cmd::Recover::description() const
{
return QStringLiteral("Recover deleted instances so they can be used again.");
}
mp::ParseCode cmd::Recover::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("name", "Names of instances to recover", "<name> [<name> ...]");
QCommandLineOption all_option(all_option_name, "Recover all deleted instances");
parser->addOption(all_option);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr);
if (parse_code != ParseCode::Ok)
return parse_code;
request.mutable_instance_names()->CopyFrom(add_instance_names(parser));
return status;
}
| 2,221
|
C++
|
.cpp
| 58
| 34.827586
| 114
| 0.71728
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,802
|
common_cli.cpp
|
canonical_multipass/src/client/cli/cmd/common_cli.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common_cli.h"
#include "animated_spinner.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/format_utils.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <QCommandLineOption>
#include <QString>
#include <chrono>
#include <fmt/ostream.h>
#include <sstream>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ParseCode cmd::check_for_name_and_all_option_conflict(const mp::ArgParser* parser, std::ostream& cerr,
bool allow_empty)
{
auto num_names = parser->positionalArguments().count();
if (num_names == 0 && !parser->isSet(all_option_name) && !allow_empty)
{
fmt::print(cerr, "Name argument or --all is required\n");
return ParseCode::CommandLineError;
}
if (num_names > 0 && parser->isSet(all_option_name))
{
fmt::print(cerr, "Cannot specify name{} when --all option set\n", num_names > 1 ? "s" : "");
return ParseCode::CommandLineError;
}
return ParseCode::Ok;
}
mp::InstanceNames cmd::add_instance_names(const mp::ArgParser* parser)
{
InstanceNames instance_names;
for (const auto& arg : parser->positionalArguments())
{
auto instance_name = instance_names.add_instance_name();
instance_name->append(arg.toStdString());
}
return instance_names;
}
mp::InstanceNames cmd::add_instance_names(const mp::ArgParser* parser, const std::string& default_name)
{
auto instance_names = add_instance_names(parser);
if (!instance_names.instance_name_size() && !parser->isSet(all_option_name))
instance_names.add_instance_name(default_name);
return instance_names;
}
std::vector<mp::InstanceSnapshotPair> cmd::add_instance_and_snapshot_names(const mp::ArgParser* parser)
{
std::vector<mp::InstanceSnapshotPair> instance_snapshot_names;
instance_snapshot_names.reserve(parser->positionalArguments().count());
for (const auto& arg : parser->positionalArguments())
{
mp::InstanceSnapshotPair inst_snap_name;
auto index = arg.indexOf('.');
inst_snap_name.set_instance_name(arg.left(index).toStdString());
if (index >= 0)
inst_snap_name.set_snapshot_name(arg.right(arg.length() - index - 1).toStdString());
instance_snapshot_names.push_back(inst_snap_name);
}
return instance_snapshot_names;
}
mp::ParseCode cmd::handle_format_option(const mp::ArgParser* parser, mp::Formatter** chosen_formatter,
std::ostream& cerr)
{
*chosen_formatter = mp::format::formatter_for(parser->value(format_option_name).toStdString());
if (*chosen_formatter == nullptr)
{
fmt::print(cerr, "Invalid format type given.\n");
return ParseCode::CommandLineError;
}
return ParseCode::Ok;
}
std::string cmd::instance_action_message_for(const mp::InstanceNames& instance_names, const std::string& action_name)
{
std::string message{action_name};
if (instance_names.instance_name().empty())
message.append("all instances");
else if (instance_names.instance_name().size() > 1)
message.append("requested instances");
else
message.append(instance_names.instance_name().Get(0));
return message;
}
mp::ReturnCode cmd::run_cmd(const QStringList& args, const mp::ArgParser* parser, std::ostream& cout,
std::ostream& cerr)
{
ArgParser aux_parser{args, parser->getCommands(), cout, cerr};
aux_parser.setVerbosityLevel(parser->verbosityLevel());
[[maybe_unused]] auto code = aux_parser.parse();
assert(code == mp::ParseCode::Ok);
return aux_parser.chosenCommand()->run(&aux_parser);
}
namespace
{
mp::ReturnCode ok2retry(mp::ReturnCode code)
{
return code == mp::ReturnCode::Ok ? mp::ReturnCode::Retry : code;
}
} // namespace
mp::ReturnCode cmd::run_cmd_and_retry(const QStringList& args, const mp::ArgParser* parser, std::ostream& cout,
std::ostream& cerr)
{
return ok2retry(run_cmd(args, parser, cout, cerr));
}
auto cmd::return_code_from(const mp::SettingsException& e) -> mp::ReturnCode
{
if (dynamic_cast<const InvalidSettingException*>(&e) || dynamic_cast<const UnrecognizedSettingException*>(&e))
return ReturnCode::CommandLineError;
return ReturnCode::CommandFail;
}
QString multipass::cmd::describe_common_settings_keys()
{
return std::accumulate(cbegin(mp::key_examples), cend(mp::key_examples),
QStringLiteral("Some common settings keys are:"),
[](const auto& a, const auto& b) { return a + "\n - " + b; }) +
"\n\nUse `" + mp::client_name +
" get --keys` to obtain the full list of available settings at any given time.";
}
void multipass::cmd::add_timeout(multipass::ArgParser* parser)
{
QCommandLineOption timeout_option(
"timeout",
QString("Maximum time, in seconds, to wait for the command to complete. "
"Note that some background operations may continue beyond that. "
"By default, instance startup and initialization is limited to "
"%1 minutes each.")
.arg(std::chrono::duration_cast<std::chrono::minutes>(multipass::default_timeout).count()),
"timeout");
parser->addOption(timeout_option);
}
int multipass::cmd::parse_timeout(const multipass::ArgParser* parser)
{
if (parser->isSet("timeout"))
{
bool ok;
const auto timeout = parser->value("timeout").toInt(&ok);
if (!ok || timeout <= 0)
throw mp::ValidationException("--timeout value has to be a positive integer");
return timeout;
}
return -1;
}
std::unique_ptr<multipass::utils::Timer> multipass::cmd::make_timer(int timeout, AnimatedSpinner* spinner,
std::ostream& cerr, const std::string& msg)
{
auto timer = std::make_unique<multipass::utils::Timer>(std::chrono::seconds(timeout), [spinner, &cerr, msg]() {
if (spinner)
spinner->stop();
cerr << msg << std::endl;
MP_UTILS.exit(mp::timeout_exit_code);
});
return timer;
}
| 6,972
|
C++
|
.cpp
| 170
| 34.817647
| 117
| 0.665386
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,803
|
aliases.cpp
|
canonical_multipass/src/client/cli/cmd/aliases.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
#include "aliases.h"
#include "common_cli.h"
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Aliases::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
cout << chosen_formatter->format(aliases);
return ReturnCode::Ok;
}
std::string cmd::Aliases::name() const
{
return "aliases";
}
QString cmd::Aliases::short_help() const
{
return QStringLiteral("List available aliases");
}
QString cmd::Aliases::description() const
{
return QStringLiteral("List available aliases");
}
mp::ParseCode cmd::Aliases::parse_args(mp::ArgParser* parser)
{
QCommandLineOption formatOption(
"format",
"Output list in the requested format. Valid formats are: table (default), json, csv and yaml. "
"The output working directory states whether the alias runs in the instance's default directory "
"or the alias running directory should try to be mapped to a mounted one.\n",
"format", "table");
parser->addOption(formatOption);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 0)
{
cerr << "This command takes no arguments\n";
return ParseCode::CommandLineError;
}
status = handle_format_option(parser, &chosen_formatter, cerr);
return status;
}
| 2,219
|
C++
|
.cpp
| 67
| 29.38806
| 105
| 0.711142
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,804
|
help.cpp
|
canonical_multipass/src/client/cli/cmd/help.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "help.h"
#include <multipass/cli/argparser.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Help::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
cmd::Command* cmd = parser->findCommand(command);
if (cmd == nullptr)
{
cerr << "Error: Unknown Command: '" << qUtf8Printable(command) << "'\n";
return ReturnCode::CommandLineError;
}
parser->forceCommandHelp();
cmd->run(parser);
return ReturnCode::Ok;
}
std::string cmd::Help::name() const { return "help"; }
QString cmd::Help::short_help() const
{
return QStringLiteral("Display help about a command");
}
QString cmd::Help::description() const
{
return QStringLiteral("Displays help for the given command.");
}
mp::ParseCode cmd::Help::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("command", "Name of command to display help for", "<command>");
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() == 0)
{
parser->forceGeneralHelp();
status = ParseCode::HelpRequested;
}
else if (parser->positionalArguments().count() > 1)
{
cerr << "Too many arguments given\n";
status = ParseCode::CommandLineError;
}
else
{
command = parser->positionalArguments().first();
}
return status;
}
| 2,173
|
C++
|
.cpp
| 70
| 26.971429
| 97
| 0.682319
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,805
|
stop.cpp
|
canonical_multipass/src/client/cli/cmd/stop.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "stop.h"
#include "common_cli.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h>
#include <multipass/settings/settings.h>
#include <multipass/utils.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Stop::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [](mp::StopReply& reply) {
return ReturnCode::Ok;
};
AnimatedSpinner spinner{cout};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
// grpc::StatusCode::FAILED_PRECONDITION matches mp::VMStateInvalidException
return status.error_code() == grpc::StatusCode::FAILED_PRECONDITION
? standard_failure_handler_for(name(), cerr, status, "Use --force to power it off.")
: standard_failure_handler_for(name(), cerr, status);
};
spinner.start(instance_action_message_for(request.instance_names(), "Stopping "));
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::stop, request, on_success, on_failure,
make_logging_spinner_callback<StopRequest, StopReply>(spinner, cerr));
}
std::string cmd::Stop::name() const { return "stop"; }
QString cmd::Stop::short_help() const
{
return QStringLiteral("Stop running instances");
}
QString cmd::Stop::description() const
{
return QStringLiteral("Stop the named instances. Exits with return code 0 \n"
"if successful.");
}
mp::ParseCode cmd::Stop::parse_args(mp::ArgParser* parser)
{
const auto petenv_name = MP_SETTINGS.get(petenv_key);
const auto& [description, syntax] =
petenv_name.isEmpty()
? std::make_pair(QString{"Names of instances to stop."}, QString{"<name> [<name> ...]"})
: std::make_pair(
QString{"Names of instances to stop. If omitted, and without the --all option, '%1' will be assumed."}
.arg(petenv_name),
QString{"[<name> ...]"});
parser->addPositionalArgument("name", description, syntax);
QCommandLineOption all_option(all_option_name, "Stop all instances");
QCommandLineOption time_option({"t", "time"}, "Time from now, in minutes, to delay shutdown of the instance",
"time", "0");
QCommandLineOption cancel_option({"c", "cancel"}, "Cancel a pending delayed shutdown");
QCommandLineOption force_option("force",
"Force the instance to shut down immediately. Warning: This could potentially "
"corrupt a running instance, so use with caution.");
parser->addOptions({all_option, time_option, cancel_option, force_option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr, /*allow_empty=*/!petenv_name.isEmpty());
if (parse_code != ParseCode::Ok)
{
if (petenv_name.isEmpty() && parser->positionalArguments().isEmpty())
fmt::print(cerr, "Note: the primary instance is disabled.\n");
return parse_code;
}
if (parser->isSet(time_option) && parser->isSet(cancel_option))
{
cerr << "Cannot set \'time\' and \'cancel\' options at the same time\n";
return ParseCode::CommandLineError;
}
if (parser->isSet(force_option) && (parser->isSet(time_option) || parser->isSet(cancel_option)))
{
cerr << "Cannot set \'force\' along with \'time\' or \'cancel\' options at the same time\n";
return ParseCode::CommandLineError;
}
request.set_force_stop(parser->isSet(force_option));
auto time = parser->value(time_option);
if (time.startsWith("+"))
{
time.remove(0, 1);
}
if (!mp::utils::has_only_digits(time.toStdString()))
{
cerr << "Time must be in digit form\n";
return ParseCode::CommandLineError;
}
request.set_time_minutes(time.toInt());
if (parser->isSet(cancel_option))
{
request.set_cancel_shutdown(true);
}
request.mutable_instance_names()->CopyFrom(add_instance_names(parser, /*default_name=*/petenv_name.toStdString()));
return status;
}
| 5,085
|
C++
|
.cpp
| 117
| 36.846154
| 120
| 0.655801
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,806
|
umount.cpp
|
canonical_multipass/src/client/cli/cmd/umount.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "umount.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Umount::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [](mp::UmountReply& reply) {
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::umount, request, on_success, on_failure);
}
std::string cmd::Umount::name() const { return "umount"; }
std::vector<std::string> cmd::Umount::aliases() const
{
return {name(), "unmount"};
}
QString cmd::Umount::short_help() const
{
return QStringLiteral("Unmount a directory from an instance");
}
QString cmd::Umount::description() const
{
return QStringLiteral("Unmount a directory from an instance.");
}
mp::ParseCode cmd::Umount::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("mount", "Mount points, in <name>[:<path>] format, where <name> "
"are instance names, and optional <path> are mount points. "
"If omitted, all mounts will be removed from the named instances.",
"<mount> [<mount> ...]");
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() < 1)
{
cerr << "Not enough arguments given\n";
status = ParseCode::CommandLineError;
}
else
{
for (const auto& arg : parser->positionalArguments())
{
auto parsed_target = arg.split(":");
auto entry = request.add_target_paths();
entry->set_instance_name(parsed_target.at(0).toStdString());
if (parsed_target.count() == 2)
{
entry->set_target_path(parsed_target.at(1).toStdString());
}
}
}
return status;
}
| 2,830
|
C++
|
.cpp
| 79
| 29.746835
| 114
| 0.64142
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,807
|
shell.cpp
|
canonical_multipass/src/client/cli/cmd/shell.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "shell.h"
#include "common_cli.h"
#include "animated_spinner.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/settings/settings.h>
#include <multipass/ssh/ssh_client.h>
#include <multipass/timer.h>
#include <chrono>
#include <cstdlib>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Shell::run(mp::ArgParser* parser)
{
petenv_name = MP_SETTINGS.get(petenv_key);
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
std::unique_ptr<mp::utils::Timer> timer;
if (parser->isSet("timeout"))
{
timer = cmd::make_timer(parser->value("timeout").toInt(),
nullptr,
cerr,
"Timed out waiting for instance to start.");
timer->start();
}
// We can assume the first array entry since `shell` only uses one instance
// at a time
auto instance_name = request.instance_name()[0];
auto on_success = [this, &timer](mp::SSHInfoReply& reply) {
if (timer)
timer->stop();
// TODO: mainly for testing - need a better way to test parsing
if (reply.ssh_info().empty())
return ReturnCode::Ok;
// TODO: this should setup a reader that continuously prints out
// streaming replies from the server corresponding to stdout/stderr streams
const auto& ssh_info = reply.ssh_info().begin()->second;
const auto& host = ssh_info.host();
const auto& port = ssh_info.port();
const auto& username = ssh_info.username();
const auto& priv_key_blob = ssh_info.priv_key_base64();
try
{
auto console_creator = [this](auto channel) { return Console::make_console(channel, term); };
mp::SSHClient ssh_client{host, port, username, priv_key_blob, console_creator};
ssh_client.connect();
}
catch (const std::exception& e)
{
cerr << "shell failed: " << e.what() << "\n";
return ReturnCode::CommandFail;
}
return ReturnCode::Ok;
};
auto on_failure = [this, &instance_name, parser](grpc::Status& status) {
QStringList retry_args{};
if (status.error_code() == grpc::StatusCode::NOT_FOUND && instance_name == petenv_name.toStdString())
retry_args.append({"multipass", "launch", "--name", petenv_name});
else if (status.error_code() == grpc::StatusCode::ABORTED)
retry_args.append({"multipass", "start", QString::fromStdString(instance_name)});
else
return standard_failure_handler_for(name(), cerr, status);
if (parser->isSet("timeout"))
retry_args.append({"--timeout", parser->value("timeout")});
return run_cmd_and_retry(retry_args, parser, cout, cerr);
};
request.set_verbosity_level(parser->verbosityLevel());
ReturnCode return_code;
while ((return_code = dispatch(&RpcMethod::ssh_info, request, on_success, on_failure)) == ReturnCode::Retry)
;
return return_code;
}
std::string cmd::Shell::name() const
{
return "shell";
}
std::vector<std::string> cmd::Shell::aliases() const
{
return {name(), "sh", "connect"};
}
QString cmd::Shell::short_help() const
{
return QStringLiteral("Open a shell on an instance");
}
QString cmd::Shell::description() const
{
return QStringLiteral(
"Open a shell prompt on the instance. If the instance is not running, it will be started automatically.");
}
mp::ParseCode cmd::Shell::parse_args(mp::ArgParser* parser)
{
const auto& [description, syntax] =
petenv_name.isEmpty()
? std::make_pair(QString{"Name of instance to open a shell on."}, QString{"<name>"})
: std::make_pair(QString{"Name of the instance to open a shell on. If omitted, '%1' (the configured "
"primary instance name) will be assumed. If the instance is not running, an "
"attempt is made to start it (see `start` for more info)."}
.arg(petenv_name),
QString{"[<name>]"});
parser->addPositionalArgument("name", description, syntax);
mp::cmd::add_timeout(parser);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
try
{
mp::cmd::parse_timeout(parser);
}
catch (const mp::ValidationException& e)
{
cerr << "error: " << e.what() << std::endl;
return ParseCode::CommandLineError;
}
const auto pos_args = parser->positionalArguments();
const auto num_args = pos_args.count();
if (num_args > 1)
{
cerr << "Too many arguments given\n";
status = ParseCode::CommandLineError;
}
else if (auto instance = num_args ? pos_args.first() : petenv_name; !instance.isEmpty())
{
auto entry = request.add_instance_name();
entry->append(instance.toStdString());
}
else
{
fmt::print(cerr, "The primary instance is disabled, please provide an instance name.\n");
return ParseCode::CommandLineError;
}
return status;
}
| 6,012
|
C++
|
.cpp
| 155
| 31.716129
| 114
| 0.627081
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,808
|
version.cpp
|
canonical_multipass/src/client/cli/cmd/version.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "version.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
#include <multipass/version.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Version::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](mp::VersionReply& reply)
{
cout << chosen_formatter->format(reply, multipass::version_string);
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status)
{
VersionReply reply;
cout << chosen_formatter->format(reply, multipass::version_string);
return ReturnCode::Ok;
};
mp::VersionRequest request;
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::version, request, on_success, on_failure);
}
std::string cmd::Version::name() const
{
return "version";
}
QString cmd::Version::short_help() const
{
return QStringLiteral("Show version details");
}
QString cmd::Version::description() const
{
return QStringLiteral("Display version information about the multipass command\n"
"and daemon.");
}
mp::ParseCode cmd::Version::parse_args(mp::ArgParser* parser)
{
QCommandLineOption formatOption("format",
"Output version information in the requested format.\n"
"Valid formats are: table (default), json, csv and yaml",
"format", "table");
parser->addOption(formatOption);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 0)
{
cerr << "This command takes no arguments\n";
return ParseCode::CommandLineError;
}
status = handle_format_option(parser, &chosen_formatter, cerr);
return status;
}
| 2,661
|
C++
|
.cpp
| 78
| 28.666667
| 93
| 0.672515
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,809
|
clone.cpp
|
canonical_multipass/src/client/cli/cmd/clone.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "clone.h"
#include "animated_spinner.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Clone::run(ArgParser* parser)
{
const auto parscode = parse_args(parser);
if (parscode != ParseCode::Ok)
{
return parser->returnCodeFrom(parscode);
}
AnimatedSpinner spinner{cout};
auto action_on_success = [this, &spinner](CloneReply& reply) -> ReturnCode {
spinner.stop();
cout << reply.reply_message();
return ReturnCode::Ok;
};
auto action_on_failure = [this, &spinner](grpc::Status& status, CloneReply& reply) -> ReturnCode {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status, reply.reply_message());
};
spinner.start("Cloning " + rpc_request.source_name());
return dispatch(&RpcMethod::clone, rpc_request, action_on_success, action_on_failure);
}
std::string cmd::Clone::name() const
{
return "clone";
}
QString cmd::Clone::short_help() const
{
return QStringLiteral("Clone an instance");
}
QString cmd::Clone::description() const
{
return QStringLiteral(
"Create an independent copy of an existing instance. The instance must be stopped before you proceed.");
}
mp::ParseCode cmd::Clone::parse_args(ArgParser* parser)
{
parser->addPositionalArgument("source_name", "The name of the source instance to be cloned", "<source_name>");
const QCommandLineOption destination_name_option{
{"n", "name"},
"Specify a custom name for the cloned instance. The name must follow the same validity rules as instance names "
"(see \"help launch\"). Default: \"<source_name>-cloneN\", where N is the Nth cloned instance.",
"destination-name"};
parser->addOption(destination_name_option);
const auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
const auto number_of_positional_arguments = parser->positionalArguments().count();
if (number_of_positional_arguments < 1)
{
cerr << "Please provide the name of the source instance.\n";
return ParseCode::CommandLineError;
}
if (number_of_positional_arguments > 1)
{
cerr << "Too many arguments.\n";
return ParseCode::CommandLineError;
}
const auto source_name = parser->positionalArguments()[0];
rpc_request.set_source_name(source_name.toStdString());
rpc_request.set_verbosity_level(parser->verbosityLevel());
if (parser->isSet(destination_name_option))
{
rpc_request.set_destination_name(parser->value(destination_name_option).toStdString());
}
return ParseCode::Ok;
}
| 3,379
|
C++
|
.cpp
| 89
| 33.47191
| 120
| 0.699694
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,810
|
authenticate.cpp
|
canonical_multipass/src/client/cli/cmd/authenticate.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "authenticate.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/prompters.h>
#include <multipass/exceptions/cli_exceptions.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Authenticate::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [](mp::AuthenticateReply& reply) { return mp::ReturnCode::Ok; };
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::authenticate, request, on_success, on_failure);
}
std::string cmd::Authenticate::name() const
{
return "authenticate";
}
std::vector<std::string> cmd::Authenticate::aliases() const
{
return {name(), "auth"};
}
QString cmd::Authenticate::short_help() const
{
return QStringLiteral("Authenticate client");
}
QString cmd::Authenticate::description() const
{
return QStringLiteral("Authenticate with the Multipass service.\n"
"A system administrator should provide you with a passphrase\n"
"to allow use of the Multipass service.");
}
mp::ParseCode cmd::Authenticate::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("passphrase",
"Passphrase to register with the Multipass service. If omitted, a prompt will be "
"displayed for entering the passphrase.",
"[<passphrase>]");
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
if (parser->positionalArguments().count() > 1)
{
cerr << "Too many arguments given\n";
return ParseCode::CommandLineError;
}
if (parser->positionalArguments().empty())
{
try
{
mp::PassphrasePrompter prompter(term);
auto passphrase = prompter.prompt();
if (passphrase.empty())
{
cerr << "No passphrase given\n";
return ParseCode::CommandLineError;
}
request.set_passphrase(passphrase);
}
catch (const mp::PromptException& e)
{
cerr << e.what() << std::endl;
return ParseCode::CommandLineError;
}
}
else
{
request.set_passphrase(parser->positionalArguments().first().toStdString());
}
return status;
}
| 3,259
|
C++
|
.cpp
| 92
| 28.945652
| 116
| 0.651525
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,811
|
prefer.cpp
|
canonical_multipass/src/client/cli/cmd/prefer.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/cli/argparser.h>
#include "common_cli.h"
#include "prefer.h"
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Prefer::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
aliases.set_active_context(parser->positionalArguments()[0].toStdString());
return ReturnCode::Ok;
}
std::string cmd::Prefer::name() const
{
return "prefer";
}
QString cmd::Prefer::short_help() const
{
return QStringLiteral("Switch the current alias context");
}
QString cmd::Prefer::description() const
{
return QStringLiteral("Switch the current alias context. If it does not exist, create it before switching.");
}
mp::ParseCode cmd::Prefer::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("name", "Name of the context to switch to", "<name>");
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() == 0)
{
cerr << "The prefer command needs an argument\n";
return ParseCode::CommandLineError;
}
if (parser->positionalArguments().count() > 1)
{
cerr << "Wrong number of arguments given\n";
return ParseCode::CommandLineError;
}
return status;
}
| 2,049
|
C++
|
.cpp
| 64
| 28.484375
| 113
| 0.707614
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,812
|
exec.cpp
|
canonical_multipass/src/client/cli/cmd/exec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "exec.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/ssh/ssh_client.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
namespace
{
const QString work_dir_option_name{"working-directory"};
const QString no_dir_mapping_option{"no-map-working-directory"};
auto is_dir_mounted(const QStringList& split_current_dir, const QStringList& split_source_dir)
{
auto source_dir_size = split_source_dir.size();
if (split_current_dir.size() < source_dir_size)
return false;
for (int i = 0; i < source_dir_size; ++i)
if (split_current_dir[i] != split_source_dir[i])
return false;
return true;
}
} // namespace
mp::ReturnCode cmd::Exec::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto instance_name = ssh_info_request.instance_name(0);
std::vector<std::string> args;
for (int i = 1; i < parser->positionalArguments().size(); ++i)
args.push_back(parser->positionalArguments().at(i).toStdString());
std::optional<std::string> work_dir;
if (parser->isSet(work_dir_option_name))
{
// If the user asked for a working directory, prepend the appropriate `cd`.
work_dir = parser->value(work_dir_option_name).toStdString();
}
else
{
// Decide whether the working directory must be mapped. There are two cases to consider:
// 1. when executing an alias, see if the working directory is set to "map";
// 2. when not executing an alias, see if the user did not specify the no-mapping argument.
// If one of these two things is true, then prepend the appropriate `cd` to the command to be ran.
if ((parser->executeAlias() && parser->executeAlias()->working_directory == "map") ||
(!parser->executeAlias() && !parser->isSet(no_dir_mapping_option)))
{
// The host directory on which the user is executing the command.
QString clean_exec_dir = QDir::cleanPath(QDir::current().canonicalPath());
QStringList split_exec_dir = clean_exec_dir.split('/');
auto on_info_success = [&work_dir, &split_exec_dir](mp::InfoReply& reply) {
for (const auto& mount : reply.details(0).mount_info().mount_paths())
{
auto source_dir = QDir(QString::fromStdString(mount.source_path()));
auto clean_source_dir = QDir::cleanPath(source_dir.absolutePath());
QStringList split_source_dir = clean_source_dir.split('/');
// If the directory is mounted, we need to `cd` to it in the instance before executing the command.
if (is_dir_mounted(split_exec_dir, split_source_dir))
{
for (int i = 0; i < split_source_dir.size(); ++i)
split_exec_dir.removeFirst();
work_dir = mount.target_path() + '/' + split_exec_dir.join('/').toStdString();
}
}
return ReturnCode::Ok;
};
auto on_info_failure = [this](grpc::Status& status) {
return standard_failure_handler_for(name(), cerr, status);
};
info_request.set_verbosity_level(parser->verbosityLevel());
info_request.add_instance_snapshot_pairs()->set_instance_name(instance_name);
info_request.set_no_runtime_information(true);
dispatch(&RpcMethod::info, info_request, on_info_success, on_info_failure);
// TODO: what to do with the returned value?
}
}
auto on_success = [this, &args, &work_dir](mp::SSHInfoReply& reply) {
return exec_success(reply, work_dir, args, term);
};
auto on_failure = [this, &instance_name, parser](grpc::Status& status) {
if (status.error_code() == grpc::StatusCode::ABORTED)
return run_cmd_and_retry({"multipass", "start", QString::fromStdString(instance_name)}, parser, cout, cerr);
else
return standard_failure_handler_for(name(), cerr, status);
};
ssh_info_request.set_verbosity_level(parser->verbosityLevel());
ReturnCode ssh_return_code;
while ((ssh_return_code = dispatch(&RpcMethod::ssh_info, ssh_info_request, on_success, on_failure)) ==
ReturnCode::Retry)
;
return ssh_return_code;
}
std::string cmd::Exec::name() const
{
return "exec";
}
QString cmd::Exec::short_help() const
{
return QStringLiteral("Run a command on an instance");
}
QString cmd::Exec::description() const
{
return QStringLiteral("Run a command on an instance");
}
mp::ReturnCode cmd::Exec::exec_success(const mp::SSHInfoReply& reply, const std::optional<std::string>& dir,
const std::vector<std::string>& args, mp::Terminal* term)
{
// TODO: mainly for testing - need a better way to test parsing
if (reply.ssh_info().empty())
return ReturnCode::Ok;
const auto& ssh_info = reply.ssh_info().begin()->second;
const auto& host = ssh_info.host();
const auto& port = ssh_info.port();
const auto& username = ssh_info.username();
const auto& priv_key_blob = ssh_info.priv_key_base64();
try
{
auto console_creator = [&term](auto channel) { return Console::make_console(channel, term); };
mp::SSHClient ssh_client{host, port, username, priv_key_blob, console_creator};
std::vector<std::vector<std::string>> all_args;
if (dir)
{
if (args[0] == "sudo")
{
// If we are running through 'sudo' and need to change directory, it might happen that the default user
// does not have access to the folder and thus the cd command will fail. Additionally, `cd` cannot be
// ran with sudo, what forces us to run everything through `sh`.
auto sh_args = fmt::format("cd {} && {}", *dir, fmt::join(args, " "));
all_args = {{"sudo", "sh", "-c", sh_args}};
}
else
all_args = {{"cd", *dir}, {args}};
}
else
all_args = {{args}};
return static_cast<mp::ReturnCode>(ssh_client.exec(all_args));
}
catch (const std::exception& e)
{
term->cerr() << "exec failed: " << e.what() << "\n";
return ReturnCode::CommandFail;
}
}
mp::ParseCode cmd::Exec::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("name", "Name of instance to execute the command on", "<name>");
parser->addPositionalArgument("command", "Command to execute on the instance", "[--] <command>");
QCommandLineOption workDirOption({"d", work_dir_option_name}, "Change to <dir> before execution", "dir");
QCommandLineOption noDirMappingOption({"n", no_dir_mapping_option},
"Do not map the host execution path to a mounted path");
parser->addOptions({workDirOption});
parser->addOptions({noDirMappingOption});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
if (!parser->unknownOptionNames().empty() && !parser->containsArgument("--"))
{
bool is_alias = parser->executeAlias() != std::nullopt;
cerr << fmt::format("\nOptions to the {} should come after \"--\", like this:\nmultipass {} <arguments>\n",
is_alias ? "alias" : "inner command",
is_alias ? "<alias> --" : "exec <instance> -- <command>");
}
return status;
}
if (parser->isSet(work_dir_option_name) && parser->isSet(no_dir_mapping_option))
{
cerr << fmt::format("Options --{} and --{} clash\n", work_dir_option_name, no_dir_mapping_option);
status = ParseCode::CommandLineError;
}
else if (parser->positionalArguments().count() < 2)
{
cerr << "Wrong number of arguments\n";
status = ParseCode::CommandLineError;
}
else
{
auto entry = ssh_info_request.add_instance_name();
entry->append(parser->positionalArguments().first().toStdString());
}
return status;
}
| 8,954
|
C++
|
.cpp
| 197
| 37.19797
| 120
| 0.615667
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,813
|
start.cpp
|
canonical_multipass/src/client/cli/cmd/start.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "start.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h>
#include <multipass/exceptions/cmd_exceptions.h>
#include <multipass/settings/settings.h>
#include <multipass/timer.h>
#include <fmt/ostream.h>
#include <cassert>
#include <chrono>
#include <cstdlib>
namespace mp = multipass;
namespace cmd = multipass::cmd;
using namespace std::chrono_literals;
namespace
{
constexpr auto deleted_error_fmt =
"Instance '{}' is deleted. Use 'recover' to recover it or 'purge' to permanently delete it.\n";
constexpr auto absent_error_fmt = "Instance '{}' does not exist.\n";
constexpr auto unknown_error_fmt = "Instance '{}' failed in an unexpected way, check logs for more information.\n";
} // namespace
mp::ReturnCode cmd::Start::run(mp::ArgParser* parser)
{
petenv_name = MP_SETTINGS.get(petenv_key);
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
AnimatedSpinner spinner{cout};
auto on_success = [&spinner, this](mp::StartReply& reply) {
spinner.stop();
if (term->is_live() && update_available(reply.update_info()))
cout << update_notice(reply.update_info());
return ReturnCode::Ok;
};
auto on_failure = [this, &spinner, parser](grpc::Status& status) {
spinner.stop();
std::string details;
if (status.error_code() == grpc::StatusCode::ABORTED && !status.error_details().empty())
{
mp::StartError start_error;
start_error.ParseFromString(status.error_details());
for (const auto& pair : start_error.instance_errors())
{
const auto* err_fmt = unknown_error_fmt;
if (pair.second == mp::StartError::INSTANCE_DELETED)
err_fmt = deleted_error_fmt;
else if (pair.second == mp::StartError::DOES_NOT_EXIST)
{
if (pair.first != petenv_name.toStdString())
err_fmt = absent_error_fmt;
else
continue;
}
fmt::format_to(std::back_inserter(details), err_fmt, pair.first);
}
if (details.empty())
{
assert(start_error.instance_errors_size() == 1 &&
std::cbegin(start_error.instance_errors())->first == petenv_name.toStdString());
QStringList launch_args{"multipass", "launch", "--name", petenv_name};
if (parser->isSet("timeout"))
launch_args.append({"--timeout", parser->value("timeout")});
return run_cmd_and_retry(launch_args, parser, cout, cerr); /*
TODO replace with create, so that all instances are started in a single go */
}
}
return standard_failure_handler_for(name(), cerr, status, details);
};
request.set_verbosity_level(parser->verbosityLevel());
std::unique_ptr<multipass::utils::Timer> timer;
if (parser->isSet("timeout"))
{
timer = cmd::make_timer(parser->value("timeout").toInt(), &spinner, cerr,
"Timed out waiting for instance to start.");
timer->start();
}
ReturnCode return_code;
auto streaming_callback = make_iterative_spinner_callback<StartRequest, StartReply>(spinner, *term);
do
{
spinner.start(instance_action_message_for(request.instance_names(), "Starting "));
} while ((return_code = dispatch(&RpcMethod::start, request, on_success, on_failure, streaming_callback)) ==
ReturnCode::Retry);
return return_code;
}
std::string cmd::Start::name() const
{
return "start";
}
QString cmd::Start::short_help() const
{
return QStringLiteral("Start instances");
}
QString cmd::Start::description() const
{
return QStringLiteral("Start the named instances. Exits with return code 0\n"
"when the instances start, or with an error code if\n"
"any fail to start.");
}
mp::ParseCode cmd::Start::parse_args(mp::ArgParser* parser)
{
const auto& [description, syntax] =
petenv_name.isEmpty()
? std::make_pair(QString{"Names of instances to start."}, QString{"<name> [<name> ...]"})
: std::make_pair(QString{"Names of instances to start. If omitted, and without the --all option, '%1' (the "
"configured primary instance name) will be assumed. If '%1' does not exist but is "
"included in a successful start command (either implicitly or explicitly), it is "
"launched automatically (see `launch` for more info)."}
.arg(petenv_name),
QString{"[<name> ...]"});
parser->addPositionalArgument("name", description, syntax);
QCommandLineOption all_option(all_option_name, "Start all instances");
parser->addOption(all_option);
mp::cmd::add_timeout(parser);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
return status;
auto parse_code = check_for_name_and_all_option_conflict(parser, cerr, /*allow_empty=*/!petenv_name.isEmpty());
if (parse_code != ParseCode::Ok)
{
if (petenv_name.isEmpty() && parser->positionalArguments().isEmpty())
fmt::print(cerr, "Note: the primary instance is disabled.\n");
return parse_code;
}
try
{
request.set_timeout(mp::cmd::parse_timeout(parser));
}
catch (const mp::ValidationException& e)
{
cerr << "error: " << e.what() << std::endl;
return ParseCode::CommandLineError;
}
request.mutable_instance_names()->CopyFrom(add_instance_names(parser, /*default_name=*/petenv_name.toStdString()));
return status;
}
| 6,669
|
C++
|
.cpp
| 156
| 34.423077
| 120
| 0.621158
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,814
|
create_alias.cpp
|
canonical_multipass/src/client/cli/cmd/create_alias.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "create_alias.h"
#include <multipass/format.h>
#include <multipass/platform.h>
multipass::ReturnCode multipass::cmd::create_alias(AliasDict& aliases, const std::string& alias_name,
const AliasDefinition& alias_definition, std::ostream& cout,
std::ostream& cerr, const std::optional<std::string>& context)
{
bool empty_before_add = aliases.empty();
auto old_context_name = aliases.active_context_name();
if (context)
aliases.set_active_context(*context);
if (!aliases.add_alias(alias_name, alias_definition))
{
aliases.set_active_context(old_context_name);
return ReturnCode::CommandLineError;
}
try
{
MP_PLATFORM.create_alias_script(aliases.active_context_name() + "." + alias_name, alias_definition);
}
catch (std::runtime_error& e)
{
aliases.remove_alias(alias_name);
aliases.set_active_context(old_context_name);
cerr << fmt::format("Error when creating script for alias: {}\n", e.what());
return ReturnCode::CommandLineError;
}
try
{
if (aliases.is_alias_unique(alias_name))
{
MP_PLATFORM.create_alias_script(alias_name, alias_definition);
}
}
catch (std::runtime_error& e)
{
aliases.remove_alias(alias_name);
aliases.set_active_context(old_context_name);
MP_PLATFORM.remove_alias_script(aliases.active_context_name() + "." + alias_name);
cerr << fmt::format("Error when creating script for alias: {}\n", e.what());
return ReturnCode::CommandLineError;
}
aliases.set_active_context(old_context_name);
#ifdef MULTIPASS_PLATFORM_WINDOWS
QChar separator(';');
#else
QChar separator(':');
#endif
// Each element of this list is a folder in the system's path.
auto path = qEnvironmentVariable("PATH").split(separator);
auto alias_folder = MP_PLATFORM.get_alias_scripts_folder().absolutePath();
// aliases.size() is the amount of contexts defined. If the alias dictionary is empty and a new alias is created
// in a context different to the default context, the dictionary will have two contexts, although only one
// defined alias.
if (empty_before_add && aliases.size() > 0 && std::find(path.cbegin(), path.cend(), alias_folder) == path.cend())
cout << MP_PLATFORM.alias_path_message();
return ReturnCode::Ok;
}
| 3,133
|
C++
|
.cpp
| 74
| 35.945946
| 117
| 0.670503
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,815
|
networks.cpp
|
canonical_multipass/src/client/cli/cmd/networks.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "networks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Networks::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](NetworksReply& reply) {
cout << chosen_formatter->format(reply);
if (term->is_live() && update_available(reply.update_info()))
cout << update_notice(reply.update_info());
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
NetworksRequest request;
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::networks, request, on_success, on_failure);
}
std::string cmd::Networks::name() const
{
return "networks";
}
std::vector<std::string> cmd::Networks::aliases() const
{
return {name()};
}
QString cmd::Networks::short_help() const
{
return QStringLiteral("List available network interfaces");
}
QString cmd::Networks::description() const
{
return QStringLiteral("List host network devices (physical interfaces, virtual switches, bridges)\n"
"available to integrate with using the `--network` switch to the `launch`\ncommand.");
}
mp::ParseCode cmd::Networks::parse_args(mp::ArgParser* parser)
{
QCommandLineOption formatOption(
"format", "Output list in the requested format.\nValid formats are: table (default), json, csv and yaml",
"format", "table");
parser->addOption(formatOption);
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 0)
{
cerr << "This command takes no arguments\n";
return ParseCode::CommandLineError;
}
status = handle_format_option(parser, &chosen_formatter, cerr);
return status;
}
| 2,720
|
C++
|
.cpp
| 76
| 31.565789
| 114
| 0.698552
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,816
|
snapshot.cpp
|
canonical_multipass/src/client/cli/cmd/snapshot.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "snapshot.h"
#include "animated_spinner.h"
#include "common_callbacks.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
namespace mp = multipass;
namespace cmd = mp::cmd;
mp::ReturnCode cmd::Snapshot::run(mp::ArgParser* parser)
{
if (auto ret = parse_args(parser); ret != ParseCode::Ok)
return parser->returnCodeFrom(ret);
AnimatedSpinner spinner{cout};
auto on_success = [this, &spinner](mp::SnapshotReply& reply) {
spinner.stop();
fmt::print(cout, "Snapshot taken: {}.{}\n", request.instance(), reply.snapshot());
return ReturnCode::Ok;
};
auto on_failure = [this, &spinner](grpc::Status& status) {
spinner.stop();
return standard_failure_handler_for(name(), cerr, status);
};
spinner.start("Taking snapshot");
return dispatch(&RpcMethod::snapshot,
request,
on_success,
on_failure,
make_logging_spinner_callback<SnapshotRequest, SnapshotReply>(spinner, cerr));
}
std::string cmd::Snapshot::name() const
{
return "snapshot";
}
QString cmd::Snapshot::short_help() const
{
return QStringLiteral("Take a snapshot of an instance");
}
QString cmd::Snapshot::description() const
{
return QStringLiteral("Take a snapshot of an instance that can later be restored to recover the current state.");
}
mp::ParseCode cmd::Snapshot::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("instance", "The instance to take a snapshot of.");
QCommandLineOption name_opt({"n", "name"},
"An optional name for the snapshot, subject to the same validity rules as instance "
"names (see `help launch`). Default: \"snapshotN\", where N is one plus the "
"number of snapshots that were ever taken for <instance>.",
"name");
QCommandLineOption comment_opt{{"comment", "c", "m"},
"An optional free comment to associate with the snapshot. (Hint: quote the text to "
"avoid spaces being parsed by your shell)",
"comment"};
parser->addOptions({name_opt, comment_opt});
if (auto status = parser->commandParse(this); status != ParseCode::Ok)
return status;
const auto positional_args = parser->positionalArguments();
const auto num_args = positional_args.count();
if (num_args < 1)
{
cerr << "Need the name of an instance to snapshot.\n";
return ParseCode::CommandLineError;
}
if (num_args > 1)
{
cerr << "Too many arguments supplied\n";
return ParseCode::CommandLineError;
}
request.set_instance(positional_args.first().toStdString());
request.set_comment(parser->value(comment_opt).toStdString());
request.set_snapshot(parser->value(name_opt).toStdString());
request.set_verbosity_level(parser->verbosityLevel());
return ParseCode::Ok;
}
| 3,709
|
C++
|
.cpp
| 89
| 34.494382
| 119
| 0.649917
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,817
|
get.cpp
|
canonical_multipass/src/client/cli/cmd/get.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "get.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/constants.h> // TODO remove (only for keys ATTOW and we shouldn't care for particular settings here)
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/settings/settings.h>
#include <QtGlobal>
#include <cassert>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::Get::run(mp::ArgParser* parser)
{
auto parse_code = parse_args(parser);
auto ret = parser->returnCodeFrom(parse_code);
if (parse_code == ParseCode::Ok)
{
try
{
if (keys_opt)
print_keys();
else
print_settings();
}
catch (const SettingsException& e)
{
cerr << e.what() << "\n";
ret = return_code_from(e);
}
}
return ret;
}
std::string cmd::Get::name() const
{
return "get";
}
QString cmd::Get::short_help() const
{
return QStringLiteral("Get a configuration setting");
}
QString cmd::Get::description() const
{
auto desc = QStringLiteral("Get the configuration setting corresponding to the given key, or all settings if "
"no key is specified.\n(Support for multiple keys and wildcards coming...)");
return desc + "\n\n" + describe_common_settings_keys();
}
mp::ParseCode cmd::Get::parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("arg", "Setting key, i.e. path to the intended setting.", "[<arg>]");
QCommandLineOption raw_option("raw", "Output in raw format. For now, this affects only the representation of empty "
"values (i.e. \"\" instead of \"<empty>\").");
QCommandLineOption keys_option("keys", "List available settings keys. This outputs the whole list of currently "
"available settings keys, or just <arg>, if provided and a valid key.");
parser->addOption(raw_option);
parser->addOption(keys_option);
auto status = parser->commandParse(this);
if (status == ParseCode::Ok)
{
keys_opt = parser->isSet(keys_option);
raw_opt = parser->isSet(raw_option);
const auto args = parser->positionalArguments();
if (args.count() == 1)
{
arg = args.at(0);
}
else if (args.count() > 1)
{
cerr << "Need at most one setting key.\n";
status = ParseCode::CommandLineError;
}
else if (!keys_opt) // support 0 or 1 positional arg when --keys is given
{
cerr << "Multiple settings not implemented yet. Please try again with one setting key or just the "
"`--keys` option for now.\n";
status = ParseCode::CommandLineError;
}
}
return status;
}
void cmd::Get::print_settings() const
{
assert(!arg.isEmpty() && "Need single arg until we implement multiple settings");
if (const auto val = MP_SETTINGS.get(arg); arg == passphrase_key) // TODO integrate into setting specs
cout << (val.isEmpty() ? "false" : "true");
else if (val.isEmpty() && !raw_opt)
cout << "<empty>";
else
cout << qUtf8Printable(val);
cout << "\n";
}
void multipass::cmd::Get::print_keys() const
{
const auto keys = MP_SETTINGS.keys();
const auto format = "{}\n";
if (arg.isEmpty())
fmt::print(cout, format, fmt::join(keys, "\n"));
else if (std::find(keys.cbegin(), keys.cend(), arg) != keys.cend()) // TODO implement key globing
fmt::print(cout, format, arg); // not very useful, but just a particular case of (intended) glob matching
else
throw mp::UnrecognizedSettingException(arg); // wildcards not implemented yet
}
| 4,440
|
C++
|
.cpp
| 116
| 31.905172
| 120
| 0.634673
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,818
|
list.cpp
|
canonical_multipass/src/client/cli/cmd/list.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "list.h"
#include "common_cli.h"
#include <multipass/cli/argparser.h>
#include <multipass/cli/formatter.h>
namespace mp = multipass;
namespace cmd = multipass::cmd;
mp::ReturnCode cmd::List::run(mp::ArgParser* parser)
{
auto ret = parse_args(parser);
if (ret != ParseCode::Ok)
{
return parser->returnCodeFrom(ret);
}
auto on_success = [this](ListReply& reply) {
cout << chosen_formatter->format(reply);
if (term->is_live() && update_available(reply.update_info()))
cout << update_notice(reply.update_info());
return ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) { return standard_failure_handler_for(name(), cerr, status); };
request.set_verbosity_level(parser->verbosityLevel());
return dispatch(&RpcMethod::list, request, on_success, on_failure);
}
std::string cmd::List::name() const
{
return "list";
}
std::vector<std::string> cmd::List::aliases() const
{
return {name(), "ls"};
}
QString cmd::List::short_help() const
{
return QStringLiteral("List all available instances or snapshots");
}
QString cmd::List::description() const
{
return QStringLiteral("List all instances or snapshots which have been created.");
}
mp::ParseCode cmd::List::parse_args(mp::ArgParser* parser)
{
QCommandLineOption snapshotsOption("snapshots", "List all available snapshots");
QCommandLineOption formatOption(
"format", "Output list in the requested format.\nValid formats are: table (default), json, csv and yaml",
"format", "table");
QCommandLineOption noIpv4Option("no-ipv4", "Do not query the instances for the IPv4's they are using");
noIpv4Option.setFlags(QCommandLineOption::HiddenFromHelp);
parser->addOptions({snapshotsOption, formatOption, noIpv4Option});
auto status = parser->commandParse(this);
if (status != ParseCode::Ok)
{
return status;
}
if (parser->positionalArguments().count() > 0)
{
cerr << "This command takes no arguments\n";
return ParseCode::CommandLineError;
}
if (parser->isSet(snapshotsOption) && parser->isSet(noIpv4Option))
{
cerr << "IP addresses are not applicable in conjunction with listing snapshots\n";
return ParseCode::CommandLineError;
}
request.set_snapshots(parser->isSet(snapshotsOption));
request.set_request_ipv4(!parser->isSet(noIpv4Option));
status = handle_format_option(parser, &chosen_formatter, cerr);
return status;
}
| 3,163
|
C++
|
.cpp
| 84
| 33.5
| 114
| 0.707556
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,819
|
yaml_formatter.cpp
|
canonical_multipass/src/client/cli/formatter/yaml_formatter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/cli/client_common.h>
#include <multipass/cli/format_utils.h>
#include <multipass/cli/yaml_formatter.h>
#include <multipass/format.h>
#include <multipass/utils.h>
#include <multipass/yaml_node_utils.h>
#include <yaml-cpp/yaml.h>
#include <locale>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace
{
template <typename ImageInfo>
std::map<std::string, YAML::Node> format_images(const ImageInfo& images_info)
{
std::map<std::string, YAML::Node> images_node;
for (const auto& image : images_info)
{
YAML::Node image_node;
image_node["aliases"] = std::vector<std::string>{};
auto aliases = image.aliases_info();
mp::format::filter_aliases(aliases);
for (auto alias = aliases.cbegin() + 1; alias != aliases.cend(); alias++)
image_node["aliases"].push_back(alias->alias());
image_node["os"] = image.os();
image_node["release"] = image.release();
image_node["version"] = image.version();
image_node["remote"] = aliases[0].remote_name();
images_node[mp::format::image_string_for(aliases[0])] = image_node;
}
return images_node;
}
YAML::Node generate_snapshot_details(const mp::DetailedInfoItem& item)
{
const auto& snapshot_details = item.snapshot_info();
const auto& fundamentals = snapshot_details.fundamentals();
YAML::Node snapshot_node;
snapshot_node["size"] = snapshot_details.size().empty() ? YAML::Node() : YAML::Node(snapshot_details.size());
snapshot_node["cpu_count"] = item.cpu_count();
snapshot_node["disk_space"] = item.disk_total();
snapshot_node["memory_size"] = item.memory_total();
YAML::Node mounts;
for (const auto& mount : item.mount_info().mount_paths())
{
YAML::Node mount_node;
mount_node["source_path"] = mount.source_path();
mounts[mount.target_path()] = mount_node;
}
snapshot_node["mounts"] = mounts;
snapshot_node["created"] = MP_FORMAT_UTILS.convert_to_user_locale(fundamentals.creation_timestamp());
snapshot_node["parent"] = fundamentals.parent().empty() ? YAML::Node() : YAML::Node(fundamentals.parent());
snapshot_node["children"] = YAML::Node(YAML::NodeType::Sequence);
for (const auto& child : snapshot_details.children())
snapshot_node["children"].push_back(child);
snapshot_node["comment"] = fundamentals.comment().empty() ? YAML::Node() : YAML::Node(fundamentals.comment());
return snapshot_node;
}
YAML::Node generate_instance_details(const mp::DetailedInfoItem& item)
{
const auto& instance_details = item.instance_info();
YAML::Node instance_node;
instance_node["state"] = mp::format::status_string_for(item.instance_status());
if (instance_details.has_num_snapshots())
instance_node["snapshot_count"] = instance_details.num_snapshots();
instance_node["image_hash"] = instance_details.id();
instance_node["image_release"] = instance_details.image_release();
instance_node["release"] =
instance_details.current_release().empty() ? YAML::Node() : YAML::Node(instance_details.current_release());
instance_node["cpu_count"] = item.cpu_count().empty() ? YAML::Node() : YAML::Node(item.cpu_count());
if (!instance_details.load().empty())
{
// The VM returns load info in the default C locale
auto current_loc = std::locale();
std::locale::global(std::locale("C"));
auto loads = mp::utils::split(instance_details.load(), " ");
for (const auto& entry : loads)
instance_node["load"].push_back(entry);
std::locale::global(current_loc);
}
YAML::Node disk;
disk["used"] = instance_details.disk_usage().empty() ? YAML::Node() : YAML::Node(instance_details.disk_usage());
disk["total"] = item.disk_total().empty() ? YAML::Node() : YAML::Node(item.disk_total());
// TODO: disk name should come from daemon
YAML::Node disk_node;
disk_node["sda1"] = disk;
instance_node["disks"].push_back(disk_node);
YAML::Node memory;
memory["usage"] = instance_details.memory_usage().empty() ? YAML::Node()
: YAML::Node(std::stoll(instance_details.memory_usage()));
memory["total"] = item.memory_total().empty() ? YAML::Node() : YAML::Node(std::stoll(item.memory_total()));
instance_node["memory"] = memory;
instance_node["ipv4"] = YAML::Node(YAML::NodeType::Sequence);
for (const auto& ip : instance_details.ipv4())
instance_node["ipv4"].push_back(ip);
YAML::Node mounts;
for (const auto& mount : item.mount_info().mount_paths())
{
YAML::Node mount_node;
for (const auto& uid_mapping : mount.mount_maps().uid_mappings())
{
auto host_uid = uid_mapping.host_id();
auto instance_uid = uid_mapping.instance_id();
mount_node["uid_mappings"].push_back(
fmt::format("{}:{}",
std::to_string(host_uid),
(instance_uid == mp::default_id) ? "default" : std::to_string(instance_uid)));
}
for (const auto& gid_mapping : mount.mount_maps().gid_mappings())
{
auto host_gid = gid_mapping.host_id();
auto instance_gid = gid_mapping.instance_id();
mount_node["gid_mappings"].push_back(
fmt::format("{}:{}",
std::to_string(host_gid),
(instance_gid == mp::default_id) ? "default" : std::to_string(instance_gid)));
}
mount_node["source_path"] = mount.source_path();
mounts[mount.target_path()] = mount_node;
}
instance_node["mounts"] = mounts;
return instance_node;
}
std::string generate_instances_list(const mp::InstancesList& instance_list)
{
YAML::Node list;
for (const auto& instance : mp::format::sorted(instance_list.instances()))
{
YAML::Node instance_node;
instance_node["state"] = mp::format::status_string_for(instance.instance_status());
instance_node["ipv4"] = YAML::Node(YAML::NodeType::Sequence);
for (const auto& ip : instance.ipv4())
instance_node["ipv4"].push_back(ip);
instance_node["release"] =
instance.current_release().empty() ? "Not Available" : fmt::format("Ubuntu {}", instance.current_release());
list[instance.name()].push_back(instance_node);
}
return mpu::emit_yaml(list);
}
std::string generate_snapshots_list(const mp::SnapshotsList& snapshot_list)
{
YAML::Node info_node;
for (const auto& item : mp::format::sorted(snapshot_list.snapshots()))
{
const auto& snapshot = item.fundamentals();
YAML::Node instance_node;
YAML::Node snapshot_node;
snapshot_node["parent"] = snapshot.parent().empty() ? YAML::Node() : YAML::Node(snapshot.parent());
snapshot_node["comment"] = snapshot.comment().empty() ? YAML::Node() : YAML::Node(snapshot.comment());
instance_node[snapshot.snapshot_name()].push_back(snapshot_node);
info_node[item.name()].push_back(instance_node);
}
return mpu::emit_yaml(info_node);
}
} // namespace
std::string mp::YamlFormatter::format(const InfoReply& reply) const
{
YAML::Node info_node;
info_node["errors"].push_back(YAML::Null);
for (const auto& info : mp::format::sorted(reply.details()))
{
if (info.has_instance_info())
{
info_node[info.name()].push_back(generate_instance_details(info));
}
else
{
assert(info.has_snapshot_info() && "either one of instance or snapshot details should be populated");
YAML::Node snapshot_node;
snapshot_node[info.snapshot_info().fundamentals().snapshot_name()] = generate_snapshot_details(info);
info_node[info.name()][0]["snapshots"].push_back(snapshot_node);
}
}
return mpu::emit_yaml(info_node);
}
std::string mp::YamlFormatter::format(const ListReply& reply) const
{
std::string output;
if (reply.has_instance_list())
{
output = generate_instances_list(reply.instance_list());
}
else
{
assert(reply.has_snapshot_list() && "eitherr one of instances or snapshots should be populated");
output = generate_snapshots_list(reply.snapshot_list());
}
return output;
}
std::string mp::YamlFormatter::format(const NetworksReply& reply) const
{
YAML::Node list;
for (const auto& interface : format::sorted(reply.interfaces()))
{
YAML::Node interface_node;
interface_node["type"] = interface.type();
interface_node["description"] = interface.description();
list[interface.name()].push_back(interface_node);
}
return mpu::emit_yaml(list);
}
std::string mp::YamlFormatter::format(const FindReply& reply) const
{
YAML::Node find;
find["errors"] = std::vector<YAML::Node>{};
find["blueprints"] = format_images(reply.blueprints_info());
find["images"] = format_images(reply.images_info());
return mpu::emit_yaml(find);
}
std::string mp::YamlFormatter::format(const VersionReply& reply, const std::string& client_version) const
{
YAML::Node version;
version["multipass"] = client_version;
if (!reply.version().empty())
{
version["multipassd"] = reply.version();
if (mp::cmd::update_available(reply.update_info()))
{
YAML::Node update;
update["title"] = reply.update_info().title();
update["description"] = reply.update_info().description();
update["url"] = reply.update_info().url();
version["update"] = update;
}
}
return mpu::emit_yaml(version);
}
std::string mp::YamlFormatter::format(const mp::AliasDict& aliases) const
{
YAML::Node aliases_list, aliases_node;
for (const auto& [context_name, context_contents] : sort_dict(aliases))
{
YAML::Node context_node;
for (const auto& [name, def] : sort_dict(context_contents))
{
YAML::Node alias_node;
alias_node["alias"] = name;
alias_node["command"] = def.command;
alias_node["instance"] = def.instance;
alias_node["working-directory"] = def.working_directory;
context_node.push_back(alias_node);
}
aliases_node[context_name] = context_node;
}
aliases_list["active_context"] = aliases.active_context_name();
aliases_list["aliases"] = aliases_node;
return mpu::emit_yaml(aliases_list);
}
| 11,319
|
C++
|
.cpp
| 264
| 36.041667
| 120
| 0.638656
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,820
|
format_utils.cpp
|
canonical_multipass/src/client/cli/formatter/format_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/csv_formatter.h>
#include <multipass/cli/format_utils.h>
#include <multipass/cli/formatter.h>
#include <multipass/cli/json_formatter.h>
#include <multipass/cli/table_formatter.h>
#include <multipass/cli/yaml_formatter.h>
#include <iomanip>
#include <locale>
#include <sstream>
namespace mp = multipass;
namespace
{
template <typename T>
std::unique_ptr<mp::Formatter> make_entry()
{
return std::make_unique<T>();
}
auto make_map()
{
std::map<std::string, std::unique_ptr<mp::Formatter>> map;
map.emplace("table", make_entry<mp::TableFormatter>());
map.emplace("json", make_entry<mp::JsonFormatter>());
map.emplace("csv", make_entry<mp::CSVFormatter>());
map.emplace("yaml", make_entry<mp::YamlFormatter>());
return map;
}
const std::map<std::string, std::unique_ptr<mp::Formatter>> formatters{make_map()};
const std::set<std::string> unwanted_aliases{"ubuntu", "default"};
} // namespace
std::string mp::format::status_string_for(const mp::InstanceStatus& status)
{
std::string status_val;
switch (status.status())
{
case mp::InstanceStatus::RUNNING:
status_val = "Running";
break;
case mp::InstanceStatus::STOPPED:
status_val = "Stopped";
break;
case mp::InstanceStatus::DELETED:
status_val = "Deleted";
break;
case mp::InstanceStatus::STARTING:
status_val = "Starting";
break;
case mp::InstanceStatus::RESTARTING:
status_val = "Restarting";
break;
case mp::InstanceStatus::DELAYED_SHUTDOWN:
status_val = "Delayed Shutdown";
break;
case mp::InstanceStatus::SUSPENDING:
status_val = "Suspending";
break;
case mp::InstanceStatus::SUSPENDED:
status_val = "Suspended";
break;
default:
status_val = "Unknown";
break;
}
return status_val;
}
std::string mp::format::image_string_for(const mp::FindReply_AliasInfo& alias)
{
return alias.remote_name().empty() ? alias.alias() : fmt::format("{}:{}", alias.remote_name(), alias);
}
mp::Formatter* mp::format::formatter_for(const std::string& format)
{
auto entry = formatters.find(format);
if (entry != formatters.end())
return entry->second.get();
return nullptr;
}
void mp::format::filter_aliases(google::protobuf::RepeatedPtrField<multipass::FindReply_AliasInfo>& aliases)
{
for (auto i = aliases.size() - 1; i >= 0; i--)
{
if (aliases.size() == 1) // Keep at least the first entry
break;
if (aliases[i].alias().length() == 1)
aliases.DeleteSubrange(i, 1);
else if (unwanted_aliases.find(aliases[i].alias()) != unwanted_aliases.end())
aliases.DeleteSubrange(i, 1);
}
}
mp::FormatUtils::FormatUtils(const Singleton<FormatUtils>::PrivatePass& pass) noexcept
: Singleton<FormatUtils>::Singleton{pass}
{
}
std::string mp::FormatUtils::convert_to_user_locale(const google::protobuf::Timestamp& timestamp) const
{
std::ostringstream oss;
oss.imbue(std::locale(""));
std::time_t t = google::protobuf::util::TimeUtil::TimestampToTimeT(timestamp);
oss << std::put_time(std::localtime(&t), "%c %Z");
return oss.str();
}
| 3,869
|
C++
|
.cpp
| 115
| 29.347826
| 108
| 0.679508
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,821
|
table_formatter.cpp
|
canonical_multipass/src/client/cli/formatter/table_formatter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/cli/client_common.h>
#include <multipass/cli/format_utils.h>
#include <multipass/cli/table_formatter.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <regex>
namespace mp = multipass;
namespace
{
const std::regex newline("(\r\n|\n)");
std::string format_images(const google::protobuf::RepeatedPtrField<mp::FindReply_ImageInfo>& images_info,
std::string type)
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "{:<28}{:<18}{:<17}{:<}\n", type, "Aliases", "Version", "Description");
for (const auto& image : images_info)
{
auto aliases = image.aliases_info();
mp::format::filter_aliases(aliases);
fmt::format_to(std::back_inserter(buf), "{:<28}{:<18}{:<17}{:<}\n", mp::format::image_string_for(aliases[0]),
fmt::format("{}", fmt::join(aliases.cbegin() + 1, aliases.cend(), ",")), image.version(),
fmt::format("{}{}", image.os().empty() ? "" : image.os() + " ", image.release()));
}
fmt::format_to(std::back_inserter(buf), "\n");
return fmt::to_string(buf);
}
std::string to_usage(const std::string& usage, const std::string& total)
{
if (usage.empty() || total.empty())
return "--";
return fmt::format("{} out of {}", mp::MemorySize{usage}.human_readable(), mp::MemorySize{total}.human_readable());
}
std::string generate_snapshot_details(const mp::DetailedInfoItem& item)
{
fmt::memory_buffer buf;
const auto& fundamentals = item.snapshot_info().fundamentals();
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Snapshot:", fundamentals.snapshot_name());
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Instance:", item.name());
if (!item.snapshot_info().size().empty())
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Size:", item.snapshot_info().size());
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "CPU(s):", item.cpu_count());
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Disk space:", item.disk_total());
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Memory size:", item.memory_total());
auto mount_paths = item.mount_info().mount_paths();
fmt::format_to(std::back_inserter(buf), "{:<16}{}", "Mounts:", mount_paths.empty() ? "--\n" : "");
for (auto mount = mount_paths.cbegin(); mount != mount_paths.cend(); ++mount)
{
if (mount != mount_paths.cbegin())
fmt::format_to(std::back_inserter(buf), "{:<16}", "");
fmt::format_to(std::back_inserter(buf),
"{:{}} => {}\n",
mount->source_path(),
item.mount_info().longest_path_len(),
mount->target_path());
}
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Created:",
MP_FORMAT_UTILS.convert_to_user_locale(fundamentals.creation_timestamp()));
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Parent:",
fundamentals.parent().empty() ? "--" : fundamentals.parent());
auto children = item.snapshot_info().children();
fmt::format_to(std::back_inserter(buf), "{:<16}{}", "Children:", children.empty() ? "--\n" : "");
for (auto child = children.cbegin(); child != children.cend(); ++child)
{
if (child != children.cbegin())
fmt::format_to(std::back_inserter(buf), "{:<16}", "");
fmt::format_to(std::back_inserter(buf), "{}\n", *child);
}
/* TODO split and align string if it extends onto several lines; but actually better implement generic word-wrapping
for all output, taking both terminal width and current indentation level into account */
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Comment:",
fundamentals.comment().empty()
? "--"
: std::regex_replace(fundamentals.comment(), newline, "$&" + std::string(16, ' ')));
return fmt::to_string(buf);
}
std::string generate_instance_details(const mp::DetailedInfoItem& item)
{
fmt::memory_buffer buf;
const auto& instance_details = item.instance_info();
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Name:", item.name());
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"State:",
mp::format::status_string_for(item.instance_status()));
if (instance_details.has_num_snapshots())
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "Snapshots:", instance_details.num_snapshots());
int ipv4_size = instance_details.ipv4_size();
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "IPv4:", ipv4_size ? instance_details.ipv4(0) : "--");
for (int i = 1; i < ipv4_size; ++i)
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "", instance_details.ipv4(i));
if (int ipv6_size = instance_details.ipv6_size())
{
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "IPv6:", instance_details.ipv6(0));
for (int i = 1; i < ipv6_size; ++i)
fmt::format_to(std::back_inserter(buf), "{:<16}{}\n", "", instance_details.ipv6(i));
}
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Release:",
instance_details.current_release().empty() ? "--" : instance_details.current_release());
fmt::format_to(std::back_inserter(buf), "{:<16}", "Image hash:");
if (instance_details.id().empty())
fmt::format_to(std::back_inserter(buf), "{}\n", "Not Available");
else
fmt::format_to(std::back_inserter(buf),
"{}{}\n",
instance_details.id().substr(0, 12),
!instance_details.image_release().empty()
? fmt::format(" (Ubuntu {})", instance_details.image_release())
: "");
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"CPU(s):",
item.cpu_count().empty() ? "--" : item.cpu_count());
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Load:",
instance_details.load().empty() ? "--" : instance_details.load());
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Disk usage:",
to_usage(instance_details.disk_usage(), item.disk_total()));
fmt::format_to(std::back_inserter(buf),
"{:<16}{}\n",
"Memory usage:",
to_usage(instance_details.memory_usage(), item.memory_total()));
const auto& mount_paths = item.mount_info().mount_paths();
fmt::format_to(std::back_inserter(buf), "{:<16}{}", "Mounts:", mount_paths.empty() ? "--\n" : "");
for (auto mount = mount_paths.cbegin(); mount != mount_paths.cend(); ++mount)
{
if (mount != mount_paths.cbegin())
fmt::format_to(std::back_inserter(buf), "{:<16}", "");
fmt::format_to(std::back_inserter(buf),
"{:{}} => {}\n",
mount->source_path(),
item.mount_info().longest_path_len(),
mount->target_path());
auto mount_maps = mount->mount_maps();
auto uid_mappings_size = mount_maps.uid_mappings_size();
for (auto i = 0; i < uid_mappings_size; ++i)
{
auto uid_map_pair = mount_maps.uid_mappings(i);
auto host_uid = uid_map_pair.host_id();
auto instance_uid = uid_map_pair.instance_id();
fmt::format_to(std::back_inserter(buf),
"{:>{}}{}:{}{}",
(i == 0) ? "UID map: " : "",
(i == 0) ? 29 : 0,
std::to_string(host_uid),
(instance_uid == mp::default_id) ? "default" : std::to_string(instance_uid),
(i == uid_mappings_size - 1) ? "\n" : ", ");
}
for (auto gid_mapping = mount_maps.gid_mappings().cbegin(); gid_mapping != mount_maps.gid_mappings().cend();
++gid_mapping)
{
auto host_gid = gid_mapping->host_id();
auto instance_gid = gid_mapping->instance_id();
fmt::format_to(std::back_inserter(buf),
"{:>{}}{}:{}{}{}",
(gid_mapping == mount_maps.gid_mappings().cbegin()) ? "GID map: " : "",
(gid_mapping == mount_maps.gid_mappings().cbegin()) ? 29 : 0,
std::to_string(host_gid),
(instance_gid == mp::default_id) ? "default" : std::to_string(instance_gid),
(std::next(gid_mapping) != mount_maps.gid_mappings().cend()) ? ", " : "",
(std::next(gid_mapping) == mount_maps.gid_mappings().cend()) ? "\n" : "");
}
}
return fmt::to_string(buf);
}
std::string generate_instances_list(const mp::InstancesList& instance_list)
{
fmt::memory_buffer buf;
const auto& instances = instance_list.instances();
if (instances.empty())
return "No instances found.\n";
const std::string name_col_header = "Name";
const auto name_column_width = mp::format::column_width(
instances.begin(),
instances.end(),
[](const auto& instance) -> int { return instance.name().length(); },
name_col_header.length(),
24);
const std::string::size_type state_column_width = 18;
const std::string::size_type ip_column_width = 17;
const auto row_format = "{:<{}}{:<{}}{:<{}}{:<}\n";
fmt::format_to(std::back_inserter(buf),
row_format,
name_col_header,
name_column_width,
"State",
state_column_width,
"IPv4",
ip_column_width,
"Image");
for (const auto& instance : mp::format::sorted(instance_list.instances()))
{
int ipv4_size = instance.ipv4_size();
fmt::format_to(std::back_inserter(buf), row_format, instance.name(), name_column_width,
mp::format::status_string_for(instance.instance_status()), state_column_width,
ipv4_size ? instance.ipv4(0) : "--", ip_column_width,
instance.current_release().empty() ? "Not Available"
: fmt::format("Ubuntu {}", instance.current_release()));
for (int i = 1; i < ipv4_size; ++i)
{
fmt::format_to(std::back_inserter(buf), row_format, "", name_column_width, "", state_column_width,
instance.ipv4(i), instance.ipv4(i).size(), "");
}
}
return fmt::to_string(buf);
}
std::string generate_snapshots_list(const mp::SnapshotsList& snapshot_list)
{
fmt::memory_buffer buf;
const auto& snapshots = snapshot_list.snapshots();
if (snapshots.empty())
return "No snapshots found.\n";
const std::string name_col_header = "Instance", snapshot_col_header = "Snapshot", parent_col_header = "Parent",
comment_col_header = "Comment";
const auto name_column_width = mp::format::column_width(
snapshots.begin(),
snapshots.end(),
[](const auto& snapshot) -> int { return snapshot.name().length(); },
name_col_header.length());
const auto snapshot_column_width = mp::format::column_width(
snapshots.begin(),
snapshots.end(),
[](const auto& snapshot) -> int { return snapshot.fundamentals().snapshot_name().length(); },
snapshot_col_header.length());
const auto parent_column_width = mp::format::column_width(
snapshots.begin(),
snapshots.end(),
[](const auto& snapshot) -> int { return snapshot.fundamentals().parent().length(); },
parent_col_header.length());
const auto row_format = "{:<{}}{:<{}}{:<{}}{:<}\n";
fmt::format_to(std::back_inserter(buf),
row_format,
name_col_header,
name_column_width,
snapshot_col_header,
snapshot_column_width,
parent_col_header,
parent_column_width,
comment_col_header);
for (const auto& snapshot : mp::format::sorted(snapshot_list.snapshots()))
{
size_t max_comment_column_width = 50;
std::smatch match;
const auto& fundamentals = snapshot.fundamentals();
if (std::regex_search(fundamentals.comment().begin(), fundamentals.comment().end(), match, newline))
max_comment_column_width = std::min((size_t)(match.position(1)) + 1, max_comment_column_width);
fmt::format_to(std::back_inserter(buf),
row_format,
snapshot.name(),
name_column_width,
fundamentals.snapshot_name(),
snapshot_column_width,
fundamentals.parent().empty() ? "--" : fundamentals.parent(),
parent_column_width,
fundamentals.comment().empty() ? "--"
: fundamentals.comment().length() > max_comment_column_width
? fmt::format("{}…", fundamentals.comment().substr(0, max_comment_column_width - 1))
: fundamentals.comment());
}
return fmt::to_string(buf);
}
} // namespace
std::string mp::TableFormatter::format(const InfoReply& reply) const
{
fmt::memory_buffer buf;
for (const auto& info : mp::format::sorted(reply.details()))
{
if (info.has_instance_info())
{
fmt::format_to(std::back_inserter(buf), generate_instance_details(info));
}
else
{
assert(info.has_snapshot_info() && "either one of instance or snapshot details should be populated");
fmt::format_to(std::back_inserter(buf), generate_snapshot_details(info));
}
fmt::format_to(std::back_inserter(buf), "\n");
}
std::string output = fmt::to_string(buf);
if (!reply.details().empty())
output.pop_back();
else
output = fmt::format("No {} found.\n", reply.snapshots() ? "snapshots" : "instances");
return output;
}
std::string mp::TableFormatter::format(const ListReply& reply) const
{
std::string output;
if (reply.has_instance_list())
{
output = generate_instances_list(reply.instance_list());
}
else
{
assert(reply.has_snapshot_list() && "either one of instances or snapshots should be populated");
output = generate_snapshots_list(reply.snapshot_list());
}
return output;
}
std::string mp::TableFormatter::format(const NetworksReply& reply) const
{
fmt::memory_buffer buf;
auto interfaces = reply.interfaces();
if (interfaces.empty())
return "No network interfaces found.\n";
const std::string name_col_header = "Name", type_col_header = "Type", desc_col_header = "Description";
const auto name_column_width = mp::format::column_width(
interfaces.begin(),
interfaces.end(),
[](const auto& interface) -> int { return interface.name().length(); },
name_col_header.length());
const auto type_column_width = mp::format::column_width(
interfaces.begin(),
interfaces.end(),
[](const auto& interface) -> int { return interface.type().length(); },
type_col_header.length());
const auto row_format = "{:<{}}{:<{}}{:<}\n";
fmt::format_to(std::back_inserter(buf),
row_format,
name_col_header,
name_column_width,
type_col_header,
type_column_width,
desc_col_header);
for (const auto& interface : format::sorted(reply.interfaces()))
{
fmt::format_to(std::back_inserter(buf), row_format, interface.name(), name_column_width, interface.type(),
type_column_width, interface.description());
}
return fmt::to_string(buf);
}
std::string mp::TableFormatter::format(const FindReply& reply) const
{
fmt::memory_buffer buf;
if (reply.show_images() && reply.show_blueprints())
{
if (reply.images_info().empty() && reply.blueprints_info().empty())
{
fmt::format_to(std::back_inserter(buf), "No images or blueprints found.\n");
}
else
{
if (!reply.images_info().empty())
fmt::format_to(std::back_inserter(buf), format_images(reply.images_info(), "Image"));
if (!reply.blueprints_info().empty())
fmt::format_to(std::back_inserter(buf), format_images(reply.blueprints_info(), "Blueprint"));
}
}
else if (reply.show_images() && !reply.show_blueprints())
{
if (reply.images_info().empty())
fmt::format_to(std::back_inserter(buf), "No images found.\n");
else
fmt::format_to(std::back_inserter(buf), format_images(reply.images_info(), "Image"));
}
else if (!reply.show_images() && reply.show_blueprints())
{
if (reply.blueprints_info().empty())
fmt::format_to(std::back_inserter(buf), "No blueprints found.\n");
else
fmt::format_to(std::back_inserter(buf), format_images(reply.blueprints_info(), "Blueprint"));
}
return fmt::to_string(buf);
}
std::string mp::TableFormatter::format(const VersionReply& reply, const std::string& client_version) const
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "{:<12}{}\n", "multipass", client_version);
if (!reply.version().empty())
{
fmt::format_to(std::back_inserter(buf), "{:<12}{}\n", "multipassd", reply.version());
if (mp::cmd::update_available(reply.update_info()))
{
fmt::format_to(std::back_inserter(buf), "{}", mp::cmd::update_notice(reply.update_info()));
}
}
return fmt::to_string(buf);
}
std::string mp::TableFormatter::format(const mp::AliasDict& aliases) const
{
fmt::memory_buffer buf;
if (aliases.empty())
return "No aliases defined.\n";
auto width = [&aliases](const auto get_width, int header_width) -> int {
return mp::format::column_width(
aliases.cbegin(),
aliases.cend(),
[&, get_width](const auto& ctx) -> int {
return ctx.second.empty() ? 0
: get_width(*std::max_element(ctx.second.cbegin(),
ctx.second.cend(),
[&get_width](const auto& lhs, const auto& rhs) {
return get_width(lhs) < get_width(rhs);
}));
},
header_width);
};
const std::string alias_col_header = "Alias", instance_col_header = "Instance", command_col_header = "Command",
context_col_header = "Context", dir_col_header = "Working directory";
const std::string active_context = "*";
const auto alias_width =
width([](const auto& alias) -> int { return alias.first.length(); }, alias_col_header.length());
const auto instance_width =
width([](const auto& alias) -> int { return alias.second.instance.length(); }, instance_col_header.length());
const auto command_width =
width([](const auto& alias) -> int { return alias.second.command.length(); }, command_col_header.length());
const auto context_width = mp::format::column_width(
aliases.cbegin(),
aliases.cend(),
[&aliases, &active_context](const auto& alias) -> int {
return alias.first == aliases.active_context_name() && !aliases.get_active_context().empty()
? alias.first.length() + active_context.length()
: alias.first.length();
},
context_col_header.length());
const auto row_format = "{:<{}}{:<{}}{:<{}}{:<{}}{:<}\n";
fmt::format_to(std::back_inserter(buf),
row_format,
alias_col_header,
alias_width,
instance_col_header,
instance_width,
command_col_header,
command_width,
context_col_header,
context_width,
dir_col_header);
for (const auto& [context_name, context_contents] : sort_dict(aliases))
{
std::string shown_context =
context_name == aliases.active_context_name() ? context_name + active_context : context_name;
for (const auto& [name, def] : sort_dict(context_contents))
{
fmt::format_to(std::back_inserter(buf), row_format, name, alias_width, def.instance, instance_width,
def.command, command_width, shown_context, context_width, def.working_directory);
}
}
return fmt::to_string(buf);
}
| 22,266
|
C++
|
.cpp
| 466
| 36.598712
| 120
| 0.548812
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,822
|
json_formatter.cpp
|
canonical_multipass/src/client/cli/formatter/json_formatter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/client_common.h>
#include <multipass/cli/format_utils.h>
#include <multipass/cli/json_formatter.h>
#include <multipass/json_utils.h>
#include <multipass/utils.h>
#include <QJsonArray>
#include <QJsonObject>
namespace mp = multipass;
namespace
{
QJsonObject format_images(const google::protobuf::RepeatedPtrField<mp::FindReply_ImageInfo>& images_info)
{
QJsonObject images_obj;
for (const auto& image : images_info)
{
QJsonObject image_obj;
image_obj.insert("os", QString::fromStdString(image.os()));
image_obj.insert("release", QString::fromStdString(image.release()));
image_obj.insert("version", QString::fromStdString(image.version()));
QJsonArray aliases_arr;
auto aliases = image.aliases_info();
mp::format::filter_aliases(aliases);
for (auto alias = aliases.cbegin() + 1; alias != aliases.cend(); alias++)
aliases_arr.append(QString::fromStdString(alias->alias()));
image_obj.insert("aliases", aliases_arr);
image_obj.insert("remote", QString::fromStdString(aliases[0].remote_name()));
images_obj.insert(QString::fromStdString(mp::format::image_string_for(aliases[0])), image_obj);
}
return images_obj;
}
QJsonObject generate_snapshot_details(const mp::DetailedInfoItem& item)
{
const auto& snapshot_details = item.snapshot_info();
const auto& fundamentals = snapshot_details.fundamentals();
QJsonObject snapshot_info;
snapshot_info.insert("size", QString::fromStdString(snapshot_details.size()));
snapshot_info.insert("cpu_count", QString::fromStdString(item.cpu_count()));
snapshot_info.insert("disk_space", QString::fromStdString(item.disk_total()));
snapshot_info.insert("memory_size", QString::fromStdString(item.memory_total()));
QJsonObject mounts;
for (const auto& mount : item.mount_info().mount_paths())
{
QJsonObject entry;
entry.insert("source_path", QString::fromStdString(mount.source_path()));
mounts.insert(QString::fromStdString(mount.target_path()), entry);
}
snapshot_info.insert("mounts", mounts);
snapshot_info.insert(
"created",
QString::fromStdString(MP_FORMAT_UTILS.convert_to_user_locale(fundamentals.creation_timestamp())));
snapshot_info.insert("parent", QString::fromStdString(fundamentals.parent()));
QJsonArray children;
for (const auto& child : snapshot_details.children())
children.append(QString::fromStdString(child));
snapshot_info.insert("children", children);
snapshot_info.insert("comment", QString::fromStdString(fundamentals.comment()));
return snapshot_info;
}
QJsonObject generate_instance_details(const mp::DetailedInfoItem& item)
{
const auto& instance_details = item.instance_info();
QJsonObject instance_info;
instance_info.insert("state", QString::fromStdString(mp::format::status_string_for(item.instance_status())));
instance_info.insert("image_hash", QString::fromStdString(instance_details.id()));
instance_info.insert("image_release", QString::fromStdString(instance_details.image_release()));
instance_info.insert("release", QString::fromStdString(instance_details.current_release()));
instance_info.insert("cpu_count", QString::fromStdString(item.cpu_count()));
if (instance_details.has_num_snapshots())
instance_info.insert("snapshot_count", QString::number(instance_details.num_snapshots()));
QJsonArray load;
if (!instance_details.load().empty())
{
auto loads = mp::utils::split(instance_details.load(), " ");
for (const auto& entry : loads)
load.append(std::stod(entry));
}
instance_info.insert("load", load);
QJsonObject disks;
QJsonObject disk;
if (!instance_details.disk_usage().empty())
disk.insert("used", QString::fromStdString(instance_details.disk_usage()));
if (!item.disk_total().empty())
disk.insert("total", QString::fromStdString(item.disk_total()));
// TODO: disk name should come from daemon
disks.insert("sda1", disk);
instance_info.insert("disks", disks);
QJsonObject memory;
if (!instance_details.memory_usage().empty())
memory.insert("used", std::stoll(instance_details.memory_usage()));
if (!item.memory_total().empty())
memory.insert("total", std::stoll(item.memory_total()));
instance_info.insert("memory", memory);
QJsonArray ipv4_addrs;
for (const auto& ip : instance_details.ipv4())
ipv4_addrs.append(QString::fromStdString(ip));
instance_info.insert("ipv4", ipv4_addrs);
QJsonObject mounts;
for (const auto& mount : item.mount_info().mount_paths())
{
QJsonObject entry;
QJsonArray mount_uids;
QJsonArray mount_gids;
auto mount_maps = mount.mount_maps();
for (auto i = 0; i < mount_maps.uid_mappings_size(); ++i)
{
auto uid_map_pair = mount_maps.uid_mappings(i);
auto host_uid = uid_map_pair.host_id();
auto instance_uid = uid_map_pair.instance_id();
mount_uids.append(QString("%1:%2")
.arg(QString::number(host_uid))
.arg((instance_uid == mp::default_id) ? "default" : QString::number(instance_uid)));
}
for (auto i = 0; i < mount_maps.gid_mappings_size(); ++i)
{
auto gid_map_pair = mount_maps.gid_mappings(i);
auto host_gid = gid_map_pair.host_id();
auto instance_gid = gid_map_pair.instance_id();
mount_gids.append(QString("%1:%2")
.arg(QString::number(host_gid))
.arg((instance_gid == mp::default_id) ? "default" : QString::number(instance_gid)));
}
entry.insert("uid_mappings", mount_uids);
entry.insert("gid_mappings", mount_gids);
entry.insert("source_path", QString::fromStdString(mount.source_path()));
mounts.insert(QString::fromStdString(mount.target_path()), entry);
}
instance_info.insert("mounts", mounts);
return instance_info;
}
std::string generate_instances_list(const mp::InstancesList& instance_list)
{
QJsonObject list_json;
QJsonArray instances;
for (const auto& instance : instance_list.instances())
{
QJsonObject instance_obj;
instance_obj.insert("name", QString::fromStdString(instance.name()));
instance_obj.insert("state", QString::fromStdString(mp::format::status_string_for(instance.instance_status())));
QJsonArray ipv4_addrs;
for (const auto& ip : instance.ipv4())
ipv4_addrs.append(QString::fromStdString(ip));
instance_obj.insert("ipv4", ipv4_addrs);
instance_obj.insert("release",
QString::fromStdString(instance.current_release().empty()
? "Not Available"
: fmt::format("Ubuntu {}", instance.current_release())));
instances.append(instance_obj);
}
list_json.insert("list", instances);
return MP_JSONUTILS.json_to_string(list_json);
}
std::string generate_snapshots_list(const mp::SnapshotsList& snapshot_list)
{
QJsonObject info_json;
QJsonObject info_obj;
info_json.insert("errors", QJsonArray());
for (const auto& item : snapshot_list.snapshots())
{
const auto& snapshot = item.fundamentals();
QJsonObject snapshot_obj;
snapshot_obj.insert("parent", QString::fromStdString(snapshot.parent()));
snapshot_obj.insert("comment", QString::fromStdString(snapshot.comment()));
const auto& it = info_obj.find(QString::fromStdString(item.name()));
if (it == info_obj.end())
{
info_obj.insert(QString::fromStdString(item.name()),
QJsonObject{{QString::fromStdString(snapshot.snapshot_name()), snapshot_obj}});
}
else
{
QJsonObject obj = it.value().toObject();
obj.insert(QString::fromStdString(snapshot.snapshot_name()), snapshot_obj);
it.value() = obj;
}
}
info_json.insert("info", info_obj);
return MP_JSONUTILS.json_to_string(info_json);
}
} // namespace
std::string mp::JsonFormatter::format(const InfoReply& reply) const
{
QJsonObject info_json;
QJsonObject info_obj;
info_json.insert("errors", QJsonArray());
for (const auto& info : reply.details())
{
const auto& instance_it = info_obj.find(QString::fromStdString(info.name()));
if (info.has_instance_info())
{
auto instance_details = generate_instance_details(info);
// Nothing for the instance so far, so insert normally
if (instance_it == info_obj.end())
{
info_obj.insert(QString::fromStdString(info.name()), instance_details);
}
// Some instance details already exist, so merge the values
else
{
QJsonObject obj = instance_it.value().toObject();
for (const auto& key : instance_details.keys())
{
assert(obj.find(key) == obj.end() && "key already exists");
obj.insert(key, instance_details[key]);
}
instance_it.value() = obj;
}
}
else
{
assert(info.has_snapshot_info() && "either one of instance or snapshot details should be populated");
auto snapshot_details = generate_snapshot_details(info);
// Nothing for the instance so far, so create the "snapshots" node and put snapshot details there
if (instance_it == info_obj.end())
{
QJsonObject instance_obj, snapshot_obj;
snapshot_obj.insert(QString::fromStdString(info.snapshot_info().fundamentals().snapshot_name()),
snapshot_details);
instance_obj.insert("snapshots", snapshot_obj);
info_obj.insert(QString::fromStdString(info.name()), instance_obj);
}
// Some instance details already exist
else
{
auto instance_obj = instance_it.value().toObject();
auto snapshots_it = instance_obj.find("snapshots");
QJsonObject snapshots_obj =
snapshots_it == instance_obj.end() ? QJsonObject() : snapshots_it.value().toObject();
snapshots_obj.insert(QString::fromStdString(info.snapshot_info().fundamentals().snapshot_name()),
snapshot_details);
instance_obj.insert("snapshots", snapshots_obj);
instance_it.value() = instance_obj;
}
}
}
info_json.insert("info", info_obj);
return MP_JSONUTILS.json_to_string(info_json);
}
std::string mp::JsonFormatter::format(const ListReply& reply) const
{
std::string output;
if (reply.has_instance_list())
{
output = generate_instances_list(reply.instance_list());
}
else
{
assert(reply.has_snapshot_list() && "either one of the reports should be populated");
output = generate_snapshots_list(reply.snapshot_list());
}
return output;
}
std::string mp::JsonFormatter::format(const NetworksReply& reply) const
{
QJsonObject list_json;
QJsonArray interfaces;
for (const auto& interface : format::sorted(reply.interfaces()))
{
QJsonObject interface_obj;
interface_obj.insert("name", QString::fromStdString(interface.name()));
interface_obj.insert("type", QString::fromStdString(interface.type()));
interface_obj.insert("description", QString::fromStdString(interface.description()));
interfaces.append(interface_obj);
}
list_json.insert("list", interfaces);
return MP_JSONUTILS.json_to_string(list_json);
}
std::string mp::JsonFormatter::format(const FindReply& reply) const
{
QJsonObject find_json;
find_json.insert("errors", QJsonArray());
find_json.insert("blueprints", format_images(reply.blueprints_info()));
find_json.insert("images", format_images(reply.images_info()));
return MP_JSONUTILS.json_to_string(find_json);
}
std::string mp::JsonFormatter::format(const VersionReply& reply, const std::string& client_version) const
{
QJsonObject version_json;
version_json.insert("multipass", QString::fromStdString(client_version));
if (!reply.version().empty())
{
version_json.insert("multipassd", QString::fromStdString(reply.version()));
if (mp::cmd::update_available(reply.update_info()))
{
QJsonObject update;
update.insert("title", QString::fromStdString(reply.update_info().title()));
update.insert("description", QString::fromStdString(reply.update_info().description()));
update.insert("url", QString::fromStdString(reply.update_info().url()));
version_json.insert("update", update);
}
}
return MP_JSONUTILS.json_to_string(version_json);
}
std::string mp::JsonFormatter::format(const mp::AliasDict& aliases) const
{
return MP_JSONUTILS.json_to_string(aliases.to_json());
}
| 14,062
|
C++
|
.cpp
| 312
| 36.730769
| 120
| 0.643881
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,823
|
csv_formatter.cpp
|
canonical_multipass/src/client/cli/formatter/csv_formatter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/csv_formatter.h>
#include <multipass/cli/format_utils.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace
{
std::string format_images(const google::protobuf::RepeatedPtrField<mp::FindReply_ImageInfo>& images_info,
std::string type)
{
fmt::memory_buffer buf;
for (const auto& image : images_info)
{
auto aliases = image.aliases_info();
mp::format::filter_aliases(aliases);
auto image_id = aliases[0].remote_name().empty()
? aliases[0].alias()
: fmt::format("{}:{}", aliases[0].remote_name(), aliases[0].alias());
fmt::format_to(std::back_inserter(buf), "{},{},{},{},{},{},{}\n", image_id, aliases[0].remote_name(),
fmt::join(aliases.cbegin() + 1, aliases.cend(), ";"), image.os(), image.release(),
image.version(), type);
}
return fmt::to_string(buf);
}
std::string format_mounts(const mp::MountInfo& mount_info)
{
fmt::memory_buffer buf;
const auto& mount_paths = mount_info.mount_paths();
if (!mount_paths.size())
return {};
auto mount = mount_paths.cbegin();
for (; mount != --mount_paths.cend(); ++mount)
fmt::format_to(std::back_inserter(buf), "{} => {};", mount->source_path(), mount->target_path());
fmt::format_to(std::back_inserter(buf), "{} => {}", mount->source_path(), mount->target_path());
return fmt::to_string(buf);
}
std::string generate_snapshot_details(const mp::InfoReply reply)
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf),
"Snapshot,Instance,CPU(s),Disk space,Memory size,Mounts,Created,Parent,Children,Comment\n");
for (const auto& info : mp::format::sorted(reply.details()))
{
const auto& fundamentals = info.snapshot_info().fundamentals();
fmt::format_to(std::back_inserter(buf),
"{},{},{},{},{},",
fundamentals.snapshot_name(),
info.name(),
info.cpu_count(),
info.disk_total(),
info.memory_total());
fmt::format_to(std::back_inserter(buf), format_mounts(info.mount_info()));
fmt::format_to(std::back_inserter(buf),
",{},{},{},\"{}\"\n",
MP_FORMAT_UTILS.convert_to_user_locale(fundamentals.creation_timestamp()),
fundamentals.parent(),
fmt::join(info.snapshot_info().children(), ";"),
fundamentals.comment());
}
return fmt::to_string(buf);
}
std::string generate_instance_details(const mp::InfoReply reply)
{
assert(reply.details_size() && "shouldn't call this if there are not entries");
assert(reply.details(0).has_instance_info() &&
"outputting instance and snapshot details together is not supported in csv format");
auto have_num_snapshots = reply.details(0).instance_info().has_num_snapshots();
fmt::memory_buffer buf;
fmt::format_to(
std::back_inserter(buf),
"Name,State,Ipv4,Ipv6,Release,Image hash,Image release,Load,Disk usage,Disk total,Memory usage,Memory "
"total,Mounts,AllIPv4,CPU(s){}\n",
have_num_snapshots ? ",Snapshots" : "");
for (const auto& info : mp::format::sorted(reply.details()))
{
const auto& instance_details = info.instance_info();
fmt::format_to(std::back_inserter(buf),
"{},{},{},{},{},{},{},{},{},{},{},{},",
info.name(),
mp::format::status_string_for(info.instance_status()),
instance_details.ipv4_size() ? instance_details.ipv4(0) : "",
instance_details.ipv6_size() ? instance_details.ipv6(0) : "",
instance_details.current_release(),
instance_details.id(),
instance_details.image_release(),
instance_details.load(),
instance_details.disk_usage(),
info.disk_total(),
instance_details.memory_usage(),
info.memory_total());
fmt::format_to(std::back_inserter(buf), format_mounts(info.mount_info()));
fmt::format_to(std::back_inserter(buf), ",{},{}", fmt::join(instance_details.ipv4(), ";"), info.cpu_count());
fmt::format_to(std::back_inserter(buf),
"{}\n",
have_num_snapshots ? fmt::format(",{}", instance_details.num_snapshots()) : "");
}
return fmt::to_string(buf);
}
std::string generate_instances_list(const mp::InstancesList& instance_list)
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Name,State,IPv4,IPv6,Release,AllIPv4\n");
for (const auto& instance : mp::format::sorted(instance_list.instances()))
{
fmt::format_to(std::back_inserter(buf), "{},{},{},{},{},\"{}\"\n", instance.name(),
mp::format::status_string_for(instance.instance_status()),
instance.ipv4_size() ? instance.ipv4(0) : "", instance.ipv6_size() ? instance.ipv6(0) : "",
instance.current_release().empty() ? "Not Available"
: fmt::format("Ubuntu {}", instance.current_release()),
fmt::join(instance.ipv4(), ","));
}
return fmt::to_string(buf);
}
std::string generate_snapshots_list(const mp::SnapshotsList& snapshot_list)
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Instance,Snapshot,Parent,Comment\n");
for (const auto& item : mp::format::sorted(snapshot_list.snapshots()))
{
const auto& snapshot = item.fundamentals();
fmt::format_to(std::back_inserter(buf),
"{},{},{},\"{}\"\n",
item.name(),
snapshot.snapshot_name(),
snapshot.parent(),
snapshot.comment());
}
return fmt::to_string(buf);
}
} // namespace
std::string mp::CSVFormatter::format(const InfoReply& reply) const
{
std::string output;
if (reply.details_size() > 0)
{
if (reply.details()[0].has_instance_info())
output = generate_instance_details(reply);
else
output = generate_snapshot_details(reply);
}
return output;
}
std::string mp::CSVFormatter::format(const ListReply& reply) const
{
std::string output;
if (reply.has_instance_list())
{
output = generate_instances_list(reply.instance_list());
}
else
{
assert(reply.has_snapshot_list() && "either one of instances or snapshots should be populated");
output = generate_snapshots_list(reply.snapshot_list());
}
return output;
}
std::string mp::CSVFormatter::format(const NetworksReply& reply) const
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Name,Type,Description\n");
for (const auto& interface : format::sorted(reply.interfaces()))
{
// Quote the description because it can contain commas.
fmt::format_to(std::back_inserter(buf), "{},{},\"{}\"\n", interface.name(), interface.type(),
interface.description());
}
return fmt::to_string(buf);
}
std::string mp::CSVFormatter::format(const FindReply& reply) const
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Image,Remote,Aliases,OS,Release,Version,Type\n");
fmt::format_to(std::back_inserter(buf), format_images(reply.images_info(), "Cloud Image"));
fmt::format_to(std::back_inserter(buf), format_images(reply.blueprints_info(), "Blueprint"));
return fmt::to_string(buf);
}
std::string mp::CSVFormatter::format(const VersionReply& reply, const std::string& client_version) const
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Multipass,Multipassd,Title,Description,URL\n");
fmt::format_to(std::back_inserter(buf), "{},{},{},{},{}\n", client_version, reply.version(),
reply.update_info().title(), reply.update_info().description(), reply.update_info().url());
return fmt::to_string(buf);
}
std::string mp::CSVFormatter::format(const mp::AliasDict& aliases) const
{
fmt::memory_buffer buf;
fmt::format_to(std::back_inserter(buf), "Alias,Instance,Command,Working directory,Context\n");
for (const auto& [context_name, context_contents] : sort_dict(aliases))
{
std::string shown_context = context_name == aliases.active_context_name() ? context_name + "*" : context_name;
for (const auto& [name, def] : sort_dict(context_contents))
{
fmt::format_to(std::back_inserter(buf), "{},{},{},{},{}\n", name, def.instance, def.command,
def.working_directory, shown_context);
}
}
return fmt::to_string(buf);
}
| 9,730
|
C++
|
.cpp
| 214
| 36.271028
| 118
| 0.593509
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,828
|
dart_ffi.cpp
|
canonical_multipass/src/client/gui/ffi/dart_ffi.cpp
|
#include "multipass/dart_ffi.h"
#include "multipass/cli/client_common.h"
#include "multipass/logging/log.h"
#include "multipass/memory_size.h"
#include "multipass/name_generator.h"
#include "multipass/platform.h"
#include "multipass/settings/settings.h"
#include "multipass/standard_paths.h"
#include "multipass/utils.h"
#include "multipass/version.h"
#include <QStorageInfo>
namespace mp = multipass;
namespace mpc = multipass::client;
namespace mpl = multipass::logging;
namespace mcp = multipass::cli::platform;
constexpr auto category = "dart-ffi";
// clang-format off
extern "C"
{
// clang-format on
const char* multipass_version()
{
return mp::version_string;
}
char* generate_petname()
{
static constexpr auto error = "failed generating petname";
try
{
static mp::NameGenerator::UPtr generator = mp::make_default_name_generator();
const auto name = generator->make_name();
return strdup(name.c_str());
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return nullptr;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return nullptr;
}
}
char* get_server_address()
{
static constexpr auto error = "failed retrieving server address";
try
{
const auto address = mpc::get_server_address();
return strdup(address.c_str());
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return nullptr;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return nullptr;
}
}
struct KeyCertificatePair get_cert_pair()
{
static constexpr auto error = "failed retrieving certificate key pair";
try
{
const auto provider = mpc::get_cert_provider();
const auto cert = provider->PEM_certificate();
const auto key = provider->PEM_signing_key();
struct KeyCertificatePair pair
{
};
pair.pem_cert = strdup(cert.c_str());
pair.pem_priv_key = strdup(key.c_str());
return pair;
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return KeyCertificatePair{nullptr, nullptr};
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return KeyCertificatePair{nullptr, nullptr};
}
}
static std::once_flag initialize_settings_once_flag;
char* settings_file()
{
static constexpr auto error = "failed getting settings file";
try
{
const auto file_name = mpc::persistent_settings_filename().toStdString();
return strdup(file_name.c_str());
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return nullptr;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return nullptr;
}
}
enum SettingResult get_setting(char* key, char** output)
{
static constexpr auto error = "failed retrieving setting with key";
const QString key_string{key};
free(key);
try
{
std::call_once(initialize_settings_once_flag, mpc::register_global_settings_handlers);
const auto value = MP_SETTINGS.get(key_string).toStdString();
*output = strdup(value.c_str());
return SettingResult::Ok;
}
catch (const mp::UnrecognizedSettingException& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{} '{}': {}", error, key_string, e.what()));
*output = nullptr;
return SettingResult::KeyNotFound;
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{} '{}': {}", error, key_string, e.what()));
*output = strdup(e.what());
return SettingResult::UnexpectedError;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, fmt::format("{} '{}'", error, key_string));
*output = strdup("unknown error");
return SettingResult::UnexpectedError;
}
}
enum SettingResult set_setting(char* key, char* value, char** output)
{
static constexpr auto error = "failed storing setting with key";
const QString key_string{key};
free(key);
const QString value_string{value};
free(value);
try
{
std::call_once(initialize_settings_once_flag, mpc::register_global_settings_handlers);
MP_SETTINGS.set(key_string, value_string);
*output = nullptr;
return SettingResult::Ok;
}
catch (const mp::UnrecognizedSettingException& e)
{
mpl::log(mpl::Level::warning,
category,
fmt::format("{} '{}'='{}': {}", error, key_string, value_string, e.what()));
*output = nullptr;
return SettingResult::KeyNotFound;
}
catch (const mp::InvalidSettingException& e)
{
mpl::log(mpl::Level::warning,
category,
fmt::format("{} '{}'='{}': {}", error, key_string, value_string, e.what()));
*output = strdup(e.what());
return SettingResult::InvalidValue;
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning,
category,
fmt::format("{} '{}'='{}': {}", error, key_string, value_string, e.what()));
*output = strdup(e.what());
return SettingResult::UnexpectedError;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, fmt::format("{} '{}'='{}'", error, key_string, value_string));
*output = strdup("unknown error");
return SettingResult::UnexpectedError;
}
}
int uid()
{
return mcp::getuid();
}
int gid()
{
return mcp::getgid();
}
int default_id()
{
return mp::default_id;
}
long long memory_in_bytes(char* value)
{
static constexpr auto error = "failed converting memory to bytes";
try
{
std::string string_value{value};
free(value);
return mp::in_bytes(string_value);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return -1;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return -1;
}
}
const char* human_readable_memory(long long bytes)
{
const auto string = mp::MemorySize::from_bytes(bytes).human_readable(/*precision=*/2, /*trim_zeros=*/true);
return strdup(string.c_str());
}
long long get_total_disk_size()
{
const auto mp_storage = MP_PLATFORM.multipass_storage_location();
const auto location =
mp_storage.isEmpty() ? MP_STDPATHS.writableLocation(mp::StandardPaths::AppDataLocation) : mp_storage;
QStorageInfo storageInfo{location};
return storageInfo.bytesTotal();
}
char* default_mount_target(char* source)
{
static constexpr auto error = "failed retrieving default mount target";
try
{
const QString q_source{source};
free(source);
const auto target = MP_UTILS.default_mount_target(q_source).toStdString();
return strdup(target.c_str());
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{}: {}", error, e.what()));
return nullptr;
}
catch (...)
{
mpl::log(mpl::Level::warning, category, error);
return nullptr;
}
}
}
| 7,563
|
C++
|
.cpp
| 252
| 24.424603
| 111
| 0.619087
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,829
|
cloud_init_iso.cpp
|
canonical_multipass/src/iso/cloud_init_iso.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include <multipass/cloud_init_iso.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/yaml_node_utils.h>
#include <QFile>
#include <array>
#include <cctype>
namespace mp = multipass;
namespace mpu = multipass::utils;
// ISO9660 + Joliet Extension format
// ---------------------------------
// 32KB Reserved
// ---------------------------------
// Primary Volume Descriptor
// ---------------------------------
// Supplemental Volume Descriptor (Joliet extension)
// ---------------------------------
// Volume Descriptor Set Terminator
// ---------------------------------
// Path Tables pointing to dir records
// ---------------------------------
// "ISO9660 records"
// root directory record
// root parent directory record
// file record 1
// ...
// file record N
// ---------------------------------
// "Joliet" version of the same records but with UCS-2 character names for dirs/files
// root directory record
// root parent directory record
// file record 1
// ...
// file record N
// ---------------------------------
// data blocks
// ---------------------------------
namespace
{
constexpr auto logical_block_size = 2048u;
constexpr std::uint16_t operator"" _u16(unsigned long long v)
{
return static_cast<std::uint16_t>(v);
}
constexpr std::uint8_t operator"" _u8(unsigned long long v)
{
return static_cast<std::uint8_t>(v);
}
uint8_t to_u8(uint32_t value)
{
return static_cast<uint8_t>(value);
}
uint32_t to_u32(uint8_t value)
{
return static_cast<uint32_t>(value);
}
std::array<uint8_t, 8> to_lsb_msb(uint32_t value)
{
return {{to_u8(value),
to_u8(value >> 8u),
to_u8(value >> 16u),
to_u8(value >> 24u),
to_u8(value >> 24u),
to_u8(value >> 16u),
to_u8(value >> 8u),
to_u8(value)}};
}
std::array<uint8_t, 4> to_lsb_msb(uint16_t value)
{
return {{to_u8(value), to_u8(value >> 8u), to_u8(value >> 8u), to_u8(value)}};
}
std::array<uint8_t, 4> to_lsb(uint32_t value)
{
return {{to_u8(value), to_u8(value >> 8u), to_u8(value >> 16u), to_u8(value >> 24u)}};
}
bool is_system_little_endian()
{
uint32_t test_value = 1; // In memory: 01 00 00 00 (little endian) or 00 00 00 01 (big endian)
return *(reinterpret_cast<uint8_t*>(&test_value)) == 1; // Check the first byte
}
// std::array<uint8_t, 8> -> std::span<uint8_t, 8> when c++20 arrives
uint32_t from_lsb_msb(const std::array<uint8_t, 8>& bytes)
{
// replace the is_system_little_endian() function with std::endian::native == std::endian::little when C++20 arrives
return is_system_little_endian()
? to_u32(bytes[0]) | to_u32(bytes[1]) << 8u | to_u32(bytes[2]) << 16u | to_u32(bytes[3]) << 24u
: to_u32(bytes[4]) << 24u | to_u32(bytes[5]) << 16u | to_u32(bytes[6]) << 8u | to_u32(bytes[7]);
}
template <typename T, typename SizeType, typename V>
void set_at(T& t, SizeType offset, const V& value)
{
std::copy(std::begin(value), std::end(value), t.begin() + offset);
}
template <typename T>
void write(const T& t, QFile& f)
{
f.write(reinterpret_cast<const char*>(t.data.data()), t.data.size());
}
// The below three utility functions should serve as the abstraction layer for binary file reading, the
// std::vector<uint8_t>, std::array<uint8_t, N> and uint8_t should be the only ones to receive data because they
// indicate the nature of the data which is raw binary bytes.
std::vector<uint8_t> read_bytes_to_vec(std::ifstream& file, std::streampos pos, size_t size)
{
std::vector<uint8_t> buffer(size);
file.seekg(pos);
if (!MP_FILEOPS.read(file, reinterpret_cast<char*>(buffer.data()), size))
{
throw std::runtime_error(fmt::format("Can not read {} bytes data from file at {}.", size, std::streamoff(pos)));
}
return buffer;
}
template <size_t N>
std::array<uint8_t, N> read_bytes_to_array(std::ifstream& file, std::streampos pos)
{
std::array<uint8_t, N> buffer{};
file.seekg(pos);
if (!MP_FILEOPS.read(file, reinterpret_cast<char*>(buffer.data()), N))
{
throw std::runtime_error(fmt::format("Can not read {} bytes data from file at {}.", N, std::streamoff(pos)));
}
return buffer;
}
uint8_t read_single_byte(std::ifstream& file, std::streampos pos)
{
uint8_t data{};
file.seekg(pos);
if (!MP_FILEOPS.read(file, reinterpret_cast<char*>(&data), 1))
{
throw std::runtime_error(fmt::format("Can not read the next byte data from file at {}.", std::streamoff(pos)));
}
return data;
}
template <size_t size>
struct PaddedString
{
PaddedString() : data(size, ' ')
{
}
explicit PaddedString(const std::string& value) : PaddedString()
{
data.replace(0, value.size(), value);
}
auto begin() const
{
return data.begin();
}
auto end() const
{
return data.end();
}
std::string data;
};
template <size_t size>
struct U16PaddedString
{
U16PaddedString() : data(size, '\0')
{
for (size_t i = 1; i < size; i += 2)
{
data.at(i) = ' ';
}
}
explicit U16PaddedString(const std::string& value) : U16PaddedString()
{
auto it = value.begin();
for (size_t i = 1; i < size; i += 2)
{
if (it == value.end())
break;
data.at(i) = *it;
++it;
}
}
auto begin() const
{
return data.begin();
}
auto end() const
{
return data.end();
}
std::string data;
};
struct DecDateTime
{
DecDateTime() : data{}
{
std::fill_n(data.begin(), 16, '0');
}
std::array<uint8_t, 17> data;
};
struct RootDirRecord
{
enum class Type
{
root,
root_parent
};
RootDirRecord(Type type, uint32_t location) : data{}
{
data[0] = data.size();
set_at(data, 2, to_lsb_msb(location));
uint32_t block_size = logical_block_size;
set_at(data, 10, to_lsb_msb(block_size)); // size of entry (limited to one block)
data[25] = 0x02; // record is a directory entry
set_at(data, 28, to_lsb_msb(1_u16)); // vol seq #
data[32] = 1; // id_len length
data[33] = type == Type::root ? 0_u8 : 1_u8; // directory id
}
std::array<uint8_t, 34> data;
};
struct VolumeDescriptor
{
VolumeDescriptor() : data{}
{
set_at(data, 1, std::string("CD001")); // identifier
data[6] = 0x01; // volume descriptor version
}
void set_volume_size(uint32_t num_blocks)
{
set_at(data, 80, to_lsb_msb(num_blocks));
}
void set_root_dir_record(const RootDirRecord& record)
{
set_at(data, 156, record.data);
}
void set_path_table_info(uint32_t size, uint32_t location)
{
set_at(data, 132, to_lsb_msb(size));
set_at(data, 140, to_lsb(location));
}
void set_common_fields()
{
uint16_t block_size = logical_block_size;
set_at(data, 120, to_lsb_msb(1_u16)); // number of disks
set_at(data, 124, to_lsb_msb(1_u16)); // disk number
set_at(data, 128, to_lsb_msb(block_size)); // logical block size
DecDateTime no_date;
set_at(data, 813, no_date.data); // vol creation date-time
set_at(data, 830, no_date.data); // vol modification date-time
set_at(data, 847, no_date.data); // vol expiration date-time
set_at(data, 864, no_date.data); // vol effective date-time
data[881] = 0x01; // file structure version
}
std::array<uint8_t, logical_block_size> data;
};
struct VolumeDescriptorSetTerminator : VolumeDescriptor
{
VolumeDescriptorSetTerminator()
{
data[0] = 0xFF; // Terminator Type
}
};
struct PrimaryVolumeDescriptor : VolumeDescriptor
{
PrimaryVolumeDescriptor()
{
data[0] = 0x01; // primary volume descriptor type
set_at(data, 8, PaddedString<32>()); // System identifier
set_at(data, 40, PaddedString<32>("cidata")); // volume identifier
set_at(data, 190, PaddedString<623>()); // various ascii identifiers
set_common_fields();
}
};
struct JolietVolumeDescriptor : VolumeDescriptor
{
JolietVolumeDescriptor()
{
data[0] = 0x02; // supplementary volume descriptor type
set_at(data, 8, U16PaddedString<32>()); // System identifier
set_at(data, 40, U16PaddedString<32>("cidata")); // volume identifier
set_at(data, 190, U16PaddedString<623>()); // various UCS-2 identifiers
set_at(data, 88, std::array<uint8_t, 3>{{0x25, 0x2f, 0x45}}); // Joliet UCS-2 escape sequence
set_common_fields();
}
};
bool is_even(size_t size)
{
return (size % 2) == 0;
}
struct FileRecord
{
FileRecord() : data(33, 0u)
{
}
void set_fields(const std::string& name, uint32_t content_location, uint32_t size)
{
set_at(data, 2, to_lsb_msb(content_location)); // content block location
set_at(data, 10, to_lsb_msb(size)); // size of extent
data[25] = 0x00; // record is a file entry
set_at(data, 28, to_lsb_msb(1_u16)); // vol seq #
auto id_len = static_cast<uint8_t>(name.length());
data[32] = id_len;
auto pad_length = is_even(id_len) ? 1u : 0u;
data.resize(data.size() + id_len + pad_length);
set_at(data, 33, name);
data[0] = static_cast<uint8_t>(data.size());
}
std::vector<uint8_t> data;
};
auto make_iso_name(const std::string& name)
{
std::string iso_name{name};
std::transform(iso_name.begin(), iso_name.end(), iso_name.begin(), [](unsigned char c) { return std::toupper(c); });
std::transform(iso_name.begin(), iso_name.end(), iso_name.begin(),
[](unsigned char c) { return std::isalnum(c) ? c : '_'; });
if (iso_name.size() > 8)
iso_name = iso_name.substr(0, 8);
iso_name.append(".;1");
return iso_name;
}
struct ISOFileRecord : FileRecord
{
ISOFileRecord(const std::string& name, uint32_t content_location, uint32_t size)
{
set_fields(make_iso_name(name), content_location, size);
}
};
auto make_u16_name(const std::string& name)
{
std::string u16_name(name.size() * 2u, '\0');
const auto size = u16_name.size();
auto it = name.begin();
for (size_t i = 1; i < size; i += 2)
{
u16_name.at(i) = *it;
++it;
}
return u16_name;
}
std::string convert_u16_name_back(const std::string_view u16_name)
{
if (!is_even(u16_name.size()))
{
throw std::runtime_error(
fmt::format("The size of {} is not even, which does not conform to u16 name format.", u16_name.data()));
}
std::string original_name(u16_name.size() / 2, '\0');
for (size_t i = 0; i < original_name.size(); ++i)
{
original_name[i] = u16_name[i * 2 + 1];
}
return original_name;
}
struct JolietFileRecord : FileRecord
{
JolietFileRecord(const std::string& name, uint32_t content_location, uint32_t size)
{
set_fields(make_u16_name(name), content_location, size);
}
};
struct RootPathTable
{
explicit RootPathTable(uint32_t dir_record_location)
{
data[0] = 0x1; // dir id len (root id len is 1)
set_at(data, 2, to_lsb(dir_record_location));
data[6] = 0x01; // dir # of parent dir
data[8] = 0x00; // dir id (0x00 = root)
}
std::array<uint8_t, 10> data{};
};
template <typename Size>
Size num_blocks(Size num_bytes)
{
return ((num_bytes + logical_block_size - 1) / logical_block_size);
}
void seek_to_next_block(QFile& f)
{
const auto next_block_pos = num_blocks(f.pos()) * logical_block_size;
f.seek(next_block_pos);
}
void pad_to_end(QFile& f)
{
seek_to_next_block(f);
f.seek(f.pos() - 1);
char end = 0;
f.write(&end, 1);
}
} // namespace
void mp::CloudInitIso::add_file(const std::string& name, const std::string& data)
{
files.push_back(FileEntry{name, data});
}
bool mp::CloudInitIso::contains(const std::string& name) const
{
return std::find_if(files.cbegin(), files.cend(), [name](const FileEntry& file_entry) -> bool {
return file_entry.name == name;
}) != std::cend(files);
}
const std::string& mp::CloudInitIso::at(const std::string& name) const
{
if (auto iter = std::find_if(files.cbegin(),
files.cend(),
[name](const FileEntry& file_entry) -> bool { return file_entry.name == name; });
iter == std::cend(files))
{
throw std::runtime_error(fmt::format("Did not find the target file {} in the CloudInitIso instance.", name));
}
else
{
return iter->data;
}
}
std::string& mp::CloudInitIso::at(const std::string& name)
{
return const_cast<std::string&>(const_cast<const mp::CloudInitIso*>(this)->at(name));
}
std::string& mp::CloudInitIso::operator[](const std::string& name)
{
if (auto iter = std::find_if(files.begin(),
files.end(),
[name](const FileEntry& file_entry) -> bool { return file_entry.name == name; });
iter == std::end(files))
{
return files.emplace_back(FileEntry{name, std::string()}).data;
}
else
{
return iter->data;
}
}
bool mp::CloudInitIso::erase(const std::string& name)
{
if (auto iter = std::find_if(files.cbegin(),
files.cend(),
[name](const FileEntry& file_entry) -> bool { return file_entry.name == name; });
iter != std::cend((files)))
{
files.erase(iter);
return true;
}
return false;
}
void mp::CloudInitIso::write_to(const Path& path)
{
QFile f{path};
if (!f.open(QIODevice::WriteOnly))
throw std::runtime_error{fmt::format(
"Failed to open file for writing during cloud-init generation: {}; path: {}", f.errorString(), path)};
const uint32_t num_reserved_bytes = 32768u;
const uint32_t num_reserved_blocks = num_blocks(num_reserved_bytes);
f.seek(num_reserved_bytes);
PrimaryVolumeDescriptor prim_desc;
JolietVolumeDescriptor joliet_desc;
const uint32_t num_blocks_for_descriptors = 3u;
const uint32_t num_blocks_for_path_table = 2u;
const uint32_t num_blocks_for_dir_records = 2u;
auto volume_size =
num_reserved_blocks + num_blocks_for_descriptors + num_blocks_for_path_table + num_blocks_for_dir_records;
for (const auto& entry : files)
{
volume_size += num_blocks(entry.data.size());
}
prim_desc.set_volume_size(volume_size);
joliet_desc.set_volume_size(volume_size);
uint32_t current_block_index = num_reserved_blocks + num_blocks_for_descriptors;
// The following records are simply to specify that a root filesystem exists
RootPathTable root_path{current_block_index + num_blocks_for_path_table};
prim_desc.set_path_table_info(root_path.data.size(), current_block_index);
++current_block_index;
RootPathTable joliet_root_path{current_block_index + num_blocks_for_path_table};
joliet_desc.set_path_table_info(joliet_root_path.data.size(), current_block_index);
++current_block_index;
RootDirRecord root_record{RootDirRecord::Type::root, current_block_index};
RootDirRecord root_parent_record{RootDirRecord::Type::root_parent, current_block_index};
prim_desc.set_root_dir_record(root_record);
++current_block_index;
RootDirRecord joliet_root_record{RootDirRecord::Type::root, current_block_index};
RootDirRecord joliet_root_parent_record{RootDirRecord::Type::root_parent, current_block_index};
joliet_desc.set_root_dir_record(joliet_root_record);
++current_block_index;
std::vector<ISOFileRecord> iso_file_records;
std::vector<JolietFileRecord> joliet_file_records;
for (const auto& entry : files)
{
iso_file_records.emplace_back(entry.name, current_block_index, entry.data.size());
joliet_file_records.emplace_back(entry.name, current_block_index, entry.data.size());
current_block_index += num_blocks(entry.data.size());
}
write(prim_desc, f);
write(joliet_desc, f);
write(VolumeDescriptorSetTerminator(), f);
write(root_path, f);
seek_to_next_block(f);
write(joliet_root_path, f);
seek_to_next_block(f);
write(root_record, f);
write(root_parent_record, f);
for (const auto& iso_record : iso_file_records)
{
write(iso_record, f);
}
seek_to_next_block(f);
write(joliet_root_record, f);
write(joliet_root_parent_record, f);
for (const auto& joliet_record : joliet_file_records)
{
write(joliet_record, f);
}
seek_to_next_block(f);
for (const auto& entry : files)
{
f.write(entry.data.data(), entry.data.size());
seek_to_next_block(f);
}
pad_to_end(f);
}
void mp::CloudInitIso::read_from(const std::filesystem::path& fs_path)
{
// Please refer to the cloud_Init_Iso_read_me.md file for the preliminaries and the thought process of the
// implementation
std::ifstream iso_file{fs_path, std::ios_base::in | std::ios::binary};
if (!MP_FILEOPS.is_open(iso_file))
{
throw std::runtime_error{
fmt::format(R"("Failed to open file "{}" for reading: {}.")", fs_path.string(), strerror(errno))};
}
const uint32_t num_reserved_bytes = 32768u; // 16 data blocks, 32kb
const uint32_t joliet_des_start_pos = num_reserved_bytes + sizeof(PrimaryVolumeDescriptor);
if (read_single_byte(iso_file, joliet_des_start_pos) != 2_u8)
{
throw std::runtime_error("The Joliet volume descriptor is not in place.");
}
const std::array<uint8_t, 5> volume_identifier = read_bytes_to_array<5>(iso_file, joliet_des_start_pos + 1u);
if (std::string_view(reinterpret_cast<const char*>(volume_identifier.data()), volume_identifier.size()) != "CD001")
{
throw std::runtime_error("The Joliet descriptor is malformed.");
}
const uint32_t root_dir_record_data_start_pos = joliet_des_start_pos + 156u;
const std::array<uint8_t, 34> root_dir_record_data =
read_bytes_to_array<34>(iso_file, root_dir_record_data_start_pos);
// size of the data should 34, record is a directory entry and directory is a root directory instead of a root
// parent directory
if (root_dir_record_data[0] != 34_u8 || root_dir_record_data[25] != 2_u8 || root_dir_record_data[33] != 0_u8)
{
throw std::runtime_error("The root directory record data is malformed.");
}
// Use std::span when C++20 arrives to avoid the copy of the std::array<uint8_t, 8>
std::array<uint8_t, 8> root_dir_record_data_location_lsb_bytes;
// location lsb_msb bytes starts from 2
std::copy_n(root_dir_record_data.cbegin() + 2u, 8, root_dir_record_data_location_lsb_bytes.begin());
const uint32_t root_dir_record_data_location_by_blocks = from_lsb_msb(root_dir_record_data_location_lsb_bytes);
const uint32_t file_records_start_pos = root_dir_record_data_location_by_blocks * logical_block_size +
2u * sizeof(RootDirRecord); // total size of root dir and root dir parent
uint32_t current_file_record_start_pos = file_records_start_pos;
while (true)
{
const uint8_t file_record_data_size = read_single_byte(iso_file, current_file_record_start_pos);
if (file_record_data_size == 0_u8)
{
break;
}
// In each iteration, the file record provides the size and location of the extent. Initially, we utilize this
// information to navigate to and read the file data. Subsequently, we return to the file record to extract the
// file name.
const uint32_t file_content_location_by_blocks =
from_lsb_msb(read_bytes_to_array<8>(iso_file, current_file_record_start_pos + 2u));
const uint32_t file_content_size =
from_lsb_msb(read_bytes_to_array<8>(iso_file, current_file_record_start_pos + 10u));
const std::vector<uint8_t> file_content =
read_bytes_to_vec(iso_file, file_content_location_by_blocks * logical_block_size, file_content_size);
const uint32_t file_name_length_start_pos = current_file_record_start_pos + 32u;
const uint8_t encoded_file_name_length = read_single_byte(iso_file, file_name_length_start_pos);
const uint32_t file_name_start_pos = file_name_length_start_pos + 1u;
const std::vector<uint8_t> encoded_file_name =
read_bytes_to_vec(iso_file, file_name_start_pos, to_u32(encoded_file_name_length));
const std::string original_file_name = convert_u16_name_back(
std::string_view{reinterpret_cast<const char*>(encoded_file_name.data()), encoded_file_name.size()});
files.emplace_back(FileEntry{original_file_name, std::string{file_content.cbegin(), file_content.cend()}});
current_file_record_start_pos += to_u32(file_record_data_size);
}
}
mp::CloudInitFileOps::CloudInitFileOps(const Singleton<CloudInitFileOps>::PrivatePass& pass) noexcept
: Singleton<CloudInitFileOps>::Singleton{pass}
{
}
void mp::CloudInitFileOps::update_cloud_init_with_new_extra_interfaces_and_new_id(
const std::string& default_mac_addr,
const std::vector<NetworkInterface>& extra_interfaces,
const std::string& new_instance_id,
const std::filesystem::path& cloud_init_path) const
{
CloudInitIso iso_file;
iso_file.read_from(cloud_init_path);
std::string& meta_data_file_content = iso_file.at("meta-data");
meta_data_file_content =
mpu::emit_cloud_config(mpu::make_cloud_init_meta_config_with_id_tweak(meta_data_file_content, new_instance_id));
// overwrite the whole network-config file content
iso_file["network-config"] =
mpu::emit_cloud_config(mpu::make_cloud_init_network_config(default_mac_addr, extra_interfaces));
iso_file.write_to(QString::fromStdString(cloud_init_path.string()));
}
void mp::CloudInitFileOps::update_cloned_cloud_init_unique_identifiers(
const std::string& default_mac_addr,
const std::vector<NetworkInterface>& extra_interfaces,
const std::string& new_hostname,
const std::filesystem::path& cloud_init_path) const
{
CloudInitIso iso_file;
iso_file.read_from(cloud_init_path);
std::string& meta_data_file_content = iso_file.at("meta-data");
meta_data_file_content =
mpu::emit_cloud_config(mpu::make_cloud_init_meta_config(new_hostname, meta_data_file_content));
std::string& network_config_file_content = iso_file["network-config"];
network_config_file_content = mpu::emit_cloud_config(
mpu::make_cloud_init_network_config(default_mac_addr, extra_interfaces, network_config_file_content));
iso_file.write_to(QString::fromStdString(cloud_init_path.string()));
}
void mp::CloudInitFileOps::add_extra_interface_to_cloud_init(const std::string& default_mac_addr,
const NetworkInterface& extra_interface,
const std::filesystem::path& cloud_init_path) const
{
CloudInitIso iso_file;
iso_file.read_from(cloud_init_path);
std::string& meta_data_file_content = iso_file.at("meta-data");
meta_data_file_content =
mpu::emit_cloud_config(mpu::make_cloud_init_meta_config_with_id_tweak(meta_data_file_content));
iso_file["network-config"] = mpu::emit_cloud_config(
mpu::add_extra_interface_to_network_config(default_mac_addr, extra_interface, iso_file["network-config"]));
iso_file.write_to(QString::fromStdString(cloud_init_path.string()));
}
std::string mp::CloudInitFileOps::get_instance_id_from_cloud_init(const std::filesystem::path& cloud_init_path) const
{
CloudInitIso iso_file;
iso_file.read_from(cloud_init_path);
const std::string& meta_data_file_content = iso_file.at("meta-data");
const auto meta_data_node = YAML::Load(meta_data_file_content);
return meta_data_node["instance-id"].as<std::string>();
}
| 25,093
|
C++
|
.cpp
| 648
| 33.17284
| 120
| 0.634439
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,835
|
update_prompt.h
|
canonical_multipass/include/multipass/update_prompt.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_UPDATE_PROMPT_H
#define MULTIPASS_UPDATE_PROMPT_H
#include <memory>
namespace multipass
{
class UpdateInfo;
class UpdatePrompt
{
public:
using UPtr = std::unique_ptr<UpdatePrompt>;
virtual ~UpdatePrompt() = default;
virtual bool is_time_to_show() = 0;
virtual void populate(UpdateInfo *update_info) = 0;
virtual void populate_if_time_to_show(UpdateInfo *update_info) = 0;
};
} // namespace multipass
#endif // MULTIPASS_UPDATE_PROMPT_H
| 1,108
|
C++
|
.h
| 33
| 31.333333
| 72
| 0.753976
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,836
|
vm_blueprint_provider.h
|
canonical_multipass/include/multipass/vm_blueprint_provider.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VM_BLUEPRINT_PROVIDER_H
#define MULTIPASS_VM_BLUEPRINT_PROVIDER_H
#include "client_launch_data.h"
#include "disabled_copy_move.h"
#include "query.h"
#include "virtual_machine_description.h"
#include "vm_image_info.h"
#include <optional>
#include <string>
#include <vector>
namespace multipass
{
class VMBlueprintProvider : private DisabledCopyMove
{
public:
virtual ~VMBlueprintProvider() = default;
virtual Query fetch_blueprint_for(const std::string& blueprint_name, VirtualMachineDescription& vm_desc,
ClientLaunchData& client_launch_data) = 0;
virtual Query blueprint_from_file(const std::string& path, const std::string& blueprint_name,
VirtualMachineDescription& vm_desc, ClientLaunchData& client_launch_data) = 0;
virtual std::optional<VMImageInfo> info_for(const std::string& blueprint_name) = 0;
virtual std::vector<VMImageInfo> all_blueprints() = 0;
virtual std::string name_from_blueprint(const std::string& blueprint_name) = 0;
virtual int blueprint_timeout(const std::string& blueprint_name) = 0;
protected:
VMBlueprintProvider() = default;
};
} // namespace multipass
#endif // MULTIPASS_VM_BLUEPRINT_PROVIDER_H
| 1,886
|
C++
|
.h
| 45
| 38.044444
| 116
| 0.737875
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,837
|
auto_join_thread.h
|
canonical_multipass/include/multipass/auto_join_thread.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 3, as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
* SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*/
#ifndef MULTIPASS_AUTO_JOIN_THREAD_H
#define MULTIPASS_AUTO_JOIN_THREAD_H
#include <memory>
#include <thread>
namespace multipass
{
struct AutoJoinThread
{
template <typename Callable, typename... Args>
AutoJoinThread(Callable&& f, Args&&... args) : thread{std::forward<Callable>(f), std::forward<Args>(args)...}
{
}
~AutoJoinThread()
{
if (thread.joinable())
thread.join();
}
std::thread thread;
};
} // namespace multipass
#endif // MULTIPASS_AUTO_JOIN_THREAD_H
| 1,261
|
C++
|
.h
| 38
| 30.210526
| 113
| 0.728618
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,839
|
network_access_manager.h
|
canonical_multipass/include/multipass/network_access_manager.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_NETWORK_ACCESS_MANAGER_H
#define MULTIPASS_NETWORK_ACCESS_MANAGER_H
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <memory>
namespace multipass
{
class NetworkAccessManager : public QNetworkAccessManager
{
Q_OBJECT
public:
using UPtr = std::unique_ptr<NetworkAccessManager>;
NetworkAccessManager(QObject* parent = nullptr);
protected:
QNetworkReply* createRequest(Operation op, const QNetworkRequest& orig_request,
QIODevice* outgoingData = nullptr) override;
};
} // namespace multipass
#endif // MULTIPASS_NETWORK_ACCESS_MANAGER_H
| 1,258
|
C++
|
.h
| 35
| 32.885714
| 83
| 0.76214
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,840
|
client_launch_data.h
|
canonical_multipass/include/multipass/client_launch_data.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_CLIENT_LAUNCH_DATA_H
#define MULTIPASS_CLIENT_LAUNCH_DATA_H
#include "alias_definition.h"
#include <string>
#include <vector>
namespace multipass
{
struct ClientLaunchData
{
AliasContext aliases_to_be_created;
std::vector<std::string> workspaces_to_be_created;
};
} // namespace multipass
#endif // MULTIPASS_CLIENT_LAUNCH_DATA_H
| 989
|
C++
|
.h
| 30
| 31.033333
| 72
| 0.767296
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,841
|
sshfs_server_config.h
|
canonical_multipass/include/multipass/sshfs_server_config.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_SSHFS_SERVER_CONFIG_H
#define MULTIPASS_SSHFS_SERVER_CONFIG_H
#include <multipass/id_mappings.h>
#include <string>
#include <unordered_map>
namespace multipass
{
struct SSHFSServerConfig
{
std::string host;
int port;
std::string username;
std::string instance;
std::string private_key;
std::string source_path;
std::string target_path;
id_mappings gid_mappings;
id_mappings uid_mappings;
};
} // namespace multipass
#endif // MULTIPASS_SSHFS_SERVER_CONFIG_H
| 1,146
|
C++
|
.h
| 37
| 28.432432
| 72
| 0.752493
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,842
|
posix.h
|
canonical_multipass/include/multipass/posix.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_POSIX_H
#define MULTIPASS_POSIX_H
#ifdef MULTIPASS_PLATFORM_WINDOWS
#include <io.h>
#else
#include <unistd.h>
#endif
#endif // MULTIPASS_POSIX_H
| 794
|
C++
|
.h
| 24
| 31.333333
| 72
| 0.762712
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,843
|
cert_provider.h
|
canonical_multipass/include/multipass/cert_provider.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_CERTPROVIDER_H
#define MULTIPASS_CERTPROVIDER_H
#include "disabled_copy_move.h"
#include <string>
namespace multipass
{
class CertProvider : private DisabledCopyMove
{
public:
virtual ~CertProvider() = default;
virtual std::string PEM_certificate() const = 0;
virtual std::string PEM_signing_key() const = 0;
protected:
CertProvider() = default;
};
} // namespace multipass
#endif // MULTIPASS_CERTPROVIDER_H
| 1,076
|
C++
|
.h
| 33
| 30.515152
| 72
| 0.759152
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,844
|
singleton.h
|
canonical_multipass/include/multipass/singleton.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_SINGLETON_H
#define MULTIPASS_SINGLETON_H
#include "disabled_copy_move.h"
#include "private_pass_provider.h"
#include <memory>
#include <mutex>
#include <type_traits>
namespace multipass
{
// A mockable singleton. To use, inherit (publicly) using the CRTP idiom
template <typename T>
class Singleton : public PrivatePassProvider<Singleton<T>>, private DisabledCopyMove
{
public:
using Base = PrivatePassProvider<Singleton<T>>;
using PrivatePass = typename Base::PrivatePass;
constexpr Singleton(const PrivatePass&) noexcept;
virtual ~Singleton() noexcept = default;
static T& instance() noexcept(noexcept(T(Base::pass)));
protected:
template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
static void mock() noexcept(noexcept(U(Base::pass))); // only works if instance not called yet, or after reset
static void reset() noexcept; // not thread-safe, make sure no other threads using this singleton anymore!
private:
template <typename U>
static void init() noexcept(noexcept(U(Base::pass)));
static std::unique_ptr<std::once_flag> once;
static std::unique_ptr<T> single;
};
} // namespace multipass
template <typename T>
inline constexpr multipass::Singleton<T>::Singleton(const multipass::Singleton<T>::PrivatePass&) noexcept
{
}
template <typename T>
std::unique_ptr<std::once_flag> multipass::Singleton<T>::once = std::make_unique<std::once_flag>();
template <typename T>
std::unique_ptr<T> multipass::Singleton<T>::single = nullptr;
template <typename T>
template <typename U, typename>
inline void multipass::Singleton<T>::mock() noexcept(noexcept(U(Base::pass)))
{
init<U>();
}
template <typename T>
inline T& multipass::Singleton<T>::instance() noexcept(noexcept(T(Base::pass)))
{
init<T>();
return *single;
}
template <typename T>
inline void multipass::Singleton<T>::reset() noexcept
{
once = std::make_unique<std::once_flag>(); // flag itself not assignable, so we use a ptr
single.reset(nullptr);
}
template <typename T>
template <typename U>
inline void multipass::Singleton<T>::init() noexcept(noexcept(U(Base::pass)))
{
std::call_once(*once, [] { single = std::make_unique<U>(Base::pass); });
}
#endif // MULTIPASS_SINGLETON_H
| 2,902
|
C++
|
.h
| 79
| 34.405063
| 114
| 0.74082
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,845
|
utils.h
|
canonical_multipass/include/multipass/utils.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_UTILS_H
#define MULTIPASS_UTILS_H
#include <multipass/logging/level.h>
#include <multipass/network_interface_info.h>
#include <multipass/path.h>
#include <multipass/singleton.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/virtual_machine.h>
#include <yaml-cpp/yaml.h>
#include <chrono>
#include <functional>
#include <future>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <QDir>
#include <QString>
#include <QStringList>
#include <QTemporaryFile>
#include <QVariant>
#define MP_UTILS multipass::Utils::instance()
namespace multipass
{
// Fwd decl
class VirtualMachine;
namespace utils
{
// enum types
enum class QuoteType
{
no_quotes,
quote_every_arg
};
enum class TimeoutAction
{
retry,
done
};
// filesystem and path helpers
QDir base_dir(const QString& path);
bool is_dir(const std::string& path);
QString backend_directory_path(const Path& path, const QString& subdirectory);
std::string filename_for(const std::string& path);
std::string contents_of(const multipass::Path& file_path);
bool invalid_target_path(const QString& target_path);
QTemporaryFile create_temp_file_with_path(const QString& filename_template);
void remove_directories(const std::vector<QString>& dirs);
// filesystem mount helpers
void make_target_dir(SSHSession& session, const std::string& root, const std::string& relative_target);
void set_owner_for(SSHSession& session, const std::string& root, const std::string& relative_target, int vm_user,
int vm_group);
std::string get_resolved_target(SSHSession& session, const std::string& target);
std::pair<std::string, std::string> get_path_split(SSHSession& session, const std::string& target);
// special-file helpers
void check_and_create_config_file(const QString& config_file_path);
// command and process helpers
std::string to_cmd(const std::vector<std::string>& args, QuoteType type);
void process_throw_on_error(const QString& program, const QStringList& arguments, const QString& message,
const QString& category = "utils", const int timeout = 30000);
bool process_log_on_error(const QString& program, const QStringList& arguments, const QString& message,
const QString& category, multipass::logging::Level level = multipass::logging::Level::debug,
const int timeout = 30000);
// networking helpers
void validate_server_address(const std::string& value);
bool valid_hostname(const std::string& name_string);
std::string generate_mac_address();
bool valid_mac_address(const std::string& mac);
std::optional<NetworkInterfaceInfo> find_bridge_with(const std::vector<NetworkInterfaceInfo>& networks,
const std::string& target_network,
const std::string& bridge_type);
// string helpers
bool has_only_digits(const std::string& value);
template <typename Str, typename Filter>
Str&& trim_begin(Str&& s, Filter&& filter);
template <typename Str>
Str&& trim_begin(Str&& s);
template <typename Str, typename Filter>
Str&& trim_end(Str&& s, Filter&& filter);
template <typename Str>
Str&& trim_end(Str&& s);
template <typename Str, typename Filter>
Str&& trim(Str&& s, Filter&& filter);
template <typename Str>
Str&& trim(Str&& s);
std::string& trim_newline(std::string& s);
std::string escape_char(const std::string& s, char c);
std::string escape_for_shell(const std::string& s);
std::vector<std::string> split(const std::string& string, const std::string& delimiter);
std::string match_line_for(const std::string& output, const std::string& matcher);
// enum helpers
template <typename RegisteredQtEnum>
QString qenum_to_qstring(RegisteredQtEnum val);
template <typename RegisteredQtEnum>
std::string qenum_to_string(RegisteredQtEnum val);
// other helpers
QString get_multipass_storage();
QString make_uuid(const std::optional<std::string>& seed = std::nullopt);
template <typename OnTimeoutCallable, typename TryAction, typename... Args>
void try_action_for(OnTimeoutCallable&& on_timeout, std::chrono::milliseconds timeout, TryAction&& try_action,
Args&&... args);
template <typename T>
bool is_default_constructed(const T& input_type)
{
return input_type == T{};
}
// simplified parallel transform, it takes a std container and a unary operation and
// returns a std::vector<OutputValueType> where the OutputValueType is the unary operation return type
// There are two options of the return types, one is the one below and the other one is auto. Eventually, I went with
// the std::invoke_result_t based one because it makes the function signature more expressive despite the fact that it
// makes std::invoke_result_t<std::decay_t<UnaryOperation>, InputValueType> code duplicate.
template <typename Container, typename UnaryOperation>
std::vector<std::invoke_result_t<std::decay_t<UnaryOperation>, typename Container::value_type>>
parallel_transform(const Container& input_container, UnaryOperation&& unary_op)
{
using InputValueType = typename Container::value_type;
using OutputValueType = std::invoke_result_t<std::decay_t<UnaryOperation>, InputValueType>;
const auto num_elements = input_container.size();
// Pre-allocate space for futures
std::vector<std::future<OutputValueType>> futures(num_elements);
int index = 0;
for (const auto& item : input_container)
{
futures[index++] = std::async(std::launch::async, unary_op, std::cref(item));
}
std::vector<OutputValueType> results;
for (auto& fut : futures)
{
auto item = fut.get();
if (!is_default_constructed(item))
{
results.emplace_back(std::move(item));
}
}
return results;
}
template <typename Container, typename UnaryOperation>
void parallel_for_each(Container& input_container, UnaryOperation&& unary_op)
{
const auto num_elements = input_container.size();
std::vector<std::future<void>> empty_futures;
empty_futures.reserve(num_elements);
for (auto& item : input_container)
{
empty_futures.emplace_back(std::async(std::launch::async, unary_op, std::ref(item)));
}
for (auto& empty_future : empty_futures)
{
empty_future.get();
}
}
} // namespace utils
class Utils : public Singleton<Utils>
{
public:
Utils(const Singleton<Utils>::PrivatePass&) noexcept;
virtual qint64 filesystem_bytes_available(const QString& data_directory) const;
virtual void exit(int code);
virtual std::string contents_of(const multipass::Path& file_path) const;
virtual void make_file_with_content(const std::string& file_name, const std::string& content,
const bool& overwrite = false);
virtual Path make_dir(const QDir& a_dir, const QString& name,
QFileDevice::Permissions permissions = QFileDevice::Permissions(0));
virtual Path make_dir(const QDir& dir, QFileDevice::Permissions permissions = QFileDevice::Permissions(0));
// command and process helpers
virtual std::string run_cmd_for_output(const QString& cmd, const QStringList& args,
const int timeout = 30000) const;
virtual bool run_cmd_for_status(const QString& cmd, const QStringList& args, const int timeout = 30000) const;
virtual Path derive_instances_dir(const Path& data_dir,
const Path& backend_directory_name,
const Path& instances_subdir) const;
// system info helpers
virtual std::string get_kernel_version() const;
// scrypt hash generator
virtual QString generate_scrypt_hash_for(const QString& passphrase) const;
// virtual machine helpers
[[nodiscard]] virtual bool is_running(const VirtualMachine::State& state) const;
virtual std::string run_in_ssh_session(SSHSession& session, const std::string& cmd, bool whisper = false) const;
// various
virtual std::vector<uint8_t> random_bytes(size_t len);
virtual QString make_uuid(const std::optional<std::string>& seed = std::nullopt) const;
virtual void sleep_for(const std::chrono::milliseconds& ms) const;
virtual bool is_ipv4_valid(const std::string& ipv4) const;
virtual Path default_mount_target(const Path& source) const;
};
} // namespace multipass
namespace multipass::utils::detail
{
// see https://en.cppreference.com/w/cpp/string/byte/isspace#Notes
inline constexpr auto is_space = [](unsigned char c) { return std::isspace(c); };
} // namespace multipass::utils::detail
template <typename Str, typename Filter>
Str&& multipass::utils::trim_begin(Str&& s, Filter&& filter)
{
const auto it = std::find_if_not(s.begin(), s.end(), std::forward<Filter>(filter));
s.erase(s.begin(), it);
return std::forward<Str>(s);
}
template <typename Str>
Str&& multipass::utils::trim_begin(Str&& s)
{
return trim_begin(std::forward<Str>(s), detail::is_space);
}
template <typename Str, typename Filter>
Str&& multipass::utils::trim_end(Str&& s, Filter&& filter)
{
auto rev_it = std::find_if_not(s.rbegin(), s.rend(), std::forward<Filter>(filter));
s.erase(rev_it.base(), s.end());
return std::forward<Str>(s);
}
template <typename Str>
Str&& multipass::utils::trim_end(Str&& s)
{
return trim_end(std::forward<Str>(s), detail::is_space);
}
template <typename Str, typename Filter>
Str&& multipass::utils::trim(Str&& s, Filter&& filter)
{
auto&& ret = trim_end(std::forward<Str>(s), filter);
return trim_begin(std::forward<decltype(ret)>(ret), std::forward<Filter>(filter));
}
template <typename Str>
Str&& multipass::utils::trim(Str&& s)
{
return trim(std::forward<Str>(s), detail::is_space);
}
template <typename OnTimeoutCallable, typename TryAction, typename... Args>
void multipass::utils::try_action_for(OnTimeoutCallable&& on_timeout, std::chrono::milliseconds timeout,
TryAction&& try_action, Args&&... args)
{
static_assert(std::is_same<decltype(try_action(std::forward<Args>(args)...)), TimeoutAction>::value, "");
using namespace std::literals::chrono_literals;
auto deadline = std::chrono::steady_clock::now() + timeout;
while (std::chrono::steady_clock::now() < deadline)
{
if (try_action(std::forward<Args>(args)...) == TimeoutAction::done)
return;
// retry every second, until timeout - mock this to avoid sleeping at all in tests
MP_UTILS.sleep_for(timeout < 1s ? timeout : 1s);
}
on_timeout();
}
template <typename RegisteredQtEnum>
QString multipass::utils::qenum_to_qstring(RegisteredQtEnum val)
{
return QVariant::fromValue(val).toString();
}
template <typename RegisteredQtEnum>
std::string multipass::utils::qenum_to_string(RegisteredQtEnum val)
{
return qenum_to_qstring(val).toStdString();
}
#endif // MULTIPASS_UTILS_H
| 11,620
|
C++
|
.h
| 269
| 38.817844
| 118
| 0.71311
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,846
|
terminal.h
|
canonical_multipass/include/multipass/terminal.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_TERMINAL_H
#define MULTIPASS_TERMINAL_H
#include <istream>
#include <memory>
#include <ostream>
#include <string>
namespace multipass
{
class Terminal
{
public:
virtual ~Terminal() = default;
virtual std::istream& cin();
virtual std::ostream& cout();
virtual std::ostream& cerr();
virtual bool cin_is_live() const = 0;
virtual bool cout_is_live() const = 0;
bool is_live() const;
virtual std::string read_all_cin();
virtual void set_cin_echo(const bool enable) = 0;
using UPtr = std::unique_ptr<Terminal>;
static UPtr make_terminal();
};
} // namespace multipass
#endif // MULTIPASS_TERMINAL_H
| 1,293
|
C++
|
.h
| 41
| 28.878049
| 72
| 0.729686
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,847
|
async_periodic_download_task.h
|
canonical_multipass/include/multipass/async_periodic_download_task.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_ASYNC_PERIODIC_DOWNLOAD_TASK_H
#define MULTIPASS_ASYNC_PERIODIC_DOWNLOAD_TASK_H
#include <multipass/exceptions/download_exception.h>
#include <multipass/logging/log.h>
#include <chrono>
#include <string_view>
#include <QTimer>
#include <QtConcurrent/QtConcurrent>
namespace mpl = multipass::logging;
namespace multipass::utils
{
// Because AsyncPeriodicDownloadTask needs to be instantiated as data member of a class to function properly, and Class
// template argument deduction (CTAD) does not work for data member, so that means we can not deduced type data member
// from the below code snippet.
// template <typename Callable, typename...Args>
// class AsyncPeriodicDownloadTask
// {
// public:
// using ReturnType = std::invoke_result_t<std::decay_t<Callable>, std::decay_t<Args>...>;
// AsyncPeriodicDownloadTask(Callable&& func, Args&&... args);
// ...
// };
// Therefore, the user has to specify the ReturnType as template argument while constructing it.
template <typename ReturnType = void>
class AsyncPeriodicDownloadTask
{
public:
template <typename Callable, typename... Args>
AsyncPeriodicDownloadTask(std::string_view launch_msg,
std::chrono::milliseconds normal_delay_time,
std::chrono::milliseconds retry_start_delay_time,
Callable&& func,
Args&&... args)
: default_delay_time{normal_delay_time}, retry_current_delay_time{retry_start_delay_time}
{
// Log in a side thread will cause some unit tests (like launch_warns_when_overcommitting_disk) to have data
// race on log, because the side thread log messes with the mock_logger. Because of that, we only allow the
// main thread log for now. That is why launch_msg parameter is here. A long-term solution would be a better
// separation of classes and mock the corresponding class function, so it will not log and mess with the
// mock_logger in the unit tests.
// TODO, remove the launch_msg parameter once we have better class separation.
mpl::log(mpl::Level::debug, "async task", std::string(launch_msg));
future = QtConcurrent::run(std::forward<Callable>(func), std::forward<Args>(args)...);
auto event_handler_on_success_and_failure = [retry_start_delay_time, this]() -> void {
try
{
// rethrow exception
future.waitForFinished();
// success case, we reset the time interval for timer and the reset the retry delay time value
timer.start(default_delay_time);
retry_current_delay_time = retry_start_delay_time;
}
catch (const multipass::DownloadException& e)
{
mpl::log(mpl::Level::debug,
"async task",
fmt::format("QFutureWatcher caught DownloadException {}", e.what()));
// failure case, trigger or continue the retry mechanism
timer.start(retry_current_delay_time);
retry_current_delay_time = std::min(2 * retry_current_delay_time, default_delay_time);
}
};
QObject::connect(&future_watcher, &QFutureWatcher<ReturnType>::finished, event_handler_on_success_and_failure);
future_watcher.setFuture(future);
QObject::connect(&timer, &QTimer::timeout, [launch_msg, this, func, args...]() -> void {
// skip it if the previous one is still running
if (future.isFinished())
{
mpl::log(mpl::Level::debug, "async task", std::string(launch_msg));
future = QtConcurrent::run(func, args...);
future_watcher.setFuture(future);
}
});
timer.start(default_delay_time);
}
void start_timer()
{
timer.start();
}
void stop_timer()
{
timer.stop();
}
void wait_ongoing_task_finish()
{
future.waitForFinished();
}
private:
QTimer timer;
QFuture<ReturnType> future;
QFutureWatcher<ReturnType> future_watcher;
const std::chrono::milliseconds default_delay_time;
std::chrono::milliseconds retry_current_delay_time;
};
} // namespace multipass::utils
#endif
| 4,986
|
C++
|
.h
| 112
| 36.9375
| 119
| 0.656855
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,848
|
standard_paths.h
|
canonical_multipass/include/multipass/standard_paths.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_STANDARD_PATHS_H
#define MULTIPASS_STANDARD_PATHS_H
#include "singleton.h"
#include <QStandardPaths>
#define MP_STDPATHS multipass::StandardPaths::instance()
namespace multipass
{
class StandardPaths : public Singleton<StandardPaths>
{
public:
// TODO try to replace all the stuff below with `using enum` in C++20 (P1099R5)
using LocateOption = QStandardPaths::LocateOption;
static constexpr auto LocateFile = LocateOption::LocateFile;
static constexpr auto LocateDirectory = LocateOption::LocateDirectory;
using LocateOptions = QStandardPaths::LocateOptions;
using StandardLocation = QStandardPaths::StandardLocation;
static constexpr auto DesktopLocation = StandardLocation::DesktopLocation;
static constexpr auto DocumentsLocation = StandardLocation::DocumentsLocation;
static constexpr auto FontsLocation = StandardLocation::FontsLocation;
static constexpr auto ApplicationsLocation = StandardLocation::ApplicationsLocation;
static constexpr auto MusicLocation = StandardLocation::MusicLocation;
static constexpr auto MoviesLocation = StandardLocation::MoviesLocation;
static constexpr auto PicturesLocation = StandardLocation::PicturesLocation;
static constexpr auto TempLocation = StandardLocation::TempLocation;
static constexpr auto HomeLocation = StandardLocation::HomeLocation;
static constexpr auto CacheLocation = StandardLocation::CacheLocation;
static constexpr auto GenericCacheLocation = StandardLocation::GenericCacheLocation;
static constexpr auto GenericDataLocation = StandardLocation::GenericDataLocation;
static constexpr auto RuntimeLocation = StandardLocation::RuntimeLocation;
static constexpr auto ConfigLocation = StandardLocation::ConfigLocation;
static constexpr auto DownloadLocation = StandardLocation::DownloadLocation;
static constexpr auto GenericConfigLocation = StandardLocation::GenericConfigLocation;
static constexpr auto AppDataLocation = StandardLocation::AppDataLocation;
static constexpr auto AppLocalDataLocation = StandardLocation::AppLocalDataLocation;
static constexpr auto AppConfigLocation = StandardLocation::AppConfigLocation;
StandardPaths(const Singleton<StandardPaths>::PrivatePass&) noexcept;
virtual QString locate(StandardLocation type, const QString& fileName,
LocateOptions options = LocateOption::LocateFile) const;
virtual QStringList standardLocations(StandardLocation type) const;
virtual QString writableLocation(StandardLocation type) const;
};
} // namespace multipass
#endif // MULTIPASS_STANDARD_PATHS_H
| 3,269
|
C++
|
.h
| 59
| 51.59322
| 90
| 0.804809
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,849
|
file_ops.h
|
canonical_multipass/include/multipass/file_ops.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_FILE_OPS_H
#define MULTIPASS_FILE_OPS_H
#include "recursive_dir_iterator.h"
#include "singleton.h"
#include <QByteArray>
#include <QDir>
#include <QFileDevice>
#include <QFileInfoList>
#include <QSaveFile>
#include <QString>
#include <QTextStream>
#include <filesystem>
#include <fstream>
#define MP_FILEOPS multipass::FileOps::instance()
namespace multipass
{
namespace fs = std::filesystem;
struct NamedFd
{
NamedFd(const fs::path& path, int fd);
~NamedFd();
fs::path path;
int fd;
};
class FileOps : public Singleton<FileOps>
{
public:
FileOps(const Singleton<FileOps>::PrivatePass&) noexcept;
// QDir operations
virtual bool exists(const QDir& dir) const;
virtual bool isReadable(const QDir& dir) const;
virtual QFileInfoList entryInfoList(const QDir& dir,
const QStringList& nameFilters,
QDir::Filters filters = QDir::NoFilter,
QDir::SortFlags sort = QDir::NoSort) const;
virtual bool mkpath(const QDir& dir, const QString& dirName) const;
virtual bool rmdir(QDir& dir, const QString& dirName) const;
// QFileInfo operations
virtual bool exists(const QFileInfo& file) const;
virtual bool isDir(const QFileInfo& file) const;
virtual bool isReadable(const QFileInfo& file) const;
virtual uint ownerId(const QFileInfo& file) const;
virtual uint groupId(const QFileInfo& file) const;
// QFile operations
virtual bool exists(const QFile& file) const;
virtual bool is_open(const QFile& file) const;
virtual bool open(QFileDevice& file, QIODevice::OpenMode mode) const;
virtual QFileDevice::Permissions permissions(const QFile& file) const;
virtual qint64 read(QFile& file, char* data, qint64 maxSize) const;
virtual QByteArray read_all(QFile& file) const;
virtual QString read_line(QTextStream& text_stream) const;
virtual bool remove(QFile& file) const;
virtual bool rename(QFile& file, const QString& newName) const;
virtual bool resize(QFile& file, qint64 sz) const;
virtual bool seek(QFile& file, qint64 pos) const;
virtual bool setPermissions(QFile& file, QFileDevice::Permissions permissions) const;
virtual qint64 size(QFile& file) const;
virtual qint64 write(QFile& file, const char* data, qint64 maxSize) const;
virtual qint64 write(QFileDevice& file, const QByteArray& data) const;
virtual bool flush(QFile& file) const;
// QSaveFile operations
virtual bool commit(QSaveFile& file) const;
// posix operations
virtual std::unique_ptr<NamedFd> open_fd(const fs::path& path, int flags, int perms) const;
virtual int read(int fd, void* buf, size_t nbytes) const;
virtual int write(int fd, const void* buf, size_t nbytes) const;
virtual off_t lseek(int fd, off_t offset, int whence) const;
// std operations
virtual void open(std::fstream& stream, const char* filename, std::ios_base::openmode mode) const;
virtual bool is_open(const std::ifstream& file) const;
virtual std::ifstream& read(std::ifstream& file, char* buffer, std::streamsize size) const;
virtual std::unique_ptr<std::ostream> open_write(const fs::path& path,
std::ios_base::openmode mode = std::ios_base::out) const;
virtual std::unique_ptr<std::istream> open_read(const fs::path& path,
std::ios_base::openmode mode = std::ios_base::in) const;
virtual void copy(const fs::path& src, const fs::path& dist, fs::copy_options copy_options) const;
virtual bool exists(const fs::path& path, std::error_code& err) const;
virtual bool is_directory(const fs::path& path, std::error_code& err) const;
virtual bool create_directory(const fs::path& path, std::error_code& err) const;
virtual bool create_directories(const fs::path& path, std::error_code& err) const;
virtual bool remove(const fs::path& path, std::error_code& err) const;
virtual void create_symlink(const fs::path& to, const fs::path& path, std::error_code& err) const;
virtual fs::path read_symlink(const fs::path& path, std::error_code& err) const;
virtual void permissions(const fs::path& path, fs::perms perms, std::error_code& err) const;
virtual fs::file_status status(const fs::path& path, std::error_code& err) const;
virtual fs::file_status symlink_status(const fs::path& path, std::error_code& err) const;
virtual std::unique_ptr<RecursiveDirIterator> recursive_dir_iterator(const fs::path& path,
std::error_code& err) const;
virtual std::unique_ptr<DirIterator> dir_iterator(const fs::path& path, std::error_code& err) const;
};
} // namespace multipass
#endif // MULTIPASS_FILE_OPS_H
| 5,521
|
C++
|
.h
| 108
| 44.851852
| 110
| 0.69798
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,850
|
virtual_machine_description.h
|
canonical_multipass/include/multipass/virtual_machine_description.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VIRTUAL_MACHINE_DESCRIPTION_H
#define MULTIPASS_VIRTUAL_MACHINE_DESCRIPTION_H
#include <multipass/memory_size.h>
#include <multipass/network_interface.h>
#include <multipass/vm_image.h>
#include <yaml-cpp/yaml.h>
#include <string>
#include <vector>
#include <QMetaType>
namespace multipass
{
class VirtualMachineDescription
{
public:
using MBytes = size_t;
int num_cores;
MemorySize mem_size;
MemorySize disk_space;
std::string vm_name;
std::string default_mac_address;
std::vector<NetworkInterface> extra_interfaces;
std::string ssh_username;
VMImage image;
Path cloud_init_iso;
YAML::Node meta_data_config;
YAML::Node user_data_config;
YAML::Node vendor_data_config;
YAML::Node network_data_config;
};
} // namespace multipass
Q_DECLARE_METATYPE(multipass::VirtualMachineDescription)
#endif // MULTIPASS_VIRTUAL_MACHINE_DESCRIPTION_H
| 1,547
|
C++
|
.h
| 48
| 29.5625
| 72
| 0.761745
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,851
|
console.h
|
canonical_multipass/include/multipass/console.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_CONSOLE_H
#define MULTIPASS_CONSOLE_H
#include "disabled_copy_move.h"
#include <libssh/libssh.h>
#include <array>
#include <functional>
#include <memory>
namespace multipass
{
class Terminal;
class Console : private DisabledCopyMove
{
public:
struct ConsoleGeometry
{
int rows;
int columns;
};
using UPtr = std::unique_ptr<Console>;
virtual ~Console() = default;
virtual void read_console() = 0;
virtual void write_console() = 0;
virtual void exit_console() = 0;
static UPtr make_console(ssh_channel channel, Terminal* term);
static void setup_environment();
protected:
explicit Console() = default;
};
} // namespace multipass
#endif // MULTIPASS_CONSOLE_H
| 1,375
|
C++
|
.h
| 46
| 27.021739
| 72
| 0.735205
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,852
|
name_generator.h
|
canonical_multipass/include/multipass/name_generator.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#ifndef MULTIPASS_NAME_GENERATOR_H
#define MULTIPASS_NAME_GENERATOR_H
#include "disabled_copy_move.h"
#include <memory>
#include <string>
namespace multipass
{
class NameGenerator : private DisabledCopyMove
{
public:
using UPtr = std::unique_ptr<NameGenerator>;
virtual ~NameGenerator() = default;
virtual std::string make_name() = 0;
protected:
NameGenerator() = default;
};
NameGenerator::UPtr make_default_name_generator();
}
#endif //MULTIPASS_NAME_GENERATOR_H
| 1,182
|
C++
|
.h
| 37
| 29.891892
| 72
| 0.762072
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,853
|
network_interface_info.h
|
canonical_multipass/include/multipass/network_interface_info.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_NETWORK_INTERFACE_INFO_H
#define MULTIPASS_NETWORK_INTERFACE_INFO_H
#include <multipass/ip_address.h>
#include <algorithm>
#include <string>
#include <vector>
namespace multipass
{
struct NetworkInterfaceInfo
{
bool has_link(const std::string& net) const
{
auto end = links.cend();
return std::find(links.cbegin(), end, net) != end;
}
std::string id;
std::string type;
std::string description;
std::vector<std::string> links = {}; // default initializer allows aggregate init of the other 3
bool needs_authorization = false; // idem
};
inline bool operator==(const NetworkInterfaceInfo& a, const NetworkInterfaceInfo& b)
{
return std::tie(a.id, a.type, a.description, a.links, a.needs_authorization) ==
std::tie(b.id, b.type, b.description, b.links, b.needs_authorization);
}
} // namespace multipass
#endif // MULTIPASS_NETWORK_INTERFACE_INFO_H
| 1,565
|
C++
|
.h
| 44
| 32.636364
| 100
| 0.729194
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,854
|
platform_unix.h
|
canonical_multipass/include/multipass/platform_unix.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_PLATFORM_UNIX_H
#define MULTIPASS_PLATFORM_UNIX_H
#include <vector>
#include <signal.h>
namespace multipass
{
namespace platform
{
sigset_t make_sigset(const std::vector<int>& sigs);
sigset_t make_and_block_signals(const std::vector<int>& sigs);
} // namespace platform
}
#endif // MULTIPASS_PLATFORM_UNIX_H
| 958
|
C++
|
.h
| 29
| 31.37931
| 72
| 0.765405
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,855
|
snapshot.h
|
canonical_multipass/include/multipass/snapshot.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_SNAPSHOT_H
#define MULTIPASS_SNAPSHOT_H
#include "disabled_copy_move.h"
#include "virtual_machine.h"
#include <memory>
#include <string>
#include <unordered_map>
class QJsonObject;
class QDateTime;
namespace multipass
{
class MemorySize;
class VMMount;
class Snapshot : private DisabledCopyMove
{
public:
virtual ~Snapshot() = default;
virtual int get_index() const noexcept = 0;
virtual std::string get_name() const = 0;
virtual std::string get_comment() const = 0;
virtual std::string get_cloud_init_instance_id() const noexcept = 0;
virtual QDateTime get_creation_timestamp() const noexcept = 0;
virtual int get_num_cores() const noexcept = 0;
virtual MemorySize get_mem_size() const noexcept = 0;
virtual MemorySize get_disk_space() const noexcept = 0;
virtual std::vector<NetworkInterface> get_extra_interfaces() const noexcept = 0;
virtual VirtualMachine::State get_state() const noexcept = 0;
// Note that these return references - careful not to delete the snapshot while they are in use
virtual const std::unordered_map<std::string, VMMount>& get_mounts() const noexcept = 0;
virtual const QJsonObject& get_metadata() const noexcept = 0;
virtual std::shared_ptr<const Snapshot> get_parent() const = 0;
virtual std::shared_ptr<Snapshot> get_parent() = 0;
virtual std::string get_parents_name() const = 0;
virtual int get_parents_index() const = 0;
// precondition for setters: call only on captured snapshots
virtual void set_name(const std::string&) = 0;
virtual void set_comment(const std::string&) = 0;
virtual void set_parent(std::shared_ptr<Snapshot>) = 0;
// precondition: capture only once
virtual void capture() = 0; // not using the constructor, we need snapshot objects for existing snapshots too
// precondition: call only on captured snapshots
virtual void erase() = 0; // not using the destructor, we want snapshots to stick around when daemon quits
// precondition: call only on captured snapshots
virtual void apply() = 0;
};
} // namespace multipass
#endif // MULTIPASS_SNAPSHOT_H
| 2,775
|
C++
|
.h
| 63
| 40.84127
| 113
| 0.738148
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,856
|
vm_image_info.h
|
canonical_multipass/include/multipass/vm_image_info.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VM_IMAGE_INFO_H
#define MULTIPASS_VM_IMAGE_INFO_H
#include <QString>
#include <QStringList>
namespace multipass
{
class VMImageInfo
{
public:
QStringList aliases;
QString os;
QString release;
QString release_title;
QString release_codename;
bool supported;
QString image_location;
QString id;
QString stream_location;
QString version;
int64_t size;
bool verify;
};
inline bool operator==(const VMImageInfo& a, const VMImageInfo& b)
{
return std::tie(a.aliases,
a.os,
a.release,
a.release_title,
a.release_codename,
a.supported,
a.image_location,
a.id,
a.stream_location,
a.version,
a.size,
a.verify) == std::tie(b.aliases,
b.os,
b.release,
b.release_title,
b.release_codename,
b.supported,
b.image_location,
b.id,
b.stream_location,
b.version,
b.size,
b.verify);
}
} // namespace multipass
#endif // MULTIPASS_VM_IMAGE_INFO_H
| 2,210
|
C++
|
.h
| 66
| 21.075758
| 72
| 0.514019
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,857
|
progress_monitor.h
|
canonical_multipass/include/multipass/progress_monitor.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#ifndef MULTIPASS_PROGRESS_MONITOR_H
#define MULTIPASS_PROGRESS_MONITOR_H
#include <functional>
namespace multipass
{
using ProgressMonitor = std::function<bool(int download_type, int progress)>;
}
#endif // MULTIPASS_PROGRESS_MONITOR_H
| 935
|
C++
|
.h
| 26
| 34.192308
| 77
| 0.771523
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,858
|
query.h
|
canonical_multipass/include/multipass/query.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_QUERY_H
#define MULTIPASS_QUERY_H
#include <string>
namespace multipass
{
class Query
{
public:
enum Type
{
Alias,
LocalFile,
HttpDownload
};
std::string name;
std::string release;
bool persistent;
std::string remote_name;
Type query_type;
bool allow_unsupported{false};
};
}
#endif // MULTIPASS_QUERY_H
| 1,014
|
C++
|
.h
| 39
| 22.974359
| 72
| 0.725026
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,859
|
client_cert_store.h
|
canonical_multipass/include/multipass/client_cert_store.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_CLIENT_CERT_STORE_H
#define MULTIPASS_CLIENT_CERT_STORE_H
#include <multipass/cert_store.h>
#include <multipass/path.h>
#include <QDir>
#include <QList>
#include <QSslCertificate>
namespace multipass
{
class ClientCertStore : public CertStore
{
public:
explicit ClientCertStore(const multipass::Path& cert_dir);
void add_cert(const std::string& pem_cert) override;
std::string PEM_cert_chain() const override;
bool verify_cert(const std::string& pem_cert) override;
bool empty() override;
private:
bool verify_cert(const QSslCertificate& cert);
QDir cert_dir;
QList<QSslCertificate> authenticated_client_certs;
};
} // namespace multipass
#endif // MULTIPASS_CLIENT_CERT_STORE_H
| 1,363
|
C++
|
.h
| 40
| 31.75
| 72
| 0.762339
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,860
|
qt_delete_later_unique_ptr.h
|
canonical_multipass/include/multipass/qt_delete_later_unique_ptr.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef QT_DELETE_LATER_UNIQUE_PTR_H
#define QT_DELETE_LATER_UNIQUE_PTR_H
#include <memory>
#include <QObject>
namespace multipass
{
/*
* A unique_ptr for Qt objects that are more safely cleaned up on the event loop
* e.g. QThread
*/
struct QtDeleteLater {
void operator()(QObject *o) {
o->deleteLater();
}
};
template<typename T>
using qt_delete_later_unique_ptr = std::unique_ptr<T, QtDeleteLater>;
} // namespace
#endif // QT_DELETE_LATER_UNIQUE_PTR_H
| 1,110
|
C++
|
.h
| 35
| 29.514286
| 80
| 0.743205
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,861
|
path.h
|
canonical_multipass/include/multipass/path.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Chris Townsend <christopher.townsend@canonical.com>
*
*/
#ifndef MULTIPASS_PATH_H
#define MULTIPASS_PATH_H
#include <QString>
namespace multipass
{
using Path = QString;
}
#endif // MULTIPASS_PATH_H
| 844
|
C++
|
.h
| 26
| 30.692308
| 72
| 0.76319
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,862
|
xz_image_decoder.h
|
canonical_multipass/include/multipass/xz_image_decoder.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_XZ_IMAGE_DECODER_H
#define MULTIPASS_XZ_IMAGE_DECODER_H
#include <multipass/path.h>
#include <multipass/progress_monitor.h>
#include <memory>
#include <QFile>
#include <xz.h>
namespace multipass
{
class XzImageDecoder
{
public:
XzImageDecoder(const Path& xz_file_path);
void decode_to(const Path& decoded_file_path, const ProgressMonitor& monitor);
using XzDecoderUPtr = std::unique_ptr<xz_dec, decltype(xz_dec_end)*>;
private:
QFile xz_file;
XzDecoderUPtr xz_decoder;
};
} // namespace multipass
#endif // MULTIPASS_XZ_IMAGE_DECODER_H
| 1,211
|
C++
|
.h
| 37
| 30.540541
| 82
| 0.760515
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,863
|
platform.h
|
canonical_multipass/include/multipass/platform.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_PLATFORM_H
#define MULTIPASS_PLATFORM_H
#include <multipass/alias_definition.h>
#include <multipass/days.h>
#include <multipass/logging/logger.h>
#include <multipass/network_interface_info.h>
#include <multipass/process/process.h>
#include <multipass/process/process_spec.h>
#include <multipass/settings/setting_spec.h>
#include <multipass/singleton.h>
#include <multipass/sshfs_server_config.h>
#include <multipass/update_prompt.h>
#include <multipass/virtual_machine_factory.h>
#include <multipass/vm_image_vault.h>
#include <QDir>
#include <QString>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#define MP_PLATFORM multipass::platform::Platform::instance()
struct sftp_attributes_struct;
namespace multipass
{
namespace platform
{
class Platform : public Singleton<Platform>
{
public:
Platform(const Singleton::PrivatePass&) noexcept;
// Get information on the network interfaces that are seen by the platform, indexed by name
virtual std::map<std::string, NetworkInterfaceInfo> get_network_interfaces_info() const;
virtual QString get_blueprints_url_override() const;
virtual bool is_alias_supported(const std::string& alias, const std::string& remote) const;
virtual bool is_remote_supported(const std::string& remote) const;
virtual bool is_backend_supported(const QString& backend) const; // temporary (?)
virtual int chown(const char* path, unsigned int uid, unsigned int gid) const;
virtual int chmod(const char* path, unsigned int mode) const;
virtual bool set_permissions(const multipass::Path path, const QFileDevice::Permissions permissions) const;
virtual bool link(const char* target, const char* link) const;
virtual bool symlink(const char* target, const char* link, bool is_dir) const;
virtual int utime(const char* path, int atime, int mtime) const;
virtual QString get_username() const;
virtual QDir get_alias_scripts_folder() const;
virtual void create_alias_script(const std::string& alias, const AliasDefinition& def) const;
virtual void remove_alias_script(const std::string& alias) const;
virtual std::string alias_path_message() const;
virtual void set_server_socket_restrictions(const std::string& server_address, const bool restricted) const;
virtual QString multipass_storage_location() const;
virtual QString daemon_config_home() const; // temporary
virtual SettingSpec::Set extra_daemon_settings() const;
virtual SettingSpec::Set extra_client_settings() const;
virtual QString default_driver() const;
virtual QString default_privileged_mounts() const;
virtual bool is_image_url_supported() const;
[[nodiscard]] virtual std::string bridge_nomenclature() const;
};
QString interpret_setting(const QString& key, const QString& val);
void sync_winterm_profiles();
std::string default_server_address();
VirtualMachineFactory::UPtr vm_backend(const Path& data_dir);
logging::Logger::UPtr make_logger(logging::Level level);
UpdatePrompt::UPtr make_update_prompt();
std::unique_ptr<Process> make_sshfs_server_process(const SSHFSServerConfig& config);
std::unique_ptr<Process> make_process(std::unique_ptr<ProcessSpec>&& process_spec);
int symlink_attr_from(const char* path, sftp_attributes_struct* attr);
std::function<int()> make_quit_watchdog(); // call while single-threaded; call result later, in dedicated thread
std::string reinterpret_interface_id(const std::string& ux_id); // give platforms a chance to reinterpret network IDs
std::string host_version();
} // namespace platform
} // namespace multipass
inline multipass::platform::Platform::Platform(const PrivatePass& pass) noexcept : Singleton(pass)
{
}
#endif // MULTIPASS_PLATFORM_H
| 4,372
|
C++
|
.h
| 91
| 45.516484
| 117
| 0.773271
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,864
|
default_vm_blueprint_provider.h
|
canonical_multipass/include/multipass/default_vm_blueprint_provider.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_DEFAULT_VM_BLUEPRINT_PROVIDER_H
#define MULTIPASS_DEFAULT_VM_BLUEPRINT_PROVIDER_H
#include <multipass/path.h>
#include <multipass/vm_blueprint_provider.h>
#include <yaml-cpp/yaml.h>
#include <QDir>
#include <QString>
#include <QSysInfo>
#include <QUrl>
#include <chrono>
#include <map>
namespace multipass
{
const QString default_blueprint_url{"https://codeload.github.com/canonical/multipass-blueprints/zip/refs/heads/main"};
class URLDownloader;
class DefaultVMBlueprintProvider final : public VMBlueprintProvider
{
public:
DefaultVMBlueprintProvider(const QUrl& blueprints_url, URLDownloader* downloader, const QDir& cache_dir_path,
const std::chrono::milliseconds& blueprints_ttl,
const QString& arch = QSysInfo::currentCpuArchitecture());
DefaultVMBlueprintProvider(URLDownloader* downloader, const QDir& cache_dir_path,
const std::chrono::milliseconds& blueprints_ttl,
const QString& arch = QSysInfo::currentCpuArchitecture());
Query fetch_blueprint_for(const std::string& blueprint_name, VirtualMachineDescription& vm_desc,
ClientLaunchData& client_launch_data) override;
Query blueprint_from_file(const std::string& path, const std::string& blueprint_name,
VirtualMachineDescription& vm_desc, ClientLaunchData& client_launch_data) override;
std::optional<VMImageInfo> info_for(const std::string& blueprint_name) override;
std::vector<VMImageInfo> all_blueprints() override;
std::string name_from_blueprint(const std::string& blueprint_name) override;
int blueprint_timeout(const std::string& blueprint_name) override;
private:
void fetch_blueprints();
void update_blueprints();
const QUrl blueprints_url;
URLDownloader* const url_downloader;
const QString archive_file_path;
const std::chrono::milliseconds blueprints_ttl;
std::chrono::steady_clock::time_point last_update;
std::map<std::string, YAML::Node> blueprint_map;
bool needs_update{true};
const QString arch;
};
} // namespace multipass
#endif // MULTIPASS_DEFAULT_VM_BLUEPRINT_PROVIDER_H
| 2,869
|
C++
|
.h
| 62
| 40.725806
| 118
| 0.728898
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,865
|
virtual_machine_factory.h
|
canonical_multipass/include/multipass/virtual_machine_factory.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VIRTUAL_MACHINE_FACTORY_H
#define MULTIPASS_VIRTUAL_MACHINE_FACTORY_H
#include "days.h"
#include "disabled_copy_move.h"
#include "fetch_type.h"
#include "path.h"
#include "virtual_machine.h"
#include "vm_image.h"
#include "vm_image_vault.h"
namespace YAML
{
class Node;
}
namespace multipass
{
class SSHKeyProvider;
class URLDownloader;
class VirtualMachineDescription;
class VMImageHost;
class VMStatusMonitor;
struct NetworkInterface;
struct NetworkInterfaceInfo;
class VirtualMachineFactory : private DisabledCopyMove
{
public:
using UPtr = std::unique_ptr<VirtualMachineFactory>;
virtual ~VirtualMachineFactory() = default;
virtual VirtualMachine::UPtr create_virtual_machine(const VirtualMachineDescription& desc,
const SSHKeyProvider& key_provider,
VMStatusMonitor& monitor) = 0;
virtual VirtualMachine::UPtr create_vm_and_clone_instance_dir_data(const VMSpecs& src_vm_spec,
const VMSpecs& dest_vm_spec,
const std::string& source_name,
const std::string& destination_name,
const VMImage& dest_vm_image,
const SSHKeyProvider& key_provider,
VMStatusMonitor& monitor) = 0;
/** Removes any resources associated with a VM of the given name.
*
* @param name The unique name assigned to the virtual machine
*/
virtual void remove_resources_for(const std::string& name) = 0;
virtual FetchType fetch_type() = 0;
virtual void prepare_networking(std::vector<NetworkInterface>& extra_interfaces) = 0; // note the arg may be updated
virtual VMImage prepare_source_image(const VMImage& source_image) = 0;
virtual void prepare_instance_image(const VMImage& instance_image, const VirtualMachineDescription& desc) = 0;
virtual void hypervisor_health_check() = 0;
virtual QString get_backend_directory_name() const = 0;
virtual Path get_instance_directory(const std::string& name) const = 0;
virtual QString get_backend_version_string() const = 0;
virtual VMImageVault::UPtr create_image_vault(std::vector<VMImageHost*> image_hosts, URLDownloader* downloader,
const Path& cache_dir_path, const Path& data_dir_path,
const days& days_to_expire) = 0;
virtual void configure(VirtualMachineDescription& vm_desc) = 0;
// List all the network interfaces seen by the backend.
virtual std::vector<NetworkInterfaceInfo> networks() const = 0;
virtual void require_snapshots_support() const = 0;
virtual void require_suspend_support() const = 0;
virtual void require_clone_support() const = 0;
protected:
VirtualMachineFactory() = default;
virtual std::string create_bridge_with(const NetworkInterfaceInfo& interface) = 0;
};
}
#endif // MULTIPASS_VIRTUAL_MACHINE_FACTORY_H
| 3,951
|
C++
|
.h
| 81
| 38.271605
| 120
| 0.642228
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,866
|
disabled_copy_move.h
|
canonical_multipass/include/multipass/disabled_copy_move.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_DISABLED_COPY_MOVE_H
#define MULTIPASS_DISABLED_COPY_MOVE_H
namespace multipass
{
/**
* A simple base class to disable copy and move construction and assignment.
*
* To use, inherit privately, Like so:
* @code
* class Foo : private DisabledCopyMove {...};`
* @endcode
*/
class DisabledCopyMove
{
public:
DisabledCopyMove(const DisabledCopyMove&) = delete;
DisabledCopyMove& operator=(const DisabledCopyMove&) = delete;
protected:
DisabledCopyMove() = default;
~DisabledCopyMove() = default; // non-virtual, but needs protected - see Core Guidelines C.35
};
} // namespace multipass
#endif // MULTIPASS_DISABLED_COPY_MOVE_H
| 1,298
|
C++
|
.h
| 39
| 31.179487
| 97
| 0.753589
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,867
|
network_interface.h
|
canonical_multipass/include/multipass/network_interface.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_NETWORK_INTERFACE_H
#define MULTIPASS_NETWORK_INTERFACE_H
#include <string>
#include <tuple>
namespace multipass
{
struct NetworkInterface
{
std::string id;
std::string mac_address;
bool auto_mode;
};
inline bool operator==(const NetworkInterface& a, const NetworkInterface& b)
{
return std::tie(a.id, a.auto_mode, a.mac_address) == std::tie(b.id, b.auto_mode, b.mac_address);
}
} // namespace multipass
#endif // MULTIPASS_NETWORK_INTERFACE_H
| 1,111
|
C++
|
.h
| 34
| 30.617647
| 100
| 0.752799
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,868
|
simple_streams_index.h
|
canonical_multipass/include/multipass/simple_streams_index.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#ifndef MULTIPASS_SIMPLE_STREAMS_INDEX_H
#define MULTIPASS_SIMPLE_STREAMS_INDEX_H
#include <QByteArray>
#include <QString>
namespace multipass
{
class SimpleStreamsIndex
{
public:
static SimpleStreamsIndex fromJson(const QByteArray& json);
const QString manifest_path;
const QString updated_at;
};
}
#endif // MULTIPASS_SIMPLE_STREAMS_INDEX_H
| 1,054
|
C++
|
.h
| 33
| 29.939394
| 72
| 0.772861
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,869
|
vm_specs.h
|
canonical_multipass/include/multipass/vm_specs.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VM_SPECS_H
#define MULTIPASS_VM_SPECS_H
#include "memory_size.h"
#include "network_interface.h"
#include "virtual_machine.h"
#include "vm_mount.h"
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <QJsonObject>
namespace multipass
{
struct VMSpecs
{
int num_cores;
MemorySize mem_size;
MemorySize disk_space;
std::string default_mac_address;
std::vector<NetworkInterface> extra_interfaces; // We want interfaces to be ordered.
std::string ssh_username;
VirtualMachine::State state;
std::unordered_map<std::string, VMMount> mounts;
bool deleted;
QJsonObject metadata;
int clone_count = 0; // tracks the number of cloned vm from this source vm (regardless of deletes)
};
inline bool operator==(const VMSpecs& a, const VMSpecs& b)
{
return std::tie(a.num_cores,
a.mem_size,
a.disk_space,
a.default_mac_address,
a.extra_interfaces,
a.ssh_username,
a.state,
a.mounts,
a.deleted,
a.metadata,
a.clone_count) == std::tie(b.num_cores,
b.mem_size,
b.disk_space,
b.default_mac_address,
b.extra_interfaces,
b.ssh_username,
b.state,
b.mounts,
b.deleted,
b.metadata,
a.clone_count);
}
inline bool operator!=(const VMSpecs& a, const VMSpecs& b) // TODO drop in C++20
{
return !(a == b);
}
} // namespace multipass
#endif // MULTIPASS_VM_SPECS_H
| 2,644
|
C++
|
.h
| 73
| 25
| 102
| 0.551132
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,870
|
memory_size.h
|
canonical_multipass/include/multipass/memory_size.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_MEMORY_SIZE_H
#define MULTIPASS_MEMORY_SIZE_H
#include <string>
namespace multipass
{
class MemorySize
{
public:
friend bool operator==(const MemorySize& a, const MemorySize& b) noexcept;
friend bool operator!=(const MemorySize& a, const MemorySize& b) noexcept;
friend bool operator<(const MemorySize& a, const MemorySize& b) noexcept;
friend bool operator>(const MemorySize& a, const MemorySize& b) noexcept;
friend bool operator<=(const MemorySize& a, const MemorySize& b) noexcept;
friend bool operator>=(const MemorySize& a, const MemorySize& b) noexcept;
MemorySize() noexcept;
explicit MemorySize(const std::string& val);
long long in_bytes() const noexcept;
long long in_kilobytes() const noexcept;
long long in_megabytes() const noexcept;
long long in_gigabytes() const noexcept;
std::string human_readable(unsigned int precision = 1, bool trim_zeros = false) const;
static MemorySize from_bytes(long long bytes) noexcept;
private:
explicit MemorySize(long long bytes) noexcept;
long long bytes;
};
long long in_bytes(const std::string& mem_value);
bool operator==(const MemorySize& a, const MemorySize& b) noexcept;
bool operator!=(const MemorySize& a, const MemorySize& b) noexcept;
bool operator<(const MemorySize& a, const MemorySize& b) noexcept;
bool operator>(const MemorySize& a, const MemorySize& b) noexcept;
bool operator<=(const MemorySize& a, const MemorySize& b) noexcept;
bool operator>=(const MemorySize& a, const MemorySize& b) noexcept;
} // namespace multipass
#endif // MULTIPASS_MEMORY_SIZE_H
| 2,244
|
C++
|
.h
| 51
| 41.235294
| 90
| 0.757562
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,871
|
mount_handler.h
|
canonical_multipass/include/multipass/mount_handler.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_MOUNT_HANDLER_H
#define MULTIPASS_MOUNT_HANDLER_H
#include <multipass/file_ops.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/ssh/ssh_key_provider.h>
#include <multipass/vm_mount.h>
#include <chrono>
#include <variant>
namespace multipass
{
class VirtualMachine;
using ServerVariant = std::variant<grpc::ServerReaderWriterInterface<StartReply, StartRequest>*,
grpc::ServerReaderWriterInterface<LaunchReply, LaunchRequest>*,
grpc::ServerReaderWriterInterface<MountReply, MountRequest>*,
grpc::ServerReaderWriterInterface<RestartReply, RestartRequest>*>;
class NativeMountNeedsStoppedVMException : public std::runtime_error
{
public:
NativeMountNeedsStoppedVMException(const std::string& vm_name)
: std::runtime_error(fmt::format("Please stop the instance {} before attempting native mounts.", vm_name))
{
}
};
class MountHandler : private DisabledCopyMove
{
public:
using UPtr = std::unique_ptr<MountHandler>;
virtual ~MountHandler() = default;
void activate(ServerVariant server, std::chrono::milliseconds timeout = std::chrono::minutes(5))
{
std::lock_guard active_lock{active_mutex};
if (!is_active())
activate_impl(server, timeout);
active = true;
}
void deactivate(bool force = false)
{
std::lock_guard active_lock{active_mutex};
if (is_active())
deactivate_impl(force);
active = false;
}
const VMMount& get_mount_spec() const noexcept
{
return mount_spec;
}
virtual bool is_active()
{
return active;
}
virtual bool is_mount_managed_by_backend()
{
return false;
}
protected:
MountHandler() = default;
MountHandler(VirtualMachine* vm,
const SSHKeyProvider* ssh_key_provider,
VMMount mount_spec,
const std::string& target)
: vm{vm}, ssh_key_provider{ssh_key_provider}, mount_spec{std::move(mount_spec)}, target{target}, active{false}
{
std::error_code err;
auto source_status = MP_FILEOPS.status(source, err);
if (source_status.type() == fs::file_type::not_found)
throw std::runtime_error(fmt::format("Mount source path \"{}\" does not exist.", source));
if (err)
throw std::runtime_error(
fmt::format("Mount source path \"{}\" is not accessible: {}.", source, err.message()));
if (source_status.type() != fs::file_type::directory)
throw std::runtime_error(fmt::format("Mount source path \"{}\" is not a directory.", source));
if (source_status.permissions() != fs::perms::unknown &&
(source_status.permissions() & fs::perms::owner_read) == fs::perms::none)
throw std::runtime_error(fmt::format("Mount source path \"{}\" is not readable.", source));
};
virtual void activate_impl(ServerVariant server, std::chrono::milliseconds timeout) = 0;
virtual void deactivate_impl(bool force) = 0;
template <typename Reply, typename Request>
static Reply make_reply_from_server(grpc::ServerReaderWriterInterface<Reply, Request>*)
{
return Reply{};
}
template <typename Reply, typename Request>
static Request make_request_from_server(grpc::ServerReaderWriterInterface<Reply, Request>*)
{
return Request{};
}
VirtualMachine* vm;
const SSHKeyProvider* ssh_key_provider;
const VMMount mount_spec = {};
const std::string target;
const std::string& source = mount_spec.get_source_path();
bool active;
std::mutex active_mutex;
};
} // namespace multipass
#endif // MULTIPASS_MOUNT_HANDLER_H
| 4,434
|
C++
|
.h
| 113
| 32.884956
| 118
| 0.669533
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,872
|
vm_mount.h
|
canonical_multipass/include/multipass/vm_mount.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VM_MOUNT_H
#define MULTIPASS_VM_MOUNT_H
#include <multipass/id_mappings.h>
#include <QJsonObject>
#include <string>
namespace multipass
{
class VMMount
{
public:
enum class MountType : int
{
Classic = 0,
Native = 1
};
VMMount() = default;
explicit VMMount(const QJsonObject& json);
VMMount(const std::string& sourcePath, id_mappings gidMappings, id_mappings uidMappings, MountType mountType);
QJsonObject serialize() const;
const std::string& get_source_path() const noexcept;
const id_mappings& get_gid_mappings() const noexcept;
const id_mappings& get_uid_mappings() const noexcept;
MountType get_mount_type() const noexcept;
friend bool operator==(const VMMount& a, const VMMount& b) noexcept;
friend bool operator!=(const VMMount& a, const VMMount& b) noexcept;
private:
std::string source_path;
id_mappings gid_mappings;
id_mappings uid_mappings;
MountType mount_type;
};
inline const std::string& VMMount::get_source_path() const noexcept
{
return source_path;
}
inline const multipass::id_mappings& VMMount::get_gid_mappings() const noexcept
{
return gid_mappings;
}
inline const multipass::id_mappings& VMMount::get_uid_mappings() const noexcept
{
return uid_mappings;
}
inline VMMount::MountType VMMount::get_mount_type() const noexcept
{
return mount_type;
}
inline bool operator==(const VMMount& a, const VMMount& b) noexcept
{
return std::tie(a.source_path, a.gid_mappings, a.uid_mappings, a.mount_type) ==
std::tie(b.source_path, b.gid_mappings, b.uid_mappings, b.mount_type);
}
inline bool operator!=(const VMMount& a, const VMMount& b) noexcept // TODO drop in C++20
{
return !(a == b);
}
} // namespace multipass
namespace fmt
{
template <>
struct formatter<multipass::VMMount::MountType>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const multipass::VMMount::MountType& mount_type, FormatContext& ctx) const
{
return format_to(ctx.out(), "{}", static_cast<int>(mount_type));
}
};
} // namespace fmt
#endif // MULTIPASS_VM_MOUNT_H
| 2,880
|
C++
|
.h
| 91
| 28.428571
| 114
| 0.726255
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,873
|
format.h
|
canonical_multipass/include/multipass/format.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_FORMAT_H
#define MULTIPASS_FORMAT_H
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <QByteArray>
#include <QProcess>
#include <QString>
namespace fmt
{
template <>
struct formatter<QByteArray>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const QByteArray& a, FormatContext& ctx) const
{
return format_to(ctx.out(), "{}", a.toStdString()); // TODO: remove the copy?
}
};
template <>
struct formatter<QString>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const QString& a, FormatContext& ctx) const
{
return format_to(ctx.out(), "{}", a.toStdString()); // TODO: remove the copy?
}
};
template <>
struct formatter<QProcess::ExitStatus>
{
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const QProcess::ExitStatus& exit_status, FormatContext& ctx) const
{
return format_to(ctx.out(), "{}", static_cast<int>(exit_status));
}
};
} // namespace fmt
#endif // MULTIPASS_FORMAT_H
| 2,001
|
C++
|
.h
| 70
| 25.157143
| 85
| 0.708333
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,874
|
new_release_info.h
|
canonical_multipass/include/multipass/new_release_info.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_NEW_RELEASE_INFO_H
#define MULTIPASS_NEW_RELEASE_INFO_H
#include <QMetaType>
#include <QUrl>
namespace multipass
{
struct NewReleaseInfo
{
QString version;
QUrl url;
QString title;
QString description;
};
} // namespace multipass
Q_DECLARE_METATYPE(multipass::NewReleaseInfo)
#endif // MULTIPASS_NEW_RELEASE_INFO_H
| 984
|
C++
|
.h
| 32
| 28.5625
| 72
| 0.765079
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,875
|
vm_image_vault.h
|
canonical_multipass/include/multipass/vm_image_vault.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VM_IMAGE_VAULT_H
#define MULTIPASS_VM_IMAGE_VAULT_H
#include "disabled_copy_move.h"
#include "fetch_type.h"
#include "memory_size.h"
#include "path.h"
#include "progress_monitor.h"
#include "vm_image_info.h"
#include <QDir>
#include <QFile>
#include <QString>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
namespace multipass
{
class VMImageHost;
namespace vault
{
// Helper functions and classes for all image vault types
QString filename_for(const Path& path);
QString copy(const QString& file_name, const QDir& output_dir);
void delete_file(const Path& path);
QString compute_image_hash(const Path& image_path);
void verify_image_download(const Path& image_path, const QString& image_hash);
QString extract_image(const Path& image_path, const ProgressMonitor& monitor, const bool delete_file = false);
std::unordered_map<std::string, VMImageHost*> configure_image_host_map(const std::vector<VMImageHost*>& image_hosts);
class DeleteOnException
{
public:
explicit DeleteOnException(const Path& path) : file(path)
{
}
~DeleteOnException()
{
if (std::uncaught_exceptions() > initial_exc_count)
{
file.remove();
}
}
private:
QFile file;
const int initial_exc_count = std::uncaught_exceptions();
};
} // namespace vault
class Query;
class VMImage;
class VMImageVault : private DisabledCopyMove
{
public:
using UPtr = std::unique_ptr<VMImageVault>;
using PrepareAction = std::function<VMImage(const VMImage&)>;
virtual ~VMImageVault() = default;
virtual VMImage fetch_image(const FetchType& fetch_type,
const Query& query,
const PrepareAction& prepare,
const ProgressMonitor& monitor,
const bool unlock,
const std::optional<std::string>& checksum,
const Path& save_dir) = 0;
virtual void remove(const std::string& name) = 0;
virtual bool has_record_for(const std::string& name) = 0;
virtual void prune_expired_images() = 0;
virtual void update_images(const FetchType& fetch_type, const PrepareAction& prepare,
const ProgressMonitor& monitor) = 0;
virtual MemorySize minimum_image_size_for(const std::string& id) = 0;
virtual void clone(const std::string& source_instance_name, const std::string& destination_instance_name) = 0;
virtual VMImageHost* image_host_for(const std::string& remote_name) const = 0;
virtual std::vector<std::pair<std::string, VMImageInfo>> all_info_for(const Query& query) const = 0;
protected:
VMImageVault() = default;
};
} // namespace multipass
#endif // MULTIPASS_VM_IMAGE_VAULT_H
| 3,500
|
C++
|
.h
| 94
| 32.319149
| 117
| 0.699058
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,876
|
callable_traits.h
|
canonical_multipass/include/multipass/callable_traits.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#ifndef MULTIPASS_CALLABLE_TRAITS_H
#define MULTIPASS_CALLABLE_TRAITS_H
#include <tuple>
namespace multipass
{
// For lambdas, look at their function operator
// For functors, look at their function-call operator
template <typename T>
struct callable_traits : public callable_traits<decltype(&T::operator())>
{
};
// Deal with references and pointers
template <typename T>
struct callable_traits<T&> : public callable_traits<T>
{
};
template <typename T>
struct callable_traits<T*> : public callable_traits<T>
{
};
// Deal with member functions
template <typename ClassType, typename ReturnType, typename... Args>
struct callable_traits<ReturnType (ClassType::*)(Args...) const> : public callable_traits<ReturnType(Args...)>
{
};
template <typename ClassType, typename ReturnType, typename... Args>
struct callable_traits<ReturnType (ClassType::*)(Args...)> : public callable_traits<ReturnType(Args...)>
{
};
// Finally, the most basic function type, where all others will drain
template <typename ReturnType, typename... Args>
struct callable_traits<ReturnType(Args...)>
{
using return_type = ReturnType;
static constexpr std::size_t num_args = sizeof...(Args);
template <std::size_t N>
struct arg
{
static_assert(N < num_args,
"error: argument index is greater than number of arguments in function");
using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
};
};
}
#endif // MULTIPASS_CALLABLE_TRAITS_H
| 2,187
|
C++
|
.h
| 63
| 32.31746
| 110
| 0.740426
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,877
|
constants.h
|
canonical_multipass/include/multipass/constants.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_CONSTANTS_H
#define MULTIPASS_CONSTANTS_H
#include <chrono>
#include <initializer_list>
using namespace std::chrono_literals;
namespace multipass
{
constexpr auto client_name = "multipass";
constexpr auto daemon_name = "multipassd";
constexpr auto snapcraft_remote = "snapcraft";
constexpr auto min_memory_size = "128M";
constexpr auto min_disk_size = "512M";
constexpr auto min_cpu_cores = "1";
constexpr auto default_memory_size = "1G";
constexpr auto default_disk_size = "5G";
constexpr auto default_cpu_cores = min_cpu_cores;
constexpr auto default_timeout = std::chrono::seconds(300);
constexpr auto image_resize_timeout = std::chrono::duration_cast<std::chrono::milliseconds>(5min).count();
constexpr auto home_automount_dir = "Home";
constexpr auto multipass_storage_env_var = "MULTIPASS_STORAGE";
constexpr auto driver_env_var = "MULTIPASS_VM_DRIVER";
constexpr auto winterm_profile_guid =
"{aaaa9e6d-1e09-4be6-b76c-82b4ba1885fb}"; // identifies the primary Multipass profile in Windows Terminal
constexpr auto bridged_network_name = "bridged";
constexpr auto settings_extension = ".conf";
constexpr auto daemon_settings_root = "local";
constexpr auto petenv_key = "client.primary-name"; // This will eventually be moved to some dynamic settings schema
constexpr auto driver_key = "local.driver"; // idem
constexpr auto passphrase_key = "local.passphrase"; // idem
constexpr auto bridged_interface_key = "local.bridged-network"; // idem
constexpr auto mounts_key = "local.privileged-mounts"; // idem
constexpr auto winterm_key = "client.apps.windows-terminal.profiles"; // idem
constexpr auto mirror_key = "local.image.mirror"; // idem; this defines the mirror of simple streams
constexpr auto cloud_init_file_name = "cloud-init-config.iso";
[[maybe_unused]] // hands off clang-format
constexpr auto key_examples = {petenv_key, driver_key, mounts_key};
constexpr auto petenv_default = "primary";
constexpr auto timeout_exit_code = 5;
constexpr auto authenticated_certs_dir = "authenticated-certs";
} // namespace multipass
#endif // MULTIPASS_CONSTANTS_H
| 2,782
|
C++
|
.h
| 57
| 47.140351
| 120
| 0.759793
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,878
|
vm_image.h
|
canonical_multipass/include/multipass/vm_image.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VIRTUAL_MACHINE_IMAGE_H
#define MULTIPASS_VIRTUAL_MACHINE_IMAGE_H
#include <multipass/path.h>
#include <vector>
namespace multipass
{
class VMImage
{
public:
Path image_path;
std::string id;
std::string original_release;
std::string current_release;
std::string release_date;
std::vector<std::string> aliases;
};
}
#endif // MULTIPASS_VIRTUAL_MACHINE_IMAGE_H
| 1,033
|
C++
|
.h
| 34
| 28.117647
| 72
| 0.754774
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,879
|
virtual_machine.h
|
canonical_multipass/include/multipass/virtual_machine.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_VIRTUAL_MACHINE_H
#define MULTIPASS_VIRTUAL_MACHINE_H
#include "disabled_copy_move.h"
#include "ip_address.h"
#include "network_interface.h"
#include "path.h"
#include <QDir>
#include <QJsonObject>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <vector>
namespace multipass
{
class MemorySize;
class VMMount;
struct VMSpecs;
class MountHandler;
class Snapshot;
class VirtualMachine : private DisabledCopyMove
{
public:
enum class State
{
off,
stopped,
starting,
restarting,
running,
delayed_shutdown,
suspending,
suspended,
unknown
};
enum class ShutdownPolicy
{
Powerdown, // gracefully shut down the vm
Poweroff, // forcefully shut down the vm
Halt // halt the vm to non-running state. More specifically. suspended and stopped state will remain the same
// and running state will be shut down to stopped state
};
using UPtr = std::unique_ptr<VirtualMachine>;
using ShPtr = std::shared_ptr<VirtualMachine>;
virtual ~VirtualMachine() = default;
virtual void start() = 0;
virtual void shutdown(ShutdownPolicy shutdown_policy = ShutdownPolicy::Powerdown) = 0;
virtual void suspend() = 0;
virtual State current_state() = 0;
virtual int ssh_port() = 0;
virtual std::string ssh_hostname()
{
return ssh_hostname(std::chrono::minutes(2));
};
virtual std::string ssh_hostname(std::chrono::milliseconds timeout) = 0;
virtual std::string ssh_username() = 0;
virtual std::string management_ipv4() = 0;
virtual std::vector<std::string> get_all_ipv4() = 0;
virtual std::string ipv6() = 0;
// careful: default param in virtual method; be sure to keep the same value in all descendants
virtual std::string ssh_exec(const std::string& cmd, bool whisper = false) = 0;
virtual void wait_until_ssh_up(std::chrono::milliseconds timeout) = 0;
virtual void wait_for_cloud_init(std::chrono::milliseconds timeout) = 0;
virtual void ensure_vm_is_running() = 0;
virtual void update_state() = 0;
virtual void update_cpus(int num_cores) = 0;
virtual void resize_memory(const MemorySize& new_size) = 0;
virtual void resize_disk(const MemorySize& new_size) = 0;
virtual void add_network_interface(int index,
const std::string& default_mac_addr,
const NetworkInterface& extra_interface) = 0;
virtual std::unique_ptr<MountHandler> make_native_mount_handler(const std::string& target,
const VMMount& mount) = 0;
using SnapshotVista = std::vector<std::shared_ptr<const Snapshot>>; // using vista to avoid confusion with C++ views
virtual SnapshotVista view_snapshots() const = 0;
virtual int get_num_snapshots() const = 0;
virtual std::shared_ptr<const Snapshot> get_snapshot(const std::string& name) const = 0;
virtual std::shared_ptr<const Snapshot> get_snapshot(int index) const = 0;
virtual std::shared_ptr<Snapshot> get_snapshot(const std::string& name) = 0;
virtual std::shared_ptr<Snapshot> get_snapshot(int index) = 0;
virtual std::shared_ptr<const Snapshot> take_snapshot(const VMSpecs& specs,
const std::string& snapshot_name,
const std::string& comment) = 0;
virtual void rename_snapshot(const std::string& old_name,
const std::string& new_name) = 0; // only VM can avoid repeated names
virtual void delete_snapshot(const std::string& name) = 0;
virtual void restore_snapshot(const std::string& name, VMSpecs& specs) = 0;
virtual void load_snapshots() = 0;
virtual std::vector<std::string> get_childrens_names(const Snapshot* parent) const = 0;
virtual int get_snapshot_count() const = 0;
virtual void remove_snapshots_from_image() const = 0;
QDir instance_directory() const;
VirtualMachine::State state;
const std::string vm_name;
std::condition_variable state_wait;
std::mutex state_mutex;
std::optional<IPAddress> management_ip;
bool shutdown_while_starting{false};
protected:
const QDir instance_dir;
VirtualMachine(VirtualMachine::State state, const std::string& vm_name, const Path& instance_dir)
: state{state}, vm_name{vm_name}, instance_dir{QDir{instance_dir}} {};
VirtualMachine(const std::string& vm_name, const Path& instance_dir)
: VirtualMachine(State::off, vm_name, instance_dir){};
};
} // namespace multipass
inline QDir multipass::VirtualMachine::instance_directory() const
{
return instance_dir; // TODO this should probably only be known at the level of the base VM
}
#endif // MULTIPASS_VIRTUAL_MACHINE_H
| 5,617
|
C++
|
.h
| 129
| 37.124031
| 120
| 0.680139
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,880
|
poco_zip_utils.h
|
canonical_multipass/include/multipass/poco_zip_utils.h
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef MULTIPASS_POCO_ZIP_UTILS_H
#define MULTIPASS_POCO_ZIP_UTILS_H
#include "singleton.h"
#include <Poco/Zip/ZipArchive.h>
#include <fstream>
#define MP_POCOZIPUTILS multipass::PocoZipUtils::instance()
namespace multipass
{
class PocoZipUtils : public Singleton<PocoZipUtils>
{
public:
PocoZipUtils(const Singleton<PocoZipUtils>::PrivatePass&) noexcept;
virtual Poco::Zip::ZipArchive zip_archive_for(std::ifstream& zip_stream) const;
};
} // namespace multipass
#endif // MULTIPASS_POCO_ZIP_UTILS_H
| 1,146
|
C++
|
.h
| 32
| 33.84375
| 83
| 0.772152
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.