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,671
|
mock_dhcp_release.cpp
|
canonical_multipass/tests/qemu/linux/mock_dhcp_release.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 <fstream>
#include <string>
namespace
{
bool should_fail(const std::string& name)
{
std::string fail{".fail"};
return std::equal(fail.rbegin(), fail.rend(), name.rbegin());
}
} // namespace
int main(int argc, char* argv[])
{
if (argc != 4)
return EXIT_FAILURE;
const std::string hw_addr{argv[3]};
if (hw_addr == "00:00:00:00:00:00")
{
abort();
}
// The first argument describes a file path which serves as a signal
// to the test using this mocked binary
std::string path{argv[1]};
std::ofstream out{path};
out << "called\n";
return should_fail(path) ? 1 : 0;
}
| 1,273
|
C++
|
.cpp
| 42
| 27.190476
| 72
| 0.689796
|
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,672
|
test_lxd_mount_handler.cpp
|
canonical_multipass/tests/lxd/test_lxd_mount_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 "mock_lxd_server_responses.h"
#include "mock_network_access_manager.h"
#include "tests/mock_file_ops.h"
#include "tests/mock_logger.h"
#include "tests/mock_virtual_machine.h"
#include "tests/stub_ssh_key_provider.h"
#include "tests/stub_status_monitor.h"
#include "tests/temp_dir.h"
#include "src/platform/backends/lxd/lxd_mount_handler.h"
#include <multipass/path.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_mount.h>
namespace mp = multipass;
namespace mpt = multipass::test;
namespace
{
class MockLXDVirtualMachine : public mpt::MockVirtualMachineT<mp::LXDVirtualMachine>
{
public:
MockLXDVirtualMachine(const mp::VirtualMachineDescription& desc,
mp::VMStatusMonitor& monitor,
mp::NetworkAccessManager* manager,
const QUrl& base_url,
const QString& bridge_name,
const QString& storage_pool,
const mp::SSHKeyProvider& key_provider)
: mpt::MockVirtualMachineT<mp::LXDVirtualMachine>{desc,
monitor,
manager,
base_url,
bridge_name,
storage_pool,
key_provider}
{
}
};
struct LXDMountHandlerTestFixture : public testing::Test
{
LXDMountHandlerTestFixture()
{
EXPECT_CALL(mock_network_access_manager, createRequest(_, _, _))
.Times(AtMost(6))
.WillRepeatedly(
[](QNetworkAccessManager::Operation, const QNetworkRequest& request, QIODevice* outgoingData) {
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
});
EXPECT_CALL(mock_file_ops, status)
.Times(AtMost(1))
.WillRepeatedly(Return(mp::fs::file_status{mp::fs::file_type::directory, mp::fs::perms::all}));
logger_scope.mock_logger->screen_logs(mpl::Level::error);
}
const std::string source_path{"sourcePath"};
const std::string target_path{"targetPath"};
mpt::MockFileOps::GuardedMock mock_file_ops_injection = mpt::MockFileOps::inject();
mpt::MockFileOps& mock_file_ops = *mock_file_ops_injection.first;
mpt::MockNetworkAccessManager mock_network_access_manager;
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
const mpt::StubSSHKeyProvider key_provider;
const mp::VMMount vm_mount{source_path, {}, {}, mp::VMMount::MountType::Native};
const QUrl base_url{"unix:///foo@1.0"};
const QString default_storage_pool{"default"};
mpt::StubVMStatusMonitor stub_monitor;
const QString bridge_name{"mpbr0"};
const mp::VirtualMachineDescription default_description{2,
mp::MemorySize{"3M"},
mp::MemorySize{}, // not used
"pied-piper-valley",
"00:16:3e:fe:f2:b9",
{},
"yoda",
{},
"",
{},
{},
{},
{}};
};
struct LXDMountHandlerInvalidGidUidParameterTests : public LXDMountHandlerTestFixture,
public testing::WithParamInterface<std::tuple<int, int, int, int>>
{
};
struct LXDMountHandlerValidGidUidParameterTests : public LXDMountHandlerTestFixture,
public testing::WithParamInterface<std::tuple<int, int>>
{
};
} // namespace
TEST_F(LXDMountHandlerTestFixture, startDoesNotThrowIfVMIsStopped)
{
NiceMock<MockLXDVirtualMachine> lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider};
mp::LXDMountHandler lxd_mount_handler(&mock_network_access_manager, &lxd_vm, &key_provider, target_path, vm_mount);
EXPECT_CALL(lxd_vm, current_state).WillOnce(Return(multipass::VirtualMachine::State::stopped));
const mp::ServerVariant dummy_server;
logger_scope.mock_logger->expect_log(mpl::Level::info, "initializing native mount ");
EXPECT_NO_THROW(lxd_mount_handler.activate(dummy_server));
}
TEST_F(LXDMountHandlerTestFixture, startThrowsIfVMIsRunning)
{
NiceMock<MockLXDVirtualMachine> lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider};
mp::LXDMountHandler lxd_mount_handler(&mock_network_access_manager, &lxd_vm, &key_provider, target_path, vm_mount);
EXPECT_CALL(lxd_vm, current_state).WillOnce(Return(multipass::VirtualMachine::State::running));
const mp::ServerVariant dummy_server;
MP_EXPECT_THROW_THAT(
lxd_mount_handler.activate(dummy_server), mp::NativeMountNeedsStoppedVMException,
mpt::match_what(AllOf(HasSubstr("Please stop the instance"), HasSubstr("before attempting native mounts."))));
}
TEST_F(LXDMountHandlerTestFixture, stopDoesNotThrowIfVMIsStopped)
{
NiceMock<MockLXDVirtualMachine> lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider};
mp::LXDMountHandler lxd_mount_handler(&mock_network_access_manager, &lxd_vm, &key_provider, target_path, vm_mount);
EXPECT_CALL(lxd_vm, current_state)
.Times(AtMost(2))
.WillRepeatedly(Return(multipass::VirtualMachine::State::stopped));
const mp::ServerVariant dummy_server;
lxd_mount_handler.activate(dummy_server);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Stopping native mount ");
EXPECT_NO_THROW(lxd_mount_handler.deactivate());
}
TEST_F(LXDMountHandlerTestFixture, stopThrowsIfVMIsRunning)
{
NiceMock<MockLXDVirtualMachine> lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider};
mp::LXDMountHandler lxd_mount_handler(&mock_network_access_manager, &lxd_vm, &key_provider, target_path, vm_mount);
EXPECT_CALL(lxd_vm, current_state).WillOnce(Return(multipass::VirtualMachine::State::stopped));
const mp::ServerVariant dummy_server;
lxd_mount_handler.activate(dummy_server);
EXPECT_CALL(lxd_vm, current_state).WillOnce(Return(multipass::VirtualMachine::State::running));
MP_EXPECT_THROW_THAT(
lxd_mount_handler.deactivate(), std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Please stop the instance"), HasSubstr("before unmount it natively."))));
}
TEST_P(LXDMountHandlerInvalidGidUidParameterTests, mountWithGidOrUid)
{
mpt::TempDir instance_dir{};
mp::LXDVirtualMachine lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
const auto& [host_gid, instance_gid, host_uid, instance_uid] = GetParam();
const mp::VMMount vm_mount{
source_path, {{host_gid, instance_gid}}, {{host_uid, instance_uid}}, mp::VMMount::MountType::Native};
MP_EXPECT_THROW_THAT(
lxd_vm.make_native_mount_handler(target_path, vm_mount);
, std::runtime_error, mpt::match_what(StrEq("LXD native mount does not accept custom ID mappings.")));
}
INSTANTIATE_TEST_SUITE_P(mountWithGidOrUidInstantiation, LXDMountHandlerInvalidGidUidParameterTests,
testing::Values(std::make_tuple(1000, -1, 1000, 1), std::make_tuple(2000, 1, 2000, 1),
std::make_tuple(2000, -1, 2000, 1)));
TEST_P(LXDMountHandlerValidGidUidParameterTests, mountWithGidOrUid)
{
mpt::TempDir instance_dir{};
mp::LXDVirtualMachine lxd_vm{default_description,
stub_monitor,
&mock_network_access_manager,
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
const auto& [host_gid, host_uid] = GetParam();
const int default_instance_id = -1;
const mp::VMMount vm_mount{source_path,
{{host_gid, default_instance_id}},
{{host_uid, default_instance_id}},
mp::VMMount::MountType::Native};
EXPECT_NO_THROW(lxd_vm.make_native_mount_handler(target_path, vm_mount));
}
INSTANTIATE_TEST_SUITE_P(mountWithGidOrUidInstantiation, LXDMountHandlerValidGidUidParameterTests,
testing::Values(std::make_tuple(1000, 1000), std::make_tuple(2000, 2000),
std::make_tuple(2000, 2000)));
| 11,368
|
C++
|
.cpp
| 213
| 35.86385
| 119
| 0.546256
|
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,673
|
test_lxd_backend.cpp
|
canonical_multipass/tests/lxd/test_lxd_backend.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 "mock_local_socket_reply.h"
#include "mock_lxd_server_responses.h"
#include "mock_network_access_manager.h"
#include "tests/common.h"
#include "tests/mock_backend_utils.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_logger.h"
#include "tests/mock_platform.h"
#include "tests/mock_status_monitor.h"
#include "tests/stub_ssh_key_provider.h"
#include "tests/stub_status_monitor.h"
#include "tests/stub_url_downloader.h"
#include "tests/temp_dir.h"
#include <src/platform/backends/lxd/lxd_virtual_machine.h>
#include <src/platform/backends/lxd/lxd_virtual_machine_factory.h>
#include <src/platform/backends/lxd/lxd_vm_image_vault.h>
#include <multipass/auto_join_thread.h>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/exceptions/start_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <multipass/network_interface_info.h>
#include <multipass/virtual_machine_description.h>
#include <QJsonDocument>
#include <QString>
#include <QUrl>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
using namespace std::chrono_literals;
namespace
{
using LXDInstanceStatusParamType = std::pair<QByteArray, mp::VirtualMachine::State>;
const QString bridge_name{"mpbr0"};
struct LXDBackend : public Test
{
LXDBackend() : mock_network_access_manager{std::make_unique<StrictMock<mpt::MockNetworkAccessManager>>()}
{
logger_scope.mock_logger->screen_logs(mpl::Level::error);
}
mp::VirtualMachineDescription default_description{2,
mp::MemorySize{"3M"},
mp::MemorySize{}, // not used
"pied-piper-valley",
"00:16:3e:fe:f2:b9",
{},
"yoda",
{},
"",
{},
{},
{},
{}};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
mpt::TempDir data_dir;
mpt::TempDir instance_dir;
mpt::StubSSHKeyProvider key_provider;
std::unique_ptr<StrictMock<mpt::MockNetworkAccessManager>> mock_network_access_manager;
QUrl base_url{"unix:///foo@1.0"};
const QString default_storage_pool{"default"};
};
struct LXDInstanceStatusTestSuite : LXDBackend, WithParamInterface<LXDInstanceStatusParamType>
{
};
const std::vector<LXDInstanceStatusParamType> lxd_instance_status_suite_inputs{
{mpt::vm_state_stopped_data, mp::VirtualMachine::State::stopped},
{mpt::vm_state_starting_data, mp::VirtualMachine::State::starting},
{mpt::vm_state_freezing_data, mp::VirtualMachine::State::suspending},
{mpt::vm_state_frozen_data, mp::VirtualMachine::State::suspended},
{mpt::vm_state_cancelling_data, mp::VirtualMachine::State::unknown},
{mpt::vm_state_error_data, mp::VirtualMachine::State::unknown},
{mpt::vm_state_other_data, mp::VirtualMachine::State::unknown},
{mpt::vm_state_fully_running_data, mp::VirtualMachine::State::running}};
} // namespace
TEST_F(LXDBackend, createsProjectStoragePoolAndNetworkOnHealthcheck)
{
bool project_created{false};
bool network_created{false};
bool storage_pool_created{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly(
[&project_created, &network_created, &storage_pool_created](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if ((url.contains("1.0/projects/multipass") || url.contains("1.0/storage-pools") ||
url.contains("1.0/networks/mpbr0")))
{
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
}
else if (url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(mpt::lxd_server_info_data);
}
}
else if (op == "POST" || op == "PUT")
{
if (url.contains("1.0/projects"))
{
const QByteArray expected_data{"{"
"\"description\":\"Project for Multipass instances\","
"\"name\":\"multipass\""
"}"};
EXPECT_EQ(data, expected_data);
project_created = true;
}
else if (url.contains("1.0/storage-pools"))
{
const QByteArray expected_data{"{"
"\"description\":\"Storage pool for Multipass\","
"\"driver\":\"dir\","
"\"name\":\"multipass\""
"}"};
EXPECT_EQ(data, expected_data);
storage_pool_created = true;
}
else if (url.contains("1.0/networks"))
{
const QByteArray expected_data{"{"
"\"description\":\"Network bridge for Multipass\","
"\"name\":\"mpbr0\"}"};
EXPECT_EQ(data, expected_data);
network_created = true;
}
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
backend.hypervisor_health_check();
EXPECT_TRUE(project_created);
EXPECT_TRUE(storage_pool_created);
EXPECT_TRUE(network_created);
}
TEST_F(LXDBackend, usesDefaultStoragePoolWhenItExistsAndNoMultipassPool)
{
bool multipass_pool_checked{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&multipass_pool_checked](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/storage-pools/default"))
{
const QByteArray storage_pool_data{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"name\": \"default\""
"},"
"\"operation\": \"\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(storage_pool_data);
}
else if (url.contains("1.0/storage-pools/multipass"))
{
multipass_pool_checked = true;
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
}
else if (url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(mpt::lxd_server_info_data);
}
}
else if (op == "POST" || op == "PUT")
{
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
logger_scope.mock_logger->expect_log(mpl::Level::debug, "Using the \'default\' storage pool.");
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
backend.hypervisor_health_check();
EXPECT_TRUE(multipass_pool_checked);
}
TEST_F(LXDBackend, usesMultipassStoragePoolWhenItExists)
{
bool multipass_pool_returned{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&multipass_pool_returned](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/storage-pools/multipass"))
{
multipass_pool_returned = true;
const QByteArray storage_pool_data{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"name\": \"multipass\""
"},"
"\"operation\": \"\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(storage_pool_data);
}
else if (url.contains("1.0/storage-pools/default"))
{
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
}
else if (url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(mpt::lxd_server_info_data);
}
}
else if (op == "POST" || op == "PUT")
{
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
logger_scope.mock_logger->expect_log(mpl::Level::debug, "Using the \'multipass\' storage pool.");
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
backend.hypervisor_health_check();
EXPECT_TRUE(multipass_pool_returned);
}
TEST_F(LXDBackend, usesMultipassPoolWhenDefaultPoolExists)
{
bool default_pool_returned{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&default_pool_returned](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/storage-pools/multipass"))
{
const QByteArray storage_pool_data{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"name\": \"multipass\""
"},"
"\"operation\": \"\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(storage_pool_data);
}
else if (url.contains("1.0/storage-pools/default"))
{
default_pool_returned = true;
const QByteArray storage_pool_data{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"name\": \"default\""
"},"
"\"operation\": \"\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(storage_pool_data);
}
else if (url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(mpt::lxd_server_info_data);
}
}
else if (op == "POST" || op == "PUT")
{
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
logger_scope.mock_logger->expect_log(mpl::Level::debug, "Using the \'multipass\' storage pool.");
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
backend.hypervisor_health_check();
}
TEST_F(LXDBackend, factory_creates_valid_virtual_machine_ptr)
{
mpt::StubVMStatusMonitor stub_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_NE(nullptr, machine);
}
TEST_F(LXDBackend, factory_creates_expected_image_vault)
{
mpt::StubVMStatusMonitor stub_monitor;
mpt::StubURLDownloader stub_downloader;
mpt::TempDir cache_dir;
mpt::TempDir data_dir;
std::vector<mp::VMImageHost*> hosts;
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
auto vault = backend.create_image_vault(hosts, &stub_downloader, cache_dir.path(), data_dir.path(), mp::days{0});
EXPECT_TRUE(dynamic_cast<mp::LXDVMImageVault*>(vault.get()));
}
TEST_F(LXDBackend, factory_does_nothing_on_configure)
{
mpt::TempDir data_dir;
mp::VirtualMachineDescription vm_desc{default_description};
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
backend.configure(vm_desc);
EXPECT_TRUE(vm_desc.cloud_init_iso.isEmpty());
}
TEST_F(LXDBackend, creates_in_stopped_state)
{
mpt::StubVMStatusMonitor stub_monitor;
bool vm_created{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_created](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/operations/0020444c-2e4c-49d5-83ed-3275e3f6d005"))
{
vm_created = true;
return new mpt::MockLocalSocketReply(mpt::create_vm_finished_data);
}
else if (vm_created && url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
}
else if (op == "POST" && url.contains("1.0/virtual-machines"))
{
return new mpt::MockLocalSocketReply(mpt::create_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_TRUE(vm_created);
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, machine_persists_and_sets_state_on_start)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool start_called{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&start_called](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley"))
{
if (url.contains("state"))
{
if (!start_called)
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("start"))
{
start_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).Times(2);
machine.start();
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::starting);
}
TEST_F(LXDBackend, machine_persists_and_sets_state_on_shutdown)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool vm_shutdown{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_shutdown](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164"))
{
vm_shutdown = true;
return new mpt::MockLocalSocketReply(mpt::vm_stop_wait_task_data);
}
else if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (vm_shutdown)
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).Times(2);
machine.shutdown();
EXPECT_TRUE(vm_shutdown);
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, machine_persists_internal_stopped_state_on_destruction)
{
mpt::MockVMStatusMonitor mock_monitor;
bool vm_created{false};
auto vm_instance_state{mp::VirtualMachine::State::off};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_created](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (!vm_created)
{
vm_created = true;
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).WillRepeatedly([&vm_instance_state](auto, auto state) {
vm_instance_state = state;
});
{
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
ASSERT_EQ(machine.state, mp::VirtualMachine::State::running);
} // Simulate multipass exiting by having the vm destruct
EXPECT_TRUE(vm_created);
EXPECT_EQ(vm_instance_state, mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, machine_does_not_update_state_in_dtor)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool vm_shutdown{false}, stop_requested{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_shutdown, &stop_requested](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164"))
{
vm_shutdown = true;
return new mpt::MockLocalSocketReply(mpt::vm_stop_wait_task_data);
}
else if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (vm_shutdown)
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
stop_requested = true;
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).Times(0);
// create in its own scope so the dtor is called
{
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
EXPECT_TRUE(vm_shutdown);
EXPECT_TRUE(stop_requested);
}
TEST_F(LXDBackend, machineLogsNotFoundExceptionInDtor)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool vm_shutdown{false}, stop_requested{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_shutdown, &stop_requested](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164"))
{
vm_shutdown = true;
return new mpt::MockLocalSocketReply(mpt::vm_stop_wait_task_data);
}
else if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (vm_shutdown)
{
throw mp::LXDNotFoundException();
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
stop_requested = true;
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::debug), mpt::MockLogger::make_cstring_matcher(StrEq("pied-piper-valley")),
mpt::MockLogger::make_cstring_matcher(StrEq("LXD object not found"))));
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
// create in its own scope so the dtor is called
{
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
machine.shutdown();
}
EXPECT_TRUE(vm_shutdown);
EXPECT_TRUE(stop_requested);
}
TEST_F(LXDBackend, does_not_call_stop_when_snap_refresh_is_detected)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool stop_requested{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&stop_requested](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
stop_requested = true;
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
QTemporaryDir common_dir;
mpt::SetEnvScope env("SNAP_COMMON", common_dir.path().toUtf8());
mpt::SetEnvScope env2("SNAP_NAME", "multipass");
QFile refresh_file{common_dir.path() + "/snap_refresh"};
refresh_file.open(QIODevice::WriteOnly);
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).Times(0);
// create in its own scope so the dtor is called
{
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
EXPECT_FALSE(stop_requested);
}
TEST_F(LXDBackend, calls_stop_when_snap_refresh_does_not_exist)
{
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
bool stop_requested{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&stop_requested](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
stop_requested = true;
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
QTemporaryDir common_dir;
mpt::SetEnvScope env("SNAP_COMMON", common_dir.path().toUtf8());
mpt::SetEnvScope env2("SNAP_NAME", "multipass");
EXPECT_CALL(mock_monitor, persist_state_for(_, _)).Times(0);
// create in its own scope so the dtor is called
{
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
EXPECT_TRUE(stop_requested);
}
TEST_F(LXDBackend, posts_expected_data_when_creating_instance)
{
mpt::StubVMStatusMonitor stub_monitor;
default_description.meta_data_config = YAML::Load("Luke: Jedi");
default_description.user_data_config = YAML::Load("Vader: Sith");
default_description.vendor_data_config = YAML::Load("Solo: Scoundrel");
default_description.disk_space = mp::MemorySize("16000000000");
QByteArray expected_data{"{"
"\"config\":{"
"\"limits.cpu\":\"2\","
"\"limits.memory\":\"3145728\","
"\"security.secureboot\":\"false\","
"\"user.meta-data\":\"#cloud-config\\nLuke: Jedi\\n\","
"\"user.user-data\":\"#cloud-config\\nVader: Sith\\n\","
"\"user.vendor-data\":\"#cloud-config\\nSolo: Scoundrel\\n\""
"},"
"\"devices\":{"
"\"config\":{"
"\"source\":\"cloud-init:config\","
"\"type\":\"disk\""
"},"
"\"eth0\":{"
"\"hwaddr\":\"00:16:3e:fe:f2:b9\","
"\"name\":\"eth0\","
"\"nictype\":\"bridged\","
"\"parent\":\"mpbr0\","
"\"type\":\"nic\""
"},"
"\"root\":{"
"\"path\":\"/\","
"\"pool\":\"default\","
"\"size\":\"16000000000\","
"\"type\":\"disk\""
"}"
"},"
"\"name\":\"pied-piper-valley\","
"\"source\":{"
"\"fingerprint\":\"\","
"\"type\":\"image\""
"}"
"}"};
bool vm_created{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&vm_created, &expected_data](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/operations/0020444c-2e4c-49d5-83ed-3275e3f6d005"))
{
vm_created = true;
return new mpt::MockLocalSocketReply(mpt::create_vm_finished_data);
}
else if (vm_created && url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
}
else if (op == "POST" && url.contains("1.0/virtual-machines"))
{
// This is the test to ensure the expected data
EXPECT_EQ(data, expected_data);
return new mpt::MockLocalSocketReply(mpt::create_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
TEST_F(LXDBackend, prepare_source_image_does_not_modify)
{
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
const mp::VMImage original_image{"/path/to/image", "deadbeef", "bin", "baz", "the past",
{"fee", "fi", "fo", "fum"}};
auto source_image = backend.prepare_source_image(original_image);
EXPECT_EQ(source_image.image_path, original_image.image_path);
EXPECT_EQ(source_image.id, original_image.id);
EXPECT_EQ(source_image.original_release, original_image.original_release);
EXPECT_EQ(source_image.current_release, original_image.current_release);
EXPECT_EQ(source_image.release_date, original_image.release_date);
EXPECT_EQ(source_image.aliases, original_image.aliases);
}
TEST_F(LXDBackend, returns_expected_backend_string)
{
const QByteArray server_data{"{"
"\"type\": \"sync\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"operation\": \"\","
"\"error_code\": 0,"
"\"error\": \"\","
"\"metadata\": {"
" \"config\": {},"
" \"api_status\": \"stable\","
" \"api_version\": \"1.0\","
" \"auth\": \"untrusted\","
" \"public\": false,"
" \"auth_methods\": ["
" \"tls\""
" ],"
" \"environment\": {"
" \"server_version\": \"4.3\""
" }"
" }"
"}\n"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&server_data](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(server_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
const QString backend_string{"lxd-4.3"};
EXPECT_EQ(backend.get_backend_version_string(), backend_string);
}
TEST_F(LXDBackend, unimplemented_functions_logs_trace_message)
{
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
const std::string name{"foo"};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("lxd factory")),
mpt::MockLogger::make_cstring_matcher(
StrEq(fmt::format("No further resources to remove for \"{}\"", name)))));
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("lxd factory")),
mpt::MockLogger::make_cstring_matcher(StrEq("No driver preparation for instance image"))));
mp::VMImage image;
YAML::Node node;
backend.remove_resources_for(name);
backend.prepare_instance_image(image, default_description);
}
TEST_F(LXDBackend, factoryDoesNotSupportSuspend)
{
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
MP_EXPECT_THROW_THAT(backend.require_suspend_support(),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("suspend")));
}
TEST_F(LXDBackend, image_fetch_type_returns_expected_type)
{
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_EQ(backend.fetch_type(), mp::FetchType::ImageOnly);
}
TEST_F(LXDBackend, healthcheck_throws_when_untrusted)
{
const QByteArray untrusted_data{"{"
"\"type\": \"sync\","
"\"status\": \"Success\","
"\"status_code\": 200,"
"\"operation\": \"\","
"\"error_code\": 0,"
"\"error\": \"\","
"\"metadata\": {"
" \"config\": {},"
" \"api_status\": \"stable\","
" \"api_version\": \"1.0\","
" \"auth\": \"untrusted\","
" \"public\": false,"
" \"auth_methods\": ["
" \"tls\""
" ]"
" }"
"}\n"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&untrusted_data](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0"))
{
return new mpt::MockLocalSocketReply(untrusted_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
MP_EXPECT_THROW_THAT(backend.hypervisor_health_check(), std::runtime_error,
mpt::match_what(StrEq("Failed to authenticate to LXD.")));
}
TEST_F(LXDBackend, healthcheck_connection_refused_error_throws_with_expected_message)
{
const std::string exception_message{"Connection refused"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
MP_EXPECT_THROW_THAT(backend.hypervisor_health_check(), std::runtime_error,
mpt::match_what(StrEq(fmt::format("{}\n\nPlease ensure the LXD snap is installed and enabled.",
exception_message))));
}
TEST_F(LXDBackend, healthcheck_unknown_server_error_throws_with_expected_message)
{
const std::string exception_message{"Unknown server"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
MP_EXPECT_THROW_THAT(backend.hypervisor_health_check(), std::runtime_error,
mpt::match_what(StrEq(fmt::format("{}\n\nPlease ensure the LXD snap is installed and enabled.",
exception_message))));
}
TEST_F(LXDBackend, healthcheck_error_advises_snap_connections_when_in_snap)
{
EXPECT_CALL(*mock_network_access_manager, createRequest).WillOnce(Throw(mp::LocalSocketConnectionException("")));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
mpt::SetEnvScope env{"SNAP_NAME", "multipass"};
MP_EXPECT_THROW_THAT(backend.hypervisor_health_check(), std::runtime_error,
mpt::match_what(HasSubstr("snap connect multipass:lxd lxd")));
}
struct LXDNetworkInfoSuite : LXDBackend, WithParamInterface<QByteArray>
{
};
TEST_P(LXDNetworkInfoSuite, returns_expected_network_info)
{
const auto leases_data = GetParam();
mpt::StubVMStatusMonitor stub_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&leases_data](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
else if (url.contains("1.0/networks/" + bridge_name + "/leases"))
{
return new mpt::MockLocalSocketReply(leases_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_EQ(machine.management_ipv4(), "10.217.27.168");
EXPECT_TRUE(machine.ipv6().empty());
EXPECT_EQ(machine.ssh_username(), default_description.ssh_username);
EXPECT_EQ(machine.ssh_port(), 22);
EXPECT_EQ(machine.VirtualMachine::ssh_hostname(), "10.217.27.168");
}
INSTANTIATE_TEST_SUITE_P(LXDBackend, LXDNetworkInfoSuite,
Values(mpt::network_leases_data, mpt::network_leases_data_with_ipv6,
mpt::network_leases_data_with_others));
TEST_F(LXDBackend, ssh_hostname_timeout_throws_and_sets_unknown_state)
{
mpt::StubVMStatusMonitor stub_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
else if (url.contains("1.0/networks/" + bridge_name + "/leases"))
{
return new mpt::MockLocalSocketReply(mpt::network_no_leases_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_THROW(machine.ssh_hostname(std::chrono::milliseconds(1)), std::runtime_error);
EXPECT_EQ(machine.state, mp::VirtualMachine::State::unknown);
}
TEST_F(LXDBackend, no_ip_address_returns_unknown)
{
mpt::StubVMStatusMonitor stub_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_partial_running_data);
}
else if (url.contains("1.0/networks/" + bridge_name + "/leases"))
{
return new mpt::MockLocalSocketReply(mpt::network_no_leases_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_EQ(machine.management_ipv4(), "UNKNOWN");
}
TEST_F(LXDBackend, lxd_request_timeout_aborts_and_throws)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto...) {
QByteArray data;
auto reply = new mpt::MockLocalSocketReply(data);
reply->setFinished(false);
return reply;
});
base_url.setHost("test");
const std::string op{"GET"};
const std::string error_string{
fmt::format("Timeout getting response for {} operation on {}", op, base_url.toString().toStdString())};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(HasSubstr(error_string))));
MP_EXPECT_THROW_THAT(mp::lxd_request(mock_network_access_manager.get(), op, base_url, std::nullopt, 3),
std::runtime_error, mpt::match_what(HasSubstr(error_string)));
}
TEST_F(LXDBackend, lxd_request_empty_data_returned_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto...) {
QByteArray data;
auto reply = new mpt::MockLocalSocketReply(data);
return reply;
});
base_url.setHost("test");
const std::string op{"GET"};
const std::string error_string{
fmt::format("Empty reply received for {} operation on {}", op, base_url.toString().toStdString())};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(HasSubstr(error_string))));
MP_EXPECT_THROW_THAT(mp::lxd_request(mock_network_access_manager.get(), op, base_url), std::runtime_error,
mpt::match_what(HasSubstr(error_string)));
}
TEST_F(LXDBackend, lxd_request_invalid_json_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
QByteArray invalid_json{"not json\r\n"};
return new mpt::MockLocalSocketReply(invalid_json);
});
base_url.setHost("test");
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::debug), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr(base_url.toString().toStdString()), HasSubstr("illegal value")))));
MP_EXPECT_THROW_THAT(
mp::lxd_request(mock_network_access_manager.get(), "GET", base_url), std::runtime_error,
mpt::match_what(AllOf(HasSubstr(base_url.toString().toStdString()), HasSubstr("illegal value"))));
}
TEST_F(LXDBackend, lxd_request_wrong_json_throws_and_logs)
{
QByteArray invalid_json{"[]\r\n"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce([&invalid_json](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
return new mpt::MockLocalSocketReply(invalid_json);
});
base_url.setHost("test");
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::debug), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr(base_url.toString().toStdString()), HasSubstr(invalid_json.toStdString())))));
MP_EXPECT_THROW_THAT(mp::lxd_request(mock_network_access_manager.get(), "GET", base_url), std::runtime_error,
mpt::match_what(AllOf(HasSubstr(base_url.toString().toStdString()))));
}
TEST_F(LXDBackend, lxd_request_bad_request_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto...) {
const QByteArray error_data{"{"
"\"type\": \"error\","
"\"error\": \"Failure\","
"\"error_code\": 400,"
"\"metadata\": {}"
"}"};
return new mpt::MockLocalSocketReply(error_data, QNetworkReply::ProtocolInvalidOperationError);
});
base_url.setHost("test");
auto error_matcher = AllOf(HasSubstr("Network error for"), HasSubstr(base_url.toString().toStdString()),
HasSubstr(": Error - Failure"));
EXPECT_CALL(*logger_scope.mock_logger,
log(_,
mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(error_matcher)));
MP_EXPECT_THROW_THAT(mp::lxd_request(mock_network_access_manager.get(), "GET", base_url), std::runtime_error,
mpt::match_what(error_matcher));
}
TEST_F(LXDBackend, lxd_request_multipart_bbad_request_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto...) {
const QByteArray error_data{"{"
"\"type\": \"error\","
"\"error\": \"Failure\","
"\"error_code\": 400,"
"\"metadata\": {}"
"}"};
return new mpt::MockLocalSocketReply(error_data, QNetworkReply::ProtocolInvalidOperationError);
});
base_url.setHost("test");
auto error_matcher = AllOf(HasSubstr("Network error for"), HasSubstr(base_url.toString().toStdString()),
HasSubstr(": Error - Failure"));
QHttpMultiPart stub_multipart;
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(error_matcher)));
MP_EXPECT_THROW_THAT(mp::lxd_request(mock_network_access_manager.get(), "GET", base_url, stub_multipart),
std::runtime_error, mpt::match_what(error_matcher));
}
TEST_F(LXDBackend, lxd_wait_error_returned_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164/wait"))
{
const QByteArray wait_reply_error{"{"
"\"error\": \"Failure\","
"\"error_code\": 400,"
"\"metadata\": {"
" \"class\": \"task\","
" \"created_at\": \"2020-11-10T11:42:58.996868033-05:00\","
" \"description\": \"Stopping container\","
" \"err\": \"\","
" \"id\": \"b043d632-5c48-44b3-983c-a25660d61164\","
" \"location\": \"none\","
" \"may_cancel\": false,"
" \"metadata\": null,"
" \"resources\": {"
" \"containers\": ["
" \"/1.0/containers/test\""
" ]"
" },"
" \"status\": \"Success\","
" \"status_code\": 200,"
" \"updated_at\": \"2020-11-10T11:42:58.996868033-05:00\""
"},"
"\"operation\": \"\","
"\"status\": \"\","
"\"status_code\": 0,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(wait_reply_error);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
base_url.setHost("test");
QJsonParseError json_error;
auto json_reply = QJsonDocument::fromJson(mpt::stop_vm_data, &json_error);
auto error_matcher = StrEq("Error waiting on operation: (400) Failure");
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(error_matcher)));
MP_EXPECT_THROW_THAT(mp::lxd_wait(mock_network_access_manager.get(), base_url, json_reply.object(), 1000),
std::runtime_error, mpt::match_what(error_matcher));
}
TEST_F(LXDBackend, lxd_wait_status_code_failure_returned_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164/wait"))
{
const QByteArray wait_reply_error{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"class\": \"task\","
" \"created_at\": \"2020-11-10T11:42:58.996868033-05:00\","
" \"description\": \"Stopping container\","
" \"err\": \"\","
" \"id\": \"b043d632-5c48-44b3-983c-a25660d61164\","
" \"location\": \"none\","
" \"may_cancel\": false,"
" \"metadata\": null,"
" \"resources\": {"
" \"containers\": ["
" \"/1.0/containers/test\""
" ]"
" },"
" \"status\": \"Success\","
" \"status_code\": 200,"
" \"updated_at\": \"2020-11-10T11:42:58.996868033-05:00\""
"},"
"\"operation\": \"\","
"\"status\": \"Bad status\","
"\"status_code\": 400,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(wait_reply_error);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
base_url.setHost("test");
QJsonParseError json_error;
auto json_reply = QJsonDocument::fromJson(mpt::stop_vm_data, &json_error);
auto error_matcher = StrEq("Failure waiting on operation: (400) Bad status");
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(error_matcher)));
MP_EXPECT_THROW_THAT(mp::lxd_wait(mock_network_access_manager.get(), base_url, json_reply.object(), 1000),
std::runtime_error, mpt::match_what(error_matcher));
}
TEST_F(LXDBackend, lxd_wait_metadata_status_code_failure_returned_throws_and_logs)
{
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/operations/b043d632-5c48-44b3-983c-a25660d61164/wait"))
{
const QByteArray wait_reply_error{"{"
"\"error\": \"\","
"\"error_code\": 0,"
"\"metadata\": {"
" \"class\": \"task\","
" \"created_at\": \"2020-11-10T11:42:58.996868033-05:00\","
" \"description\": \"Stopping container\","
" \"err\": \"Failed to stop instance\","
" \"id\": \"b043d632-5c48-44b3-983c-a25660d61164\","
" \"location\": \"none\","
" \"may_cancel\": false,"
" \"metadata\": null,"
" \"resources\": {"
" \"containers\": ["
" \"/1.0/containers/test\""
" ]"
" },"
" \"status\": \"Failure\","
" \"status_code\": 400,"
" \"updated_at\": \"2020-11-10T11:42:58.996868033-05:00\""
"},"
"\"operation\": \"\","
"\"status\": \"Success\","
"\"status_code\": 0,"
"\"type\": \"sync\""
"}"};
return new mpt::MockLocalSocketReply(wait_reply_error);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
base_url.setHost("test");
QJsonParseError json_error;
auto json_reply = QJsonDocument::fromJson(mpt::stop_vm_data, &json_error);
auto error_matcher = StrEq("Operation completed with error: (400) Failed to stop instance");
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::error), mpt::MockLogger::make_cstring_matcher(StrEq("lxd request")),
mpt::MockLogger::make_cstring_matcher(error_matcher)));
MP_EXPECT_THROW_THAT(mp::lxd_wait(mock_network_access_manager.get(), base_url, json_reply.object(), 1000),
std::runtime_error, mpt::match_what(error_matcher));
}
TEST_F(LXDBackend, unsupported_suspend_throws)
{
mpt::StubVMStatusMonitor stub_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_fully_running_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
MP_EXPECT_THROW_THAT(machine.suspend(),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("suspend")));
}
TEST_F(LXDBackend, start_while_frozen_unfreezes)
{
mpt::StubVMStatusMonitor stub_monitor;
bool unfreeze_called{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&unfreeze_called](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_frozen_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("unfreeze"))
{
unfreeze_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::info), mpt::MockLogger::make_cstring_matcher(StrEq("pied-piper-valley")),
mpt::MockLogger::make_cstring_matcher(StrEq("Resuming from a suspended state"))));
machine.start();
EXPECT_TRUE(unfreeze_called);
}
TEST_F(LXDBackend, shutdown_while_stopped_does_nothing_and_logs_debug)
{
mpt::MockVMStatusMonitor mock_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillRepeatedly([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
ASSERT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(
*logger_scope.mock_logger,
log(Eq(mpl::Level::info),
mpt::MockLogger::make_cstring_matcher(StrEq("pied-piper-valley")),
mpt::MockLogger::make_cstring_matcher(StrEq("Ignoring shutdown since instance is already stopped."))));
machine.shutdown();
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, shutdown_while_frozen_throws_and_logs_info)
{
const std::string sub_error_msg{"Cannot shut down suspended instance"};
mpt::MockVMStatusMonitor mock_monitor;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillRepeatedly([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_frozen_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
mock_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
ASSERT_EQ(machine.current_state(), mp::VirtualMachine::State::suspended);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
MP_EXPECT_THROW_THAT(machine.shutdown(), mp::VMStateInvalidException, mpt::match_what(HasSubstr(sub_error_msg)));
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::suspended);
}
TEST_F(LXDBackend, ensure_vm_running_does_not_throw_starting)
{
mpt::StubVMStatusMonitor stub_monitor;
bool start_called{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&start_called](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (!start_called)
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_starting_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (data.contains("start"))
{
start_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
machine.start();
ASSERT_EQ(machine.state, mp::VirtualMachine::State::starting);
EXPECT_NO_THROW(machine.ensure_vm_is_running());
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::starting);
}
TEST_F(LXDBackend, shutdown_while_starting_throws_and_sets_correct_state)
{
mpt::StubVMStatusMonitor stub_monitor;
bool stop_called{false}, start_called{false};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&stop_called, &start_called](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if ((!stop_called && !start_called) || (stop_called && start_called))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
else
{
return new mpt::MockLocalSocketReply(mpt::vm_state_starting_data);
}
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (data.contains("start"))
{
start_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
else if (data.contains("stop"))
{
stop_called = true;
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
machine.start();
ASSERT_EQ(machine.state, mp::VirtualMachine::State::starting);
mp::AutoJoinThread thread = [&machine] {
machine.shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff);
}; // force shutdown
while (machine.state != mp::VirtualMachine::State::off)
std::this_thread::sleep_for(1ms);
MP_EXPECT_THROW_THAT(machine.ensure_vm_is_running(1ms), mp::StartException,
mpt::match_what(StrEq("Instance shutdown during start")));
EXPECT_TRUE(start_called);
EXPECT_TRUE(stop_called);
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, start_failure_while_starting_throws_and_sets_correct_state)
{
mpt::StubVMStatusMonitor stub_monitor;
bool start_called{false};
int running_returned{0};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&start_called, &running_returned](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (!start_called || running_returned > 1)
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
++running_returned;
return new mpt::MockLocalSocketReply(mpt::vm_state_partial_running_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("start"))
{
start_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
machine.start();
ASSERT_EQ(machine.state, mp::VirtualMachine::State::starting);
EXPECT_NO_THROW(machine.ensure_vm_is_running(1ms));
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::starting);
MP_EXPECT_THROW_THAT(machine.ensure_vm_is_running(1ms), mp::StartException,
mpt::match_what(StrEq("Instance shutdown during start")));
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::stopped);
}
TEST_F(LXDBackend, reboots_while_starting_does_not_throw_and_sets_correct_state)
{
mpt::StubVMStatusMonitor stub_monitor;
bool start_called{false}, reboot_simulated{false};
int running_returned{0};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&start_called, &running_returned, &reboot_simulated](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
if (!start_called || ++running_returned == 2)
{
if (running_returned == 2)
{
reboot_simulated = true;
}
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
return new mpt::MockLocalSocketReply(mpt::vm_state_partial_running_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("start"))
{
start_called = true;
return new mpt::MockLocalSocketReply(mpt::start_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
machine.start();
ASSERT_EQ(machine.current_state(), mp::VirtualMachine::State::starting);
EXPECT_NO_THROW(machine.ensure_vm_is_running(1ms));
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::starting);
EXPECT_TRUE(reboot_simulated);
}
TEST_F(LXDBackend, current_state_connection_error_logs_warning_and_sets_unknown_state)
{
mpt::StubVMStatusMonitor stub_monitor;
const std::string exception_message{"Cannot connect to socket"};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("pied-piper-valley")),
mpt::MockLogger::make_cstring_matcher(StrEq(exception_message))))
.Times(2);
EXPECT_EQ(machine.current_state(), mp::VirtualMachine::State::unknown);
}
TEST_P(LXDInstanceStatusTestSuite, lxd_state_returns_expected_VirtualMachine_state)
{
mpt::StubVMStatusMonitor stub_monitor;
const auto status_data = GetParam().first;
const auto expected_state = GetParam().second;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&status_data](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(status_data);
}
else if (op == "PUT" && url.contains("1.0/virtual-machines/pied-piper-valley/state") &&
data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
if (expected_state == multipass::VirtualMachine::State::unknown)
{
QJsonParseError json_error;
const auto json_reply = QJsonDocument::fromJson(status_data, &json_error);
ASSERT_EQ(json_error.error, QJsonParseError::NoError);
const auto metadata = json_reply["metadata"].toObject();
const auto code = metadata["status_code"].toInt();
if (code > 112)
{
QString error_msg{"unexpected LXD state: "};
error_msg += metadata["status"].toString() + " (" + QString::number(code) + ")";
logger_scope.mock_logger->expect_log(mpl::Level::error, error_msg.toStdString(), AtLeast(1));
}
}
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
EXPECT_EQ(machine.current_state(), expected_state);
}
INSTANTIATE_TEST_SUITE_P(LXDBackend, LXDInstanceStatusTestSuite, ValuesIn(lxd_instance_status_suite_inputs));
namespace
{
auto custom_request_matcher(const QString& verb, const std::string& url_sub_str)
{
auto get_verb = [](const auto& request) {
return request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
};
auto get_url = [](const auto& request) { return request.url().toString().toStdString(); };
return AllOf(ResultOf(get_verb, Eq(verb)), ResultOf(get_url, HasSubstr(url_sub_str)));
}
const auto network_request_matcher = custom_request_matcher("GET", "1.0/networks?recursion=1");
} // namespace
TEST_F(LXDBackend, requests_networks)
{
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{mpt::networks_empty_data}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THAT(backend.networks(), IsEmpty());
}
struct LXDNetworksBadJson : LXDBackend, WithParamInterface<QByteArray>
{
};
TEST_P(LXDNetworksBadJson, handles_gibberish_networks_reply)
{
auto log_matcher =
mpt::MockLogger::make_cstring_matcher(AnyOf(HasSubstr("Error parsing JSON"), HasSubstr("Empty reply")));
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::debug), _, log_matcher));
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{GetParam()}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THROW(backend.networks(), std::runtime_error);
}
INSTANTIATE_TEST_SUITE_P(LXDBackend, LXDNetworksBadJson,
Values("gibberish", "unstarted}", "{unfinished", "strange\"", "{noval}", "]["));
struct LXDNetworksBadFields : LXDBackend, WithParamInterface<QByteArray>
{
};
TEST_P(LXDNetworksBadFields, ignores_network_without_expected_fields)
{
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{GetParam()}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THAT(backend.networks(), IsEmpty());
}
INSTANTIATE_TEST_SUITE_P(LXDBackend, LXDNetworksBadFields,
Values("{}", "{\"other\": \"stuff\"}", "{\"metadata\": \"notarray\"}",
"{\"metadata\": [\"notdict\"]}",
"{\"metadata\": [{\"type\": \"bridge\", \"but\": \"noname\"}]}",
"{\"metadata\": [{\"name\": \"\", \"type\": \"bridge\", \"but\": \"empty name\"}]}",
"{\"metadata\": [{\"name\": \"bla\", \"but\": \"notype\"}]}",
"{\"metadata\": [{\"name\": 123, \"type\": \"bridge\"}]}",
"{\"metadata\": [{\"name\": \"eth0\", \"type\": 123}]}"));
struct LXDNetworksOnlySupportedTypes : LXDBackend, WithParamInterface<QByteArray>
{
};
TEST_P(LXDNetworksOnlySupportedTypes, reports_only_bridge_and_ethernet_networks)
{
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{GetParam()}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, get_network_interfaces_info)
.WillOnce(Return(std::map<std::string, mp::NetworkInterfaceInfo>{
{"lxdbr0", {"lxdbr0", "bridge", "gobbledygook"}},
{"mpbr0", {"mpbr0", "bridge", "gobbledygook"}},
{"virbr0", {"virbr0", "bridge", "gobbledygook"}},
{"mpqemubr0", {"mpqemubr0", "bridge", "gobbledygook"}},
{"enxe4b97a832426", {"enxe4b97a832426", "ethernet", "gobbledygook"}}}));
auto id_matcher = [](const std::string& expect) { return Field(&mp::NetworkInterfaceInfo::id, Eq(expect)); };
EXPECT_THAT(backend.networks(),
AllOf(Each(Field(&mp::NetworkInterfaceInfo::type, MatchesRegex("bridge|ethernet"))),
UnorderedElementsAre(id_matcher("enxe4b97a832426"), id_matcher("lxdbr0"), id_matcher("mpbr0"),
id_matcher("virbr0"), id_matcher("mpqemubr0"))));
}
INSTANTIATE_TEST_SUITE_P(LXDBackend, LXDNetworksOnlySupportedTypes,
Values(mpt::networks_realistic_data, mpt::networks_faulty_data));
TEST_F(LXDBackend, honors_bridge_description_from_lxd_when_available)
{
auto description = "Australopithecus";
auto data_template = QStringLiteral(R"({"metadata": [{"type": "bridge", "name": "br0", "description": "%1"}]})");
auto data = data_template.arg(description).toUtf8();
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{{data}}));
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, get_network_interfaces_info)
.WillOnce(Return(std::map<std::string, mp::NetworkInterfaceInfo>{{"br0", {"br0", "bridge", "gibberish"}}}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THAT(backend.networks(), ElementsAre(Field(&mp::NetworkInterfaceInfo::description, Eq(description))));
}
TEST_F(LXDBackend, falls_back_to_bridge_description_from_platform)
{
auto data = QByteArrayLiteral(R"({"metadata": [{"type": "bridge", "name": "br0", "description": ""}]})");
auto fallback_desc = "fallback";
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, get_network_interfaces_info)
.WillOnce(Return(std::map<std::string, mp::NetworkInterfaceInfo>{{"br0", {"br0", "bridge", fallback_desc}}}));
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{{data}}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THAT(backend.networks(), ElementsAre(Field(&mp::NetworkInterfaceInfo::description, Eq(fallback_desc))));
}
TEST_F(LXDBackend, skips_platform_network_inspection_when_lxd_reports_no_networks)
{
auto data = QByteArrayLiteral(R"({"metadata": []})");
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, get_network_interfaces_info).Times(0);
EXPECT_CALL(*mock_network_access_manager,
createRequest(QNetworkAccessManager::CustomOperation, network_request_matcher, _))
.WillOnce(Return(new mpt::MockLocalSocketReply{{data}}));
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_THAT(backend.networks(), IsEmpty());
}
namespace
{
Matcher<QIODevice*> request_data_matcher(Matcher<QJsonObject> json_matcher)
{
auto extract_json = [](QIODevice* device) {
device->open(QIODevice::ReadOnly);
return QJsonDocument::fromJson(device->readAll()).object();
};
return ResultOf(extract_json, json_matcher);
}
std::vector<QJsonObject> extract_devices(const QJsonObject& request_json)
{
std::vector<QJsonObject> ret; // we need an stl collection that gmock can work with
for (const auto& device : request_json["devices"].toObject())
ret.push_back(device.toObject());
return ret;
}
bool device_json_matches_interface(const QJsonObject& device, const mp::NetworkInterface& interface)
{
return device["type"] == "nic" && device["nictype"] == "bridged" &&
device["parent"].toString().toStdString() == interface.id &&
device["hwaddr"].toString().toStdString() == interface.mac_address;
}
std::vector<Matcher<QJsonObject>> device_json_matchers_from(const std::vector<mp::NetworkInterface>& interfaces)
{
std::vector<Matcher<QJsonObject>> device_matchers;
for (const auto& interface : interfaces)
{
device_matchers.push_back(Truly(
[&interface](const QJsonObject& device) { return device_json_matches_interface(device, interface); }));
}
return device_matchers;
}
void setup_vm_creation_expectations(mpt::MockNetworkAccessManager& mock_network_access_mgr,
Matcher<QIODevice*> request_contents_matcher)
{
EXPECT_CALL(mock_network_access_mgr, createRequest(QNetworkAccessManager::CustomOperation,
custom_request_matcher("GET", "pied-piper-valley/state"), _))
.Times(3)
.WillOnce(Return(new mpt::MockLocalSocketReply{mpt::not_found_data, QNetworkReply::ContentNotFoundError}))
.WillRepeatedly([] { return new mpt::MockLocalSocketReply{mpt::vm_info_data}; });
EXPECT_CALL(mock_network_access_mgr,
createRequest(QNetworkAccessManager::CustomOperation,
custom_request_matcher("POST", "virtual-machines"), request_contents_matcher))
.WillOnce(Return(new mpt::MockLocalSocketReply{mpt::create_vm_data}));
EXPECT_CALL(mock_network_access_mgr,
createRequest(QNetworkAccessManager::CustomOperation,
custom_request_matcher("GET", "operations/0020444c-2e4c-49d5-83ed-3275e3f6d005/wait"), _))
.WillOnce(Return(new mpt::MockLocalSocketReply{mpt::create_vm_finished_data}));
}
} // namespace
TEST_F(LXDBackend, posts_extra_network_devices)
{
mpt::StubVMStatusMonitor stub_monitor;
default_description.extra_interfaces.push_back({"parent1", "ab:cd:ef:01:23:45", true});
default_description.extra_interfaces.push_back({"parent2", "01:23:45:ab:cd:ef", false});
default_description.extra_interfaces.push_back({"parent3", "ba:ba:ca:ca:ca:ba", true});
auto devices_matcher = IsSupersetOf(device_json_matchers_from(default_description.extra_interfaces));
auto json_matcher = ResultOf(&extract_devices, devices_matcher);
setup_vm_creation_expectations(*mock_network_access_manager, request_data_matcher(json_matcher));
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
TEST_F(LXDBackend, posts_network_data_config_if_available)
{
mpt::StubVMStatusMonitor stub_monitor;
static constexpr auto config = "Leia: Princess";
default_description.network_data_config = config;
auto get_config = [](const auto& json) {
return json["config"].toObject()["user.network-config"].toString().toStdString();
};
auto json_matcher = ResultOf(get_config, HasSubstr(config));
setup_vm_creation_expectations(*mock_network_access_manager, request_data_matcher(json_matcher));
mp::LXDVirtualMachine machine{default_description,
stub_monitor,
mock_network_access_manager.get(),
base_url,
bridge_name,
default_storage_pool,
key_provider,
instance_dir.path()};
}
namespace
{
class CustomLXDFactory : public mp::LXDVirtualMachineFactory
{
public:
using mp::LXDVirtualMachineFactory::create_bridge_with;
using mp::LXDVirtualMachineFactory::LXDVirtualMachineFactory;
MOCK_METHOD(void, prepare_networking, (std::vector<mp::NetworkInterface>&), (override));
};
} // namespace
TEST_F(LXDBackend, prepares_networking_via_base_factory)
{
CustomLXDFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
std::vector<mp::NetworkInterface> extra_networks{{"netid", "mac", false}};
auto address = [](const auto& v) { return &v; }; // replace with Address matcher once available
EXPECT_CALL(backend, prepare_networking(ResultOf(address, Eq(&extra_networks))));
backend.prepare_networking(extra_networks);
}
TEST_F(LXDBackend, createsBridgesViaBackendUtils)
{
const auto net = mp::NetworkInterfaceInfo{"bla", "ethernet", "ble"};
const auto bridge = "bli";
auto [mock_backend, guard] = mpt::MockBackend::inject();
CustomLXDFactory factory{std::move(mock_network_access_manager), data_dir.path(), base_url};
EXPECT_CALL(*mock_backend, create_bridge_with(net.id)).WillOnce(Return(bridge));
EXPECT_EQ(factory.create_bridge_with(net), bridge);
}
TEST_F(LXDBackend, addsNetworkInterface)
{
mpt::StubVMStatusMonitor stub_monitor;
unsigned patch_times_called = 0;
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillRepeatedly([&patch_times_called](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state"))
{
return new mpt::MockLocalSocketReply(mpt::vm_state_stopped_data);
}
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
if (op == "PUT")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley/state") && data.contains("stop"))
{
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
if (url.contains("1.0/virtual-machines"))
{
return new mpt::MockLocalSocketReply(mpt::delete_vm_wait_task_data);
}
}
if (op == "PATCH")
{
++patch_times_called;
EXPECT_EQ(data.toStdString(),
"{\"devices\":{\"eth2\":{\"hwaddr\":\"52:54:00:56:78:90\",\"name\":"
"\"eth2\",\"nictype\":\"bridged\",\"parent\":\"id\",\"type\":\"nic\"}}}");
return new mpt::MockLocalSocketReply(mpt::stop_vm_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVirtualMachineFactory backend{std::move(mock_network_access_manager), data_dir.path(), base_url};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->shutdown();
machine->add_network_interface(1, "", {"id", "52:54:00:56:78:90", true});
EXPECT_EQ(patch_times_called, 1u);
}
| 104,993
|
C++
|
.cpp
| 1,982
| 36.757316
| 120
| 0.534961
|
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,674
|
test_lxd_image_vault.cpp
|
canonical_multipass/tests/lxd/test_lxd_image_vault.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 "mock_local_socket_reply.h"
#include "mock_lxd_server_responses.h"
#include "mock_network_access_manager.h"
#include "tests/common.h"
#include "tests/mock_image_host.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/stub_url_downloader.h"
#include "tests/temp_dir.h"
#include "tests/tracking_url_downloader.h"
#include <src/platform/backends/lxd/lxd_vm_image_vault.h>
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/image_vault_exceptions.h>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/format.h>
#include <multipass/vm_image.h>
#include <QUrl>
#include <vector>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct LXDImageVault : public Test
{
LXDImageVault() : mock_network_access_manager{std::make_unique<NiceMock<mpt::MockNetworkAccessManager>>()}
{
hosts.push_back(&host);
ON_CALL(host, info_for_full_hash(_)).WillByDefault([this](auto...) { return host.mock_bionic_image_info; });
logger_scope.mock_logger->screen_logs(mpl::Level::error);
}
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
std::unique_ptr<NiceMock<mpt::MockNetworkAccessManager>> mock_network_access_manager;
std::vector<mp::VMImageHost*> hosts;
NiceMock<mpt::MockImageHost> host;
QUrl base_url{"unix:///foo@1.0"};
mp::ProgressMonitor stub_monitor{[](int, int) { return true; }};
mp::VMImageVault::PrepareAction stub_prepare{
[](const mp::VMImage& source_image) -> mp::VMImage { return source_image; }};
std::string instance_name{"pied-piper-valley"};
mp::Query default_query{instance_name, "xenial", false, "", mp::Query::Type::Alias};
mpt::StubURLDownloader stub_url_downloader;
mpt::TempDir cache_dir;
mpt::TempDir save_dir;
};
} // namespace
TEST_F(LXDImageVault, instance_exists_fetch_returns_expected_image_info)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_EQ(image.id, mpt::default_id);
EXPECT_EQ(image.original_release, "18.04 LTS");
}
TEST_F(LXDImageVault, instance_exists_custom_image_returns_expected_image_info)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_custom_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_EQ(image.id, "6937ddd3f4c3329182855843571fc91ae4fee24e8e0eb0f7cdcf2c22feed4dab");
EXPECT_EQ(image.original_release, "Snapcraft builder for Core 20");
EXPECT_EQ(image.release_date, "20200923");
}
TEST_F(LXDImageVault, instance_exists_uses_cached_release_title)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data_with_image_release);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_EQ(image.id, mpt::default_id);
EXPECT_EQ(image.original_release, "Fake Title");
}
TEST_F(LXDImageVault, instance_exists_no_cached_release_title_info_for_fails)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
EXPECT_CALL(host, info_for(_)).WillRepeatedly(Throw(std::runtime_error("foo")));
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_EQ(image.id, mpt::default_id);
EXPECT_EQ(image.original_release, "");
}
TEST_F(LXDImageVault, returns_expected_info_with_valid_remote)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::Query query{"", "bionic", false, "release", mp::Query::Type::Alias};
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_EQ(image.id, mpt::default_id);
EXPECT_EQ(image.original_release, "18.04 LTS");
EXPECT_EQ(image.release_date, mpt::default_version);
}
TEST_F(LXDImageVault, throws_with_invalid_alias)
{
ON_CALL(host, info_for(_)).WillByDefault([this](auto query) -> std::optional<mp::VMImageInfo> {
if (query.release != "bionic")
{
return std::nullopt;
}
return host.mock_bionic_image_info;
});
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto...) {
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
const std::string alias{"xenial"};
mp::Query query{"", alias, false, "release", mp::Query::Type::Alias};
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
MP_EXPECT_THROW_THAT(
image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()),
std::runtime_error,
mpt::match_what(
StrEq(fmt::format("Unable to find an image matching \"{}\" in remote \"{}\".", alias, "release"))));
}
TEST_F(LXDImageVault, throws_with_invalid_remote)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto...) {
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
const std::string remote{"bar"};
mp::Query query{"", "foo", false, remote, mp::Query::Type::Alias};
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
MP_EXPECT_THROW_THAT(image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()),
std::runtime_error,
mpt::match_what(HasSubstr(fmt::format("Remote \'{}\' is not found.", remote))));
}
TEST_F(LXDImageVault, does_not_download_if_image_exists)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
}
else if (op == "POST" && url.contains("1.0/images"))
{
ADD_FAILURE() << "Image download shouldn't be requested";
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
}
TEST_F(LXDImageVault, instance_exists_missing_image_does_not_download_image)
{
bool download_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&download_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
else if (op == "POST" && url.contains("1.0/images"))
{
download_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
const auto missing_img_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
EXPECT_CALL(host, info_for(_)).WillRepeatedly(Return(host.mock_bionic_image_info));
EXPECT_CALL(host, info_for(Field(&mp::Query::release, missing_img_hash))).WillRepeatedly(Return(std::nullopt));
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
mp::VMImage image;
EXPECT_NO_THROW(image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_FALSE(download_requested);
EXPECT_EQ(image.original_release, mpt::default_release_info);
}
TEST_F(LXDImageVault, requests_download_if_image_does_not_exist)
{
bool download_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&download_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
download_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
EXPECT_TRUE(download_requested);
}
TEST_F(LXDImageVault, sets_fingerprint_with_hash_query)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([](auto, auto request, auto outgoingData) {
outgoingData->open(QIODevice::ReadOnly);
auto data = outgoingData->readAll();
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
EXPECT_TRUE(data.contains("fingerprint"));
EXPECT_FALSE(data.contains("alias"));
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const mp::Query query{"", "e3b0c44298fc1c1", false, "release", mp::Query::Type::Alias};
EXPECT_NO_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()));
}
TEST_F(LXDImageVault, download_deletes_and_throws_on_cancel)
{
bool delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
else if (op == "GET" && url.contains("1.0/operations/0a19a412-03d0-4118-bee8-a3095f06d4da"))
{
return new mpt::MockLocalSocketReply(mpt::image_downloading_task_data);
}
else if (op == "DELETE" && url.contains("1.0/operations/0a19a412-03d0-4118-bee8-a3095f06d4da"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::ProgressMonitor monitor{[](auto, auto progress) {
EXPECT_EQ(progress, 25);
return false;
}};
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
monitor,
false,
std::nullopt,
save_dir.path()),
mp::AbortedDownloadException);
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, percent_complete_returns_negative_on_metadata_download)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
else if (op == "GET" && url.contains("1.0/operations/0a19a412-03d0-4118-bee8-a3095f06d4da"))
{
return new mpt::MockLocalSocketReply(mpt::metadata_downloading_task_data);
}
else if (op == "DELETE" && url.contains("1.0/operations/0a19a412-03d0-4118-bee8-a3095f06d4da"))
{
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::ProgressMonitor monitor{[](auto, auto progress) {
EXPECT_EQ(progress, -1);
return false;
}};
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_THROW(image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
monitor,
false,
std::nullopt,
save_dir.path()),
mp::AbortedDownloadException);
}
TEST_F(LXDImageVault, delete_requested_on_instance_remove)
{
bool delete_requested{false}, wait_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested, &wait_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "DELETE" && url.contains("1.0/virtual-machines/pied-piper-valley"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::delete_vm_data);
}
else if (op == "GET" && url.contains("1.0/operations/1c6265fc-8194-4790-9ab0-3225b0479155"))
{
wait_requested = true;
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.remove(instance_name));
EXPECT_TRUE(delete_requested);
EXPECT_TRUE(wait_requested);
}
TEST_F(LXDImageVault, logs_warning_when_removing_nonexistent_instance)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "DELETE" && url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::post_no_error_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const std::string name{"foo"};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(
StrEq(fmt::format("Instance \'{}\' does not exist: not removing", name)))))
.Times(1);
EXPECT_NO_THROW(image_vault.remove(name));
}
TEST_F(LXDImageVault, has_record_for_returns_expected_values)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/virtual-machines/pied-piper-valley"))
{
return new mpt::MockLocalSocketReply(mpt::vm_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_TRUE(image_vault.has_record_for(instance_name));
EXPECT_FALSE(image_vault.has_record_for("foo"));
}
TEST_F(LXDImageVault, has_record_for_error_logs_message_and_returns_true)
{
const std::string exception_message{"Cannot connect to socket"};
const std::string instance_name{"foo"};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq(
fmt::format("{} - Unable to determine if \'{}\' exists", exception_message, instance_name)))));
EXPECT_TRUE(image_vault.has_record_for(instance_name));
}
TEST_F(LXDImageVault, update_image_downloads_new_and_deletes_old_and_logs_expected_message)
{
bool download_requested{false}, delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&download_requested, &delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_update_source_info);
}
else if (op == "POST" && url.contains("1.0/images"))
{
download_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
else if (op == "DELETE" &&
url.contains("1.0/images/aedb5a84aaf2e4e443e090511156366a2800c26cec1b6a46f44d153c4bf04205"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_delete_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::debug), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq("Checking for images to update…"))));
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::info), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq("Updating bionic source image to latest"))));
image_vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor);
EXPECT_TRUE(download_requested);
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, update_image_not_downloaded_when_no_new_image)
{
bool download_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&download_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
else if (op == "POST" && url.contains("1.0/images"))
{
download_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_download_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
image_vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor);
EXPECT_FALSE(download_requested);
}
TEST_F(LXDImageVault, update_image_no_project_does_not_throw)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor));
}
TEST_F(LXDImageVault, image_update_source_delete_requested_on_expiration)
{
bool delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_update_source_info);
}
else if (op == "DELETE" &&
url.contains("1.0/images/aedb5a84aaf2e4e443e090511156366a2800c26cec1b6a46f44d153c4bf04205"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_delete_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::info), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq("Source image \'bionic\' is expired. Removing it…"))));
image_vault.prune_expired_images();
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, image_hash_delete_requested_on_expiration)
{
bool delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
else if (op == "DELETE" &&
url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_delete_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
image_vault.prune_expired_images();
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, prune_uses_last_update_property_on_new_unused_image)
{
bool delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_unused_updated_image);
}
else if (op == "DELETE" &&
url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
delete_requested = true;
return new mpt::MockLocalSocketReply(mpt::image_delete_task_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
image_vault.prune_expired_images();
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, prune_expired_image_no_project_does_not_throw)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.prune_expired_images());
}
TEST_F(LXDImageVault, prune_expired_error_logs_warning_does_not_throw)
{
const std::string exception_message{"Cannot connect to socket"};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq(exception_message))));
EXPECT_NO_THROW(image_vault.prune_expired_images());
}
TEST_F(LXDImageVault, prune_expired_image_delete_fails_does_no_throw)
{
bool delete_requested{false};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&delete_requested](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
else if (op == "DELETE" &&
url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
delete_requested = true;
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_NO_THROW(image_vault.prune_expired_images());
EXPECT_TRUE(delete_requested);
}
TEST_F(LXDImageVault, custom_image_found_returns_expected_info)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images?recursion=1"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const mp::Query query{"", "snapcraft", false, "release", mp::Query::Type::Alias};
auto image = image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path());
EXPECT_EQ(image.id, mpt::lxd_snapcraft_image_id);
EXPECT_EQ(image.original_release, mpt::snapcraft_release_info);
EXPECT_EQ(image.release_date, mpt::snapcraft_image_version);
}
TEST_F(LXDImageVault, custom_image_downloads_and_creates_correct_upload)
{
const std::string content{"This is a fake image!"};
mpt::TrackingURLDownloader url_downloader{content};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback([](mpt::MockProcess* process) {
if (process->program().startsWith("tar"))
{
auto tar_args = process->arguments();
EXPECT_EQ(tar_args.size(), 5);
QFile output_file{tar_args[1]}, input_file{tar_args[3] + "/" + tar_args[4]};
output_file.open(QIODevice::WriteOnly);
input_file.open(QIODevice::ReadOnly);
output_file.write(input_file.readAll());
mp::ProcessState exit_state;
exit_state.exit_code = 0;
ON_CALL(*process, execute(_)).WillByDefault(Return(exit_state));
}
});
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([](auto, auto request, auto outgoingData) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
auto content_header = request.header(QNetworkRequest::ContentTypeHeader).toString();
EXPECT_TRUE(content_header.contains("multipart/form-data"));
EXPECT_TRUE(content_header.contains("boundary"));
return new mpt::MockLocalSocketReply(mpt::image_upload_task_data);
}
else if (op == "GET" && url.contains("1.0/operations/dcce4fda-aab9-4117-89c1-9f42b8e3f4a8"))
{
return new mpt::MockLocalSocketReply(mpt::image_upload_task_complete_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const mp::Query query{"", "custom", false, "release", mp::Query::Type::Alias};
auto image = image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path());
EXPECT_EQ(image.id, mpt::lxd_custom_image_id);
EXPECT_EQ(image.original_release, mpt::custom_release_info);
EXPECT_EQ(image.release_date, mpt::custom_image_version);
}
TEST_F(LXDImageVault, fetch_image_unable_to_connect_logs_error_and_returns_blank_vmimage)
{
const std::string exception_message{"Cannot connect to socket"};
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _))
.WillByDefault([&exception_message](auto...) -> QNetworkReply* {
throw mp::LocalSocketConnectionException(exception_message);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("lxd image vault")),
mpt::MockLogger::make_cstring_matcher(
StrEq(fmt::format("{} - returning blank image info", exception_message)))));
auto image = image_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path());
EXPECT_TRUE(image.id.empty());
EXPECT_TRUE(image.original_release.empty());
EXPECT_TRUE(image.release_date.empty());
}
TEST_F(LXDImageVault, minimum_image_size_returns_expected_size)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
return new mpt::MockLocalSocketReply(mpt::normal_image_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const auto image_size =
image_vault.minimum_image_size_for("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
EXPECT_EQ(image_size, mp::MemorySize{"10G"});
}
TEST_F(LXDImageVault, minimum_image_size_large_returns_expected_size)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET")
{
if (url.contains("1.0/images/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
{
return new mpt::MockLocalSocketReply(mpt::large_image_info_data);
}
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const auto image_size =
image_vault.minimum_image_size_for("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
EXPECT_EQ(image_size, mp::MemorySize{"33345572108"});
}
TEST_F(LXDImageVault, minimum_image_size_throws_when_not_found)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto...) {
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const std::string id{"12345"};
MP_EXPECT_THROW_THAT(
image_vault.minimum_image_size_for(id), std::runtime_error,
mpt::match_what(AllOf(HasSubstr(fmt::format("Cannot retrieve info for image with id \'{}\'", id)))));
}
TEST_F(LXDImageVault, http_based_image_downloads_and_creates_correct_upload)
{
const std::string content{"This is a fake image!"};
mpt::TrackingURLDownloader url_downloader{content};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback([](mpt::MockProcess* process) {
if (process->program().startsWith("tar"))
{
auto tar_args = process->arguments();
EXPECT_EQ(tar_args.size(), 5);
QFile output_file{tar_args[1]}, input_file{tar_args[3] + "/" + tar_args[4]};
output_file.open(QIODevice::WriteOnly);
input_file.open(QIODevice::ReadOnly);
output_file.write(input_file.readAll());
mp::ProcessState exit_state;
exit_state.exit_code = 0;
ON_CALL(*process, execute(_)).WillByDefault(Return(exit_state));
}
});
ON_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillByDefault([](auto, auto request, auto outgoingData) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
auto content_header = request.header(QNetworkRequest::ContentTypeHeader).toString();
EXPECT_TRUE(content_header.contains("multipart/form-data"));
EXPECT_TRUE(content_header.contains("boundary"));
return new mpt::MockLocalSocketReply(mpt::image_upload_task_data);
}
else if (op == "GET" && url.contains("1.0/operations/dcce4fda-aab9-4117-89c1-9f42b8e3f4a8"))
{
return new mpt::MockLocalSocketReply(mpt::image_upload_task_complete_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
auto current_time = QDateTime::currentDateTime();
const std::string download_url{"http://www.foo.com/images/foo.img"};
const mp::Query query{"", download_url, false, "", mp::Query::Type::HttpDownload};
auto image = image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path());
EXPECT_EQ(image.id, "bc5a973bd6f2bef30658fb51177cf5e506c1d60958a4c97813ee26416dc368da");
auto image_time = QDateTime::fromString(QString::fromStdString(image.release_date), Qt::ISODateWithMs);
EXPECT_TRUE(image_time >= current_time);
EXPECT_EQ(url_downloader.downloaded_files.size(), 1);
EXPECT_EQ(url_downloader.downloaded_urls.size(), 1);
EXPECT_EQ(url_downloader.downloaded_urls.front().toStdString(), download_url);
}
TEST_F(LXDImageVault, file_based_fetch_copies_image_and_returns_expected_info)
{
mpt::TempFile file;
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback([](mpt::MockProcess* process) {
if (process->program().startsWith("tar"))
{
auto tar_args = process->arguments();
EXPECT_EQ(tar_args.size(), 5);
QFile output_file{tar_args[1]}, input_file{tar_args[3] + "/" + tar_args[4]};
output_file.open(QIODevice::WriteOnly);
input_file.open(QIODevice::ReadOnly);
output_file.write(input_file.readAll());
mp::ProcessState exit_state;
exit_state.exit_code = 0;
ON_CALL(*process, execute(_)).WillByDefault(Return(exit_state));
}
});
ON_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillByDefault([](auto, auto request, auto outgoingData) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "POST" && url.contains("1.0/images"))
{
auto content_header = request.header(QNetworkRequest::ContentTypeHeader).toString();
EXPECT_TRUE(content_header.contains("multipart/form-data"));
EXPECT_TRUE(content_header.contains("boundary"));
return new mpt::MockLocalSocketReply(mpt::image_upload_task_data);
}
else if (op == "GET" && url.contains("1.0/operations/dcce4fda-aab9-4117-89c1-9f42b8e3f4a8"))
{
return new mpt::MockLocalSocketReply(mpt::image_upload_task_complete_data);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
auto current_time = QDateTime::currentDateTime();
const mp::Query query{"", file.url().toStdString(), false, "", mp::Query::Type::LocalFile};
auto image = image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path());
EXPECT_EQ(image.id, "bc5a973bd6f2bef30658fb51177cf5e506c1d60958a4c97813ee26416dc368da");
auto image_time = QDateTime::fromString(QString::fromStdString(image.release_date), Qt::ISODateWithMs);
EXPECT_TRUE(image_time >= current_time);
}
TEST_F(LXDImageVault, invalid_local_file_image_throws)
{
ON_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillByDefault([](auto...) {
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
const std::string missing_file{"/foo"};
const mp::Query query{"", fmt::format("file://{}", missing_file), false, "", mp::Query::Type::LocalFile};
MP_EXPECT_THROW_THAT(image_vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.path()),
std::runtime_error,
mpt::match_what(StrEq(fmt::format("Custom image `{}` does not exist.", missing_file))));
}
TEST_F(LXDImageVault, updateImagesThrowsOnMissingImage)
{
ON_CALL(*mock_network_access_manager.get(), createRequest(_, _, _)).WillByDefault([](auto, auto request, auto) {
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
auto url = request.url().toString();
if (op == "GET" && url.contains("1.0/images"))
{
return new mpt::MockLocalSocketReply(mpt::image_info_update_source_info);
}
return new mpt::MockLocalSocketReply(mpt::not_found_data, QNetworkReply::ContentNotFoundError);
});
mp::LXDVMImageVault image_vault{hosts, &stub_url_downloader, mock_network_access_manager.get(),
base_url, cache_dir.path(), mp::days{0}};
EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt));
EXPECT_THROW(image_vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor),
mp::ImageNotFoundException);
}
TEST_F(LXDImageVault, lxdImageVaultCloneThrow)
{
mp::LXDVMImageVault image_vault{hosts,
&stub_url_downloader,
mock_network_access_manager.get(),
base_url,
cache_dir.path(),
mp::days{0}};
MP_EXPECT_THROW_THAT(image_vault.clone("dummy_src_image_name", "dummy_dest_image_name"),
mp::NotImplementedOnThisBackendException,
mpt::match_what(StrEq("The clone feature is not implemented on this backend.")));
}
| 55,396
|
C++
|
.cpp
| 1,016
| 40.543307
| 119
| 0.579242
|
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,675
|
test_platform_unix.cpp
|
canonical_multipass/tests/unix/test_platform_unix.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 <tests/common.h>
#include <tests/mock_environment_helpers.h>
#include <tests/mock_platform.h>
#include <tests/temp_file.h>
#include "mock_libc_functions.h"
#include <multipass/constants.h>
#include <multipass/format.h>
#include <multipass/platform.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestPlatformUnix : public Test
{
mpt::TempFile file;
};
} // namespace
TEST_F(TestPlatformUnix, setServerSocketRestrictionsNotRestrictedIsCorrect)
{
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, 0, 0)).WillOnce(Return(0));
EXPECT_CALL(*mock_platform, chmod(_, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH))
.WillOnce(Return(0));
EXPECT_NO_THROW(MP_PLATFORM.Platform::set_server_socket_restrictions(fmt::format("unix:{}", file.name()), false));
}
TEST_F(TestPlatformUnix, setServerSocketRestrictionsRestrictedIsCorrect)
{
auto [mock_platform, guard] = mpt::MockPlatform::inject();
const int gid{42};
struct group group;
group.gr_gid = gid;
EXPECT_CALL(*mock_platform, chown(_, 0, gid)).WillOnce(Return(0));
EXPECT_CALL(*mock_platform, chmod(_, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)).WillOnce(Return(0));
REPLACE(getgrnam, [&group](auto) { return &group; });
EXPECT_NO_THROW(MP_PLATFORM.Platform::set_server_socket_restrictions(fmt::format("unix:{}", file.name()), true));
}
TEST_F(TestPlatformUnix, setServerSocketRestrictionsNoUnixPathThrows)
{
MP_EXPECT_THROW_THAT(MP_PLATFORM.set_server_socket_restrictions(file.name().toStdString(), false),
std::runtime_error,
mpt::match_what(StrEq(fmt::format("invalid server address specified: {}", file.name()))));
}
TEST_F(TestPlatformUnix, setServerSocketRestrictionsNonUnixTypeReturns)
{
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown).Times(0);
EXPECT_CALL(*mock_platform, chmod).Times(0);
EXPECT_NO_THROW(MP_PLATFORM.Platform::set_server_socket_restrictions(fmt::format("dns:{}", file.name()), false));
}
TEST_F(TestPlatformUnix, setServerSocketRestrictionsChownFailsThrows)
{
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, 0, 0)).WillOnce([](auto...) {
errno = EPERM;
return -1;
});
MP_EXPECT_THROW_THAT(
MP_PLATFORM.Platform::set_server_socket_restrictions(fmt::format("unix:{}", file.name()), false),
std::runtime_error,
mpt::match_what(StrEq("Could not set ownership of the multipass socket: Operation not permitted")));
}
TEST_F(TestPlatformUnix, setServerSocketRestrictionsChmodFailsThrows)
{
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, 0, 0)).WillOnce(Return(0));
EXPECT_CALL(*mock_platform, chmod(_, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH))
.WillOnce([](auto...) {
errno = EPERM;
return -1;
});
MP_EXPECT_THROW_THAT(
MP_PLATFORM.Platform::set_server_socket_restrictions(fmt::format("unix:{}", file.name()), false),
std::runtime_error,
mpt::match_what(StrEq("Could not set permissions for the multipass socket: Operation not permitted")));
}
TEST_F(TestPlatformUnix, chmodSetsFileModsAndReturns)
{
auto perms = QFileInfo(file.name()).permissions();
ASSERT_EQ(perms, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadUser | QFileDevice::WriteUser);
EXPECT_EQ(MP_PLATFORM.chmod(file.name().toStdString().c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP), 0);
perms = QFileInfo(file.name()).permissions();
EXPECT_EQ(perms, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadUser | QFileDevice::WriteUser |
QFileDevice::ReadGroup | QFileDevice::WriteGroup);
}
TEST_F(TestPlatformUnix, multipassStorageLocationReturnsExpectedPath)
{
mpt::SetEnvScope e(mp::multipass_storage_env_var, file.name().toUtf8());
auto storage_path = MP_PLATFORM.multipass_storage_location();
EXPECT_EQ(storage_path, file.name());
}
TEST_F(TestPlatformUnix, multipassStorageLocationNotSetReturnsEmpty)
{
auto storage_path = MP_PLATFORM.multipass_storage_location();
EXPECT_TRUE(storage_path.isEmpty());
}
| 5,044
|
C++
|
.cpp
| 112
| 40.660714
| 120
| 0.711633
|
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,676
|
test_daemon_rpc.cpp
|
canonical_multipass/tests/unix/test_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 <tests/common.h>
#include <tests/daemon_test_fixture.h>
#include <tests/mock_cert_provider.h>
#include <tests/mock_cert_store.h>
#include <tests/mock_daemon.h>
#include <tests/mock_logger.h>
#include <tests/mock_platform.h>
#include <tests/mock_utils.h>
#include <src/daemon/daemon_rpc.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
constexpr auto key_data = "-----BEGIN PRIVATE KEY-----\n"
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgsSAz5ggzrLjai0I/\n"
"F0hYg5oG/shpXJiBQtJdBCG3lUShRANCAAQAFGNAqq7c5IMDeQ/cV4+Emogmkfpb\n"
"TLSPfXgXVLHRsvL04xUAkqGpL+eyGFVE6dqaJ7sAPJJwlVj1xD0r5DX5\n"
"-----END PRIVATE KEY-----\n";
constexpr auto cert_data = "-----BEGIN CERTIFICATE-----\n"
"MIIBUjCB+AIBKjAKBggqhkjOPQQDAjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJ\n"
"Q2Fub25pY2FsMRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTgwNjIxMTM0MjI5WhcN\n"
"MTkwNjIxMTM0MjI5WjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJQ2Fub25pY2Fs\n"
"MRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQA\n"
"FGNAqq7c5IMDeQ/cV4+EmogmkfpbTLSPfXgXVLHRsvL04xUAkqGpL+eyGFVE6dqa\n"
"J7sAPJJwlVj1xD0r5DX5MAoGCCqGSM49BAMCA0kAMEYCIQCvI0PYv9f201fbe4LP\n"
"BowTeYWSqMQtLNjvZgd++AAGhgIhALNPW+NRSKCXwadiIFgpbjPInLPqXPskLWSc\n"
"aXByaQyt\n"
"-----END CERTIFICATE-----\n";
struct TestDaemonRpc : public mpt::DaemonTestFixture
{
TestDaemonRpc()
{
EXPECT_CALL(*mock_cert_provider, PEM_certificate()).WillOnce(Return(cert_data));
EXPECT_CALL(*mock_cert_provider, PEM_signing_key()).WillOnce(Return(key_data));
EXPECT_CALL(*mock_platform, multipass_storage_location()).Times(AnyNumber()).WillRepeatedly(Return(QString()));
}
mp::Rpc::Stub make_secure_stub()
{
auto opts = grpc::SslCredentialsOptions();
opts.server_certificate_request = GRPC_SSL_REQUEST_SERVER_CERTIFICATE_BUT_DONT_VERIFY;
opts.pem_cert_chain = mpt::client_cert;
opts.pem_private_key = mpt::client_key;
auto channel = grpc::CreateChannel(server_address, grpc::SslCredentials(opts));
return mp::Rpc::Stub(channel);
}
mpt::MockDaemon make_secure_server()
{
config_builder.cert_provider = std::move(mock_cert_provider);
config_builder.client_cert_store = std::move(mock_cert_store);
return mpt::MockDaemon(config_builder.build());
}
void mock_empty_list_reply(mpt::MockDaemon& mock_daemon)
{
EXPECT_CALL(mock_daemon, list(_, _, _)).WillOnce([](auto, auto* server, auto* status_promise) {
mp::ListReply reply;
reply.mutable_instance_list();
server->Write(reply);
status_promise->set_value(grpc::Status::OK);
});
}
std::unique_ptr<NiceMock<mpt::MockCertProvider>> mock_cert_provider{
std::make_unique<NiceMock<mpt::MockCertProvider>>()};
std::unique_ptr<mpt::MockCertStore> mock_cert_store{std::make_unique<mpt::MockCertStore>()};
mpt::MockPlatform::GuardedMock platform_attr{mpt::MockPlatform::inject()};
mpt::MockPlatform* mock_platform = platform_attr.first;
mpt::MockUtils::GuardedMock attr{mpt::MockUtils::inject<NiceMock>()};
mpt::MockUtils* mock_utils = attr.first;
};
} // namespace
TEST_F(TestDaemonRpc, setsRestrictedPermissionsWhenNoCerts)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(true));
mpt::MockDaemon daemon{make_secure_server()};
}
TEST_F(TestDaemonRpc, setsUnrestrictedPermissionsWhenCertAlreadyExists)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(false));
mpt::MockDaemon daemon{make_secure_server()};
}
TEST_F(TestDaemonRpc, authenticateCompletesSuccessfully)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert(StrEq(mpt::client_cert))).Times(1);
mpt::MockDaemon daemon{make_secure_server()};
EXPECT_CALL(daemon, authenticate(_, _, _)).WillOnce([](auto, auto, auto* status_promise) {
status_promise->set_value(grpc::Status::OK);
});
send_command({"authenticate", "foo"});
}
TEST_F(TestDaemonRpc, authenticateFailsSkipsCertImportCalls)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert(_)).Times(0);
mpt::MockDaemon daemon{make_secure_server()};
EXPECT_CALL(daemon, authenticate(_, _, _)).WillOnce([](auto, auto, auto* status_promise) {
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, ""));
});
send_command({"authenticate", "foo"});
}
TEST_F(TestDaemonRpc, authenticateAddCertFailsReturnsError)
{
const std::string error_msg{"Error adding certificate"};
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert).WillOnce(Throw(std::runtime_error(error_msg)));
mpt::MockDaemon daemon{make_secure_server()};
EXPECT_CALL(daemon, authenticate(_, _, _)).WillOnce([](auto, auto, auto* status_promise) {
status_promise->set_value(grpc::Status::OK);
});
std::stringstream stream;
send_command({"authenticate", "foo"}, trash_stream, stream);
EXPECT_THAT(stream.str(), HasSubstr(error_msg));
}
TEST_F(TestDaemonRpc, pingReturnsOkWhenCertIsVerified)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(false));
EXPECT_CALL(*mock_cert_store, verify_cert(StrEq(mpt::client_cert))).WillOnce(Return(true));
mpt::MockDaemon daemon{make_secure_server()};
mp::Rpc::Stub stub{make_secure_stub()};
grpc::ClientContext context;
mp::PingRequest request;
mp::PingReply reply;
EXPECT_TRUE(stub.ping(&context, request, &reply).ok());
}
TEST_F(TestDaemonRpc, pingReturnsUnauthenticatedWhenCertIsNotVerified)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).WillOnce(Return(false));
EXPECT_CALL(*mock_cert_store, verify_cert(StrEq(mpt::client_cert))).WillOnce(Return(false));
mpt::MockDaemon daemon{make_secure_server()};
mp::Rpc::Stub stub{make_secure_stub()};
grpc::ClientContext context;
mp::PingRequest request;
mp::PingReply reply;
EXPECT_EQ(stub.ping(&context, request, &reply).error_code(), grpc::StatusCode::UNAUTHENTICATED);
}
// The following 'list' command tests are for testing the authentication of an arbitrary command in DaemonRpc
TEST_F(TestDaemonRpc, listCertExistsCompletesSuccessfully)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).Times(2).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_cert_store, verify_cert(StrEq(mpt::client_cert))).WillOnce(Return(true));
mpt::MockDaemon daemon{make_secure_server()};
mock_empty_list_reply(daemon);
send_command({"list"});
}
TEST_F(TestDaemonRpc, listNoCertsExistWillVerifyAndComplete)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert(StrEq(mpt::client_cert))).Times(1);
mpt::MockDaemon daemon{make_secure_server()};
mock_empty_list_reply(daemon);
send_command({"list"});
}
TEST_F(TestDaemonRpc, listCertNotVerifiedHasError)
{
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).Times(2).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_cert_store, verify_cert(StrEq(mpt::client_cert))).WillOnce(Return(false));
mpt::MockDaemon daemon{make_secure_server()};
std::stringstream stream;
send_command({"list"}, trash_stream, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr("The client is not authenticated with the Multipass service."),
HasSubstr("Please use 'multipass authenticate' before proceeding.")));
}
TEST_F(TestDaemonRpc, listTCPSocketNoCertsExistHasError)
{
server_address = "localhost:50052";
config_builder.server_address = server_address;
EXPECT_CALL(*mock_platform, set_server_socket_restrictions).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).Times(1);
EXPECT_CALL(*mock_cert_store, add_cert(StrEq(mpt::client_cert))).Times(0);
EXPECT_CALL(*mock_cert_store, verify_cert(StrEq(mpt::client_cert))).WillOnce(Return(false));
mpt::MockDaemon daemon{make_secure_server()};
std::stringstream stream;
send_command({"list"}, trash_stream, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr("The client is not authenticated with the Multipass service."),
HasSubstr("Please use 'multipass authenticate' before proceeding.")));
}
TEST_F(TestDaemonRpc, listAcceptCertFailsHasError)
{
const std::string error_msg{"Error adding certificate"};
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_cert_store, empty()).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert(StrEq(mpt::client_cert))).WillOnce(Throw(std::runtime_error(error_msg)));
mpt::MockDaemon daemon{make_secure_server()};
std::stringstream stream;
send_command({"list"}, trash_stream, stream);
EXPECT_THAT(stream.str(), HasSubstr(error_msg));
}
TEST_F(TestDaemonRpc, listSettingServerPermissionsFailLogsErrorAndExits)
{
const std::string error_msg{"Error setting socket permissions"};
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, true)).Times(1);
EXPECT_CALL(*mock_platform, set_server_socket_restrictions(_, false))
.WillOnce(Throw(std::runtime_error(error_msg)));
EXPECT_CALL(*mock_cert_store, empty()).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cert_store, add_cert(StrEq(mpt::client_cert))).Times(1);
// Detects if the daemon would actually exit
EXPECT_CALL(*mock_utils, exit(EXIT_FAILURE)).Times(1);
mpt::MockDaemon daemon{make_secure_server()};
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::error, error_msg);
logger_scope.mock_logger->expect_log(mpl::Level::error, "Failed to set up autostart prerequisites", AnyNumber());
mock_empty_list_reply(daemon);
send_command({"list"});
}
| 12,015
|
C++
|
.cpp
| 234
| 45.25641
| 119
| 0.70453
|
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,677
|
mock_libc_functions.cpp
|
canonical_multipass/tests/unix/mock_libc_functions.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 "mock_libc_functions.h"
#include <stdio.h>
#include <unistd.h>
extern "C"
{
IMPL_MOCK_DEFAULT(1, getgrnam);
int ut_isatty(int fd)
{
return mock_isatty(fd);
}
int ut_fileno(FILE* stream)
{
return mock_fileno(stream);
}
int ut_tcgetattr(int fd, struct termios* termios_p)
{
return mock_tcgetattr(fd, termios_p);
}
int ut_tcsetattr(int fd, int optional_actions, const struct termios* termios_p)
{
return mock_tcsetattr(fd, optional_actions, termios_p);
}
}
// By default, call real functions
std::function<int(int)> mock_isatty = isatty;
std::function<int(FILE*)> mock_fileno = fileno;
std::function<int(int, struct termios*)> mock_tcgetattr = tcgetattr;
std::function<int(int, int, const struct termios*)> mock_tcsetattr = tcsetattr;
| 1,461
|
C++
|
.cpp
| 44
| 29.772727
| 83
| 0.711143
|
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,678
|
test_unix_terminal.cpp
|
canonical_multipass/tests/unix/test_unix_terminal.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 <tests/common.h>
#include "mock_libc_functions.h"
#include <src/platform/console/unix_terminal.h>
#include <tuple>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestUnixTerminal : public Test
{
mp::UnixTerminal unix_terminal;
const int fake_fd{42};
};
} // namespace
TEST_F(TestUnixTerminal, cinFdReturnsExpectedFd)
{
REPLACE(fileno, [this](auto stream) {
EXPECT_EQ(stream, stdin);
return fake_fd;
});
EXPECT_EQ(unix_terminal.cin_fd(), fake_fd);
}
TEST_F(TestUnixTerminal, coutFdReturnsExpectedFd)
{
REPLACE(fileno, [this](auto stream) {
EXPECT_EQ(stream, stdout);
return fake_fd;
});
EXPECT_EQ(unix_terminal.cout_fd(), fake_fd);
}
TEST_F(TestUnixTerminal, isLiveReturnsTrueWhenTTY)
{
REPLACE(fileno, [this](auto) { return fake_fd; });
REPLACE(isatty, [this](auto fd) {
EXPECT_EQ(fd, fake_fd);
return 1;
});
EXPECT_TRUE(unix_terminal.cin_is_live());
EXPECT_TRUE(unix_terminal.cout_is_live());
}
TEST_F(TestUnixTerminal, isLiveReturnsFalseWhenNotTTY)
{
REPLACE(fileno, [this](auto) { return fake_fd; });
REPLACE(isatty, [this](auto fd) {
EXPECT_EQ(fd, fake_fd);
return 0;
});
EXPECT_FALSE(unix_terminal.cin_is_live());
EXPECT_FALSE(unix_terminal.cout_is_live());
}
TEST_F(TestUnixTerminal, setsEchoOnTerminal)
{
REPLACE(fileno, [this](auto) { return fake_fd; });
REPLACE(tcgetattr, [](auto...) { return 0; });
REPLACE(tcsetattr, [](auto, auto, auto termios_p) {
EXPECT_TRUE((termios_p->c_lflag & ECHO) == ECHO);
return 0;
});
unix_terminal.set_cin_echo(true);
}
TEST_F(TestUnixTerminal, unsetsEchoOnTerminal)
{
REPLACE(fileno, [this](auto) { return fake_fd; });
REPLACE(tcgetattr, [](auto...) { return 0; });
REPLACE(tcsetattr, [](auto, auto, auto termios_p) {
EXPECT_FALSE((termios_p->c_lflag & ECHO) == ECHO);
return 0;
});
unix_terminal.set_cin_echo(false);
}
| 2,689
|
C++
|
.cpp
| 87
| 27.057471
| 72
| 0.684517
|
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,679
|
client_cert_store.cpp
|
canonical_multipass/src/cert/client_cert_store.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/client_cert_store.h>
#include <multipass/constants.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/utils.h>
#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <stdexcept>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto chain_name = "multipass_client_certs.pem";
constexpr auto category = "client cert store";
auto load_certs_from_file(const QDir& cert_dir)
{
QList<QSslCertificate> certs;
auto path = cert_dir.filePath(chain_name);
QFile cert_file{path};
if (cert_file.exists())
{
cert_file.open(QFile::ReadOnly);
certs = QSslCertificate::fromDevice(&cert_file);
}
return certs;
}
} // namespace
mp::ClientCertStore::ClientCertStore(const multipass::Path& data_dir)
: cert_dir(MP_UTILS.make_dir(data_dir, mp::authenticated_certs_dir)),
authenticated_client_certs{load_certs_from_file(cert_dir)}
{
mpl::log(mpl::Level::trace, category, fmt::format("Loading client certs from {}", cert_dir.absolutePath()));
}
void mp::ClientCertStore::add_cert(const std::string& pem_cert)
{
mpl::log(mpl::Level::trace, category, fmt::format("Adding cert:\n{}", pem_cert));
QSslCertificate cert(QByteArray::fromStdString(pem_cert));
if (cert.isNull())
throw std::runtime_error("invalid certificate data");
if (verify_cert(cert))
return;
QSaveFile file{cert_dir.filePath(chain_name)};
if (!MP_FILEOPS.open(file, QIODevice::WriteOnly))
throw std::runtime_error("failed to create file to store certificate");
file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
// QIODevice::Append is not supported in QSaveFile, so must write out all of the
// existing clients certs each time.
for (const auto& saved_cert : authenticated_client_certs)
{
MP_FILEOPS.write(file, saved_cert.toPem());
}
MP_FILEOPS.write(file, cert.toPem());
if (!MP_FILEOPS.commit(file))
throw std::runtime_error("failed to write certificate");
authenticated_client_certs.push_back(cert);
}
std::string mp::ClientCertStore::PEM_cert_chain() const
{
auto path = cert_dir.filePath(chain_name);
if (QFile::exists(path))
return mp::utils::contents_of(path);
return {};
}
bool mp::ClientCertStore::verify_cert(const std::string& pem_cert)
{
mpl::log(mpl::Level::trace, category, fmt::format("Verifying cert:\n{}", pem_cert));
return verify_cert(QSslCertificate(QByteArray::fromStdString(pem_cert)));
}
bool mp::ClientCertStore::verify_cert(const QSslCertificate& cert)
{
return authenticated_client_certs.contains(cert);
}
bool mp::ClientCertStore::empty()
{
return authenticated_client_certs.empty();
}
| 3,442
|
C++
|
.cpp
| 94
| 33.12766
| 112
| 0.723443
|
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,680
|
ssl_cert_provider.cpp
|
canonical_multipass/src/cert/ssl_cert_provider.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/format.h>
#include <multipass/ssl_cert_provider.h>
#include <multipass/utils.h>
#include "biomem.h"
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <QFile>
#include <array>
#include <cerrno>
#include <cstring>
#include <memory>
#include <vector>
namespace mp = multipass;
namespace
{
class WritableFile
{
public:
explicit WritableFile(const QString& name) : fp{fopen(name.toStdString().c_str(), "wb"), fclose}
{
if (fp == nullptr)
throw std::runtime_error(fmt::format("failed to open file '{}': {}({})", name, strerror(errno), errno));
}
FILE* get() const
{
return fp.get();
}
private:
std::unique_ptr<FILE, std::function<int(FILE*)>> fp;
};
class EVPKey
{
public:
EVPKey()
{
if (key == nullptr)
throw std::runtime_error("Failed to allocate EVP_PKEY");
std::unique_ptr<EC_KEY, decltype(EC_KEY_free)*> ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1),
EC_KEY_free);
if (ec_key == nullptr)
throw std::runtime_error("Failed to allocate ec key structure");
if (!EC_KEY_generate_key(ec_key.get()))
throw std::runtime_error("Failed to generate key");
if (!EVP_PKEY_assign_EC_KEY(key.get(), ec_key.get()))
throw std::runtime_error("Failed to assign key");
// EVPKey has ownership now
ec_key.release();
}
std::string as_pem() const
{
mp::BIOMem mem;
auto bytes = PEM_write_bio_PrivateKey(mem.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr);
if (bytes == 0)
throw std::runtime_error("Failed to export certificate in PEM format");
return mem.as_string();
}
void write(const QString& name)
{
WritableFile file{name};
if (!PEM_write_PrivateKey(file.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr))
throw std::runtime_error(fmt::format("Failed writing certificate private key to file '{}'", name));
QFile::setPermissions(name, QFile::ReadOwner);
}
EVP_PKEY* get() const
{
return key.get();
}
private:
std::unique_ptr<EVP_PKEY, decltype(EVP_PKEY_free)*> key{EVP_PKEY_new(), EVP_PKEY_free};
};
std::vector<unsigned char> as_vector(const std::string& v)
{
return {v.begin(), v.end()};
}
std::string cn_name_from(const std::string& server_name)
{
if (server_name.empty())
return mp::utils::make_uuid().toStdString();
return server_name;
}
void set_san_name(X509* c, const std::string& server_name)
{
std::string san_dns = server_name;
GENERAL_NAMES* gens = sk_GENERAL_NAME_new_null();
GENERAL_NAME* gen = GENERAL_NAME_new();
ASN1_IA5STRING* ia5 = ASN1_IA5STRING_new();
ASN1_STRING_set(ia5, san_dns.data(), san_dns.length());
GENERAL_NAME_set0_value(gen, GEN_DNS, ia5);
sk_GENERAL_NAME_push(gens, gen);
X509_add1_ext_i2d(c, NID_subject_alt_name, gens, 0, X509V3_ADD_DEFAULT);
GENERAL_NAMES_free(gens);
}
class X509Cert
{
public:
explicit X509Cert(const EVPKey& key, const std::string& server_name)
{
if (x509 == nullptr)
throw std::runtime_error("Failed to allocate x509 cert structure");
long big_num{0};
auto rand_bytes = MP_UTILS.random_bytes(4);
for (unsigned int i = 0; i < 4u; i++)
big_num |= rand_bytes[i] << i * 8u;
X509_set_version(x509.get(), 2);
ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), big_num);
X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
X509_gmtime_adj(X509_get_notAfter(x509.get()), 31536000L);
constexpr int APPEND_ENTRY{-1};
constexpr int ADD_RDN{0};
auto country = as_vector("US");
auto org = as_vector("Canonical");
auto cn = as_vector(cn_name_from(server_name));
auto name = X509_get_subject_name(x509.get());
X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, country.data(), country.size(), APPEND_ENTRY, ADD_RDN);
X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org.data(), org.size(), APPEND_ENTRY, ADD_RDN);
X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, cn.data(), cn.size(), APPEND_ENTRY, ADD_RDN);
X509_set_issuer_name(x509.get(), name);
set_san_name(x509.get(), server_name);
if (!X509_set_pubkey(x509.get(), key.get()))
throw std::runtime_error("Failed to set certificate public key");
if (!X509_sign(x509.get(), key.get(), EVP_sha256()))
throw std::runtime_error("Failed to sign certificate");
}
std::string as_pem()
{
mp::BIOMem mem;
auto bytes = PEM_write_bio_X509(mem.get(), x509.get());
if (bytes == 0)
throw std::runtime_error("Failed to write certificate in PEM format");
return mem.as_string();
}
void write(const QString& name)
{
WritableFile file{name};
if (!PEM_write_X509(file.get(), x509.get()))
throw std::runtime_error(fmt::format("Failed writing certificate to file '{}'", name));
}
private:
std::unique_ptr<X509, decltype(X509_free)*> x509{X509_new(), X509_free};
};
mp::SSLCertProvider::KeyCertificatePair make_cert_key_pair(const QDir& cert_dir, const std::string& server_name)
{
QString prefix = server_name.empty() ? "multipass_cert" : QString::fromStdString(server_name);
auto priv_key_path = cert_dir.filePath(prefix + "_key.pem");
auto cert_path = cert_dir.filePath(prefix + ".pem");
if (QFile::exists(priv_key_path) && QFile::exists(cert_path))
{
return {mp::utils::contents_of(cert_path), mp::utils::contents_of(priv_key_path)};
}
EVPKey key;
X509Cert cert{key, server_name};
key.write(priv_key_path);
cert.write(cert_path);
return {cert.as_pem(), key.as_pem()};
}
} // namespace
mp::SSLCertProvider::SSLCertProvider(const multipass::Path& cert_dir, const std::string& server_name)
: key_cert_pair{make_cert_key_pair(cert_dir, server_name)}
{
}
mp::SSLCertProvider::SSLCertProvider(const multipass::Path& data_dir) : SSLCertProvider(data_dir, "")
{
}
std::string mp::SSLCertProvider::PEM_certificate() const
{
return key_cert_pair.pem_cert;
}
std::string mp::SSLCertProvider::PEM_signing_key() const
{
return key_cert_pair.pem_priv_key;
}
| 7,103
|
C++
|
.cpp
| 189
| 31.962963
| 116
| 0.644823
|
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,681
|
biomem.cpp
|
canonical_multipass/src/cert/biomem.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 "biomem.h"
#include <stdexcept>
#include <vector>
namespace mp = multipass;
mp::BIOMem::BIOMem() : bio{BIO_new(BIO_s_mem()), BIO_free}
{
if (bio == nullptr)
throw std::runtime_error("Failed to create BIO structure");
}
mp::BIOMem::BIOMem(const std::string& pem_source) : BIOMem()
{
BIO_write(bio.get(), pem_source.data(), pem_source.size());
}
std::string mp::BIOMem::as_string() const
{
std::vector<char> pem(BIO_number_written(bio.get()));
BIO_read(bio.get(), pem.data(), pem.size());
return {pem.begin(), pem.end()};
}
BIO* mp::BIOMem::get() const
{
return bio.get();
}
| 1,249
|
C++
|
.cpp
| 39
| 29.641026
| 72
| 0.704904
|
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,682
|
ssh_process.cpp
|
canonical_multipass/src/ssh/ssh_process.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/exceptions/exitless_sshprocess_exceptions.h>
#include <multipass/exceptions/ssh_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/ssh/ssh_process.h>
#include <multipass/ssh/throw_on_error.h>
#include <libssh/callbacks.h>
#include <array>
#include <cerrno>
#include <cstring>
#include <sstream>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "ssh process";
template <typename T>
class ExitStatusCallback
{
public:
ExitStatusCallback(ssh_channel channel, T& result_holder) : channel{channel}
{
ssh_callbacks_init(&cb);
cb.channel_exit_status_function = channel_exit_status_cb;
cb.userdata = &result_holder;
ssh_add_channel_callbacks(channel, &cb);
}
~ExitStatusCallback()
{
ssh_remove_channel_callbacks(channel, &cb);
}
private:
static void channel_exit_status_cb(ssh_session, ssh_channel, int exit_status, void* userdata)
{
auto exit_code = reinterpret_cast<T*>(userdata);
*exit_code = exit_status;
}
ssh_channel channel;
ssh_channel_callbacks_struct cb{};
};
auto make_channel(ssh_session session, const std::string& cmd)
{
if (!ssh_is_connected(session))
throw mp::SSHException(
fmt::format("unable to create a channel for remote process: '{}', the SSH session is not connected", cmd));
mp::SSHProcess::ChannelUPtr channel{ssh_channel_new(session), ssh_channel_free};
mp::SSH::throw_on_error(channel, session, "[ssh proc] failed to open session channel", ssh_channel_open_session);
mp::SSH::throw_on_error(channel, session, "[ssh proc] exec request failed", ssh_channel_request_exec, cmd.c_str());
return channel;
}
} // namespace
mp::SSHProcess::SSHProcess(ssh_session session, const std::string& cmd, std::unique_lock<std::mutex> session_lock)
: session_lock{std::move(session_lock)}, // this is held until the exit code is requested or this is destroyed
session{session},
cmd{cmd},
channel{make_channel(session, cmd)},
exit_result{}
{
assert(this->session_lock.owns_lock());
}
bool mp::SSHProcess::exit_recognized(std::chrono::milliseconds timeout)
{
rethrow_if_saved();
if (std::holds_alternative<int>(exit_result))
return true;
try
{
read_exit_code(timeout, /* save_exception = */ false);
return true;
}
catch (SSHProcessTimeoutException&)
{
return false;
}
}
int mp::SSHProcess::exit_code(std::chrono::milliseconds timeout)
{
rethrow_if_saved();
if (auto exit_status = std::get_if<int>(&exit_result))
return *exit_status;
auto local_lock = std::move(session_lock); // unlock at the end
read_exit_code(timeout, /* save_exception = */ true);
assert(std::holds_alternative<int>(exit_result));
return std::get<int>(exit_result);
}
void mp::SSHProcess::read_exit_code(std::chrono::milliseconds timeout, bool save_exception)
{
assert(std::holds_alternative<std::monostate>(exit_result));
ExitStatusCallback cb{channel.get(), exit_result};
std::unique_ptr<ssh_event_struct, decltype(ssh_event_free)*> event{ssh_event_new(), ssh_event_free};
ssh_event_add_session(event.get(), session);
auto deadline = std::chrono::steady_clock::now() + timeout;
int rc{SSH_OK};
while ((std::chrono::steady_clock::now() < deadline) && rc == SSH_OK && !std::holds_alternative<int>(exit_result))
{
rc = ssh_event_dopoll(event.get(), timeout.count());
}
if (!std::holds_alternative<int>(exit_result))
{
std::exception_ptr eptr;
if (rc == SSH_ERROR) // we expect SSH_AGAIN or SSH_OK (unchanged) when there is a timeout
eptr = std::make_exception_ptr(SSHProcessExitError{cmd, std::strerror(errno)});
else
eptr = std::make_exception_ptr(SSHProcessTimeoutException{cmd, timeout});
// note that make_exception_ptr takes by value; we repeat the call with the concrete types to avoid slicing
if (save_exception)
exit_result = eptr;
rethrow_exception(eptr);
}
}
std::string mp::SSHProcess::read_std_output()
{
return read_stream(StreamType::out);
}
std::string mp::SSHProcess::read_std_error()
{
return read_stream(StreamType::err);
}
std::string mp::SSHProcess::read_stream(StreamType type, int timeout)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}:{} {}(type = {}, timeout = {}): ",
__FILE__,
__LINE__,
__FUNCTION__,
static_cast<int>(type),
timeout));
// If the channel is closed there's no output to read
if (ssh_channel_is_closed(channel.get()))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}:{} {}(): channel closed", __FILE__, __LINE__, __FUNCTION__));
return std::string();
}
std::stringstream output;
std::array<char, 256> buffer;
int num_bytes{0};
const bool is_std_err = type == StreamType::err;
do
{
num_bytes = ssh_channel_read_timeout(channel.get(), buffer.data(), buffer.size(), is_std_err, timeout);
mpl::log(mpl::Level::trace,
category,
fmt::format("{}:{} {}(): num_bytes = {}", __FILE__, __LINE__, __FUNCTION__, num_bytes));
if (num_bytes < 0)
{
// Latest libssh now returns an error if the channel has been closed instead of returning 0 bytes
if (ssh_channel_is_closed(channel.get()))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}:{} {}(): channel closed", __FILE__, __LINE__, __FUNCTION__));
return output.str();
}
throw mp::SSHException(
fmt::format("error while reading ssh channel for remote process '{}' - error: {}", cmd, num_bytes));
}
output.write(buffer.data(), num_bytes);
} while (num_bytes > 0);
return output.str();
}
ssh_channel mp::SSHProcess::release_channel()
{
auto local_lock = std::move(session_lock); // released at the end; callers are on their own to ensure thread safety
return channel.release();
}
void multipass::SSHProcess::rethrow_if_saved() const
{
if (auto eptrptr = std::get_if<std::exception_ptr>(&exit_result))
{
assert(!session_lock.owns_lock());
std::rethrow_exception(*eptrptr);
}
}
| 7,264
|
C++
|
.cpp
| 192
| 31.671875
| 119
| 0.641386
|
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,683
|
openssh_key_provider.cpp
|
canonical_multipass/src/ssh/openssh_key_provider.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/ssh/openssh_key_provider.h>
#include <multipass/utils.h>
#include <multipass/format.h>
#include <QDir>
#include <QFile>
#include <memory>
namespace mp = multipass;
namespace
{
mp::OpenSSHKeyProvider::KeyUPtr create_priv_key(const QString& priv_key_path)
{
ssh_key priv_key;
auto ret = ssh_pki_generate(SSH_KEYTYPE_RSA, 2048, &priv_key);
if (ret != SSH_OK)
throw std::runtime_error("unable to generate ssh key");
mp::OpenSSHKeyProvider::KeyUPtr key{priv_key};
ret = ssh_pki_export_privkey_file(priv_key, nullptr, nullptr, nullptr, priv_key_path.toStdString().c_str());
if (ret != SSH_OK)
throw std::runtime_error(fmt::format("failed to export ssh private key to file '{}'", priv_key_path));
QFile::setPermissions(priv_key_path, QFile::ReadOwner);
return key;
}
mp::OpenSSHKeyProvider::KeyUPtr get_priv_key(const QDir& key_dir)
{
auto priv_key_path = key_dir.filePath("id_rsa");
if (QFile::exists(priv_key_path))
{
ssh_key priv_key;
auto imported =
ssh_pki_import_privkey_file(priv_key_path.toStdString().c_str(), nullptr, nullptr, nullptr, &priv_key);
if (imported != SSH_OK)
return create_priv_key(priv_key_path);
return mp::OpenSSHKeyProvider::KeyUPtr{priv_key};
}
return create_priv_key(priv_key_path);
}
} // namespace
void mp::OpenSSHKeyProvider::KeyDeleter::operator()(ssh_key key)
{
ssh_key_free(key);
}
mp::OpenSSHKeyProvider::OpenSSHKeyProvider(const mp::Path& cache_dir)
: ssh_key_dir{MP_UTILS.make_dir(cache_dir, "ssh-keys")}, priv_key{get_priv_key(ssh_key_dir)}
{
}
std::string mp::OpenSSHKeyProvider::private_key_as_base64() const
{
QFile key_file{ssh_key_dir.filePath("id_rsa")};
auto opened = key_file.open(QIODevice::ReadOnly);
if (!opened)
throw std::runtime_error(fmt::format("Unable to open private key file '{}'", key_file.fileName()));
auto data = key_file.readAll();
auto data_size = static_cast<size_t>(data.length());
return {data.constData(), data_size};
}
std::string mp::OpenSSHKeyProvider::public_key_as_base64() const
{
char* base64{nullptr};
auto ret = ssh_pki_export_pubkey_base64(priv_key.get(), &base64);
std::unique_ptr<char, decltype(std::free)*> base64_output{base64, std::free};
if (ret != SSH_OK)
throw std::runtime_error("unable to export public key as base64");
return {base64};
}
ssh_key mp::OpenSSHKeyProvider::private_key() const
{
return priv_key.get();
}
| 3,160
|
C++
|
.cpp
| 84
| 33.904762
| 115
| 0.70121
|
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,684
|
sftp_utils.cpp
|
canonical_multipass/src/ssh/sftp_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/file_ops.h>
#include <multipass/ssh/sftp_utils.h>
#include <fmt/std.h>
namespace multipass
{
SFTPUtils::SFTPUtils(const PrivatePass& pass) noexcept : Singleton<SFTPUtils>::Singleton{pass}
{
}
fs::path SFTPUtils::get_local_file_target(const fs::path& source_path, const fs::path& target_path, bool make_parent)
{
std::error_code err;
if (!MP_FILEOPS.exists(target_path, err) && !err)
{
auto parent_path = target_path.parent_path();
parent_path = parent_path.empty() ? "." : parent_path;
if (make_parent && !MP_FILEOPS.create_directories(parent_path, err) && err)
throw SFTPError{"cannot create local directory {}: {}", parent_path, err.message()};
if (MP_FILEOPS.exists(parent_path, err) && !err)
return target_path;
else if (err)
throw SFTPError{"cannot access {}: {}", parent_path, err.message()};
else
throw SFTPError{"local target does not exist"};
}
else if (err)
throw SFTPError{"cannot access {}: {}", target_path, err.message()};
if (!MP_FILEOPS.is_directory(target_path, err))
return target_path;
auto target_full_path = target_path / source_path.filename();
if (MP_FILEOPS.is_directory(target_full_path, err))
throw SFTPError{"cannot overwrite local directory {} with non-directory", target_full_path};
else if (err && err != std::errc::no_such_file_or_directory)
throw SFTPError{"cannot access {}: {}", target_full_path, err.message()};
return target_full_path;
}
fs::path SFTPUtils::get_remote_file_target(sftp_session sftp, const fs::path& source_path, const fs::path& target_path,
bool make_parent)
{
auto target_full_path = target_path.empty() ? source_path.filename() : target_path;
auto target_attr = mp_sftp_stat(sftp, target_full_path.u8string().c_str());
if (!target_attr)
{
auto parent_path = target_full_path.parent_path().u8string();
parent_path = parent_path.empty() ? "." : parent_path;
if (make_parent)
mkdir_recursive(sftp, parent_path);
return mp_sftp_stat(sftp, parent_path.c_str()) ? target_full_path
: throw SFTPError{"remote target does not exist"};
}
if (target_attr->type != SSH_FILEXFER_TYPE_DIRECTORY)
return target_full_path;
target_full_path += source_path.filename().u8string().insert(0, "/");
target_attr = mp_sftp_stat(sftp, target_full_path.u8string().c_str());
if (target_attr && target_attr->type == SSH_FILEXFER_TYPE_DIRECTORY)
throw SFTPError{"cannot overwrite remote directory {:?} with non-directory", target_full_path};
return target_full_path;
}
fs::path SFTPUtils::get_local_dir_target(const fs::path& source_path, const fs::path& target_path, bool make_parent)
{
std::error_code err;
if (MP_FILEOPS.exists(target_path, err) && !MP_FILEOPS.is_directory(target_path, err) && !err)
throw SFTPError{"cannot overwrite local non-directory {} with directory", target_path};
else if (err)
throw SFTPError{"cannot access {}: {}", target_path, err.message()};
if (!MP_FILEOPS.exists(target_path, err))
{
if (make_parent ? MP_FILEOPS.create_directories(target_path, err)
: MP_FILEOPS.create_directory(target_path, err);
err)
throw SFTPError{"cannot create local directory {}: {}", target_path, err.message()};
return target_path;
}
auto child_path = target_path / source_path.filename();
if (MP_FILEOPS.exists(child_path, err) && !MP_FILEOPS.is_directory(child_path, err) && !err)
throw SFTPError{"cannot overwrite local non-directory {} with directory", child_path};
else if (err)
throw SFTPError{"cannot access {}: {}", child_path, err.message()};
if (!MP_FILEOPS.create_directory(child_path, err) && err)
throw SFTPError{"cannot create local directory {}: {}", child_path, err.message()};
return child_path;
}
fs::path SFTPUtils::get_remote_dir_target(sftp_session sftp, const fs::path& source_path, const fs::path& target_path,
bool make_parent)
{
auto target_path_string = target_path.u8string();
auto target_info = mp_sftp_stat(sftp, target_path_string.c_str());
if (target_info && target_info->type != SSH_FILEXFER_TYPE_DIRECTORY)
throw SFTPError{"cannot overwrite remote non-directory {} with directory", target_path};
if (!target_info)
{
if (make_parent)
mkdir_recursive(sftp, target_path);
else if (sftp_mkdir(sftp, target_path_string.c_str(), 0777) != SSH_FX_OK)
throw SFTPError{"cannot create remote directory {}: {}", target_path, ssh_get_error(sftp->session)};
return target_path;
}
fs::path child_path = target_path_string + '/' + source_path.filename().u8string();
auto child_path_string = child_path.u8string();
auto child_info = mp_sftp_stat(sftp, child_path_string.c_str());
if (child_info && child_info->type != SSH_FILEXFER_TYPE_DIRECTORY)
throw SFTPError{"cannot overwrite remote non-directory {:?} with directory", child_path};
if (!child_info && sftp_mkdir(sftp, child_path_string.c_str(), 0777) != SSH_FX_OK)
throw SFTPError{"cannot create remote directory {:?}: {}", child_path, ssh_get_error(sftp->session)};
return child_path;
}
void SFTPUtils::mkdir_recursive(sftp_session sftp, const fs::path& path)
{
std::vector<fs::path> partial_paths;
// this takes a path and creates a list of all sub-paths
// e.g "some/nested/path" => ["some", "some/nested", "some/nested/path"]
std::partial_sum(path.begin(), path.end(), std::back_inserter(partial_paths),
[](auto acc, auto curr) { return acc.u8string() + '/' + curr.u8string(); });
for (const auto& partial_path : partial_paths)
if (auto attr = mp_sftp_lstat(sftp, partial_path.u8string().c_str());
attr && attr->type != SSH_FILEXFER_TYPE_DIRECTORY)
throw SFTPError{"cannot overwrite remote non-directory {:?} with directory", partial_path};
else if (!attr && sftp_mkdir(sftp, partial_path.u8string().c_str(), 0777) != SSH_FX_OK)
throw SFTPError{"cannot create remote directory {:?}: {}", partial_path, ssh_get_error(sftp->session)};
}
std::unique_ptr<SFTPClient> SFTPUtils::make_SFTPClient(const std::string& host, int port, const std::string& username,
const std::string& priv_key_blob)
{
return std::make_unique<SFTPClient>(host, port, username, priv_key_blob);
}
std::unique_ptr<SFTPDirIterator> SFTPUtils::make_SFTPDirIterator(sftp_session sftp, const fs::path& path)
{
return std::make_unique<SFTPDirIterator>(sftp, path);
}
} // namespace multipass
| 7,576
|
C++
|
.cpp
| 145
| 45.213793
| 119
| 0.653924
|
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,685
|
ssh_session.cpp
|
canonical_multipass/src/ssh/ssh_session.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/exceptions/ssh_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/ssh/ssh_key_provider.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/ssh/throw_on_error.h>
#include <multipass/standard_paths.h>
#include <QDir>
#include <string>
namespace mp = multipass;
namespace mpl = multipass::logging;
mp::SSHSession::SSHSession(const std::string& host,
int port,
const std::string& username,
const SSHKeyProvider& key_provider,
const std::chrono::milliseconds timeout)
: session{ssh_new(), ssh_free}, mut{}
{
if (session == nullptr)
throw mp::SSHException("could not allocate ssh session");
const long timeout_secs = std::chrono::duration_cast<std::chrono::seconds>(timeout).count();
const int nodelay{1};
auto ssh_dir = QDir(MP_STDPATHS.writableLocation(StandardPaths::AppConfigLocation)).filePath("ssh").toStdString();
set_option(SSH_OPTIONS_HOST, host.c_str());
set_option(SSH_OPTIONS_PORT, &port);
set_option(SSH_OPTIONS_USER, username.c_str());
set_option(SSH_OPTIONS_TIMEOUT, &timeout_secs);
set_option(SSH_OPTIONS_NODELAY, &nodelay);
set_option(SSH_OPTIONS_CIPHERS_C_S, "chacha20-poly1305@openssh.com,aes256-ctr");
set_option(SSH_OPTIONS_CIPHERS_S_C, "chacha20-poly1305@openssh.com,aes256-ctr");
set_option(SSH_OPTIONS_SSH_DIR, ssh_dir.c_str());
SSH::throw_on_error(session, "ssh connection failed", ssh_connect);
SSH::throw_on_error(session,
"ssh failed to authenticate",
ssh_userauth_publickey,
nullptr,
key_provider.private_key());
}
multipass::SSHSession::SSHSession(multipass::SSHSession&& other)
: SSHSession(std::move(other), std::unique_lock{other.mut})
{
}
multipass::SSHSession::SSHSession(multipass::SSHSession&& other, std::unique_lock<std::mutex>)
: session{std::move(other.session)}, mut{}
{
}
multipass::SSHSession& multipass::SSHSession::operator=(multipass::SSHSession&& other)
{
if (this != &other)
{
std::scoped_lock lock{mut, other.mut};
session = std::move(other.session);
}
return *this;
}
multipass::SSHSession::~SSHSession()
{
std::unique_lock lock{mut};
ssh_disconnect(session.get());
force_shutdown(); // do we really need this?
}
mp::SSHProcess mp::SSHSession::exec(const std::string& cmd, bool whisper)
{
auto lvl = whisper ? mpl::Level::trace : mpl::Level::debug;
mpl::log(lvl, "ssh session", fmt::format("Executing '{}'", cmd));
return {session.get(), cmd, std::unique_lock{mut}};
}
void mp::SSHSession::force_shutdown()
{
auto socket = ssh_get_fd(session.get());
const int shutdown_read_and_writes = 2;
shutdown(socket, shutdown_read_and_writes);
}
mp::SSHSession::operator ssh_session()
{
return session.get();
}
namespace
{
const char* name_for(ssh_options_e type)
{
switch (type)
{
case SSH_OPTIONS_HOST:
return "host";
case SSH_OPTIONS_PORT:
return "port";
case SSH_OPTIONS_USER:
return "username";
case SSH_OPTIONS_TIMEOUT:
return "timeout";
case SSH_OPTIONS_NODELAY:
return "NODELAY";
case SSH_OPTIONS_CIPHERS_C_S:
return "client to server ciphers";
case SSH_OPTIONS_CIPHERS_S_C:
return "server to client ciphers";
case SSH_OPTIONS_SSH_DIR:
return "ssh config directory";
default:
break;
}
return "unknown";
}
std::string as_string(ssh_options_e type, const void* value)
{
switch (type)
{
case SSH_OPTIONS_HOST:
case SSH_OPTIONS_USER:
case SSH_OPTIONS_CIPHERS_C_S:
case SSH_OPTIONS_CIPHERS_S_C:
case SSH_OPTIONS_SSH_DIR:
return std::string(reinterpret_cast<const char*>(value));
case SSH_OPTIONS_PORT:
case SSH_OPTIONS_NODELAY:
return std::to_string(*reinterpret_cast<const int*>(value));
case SSH_OPTIONS_TIMEOUT:
return std::to_string(*reinterpret_cast<const long*>(value));
default:
break;
}
return fmt::format("{}", value);
}
} // namespace
void mp::SSHSession::set_option(ssh_options_e type, const void* data)
{
const auto ret = ssh_options_set(session.get(), type, data);
if (ret != SSH_OK)
{
throw mp::SSHException(fmt::format("libssh failed to set {} option to '{}': '{}'", name_for(type),
as_string(type, data), ssh_get_error(session.get())));
}
}
bool multipass::SSHSession::is_connected() const
{
std::unique_lock lock{mut};
return static_cast<bool>(ssh_is_connected(session.get()));
}
| 5,399
|
C++
|
.cpp
| 155
| 29.483871
| 118
| 0.665517
|
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,686
|
sftp_client.cpp
|
canonical_multipass/src/ssh/sftp_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 <multipass/ssh/sftp_client.h>
#include "ssh_client_key_provider.h"
#include <multipass/file_ops.h>
#include <multipass/logging/log.h>
#include <multipass/ssh/sftp_utils.h>
#include <multipass/ssh/throw_on_error.h>
#include <multipass/utils.h>
#include <array>
#include <fcntl.h>
#include <fmt/std.h>
constexpr int file_mode = 0664;
constexpr auto max_transfer = 65536u;
const std::string stream_file_name{"stream_output.dat"};
const char* log_category = "sftp";
namespace multipass
{
namespace mpl = logging;
SFTPSessionUPtr make_sftp_session(ssh_session session)
{
auto sftp = mp_sftp_new(session);
if (!sftp)
throw std::runtime_error(fmt::format("[sftp] could not create new sftp session: {}", ssh_get_error(session)));
return sftp;
}
SFTPClient::SFTPClient(const std::string& host, int port, const std::string& username, const std::string& priv_key_blob)
: SFTPClient{std::make_unique<SSHSession>(host, port, username, SSHClientKeyProvider(priv_key_blob))}
{
}
SFTPClient::SFTPClient(SSHSessionUPtr ssh_session)
: ssh_session{std::move(ssh_session)}, sftp{make_sftp_session(*this->ssh_session)}
{
SSH::throw_on_error(sftp, *this->ssh_session, "[sftp] init failed", sftp_init);
}
bool SFTPClient::is_remote_dir(const fs::path& path)
{
auto attr = mp_sftp_stat(sftp.get(), path.u8string().c_str());
return attr && attr->type == SSH_FILEXFER_TYPE_DIRECTORY;
}
bool SFTPClient::push(const fs::path& source_path, const fs::path& target_path, const Flags flags)
try
{
auto source = source_path.string();
utils::trim_end(source, [](char ch) { return ch == '/' || ch == fs::path::preferred_separator; });
std::error_code err;
if (MP_FILEOPS.is_directory(source_path, err) && !err)
{
if (!flags.testFlag(Flag::Recursive))
throw SFTPError{"omitting local directory {}: recursive mode not specified", source_path};
auto full_target_path = MP_SFTPUTILS.get_remote_dir_target(sftp.get(), source, target_path,
flags.testFlag(SFTPClient::Flag::MakeParent));
return push_dir(source, full_target_path);
}
else if (err)
throw SFTPError{"cannot access {}: {}", source_path, err.message()};
auto full_target_path = MP_SFTPUTILS.get_remote_file_target(sftp.get(), source, target_path,
flags.testFlag(SFTPClient::Flag::MakeParent));
push_file(source, full_target_path);
return true;
}
catch (const SFTPError& e)
{
mpl::log(mpl::Level::error, log_category, e.what());
return false;
}
bool SFTPClient::pull(const fs::path& source_path, const fs::path& target_path, const Flags flags)
try
{
auto source = source_path.string();
utils::trim_end(source, [](char ch) { return ch == '/' || ch == fs::path::preferred_separator; });
if (is_remote_dir(source_path))
{
if (!flags.testFlag(Flag::Recursive))
throw SFTPError{"omitting remote directory {}: recursive mode not specified", source_path};
auto full_target_path =
MP_SFTPUTILS.get_local_dir_target(source, target_path, flags.testFlag(SFTPClient::Flag::MakeParent));
return pull_dir(source, full_target_path);
}
auto full_target_path =
MP_SFTPUTILS.get_local_file_target(source, target_path, flags.testFlag(SFTPClient::Flag::MakeParent));
pull_file(source, full_target_path);
return true;
}
catch (const SFTPError& e)
{
mpl::log(mpl::Level::error, log_category, e.what());
return false;
}
void SFTPClient::push_file(const fs::path& source_path, const fs::path& target_path)
{
auto local_file = MP_FILEOPS.open_read(source_path, std::ios_base::in | std::ios_base::binary);
if (local_file->fail())
throw SFTPError{"cannot open local file {}: {}", source_path, strerror(errno)};
do_push_file(*local_file, target_path);
std::error_code _;
auto status = MP_FILEOPS.status(source_path, _);
if (sftp_chmod(sftp.get(), target_path.u8string().c_str(), static_cast<mode_t>(status.permissions())) != SSH_FX_OK)
throw SFTPError{"cannot set permissions for remote file {}: {}", target_path, ssh_get_error(sftp->session)};
if (local_file->fail() && !local_file->eof())
throw SFTPError{"cannot read from local file {}: {}", source_path, strerror(errno)};
}
void SFTPClient::pull_file(const fs::path& source_path, const fs::path& target_path)
{
auto local_file = MP_FILEOPS.open_write(target_path, std::ios_base::out | std::ios_base::binary);
if (local_file->fail())
throw SFTPError{"cannot open local file {}: {}", target_path, strerror(errno)};
do_pull_file(source_path, *local_file);
auto source_perms = mp_sftp_stat(sftp.get(), source_path.u8string().c_str())->permissions;
std::error_code err;
if (MP_FILEOPS.permissions(target_path, static_cast<fs::perms>(source_perms), err); err)
throw SFTPError{"cannot set permissions for local file {}: {}", target_path, err.message()};
if (local_file->fail())
throw SFTPError{"cannot write to local file {}: {}", target_path, strerror(errno)};
}
bool SFTPClient::push_dir(const fs::path& source_path, const fs::path& target_path)
{
auto success = true;
std::error_code err;
auto local_iter = MP_FILEOPS.recursive_dir_iterator(source_path, err);
if (err)
throw SFTPError{"cannot open local directory {}: {}", source_path, err.message()};
std::vector<std::pair<fs::path, fs::perms>> subdirectory_perms{
{target_path, MP_FILEOPS.status(source_path, err).permissions()}};
while (local_iter->hasNext())
{
try
{
const auto& entry = local_iter->next();
auto remote_file_str =
entry.path().u8string().replace(0, source_path.u8string().size(), target_path.u8string());
std::replace(remote_file_str.begin(), remote_file_str.end(), (char)fs::path::preferred_separator, '/');
const fs::path remote_file_path{remote_file_str};
const auto status = entry.symlink_status();
switch (status.type())
{
case fs::file_type::regular:
{
push_file(entry.path(), remote_file_path);
break;
}
case fs::file_type::directory:
{
if (sftp_mkdir(sftp.get(), remote_file_path.u8string().c_str(), 0777) != SSH_OK &&
sftp_get_error(sftp.get()) != SSH_FX_FILE_ALREADY_EXISTS)
throw SFTPError{"cannot create remote directory {:?}: {}",
remote_file_path,
ssh_get_error(sftp->session)};
subdirectory_perms.emplace_back(remote_file_path, status.permissions());
break;
}
case fs::file_type::symlink:
{
auto link_target = MP_FILEOPS.read_symlink(entry.path(), err);
if (err)
throw SFTPError{"cannot read local link {}: {}", entry.path(), err.message()};
auto remote_file_info = mp_sftp_lstat(sftp.get(), remote_file_path.u8string().c_str());
if (remote_file_info && remote_file_info->type == SSH_FILEXFER_TYPE_DIRECTORY)
throw SFTPError{"cannot overwrite remote directory {:?} with non-directory", remote_file_path};
if ((sftp_unlink(sftp.get(), remote_file_path.u8string().c_str()) != SSH_FX_OK &&
sftp_get_error(sftp.get()) != SSH_FX_NO_SUCH_FILE) ||
sftp_symlink(sftp.get(), link_target.u8string().c_str(), remote_file_path.u8string().c_str()) !=
SSH_FX_OK)
throw SFTPError{"cannot create remote symlink {:?}: {}",
remote_file_path,
ssh_get_error(sftp->session)};
break;
}
default:
throw SFTPError{"cannot copy {}: not a regular file", entry.path()};
}
}
catch (const SFTPError& e)
{
mpl::log(mpl::Level::error, log_category, e.what());
success = false;
}
}
for (auto it = subdirectory_perms.crbegin(); it != subdirectory_perms.crend(); ++it)
{
const auto& [path, perms] = *it;
if (sftp_chmod(sftp.get(), path.u8string().c_str(), static_cast<mode_t>(perms)) != SSH_FX_OK)
{
mpl::log(
mpl::Level::error, log_category,
fmt::format("cannot set permissions for remote directory {}: {}", path, ssh_get_error(sftp->session)));
success = false;
}
}
return success;
}
bool SFTPClient::pull_dir(const fs::path& source_path, const fs::path& target_path)
{
auto success = true;
std::error_code err;
auto remote_iter = MP_SFTPUTILS.make_SFTPDirIterator(sftp.get(), source_path);
std::vector<std::pair<fs::path, mode_t>> subdirectory_perms{
{target_path, mp_sftp_stat(sftp.get(), source_path.u8string().c_str())->permissions}};
while (remote_iter->hasNext())
{
try
{
const auto entry = remote_iter->next();
const auto local_file_path = target_path / (entry->name + source_path.string().size() + 1);
switch (entry->type)
{
case SSH_FILEXFER_TYPE_REGULAR:
{
pull_file(entry->name, local_file_path);
break;
}
case SSH_FILEXFER_TYPE_DIRECTORY:
{
if (MP_FILEOPS.create_directory(local_file_path, err); err)
throw SFTPError{"cannot create local directory {}: {}", local_file_path, err.message()};
subdirectory_perms.emplace_back(local_file_path, entry->permissions);
break;
}
case SSH_FILEXFER_TYPE_SYMLINK:
{
auto link_target = mp_sftp_readlink(sftp.get(), entry->name);
if (!link_target)
throw SFTPError{"cannot read remote link \"{}\": {}", entry->name, ssh_get_error(sftp->session)};
if (MP_FILEOPS.is_directory(local_file_path, err))
throw SFTPError{"cannot overwrite local directory {} with non-directory", local_file_path};
if (MP_FILEOPS.remove(local_file_path, err); !err)
if (MP_FILEOPS.create_symlink(link_target.get(), local_file_path, err); !err)
break;
throw SFTPError{"cannot create local symlink {}: {}", local_file_path, err.message()};
}
default:
throw SFTPError{"cannot copy \"{}\": not a regular file", entry->name};
}
}
catch (const SFTPError& e)
{
mpl::log(mpl::Level::error, log_category, e.what());
success = false;
}
}
for (auto it = subdirectory_perms.crbegin(); it != subdirectory_perms.crend(); ++it)
{
const auto& [path, perms] = *it;
MP_FILEOPS.permissions(path, static_cast<fs::perms>(perms), err);
if (err)
{
mpl::log(mpl::Level::error, log_category,
fmt::format("cannot set permissions for local directory {}: {}", path, err.message()));
success = false;
}
}
return success;
}
void SFTPClient::from_cin(std::istream& cin, const fs::path& target_path, bool make_parent)
{
auto full_target_path = MP_SFTPUTILS.get_remote_file_target(sftp.get(), stream_file_name, target_path, make_parent);
do_push_file(cin, full_target_path);
}
void SFTPClient::to_cout(const fs::path& source_path, std::ostream& cout)
{
do_pull_file(source_path, cout);
}
void SFTPClient::do_push_file(std::istream& source, const fs::path& target_path)
{
auto remote_file =
mp_sftp_open(sftp.get(), target_path.u8string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, file_mode);
if (!remote_file)
throw SFTPError{"cannot open remote file {}: {}", target_path, ssh_get_error(sftp->session)};
std::array<char, max_transfer> buffer{};
while (auto r = source.read(buffer.data(), buffer.size()).gcount())
if (sftp_write(remote_file.get(), buffer.data(), r) < 0)
throw SFTPError{"cannot write to remote file {}: {}", target_path, ssh_get_error(sftp->session)};
}
void SFTPClient::do_pull_file(const fs::path& source_path, std::ostream& target)
{
auto remote_file = mp_sftp_open(sftp.get(), source_path.u8string().c_str(), O_RDONLY, 0);
if (!remote_file)
throw SFTPError{"cannot open remote file {}: {}", source_path, ssh_get_error(sftp->session)};
std::array<char, max_transfer> buffer{};
while (auto r = sftp_read(remote_file.get(), buffer.data(), buffer.size()))
{
if (r < 0)
throw SFTPError{"cannot read from remote file {}: {}", source_path, ssh_get_error(sftp->session)};
target.write(buffer.data(), r);
}
}
} // namespace multipass
| 13,828
|
C++
|
.cpp
| 301
| 37.355482
| 120
| 0.609041
|
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,687
|
ssh_client_key_provider.cpp
|
canonical_multipass/src/ssh/ssh_client_key_provider.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 "ssh_client_key_provider.h"
#include <stdexcept>
namespace mp = multipass;
namespace
{
mp::SSHClientKeyProvider::KeyUPtr import_priv_key(const std::string& priv_key_blob)
{
ssh_key priv_key;
ssh_pki_import_privkey_base64(priv_key_blob.c_str(), nullptr, nullptr, nullptr, &priv_key);
return mp::SSHClientKeyProvider::KeyUPtr{priv_key};
}
}
void mp::SSHClientKeyProvider::KeyDeleter::operator()(ssh_key key)
{
ssh_key_free(key);
}
mp::SSHClientKeyProvider::SSHClientKeyProvider(const std::string& priv_key_blob)
: priv_key{import_priv_key(priv_key_blob)}
{
}
std::string mp::SSHClientKeyProvider::private_key_as_base64() const
{
throw std::runtime_error("Unimplemented");
}
std::string mp::SSHClientKeyProvider::public_key_as_base64() const
{
throw std::runtime_error("Unimplemented");
}
ssh_key mp::SSHClientKeyProvider::private_key() const
{
return priv_key.get();
}
| 1,546
|
C++
|
.cpp
| 48
| 30.020833
| 95
| 0.752688
|
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,688
|
sftp_dir_iterator.cpp
|
canonical_multipass/src/ssh/sftp_dir_iterator.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/format.h>
#include <multipass/ssh/sftp_dir_iterator.h>
#include <multipass/ssh/sftp_utils.h>
#include <stdexcept>
namespace multipass
{
void SFTPDirIterator::push_dir(const std::string& path)
{
auto dir = mp_sftp_opendir(sftp, path.c_str());
if (!dir)
throw SFTPError{"cannot open remote directory '{}': {}", path, ssh_get_error(sftp->session)};
dirs.push(std::move(dir));
}
SFTPDirIterator::SFTPDirIterator(sftp_session sftp, const fs::path& path) : sftp(sftp)
{
push_dir(path.u8string());
next();
}
bool SFTPDirIterator::hasNext() const
{
return bool{next_attr};
}
SFTPAttributesUPtr SFTPDirIterator::next()
{
if (dirs.empty())
return std::move(next_attr);
auto dir = dirs.top().get();
while (auto attr = mp_sftp_readdir(sftp, dir))
{
if (strcmp(attr->name, ".") == 0 || strcmp(attr->name, "..") == 0)
continue;
auto path = fmt::format("{}/{}", dir->name, attr->name);
if (attr->type == SSH_FILEXFER_TYPE_DIRECTORY)
push_dir(path);
attr->name = strdup(path.c_str());
next_attr.swap(attr);
return attr;
}
if (sftp_dir_eof(dir))
{
dirs.pop();
return next();
}
SFTPError err{"cannot read remote directory '{}': {}", dir->name, ssh_get_error(sftp->session)};
dirs.pop();
throw err;
}
} // namespace multipass
| 2,039
|
C++
|
.cpp
| 64
| 27.75
| 101
| 0.662761
|
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,689
|
ssh_client.cpp
|
canonical_multipass/src/ssh/ssh_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 <multipass/ssh/ssh_client.h>
#include <multipass/ssh/throw_on_error.h>
#include <multipass/utils.h>
#include "ssh_client_key_provider.h"
namespace mp = multipass;
namespace
{
mp::SSHClient::ChannelUPtr make_channel(ssh_session session)
{
mp::SSHClient::ChannelUPtr channel{ssh_channel_new(session), ssh_channel_free};
mp::SSH::throw_on_error(channel, session, "[ssh client] channel creation failed", ssh_channel_open_session);
return channel;
}
} // namespace
mp::SSHClient::SSHClient(const std::string& host, int port, const std::string& username,
const std::string& priv_key_blob, ConsoleCreator console_creator)
: SSHClient{std::make_unique<mp::SSHSession>(host, port, username, mp::SSHClientKeyProvider(priv_key_blob)),
console_creator}
{
}
mp::SSHClient::SSHClient(SSHSessionUPtr ssh_session, ConsoleCreator console_creator)
: ssh_session{std::move(ssh_session)},
channel{make_channel(*this->ssh_session)},
console{console_creator(channel.get())}
{
}
void mp::SSHClient::connect()
{
exec(std::vector<std::string>{});
}
int mp::SSHClient::exec(const std::vector<std::string>& args)
{
return exec_string(utils::to_cmd(args, mp::utils::QuoteType::quote_every_arg));
}
int mp::SSHClient::exec(const std::vector<std::vector<std::string>>& args_list)
{
std::string cmd_line;
if (args_list.size())
{
auto args_it = args_list.begin();
cmd_line = utils::to_cmd(*args_it++, mp::utils::QuoteType::quote_every_arg);
for (; args_it != args_list.end(); ++args_it)
cmd_line += "&&" + utils::to_cmd(*args_it, mp::utils::QuoteType::quote_every_arg);
}
return exec_string(cmd_line);
}
void mp::SSHClient::handle_ssh_events()
{
using ConnectorUPtr = std::unique_ptr<ssh_connector_struct, void (*)(ssh_connector)>;
std::unique_ptr<ssh_event_struct, void (*)(ssh_event)> event{ssh_event_new(), ssh_event_free};
// stdin
ConnectorUPtr connector_in{ssh_connector_new(*ssh_session), ssh_connector_free};
ssh_connector_set_out_channel(connector_in.get(), channel.get(), SSH_CONNECTOR_STDOUT);
ssh_connector_set_in_fd(connector_in.get(), fileno(stdin));
ssh_event_add_connector(event.get(), connector_in.get());
// stdout
ConnectorUPtr connector_out{ssh_connector_new(*ssh_session), ssh_connector_free};
ssh_connector_set_out_fd(connector_out.get(), fileno(stdout));
ssh_connector_set_in_channel(connector_out.get(), channel.get(), SSH_CONNECTOR_STDOUT);
ssh_event_add_connector(event.get(), connector_out.get());
// stderr
ConnectorUPtr connector_err{ssh_connector_new(*ssh_session), ssh_connector_free};
ssh_connector_set_out_fd(connector_err.get(), fileno(stderr));
ssh_connector_set_in_channel(connector_err.get(), channel.get(), SSH_CONNECTOR_STDERR);
ssh_event_add_connector(event.get(), connector_err.get());
while (ssh_channel_is_open(channel.get()) && !ssh_channel_is_eof(channel.get()))
{
ssh_event_dopoll(event.get(), 60000);
}
ssh_event_remove_connector(event.get(), connector_in.get());
ssh_event_remove_connector(event.get(), connector_out.get());
ssh_event_remove_connector(event.get(), connector_err.get());
}
int mp::SSHClient::exec_string(const std::string& cmd_line)
{
if (cmd_line.empty())
SSH::throw_on_error(channel, *ssh_session, "[ssh client] shell request failed", ssh_channel_request_shell);
else
SSH::throw_on_error(channel, *ssh_session, "[ssh client] exec request failed", ssh_channel_request_exec,
cmd_line.c_str());
handle_ssh_events();
return ssh_channel_get_exit_status(channel.get());
}
| 4,356
|
C++
|
.cpp
| 99
| 39.626263
| 115
| 0.698465
|
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,690
|
basic_process.cpp
|
canonical_multipass/src/process/basic_process.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/format.h>
#include <multipass/logging/log.h>
#include <multipass/process/basic_process.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
// Want to call qRegisterMetaType just once
static auto reg = []() -> bool {
qRegisterMetaType<multipass::ProcessState>();
qRegisterMetaType<QProcess::ProcessError>();
return true;
}();
} // namespace
mp::BasicProcess::CustomQProcess::CustomQProcess(BasicProcess* p) : QProcess{p}
{
setChildProcessModifier([p] { p->setup_child_process(); });
}
mp::BasicProcess::BasicProcess(std::shared_ptr<mp::ProcessSpec> spec) : process_spec{spec}, process{this}
{
connect(&process, &QProcess::started, this, &mp::BasicProcess::handle_started);
connect(&process, qOverload<int, QProcess::ExitStatus>(&QProcess::finished),
[this](int exit_code, QProcess::ExitStatus exit_status) {
mp::ProcessState process_state;
if (exit_status == QProcess::NormalExit)
{
process_state.exit_code = exit_code;
}
else // crash
{
process_state.error = mp::ProcessState::Error{process.error(), error_string()};
}
emit mp::Process::finished(process_state);
});
connect(&process, &QProcess::errorOccurred,
[this](QProcess::ProcessError error) { emit mp::Process::error_occurred(error, error_string()); });
connect(&process, &QProcess::readyReadStandardOutput, this, &mp::Process::ready_read_standard_output);
connect(&process, &QProcess::readyReadStandardError, this, &mp::Process::ready_read_standard_error);
connect(&process, &QProcess::stateChanged, this, &mp::Process::state_changed);
process.setProgram(process_spec->program());
process.setArguments(process_spec->arguments());
process.setProcessEnvironment(process_spec->environment());
if (!process_spec->working_directory().isNull())
process.setWorkingDirectory(process_spec->working_directory());
// TODO: multiline output produces poor formatting in logs, needs improving
QObject::connect(&process, &QProcess::readyReadStandardError, [this]() {
// Using readAllStandardError() removes it from buffer for Process consumers, so peek() instead.
// This copies the implementation of QProcess::readAllStandardError() replacing the read with peek.
auto original = process.readChannel();
process.setReadChannel(QProcess::StandardError);
QByteArray data = process.peek(process.bytesAvailable());
process.setReadChannel(original);
mpl::log(process_spec->error_log_level(), qUtf8Printable(process_spec->program()), qUtf8Printable(data));
});
}
mp::BasicProcess::~BasicProcess() = default;
QString mp::BasicProcess::program() const
{
return process.program();
}
QStringList mp::BasicProcess::arguments() const
{
return process.arguments();
}
QString mp::BasicProcess::working_directory() const
{
return process.workingDirectory();
}
QProcessEnvironment mp::BasicProcess::process_environment() const
{
return process.processEnvironment();
}
qint64 mp::BasicProcess::process_id() const
{
return pid;
}
void mp::BasicProcess::start()
{
process.start();
}
void mp::BasicProcess::terminate()
{
process.terminate();
}
void mp::BasicProcess::kill()
{
process.kill();
}
bool mp::BasicProcess::wait_for_started(int msecs)
{
return process.waitForStarted(msecs);
}
bool mp::BasicProcess::wait_for_finished(int msecs)
{
return process.waitForFinished(msecs);
}
bool mp::BasicProcess::wait_for_ready_read(int msecs)
{
return process.waitForReadyRead(msecs);
}
mp::ProcessState mp::BasicProcess::process_state() const
{
mp::ProcessState state;
if (process.error() != QProcess::ProcessError::UnknownError)
{
state.error = mp::ProcessState::Error{process.error(), error_string()};
}
else if (process.state() != QProcess::Running && process.exitStatus() == QProcess::NormalExit)
{
state.exit_code = process.exitCode();
}
return state;
}
QString mp::BasicProcess::error_string() const
{
return QString{"program: %1; error: %2"}.arg(process_spec->program(), process.errorString());
}
bool mp::BasicProcess::running() const
{
return process.state() == QProcess::Running;
}
QByteArray mp::BasicProcess::read_all_standard_output()
{
return process.readAllStandardOutput();
}
QByteArray mp::BasicProcess::read_all_standard_error()
{
return process.readAllStandardError();
}
qint64 mp::BasicProcess::write(const QByteArray& data)
{
return process.write(data);
}
void mp::BasicProcess::close_write_channel()
{
process.closeWriteChannel();
}
void mp::BasicProcess::set_process_channel_mode(QProcess::ProcessChannelMode mode)
{
process.setProcessChannelMode(mode);
}
mp::ProcessState mp::BasicProcess::execute(const int timeout)
{
mp::ProcessState exit_state;
start();
if (!process.waitForStarted(timeout) || !process.waitForFinished(timeout) ||
process.exitStatus() != QProcess::NormalExit)
{
mpl::log(mpl::Level::error, qUtf8Printable(process_spec->program()), qUtf8Printable(process.errorString()));
exit_state.error = mp::ProcessState::Error{process.error(), error_string()};
return exit_state;
}
exit_state.exit_code = process.exitCode();
return exit_state;
}
void mp::BasicProcess::setup_child_process()
{
}
void mp::BasicProcess::handle_started()
{
pid = process.processId(); // save this, so we know it even after finished
const auto& program = process_spec->program().toStdString();
mpl::log(mpl::Level::debug, program,
fmt::format("[{}] started: {} {}", pid, program, process_spec->arguments().join(' ')));
emit mp::Process::started();
}
| 6,529
|
C++
|
.cpp
| 182
| 31.598901
| 116
| 0.705752
|
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,691
|
simple_process_spec.cpp
|
canonical_multipass/src/process/simple_process_spec.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/process/simple_process_spec.h>
namespace mp = multipass;
namespace
{
class SimpleProcessSpec : public mp::ProcessSpec
{
public:
SimpleProcessSpec(const QString& cmd, const QStringList& args) : cmd{cmd}, args{args}
{
}
QString program() const override
{
return cmd;
}
QStringList arguments() const override
{
return args;
}
QString apparmor_profile() const override
{
return QString();
}
private:
const QString cmd;
const QStringList args;
};
} // namespace
std::unique_ptr<mp::ProcessSpec> mp::simple_process_spec(const QString& cmd, const QStringList& args)
{
return std::make_unique<::SimpleProcessSpec>(cmd, args);
}
| 1,359
|
C++
|
.cpp
| 47
| 25.659574
| 101
| 0.723372
|
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,692
|
qemuimg_process_spec.cpp
|
canonical_multipass/src/process/qemuimg_process_spec.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/exceptions/snap_environment_exception.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <multipass/snap_utils.h>
namespace mp = multipass;
namespace mpu = multipass::utils;
mp::QemuImgProcessSpec::QemuImgProcessSpec(const QStringList& args, const QString& source_image,
const QString& target_image)
: args{args}, source_image{source_image}, target_image{target_image}
{
}
QString mp::QemuImgProcessSpec::program() const
{
return "qemu-img";
}
QStringList mp::QemuImgProcessSpec::arguments() const
{
return args;
}
QString mp::QemuImgProcessSpec::apparmor_profile() const
{
QString profile_template(R"END(
#include <tunables/global>
profile %1 flags=(attach_disconnected) {
#include <abstractions/base>
capability ipc_lock,
capability dac_read_search,
%2
# binary and its libs
%3/usr/bin/%4 ixr,
%3/{usr/,}lib/@{multiarch}/{,**/}*.so* rm,
# CLASSIC ONLY: need to specify required libs from core snap
/{,var/lib/snapd/}snap/core18/*/{,usr/}lib/@{multiarch}/{,**/}*.so* rm,
# Images
%5
# Allow multipassd send qemu-img signals
signal (receive) peer=%6,
}
)END");
/* Customisations depending on if running inside snap or not */
QString root_dir; // root directory: either "" or $SNAP
QString images;
QString extra_capabilities;
QString signal_peer; // who can send kill signal to qemu-img
try
{
root_dir = mpu::snap_dir();
signal_peer = "snap.multipass.multipassd"; // only multipassd can send qemu-img signals
}
catch (mp::SnapEnvironmentException&)
{
extra_capabilities = "capability dac_override,"; // FIXME - unclear why this is required when
// not snap confined
signal_peer = "unconfined";
}
if (!source_image.isEmpty())
images.append(QString(" %1 rwk,\n").arg(source_image)); // allow amending to qcow2 v3
if (!target_image.isEmpty())
images.append(QString(" %1 rwk,\n").arg(target_image));
return profile_template.arg(apparmor_profile_name(), extra_capabilities, root_dir, program(), images, signal_peer);
}
| 2,840
|
C++
|
.cpp
| 76
| 32.697368
| 119
| 0.690684
|
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,693
|
process_spec.cpp
|
canonical_multipass/src/process/process_spec.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/process/process_spec.h>
#include <QFileInfo>
namespace mp = multipass;
namespace mpl = multipass::logging;
// Create Process with these fixed arguments. Other optional arguments can be appended in Process::start()
QStringList mp::ProcessSpec::arguments() const
{
return QStringList();
}
// Set environment of child as that of this process
QProcessEnvironment mp::ProcessSpec::environment() const
{
return QProcessEnvironment::systemEnvironment();
}
// Specify working directory of process
QString mp::ProcessSpec::working_directory() const
{
return QString();
}
// Set what multipass logging level the stderr of the child process should have
mpl::Level mp::ProcessSpec::error_log_level() const
{
return mpl::Level::warning;
}
// For cases when multiple instances of this process need different AppArmor profiles, use this
// identifier to distinguish them
QString multipass::ProcessSpec::identifier() const
{
return QString();
}
// String used to register this profile with AppArmor
const QString mp::ProcessSpec::apparmor_profile_name() const
{
const QString executable_name = QFileInfo(program()).fileName(); // in case full path is specified
if (!identifier().isNull())
{
return "multipass." + identifier() + '.' + executable_name;
}
else
{
return "multipass." + executable_name;
}
}
| 2,009
|
C++
|
.cpp
| 59
| 31.542373
| 106
| 0.751031
|
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,694
|
xz_image_decoder.cpp
|
canonical_multipass/src/xz_decoder/xz_image_decoder.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/xz_image_decoder.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/format.h>
#include <vector>
namespace mp = multipass;
namespace
{
bool verify_decode(const xz_ret& ret)
{
switch (ret)
{
case XZ_OK:
break;
case XZ_STREAM_END:
return false;
case XZ_MEM_ERROR:
throw std::runtime_error("xz decoder memory allocation failed");
case XZ_MEMLIMIT_ERROR:
throw std::runtime_error("xz decoder memory usage limit reached");
case XZ_FORMAT_ERROR:
throw std::runtime_error("not a xz file");
case XZ_OPTIONS_ERROR:
throw std::runtime_error("unsupported options in the xz headers");
case XZ_DATA_ERROR:
case XZ_BUF_ERROR:
throw std::runtime_error("xz file is corrupt");
default:
throw std::runtime_error("xz decoder unhandled error condition");
}
return true;
}
} // namespace
mp::XzImageDecoder::XzImageDecoder(const Path& xz_file_path)
: xz_file{xz_file_path}, xz_decoder{xz_dec_init(XZ_DYNALLOC, 1u << 26), xz_dec_end}
{
xz_crc32_init();
xz_crc64_init();
}
void mp::XzImageDecoder::decode_to(const Path& decoded_image_path, const ProgressMonitor& monitor)
{
if (!xz_file.open(QIODevice::ReadOnly))
throw std::runtime_error(fmt::format("failed to open {} for reading", xz_file.fileName()));
QFile decoded_file{decoded_image_path};
if (!decoded_file.open(QIODevice::WriteOnly))
throw std::runtime_error(fmt::format("failed to open {} for writing", decoded_file.fileName()));
struct xz_buf decode_buf
{
};
const auto max_size = 65536u;
std::vector<char> read_data, write_data;
read_data.reserve(max_size);
write_data.reserve(max_size);
decode_buf.in = reinterpret_cast<unsigned char*>(read_data.data());
decode_buf.in_pos = 0;
decode_buf.in_size = 0;
decode_buf.out = reinterpret_cast<unsigned char*>(write_data.data());
decode_buf.out_pos = 0;
decode_buf.out_size = max_size;
const auto file_size = xz_file.size();
qint64 total_bytes_extracted{0};
auto last_progress = -1;
while (true)
{
if (decode_buf.in_pos == decode_buf.in_size)
{
decode_buf.in_size = xz_file.read(read_data.data(), max_size);
decode_buf.in_pos = 0;
total_bytes_extracted += decode_buf.in_size;
auto progress = (total_bytes_extracted / (float)file_size) * 100;
if (last_progress != progress)
monitor(LaunchProgress::EXTRACT, progress);
last_progress = progress;
}
if (!verify_decode(xz_dec_run(xz_decoder.get(), &decode_buf)))
{
decoded_file.write(write_data.data(), decode_buf.out_pos);
return;
}
if (decode_buf.out_pos == max_size)
{
decoded_file.write(write_data.data(), decode_buf.out_pos);
decode_buf.out_pos = 0;
}
}
}
| 3,608
|
C++
|
.cpp
| 101
| 30.049505
| 104
| 0.65788
|
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,695
|
vm_image_vault_utils.cpp
|
canonical_multipass/src/utils/vm_image_vault_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/format.h>
#include <multipass/vm_image_host.h>
#include <multipass/vm_image_vault.h>
#include <multipass/xz_image_decoder.h>
#include <QCryptographicHash>
#include <QFileInfo>
#include <stdexcept>
namespace mp = multipass;
QString mp::vault::filename_for(const mp::Path& path)
{
QFileInfo file_info(path);
return file_info.fileName();
}
QString mp::vault::copy(const QString& file_name, const QDir& output_dir)
{
if (file_name.isEmpty())
return {};
if (!QFileInfo::exists(file_name))
throw std::runtime_error(fmt::format("{} missing", file_name));
QFileInfo info{file_name};
const auto source_name = info.fileName();
auto new_path = output_dir.filePath(source_name);
QFile::copy(file_name, new_path);
return new_path;
}
void mp::vault::delete_file(const mp::Path& path)
{
QFile file{path};
file.remove();
}
QString mp::vault::compute_image_hash(const mp::Path& image_path)
{
QFile image_file(image_path);
if (!image_file.open(QFile::ReadOnly))
{
throw std::runtime_error("Cannot open image file for computing hash");
}
QCryptographicHash hash(QCryptographicHash::Sha256);
if (!hash.addData(&image_file))
{
throw std::runtime_error("Cannot read image file to compute hash");
}
return hash.result().toHex();
}
void mp::vault::verify_image_download(const mp::Path& image_path, const QString& image_hash)
{
auto computed_hash = compute_image_hash(image_path);
if (computed_hash != image_hash)
{
throw std::runtime_error("Downloaded image hash does not match");
}
}
QString mp::vault::extract_image(const mp::Path& image_path, const mp::ProgressMonitor& monitor, const bool delete_file)
{
mp::XzImageDecoder xz_decoder(image_path);
QString new_image_path{image_path};
new_image_path.remove(".xz");
xz_decoder.decode_to(new_image_path, monitor);
mp::vault::delete_file(image_path);
return new_image_path;
}
std::unordered_map<std::string, mp::VMImageHost*>
mp::vault::configure_image_host_map(const std::vector<mp::VMImageHost*>& image_hosts)
{
std::unordered_map<std::string, mp::VMImageHost*> remote_image_host_map;
for (const auto& image_host : image_hosts)
{
for (const auto& remote : image_host->supported_remotes())
{
remote_image_host_map[remote] = image_host;
}
}
return remote_image_host_map;
}
| 3,084
|
C++
|
.cpp
| 90
| 30.455556
| 120
| 0.70424
|
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,696
|
standard_paths.cpp
|
canonical_multipass/src/utils/standard_paths.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/standard_paths.h>
namespace mp = multipass;
mp::StandardPaths::StandardPaths(const Singleton<StandardPaths>::PrivatePass& pass) noexcept
: Singleton<StandardPaths>::Singleton{pass}
{
}
QString mp::StandardPaths::locate(StandardLocation type, const QString& fileName, LocateOptions options) const
{
return QStandardPaths::locate(type, fileName, options);
}
QStringList mp::StandardPaths::standardLocations(StandardLocation type) const
{
return QStandardPaths::standardLocations(type);
}
QString mp::StandardPaths::writableLocation(StandardLocation type) const
{
return QStandardPaths::writableLocation(type);
}
| 1,280
|
C++
|
.cpp
| 34
| 35.558824
| 110
| 0.785484
|
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,697
|
yaml_node_utils.cpp
|
canonical_multipass/src/utils/yaml_node_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/format.h>
#include <multipass/network_interface.h>
#include <multipass/yaml_node_utils.h>
#include <cassert>
namespace mp = multipass;
namespace
{
YAML::Node create_extra_interface_node(const std::string& extra_interface_name,
const std::string& extra_interface_mac_address)
{
YAML::Node extra_interface_data{};
extra_interface_data["match"]["macaddress"] = extra_interface_mac_address;
extra_interface_data["dhcp4"] = true;
extra_interface_data["dhcp-identifier"] = "mac";
// We make the default gateway associated with the first interface.
extra_interface_data["dhcp4-overrides"]["route-metric"] = 200;
// Make the interface optional, which means that networkd will not wait for the device to be configured.
extra_interface_data["optional"] = true;
return extra_interface_data;
};
YAML::Node create_default_interface_node(const std::string& default_interface_mac_address)
{
YAML::Node default_interface_data{};
default_interface_data["match"]["macaddress"] = default_interface_mac_address;
default_interface_data["dhcp4"] = true;
default_interface_data["dhcp-identifier"] = "mac";
return default_interface_data;
};
} // namespace
std::string mp::utils::emit_yaml(const YAML::Node& node)
{
YAML::Emitter emitter;
emitter.SetIndent(2);
emitter << node;
if (!emitter.good())
throw std::runtime_error{fmt::format("Failed to emit YAML: {}", emitter.GetLastError())};
emitter << YAML::Newline;
return emitter.c_str();
}
std::string mp::utils::emit_cloud_config(const YAML::Node& node)
{
return fmt::format("#cloud-config\n{}", emit_yaml(node));
}
YAML::Node mp::utils::make_cloud_init_meta_config(const std::string& name, const std::string& file_content)
{
YAML::Node meta_data = file_content.empty() ? YAML::Node{} : YAML::Load(file_content);
if (!file_content.empty())
{
const std::string old_hostname = meta_data["local-hostname"].as<std::string>();
std::string old_instance_id = meta_data["instance-id"].as<std::string>();
// The assumption here is that the instance_id is the hostname optionally appended _e sequence
assert(old_instance_id.size() >= old_hostname.size());
// replace the old host name with the new host name
meta_data["instance-id"] = old_instance_id.replace(0, old_hostname.size(), name);
}
else
{
meta_data["instance-id"] = name;
}
meta_data["local-hostname"] = name;
meta_data["cloud-name"] = "multipass";
return meta_data;
}
YAML::Node mp::utils::make_cloud_init_meta_config_with_id_tweak(const std::string& file_content,
const std::string& new_instance_id)
{
YAML::Node meta_data = YAML::Load(file_content);
if (new_instance_id.empty())
{
meta_data["instance-id"] = YAML::Node{meta_data["instance-id"].as<std::string>() + "_e"};
}
else
{
meta_data["instance-id"] = YAML::Node{new_instance_id};
}
return meta_data;
}
YAML::Node mp::utils::make_cloud_init_network_config(const std::string& default_mac_addr,
const std::vector<mp::NetworkInterface>& extra_interfaces,
const std::string& file_content)
{
YAML::Node network_data = file_content.empty() ? YAML::Node{} : YAML::Load(file_content);
network_data["version"] = "2";
network_data["ethernets"]["default"] = create_default_interface_node(default_mac_addr);
for (size_t i = 0; i < extra_interfaces.size(); ++i)
{
if (extra_interfaces[i].auto_mode)
{
const std::string name = "extra" + std::to_string(i);
network_data["ethernets"][name] = create_extra_interface_node(name, extra_interfaces[i].mac_address);
}
}
return network_data;
}
YAML::Node mp::utils::add_extra_interface_to_network_config(const std::string& default_mac_addr,
const NetworkInterface& extra_interface,
const std::string& network_config_file_content)
{
if (!extra_interface.auto_mode)
{
return network_config_file_content.empty() ? YAML::Node{} : YAML::Load(network_config_file_content);
}
if (network_config_file_content.empty())
{
YAML::Node network_data{};
network_data["version"] = "2";
network_data["ethernets"]["default"] = create_default_interface_node(default_mac_addr);
const std::string extra_interface_name = "extra0";
network_data["ethernets"][extra_interface_name] =
create_extra_interface_node(extra_interface_name, extra_interface.mac_address);
return network_data;
}
YAML::Node network_data = YAML::Load(network_config_file_content);
int i = 0;
while (true)
{
const std::string extra_interface_name = "extra" + std::to_string(i);
if (!network_data["ethernets"][extra_interface_name].IsDefined())
{
// append the new network interface
network_data["ethernets"][extra_interface_name] =
create_extra_interface_node(extra_interface_name, extra_interface.mac_address);
return network_data;
}
++i;
}
}
| 6,079
|
C++
|
.cpp
| 143
| 35.265734
| 113
| 0.642385
|
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,698
|
snap_utils.cpp
|
canonical_multipass/src/utils/snap_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/exceptions/snap_environment_exception.h>
#include <multipass/snap_utils.h>
#include <QFileInfo>
#include <QString>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace
{
const QString snap_name{"multipass"};
void verify_snap_name()
{
if (!mpu::in_multipass_snap())
throw mp::SnapEnvironmentException("SNAP_NAME", snap_name.toStdString());
}
QByteArray checked_snap_env_var(const char* var)
{
verify_snap_name();
auto ret = qgetenv(var); // Inside snap, this can be trusted.
if (ret.isEmpty())
throw mp::SnapEnvironmentException(var);
return ret;
}
QByteArray checked_snap_dir(const char* dir)
{
return QFileInfo(checked_snap_env_var(dir)).canonicalFilePath().toUtf8(); // To resolve any symlinks
}
} // namespace
bool mpu::in_multipass_snap()
{
return qgetenv("SNAP_NAME") == snap_name;
}
QByteArray mpu::snap_dir()
{
return checked_snap_dir("SNAP");
}
QByteArray mpu::snap_common_dir()
{
return checked_snap_dir("SNAP_COMMON");
}
QByteArray mpu::snap_real_home_dir()
{
return checked_snap_dir("SNAP_REAL_HOME");
}
QByteArray mpu::snap_user_common_dir()
{
return checked_snap_dir("SNAP_USER_COMMON");
}
| 1,842
|
C++
|
.cpp
| 63
| 26.825397
| 104
| 0.734844
|
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,699
|
timer.cpp
|
canonical_multipass/src/utils/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/timer.h>
#include <multipass/top_catch_all.h>
namespace mpu = multipass::utils;
mpu::Timer::Timer(std::chrono::milliseconds timeout, std::function<void()> callback)
: timeout(timeout), callback(callback), current_state(TimerState::Stopped)
{
}
mpu::Timer::~Timer()
{
multipass::top_catch_all("timer", [this]() { stop(); });
}
void mpu::Timer::start()
{
stop();
current_state = TimerState::Running;
t = std::thread(&Timer::main, this);
}
void mpu::Timer::main()
{
auto remaining_time = timeout;
std::unique_lock<std::mutex> lk(cv_m);
while (current_state != TimerState::Stopped)
{
auto start_time = std::chrono::system_clock::now();
if (current_state == TimerState::Running && !MP_TIMER_SYNC_FUNCS.wait_for(cv, lk, remaining_time, [this] {
return current_state != TimerState::Running;
}))
{
current_state = TimerState::Stopped;
callback();
}
else if (current_state == TimerState::Paused)
{
remaining_time = std::chrono::duration_cast<std::chrono::milliseconds>(
remaining_time - (std::chrono::system_clock::now() - start_time));
MP_TIMER_SYNC_FUNCS.wait(cv, lk, [this] { return current_state != TimerState::Paused; });
}
}
}
void mpu::Timer::pause()
{
{
std::lock_guard<std::mutex> lk(cv_m);
if (current_state != TimerState::Running)
return;
current_state = TimerState::Paused;
}
MP_TIMER_SYNC_FUNCS.notify_all(cv);
}
void mpu::Timer::resume()
{
{
std::lock_guard<std::mutex> lk(cv_m);
if (current_state != TimerState::Paused)
return;
current_state = TimerState::Running;
}
MP_TIMER_SYNC_FUNCS.notify_all(cv);
}
void mpu::Timer::stop()
{
{
std::lock_guard<std::mutex> lk(cv_m);
current_state = TimerState::Stopped;
}
MP_TIMER_SYNC_FUNCS.notify_all(cv);
if (t.joinable())
t.join();
}
mpu::TimerSyncFuncs::TimerSyncFuncs(const Singleton<TimerSyncFuncs>::PrivatePass& pass) noexcept
: Singleton<TimerSyncFuncs>::Singleton{pass}
{
}
void mpu::TimerSyncFuncs::notify_all(std::condition_variable& cv) const
{
cv.notify_all();
}
void mpu::TimerSyncFuncs::wait(std::condition_variable& cv, std::unique_lock<std::mutex>& lock,
std::function<bool()> predicate) const
{
cv.wait(lock, predicate);
}
bool mpu::TimerSyncFuncs::wait_for(std::condition_variable& cv, std::unique_lock<std::mutex>& lock,
const std::chrono::duration<int, std::milli>& rel_time,
std::function<bool()> predicate) const
{
return cv.wait_for(lock, rel_time, predicate);
}
| 3,436
|
C++
|
.cpp
| 104
| 27.509615
| 114
| 0.640639
|
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,700
|
json_utils.cpp
|
canonical_multipass/src/utils/json_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/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/json_utils.h>
#include <multipass/utils.h>
#include <multipass/vm_specs.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QSaveFile>
#include <stdexcept>
namespace mp = multipass;
namespace mpu = multipass::utils;
mp::JsonUtils::JsonUtils(const Singleton<JsonUtils>::PrivatePass& pass) noexcept : Singleton<JsonUtils>{pass}
{
}
void mp::JsonUtils::write_json(const QJsonObject& root, QString file_name) const
{
auto dir = QFileInfo(file_name).absoluteDir();
if (!MP_FILEOPS.mkpath(dir, "."))
throw std::runtime_error(fmt::format("Could not create path '{}'", dir.absolutePath()));
QSaveFile db_file{file_name};
if (!MP_FILEOPS.open(db_file, QIODevice::WriteOnly))
throw std::runtime_error{fmt::format("Could not open transactional file for writing; filename: {}", file_name)};
if (MP_FILEOPS.write(db_file, QJsonDocument{root}.toJson()) == -1)
throw std::runtime_error{fmt::format("Could not write json to transactional file; filename: {}; error: {}",
file_name,
db_file.errorString())};
if (!MP_FILEOPS.commit(db_file))
throw std::runtime_error{fmt::format("Could not commit transactional file; filename: {}", file_name)};
}
std::string mp::JsonUtils::json_to_string(const QJsonObject& root) const
{
// The function name toJson() is shockingly wrong, for it converts an actual JsonDocument to a QByteArray.
return QJsonDocument(root).toJson().toStdString();
}
QJsonValue mp::JsonUtils::update_cloud_init_instance_id(const QJsonValue& cloud_init_instance_id_value,
const std::string& src_vm_name,
const std::string& dest_vm_name) const
{
std::string cloud_init_instance_id_str = cloud_init_instance_id_value.toString().toStdString();
assert(cloud_init_instance_id_str.size() >= src_vm_name.size());
return QJsonValue{QString::fromStdString(cloud_init_instance_id_str.replace(0, src_vm_name.size(), dest_vm_name))};
}
QJsonValue mp::JsonUtils::update_unique_identifiers_of_metadata(const QJsonValue& metadata_value,
const multipass::VMSpecs& src_specs,
const multipass::VMSpecs& dest_specs,
const std::string& src_vm_name,
const std::string& dest_vm_name) const
{
assert(src_specs.extra_interfaces.size() == dest_specs.extra_interfaces.size());
QJsonObject result_metadata_object = metadata_value.toObject();
QJsonValueRef arguments = result_metadata_object["arguments"];
QJsonArray json_array = arguments.toArray();
for (QJsonValueRef item : json_array)
{
QString str = item.toString();
str.replace(src_specs.default_mac_address.c_str(), dest_specs.default_mac_address.c_str());
for (size_t i = 0; i < src_specs.extra_interfaces.size(); ++i)
{
const std::string& src_extra_interface_mac_addr = src_specs.extra_interfaces[i].mac_address;
if (!src_extra_interface_mac_addr.empty())
{
const std::string& dest_extra_interface_mac_addr = dest_specs.extra_interfaces[i].mac_address;
str.replace(src_extra_interface_mac_addr.c_str(), dest_extra_interface_mac_addr.c_str());
}
}
// string replacement is "instances/<src_name>"->"instances/<dest_name>" instead of
// "<src_name>"->"<dest_name>", because the second one might match other substrings of the metadata.
str.replace("instances/" + QString{src_vm_name.c_str()}, "instances/" + QString{dest_vm_name.c_str()});
item = str;
}
arguments = json_array;
return QJsonValue{result_metadata_object};
}
QJsonArray mp::JsonUtils::extra_interfaces_to_json_array(
const std::vector<mp::NetworkInterface>& extra_interfaces) const
{
QJsonArray json;
for (const auto& interface : extra_interfaces)
{
QJsonObject entry;
entry.insert("id", QString::fromStdString(interface.id));
entry.insert("mac_address", QString::fromStdString(interface.mac_address));
entry.insert("auto_mode", interface.auto_mode);
json.append(entry);
}
return json;
}
std::optional<std::vector<mp::NetworkInterface>> mp::JsonUtils::read_extra_interfaces(const QJsonObject& record) const
{
if (record.contains("extra_interfaces"))
{
std::vector<mp::NetworkInterface> extra_interfaces;
for (QJsonValueRef entry : record["extra_interfaces"].toArray())
{
auto id = entry.toObject()["id"].toString().toStdString();
auto mac_address = entry.toObject()["mac_address"].toString().toStdString();
if (!mpu::valid_mac_address(mac_address))
{
throw std::runtime_error(fmt::format("Invalid MAC address {}", mac_address));
}
auto auto_mode = entry.toObject()["auto_mode"].toBool();
extra_interfaces.push_back(mp::NetworkInterface{id, mac_address, auto_mode});
}
return extra_interfaces;
}
return std::nullopt;
}
| 6,154
|
C++
|
.cpp
| 125
| 40.376
| 120
| 0.642358
|
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,701
|
file_ops.cpp
|
canonical_multipass/src/utils/file_ops.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/file_ops.h>
#include <multipass/posix.h>
#include <fcntl.h>
namespace mp = multipass;
namespace fs = mp::fs;
mp::NamedFd::NamedFd(const fs::path& path, int fd) : path{path}, fd{fd}
{
}
mp::NamedFd::~NamedFd()
{
if (fd != -1)
::close(fd);
}
mp::FileOps::FileOps(const Singleton<FileOps>::PrivatePass& pass) noexcept : Singleton<FileOps>::Singleton{pass}
{
}
bool mp::FileOps::exists(const QDir& dir) const
{
return dir.exists();
}
bool mp::FileOps::isReadable(const QDir& dir) const
{
return dir.isReadable();
}
QFileInfoList multipass::FileOps::entryInfoList(const QDir& dir,
const QStringList& nameFilters,
QDir::Filters filters,
QDir::SortFlags sort) const
{
return dir.entryInfoList(nameFilters, filters, sort);
}
bool mp::FileOps::mkpath(const QDir& dir, const QString& dirName) const
{
return dir.mkpath(dirName);
}
bool mp::FileOps::rmdir(QDir& dir, const QString& dirName) const
{
return dir.rmdir(dirName);
}
bool mp::FileOps::exists(const QFile& file) const
{
return file.exists();
}
bool mp::FileOps::isDir(const QFileInfo& file) const
{
return file.isDir();
}
bool mp::FileOps::exists(const QFileInfo& file) const
{
return file.exists();
}
bool mp::FileOps::isReadable(const QFileInfo& file) const
{
return file.isReadable();
}
uint mp::FileOps::ownerId(const QFileInfo& file) const
{
return file.ownerId();
}
uint mp::FileOps::groupId(const QFileInfo& file) const
{
return file.groupId();
}
bool mp::FileOps::is_open(const QFile& file) const
{
return file.isOpen();
}
bool mp::FileOps::open(QFileDevice& file, QIODevice::OpenMode mode) const
{
return file.open(mode);
}
QFileDevice::Permissions mp::FileOps::permissions(const QFile& file) const
{
return file.permissions();
}
qint64 mp::FileOps::read(QFile& file, char* data, qint64 maxSize) const
{
return file.read(data, maxSize);
}
QByteArray mp::FileOps::read_all(QFile& file) const
{
return file.readAll();
}
QString mp::FileOps::read_line(QTextStream& text_stream) const
{
return text_stream.readLine();
}
bool mp::FileOps::remove(QFile& file) const
{
return file.remove();
}
bool mp::FileOps::rename(QFile& file, const QString& newName) const
{
return file.rename(newName);
}
bool mp::FileOps::resize(QFile& file, qint64 sz) const
{
return file.resize(sz);
}
bool mp::FileOps::seek(QFile& file, qint64 pos) const
{
return file.seek(pos);
}
bool mp::FileOps::setPermissions(QFile& file, QFileDevice::Permissions permissions) const
{
return file.setPermissions(permissions);
}
qint64 mp::FileOps::size(QFile& file) const
{
return file.size();
}
qint64 mp::FileOps::write(QFile& file, const char* data, qint64 maxSize) const
{
return file.write(data, maxSize);
}
qint64 mp::FileOps::write(QFileDevice& file, const QByteArray& data) const
{
return file.write(data);
}
bool mp::FileOps::flush(QFile& file) const
{
return file.flush();
}
bool mp::FileOps::commit(QSaveFile& file) const
{
return file.commit();
}
std::unique_ptr<mp::NamedFd> mp::FileOps::open_fd(const fs::path& path, int flags, int perms) const
{
const auto fd = ::open(path.string().c_str(), flags | O_BINARY, perms);
return std::make_unique<mp::NamedFd>(path, fd);
}
int mp::FileOps::read(int fd, void* buf, size_t nbytes) const
{
return ::read(fd, buf, nbytes);
}
int mp::FileOps::write(int fd, const void* buf, size_t nbytes) const
{
return ::write(fd, buf, nbytes);
}
off_t mp::FileOps::lseek(int fd, off_t offset, int whence) const
{
return ::lseek(fd, offset, whence);
}
void mp::FileOps::open(std::fstream& stream, const char* filename, std::ios_base::openmode mode) const
{
stream.open(filename, mode);
}
bool mp::FileOps::is_open(const std::ifstream& file) const
{
return file.is_open();
}
std::ifstream& mp::FileOps::read(std::ifstream& file, char* buffer, std::streamsize size) const
{
file.read(buffer, size);
return file;
}
std::unique_ptr<std::ostream> mp::FileOps::open_write(const fs::path& path, std::ios_base::openmode mode) const
{
return std::make_unique<std::ofstream>(path, mode);
}
std::unique_ptr<std::istream> mp::FileOps::open_read(const fs::path& path, std::ios_base::openmode mode) const
{
return std::make_unique<std::ifstream>(path, mode);
}
void mp::FileOps::copy(const fs::path& src, const fs::path& dist, fs::copy_options copy_options) const
{
fs::copy(src, dist, copy_options);
}
bool mp::FileOps::exists(const fs::path& path, std::error_code& err) const
{
return fs::exists(path, err);
}
bool mp::FileOps::is_directory(const fs::path& path, std::error_code& err) const
{
return fs::is_directory(path, err);
}
bool mp::FileOps::create_directory(const fs::path& path, std::error_code& err) const
{
return fs::create_directory(path, err);
}
bool mp::FileOps::create_directories(const fs::path& path, std::error_code& err) const
{
return fs::create_directories(path, err);
}
bool mp::FileOps::remove(const fs::path& path, std::error_code& err) const
{
return fs::remove(path, err);
}
void mp::FileOps::create_symlink(const fs::path& to, const fs::path& path, std::error_code& err) const
{
fs::create_symlink(to, path, err);
}
fs::path mp::FileOps::read_symlink(const fs::path& path, std::error_code& err) const
{
return fs::read_symlink(path, err);
}
void mp::FileOps::permissions(const fs::path& path, fs::perms perms, std::error_code& err) const
{
fs::permissions(path, perms, err);
}
fs::file_status mp::FileOps::status(const fs::path& path, std::error_code& err) const
{
return fs::status(path, err);
}
fs::file_status mp::FileOps::symlink_status(const fs::path& path, std::error_code& err) const
{
return fs::symlink_status(path, err);
}
std::unique_ptr<mp::RecursiveDirIterator> mp::FileOps::recursive_dir_iterator(const fs::path& path,
std::error_code& err) const
{
return std::make_unique<mp::RecursiveDirIterator>(path, err);
}
std::unique_ptr<mp::DirIterator> mp::FileOps::dir_iterator(const fs::path& path, std::error_code& err) const
{
return std::make_unique<mp::DirIterator>(path, err);
}
| 7,006
|
C++
|
.cpp
| 234
| 26.769231
| 112
| 0.697633
|
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,702
|
memory_size.cpp
|
canonical_multipass/src/utils/memory_size.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/exceptions/invalid_memory_size_exception.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <multipass/utils.h>
#include <cmath>
#include <QRegularExpression>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace
{
constexpr auto kibi = 1024LL;
constexpr auto mebi = kibi * kibi;
constexpr auto gibi = mebi * kibi;
} // namespace
long long mp::in_bytes(const std::string& mem_value)
{
QRegularExpression regex{
QRegularExpression::anchoredPattern("\\s*(\\d+)(?:\\.(\\d+)(?=[KMG]))?(?:([KMG])(?:i?B)?|B)?\\s*"),
QRegularExpression::CaseInsensitiveOption};
const auto matcher = regex.match(QString::fromStdString(mem_value)); // TODO accept decimals
if (matcher.hasMatch())
{
auto val = matcher.captured(1).toLongLong(); // value is in the second capture (1st one is the whole match)
auto mantissa = 0LL;
const auto unit = matcher.captured(3); // unit in the fourth capture (idem)
if (!matcher.captured(2).isEmpty())
{
assert(!unit.isEmpty() && "Shouldn't be here (invalid decimal amount and unit)");
mantissa = matcher.captured(2).toLongLong(); // mantissa is in the third capture
}
if (!unit.isEmpty())
{
switch (unit.at(0).toLower().toLatin1())
{
case 'g':
val *= gibi;
mantissa *= gibi;
break;
case 'm':
val *= mebi;
mantissa *= mebi;
break;
case 'k':
val *= kibi;
mantissa *= kibi;
break;
default:
assert(false && "Shouldn't be here (invalid unit)");
}
}
return val + (long long)(mantissa / pow(10, matcher.captured(2).size()));
}
throw mp::InvalidMemorySizeException{mem_value};
}
mp::MemorySize::MemorySize() noexcept : bytes{0LL}
{
}
mp::MemorySize::MemorySize(const std::string& val) : bytes{mp::in_bytes(val)}
{
}
mp::MemorySize::MemorySize(long long bytes) noexcept : bytes{bytes}
{
}
mp::MemorySize mp::MemorySize::from_bytes(long long value) noexcept
{
return MemorySize{value};
}
long long mp::MemorySize::in_bytes() const noexcept
{
return bytes;
}
long long mp::MemorySize::in_kilobytes() const noexcept
{
return bytes / kibi; // integer division to floor
}
long long mp::MemorySize::in_megabytes() const noexcept
{
return bytes / mebi; // integer division to floor
}
long long mp::MemorySize::in_gigabytes() const noexcept
{
return bytes / gibi; // integer division to floor
}
bool mp::operator==(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes == b.bytes;
}
bool mp::operator!=(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes != b.bytes;
}
bool mp::operator<(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes < b.bytes;
}
bool mp::operator>(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes > b.bytes;
}
bool mp::operator<=(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes <= b.bytes;
}
bool mp::operator>=(const MemorySize& a, const MemorySize& b) noexcept
{
return a.bytes >= b.bytes;
}
std::string mp::MemorySize::human_readable(unsigned int precision, bool trim_zeros) const
{
const auto giga = std::pair{gibi, "GiB"};
const auto mega = std::pair{mebi, "MiB"};
const auto kilo = std::pair{kibi, "KiB"};
for (auto [unit, suffix] : {giga, mega, kilo})
if (auto quotient = bytes / static_cast<float>(unit); quotient >= 1)
{
auto result = fmt::format("{:.{}f}", quotient, precision);
if (!trim_zeros)
return result + suffix;
result = mpu::trim_end(result, [](const char c) { return c == '0'; });
result = mpu::trim_end(result, [](const char c) { return c == '.'; });
return result + suffix;
}
return fmt::format("{}B", bytes);
}
| 4,711
|
C++
|
.cpp
| 140
| 28.392857
| 115
| 0.641127
|
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,703
|
poco_zip_utils.cpp
|
canonical_multipass/src/utils/poco_zip_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/poco_zip_utils.h>
namespace mp = multipass;
mp::PocoZipUtils::PocoZipUtils(const Singleton<PocoZipUtils>::PrivatePass& pass) noexcept
: Singleton<PocoZipUtils>::Singleton{pass}
{
}
Poco::Zip::ZipArchive mp::PocoZipUtils::zip_archive_for(std::ifstream& zip_stream) const
{
return Poco::Zip::ZipArchive{zip_stream};
}
| 976
|
C++
|
.cpp
| 26
| 35.5
| 89
| 0.761099
|
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,704
|
vm_mount.cpp
|
canonical_multipass/src/utils/vm_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 <multipass/vm_mount.h>
#include <QJsonArray>
namespace mp = multipass;
namespace
{
mp::VMMount parse_json(const QJsonObject& json)
{
mp::id_mappings uid_mappings;
mp::id_mappings gid_mappings;
auto source_path = json["source_path"].toString().toStdString();
for (const QJsonValueRef uid_entry : json["uid_mappings"].toArray())
{
uid_mappings.push_back(
{uid_entry.toObject()["host_uid"].toInt(), uid_entry.toObject()["instance_uid"].toInt()});
}
for (const QJsonValueRef gid_entry : json["gid_mappings"].toArray())
{
gid_mappings.push_back(
{gid_entry.toObject()["host_gid"].toInt(), gid_entry.toObject()["instance_gid"].toInt()});
}
mp::unique_id_mappings(uid_mappings);
mp::unique_id_mappings(gid_mappings);
auto mount_type = mp::VMMount::MountType(json["mount_type"].toInt());
return mp::VMMount{std::move(source_path), std::move(gid_mappings), std::move(uid_mappings), mount_type};
}
auto print_mappings(const std::unordered_map<int, std::unordered_set<int>>& dup_id_map,
const std::unordered_map<int, std::unordered_set<int>>& dup_rev_id_map)
{
std::string retval;
for (const auto& pair : dup_id_map)
{
retval += fmt::format("{}: [", pair.first);
for (const auto& mapping : pair.second)
retval += fmt::format("{}:{}, ", pair.first, mapping);
retval = retval.substr(0, retval.size() - 2);
retval += "]; ";
}
for (const auto& pair : dup_rev_id_map)
{
retval += fmt::format("{}: [", pair.first);
for (const auto& mapping : pair.second)
retval += fmt::format("{}:{}, ", mapping, pair.first);
retval = retval.substr(0, retval.size() - 2);
retval += "]; ";
}
return retval.substr(0, retval.size() - 2);
}
} // namespace
mp::VMMount::VMMount(const std::string& sourcePath,
id_mappings gidMappings,
id_mappings uidMappings,
MountType mountType)
: source_path(sourcePath),
gid_mappings(std::move(gidMappings)),
uid_mappings(std::move(uidMappings)),
mount_type(mountType)
{
fmt::memory_buffer errors;
if (const auto& [dup_uid_map, dup_rev_uid_map] = mp::unique_id_mappings(uid_mappings);
!dup_uid_map.empty() || !dup_rev_uid_map.empty())
{
fmt::format_to(std::back_inserter(errors),
fmt::format("\nuids: {}", print_mappings(dup_uid_map, dup_rev_uid_map)));
}
if (const auto& [dup_gid_map, dup_rev_gid_map] = mp::unique_id_mappings(gid_mappings);
!dup_gid_map.empty() || !dup_rev_gid_map.empty())
{
fmt::format_to(std::back_inserter(errors),
fmt::format("\ngids: {}", print_mappings(dup_gid_map, dup_rev_gid_map)));
}
if (errors.size())
throw std::runtime_error(
fmt::format("Mount cannot apply mapping with duplicate ids:{}", fmt::to_string(errors)));
}
mp::VMMount::VMMount(const QJsonObject& json) : VMMount{parse_json(json)} // delegate on copy ctor
{
}
QJsonObject mp::VMMount::serialize() const
{
QJsonObject ret;
ret.insert("source_path", QString::fromStdString(source_path));
QJsonArray uid_mappings_json;
for (const auto& map : uid_mappings)
{
QJsonObject map_entry;
map_entry.insert("host_uid", map.first);
map_entry.insert("instance_uid", map.second);
uid_mappings_json.append(map_entry);
}
ret.insert("uid_mappings", uid_mappings_json);
QJsonArray gid_mappings_json;
for (const auto& map : gid_mappings)
{
QJsonObject map_entry;
map_entry.insert("host_gid", map.first);
map_entry.insert("instance_gid", map.second);
gid_mappings_json.append(map_entry);
}
ret.insert("gid_mappings", gid_mappings_json);
ret.insert("mount_type", static_cast<int>(mount_type));
return ret;
}
| 4,611
|
C++
|
.cpp
| 118
| 32.898305
| 109
| 0.636425
|
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,705
|
sftp_server.cpp
|
canonical_multipass/src/sshfs_mount/sftp_server.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 "sftp_server.h"
#include <multipass/cli/client_platform.h>
#include <multipass/exceptions/exitless_sshprocess_exceptions.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/ssh/throw_on_error.h>
#include <multipass/utils.h>
#include <QDir>
#include <QFile>
#include <fcntl.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "sftp server";
using SftpHandleUPtr = std::unique_ptr<ssh_string_struct, void (*)(ssh_string)>;
using namespace std::literals::chrono_literals;
enum Permissions
{
read_user = 0400,
write_user = 0200,
exec_user = 0100,
read_group = 040,
write_group = 020,
exec_group = 010,
read_other = 04,
write_other = 02,
exec_other = 01
};
auto make_sftp_session(ssh_session session, ssh_channel channel)
{
mp::SftpServer::SftpSessionUptr sftp_server_session{sftp_server_new(session, channel), sftp_free};
mp::SSH::throw_on_error(sftp_server_session, session, "[sftp] server init failed", sftp_server_init);
return sftp_server_session;
}
int reply_ok(sftp_client_message msg)
{
return sftp_reply_status(msg, SSH_FX_OK, nullptr);
}
int reply_failure(sftp_client_message msg)
{
return sftp_reply_status(msg, SSH_FX_FAILURE, nullptr);
}
int reply_perm_denied(sftp_client_message msg)
{
return sftp_reply_status(msg, SSH_FX_PERMISSION_DENIED, "permission denied");
}
int reply_bad_handle(sftp_client_message msg, const char* type)
{
return sftp_reply_status(msg, SSH_FX_BAD_MESSAGE, fmt::format("{}: invalid handle", type).c_str());
}
int reply_unsupported(sftp_client_message msg)
{
return sftp_reply_status(msg, SSH_FX_OP_UNSUPPORTED, "Unsupported message");
}
fmt::memory_buffer& operator<<(fmt::memory_buffer& buf, const char* v)
{
fmt::format_to(std::back_inserter(buf), v);
return buf;
}
auto longname_from(const QFileInfo& file_info, const std::string& filename)
{
fmt::memory_buffer out;
auto mode = file_info.permissions();
if (file_info.isSymLink())
out << "l";
else if (file_info.isDir())
out << "d";
else
out << "-";
/* user */
if (mode & QFileDevice::ReadOwner)
out << "r";
else
out << "-";
if (mode & QFileDevice::WriteOwner)
out << "w";
else
out << "-";
if (mode & QFileDevice::ExeOwner)
out << "x";
else
out << "-";
/*group*/
if (mode & QFileDevice::ReadGroup)
out << "r";
else
out << "-";
if (mode & QFileDevice::WriteGroup)
out << "w";
else
out << "-";
if (mode & QFileDevice::ExeGroup)
out << "x";
else
out << "-";
/* other */
if (mode & QFileDevice::ReadOther)
out << "r";
else
out << "-";
if (mode & QFileDevice::WriteOther)
out << "w";
else
out << "-";
if (mode & QFileDevice::ExeOther)
out << "x";
else
out << "-";
fmt::format_to(std::back_inserter(out), " 1 {} {} {}", file_info.ownerId(), file_info.groupId(), file_info.size());
const auto timestamp = file_info.lastModified().toString("MMM d hh:mm:ss yyyy").toStdString();
fmt::format_to(std::back_inserter(out), " {} {}", timestamp, filename);
return out;
}
auto to_unix_permissions(QFile::Permissions perms)
{
int out = 0;
if (perms & QFileDevice::ReadOwner)
out |= Permissions::read_user;
if (perms & QFileDevice::WriteOwner)
out |= Permissions::write_user;
if (perms & QFileDevice::ExeOwner)
out |= Permissions::exec_user;
if (perms & QFileDevice::ReadGroup)
out |= Permissions::read_group;
if (perms & QFileDevice::WriteGroup)
out |= Permissions::write_group;
if (perms & QFileDevice::ExeGroup)
out |= Permissions::exec_group;
if (perms & QFileDevice::ReadOther)
out |= Permissions::read_other;
if (perms & QFileDevice::WriteOther)
out |= Permissions::write_other;
if (perms & QFileDevice::ExeOther)
out |= Permissions::exec_other;
return out;
}
auto validate_path(const std::string& source_path, const std::string& current_path)
{
if (source_path.empty())
return false;
return current_path.compare(0, source_path.length(), source_path) == 0;
}
void check_sshfs_status(mp::SSHSession& session, mp::SSHProcess& sshfs_process)
{
if (sshfs_process.exit_recognized(250ms))
{
// This `if` is artificial and should not really be here. However there is a complex arrangement of Sftp and
// SshfsMount tests depending on this.
if (sshfs_process.exit_code(250ms) != 0) // TODO remove
throw std::runtime_error(sshfs_process.read_std_error());
}
}
auto create_sshfs_process(mp::SSHSession& session, const std::string& sshfs_exec_line, const std::string& source,
const std::string& target)
{
auto sshfs_process = session.exec(fmt::format("sudo {} :\"{}\" \"{}\"", sshfs_exec_line, source, target));
check_sshfs_status(session, sshfs_process);
return std::make_unique<mp::SSHProcess>(std::move(sshfs_process));
}
int mapped_id_for(const mp::id_mappings& id_maps, const int id, const int default_id)
{
if (id == mp::no_id_info_available)
return default_id;
auto found = std::find_if(id_maps.cbegin(), id_maps.cend(), [id](std::pair<int, int> p) { return id == p.first; });
return found == id_maps.cend() ? -1 : (found->second == mp::default_id ? default_id : found->second);
}
int reverse_id_for(const mp::id_mappings& id_maps, const int id, const int default_id)
{
auto found = std::find_if(id_maps.cbegin(), id_maps.cend(), [id](std::pair<int, int> p) { return id == p.second; });
auto default_found = std::find_if(id_maps.cbegin(), id_maps.cend(), [default_id](std::pair<int, int> p) {
return default_id == p.second;
});
return found == id_maps.cend() ? (default_found == id_maps.cend() ? default_id : default_found->first)
: found->first;
}
} // namespace
mp::SftpServer::SftpServer(SSHSession&& session, const std::string& source, const std::string& target,
const id_mappings& gid_mappings, const id_mappings& uid_mappings, int default_uid,
int default_gid, const std::string& sshfs_exec_line)
: ssh_session{std::move(session)},
sshfs_process{create_sshfs_process(ssh_session, sshfs_exec_line, mp::utils::escape_char(source, '"'),
mp::utils::escape_char(target, '"'))},
sftp_server_session{make_sftp_session(ssh_session, sshfs_process->release_channel())},
source_path{source},
target_path{target},
gid_mappings{gid_mappings},
uid_mappings{uid_mappings},
default_uid{default_uid},
default_gid{default_gid},
sshfs_exec_line{sshfs_exec_line}
{
}
mp::SftpServer::~SftpServer()
{
stop_invoked = true;
}
sftp_attributes_struct mp::SftpServer::attr_from(const QFileInfo& file_info)
{
sftp_attributes_struct attr{};
attr.size = file_info.size();
attr.uid = mapped_uid_for(file_info.ownerId());
attr.gid = mapped_gid_for(file_info.groupId());
attr.permissions = to_unix_permissions(file_info.permissions());
attr.atime = file_info.lastRead().toUTC().toMSecsSinceEpoch() / 1000;
attr.mtime = file_info.lastModified().toUTC().toMSecsSinceEpoch() / 1000;
attr.flags =
SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_UIDGID | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME;
if (file_info.isSymLink())
attr.permissions |= SSH_S_IFLNK | 0777;
else if (file_info.isDir())
attr.permissions |= SSH_S_IFDIR;
else if (file_info.isFile())
attr.permissions |= SSH_S_IFREG;
return attr;
}
inline int mp::SftpServer::mapped_uid_for(const int uid)
{
return mapped_id_for(uid_mappings, uid, default_uid);
}
inline int mp::SftpServer::mapped_gid_for(const int gid)
{
return mapped_id_for(gid_mappings, gid, default_gid);
}
inline int mp::SftpServer::reverse_uid_for(const int uid, const int default_id)
{
return reverse_id_for(uid_mappings, uid, default_id);
}
inline int mp::SftpServer::reverse_gid_for(const int gid, const int default_id)
{
return reverse_id_for(gid_mappings, gid, default_id);
}
inline bool mp::SftpServer::has_uid_mapping_for(const int uid)
{
return std::any_of(uid_mappings.begin(), uid_mappings.end(), [uid](std::pair<int, int> p) {
return uid == p.first;
});
}
inline bool mp::SftpServer::has_gid_mapping_for(const int gid)
{
return std::any_of(gid_mappings.begin(), gid_mappings.end(), [gid](std::pair<int, int> p) {
return gid == p.first;
});
}
inline bool mp::SftpServer::has_reverse_uid_mapping_for(const int uid)
{
return std::any_of(uid_mappings.cbegin(), uid_mappings.cend(), [uid](std::pair<int, int> p) {
return uid == p.second;
});
}
inline bool mp::SftpServer::has_reverse_gid_mapping_for(const int gid)
{
return std::any_of(gid_mappings.cbegin(), gid_mappings.cend(), [gid](std::pair<int, int> p) {
return gid == p.second;
});
}
bool mp::SftpServer::has_id_mappings_for(const QFileInfo& file_info)
{
return has_uid_mapping_for(MP_FILEOPS.ownerId(file_info)) && has_gid_mapping_for(MP_FILEOPS.groupId(file_info));
}
void mp::SftpServer::process_message(sftp_client_message msg)
{
int ret = 0;
const auto type = sftp_client_message_get_type(msg);
switch (type)
{
case SFTP_REALPATH:
ret = handle_realpath(msg);
break;
case SFTP_OPENDIR:
ret = handle_opendir(msg);
break;
case SFTP_MKDIR:
ret = handle_mkdir(msg);
break;
case SFTP_RMDIR:
ret = handle_rmdir(msg);
break;
case SFTP_LSTAT:
case SFTP_STAT:
ret = handle_stat(msg, type == SFTP_STAT);
break;
case SFTP_FSTAT:
ret = handle_fstat(msg);
break;
case SFTP_READDIR:
ret = handle_readdir(msg);
break;
case SFTP_CLOSE:
ret = handle_close(msg);
break;
case SFTP_OPEN:
ret = handle_open(msg);
break;
case SFTP_READ:
ret = handle_read(msg);
break;
case SFTP_WRITE:
ret = handle_write(msg);
break;
case SFTP_RENAME:
ret = handle_rename(msg);
break;
case SFTP_REMOVE:
ret = handle_remove(msg);
break;
case SFTP_SETSTAT:
case SFTP_FSETSTAT:
ret = handle_setstat(msg);
break;
case SFTP_READLINK:
ret = handle_readlink(msg);
break;
case SFTP_SYMLINK:
ret = handle_symlink(msg);
break;
case SFTP_EXTENDED:
ret = handle_extended(msg);
break;
default:
mpl::log(mpl::Level::trace, category, fmt::format("Unknown message: {}", static_cast<int>(type)));
ret = reply_unsupported(msg);
}
if (ret != 0)
mpl::log(mpl::Level::error, category, fmt::format("error occurred when replying to client: {}", ret));
}
void mp::SftpServer::run()
{
using MsgUPtr = std::unique_ptr<sftp_client_message_struct, decltype(sftp_client_message_free)*>;
while (true)
{
MsgUPtr client_msg{sftp_get_client_message(sftp_server_session.get()), sftp_client_message_free};
auto msg = client_msg.get();
if (msg == nullptr)
{
if (stop_invoked)
break;
int status{0};
try
{
status = sshfs_process->exit_code(250ms);
}
catch (const mp::ExitlessSSHProcessException&) // should we limit this to SSHProcessExitError?
{
status = 1;
}
if (status != 0)
{
mpl::log(mpl::Level::error, category,
"sshfs in the instance appears to have exited unexpectedly. Trying to recover.");
std::string mount_path = [this] {
auto proc = ssh_session.exec(fmt::format("findmnt --source :{} -o TARGET -n", source_path));
return proc.read_std_output();
}();
if (!mount_path.empty())
{
ssh_session.exec(fmt::format("sudo umount {}", mount_path));
}
sshfs_process =
create_sshfs_process(ssh_session, sshfs_exec_line, mp::utils::escape_char(source_path, '"'),
mp::utils::escape_char(target_path, '"'));
sftp_server_session = make_sftp_session(ssh_session, sshfs_process->release_channel());
continue;
}
else
{
break;
}
}
process_message(msg);
}
}
void mp::SftpServer::stop()
{
stop_invoked = true;
ssh_session.force_shutdown();
}
int mp::SftpServer::handle_close(sftp_client_message msg)
{
const auto id = sftp_handle(sftp_server_session.get(), msg->handle);
if (!open_file_handles.erase(id) && !open_dir_handles.erase(id))
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "close");
}
sftp_handle_remove(sftp_server_session.get(), id);
return reply_ok(msg);
}
int mp::SftpServer::handle_fstat(sftp_client_message msg)
{
const auto handle = get_handle<NamedFd>(msg);
if (handle == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "fstat");
}
const auto& [path, _] = *handle;
QFileInfo file_info(path.string().c_str());
if (file_info.isSymLink())
file_info = QFileInfo(file_info.symLinkTarget());
auto attr = attr_from(file_info);
return sftp_reply_attr(msg, &attr);
}
int mp::SftpServer::handle_mkdir(sftp_client_message msg)
{
const auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QDir dir(filename);
QFileInfo current_dir(filename);
QFileInfo parent_dir(current_dir.path());
if (!has_id_mappings_for(parent_dir))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot create path \'{}\' with permissions \'{}:{}\': permission denied",
__FUNCTION__,
parent_dir.ownerId(),
parent_dir.groupId(),
filename));
return reply_perm_denied(msg);
}
if (!dir.mkdir(filename))
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: mkdir failed for '{}'", __FUNCTION__, filename));
return reply_failure(msg);
}
std::error_code err;
MP_FILEOPS.permissions(filename, static_cast<fs::perms>(msg->attr->permissions), err);
if (err)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: set permissions failed for '{}': {}", __FUNCTION__, filename, err.message()));
return reply_failure(msg);
}
int rev_uid = reverse_uid_for(parent_dir.ownerId(), parent_dir.ownerId());
int rev_gid = reverse_gid_for(parent_dir.groupId(), parent_dir.groupId());
if (MP_PLATFORM.chown(filename, rev_uid, rev_gid) < 0)
{
mpl::log(mpl::Level::trace, category,
fmt::format("failed to chown '{}' to owner:{} and group:{}", filename, rev_uid, rev_gid));
return reply_failure(msg);
}
return reply_ok(msg);
}
int mp::SftpServer::handle_rmdir(sftp_client_message msg)
{
const auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QFileInfo current_dir(filename);
if (MP_FILEOPS.exists(current_dir) && !has_id_mappings_for(current_dir))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
std::error_code err;
if (!MP_FILEOPS.remove(filename, err) && !err)
err = std::make_error_code(std::errc::no_such_file_or_directory);
if (err)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: rmdir failed for '{}': {}", __FUNCTION__, filename, err.message()));
return reply_failure(msg);
}
return reply_ok(msg);
}
int mp::SftpServer::handle_open(sftp_client_message msg)
{
const auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
std::error_code err;
const auto status = MP_FILEOPS.symlink_status(filename, err);
if (err && status.type() != fs::file_type::not_found)
{
mpl::log(mpl::Level::trace, category, fmt::format("Cannot get status of '{}': {}", filename, err.message()));
return reply_perm_denied(msg);
}
const auto exists = fs::is_symlink(status) || fs::is_regular_file(status);
QFileInfo file_info(filename);
QFileInfo current_dir(file_info.path());
if ((exists && !has_id_mappings_for(file_info)) || (!exists && !has_id_mappings_for(current_dir)))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
int mode = 0;
const auto flags = sftp_client_message_get_flags(msg);
if (flags & SSH_FXF_READ)
mode |= O_RDONLY;
if (flags & SSH_FXF_WRITE)
mode |= O_WRONLY;
if ((flags & SSH_FXF_READ) && (flags & SSH_FXF_WRITE))
{
mode &= ~O_RDONLY;
mode &= ~O_WRONLY;
mode |= O_RDWR;
}
if (flags & SSH_FXF_APPEND)
mode |= O_APPEND;
if (flags & SSH_FXF_TRUNC)
mode |= O_TRUNC;
if (flags & SSH_FXF_CREAT)
mode |= O_CREAT;
if (flags & SSH_FXF_EXCL)
mode |= O_EXCL;
auto named_fd = MP_FILEOPS.open_fd(filename, mode, msg->attr ? msg->attr->permissions : 0);
if (named_fd->fd == -1)
{
mpl::log(mpl::Level::trace, category, fmt::format("Cannot open '{}': {}", filename, std::strerror(errno)));
return reply_failure(msg);
}
if (!exists)
{
auto new_uid = reverse_uid_for(current_dir.ownerId(), current_dir.ownerId());
auto new_gid = reverse_gid_for(current_dir.groupId(), current_dir.groupId());
if (MP_PLATFORM.chown(filename, new_uid, new_gid) < 0)
{
mpl::log(mpl::Level::trace, category,
fmt::format("failed to chown '{}' to owner:{} and group:{}", filename, new_uid, new_gid));
return reply_failure(msg);
}
}
SftpHandleUPtr sftp_handle{sftp_handle_alloc(sftp_server_session.get(), named_fd.get()), ssh_string_free};
if (!sftp_handle)
{
mpl::log(mpl::Level::trace, category, "Cannot allocate handle for open()");
return reply_failure(msg);
}
open_file_handles.emplace(named_fd.get(), std::move(named_fd));
return sftp_reply_handle(msg, sftp_handle.get());
}
int mp::SftpServer::handle_opendir(sftp_client_message msg)
{
const auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
std::error_code err;
auto dir_iterator = MP_FILEOPS.dir_iterator(filename, err);
if (err.value() == int(std::errc::no_such_file_or_directory) || err.value() == int(std::errc::no_such_process))
{
mpl::log(mpl::Level::trace, category, fmt::format("Cannot open directory '{}': {}", filename, err.message()));
return sftp_reply_status(msg, SSH_FX_NO_SUCH_FILE, "no such directory");
}
if (err.value() == int(std::errc::permission_denied))
{
mpl::log(mpl::Level::trace, category, fmt::format("Cannot read directory '{}': {}", filename, err.message()));
return reply_perm_denied(msg);
}
QFileInfo file_info{filename};
if (!has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
SftpHandleUPtr sftp_handle{sftp_handle_alloc(sftp_server_session.get(), dir_iterator.get()), ssh_string_free};
if (!sftp_handle)
{
mpl::log(mpl::Level::trace, category, "Cannot allocate handle for opendir()");
return reply_failure(msg);
}
open_dir_handles.emplace(dir_iterator.get(), std::move(dir_iterator));
return sftp_reply_handle(msg, sftp_handle.get());
}
int mp::SftpServer::handle_read(sftp_client_message msg)
{
const auto handle = get_handle<NamedFd>(msg);
if (handle == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "read");
}
const auto& [path, file] = *handle;
if (MP_FILEOPS.lseek(file, msg->offset, SEEK_SET) == -1)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot seek to position {} in '{}'", __FUNCTION__, msg->offset, path.string()));
return reply_failure(msg);
}
constexpr auto max_packet_size = 65536u;
std::array<char, max_packet_size> buffer{};
if (const auto r = MP_FILEOPS.read(file, buffer.data(), std::min(msg->len, max_packet_size)); r > 0)
return sftp_reply_data(msg, buffer.data(), r);
else if (r == 0)
return sftp_reply_status(msg, SSH_FX_EOF, "End of file");
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: read failed for '{}': {}", __FUNCTION__, path.string(), std::strerror(errno)));
return sftp_reply_status(msg, SSH_FX_FAILURE, std::strerror(errno));
}
int mp::SftpServer::handle_readdir(sftp_client_message msg)
{
const auto handle = get_handle<DirIterator>(msg);
if (handle == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "readdir");
}
auto& dir_iterator = *handle;
if (!dir_iterator.hasNext())
return sftp_reply_status(msg, SSH_FX_EOF, nullptr);
const auto max_num_entries_per_packet = 50ll;
for (int i = 0; i < max_num_entries_per_packet && dir_iterator.hasNext(); i++)
{
const auto& entry = dir_iterator.next();
QFileInfo file_info{entry.path().string().c_str()};
sftp_attributes_struct attr{};
if (entry.is_symlink())
{
mp::platform::symlink_attr_from(file_info.absoluteFilePath().toStdString().c_str(), &attr);
attr.uid = mapped_uid_for(attr.uid);
attr.gid = mapped_gid_for(attr.gid);
}
else
{
attr = attr_from(file_info);
}
const auto longname = longname_from(file_info, entry.path().string());
sftp_reply_names_add(msg, entry.path().filename().string().c_str(), longname.data(), &attr);
}
return sftp_reply_names(msg);
}
int mp::SftpServer::handle_readlink(sftp_client_message msg)
{
auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(
mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
auto link = QFile::symLinkTarget(filename);
if (link.isEmpty())
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: invalid link for \'{}\'", __FUNCTION__, filename));
return sftp_reply_status(msg, SSH_FX_NO_SUCH_FILE, "invalid link");
}
QFileInfo file_info{filename};
if (!has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
sftp_attributes_struct attr{};
sftp_reply_names_add(msg, link.toStdString().c_str(), link.toStdString().c_str(), &attr);
return sftp_reply_names(msg);
}
int mp::SftpServer::handle_realpath(sftp_client_message msg)
{
auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(
mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info{filename};
if (!has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
auto realpath = QFileInfo(filename).absoluteFilePath();
return sftp_reply_name(msg, realpath.toStdString().c_str(), nullptr);
}
int mp::SftpServer::handle_remove(sftp_client_message msg)
{
const auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info{filename};
if (MP_FILEOPS.exists(file_info) && !has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
std::error_code err;
if (!MP_FILEOPS.remove(filename, err) && !err)
err = std::make_error_code(std::errc::no_such_file_or_directory);
if (err)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot remove '{}': {}", __FUNCTION__, filename, err.message()));
return reply_failure(msg);
}
return reply_ok(msg);
}
int mp::SftpServer::handle_rename(sftp_client_message msg)
{
const auto source = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, source))
{
mpl::log(
mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, source, source_path));
return reply_perm_denied(msg);
}
QFileInfo source_info{source};
if (!source_info.isSymLink() && !MP_FILEOPS.exists(source_info))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: cannot rename \'{}\': no such file", __FUNCTION__, source));
return sftp_reply_status(msg, SSH_FX_NO_SUCH_FILE, "no such file");
}
if (!has_id_mappings_for(source_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, source));
return reply_perm_denied(msg);
}
const auto target = sftp_client_message_get_data(msg);
if (!validate_path(source_path, target))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: cannot validate target path \'{}\' against source \'{}\'", __FUNCTION__, target,
source_path));
return reply_perm_denied(msg);
}
QFileInfo target_info{target};
if (MP_FILEOPS.exists(target_info) && !has_id_mappings_for(target_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, target));
return reply_perm_denied(msg);
}
QFile target_file{target};
if (MP_FILEOPS.exists(target_info))
{
if (!MP_FILEOPS.remove(target_file))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: cannot remove \'{}\' for renaming", __FUNCTION__, target));
return reply_failure(msg);
}
}
QFile source_file{source};
if (!MP_FILEOPS.rename(source_file, target))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: failed renaming \'{}\' to \'{}\'", __FUNCTION__, source, target));
return reply_failure(msg);
}
return reply_ok(msg);
}
int mp::SftpServer::handle_setstat(sftp_client_message msg)
{
QString filename;
if (sftp_client_message_get_type(msg) == SFTP_FSETSTAT)
{
const auto handle = get_handle<NamedFd>(msg);
if (handle == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "setstat");
}
const auto& [path, _] = *handle;
filename = path.string().c_str();
}
else
{
filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename.toStdString()))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot validate path '{}' against source '{}'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info{filename};
if (!file_info.isSymLink() && !MP_FILEOPS.exists(file_info))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot setstat '{}': no such file", __FUNCTION__, filename));
return sftp_reply_status(msg, SSH_FX_NO_SUCH_FILE, "no such file");
}
}
QFile file{filename};
QFileInfo file_info{filename};
if (!has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
if (msg->attr->flags & SSH_FILEXFER_ATTR_SIZE)
{
if (!MP_FILEOPS.resize(file, msg->attr->size))
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: cannot resize '{}'", __FUNCTION__, filename));
return reply_failure(msg);
}
}
if (msg->attr->flags & SSH_FILEXFER_ATTR_PERMISSIONS)
{
std::error_code err;
MP_FILEOPS.permissions(file.fileName().toStdString(), static_cast<fs::perms>(msg->attr->permissions), err);
if (err)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: set permissions failed for '{}': {}", __FUNCTION__, filename, err.message()));
return reply_failure(msg);
}
}
if (msg->attr->flags & SSH_FILEXFER_ATTR_ACMODTIME)
{
if (MP_PLATFORM.utime(filename.toStdString().c_str(), msg->attr->atime, msg->attr->mtime) < 0)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot set modification date for '{}'", __FUNCTION__, filename));
return reply_failure(msg);
}
}
if (msg->attr->flags & SSH_FILEXFER_ATTR_UIDGID)
{
if (!has_reverse_uid_mapping_for(msg->attr->uid) && !has_reverse_gid_mapping_for(msg->attr->gid))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot set ownership for \'{}\' without id mapping", __FUNCTION__, filename));
return reply_perm_denied(msg);
}
if (MP_PLATFORM.chown(filename.toStdString().c_str(),
reverse_uid_for(msg->attr->uid, msg->attr->uid),
reverse_gid_for(msg->attr->gid, msg->attr->gid)) < 0)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot set ownership for '{}'", __FUNCTION__, filename));
return reply_failure(msg);
}
}
return reply_ok(msg);
}
int mp::SftpServer::handle_stat(sftp_client_message msg, const bool follow)
{
auto filename = sftp_client_message_get_filename(msg);
if (!validate_path(source_path, filename))
{
mpl::log(
mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, filename, source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info(filename);
if (!file_info.isSymLink() && !MP_FILEOPS.exists(file_info))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot stat \'{}\': no such file", __FUNCTION__, filename));
return sftp_reply_status(msg, SSH_FX_NO_SUCH_FILE, "no such file");
}
sftp_attributes_struct attr{};
if (!follow && file_info.isSymLink())
{
mp::platform::symlink_attr_from(filename, &attr);
attr.uid = mapped_uid_for(attr.uid);
attr.gid = mapped_gid_for(attr.gid);
}
else
{
if (file_info.isSymLink())
file_info = QFileInfo(file_info.symLinkTarget());
attr = attr_from(file_info);
}
return sftp_reply_attr(msg, &attr);
}
int mp::SftpServer::handle_symlink(sftp_client_message msg)
{
const auto old_name = sftp_client_message_get_filename(msg);
const auto new_name = sftp_client_message_get_data(msg);
if (!validate_path(source_path, new_name))
{
mpl::log(
mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, new_name, source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info{old_name};
if (MP_FILEOPS.exists(file_info) && !has_id_mappings_for(file_info))
{
mpl::log(
mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied", __FUNCTION__, old_name));
return reply_perm_denied(msg);
}
if (!MP_PLATFORM.symlink(old_name, new_name, QFileInfo(old_name).isDir()))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: failure creating symlink from \'{}\' to \'{}\'", __FUNCTION__, old_name, new_name));
return reply_failure(msg);
}
return reply_ok(msg);
}
int mp::SftpServer::handle_write(sftp_client_message msg)
{
const auto handle = get_handle<NamedFd>(msg);
if (handle == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: bad handle requested", __FUNCTION__));
return reply_bad_handle(msg, "write");
}
const auto& [path, file] = *handle;
if (MP_FILEOPS.lseek(file, msg->offset, SEEK_SET) == -1)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot seek to position {} in '{}'", __FUNCTION__, msg->offset, path.string()));
return reply_failure(msg);
}
auto len = ssh_string_len(msg->data);
auto data_ptr = ssh_string_get_char(msg->data);
do
{
const auto r = MP_FILEOPS.write(file, data_ptr, len);
if (r == -1)
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: write failed for '{}': {}", __FUNCTION__, path.string(), std::strerror(errno)));
return reply_failure(msg);
}
data_ptr += r;
len -= r;
} while (len > 0);
return reply_ok(msg);
}
int mp::SftpServer::handle_extended(sftp_client_message msg)
{
const auto submessage = sftp_client_message_get_submessage(msg);
if (submessage == nullptr)
{
mpl::log(mpl::Level::trace, category, fmt::format("{}: invalid submesage requested", __FUNCTION__));
return reply_failure(msg);
}
const std::string method(submessage);
if (method == "hardlink@openssh.com")
{
const auto old_name = sftp_client_message_get_filename(msg);
const auto new_name = sftp_client_message_get_data(msg);
if (!validate_path(source_path, new_name))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: cannot validate path \'{}\' against source \'{}\'", __FUNCTION__, new_name,
source_path));
return reply_perm_denied(msg);
}
QFileInfo file_info{old_name};
if (!has_id_mappings_for(file_info))
{
mpl::log(mpl::Level::trace,
category,
fmt::format("{}: cannot access path \'{}\' without id mapping: permission denied",
__FUNCTION__,
old_name));
return reply_perm_denied(msg);
}
if (!MP_PLATFORM.link(old_name, new_name))
{
mpl::log(mpl::Level::trace, category,
fmt::format("{}: failed creating link from \'{}\' to \'{}\'", __FUNCTION__, old_name, new_name));
return reply_failure(msg);
}
}
else if (method == "posix-rename@openssh.com")
{
return handle_rename(msg);
}
else
{
mpl::log(mpl::Level::trace, category, fmt::format("Unhandled extended method requested: {}", method));
return reply_unsupported(msg);
}
return reply_ok(msg);
}
template <typename T>
T* multipass::SftpServer::get_handle(sftp_client_message msg)
{
return static_cast<T*>(sftp_handle(msg->sftp, msg->handle));
}
| 39,895
|
C++
|
.cpp
| 1,057
| 30.194891
| 120
| 0.593724
|
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,706
|
sshfs_mount_handler.cpp
|
canonical_multipass/src/sshfs_mount/sshfs_mount_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 <multipass/exceptions/exitless_sshprocess_exceptions.h>
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/platform.h>
#include <multipass/sshfs_mount/sshfs_mount_handler.h>
#include <multipass/utils.h>
#include <QCoreApplication>
#include <QEventLoop>
#include <QThread>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "sshfs-mount-handler";
void start_and_block_until_connected(mp::Process* process)
{
QEventLoop event_loop;
auto stop_conn = QObject::connect(process, &mp::Process::finished, &event_loop, &QEventLoop::quit);
auto running_conn = QObject::connect(process, &mp::Process::ready_read_standard_output, [process, &event_loop]() {
if (process->read_all_standard_output().contains("Connected")) // Magic string printed by sshfs_server
event_loop.quit();
});
process->start();
// This blocks and waits either for "Connected" or for failure.
event_loop.exec();
QObject::disconnect(stop_conn);
QObject::disconnect(running_conn);
}
bool has_sshfs(const std::string& name, mp::SSHSession& session)
{
// Check if snap support is installed in the instance
if (session.exec("which snap").exit_code() != 0)
{
mpl::log(mpl::Level::warning, category, fmt::format("Snap support is not installed in '{}'", name));
throw std::runtime_error(
fmt::format("Snap support needs to be installed in '{}' in order to support mounts.\n"
"Please see https://docs.snapcraft.io/installing-snapd for information on\n"
"how to install snap support for your instance's distribution.\n\n"
"If your distribution's instructions specify enabling classic snap support,\n"
"please do that as well.\n\n"
"Alternatively, install `sshfs` manually inside the instance.",
name));
}
// Check if multipass-sshfs is already installed
if (session.exec("sudo snap list multipass-sshfs").exit_code(std::chrono::seconds(15)) == 0)
{
mpl::log(mpl::Level::debug, category,
fmt::format("The multipass-sshfs snap is already installed on '{}'", name));
return true;
}
// Check if /snap exists for "classic" snap support
if (session.exec("[ -e /snap ]").exit_code() != 0)
{
mpl::log(mpl::Level::warning, category, fmt::format("Classic snap support symlink is needed in '{}'", name));
throw std::runtime_error(
fmt::format("Classic snap support is not enabled for '{}'!\n\n"
"Please see https://docs.snapcraft.io/installing-snapd for information on\n"
"how to enable classic snap support for your instance's distribution.",
name));
}
return false;
}
void install_sshfs_for(const std::string& name, mp::SSHSession& session, const std::chrono::milliseconds& timeout)
try
{
mpl::log(mpl::Level::info, category, fmt::format("Installing the multipass-sshfs snap in '{}'", name));
auto proc = session.exec("sudo snap install multipass-sshfs");
if (proc.exit_code(timeout) != 0)
{
auto error_msg = proc.read_std_error();
mpl::log(mpl::Level::error,
category,
fmt::format("Failed to install 'multipass-sshfs': {}", mpu::trim_end(error_msg)));
throw mp::SSHFSMissingError();
}
}
catch (const mp::ExitlessSSHProcessException& e)
{
mpl::log(mpl::Level::error,
category,
fmt::format("Could not install 'multipass-sshfs' in '{}': {}", name, e.what()));
throw mp::SSHFSMissingError();
}
} // namespace
namespace multipass
{
SSHFSMountHandler::SSHFSMountHandler(VirtualMachine* vm,
const SSHKeyProvider* ssh_key_provider,
const std::string& target,
VMMount mount_spec)
: MountHandler{vm, ssh_key_provider, std::move(mount_spec), target},
process{nullptr},
config{"",
0,
vm->ssh_username(),
vm->vm_name,
ssh_key_provider->private_key_as_base64(),
source,
target,
this->mount_spec.get_gid_mappings(),
this->mount_spec.get_uid_mappings()}
{
mpl::log(
mpl::Level::info,
category,
fmt::format("initializing mount {} => {} in '{}'", this->mount_spec.get_source_path(), target, vm->vm_name));
}
bool SSHFSMountHandler::is_active()
try
{
if (!active || !process || !process->running())
return false;
SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider};
const auto resolved_target = mp::utils::get_resolved_target(session, target);
return !session.exec(fmt::format("findmnt --type fuse.sshfs | grep -E '^{} +:{}'", resolved_target, source))
.exit_code();
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Failed checking SSHFS mount \"{}\" in instance '{}': {}", target, vm->vm_name, e.what()));
return false;
}
void SSHFSMountHandler::activate_impl(ServerVariant server, std::chrono::milliseconds timeout)
{
SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider};
if (!has_sshfs(vm->vm_name, session))
{
auto visitor = [](auto server) {
if (server)
{
auto reply = make_reply_from_server(server);
reply.set_reply_message("Enabling support for mounting");
server->Write(reply);
}
};
std::visit(visitor, server);
install_sshfs_for(vm->vm_name, session, timeout);
}
// Can't obtain hostname/IP address until instance is running
config.host = vm->ssh_hostname();
config.port = vm->ssh_port();
if (process)
process.reset();
process.reset(platform::make_sshfs_server_process(config).release());
QObject::connect(process.get(), &Process::finished, [this](const ProcessState& exit_state) {
if (exit_state.completed_successfully())
{
mpl::log(mpl::Level::info, category,
fmt::format("Mount \"{}\" in instance '{}' has stopped", target, vm->vm_name));
}
else
{
// not error as it failing can indicate we need to install sshfs in the VM
mpl::log(mpl::Level::warning, category,
fmt::format("Mount \"{}\" in instance '{}' has stopped unsuccessfully: {}", target, vm->vm_name,
exit_state.failure_message()));
}
});
QObject::connect(process.get(), &Process::error_occurred, [this](auto error, auto error_string) {
mpl::log(mpl::Level::error, category,
fmt::format("There was an error with sshfs_server for instance '{}' with path \"{}\": {} - {}",
vm->vm_name, target, mpu::qenum_to_string(error), error_string));
});
mpl::log(mpl::Level::info, category, fmt::format("process program '{}'", process->program()));
mpl::log(mpl::Level::info, category, fmt::format("process arguments '{}'", process->arguments().join(", ")));
start_and_block_until_connected(process.get());
// after the process is started, it must be moved to the main thread
// when starting an instance that already has mounts defined, it is started in a thread from the global thread pool
// this makes the sshfs_server process to be owned by that thread
// when stopping the mount from the main thread again, qt will try to send an event from the main thread to the one
// in which the process lives this will result in an error since qt can't send events from one thread to another
process->moveToThread(QCoreApplication::instance()->thread());
// Check in case sshfs_server stopped, usually due to an error
auto process_state = process->process_state();
if (process_state.exit_code == 9) // Magic number returned by sshfs_server
throw SSHFSMissingError();
else if (process_state.exit_code || process_state.error)
throw std::runtime_error(
fmt::format("{}: {}", process_state.failure_message(), process->read_all_standard_error()));
}
void SSHFSMountHandler::deactivate_impl(bool force)
{
mpl::log(mpl::Level::info, category, fmt::format("Stopping mount \"{}\" in instance '{}'", target, vm->vm_name));
QObject::disconnect(process.get(), &Process::error_occurred, nullptr, nullptr);
if (process->terminate(); !process->wait_for_finished(5000))
{
auto err = fmt::format("Failed to terminate SSHFS mount process: {}", process->read_all_standard_error());
if (force)
mpl::log(
mpl::Level::warning, category,
fmt::format("Failed to gracefully stop mount \"{}\" in instance '{}': {}", target, vm->vm_name, err));
else
throw std::runtime_error{err};
}
process.reset();
}
SSHFSMountHandler::~SSHFSMountHandler()
{
deactivate(/*force=*/true);
}
} // namespace multipass
| 9,963
|
C++
|
.cpp
| 218
| 37.986239
| 119
| 0.63048
|
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,707
|
sshfs_server.cpp
|
canonical_multipass/src/sshfs_mount/sshfs_server.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 <iostream>
#include <memory>
#include <string>
#include <QStringList>
#include "sshfs_mount.h"
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/id_mappings.h>
#include <multipass/logging/log.h>
#include <multipass/logging/multiplexing_logger.h>
#include <multipass/logging/standard_logger.h>
#include <multipass/platform.h>
#include <multipass/ssh/ssh_session.h>
#include <ssh/ssh_client_key_provider.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpp = multipass::platform;
using namespace std;
namespace
{
mp::id_mappings convert_id_mappings(const char* in)
{
mp::id_mappings ret_map;
QString input(in);
auto maps = input.split(',', Qt::SkipEmptyParts);
for (auto map : maps)
{
auto ids = map.split(":");
if (ids.count() != 2)
{
cerr << "Incorrect ID mapping syntax";
continue;
}
bool ok1, ok2;
int from = ids.first().toInt(&ok1);
int to = ids.last().toInt(&ok2);
if (!ok1 || !ok2)
{
cerr << "Incorrect ID mapping ids found, ignored" << endl;
continue;
}
ret_map.push_back({from, to});
}
return ret_map;
}
} // namespace
int main(int argc, char* argv[])
{
if (argc != 9)
{
cerr << "Incorrect arguments" << endl;
exit(2);
}
const auto key = qgetenv("KEY");
if (key == nullptr)
{
cerr << "KEY not set" << endl;
exit(2);
}
const auto priv_key_blob = string(key);
const auto host = string(argv[1]);
const int port = atoi(argv[2]);
const auto username = string(argv[3]);
const auto source_path = string(argv[4]);
const auto target_path = string(argv[5]);
const mp::id_mappings uid_mappings = convert_id_mappings(argv[6]);
const mp::id_mappings gid_mappings = convert_id_mappings(argv[7]);
const mpl::Level log_level = static_cast<mpl::Level>(atoi(argv[8]));
auto logger = mpp::make_logger(log_level);
if (!logger)
logger = std::make_unique<mpl::StandardLogger>(log_level);
// Use the MultiplexingLogger as we may end up routing messages to the daemon too at some point
auto standard_logger = std::make_shared<mpl::MultiplexingLogger>(std::move(logger));
mpl::set_logger(standard_logger);
try
{
auto watchdog = mpp::make_quit_watchdog(); // called while there is only one thread
mp::SSHSession session{host, port, username, mp::SSHClientKeyProvider{priv_key_blob}};
mp::SshfsMount sshfs_mount(std::move(session), source_path, target_path, gid_mappings, uid_mappings);
// ssh lives on its own thread, use this thread to listen for quit signal
if (int sig = watchdog())
cout << "Received signal " << sig << ". Stopping" << endl;
sshfs_mount.stop();
exit(0);
}
catch (const mp::SSHFSMissingError&)
{
cerr << "SSHFS was not found on the host: " << host << endl;
exit(9);
}
catch (const exception& e)
{
cerr << e.what();
}
return 1;
}
| 3,755
|
C++
|
.cpp
| 111
| 28.738739
| 109
| 0.649931
|
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,708
|
sshfs_mount.cpp
|
canonical_multipass/src/sshfs_mount/sshfs_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 "sshfs_mount.h"
#include "sftp_server.h"
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/format.h>
#include <multipass/id_mappings.h>
#include <multipass/logging/log.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/top_catch_all.h>
#include <multipass/utils.h>
#include <semver200.h>
#include <QDir>
#include <QString>
#include <iostream>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "sshfs mount";
const std::string fuse_version_string{"FUSE library version"};
const std::string ld_library_path_key{"LD_LIBRARY_PATH="};
const std::string snap_path_key{"SNAP="};
auto get_sshfs_exec_and_options(mp::SSHSession& session)
{
std::string sshfs_exec;
try
{
// Prefer to use Snap package version first
auto sshfs_env{MP_UTILS.run_in_ssh_session(session, "snap run multipass-sshfs.env")};
auto ld_library_path = mp::utils::match_line_for(sshfs_env, ld_library_path_key);
auto snap_path = mp::utils::match_line_for(sshfs_env, snap_path_key);
snap_path = snap_path.substr(snap_path_key.length());
sshfs_exec = fmt::format("env {} {}/bin/sshfs", ld_library_path, snap_path);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::debug, category,
fmt::format("'multipass-sshfs' snap package is not installed: {}", e.what()));
// Fallback to looking for distro version if snap is not found
try
{
sshfs_exec = MP_UTILS.run_in_ssh_session(session, "sudo which sshfs");
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Unable to determine if 'sshfs' is installed: {}", e.what()));
throw mp::SSHFSMissingError();
}
}
sshfs_exec = mp::utils::trim_end(sshfs_exec);
auto version_info{MP_UTILS.run_in_ssh_session(session, fmt::format("sudo {} -V", sshfs_exec))};
sshfs_exec += " -o slave -o transform_symlinks -o allow_other -o Compression=no";
auto fuse_version_line = mp::utils::match_line_for(version_info, fuse_version_string);
if (!fuse_version_line.empty())
{
std::string fuse_version;
// split on the fuse_version_string along with 0 or 1 colon(s)
auto tokens = mp::utils::split(fuse_version_line, fmt::format("{}:? ", fuse_version_string));
if (tokens.size() == 2)
fuse_version = tokens[1];
if (fuse_version.empty())
{
mpl::log(mpl::Level::warning, category, fmt::format("Unable to parse the {}", fuse_version_string));
mpl::log(mpl::Level::debug, category,
fmt::format("Unable to parse the {}: {}", fuse_version_string, fuse_version_line));
}
// The option was made the default in libfuse 3.0
else if (version::Semver200_version(fuse_version) < version::Semver200_version("3.0.0"))
{
sshfs_exec += " -o nonempty -o cache=no";
}
else
{
sshfs_exec += " -o dir_cache=no";
}
}
else
{
mpl::log(mpl::Level::warning, category, fmt::format("Unable to retrieve \'{}\'", fuse_version_string));
}
return sshfs_exec;
}
auto make_sftp_server(mp::SSHSession&& session, const std::string& source, const std::string& target,
const mp::id_mappings& gid_mappings, const mp::id_mappings& uid_mappings)
{
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(source = {}, target = {}, …): ", __FILE__, __LINE__, __FUNCTION__, source, target));
auto sshfs_exec_line = get_sshfs_exec_and_options(session);
// Split the path in existing and missing parts.
const auto& [leading, missing] = mpu::get_path_split(session, target);
auto output = MP_UTILS.run_in_ssh_session(session, "id -u");
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): `id -u` = {}", __FILE__, __LINE__, __FUNCTION__, output));
auto default_uid = std::stoi(output);
output = MP_UTILS.run_in_ssh_session(session, "id -g");
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): `id -g` = {}", __FILE__, __LINE__, __FUNCTION__, output));
auto default_gid = std::stoi(output);
// We need to create the part of the path which does not still exist,
// and set then the correct ownership.
if (missing != ".")
{
mpu::make_target_dir(session, leading, missing);
mpu::set_owner_for(session, leading, missing, default_uid, default_gid);
}
return std::make_unique<mp::SftpServer>(std::move(session), source, leading + missing, gid_mappings, uid_mappings,
default_uid, default_gid, sshfs_exec_line);
}
} // namespace
mp::SshfsMount::SshfsMount(SSHSession&& session, const std::string& source, const std::string& target,
const mp::id_mappings& gid_mappings, const mp::id_mappings& uid_mappings)
: sftp_server{make_sftp_server(std::move(session), source, target, gid_mappings, uid_mappings)},
sftp_thread{[this]() {
mp::top_catch_all(category, [this] {
std::cout << "Connected" << std::endl;
sftp_server->run();
std::cout << "Stopped" << std::endl;
});
}}
{
}
mp::SshfsMount::~SshfsMount()
{
stop();
}
void mp::SshfsMount::stop()
{
sftp_server->stop();
if (sftp_thread.joinable())
sftp_thread.join();
}
| 6,259
|
C++
|
.cpp
| 148
| 35.797297
| 121
| 0.627261
|
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,709
|
settings.cpp
|
canonical_multipass/src/settings/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 <multipass/settings/settings.h>
#include <memory>
#include <stdexcept>
namespace mp = multipass;
mp::Settings::Settings(const Singleton<Settings>::PrivatePass& pass) : Singleton<Settings>::Singleton{pass}
{
}
auto mp::Settings::register_handler(std::unique_ptr<SettingsHandler> handler) -> SettingsHandler*
{
assert(handler && "can't have null settings handler"); // TODO use a `not_null` type (e.g. gsl::not_null)
auto ret = handler.get();
handlers.push_back(std::move(handler));
return ret;
}
void mp::Settings::unregister_handler(SettingsHandler* handler)
{
auto it = std::find_if(handlers.begin(), handlers.end(), [handler](const auto& uptr) { // trust me clang-format
return uptr.get() == handler;
});
if (it != handlers.end())
handlers.erase(it);
}
std::set<QString> multipass::Settings::keys() const
{
std::set<QString> ret{};
if (!handlers.empty())
{
auto it = handlers.cbegin();
assert(*it && "can't have null settings handler"); // TODO use a `not_null` type (e.g. gsl::not_null)
ret = (*it)->keys();
while (++it != handlers.cend())
{
assert(*it && "can't have null settings handler"); // TODO use a `not_null` type (e.g. gsl::not_null)
ret.merge((*it)->keys());
}
}
return ret;
}
// TODO try installing yaml backend
QString mp::Settings::get(const QString& key) const
{
for (const auto& handler : handlers)
{
try
{
assert(handler && "can't have null settings handler"); // TODO use a `not_null` type (e.g. gsl::not_null)
return handler->get(key);
}
catch (const UnrecognizedSettingException&)
{
continue;
}
}
throw UnrecognizedSettingException{key};
}
void mp::Settings::set(const QString& key, const QString& val)
{
auto success = false;
for (const auto& handler : handlers)
{
try
{
assert(handler && "can't have null settings handler"); // TODO use a `not_null` type (e.g. gsl::not_null)
handler->set(key, val);
success = true; // don't return yet, give all handlers a chance to react
}
catch (const UnrecognizedSettingException&)
{
continue;
}
}
if (!success)
throw UnrecognizedSettingException{key};
}
| 3,030
|
C++
|
.cpp
| 90
| 28.322222
| 117
| 0.642955
|
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,710
|
basic_setting_spec.cpp
|
canonical_multipass/src/settings/basic_setting_spec.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/settings/basic_setting_spec.h>
namespace mp = multipass;
mp::BasicSettingSpec::BasicSettingSpec(QString key, QString default_)
: key{std::move(key)},
default_{std::move(default_)} // no point interpreting here, polymorphism disabled at construction
{
}
QString multipass::BasicSettingSpec::get_key() const
{
return key;
}
QString multipass::BasicSettingSpec::get_default() const
{
return default_;
}
QString multipass::BasicSettingSpec::interpret(QString val) const
{
return val;
}
| 1,158
|
C++
|
.cpp
| 35
| 30.857143
| 104
| 0.759176
|
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,711
|
persistent_settings_handler.cpp
|
canonical_multipass/src/settings/persistent_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 "wrapped_qsettings.h"
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/file_ops.h>
#include <multipass/logging/log.h>
#include <multipass/settings/persistent_settings_handler.h>
#include <cassert>
namespace mp = multipass;
namespace mpl = mp::logging;
namespace
{
std::unique_ptr<mp::WrappedQSettings> persistent_settings(const QString& filename)
{
return mp::WrappedQSettingsFactory::instance().make_wrapped_qsettings(filename, QSettings::IniFormat);
}
bool exists_but_unreadable(const QString& filename)
{
std::fstream in_stream;
MP_FILEOPS.open(in_stream, qPrintable(filename), std::ios_base::in);
return in_stream.fail() && errno && errno != ENOENT; /*
Note: QFile::error() not enough for us: it would not distinguish the actual cause of failure;
Note: errno is only set on some platforms, but those were experimentally verified to be the only ones that do
not set a bad QSettings status on permission denied; to make this code portable, we need to account for a
zero errno on the remaining platforms */
}
void check_status(const mp::WrappedQSettings& qsettings, const QString& attempted_operation)
{
auto status = qsettings.status();
if (status || exists_but_unreadable(qsettings.fileName()))
throw mp::PersistentSettingsException{
attempted_operation, status == QSettings::FormatError
? QStringLiteral("format error")
: QStringLiteral("access error (consider running with an administrative role)")};
}
QString checked_get(mp::WrappedQSettings& qsettings, const QString& key, const mp::SettingSpec& spec, std::mutex& mutex)
{
std::lock_guard<std::mutex> lock{mutex};
const auto& fallback = spec.get_default();
auto ret = qsettings.value(key, fallback).toString();
check_status(qsettings, QStringLiteral("read"));
try
{
spec.interpret(ret); // check validity of what we read from disk
}
catch (const mp::InvalidSettingException& e)
{
mpl::log(mpl::Level::warning, "settings", fmt::format("{}. Resetting '{}'.", e.what(), key));
qsettings.remove(key);
qsettings.sync();
check_status(qsettings, "reset");
ret = fallback;
}
return ret;
}
void checked_set(mp::WrappedQSettings& qsettings, const QString& key, const QString& val, std::mutex& mutex)
{
std::lock_guard<std::mutex> lock{mutex};
qsettings.setValue(key, val);
qsettings.sync(); // flush to confirm we can write
check_status(qsettings, QStringLiteral("read/write"));
}
} // namespace
mp::PersistentSettingsHandler::PersistentSettingsHandler(QString filename, SettingSpec::Set settings)
: filename{std::move(filename)}, settings{convert(std::move(settings))}
{
}
// TODO try installing yaml backend
QString mp::PersistentSettingsHandler::get(const QString& key) const
{
const auto& setting_spec = get_setting(key); // make sure the key is valid before reading from disk
auto settings_file = persistent_settings(filename);
return checked_get(*settings_file, key, setting_spec, mutex);
}
auto mp::PersistentSettingsHandler::get_setting(const QString& key) const -> const SettingSpec&
{
try
{
assert(settings.at(key) && "can't have null setting spec"); // TODO use a `not_null` type (e.g. gsl::not_null)
return *settings.at(key);
}
catch (const std::out_of_range&)
{
throw UnrecognizedSettingException{key};
}
}
void mp::PersistentSettingsHandler::set(const QString& key, const QString& val)
{
auto interpreted = get_setting(key).interpret(val); // check both key and value validity, convert as appropriate
auto settings_file = persistent_settings(filename);
checked_set(*settings_file, key, interpreted, mutex);
}
std::set<QString> mp::PersistentSettingsHandler::keys() const
{
std::set<QString> ret{};
std::transform(cbegin(settings), cend(settings), std::inserter(ret, begin(ret)),
[](const auto& elem) { return elem.first; }); // I wish get<0> worked here... maybe in C++20
return ret;
}
auto mp::PersistentSettingsHandler::convert(SettingSpec::Set settings) -> SettingMap
{
SettingMap ret;
while (!settings.empty())
{
auto it = settings.begin();
assert(*it && "can't have null setting spec"); // TODO use a `not_null` type (e.g. gsl::not_null)
auto key = (*it)->get_key(); // ensure setting not extracted yet
ret.emplace(std::move(key), std::move(settings.extract(it).value())); /* need to extract to be able to move
see notes in https://en.cppreference.com/w/cpp/container/set/begin */
}
return ret;
}
| 5,443
|
C++
|
.cpp
| 126
| 38.119048
| 120
| 0.6935
|
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,712
|
bool_setting_spec.cpp
|
canonical_multipass/src/settings/bool_setting_spec.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/exceptions/settings_exceptions.h>
#include <multipass/settings/bool_setting_spec.h>
namespace mp = multipass;
namespace
{
QString interpret_bool(QString val)
{ // constrain accepted values to avoid QVariant::toBool interpreting non-empty strings (such as "nope") as true
static constexpr auto convert_to_true = {"on", "yes", "1"};
static constexpr auto convert_to_false = {"off", "no", "0"};
auto lower_val = val.toLower();
if (std::find(cbegin(convert_to_true), cend(convert_to_true), lower_val) != cend(convert_to_true))
val = QStringLiteral("true");
else if (std::find(cbegin(convert_to_false), cend(convert_to_false), lower_val) != cend(convert_to_false))
val = QStringLiteral("false");
return val;
}
QString interpret_impl(const QString& key, QString val)
{
auto ret = interpret_bool(std::move(val));
if (ret != "true" && ret != "false")
throw mp::InvalidSettingException(key, ret, "Invalid value, try \"true\" or \"false\"");
return ret;
}
std::pair<QString, QString> munch_params(QString key, QString default_) // work around use after move
{
auto interpreted_default = interpret_impl(key, std::move(default_));
return {std::move(key), std::move(interpreted_default)};
}
} // namespace
mp::BoolSettingSpec::BoolSettingSpec(QString key, QString default_)
: BoolSettingSpec{munch_params(std::move(key), std::move(default_))}
{
}
mp::BoolSettingSpec::BoolSettingSpec(std::pair<QString, QString> params)
: BasicSettingSpec(std::move(params.first), std::move(params.second))
{
}
QString mp::BoolSettingSpec::interpret(QString val) const
{
return interpret_impl(key, std::move(val));
}
| 2,326
|
C++
|
.cpp
| 57
| 37.947368
| 112
| 0.722321
|
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,713
|
custom_setting_spec.cpp
|
canonical_multipass/src/settings/custom_setting_spec.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/settings/custom_setting_spec.h>
namespace mp = multipass;
mp::CustomSettingSpec::CustomSettingSpec(QString key, QString default_, std::function<QString(QString)> interpreter)
: multipass::BasicSettingSpec(std::move(key), interpreter(std::move(default_))), interpreter{std::move(interpreter)}
{
}
QString mp::CustomSettingSpec::interpret(QString val) const
{
return interpreter(std::move(val));
}
| 1,056
|
C++
|
.cpp
| 26
| 38.576923
| 120
| 0.765107
|
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,714
|
default_vm_blueprint_provider.cpp
|
canonical_multipass/src/blueprint_provider/default_vm_blueprint_provider.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/default_vm_blueprint_provider.h>
#include <multipass/exceptions/blueprint_exceptions.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/exceptions/invalid_memory_size_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/poco_zip_utils.h>
#include <multipass/query.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <multipass/yaml_node_utils.h>
#include <QFile>
#include <QFileInfo>
#include <Poco/StreamCopier.h>
#include <Poco/Zip/ZipStream.h>
#include <fstream>
#include <sstream>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
const QString github_blueprints_archive_name{"multipass-blueprints.zip"};
// The folders where to read definitions. The list is sorted by precedence.
constexpr auto version_v1{"v1"};
constexpr auto version_v2{"v2"};
const QStringList blueprint_dir_versions{version_v2, version_v1};
constexpr auto category = "blueprint provider";
static constexpr auto bad_conversion_template{"Cannot convert \'{}\' key for the {} Blueprint"};
const auto runs_on_key{"runs-on"};
const auto instances_key{"instances"};
bool runs_on(const std::string& blueprint_name, const YAML::Node& blueprint_node, const std::string& arch)
{
if (blueprint_node["blueprint-version"].as<std::string>() == version_v1)
{
if (blueprint_node[runs_on_key])
{
try
{
const auto runs_on = blueprint_node[runs_on_key].as<std::vector<std::string>>();
return std::find(runs_on.cbegin(), runs_on.cend(), arch) != runs_on.cend();
}
catch (const YAML::BadConversion&)
{
throw mp::InvalidBlueprintException(fmt::format(bad_conversion_template, runs_on_key, blueprint_name));
}
}
else
{
return true;
}
}
if (blueprint_node[instances_key] && blueprint_node[instances_key][blueprint_name] &&
blueprint_node[instances_key][blueprint_name]["images"])
{
if (blueprint_node[instances_key][blueprint_name]["images"][arch])
{
if (blueprint_node[instances_key][blueprint_name]["images"][arch]["url"])
return true;
}
else
{
return false;
}
}
throw mp::InvalidBlueprintException(fmt::format(bad_conversion_template, instances_key, blueprint_name));
}
auto blueprints_map_for(const std::string& archive_file_path, bool& needs_update, const std::string& arch)
{
std::map<std::string, YAML::Node> blueprints_map;
std::ifstream zip_stream{archive_file_path, std::ios::binary};
auto zip_archive = MP_POCOZIPUTILS.zip_archive_for(zip_stream);
for (const auto& blueprint_dir_version : blueprint_dir_versions)
{
for (auto it = zip_archive.headerBegin(); it != zip_archive.headerEnd(); ++it)
{
if (it->second.isFile())
{
auto file_name = it->second.getFileName();
QFileInfo file_info{QString::fromStdString(file_name)};
auto blueprint_name = file_info.baseName().toStdString();
if (!blueprints_map.count(blueprint_name) && file_info.dir().dirName() == blueprint_dir_version &&
(file_info.suffix() == "yaml" || file_info.suffix() == "yml"))
{
if (!mp::utils::valid_hostname(blueprint_name))
{
mpl::log(mpl::Level::error, category,
fmt::format("Invalid Blueprint name \'{}\': must be a valid host name",
file_info.baseName()));
needs_update = true;
continue;
}
Poco::Zip::ZipInputStream zip_input_stream{zip_stream, it->second};
std::ostringstream out(std::ios::binary);
Poco::StreamCopier::copyStream(zip_input_stream, out);
auto blueprint_node = YAML::Load(out.str());
blueprint_node["blueprint-version"] = blueprint_dir_version.toStdString();
try
{
if (runs_on(blueprint_name, blueprint_node, arch))
{
mpl::log(
mpl::Level::debug, category,
fmt::format("Loading \"{}\" {}", blueprint_name, blueprint_dir_version.toStdString()));
blueprints_map[blueprint_name] = blueprint_node;
}
else
{
mpl::log(mpl::Level::debug, category,
fmt::format("Not loading foreign arch \"{}\" {}", blueprint_name,
blueprint_dir_version.toStdString()));
}
}
catch (mp::InvalidBlueprintException&)
{
mpl::log(mpl::Level::debug, category,
fmt::format("Not loading malformed \"{}\" {}", blueprint_name,
blueprint_dir_version.toStdString()));
}
}
}
}
}
return blueprints_map;
}
std::string get_blueprint_version(const YAML::Node& blueprint_instance)
{
if (blueprint_instance["images"])
return "v2";
return "v1";
}
void merge_yaml_entries(YAML::Node& ours, const YAML::Node& theirs, const std::string& key, bool override_null = false)
{
if (!ours.IsDefined() || (override_null && ours.IsNull()))
{
ours = YAML::Clone(theirs);
return;
}
if (ours.IsSequence() && theirs.IsSequence())
{
for (const auto& value : theirs)
ours.push_back(value);
return;
}
if (ours.IsMap() && theirs.IsMap())
{
for (const auto& value : theirs)
if (value.first.IsScalar())
{
const auto subkey = value.first.Scalar();
auto subnode = ours[subkey];
merge_yaml_entries(subnode, value.second, subkey);
}
return;
}
throw mp::InvalidBlueprintException{fmt::format("Cannot merge values of {}:\n{}\n\n{}",
key,
mp::utils::emit_yaml(ours),
mp::utils::emit_yaml(theirs))};
}
mp::Query blueprint_from_yaml_node(YAML::Node& blueprint_config, const std::string& blueprint_name,
mp::VirtualMachineDescription& vm_desc, mp::ClientLaunchData& client_launch_data,
const QString& arch, mp::URLDownloader* url_downloader, bool& needs_update)
{
mp::Query query{"", "default", false, "", mp::Query::Type::Alias};
if (!blueprint_config[instances_key][blueprint_name])
{
throw mp::InvalidBlueprintException(
fmt::format("There are no instance definitions matching Blueprint name \"{}\"", blueprint_name));
}
auto blueprint_instance = blueprint_config[instances_key][blueprint_name];
if (!blueprint_config["blueprint-version"])
{
blueprint_config["blueprint-version"] = get_blueprint_version(blueprint_instance);
}
mpl::log(mpl::Level::debug, category,
fmt::format("Loading Blueprint \"{}\", version {}", blueprint_name,
blueprint_config["blueprint-version"].as<std::string>()));
auto blueprint_aliases = blueprint_config["aliases"];
if (blueprint_aliases)
{
for (const auto& alias_to_be_defined : blueprint_aliases)
{
auto alias_name = alias_to_be_defined.first.as<std::string>();
auto instance_and_command = mp::utils::split(alias_to_be_defined.second.as<std::string>(), ":");
if (instance_and_command.size() != 2)
throw mp::InvalidBlueprintException(
fmt::format("Alias definition must be in the form instance:command"));
mpl::log(mpl::Level::trace, category,
fmt::format("Add alias [{}, {}, {}] to RPC answer", alias_name, instance_and_command[0],
instance_and_command[1]));
mp::AliasDefinition alias_definition{instance_and_command[0], instance_and_command[1], "map"};
client_launch_data.aliases_to_be_created.emplace(alias_name, alias_definition);
}
}
// TODO: Abstract all of the following YAML schema boilerplate
if (blueprint_config["blueprint-version"].as<std::string>() == version_v2)
{
auto arch_node = blueprint_instance["images"][arch.toStdString()];
if (arch_node["url"])
query.release = arch_node["url"].as<std::string>();
else
throw mp::InvalidBlueprintException(fmt::format("No image URL for architecture {} in Blueprint", arch));
query.query_type = mp::Query::Type::HttpDownload;
if (arch_node["sha256"])
{
auto sha256_string = arch_node["sha256"].as<std::string>();
if (QString::fromStdString(sha256_string).startsWith("http"))
{
mpl::log(mpl::Level::debug, category, fmt::format("Downloading SHA256 from {}", sha256_string));
auto downloaded_sha256 = url_downloader->download(QUrl(QString::fromStdString(sha256_string)));
if (downloaded_sha256.size() > 64)
downloaded_sha256.truncate(64); // To account for newlines or other content.
sha256_string = QString(downloaded_sha256).toStdString();
}
mpl::log(mpl::Level::debug, category, fmt::format("Add SHA256 \"{}\" to image record", sha256_string));
vm_desc.image.id = sha256_string;
}
else
{
mpl::log(mpl::Level::debug, category, "No SHA256 to check");
}
}
else if (blueprint_instance["image"])
{
// This only supports the "alias" and "remote:alias" scheme at this time
auto image_str{blueprint_config[instances_key][blueprint_name]["image"].as<std::string>()};
auto tokens = mp::utils::split(image_str, ":");
if (tokens.size() == 2)
{
query.remote_name = tokens[0];
query.release = tokens[1];
}
else if (tokens.size() == 1)
{
query.release = tokens[0];
}
else
{
needs_update = true;
throw mp::InvalidBlueprintException("Unsupported image scheme in Blueprint");
}
}
if (blueprint_instance["limits"]["min-cpu"])
{
try
{
auto min_cpus = blueprint_instance["limits"]["min-cpu"].as<int>();
if (vm_desc.num_cores == 0)
{
vm_desc.num_cores = min_cpus;
}
else if (vm_desc.num_cores < min_cpus)
{
throw mp::BlueprintMinimumException("Number of CPUs", std::to_string(min_cpus));
}
}
catch (const YAML::BadConversion&)
{
needs_update = true;
throw mp::InvalidBlueprintException(fmt::format("Minimum CPU value in Blueprint is invalid"));
}
}
if (blueprint_instance["limits"]["min-mem"])
{
auto min_mem_size_str{blueprint_instance["limits"]["min-mem"].as<std::string>()};
try
{
mp::MemorySize min_mem_size{min_mem_size_str};
if (vm_desc.mem_size.in_bytes() == 0)
{
vm_desc.mem_size = min_mem_size;
}
else if (vm_desc.mem_size < min_mem_size)
{
throw mp::BlueprintMinimumException("Memory size", min_mem_size_str);
}
}
catch (const mp::InvalidMemorySizeException&)
{
needs_update = true;
throw mp::InvalidBlueprintException(fmt::format("Minimum memory size value in Blueprint is invalid"));
}
}
if (blueprint_instance["limits"]["min-disk"])
{
auto min_disk_space_str{blueprint_instance["limits"]["min-disk"].as<std::string>()};
try
{
mp::MemorySize min_disk_space{min_disk_space_str};
if (vm_desc.disk_space.in_bytes() == 0)
{
vm_desc.disk_space = min_disk_space;
}
else if (vm_desc.disk_space < min_disk_space)
{
throw mp::BlueprintMinimumException("Disk space", min_disk_space_str);
}
}
catch (const mp::InvalidMemorySizeException&)
{
needs_update = true;
throw mp::InvalidBlueprintException(fmt::format("Minimum disk space value in Blueprint is invalid"));
}
}
if (blueprint_instance["cloud-init"]["vendor-data"])
{
try
{
auto cloud_init_config = YAML::Load(blueprint_instance["cloud-init"]["vendor-data"].as<std::string>());
merge_yaml_entries(vm_desc.vendor_data_config, cloud_init_config, "vendor-data", true);
}
catch (const YAML::BadConversion&)
{
needs_update = true;
throw mp::InvalidBlueprintException(
fmt::format("Cannot convert cloud-init data for the {} Blueprint", blueprint_name));
}
}
auto blueprint_workspaces = blueprint_instance["workspace"];
if (blueprint_workspaces && blueprint_workspaces.as<bool>())
{
mpl::log(mpl::Level::trace, category, fmt::format("Add workspace {} to RPC answer", blueprint_name));
client_launch_data.workspaces_to_be_created.push_back(blueprint_name);
}
return query;
}
} // namespace
mp::DefaultVMBlueprintProvider::DefaultVMBlueprintProvider(const QUrl& blueprints_url, URLDownloader* downloader,
const QDir& archive_dir,
const std::chrono::milliseconds& blueprints_ttl,
const QString& arch)
: blueprints_url{blueprints_url},
url_downloader{downloader},
archive_file_path{archive_dir.filePath(github_blueprints_archive_name)},
blueprints_ttl{blueprints_ttl},
arch{arch}
{
update_blueprints();
}
mp::DefaultVMBlueprintProvider::DefaultVMBlueprintProvider(URLDownloader* downloader, const QDir& archive_dir,
const std::chrono::milliseconds& blueprints_ttl,
const QString& arch)
: DefaultVMBlueprintProvider(default_blueprint_url, downloader, archive_dir, blueprints_ttl, arch)
{
}
mp::Query mp::DefaultVMBlueprintProvider::fetch_blueprint_for(const std::string& blueprint_name,
VirtualMachineDescription& vm_desc,
ClientLaunchData& client_launch_data)
{
update_blueprints();
auto& blueprint_config = blueprint_map.at(blueprint_name);
return blueprint_from_yaml_node(blueprint_config, blueprint_name, vm_desc, client_launch_data, arch, url_downloader,
needs_update);
}
mp::Query mp::DefaultVMBlueprintProvider::blueprint_from_file(const std::string& path,
const std::string& blueprint_name,
VirtualMachineDescription& vm_desc,
ClientLaunchData& client_launch_data)
{
if (!MP_PLATFORM.is_image_url_supported())
throw std::runtime_error(fmt::format("Launching a Blueprint from a file is not supported"));
mpl::log(mpl::Level::debug, category, fmt::format("Reading Blueprint '{}' from file {}", blueprint_name, path));
QFileInfo file_info{QString::fromStdString(path)};
if (!mp::utils::valid_hostname(blueprint_name))
{
auto error_message =
fmt::format("Invalid Blueprint name \'{}\': must be a valid host name", file_info.baseName());
mpl::log(mpl::Level::error, category, error_message);
throw InvalidBlueprintException(error_message);
}
YAML::Node blueprint_config;
try
{
blueprint_config = YAML::LoadFile(path);
}
catch (const YAML::BadFile&)
{
throw InvalidBlueprintException(fmt::format("Wrong file \'{}\'", path));
}
return blueprint_from_yaml_node(blueprint_config, blueprint_name, vm_desc, client_launch_data, arch, url_downloader,
needs_update);
}
std::optional<mp::VMImageInfo> mp::DefaultVMBlueprintProvider::info_for(const std::string& blueprint_name)
{
update_blueprints();
static constexpr auto missing_key_template{"The \'{}\' key is required for the {} Blueprint"};
YAML::Node blueprint_config;
if (auto it = blueprint_map.find(blueprint_name); it != blueprint_map.end())
blueprint_config = it->second;
else
return std::nullopt;
VMImageInfo image_info;
image_info.aliases.append(QString::fromStdString(blueprint_name));
const auto description_key{"description"};
const auto version_key{"version"};
if (!blueprint_config[description_key])
{
needs_update = true;
throw InvalidBlueprintException(fmt::format(missing_key_template, description_key, blueprint_name));
}
if (!blueprint_config[version_key])
{
needs_update = true;
throw InvalidBlueprintException(fmt::format(missing_key_template, version_key, blueprint_name));
}
try
{
image_info.release_title = QString::fromStdString(blueprint_config[description_key].as<std::string>());
}
catch (const YAML::BadConversion&)
{
needs_update = true;
throw InvalidBlueprintException(fmt::format(bad_conversion_template, description_key, blueprint_name));
}
try
{
image_info.version = QString::fromStdString(blueprint_config["version"].as<std::string>());
}
catch (const YAML::BadConversion&)
{
needs_update = true;
throw InvalidBlueprintException(fmt::format(bad_conversion_template, version_key, blueprint_name));
}
return image_info;
}
std::vector<mp::VMImageInfo> mp::DefaultVMBlueprintProvider::all_blueprints()
{
update_blueprints();
bool will_need_update{false};
std::vector<VMImageInfo> blueprint_info;
for (const auto& [key, config] : blueprint_map)
{
try
{
auto info = info_for(key);
assert(info && "key missing from blueprint map");
blueprint_info.push_back(*info);
}
catch (const InvalidBlueprintException& e)
{
// Don't force updates in info_for() since we are looping and only force the update once we
// finish iterating.
needs_update = false;
will_need_update = true;
mpl::log(mpl::Level::error, category, fmt::format("Invalid Blueprint: {}", e.what()));
}
catch (const IncompatibleBlueprintException& e)
{
mpl::log(mpl::Level::trace, category, fmt::format("Skipping incompatible Blueprint: {}", e.what()));
}
}
if (will_need_update)
needs_update = true;
return blueprint_info;
}
std::string mp::DefaultVMBlueprintProvider::name_from_blueprint(const std::string& blueprint_name)
{
if (blueprint_map.count(blueprint_name) == 1)
return blueprint_name;
auto name_qstr = QString::fromStdString(blueprint_name);
if (name_qstr.startsWith("file://") &&
(name_qstr.toLower().endsWith(".yaml") || name_qstr.toLower().endsWith(".yml")))
{
auto file_path = name_qstr.remove(0, 7);
auto chop = file_path.at(file_path.size() - 4) == '.' ? 4 : 5;
return QFileInfo(file_path).fileName().chopped(chop).toStdString();
}
return {};
}
int mp::DefaultVMBlueprintProvider::blueprint_timeout(const std::string& blueprint_name)
{
auto timeout_seconds{0};
try
{
blueprint_map.at(blueprint_name);
auto& blueprint_config = blueprint_map.at(blueprint_name);
auto blueprint_instance = blueprint_config[instances_key][blueprint_name];
if (blueprint_instance["timeout"])
{
try
{
timeout_seconds = blueprint_instance["timeout"].as<int>();
}
catch (const YAML::BadConversion&)
{
needs_update = true;
throw InvalidBlueprintException(fmt::format("Invalid timeout given in Blueprint"));
}
}
}
catch (const std::out_of_range&)
{
// Ignore
}
return timeout_seconds;
}
void mp::DefaultVMBlueprintProvider::fetch_blueprints()
{
url_downloader->download_to(blueprints_url, archive_file_path, -1, -1, [](auto...) { return true; });
blueprint_map = blueprints_map_for(archive_file_path.toStdString(), needs_update, arch.toStdString());
}
void mp::DefaultVMBlueprintProvider::update_blueprints()
{
const auto now = std::chrono::steady_clock::now();
if ((now - last_update) > blueprints_ttl || needs_update)
{
try
{
fetch_blueprints();
last_update = now;
needs_update = false;
}
catch (const Poco::Exception& e)
{
mpl::log(mpl::Level::error, category,
fmt::format("Error extracting Blueprints zip file: {}", e.displayText()));
}
catch (const DownloadException& e)
{
mpl::log(mpl::Level::error, category, fmt::format("Error fetching Blueprints: {}", e.what()));
}
}
}
| 22,879
|
C++
|
.cpp
| 540
| 31.724074
| 120
| 0.583663
|
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,715
|
platform_linux.cpp
|
canonical_multipass/src/platform/platform_linux.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/constants.h>
#include <multipass/exceptions/autostart_setup_exception.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <multipass/settings/settings.h>
#include <multipass/snap_utils.h>
#include <multipass/standard_paths.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine_factory.h>
#include "backends/libvirt/libvirt_virtual_machine_factory.h"
#include "backends/lxd/lxd_virtual_machine_factory.h"
#ifdef QEMU_ENABLED
#include "backends/qemu/qemu_virtual_machine_factory.h"
#else
#define QEMU_ENABLED 0
#endif
#ifdef MULTIPASS_JOURNALD_ENABLED
#include "logger/journald_logger.h"
#else
#include "logger/syslog_logger.h"
#endif
#include "platform_linux_detail.h"
#include "platform_shared.h"
#include "shared/linux/process_factory.h"
#include "shared/sshfs_server_process_spec.h"
#include <disabled_update_prompt.h>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QRegularExpression>
#include <QString>
#include <QTextStream>
#include <errno.h>
#include <linux/if_arp.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "Linux platform";
constexpr auto br_nomenclature = "bridge";
// Fetch the ARP protocol HARDWARE identifier.
int get_net_type(const QDir& net_dir) // types defined in if_arp.h
{
static constexpr auto default_ret = -1;
static const auto type_filename = QStringLiteral("type");
QFile type_file{net_dir.filePath(type_filename)};
if (type_file.open(QIODevice::ReadOnly | QIODevice::Text))
{
bool ok;
auto got = QTextStream{&type_file}.read(6).toInt(&ok); // 6 chars enough for up to 0xFFFF; 0 returned on failure
return ok ? got : default_ret;
}
auto snap_hint = mpu::in_multipass_snap() ? " Is the 'network-observe' snap interface connected?" : "";
mpl::log(mpl::Level::warning, category, fmt::format("Could not read {}.{}", type_file.fileName(), snap_hint));
return default_ret;
}
// device types found in Linux source (in drivers/net/): PHY, bareudp, bond, geneve, gtp, macsec, ppp, vxlan, wlan, wwan
// should be empty for ethernet
QString get_net_devtype(const QDir& net_dir)
{
static constexpr auto max_read = 5000;
static const auto uevent_filename = QStringLiteral("uevent");
static const auto devtype_regex =
QRegularExpression{QStringLiteral("^DEVTYPE=(.*)$"), QRegularExpression::MultilineOption};
QFile uevent_file{net_dir.filePath(uevent_filename)};
if (uevent_file.open(QIODevice::ReadOnly | QIODevice::Text))
{
auto contents = QTextStream{&uevent_file}.read(max_read);
return devtype_regex.match(contents).captured(1);
}
mpl::log(mpl::Level::warning, category, fmt::format("Could not read {}", uevent_file.fileName()));
return {};
}
bool is_virtual_net(const QDir& net_dir)
{
static const auto virtual_dir = QStringLiteral("virtual");
return net_dir.canonicalPath().contains(virtual_dir, Qt::CaseInsensitive);
}
bool is_ethernet(const QDir& net_dir)
{
static const auto wireless = QStringLiteral("wireless");
return !is_virtual_net(net_dir) && !net_dir.exists(wireless) && get_net_type(net_dir) == ARPHRD_ETHER &&
get_net_devtype(net_dir).isEmpty();
}
std::optional<mp::NetworkInterfaceInfo> get_network(const QDir& net_dir)
{
static const auto bridge_fname = QStringLiteral("brif");
auto id = net_dir.dirName().toStdString();
if (net_dir.exists(br_nomenclature))
{
std::vector<std::string> links;
QStringList bridge_members = QDir{net_dir.filePath(bridge_fname)}.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
links.reserve(bridge_members.size());
std::transform(bridge_members.cbegin(), bridge_members.cend(), std::back_inserter(links),
[](const QString& interface) { return interface.toStdString(); });
return {{std::move(id),
br_nomenclature,
/*description=*/"",
std::move(links)}}; // description needs updating with links
}
else if (is_ethernet(net_dir))
return {{std::move(id), "ethernet", "Ethernet device"}};
return std::nullopt;
}
void update_bridges(std::map<std::string, mp::NetworkInterfaceInfo>& networks)
{
for (auto& item : networks)
{
if (auto& net = item.second; net.type == br_nomenclature)
{ // bridge descriptions and links depend on what other networks we recognized
auto& links = net.links;
auto is_unknown = [&networks](const std::string& id) {
auto same_as = [&id](const auto& other) { return other.first == id; };
return std::find_if(networks.cbegin(), networks.cend(), same_as) == networks.cend();
};
links.erase(std::remove_if(links.begin(), links.end(), is_unknown),
links.end()); // filter links to networks we don't recognize
net.description =
links.empty() ? "Network bridge"
: fmt::format("Network bridge with {}", fmt::join(links.cbegin(), links.cend(), ", "));
}
}
}
std::string get_alias_script_path(const std::string& alias)
{
auto aliases_folder = MP_PLATFORM.get_alias_scripts_folder();
return aliases_folder.absoluteFilePath(QString::fromStdString(alias)).toStdString();
}
} // namespace
std::unique_ptr<QFile> multipass::platform::detail::find_os_release()
{
const std::array<QString, 3> options{QStringLiteral("/var/lib/snapd/hostfs/etc/os-release"),
QStringLiteral("/var/lib/snapd/hostfs/usr/lib/os-release"),
QStringLiteral("")};
auto it = options.cbegin();
auto ret = std::make_unique<QFile>(*it);
while (++it != options.cend() && !MP_FILEOPS.open(*ret, QIODevice::ReadOnly | QIODevice::Text))
ret->setFileName(*it);
return ret;
}
std::pair<QString, QString> multipass::platform::detail::parse_os_release(const QStringList& os_data)
{
const QString id_field = "NAME";
const QString version_field = "VERSION_ID";
QString distro_id = "unknown";
QString distro_rel = "unknown";
auto strip_quotes = [](const QString& val) -> QString { return val.mid(1, val.length() - 2); };
for (const QString& line : os_data)
{
QStringList split = line.split('=', Qt::KeepEmptyParts);
if (split.length() == 2 && split[1].length() > 2) // Check for at least 1 char between quotes.
{
if (split[0] == id_field)
distro_id = strip_quotes(split[1]);
else if (split[0] == version_field)
distro_rel = strip_quotes(split[1]);
}
}
return std::pair(distro_id, distro_rel);
}
std::string multipass::platform::detail::read_os_release()
{
std::unique_ptr<QFile> os_release = find_os_release();
QStringList os_info;
if (MP_FILEOPS.is_open(*os_release))
{
QTextStream input(os_release.get());
QString line = MP_FILEOPS.read_line(input);
while (!line.isNull())
{
os_info.append(line);
line = MP_FILEOPS.read_line(input);
}
os_release->close();
auto parsed = parse_os_release(os_info);
return fmt::format("{}-{}", parsed.first, parsed.second);
}
return "unknown-unknown";
}
std::map<std::string, mp::NetworkInterfaceInfo> mp::platform::Platform::get_network_interfaces_info() const
{
static const auto sysfs = QDir{QStringLiteral("/sys/class/net")};
return detail::get_network_interfaces_from(sysfs);
}
QString mp::platform::Platform::get_blueprints_url_override() const
{
return QString::fromUtf8(qgetenv("MULTIPASS_BLUEPRINTS_URL"));
}
bool mp::platform::Platform::is_alias_supported(const std::string& alias, const std::string& remote) const
{
if (remote == mp::snapcraft_remote)
{
return supported_snapcraft_aliases.find(alias) != supported_snapcraft_aliases.end();
}
return true;
}
bool mp::platform::Platform::is_remote_supported(const std::string& remote) const
{
return true;
}
bool mp::platform::Platform::is_backend_supported(const QString& backend) const
{
return (backend == "qemu" && QEMU_ENABLED) || backend == "libvirt" || backend == "lxd";
}
bool mp::platform::Platform::link(const char* target, const char* link) const
{
return ::link(target, link) == 0;
}
QDir mp::platform::Platform::get_alias_scripts_folder() const
{
QDir aliases_folder;
if (mpu::in_multipass_snap())
{
aliases_folder = QDir(QString(mpu::snap_user_common_dir()) + "/bin");
}
else
{
QString location = MP_STDPATHS.writableLocation(mp::StandardPaths::AppLocalDataLocation) + "/bin";
aliases_folder = QDir{location};
}
return aliases_folder;
}
void mp::platform::Platform::create_alias_script(const std::string& alias, const mp::AliasDefinition& def) const
{
std::string file_path = get_alias_script_path(alias);
std::string multipass_exec = mpu::in_multipass_snap()
? "exec /usr/bin/snap run multipass"
: fmt::format("\"{}\"", QCoreApplication::applicationFilePath());
std::string script = "#!/bin/sh\n\n" + multipass_exec + " " + alias + " -- \"${@}\"\n";
MP_UTILS.make_file_with_content(file_path, script, true);
QFile file(QString::fromStdString(file_path));
auto permissions =
MP_FILEOPS.permissions(file) | QFileDevice::ExeOwner | QFileDevice::ExeGroup | QFileDevice::ExeOther;
if (!MP_FILEOPS.setPermissions(file, permissions))
throw std::runtime_error(fmt::format("cannot set permissions to alias script '{}'", file_path));
}
void mp::platform::Platform::remove_alias_script(const std::string& alias) const
{
auto file_path = get_alias_script_path(alias);
if (::unlink(file_path.c_str()))
throw std::runtime_error(strerror(errno));
}
auto mp::platform::Platform::extra_daemon_settings() const -> SettingSpec::Set
{
return {};
}
auto mp::platform::Platform::extra_client_settings() const -> SettingSpec::Set
{
return {};
}
QString mp::platform::Platform::daemon_config_home() const // temporary
{
auto ret = QString{qgetenv("DAEMON_CONFIG_HOME")};
if (ret.isEmpty())
ret = QStringLiteral("/root/.config");
ret = QDir{ret}.absoluteFilePath(mp::daemon_name);
return ret;
}
QString mp::platform::Platform::default_driver() const
{
if (QEMU_ENABLED)
return QStringLiteral("qemu");
else
return QStringLiteral("lxd");
}
QString mp::platform::Platform::default_privileged_mounts() const
{
return QStringLiteral("true");
}
bool mp::platform::Platform::is_image_url_supported() const
{
return true;
}
std::string mp::platform::Platform::bridge_nomenclature() const
{
return br_nomenclature;
}
auto mp::platform::detail::get_network_interfaces_from(const QDir& sys_dir)
-> std::map<std::string, NetworkInterfaceInfo>
{
auto ifaces_info = std::map<std::string, mp::NetworkInterfaceInfo>();
for (const auto& entry : sys_dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs))
{
if (auto iface = get_network(QDir{sys_dir.filePath(entry)}); iface)
{
auto name = iface->id; // (can't rely on param evaluation order)
ifaces_info.emplace(std::move(name), std::move(*iface));
}
}
update_bridges(ifaces_info);
return ifaces_info;
}
QString mp::platform::interpret_setting(const QString& key, const QString& val)
{
// this should not happen (settings should have found it to be an invalid key)
throw InvalidSettingException(key, val, "Setting unavailable on Linux");
}
void mp::platform::sync_winterm_profiles()
{
// NOOP on Linux
}
std::string mp::platform::default_server_address()
{
std::string base_dir;
try
{
// if Snap, client and daemon can both access $SNAP_COMMON so can put socket there
base_dir = mpu::snap_common_dir().toStdString();
}
catch (const mp::SnapEnvironmentException&)
{
base_dir = "/run";
}
return "unix:" + base_dir + "/multipass_socket";
}
mp::VirtualMachineFactory::UPtr mp::platform::vm_backend(const mp::Path& data_dir)
{
const auto& driver = MP_SETTINGS.get(mp::driver_key);
#if QEMU_ENABLED
if (driver == QStringLiteral("qemu"))
return std::make_unique<QemuVirtualMachineFactory>(data_dir);
#endif
if (driver == QStringLiteral("libvirt"))
return std::make_unique<LibVirtVirtualMachineFactory>(data_dir);
if (driver == QStringLiteral("lxd"))
return std::make_unique<LXDVirtualMachineFactory>(data_dir);
throw std::runtime_error(fmt::format("Unsupported virtualization driver: {}", driver));
}
std::unique_ptr<mp::Process> mp::platform::make_sshfs_server_process(const mp::SSHFSServerConfig& config)
{
return MP_PROCFACTORY.create_process(std::make_unique<mp::SSHFSServerProcessSpec>(config));
}
std::unique_ptr<mp::Process> mp::platform::make_process(std::unique_ptr<mp::ProcessSpec>&& process_spec)
{
return MP_PROCFACTORY.create_process(std::move(process_spec));
}
mp::UpdatePrompt::UPtr mp::platform::make_update_prompt()
{
return std::make_unique<DisabledUpdatePrompt>();
}
mp::logging::Logger::UPtr mp::platform::make_logger(mp::logging::Level level)
{
#if MULTIPASS_JOURNALD_ENABLED
return std::make_unique<logging::JournaldLogger>(level);
#else
return std::make_unique<logging::SyslogLogger>(level);
#endif
}
std::string mp::platform::reinterpret_interface_id(const std::string& ux_id)
{
return ux_id;
}
std::string multipass::platform::host_version()
{
return mpu::in_multipass_snap() ? multipass::platform::detail::read_os_release()
: fmt::format("{}-{}", QSysInfo::productType(), QSysInfo::productVersion());
}
| 14,962
|
C++
|
.cpp
| 383
| 34.130548
| 120
| 0.679799
|
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,716
|
platform_unix.cpp
|
canonical_multipass/src/platform/platform_unix.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/format.h>
#include <multipass/platform.h>
#include <multipass/platform_unix.h>
#include <multipass/utils.h>
#include <grp.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <libssh/sftp.h>
namespace mp = multipass;
namespace
{
const std::vector<std::string> supported_socket_groups{"sudo", "admin", "wheel"};
sftp_attributes_struct stat_to_attr(const struct stat* st)
{
sftp_attributes_struct attr{};
attr.size = st->st_size;
attr.uid = st->st_uid;
attr.gid = st->st_gid;
attr.flags =
SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_UIDGID | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME;
attr.atime = st->st_atime;
attr.mtime = st->st_mtime;
attr.permissions = st->st_mode;
return attr;
}
} // namespace
int mp::platform::Platform::chown(const char* path, unsigned int uid, unsigned int gid) const
{
return ::lchown(path, uid, gid);
}
int mp::platform::Platform::chmod(const char* path, unsigned int mode) const
{
return ::chmod(path, mode);
}
bool mp::platform::Platform::set_permissions(const mp::Path path, const QFileDevice::Permissions permissions) const
{
return QFile::setPermissions(path, permissions);
}
bool mp::platform::Platform::symlink(const char* target, const char* link, bool is_dir) const
{
return ::symlink(target, link) == 0;
}
int mp::platform::Platform::utime(const char* path, int atime, int mtime) const
{
struct timeval tv[2];
tv[0].tv_sec = atime;
tv[0].tv_usec = 0;
tv[1].tv_sec = mtime;
tv[1].tv_usec = 0;
return ::lutimes(path, tv);
}
QString mp::platform::Platform::get_username() const
{
return {};
}
std::string mp::platform::Platform::alias_path_message() const
{
return fmt::format("You'll need to add this to your shell configuration (.bashrc, .zshrc or so) for\n"
"aliases to work without prefixing with `multipass`:\n\nPATH=\"$PATH:{}\"\n",
get_alias_scripts_folder().absolutePath());
}
void mp::platform::Platform::set_server_socket_restrictions(const std::string& server_address,
const bool restricted) const
{
auto tokens = mp::utils::split(server_address, ":");
if (tokens.size() != 2u)
throw std::runtime_error(fmt::format("invalid server address specified: {}", server_address));
const auto schema = tokens[0];
if (schema != "unix")
return;
int gid{0};
int mode{S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP};
if (restricted)
{
for (const auto& socket_group : supported_socket_groups)
{
auto group = getgrnam(socket_group.c_str());
if (group)
{
gid = group->gr_gid;
break;
}
}
}
else
{
mode |= S_IROTH | S_IWOTH;
}
const auto socket_path = tokens[1];
if (chown(socket_path.c_str(), 0, gid) == -1)
throw std::runtime_error(fmt::format("Could not set ownership of the multipass socket: {}", strerror(errno)));
if (chmod(socket_path.c_str(), mode) == -1)
throw std::runtime_error(
fmt::format("Could not set permissions for the multipass socket: {}", strerror(errno)));
}
QString mp::platform::Platform::multipass_storage_location() const
{
return mp::utils::get_multipass_storage();
}
int mp::platform::symlink_attr_from(const char* path, sftp_attributes_struct* attr)
{
struct stat st
{
};
auto ret = lstat(path, &st);
if (ret < 0)
return ret;
*attr = stat_to_attr(&st);
return 0;
}
sigset_t mp::platform::make_sigset(const std::vector<int>& sigs)
{
sigset_t sigset;
sigemptyset(&sigset);
for (auto signal : sigs)
{
sigaddset(&sigset, signal);
}
return sigset;
}
sigset_t mp::platform::make_and_block_signals(const std::vector<int>& sigs)
{
auto sigset{make_sigset(sigs)};
pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
return sigset;
}
std::function<int()> mp::platform::make_quit_watchdog()
{
return [sigset = make_and_block_signals({SIGQUIT, SIGTERM, SIGHUP})]() {
int sig = -1;
sigwait(&sigset, &sig);
return sig;
};
}
| 4,901
|
C++
|
.cpp
| 150
| 27.813333
| 120
| 0.654156
|
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,717
|
console.cpp
|
canonical_multipass/src/platform/console/console.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/console.h>
#include <multipass/terminal.h>
#include "unix_console.h"
#include "unix_terminal.h"
namespace mp = multipass;
mp::Console::UPtr mp::Console::make_console(ssh_channel channel, Terminal* term)
{
return std::make_unique<UnixConsole>(channel, static_cast<UnixTerminal*>(term));
}
void mp::Console::setup_environment()
{
UnixConsole::setup_environment();
}
| 1,025
|
C++
|
.cpp
| 29
| 33.37931
| 84
| 0.756811
|
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,718
|
terminal.cpp
|
canonical_multipass/src/platform/console/terminal.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 "unix_terminal.h"
#include <multipass/terminal.h>
#include <iostream>
namespace mp = multipass;
/* Note on connection between std::cin/cout/cerr and stdin/out/err
*
* std::cin/cout/cerr create an i/ostream wrapping around stdin/out/err,
* but I'm unable to find a cross-platform way to get the FD corresponding
* to the std library api.
*
* Therefore the mix of std C++ and C apis here is an unfortunate but IMO
* least worst way of doing what we need.
*/
mp::Terminal::UPtr mp::Terminal::make_terminal()
{
return std::make_unique<UnixTerminal>();
}
std::istream& mp::Terminal::cin()
{
return std::cin;
}
std::ostream& mp::Terminal::cout()
{
return std::cout;
}
std::ostream& mp::Terminal::cerr()
{
return std::cerr;
}
bool mp::Terminal::is_live() const
{
return cin_is_live() && cout_is_live();
}
std::string mp::Terminal::read_all_cin()
{
std::string content;
char arr[1024];
while (!cin().eof())
{
cin().read(arr, sizeof(arr));
int s = cin().gcount();
content.append(arr, s);
}
return content;
}
| 1,721
|
C++
|
.cpp
| 61
| 25.57377
| 74
| 0.70321
|
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,719
|
unix_console.cpp
|
canonical_multipass/src/platform/console/unix_console.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 "unix_console.h"
#include <multipass/platform_unix.h>
#include <sys/ioctl.h>
#include <cstdlib>
namespace mp = multipass;
namespace
{
mp::Console::ConsoleGeometry local_pty_size{0, 0};
ssh_channel global_channel;
int global_cout_fd;
bool update_local_pty_size(int cout_fd)
{
struct winsize win = {0, 0, 0, 0};
ioctl(cout_fd, TIOCGWINSZ, &win);
bool local_pty_size_changed = local_pty_size.rows != win.ws_row || local_pty_size.columns != win.ws_col;
if (local_pty_size_changed)
{
local_pty_size.rows = win.ws_row;
local_pty_size.columns = win.ws_col;
}
return local_pty_size_changed;
}
static void sigwinch_handler(int sig)
{
if (sig == SIGWINCH)
{
if (update_local_pty_size(global_cout_fd))
{
ssh_channel_change_pty_size(global_channel, local_pty_size.columns, local_pty_size.rows);
}
}
}
} // namespace
mp::UnixConsole::UnixConsole(ssh_channel channel, UnixTerminal* term) : term{term}
{
global_channel = channel;
global_cout_fd = term->cout_fd();
sigemptyset(&winch_action.sa_mask);
winch_action.sa_flags = 0;
winch_action.sa_handler = sigwinch_handler;
sigaction(SIGWINCH, &winch_action, nullptr);
if (term->is_live())
{
setup_console();
const char* term_type = std::getenv("TERM");
term_type = (term_type == nullptr) ? "xterm" : term_type;
update_local_pty_size(term->cout_fd());
ssh_channel_request_pty_size(channel, term_type, local_pty_size.columns, local_pty_size.rows);
}
}
mp::UnixConsole::~UnixConsole()
{
if (term->is_live())
{
restore_console();
}
}
void mp::UnixConsole::setup_environment()
{
}
void mp::UnixConsole::setup_console()
{
struct termios terminal_local;
tcgetattr(term->cin_fd(), &terminal_local);
saved_terminal = terminal_local;
cfmakeraw(&terminal_local);
tcsetattr(term->cin_fd(), TCSANOW, &terminal_local);
}
void mp::UnixConsole::restore_console()
{
tcsetattr(term->cin_fd(), TCSANOW, &saved_terminal);
}
| 2,707
|
C++
|
.cpp
| 88
| 26.943182
| 108
| 0.687452
|
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,720
|
unix_terminal.cpp
|
canonical_multipass/src/platform/console/unix_terminal.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 "unix_terminal.h"
#include <iostream>
#include <termios.h>
#include <unistd.h>
namespace mp = multipass;
int mp::UnixTerminal::cin_fd() const
{
return fileno(stdin);
}
bool mp::UnixTerminal::cin_is_live() const
{
return (isatty(cin_fd()) == 1);
}
int mp::UnixTerminal::cout_fd() const
{
return fileno(stdout);
}
bool mp::UnixTerminal::cout_is_live() const
{
return (isatty(cout_fd()) == 1);
}
void mp::UnixTerminal::set_cin_echo(const bool enable)
{
struct termios tty;
tcgetattr(cin_fd(), &tty);
if (!enable)
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
tcsetattr(cin_fd(), TCSANOW, &tty);
}
| 1,296
|
C++
|
.cpp
| 47
| 24.914894
| 72
| 0.706785
|
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,721
|
libvirt_virtual_machine.cpp
|
canonical_multipass/src/platform/backends/libvirt/libvirt_virtual_machine.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 "libvirt_virtual_machine.h"
#include <multipass/exceptions/start_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/memory_size.h>
#include <multipass/vm_status_monitor.h>
#include <shared/linux/backend_utils.h>
#include <shared/qemu_img_utils/qemu_img_utils.h>
#include <shared/shared_backend_utils.h>
#include <QXmlStreamReader>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
auto instance_mac_addr_for(virDomainPtr domain, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
std::string mac_addr;
std::unique_ptr<char, decltype(free)*> desc{libvirt_wrapper->virDomainGetXMLDesc(domain, 0), free};
QXmlStreamReader reader(desc.get());
while (!reader.atEnd())
{
reader.readNext();
if (reader.name() == QStringLiteral("mac"))
{
mac_addr = reader.attributes().value("address").toString().toStdString();
break;
}
}
return mac_addr;
}
auto instance_ip_for(const std::string& mac_addr, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
std::optional<mp::IPAddress> ip_address;
mp::LibVirtVirtualMachine::ConnectionUPtr connection{nullptr, nullptr};
try
{
connection = mp::LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
}
catch (const std::exception&)
{
return ip_address;
}
mp::LibVirtVirtualMachine::NetworkUPtr network{libvirt_wrapper->virNetworkLookupByName(connection.get(), "default"),
libvirt_wrapper->virNetworkFree};
virNetworkDHCPLeasePtr* leases = nullptr;
auto nleases = libvirt_wrapper->virNetworkGetDHCPLeases(network.get(), mac_addr.c_str(), &leases, 0);
auto leases_deleter = [&nleases, &libvirt_wrapper](virNetworkDHCPLeasePtr* leases) {
for (auto i = 0; i < nleases; ++i)
{
libvirt_wrapper->virNetworkDHCPLeaseFree(leases[i]);
}
free(leases);
};
std::unique_ptr<virNetworkDHCPLeasePtr, decltype(leases_deleter)> leases_ptr{leases, leases_deleter};
if (nleases > 0)
{
ip_address.emplace(leases[0]->ipaddr);
}
return ip_address;
}
auto host_architecture_for(virConnectPtr connection, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
std::string arch;
std::unique_ptr<char, decltype(free)*> capabilities{libvirt_wrapper->virConnectGetCapabilities(connection), free};
QXmlStreamReader reader(capabilities.get());
while (!reader.atEnd())
{
reader.readNext();
if (reader.name() == QStringLiteral("arch"))
{
arch = reader.readElementText().toStdString();
break;
}
}
return arch;
}
auto generate_xml_config_for(const mp::VirtualMachineDescription& desc, const std::string& bridge_name,
const std::string& arch)
{
static constexpr auto mem_unit = "k"; // see https://libvirt.org/formatdomain.html#elementsMemoryAllocation
const auto memory = desc.mem_size.in_kilobytes(); /* floored here, but then "[...] the value will be rounded up to
the nearest kibibyte by libvirt, and may be further rounded to the granularity supported by the hypervisor [...]" */
auto qemu_path = fmt::format("/usr/bin/qemu-system-{}", arch);
return fmt::format(
"<domain type=\'kvm\'>\n"
" <name>{}</name>\n"
" <memory unit=\'{}\'>{}</memory>\n"
" <currentMemory unit=\'{}\'>{}</currentMemory>\n"
" <vcpu placement=\'static\'>{}</vcpu>\n"
" <resource>\n"
" <partition>/machine</partition>\n"
" </resource>\n"
" <os>\n"
" <type arch=\'{}\'>hvm</type>\n"
" <boot dev=\'hd\'/>\n"
" </os>\n"
" <features>\n"
" <acpi/>\n"
" <apic/>\n"
" <vmport state=\'off\'/>\n"
" </features>\n"
" <cpu mode=\'host-passthrough\'>\n"
" </cpu>\n"
" <devices>\n"
" <emulator>{}</emulator>\n"
" <disk type=\'file\' device=\'disk\'>\n"
" <driver name=\'qemu\' type=\'qcow2\' discard=\'unmap\'/>\n"
" <source file=\'{}\'/>\n"
" <backingStore/>\n"
" <target dev=\'vda\' bus=\'virtio\'/>\n"
" <alias name=\'virtio-disk0\'/>\n"
" </disk>\n"
" <disk type=\'file\' device=\'disk\'>\n"
" <driver name=\'qemu\' type=\'raw\'/>\n"
" <source file=\'{}\'/>\n"
" <backingStore/>\n"
" <target dev=\'vdb\' bus=\'virtio\'/>\n"
" <alias name=\'virtio-disk1\'/>\n"
" </disk>\n"
" <interface type=\'bridge\'>\n"
" <mac address=\'{}\'/>\n"
" <source bridge=\'{}\'/>\n"
" <target dev=\'vnet0\'/>\n"
" <model type=\'virtio\'/>\n"
" <alias name=\'net0\'/>\n"
" </interface>\n"
" <serial type=\'pty\'>\n"
" <source path=\'/dev/pts/2\'/>\n"
" <target port=\"0\"/>\n"
" </serial>\n"
" <video>\n"
" <model type=\'qxl\' ram=\'65536\' vram=\'65536\' vgamem=\'16384\' heads=\'1\' primary=\'yes\'/>\n"
" <alias name=\'video0\'/>\n"
" </video>\n"
" </devices>\n"
"</domain>",
desc.vm_name, mem_unit, memory, mem_unit, memory, desc.num_cores, arch, qemu_path,
desc.image.image_path.toStdString(), desc.cloud_init_iso.toStdString(), desc.default_mac_address, bridge_name);
}
auto domain_by_name_for(const std::string& vm_name, virConnectPtr connection,
const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
mp::LibVirtVirtualMachine::DomainUPtr domain{libvirt_wrapper->virDomainLookupByName(connection, vm_name.c_str()),
libvirt_wrapper->virDomainFree};
return domain;
}
auto domain_by_definition_for(const mp::VirtualMachineDescription& desc, const std::string& bridge_name,
virConnectPtr connection, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
mp::LibVirtVirtualMachine::DomainUPtr domain{
libvirt_wrapper->virDomainDefineXML(
connection,
generate_xml_config_for(desc, bridge_name, host_architecture_for(connection, libvirt_wrapper)).c_str()),
libvirt_wrapper->virDomainFree};
return domain;
}
auto refresh_instance_state_for_domain(virDomainPtr domain, const mp::VirtualMachine::State& current_instance_state,
const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
auto domain_state{0};
if (!domain || libvirt_wrapper->virDomainGetState(domain, &domain_state, nullptr, 0) == -1 ||
domain_state == VIR_DOMAIN_NOSTATE)
return mp::VirtualMachine::State::unknown;
if (libvirt_wrapper->virDomainHasManagedSaveImage(domain, 0) == 1)
return mp::VirtualMachine::State::suspended;
// Most of these libvirt domain states don't have a Multipass instance state
// analogue, so we'll treat them as "off".
const auto domain_off_states = {VIR_DOMAIN_BLOCKED, VIR_DOMAIN_PAUSED, VIR_DOMAIN_SHUTDOWN,
VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_CRASHED, VIR_DOMAIN_PMSUSPENDED};
if (std::find(domain_off_states.begin(), domain_off_states.end(), domain_state) != domain_off_states.end())
return mp::VirtualMachine::State::off;
if (domain_state == VIR_DOMAIN_RUNNING && current_instance_state == mp::VirtualMachine::State::off)
return mp::VirtualMachine::State::running;
return current_instance_state;
}
bool domain_is_running(virDomainPtr domain, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
auto domain_state{0};
if (libvirt_wrapper->virDomainGetState(domain, &domain_state, nullptr, 0) == -1 ||
domain_state != VIR_DOMAIN_RUNNING)
return false;
return true;
}
template <typename Updater, typename Integer>
void update_max_and_property(virDomainPtr domain_ptr, Updater* fun_ptr, Integer new_value, unsigned int max_flag,
const std::string& property_name)
{
assert(domain_ptr);
int twice = 0;
unsigned int flags = VIR_DOMAIN_AFFECT_CONFIG | max_flag;
do
{
if (fun_ptr(domain_ptr, new_value, flags) < 0)
throw std::runtime_error(fmt::format("Could not update property: {}", property_name));
flags &= ~max_flag;
} while (!twice++); // first set the maximum, then actual
}
std::string management_ipv4_impl(std::optional<mp::IPAddress>& management_ip,
const std::string& mac_addr,
const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
if (!management_ip)
{
auto result = instance_ip_for(mac_addr, libvirt_wrapper);
if (result)
management_ip.emplace(result.value());
else
return "UNKNOWN";
}
return management_ip.value().as_string();
}
} // namespace
mp::LibVirtVirtualMachine::LibVirtVirtualMachine(const VirtualMachineDescription& desc,
const std::string& bridge_name,
VMStatusMonitor& monitor,
const LibvirtWrapper::UPtr& libvirt_wrapper,
const SSHKeyProvider& key_provider,
const Path& instance_dir)
: BaseVirtualMachine{desc.vm_name, key_provider, instance_dir},
username{desc.ssh_username},
desc{desc},
monitor{&monitor},
bridge_name{bridge_name},
libvirt_wrapper{libvirt_wrapper}
{
try
{
initialize_domain_info(open_libvirt_connection(libvirt_wrapper).get());
}
catch (const std::exception&)
{
state = VirtualMachine::State::unknown;
}
}
mp::LibVirtVirtualMachine::~LibVirtVirtualMachine()
{
update_suspend_status = false;
if (state == State::running)
suspend();
}
void mp::LibVirtVirtualMachine::start()
{
auto connection = open_libvirt_connection(libvirt_wrapper);
DomainUPtr domain{nullptr, nullptr};
if (state == VirtualMachine::State::unknown)
domain = initialize_domain_info(connection.get());
else
domain = domain_by_name_for(vm_name, connection.get(), libvirt_wrapper);
state = refresh_instance_state_for_domain(domain.get(), state, libvirt_wrapper);
if (state == State::suspended)
mpl::log(mpl::Level::info, vm_name, fmt::format("Resuming from a suspended state"));
state = State::starting;
update_state();
if (libvirt_wrapper->virDomainCreate(domain.get()) == -1)
{
state = State::suspended;
update_state();
std::string error_string{libvirt_wrapper->virGetLastErrorMessage()};
if (error_string.find("virtio-net-pci.rom: 0x80000 in != 0x40000") != std::string::npos)
{
error_string = fmt::format("Unable to start suspended instance due to incompatible save image.\n"
"Please use the following steps to recover:\n"
" 1. snap refresh multipass --channel core16/beta\n"
" 2. multipass start {}\n"
" 3. Save any data in the instance\n"
" 4. multipass stop {}\n"
" 5. snap refresh multipass --channel stable\n"
" 6. multipass start {}\n",
vm_name, vm_name, vm_name);
}
throw std::runtime_error(error_string);
}
monitor->on_resume();
}
void mp::LibVirtVirtualMachine::shutdown(ShutdownPolicy shutdown_policy)
{
std::unique_lock<std::mutex> lock{state_mutex};
auto domain = checked_vm_domain();
state = refresh_instance_state_for_domain(domain.get(), state, libvirt_wrapper);
try
{
check_state_for_shutdown(shutdown_policy);
}
catch (const VMStateIdempotentException& e)
{
mpl::log(mpl::Level::info, vm_name, e.what());
return;
}
if (shutdown_policy == ShutdownPolicy::Poweroff) // TODO delete suspension state if it exists
{
mpl::log(mpl::Level::info, vm_name, "Forcing shutdown");
libvirt_wrapper->virDomainDestroy(domain.get());
if (state == State::starting || state == State::restarting)
{
libvirt_wrapper->virDomainDestroy(domain.get());
state_wait.wait(lock, [this] { return shutdown_while_starting; });
}
}
else
{
drop_ssh_session();
if (libvirt_wrapper->virDomainShutdown(domain.get()) == -1)
{
auto warning_string{
fmt::format("Cannot shutdown '{}': {}", vm_name, libvirt_wrapper->virGetLastErrorMessage())};
mpl::log(mpl::Level::warning, vm_name, warning_string);
throw std::runtime_error(warning_string);
}
}
state = State::off;
update_state();
monitor->on_shutdown();
}
void mp::LibVirtVirtualMachine::suspend()
{
auto domain = domain_by_name_for(vm_name, open_libvirt_connection(libvirt_wrapper).get(), libvirt_wrapper);
state = refresh_instance_state_for_domain(domain.get(), state, libvirt_wrapper);
if (state == State::running || state == State::delayed_shutdown)
{
drop_ssh_session();
if (!domain || libvirt_wrapper->virDomainManagedSave(domain.get(), 0) < 0)
{
auto warning_string{
fmt::format("Cannot suspend '{}': {}", vm_name, libvirt_wrapper->virGetLastErrorMessage())};
mpl::log(mpl::Level::warning, vm_name, warning_string);
throw std::runtime_error(warning_string);
}
if (update_suspend_status)
{
state = State::suspended;
update_state();
}
}
else if (state == State::off)
{
mpl::log(mpl::Level::info, vm_name, fmt::format("Ignoring suspend issued while stopped"));
}
monitor->on_suspend();
}
mp::VirtualMachine::State mp::LibVirtVirtualMachine::current_state()
{
try
{
auto connection = open_libvirt_connection(libvirt_wrapper);
auto domain = domain_by_name_for(vm_name, connection.get(), libvirt_wrapper);
if (!domain)
initialize_domain_info(connection.get());
state = refresh_instance_state_for_domain(domain.get(), state, libvirt_wrapper);
}
catch (const std::exception&)
{
state = VirtualMachine::State::unknown;
}
return state;
}
int mp::LibVirtVirtualMachine::ssh_port()
{
return 22;
}
void mp::LibVirtVirtualMachine::ensure_vm_is_running()
{
auto is_vm_running = [this] {
auto domain = domain_by_name_for(vm_name, open_libvirt_connection(libvirt_wrapper).get(), libvirt_wrapper);
return domain_is_running(domain.get(), libvirt_wrapper);
};
mp::backend::ensure_vm_is_running_for(this, is_vm_running, "Instance failed to start");
}
std::string mp::LibVirtVirtualMachine::ssh_hostname(std::chrono::milliseconds timeout)
{
auto get_ip = [this]() -> std::optional<IPAddress> { return instance_ip_for(mac_addr, libvirt_wrapper); };
return mp::backend::ip_address_for(this, get_ip, timeout);
}
std::string mp::LibVirtVirtualMachine::ssh_username()
{
return username;
}
std::string mp::LibVirtVirtualMachine::management_ipv4()
{
return management_ipv4_impl(management_ip, mac_addr, libvirt_wrapper);
}
std::string mp::LibVirtVirtualMachine::ipv6()
{
return {};
}
void mp::LibVirtVirtualMachine::update_state()
{
monitor->persist_state_for(vm_name, state);
}
mp::LibVirtVirtualMachine::DomainUPtr mp::LibVirtVirtualMachine::initialize_domain_info(virConnectPtr connection)
{
auto domain = domain_by_name_for(vm_name, connection, libvirt_wrapper);
if (!domain)
{
domain = domain_by_definition_for(desc, bridge_name, connection, libvirt_wrapper);
}
if (mac_addr.empty())
mac_addr = instance_mac_addr_for(domain.get(), libvirt_wrapper);
management_ipv4_impl(management_ip, mac_addr, libvirt_wrapper); // To set the IP.
state = refresh_instance_state_for_domain(domain.get(), state, libvirt_wrapper);
return domain;
}
mp::LibVirtVirtualMachine::DomainUPtr mp::LibVirtVirtualMachine::checked_vm_domain() const
{
auto connection = open_libvirt_connection(libvirt_wrapper);
assert(connection && "should have thrown otherwise");
auto domain = domain_by_name_for(vm_name, connection.get(), libvirt_wrapper);
if (!domain)
throw std::runtime_error{
fmt::format("Could not obtain libvirt domain: {}", libvirt_wrapper->virGetLastErrorMessage())};
return domain;
}
mp::LibVirtVirtualMachine::ConnectionUPtr
mp::LibVirtVirtualMachine::open_libvirt_connection(const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
if (!libvirt_wrapper)
throw std::runtime_error("The libvirt library is not loaded. Please ensure libvirt is installed and running.");
mp::LibVirtVirtualMachine::ConnectionUPtr connection{libvirt_wrapper->virConnectOpen("qemu:///system"),
libvirt_wrapper->virConnectClose};
if (!connection)
{
throw std::runtime_error(
fmt::format("Cannot connect to libvirtd: {}\nPlease ensure libvirt is installed and running.",
libvirt_wrapper->virGetLastErrorMessage()));
}
return connection;
}
void mp::LibVirtVirtualMachine::update_cpus(int num_cores)
{
assert(num_cores > 0);
update_max_and_property(checked_vm_domain().get(), libvirt_wrapper->virDomainSetVcpusFlags, num_cores,
VIR_DOMAIN_VCPU_MAXIMUM, "CPUs");
desc.num_cores = num_cores;
}
void mp::LibVirtVirtualMachine::resize_memory(const MemorySize& new_size)
{
auto new_size_kb = new_size.in_kilobytes(); /* floored here */
update_max_and_property(checked_vm_domain().get(), libvirt_wrapper->virDomainSetMemoryFlags, new_size_kb,
VIR_DOMAIN_MEM_MAXIMUM, "memory");
desc.mem_size = new_size;
}
void mp::LibVirtVirtualMachine::resize_disk(const MemorySize& new_size)
{
assert(new_size > desc.disk_space);
mp::backend::resize_instance_image(new_size, desc.image.image_path);
desc.disk_space = new_size;
}
| 19,373
|
C++
|
.cpp
| 463
| 34.025918
| 120
| 0.623631
|
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,722
|
libvirt_virtual_machine_factory.cpp
|
canonical_multipass/src/platform/backends/libvirt/libvirt_virtual_machine_factory.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 "libvirt_virtual_machine_factory.h"
#include "libvirt_virtual_machine.h"
#include <multipass/logging/log.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine_description.h>
#include <shared/linux/backend_utils.h>
#include <shared/qemu_img_utils/qemu_img_utils.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto multipass_bridge_name = "mpvirtbr0";
constexpr auto logging_category = "libvirt factory";
auto generate_libvirt_bridge_xml_config(const mp::Path& data_dir, const std::string& bridge_name)
{
auto network_dir = MP_UTILS.make_dir(QDir(data_dir), "network");
auto subnet = MP_BACKEND.get_subnet(network_dir, QString::fromStdString(bridge_name));
return fmt::format("<network>\n"
" <name>default</name>\n"
" <bridge name=\"{}\"/>\n"
" <domain name=\"multipass\" localOnly=\"yes\"/>\n"
" <forward/>\n"
" <ip address=\"{}.1\" netmask=\"255.255.255.0\">\n"
" <dhcp>\n"
" <range start=\"{}.2\" end=\"{}.254\"/>\n"
" </dhcp>\n"
" </ip>\n"
"</network>",
bridge_name, subnet, subnet, subnet);
}
std::string enable_libvirt_network(const mp::Path& data_dir, const mp::LibvirtWrapper::UPtr& libvirt_wrapper)
{
mp::LibVirtVirtualMachine::ConnectionUPtr connection{nullptr, nullptr};
try
{
connection = mp::LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
}
catch (const std::exception&)
{
return {};
}
mp::LibVirtVirtualMachine::NetworkUPtr network{libvirt_wrapper->virNetworkLookupByName(connection.get(), "default"),
libvirt_wrapper->virNetworkFree};
std::string bridge_name;
if (network == nullptr)
{
bridge_name = multipass_bridge_name;
network = mp::LibVirtVirtualMachine::NetworkUPtr{
libvirt_wrapper->virNetworkCreateXML(connection.get(),
generate_libvirt_bridge_xml_config(data_dir, bridge_name).c_str()),
libvirt_wrapper->virNetworkFree};
}
else
{
auto libvirt_bridge = libvirt_wrapper->virNetworkGetBridgeName(network.get());
bridge_name = libvirt_bridge;
free(libvirt_bridge);
}
if (libvirt_wrapper->virNetworkIsActive(network.get()) == 0)
{
libvirt_wrapper->virNetworkCreate(network.get());
}
return bridge_name;
}
auto make_libvirt_wrapper(const std::string& libvirt_object_path)
{
try
{
return std::make_unique<mp::LibvirtWrapper>(libvirt_object_path);
}
catch (const mp::BaseLibvirtException& e)
{
mpl::log(mpl::Level::warning, logging_category, e.what());
return mp::LibvirtWrapper::UPtr(nullptr);
}
}
} // namespace
mp::LibVirtVirtualMachineFactory::LibVirtVirtualMachineFactory(const mp::Path& data_dir,
const std::string& libvirt_object_path)
: BaseVirtualMachineFactory(
MP_UTILS.derive_instances_dir(data_dir, get_backend_directory_name(), instances_subdir)),
libvirt_wrapper{make_libvirt_wrapper(libvirt_object_path)},
data_dir{data_dir},
bridge_name{enable_libvirt_network(data_dir, libvirt_wrapper)},
libvirt_object_path{libvirt_object_path}
{
}
mp::LibVirtVirtualMachineFactory::LibVirtVirtualMachineFactory(const mp::Path& data_dir)
: LibVirtVirtualMachineFactory(data_dir, "libvirt.so.0")
{
}
mp::VirtualMachine::UPtr mp::LibVirtVirtualMachineFactory::create_virtual_machine(const VirtualMachineDescription& desc,
const SSHKeyProvider& key_provider,
VMStatusMonitor& monitor)
{
if (bridge_name.empty())
bridge_name = enable_libvirt_network(data_dir, libvirt_wrapper);
return std::make_unique<mp::LibVirtVirtualMachine>(desc,
bridge_name,
monitor,
libvirt_wrapper,
key_provider,
get_instance_directory(desc.vm_name));
}
mp::LibVirtVirtualMachineFactory::~LibVirtVirtualMachineFactory()
{
if (bridge_name == multipass_bridge_name)
{
auto connection = LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
mp::LibVirtVirtualMachine::NetworkUPtr network{
libvirt_wrapper->virNetworkLookupByName(connection.get(), "default"), libvirt_wrapper->virNetworkFree};
libvirt_wrapper->virNetworkDestroy(network.get());
}
}
void mp::LibVirtVirtualMachineFactory::remove_resources_for_impl(const std::string& name)
{
auto connection = LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
libvirt_wrapper->virDomainUndefine(libvirt_wrapper->virDomainLookupByName(connection.get(), name.c_str()));
}
mp::VMImage mp::LibVirtVirtualMachineFactory::prepare_source_image(const VMImage& source_image)
{
VMImage image{source_image};
image.image_path = mp::backend::convert_to_qcow_if_necessary(source_image.image_path);
return image;
}
void mp::LibVirtVirtualMachineFactory::prepare_instance_image(const VMImage& instance_image,
const VirtualMachineDescription& desc)
{
mp::backend::resize_instance_image(desc.disk_space, instance_image.image_path);
}
void mp::LibVirtVirtualMachineFactory::hypervisor_health_check()
{
MP_BACKEND.check_for_kvm_support();
MP_BACKEND.check_if_kvm_is_in_use();
if (!libvirt_wrapper)
libvirt_wrapper = make_libvirt_wrapper(libvirt_object_path);
LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
if (bridge_name.empty())
bridge_name = enable_libvirt_network(data_dir, libvirt_wrapper);
}
QString mp::LibVirtVirtualMachineFactory::get_backend_version_string() const
{
try
{
unsigned long libvirt_version;
auto connection = LibVirtVirtualMachine::open_libvirt_connection(libvirt_wrapper);
if (libvirt_wrapper->virConnectGetVersion(connection.get(), &libvirt_version) == 0 && libvirt_version != 0)
{
return QString("libvirt-%1.%2.%3")
.arg(libvirt_version / 1000000)
.arg(libvirt_version / 1000 % 1000)
.arg(libvirt_version % 1000);
}
}
catch (const std::exception&)
{
// Ignore
}
mpl::log(mpl::Level::error, logging_category, "Failed to determine libvirtd version.");
return QString("libvirt-unknown");
}
| 7,702
|
C++
|
.cpp
| 178
| 33.88764
| 120
| 0.632106
|
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,723
|
libvirt_wrapper.cpp
|
canonical_multipass/src/platform/backends/libvirt/libvirt_wrapper.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 "libvirt_wrapper.h"
#include <dlfcn.h>
namespace mp = multipass;
namespace
{
auto open_libvirt_handle(const std::string& filename)
{
// If filename is empty, it's for testing, ie, opening the test executable itself
auto handle = dlopen(filename.empty() ? nullptr : filename.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (!handle)
throw mp::LibvirtOpenException(dlerror());
return handle;
}
auto get_symbol_address_for(const std::string& symbol, void* handle)
{
auto address = dlsym(handle, symbol.c_str());
if (!address)
{
std::string error{dlerror()};
dlclose(handle);
throw mp::LibvirtSymbolAddressException(symbol, error.c_str());
}
return address;
}
} // namespace
mp::LibvirtWrapper::LibvirtWrapper(const std::string& filename)
: handle{open_libvirt_handle(filename)},
virConnectOpen{reinterpret_cast<virConnectOpen_t>(get_symbol_address_for("virConnectOpen", handle))},
virConnectClose{reinterpret_cast<virConnectClose_t>(get_symbol_address_for("virConnectClose", handle))},
virConnectGetCapabilities{
reinterpret_cast<virConnectGetCapabilities_t>(get_symbol_address_for("virConnectGetCapabilities", handle))},
virConnectGetVersion{
reinterpret_cast<virConnectGetVersion_t>(get_symbol_address_for("virConnectGetVersion", handle))},
virNetworkLookupByName{
reinterpret_cast<virNetworkLookupByName_t>(get_symbol_address_for("virNetworkLookupByName", handle))},
virNetworkCreateXML{
reinterpret_cast<virNetworkCreateXML_t>(get_symbol_address_for("virNetworkCreateXML", handle))},
virNetworkDestroy{reinterpret_cast<virNetworkDestroy_t>(get_symbol_address_for("virNetworkDestroy", handle))},
virNetworkFree{reinterpret_cast<virNetworkFree_t>(get_symbol_address_for("virNetworkFree", handle))},
virNetworkGetBridgeName{
reinterpret_cast<virNetworkGetBridgeName_t>(get_symbol_address_for("virNetworkGetBridgeName", handle))},
virNetworkIsActive{reinterpret_cast<virNetworkIsActive_t>(get_symbol_address_for("virNetworkIsActive", handle))},
virNetworkCreate{reinterpret_cast<virNetworkCreate_t>(get_symbol_address_for("virNetworkCreate", handle))},
virNetworkGetDHCPLeases{
reinterpret_cast<virNetworkGetDHCPLeases_t>(get_symbol_address_for("virNetworkGetDHCPLeases", handle))},
virNetworkDHCPLeaseFree{
reinterpret_cast<virNetworkDHCPLeaseFree_t>(get_symbol_address_for("virNetworkDHCPLeaseFree", handle))},
virDomainUndefine{reinterpret_cast<virDomainUndefine_t>(get_symbol_address_for("virDomainUndefine", handle))},
virDomainLookupByName{
reinterpret_cast<virDomainLookupByName_t>(get_symbol_address_for("virDomainLookupByName", handle))},
virDomainGetXMLDesc{
reinterpret_cast<virDomainGetXMLDesc_t>(get_symbol_address_for("virDomainGetXMLDesc", handle))},
virDomainDestroy{reinterpret_cast<virDomainDestroy_t>(get_symbol_address_for("virDomainDestroy", handle))},
virDomainFree{reinterpret_cast<virDomainFree_t>(get_symbol_address_for("virDomainFree", handle))},
virDomainDefineXML{reinterpret_cast<virDomainDefineXML_t>(get_symbol_address_for("virDomainDefineXML", handle))},
virDomainGetState{reinterpret_cast<virDomainGetState_t>(get_symbol_address_for("virDomainGetState", handle))},
virDomainCreate{reinterpret_cast<virDomainCreate_t>(get_symbol_address_for("virDomainCreate", handle))},
virDomainShutdown{reinterpret_cast<virDomainShutdown_t>(get_symbol_address_for("virDomainShutdown", handle))},
virDomainManagedSave{
reinterpret_cast<virDomainManagedSave_t>(get_symbol_address_for("virDomainManagedSave", handle))},
virDomainHasManagedSaveImage{reinterpret_cast<virDomainHasManagedSaveImage_t>(
get_symbol_address_for("virDomainHasManagedSaveImage", handle))},
virDomainSetVcpusFlags{
reinterpret_cast<virDomainSetVcpusFlags_t>(get_symbol_address_for("virDomainSetVcpusFlags", handle))},
virDomainSetMemoryFlags{
reinterpret_cast<virDomainSetMemoryFlags_t>(get_symbol_address_for("virDomainSetMemoryFlags", handle))},
virGetLastErrorMessage{
reinterpret_cast<virGetLastErrorMessage_t>(get_symbol_address_for("virGetLastErrorMessage", handle))}
{
}
mp::LibvirtWrapper::~LibvirtWrapper()
{
dlclose(handle);
}
| 5,039
|
C++
|
.cpp
| 90
| 50.488889
| 119
| 0.75633
|
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,724
|
base_virtual_machine_factory.cpp
|
canonical_multipass/src/platform/backends/shared/base_virtual_machine_factory.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 "base_virtual_machine_factory.h"
#include "multipass/platform.h"
#include <multipass/cloud_init_iso.h>
#include <multipass/constants.h>
#include <multipass/network_interface.h>
#include <multipass/network_interface_info.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/yaml_node_utils.h>
namespace mp = multipass;
namespace mpu = multipass::utils;
const mp::Path mp::BaseVirtualMachineFactory::instances_subdir = "vault/instances";
mp::BaseVirtualMachineFactory::BaseVirtualMachineFactory(const Path& instances_dir) : instances_dir{instances_dir} {};
void mp::BaseVirtualMachineFactory::configure(VirtualMachineDescription& vm_desc)
{
auto instance_dir{mpu::base_dir(vm_desc.image.image_path)};
const auto cloud_init_iso = instance_dir.filePath(cloud_init_file_name);
if (!QFile::exists(cloud_init_iso))
{
mp::CloudInitIso iso;
iso.add_file("meta-data", mpu::emit_cloud_config(vm_desc.meta_data_config));
iso.add_file("vendor-data", mpu::emit_cloud_config(vm_desc.vendor_data_config));
iso.add_file("user-data", mpu::emit_cloud_config(vm_desc.user_data_config));
if (!vm_desc.network_data_config.IsNull())
iso.add_file("network-config", mpu::emit_cloud_config(vm_desc.network_data_config));
iso.write_to(cloud_init_iso);
}
vm_desc.cloud_init_iso = cloud_init_iso;
}
void mp::BaseVirtualMachineFactory::prepare_networking(std::vector<NetworkInterface>& extra_interfaces)
{
if (!extra_interfaces.empty())
{
auto host_nets = networks(); // expensive
for (auto& net : extra_interfaces)
prepare_interface(net, host_nets);
}
}
void mp::BaseVirtualMachineFactory::prepare_interface(NetworkInterface& net,
std::vector<NetworkInterfaceInfo>& host_nets)
{
const auto bridge_type = MP_PLATFORM.bridge_nomenclature();
auto net_it = std::find_if(host_nets.cbegin(), host_nets.cend(),
[&net](const mp::NetworkInterfaceInfo& info) { return info.id == net.id; });
if (net_it != host_nets.end() && net_it->type != bridge_type)
{
if (auto bridge = mpu::find_bridge_with(host_nets, net.id, bridge_type))
{
net.id = bridge->id;
}
else
{
net.id = create_bridge_with(*net_it);
host_nets.push_back({net.id, bridge_type, "new bridge", {net_it->id}});
}
}
}
void mp::copy_instance_dir_with_essential_files(const fs::path& source_instance_dir_path,
const fs::path& dest_instance_dir_path)
{
if (fs::exists(source_instance_dir_path) && fs::is_directory(source_instance_dir_path))
{
for (const auto& entry : fs::directory_iterator(source_instance_dir_path))
{
fs::create_directory(dest_instance_dir_path);
// 1. Only cloud-init-config.iso file and <image_name>.img file are needed for qemu
// 2. Only cloud-init-config.iso file is needed for virutalbox because the rest files are taken care of by
// clonevm command
// 3. Only cloud-init-config.iso file is needed for hyperv because the rest files are taken
// care of by export and import command
// By the way, snapshot related files are excluded in all three backends, so as a result we can have an
// inclusion file list below which works for all three backends
if (entry.path().extension().string() == ".iso" || entry.path().extension().string() == ".img")
{
const fs::path dest_file_path = dest_instance_dir_path / entry.path().filename();
fs::copy(entry.path(), dest_file_path, fs::copy_options::update_existing);
}
}
}
}
| 4,488
|
C++
|
.cpp
| 95
| 40.031579
| 118
| 0.660653
|
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,725
|
base_snapshot.cpp
|
canonical_multipass/src/platform/backends/shared/base_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 "base_snapshot.h"
#include "multipass/virtual_machine.h"
#include <multipass/cloud_init_iso.h>
#include <multipass/constants.h>
#include <multipass/file_ops.h>
#include <multipass/json_utils.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_mount.h>
#include <multipass/vm_specs.h>
#include <scope_guard.hpp>
#include <QJsonArray>
#include <QString>
#include <QFile>
#include <QJsonParseError>
#include <QTemporaryDir>
#include <stdexcept>
namespace mp = multipass;
namespace
{
constexpr auto snapshot_extension = "snapshot.json";
constexpr auto index_digits = 4; // these two go together
constexpr auto max_snapshots = 9999;
const auto snapshot_template = QStringLiteral("@s%1"); /* avoid confusion with snapshot names by prepending a character
that can't be part of the name (users can call a snapshot
"s1", but they cannot call it "@s1") */
QString derive_index_string(int index)
{
return QString{"%1"}.arg(index, index_digits, 10, QLatin1Char('0'));
}
QJsonObject read_snapshot_json(const QString& filename)
{
QFile file{filename};
if (!MP_FILEOPS.open(file, QIODevice::ReadOnly))
throw std::runtime_error{fmt::format("Could not open snapshot file for for reading: {}", file.fileName())};
QJsonParseError parse_error{};
const auto& data = MP_FILEOPS.read_all(file);
if (const auto json = QJsonDocument::fromJson(data, &parse_error).object(); parse_error.error)
throw std::runtime_error{fmt::format("Could not parse snapshot JSON; error: {}; file: {}",
parse_error.errorString(),
file.fileName())};
else if (json.isEmpty())
throw std::runtime_error{fmt::format("Empty snapshot JSON: {}", file.fileName())};
else
return json["snapshot"].toObject();
}
std::unordered_map<std::string, mp::VMMount> load_mounts(const QJsonArray& mounts_json)
{
std::unordered_map<std::string, mp::VMMount> mounts;
for (const auto& entry : mounts_json)
{
const auto& json = entry.toObject();
mounts[json["target_path"].toString().toStdString()] = mp::VMMount{json};
}
return mounts;
}
std::shared_ptr<mp::Snapshot> find_parent(const QJsonObject& json, mp::VirtualMachine& vm)
{
auto parent_idx = json["parent"].toInt();
try
{
return parent_idx ? vm.get_snapshot(parent_idx) : nullptr;
}
catch (std::out_of_range&)
{
throw std::runtime_error{fmt::format("Missing snapshot parent. Snapshot name: {}; parent index: {}",
json["name"].toString(),
parent_idx)};
}
}
// When it does not contain cloud_init_instance_id, it signifies that the legacy snapshot does not have the
// item and it needs to fill cloud_init_instance_id with the current value. The current value equals to the
// value at snapshot time because cloud_init_instance_id has been an immutable variable up to this point.
std::string choose_cloud_init_instance_id(const QJsonObject& json, const std::filesystem::path& cloud_init_iso_path)
{
return json.contains("cloud_init_instance_id")
? json["cloud_init_instance_id"].toString().toStdString()
: MP_CLOUD_INIT_FILE_OPS.get_instance_id_from_cloud_init(cloud_init_iso_path);
}
} // namespace
mp::BaseSnapshot::BaseSnapshot(const std::string& name, // NOLINT(modernize-pass-by-value)
const std::string& comment, // NOLINT(modernize-pass-by-value)
const std::string& cloud_init_instance_id,
std::shared_ptr<Snapshot> parent,
int index,
QDateTime&& creation_timestamp,
int num_cores,
MemorySize mem_size,
MemorySize disk_space,
std::vector<NetworkInterface> extra_interfaces,
VirtualMachine::State state,
std::unordered_map<std::string, VMMount> mounts,
QJsonObject metadata,
const QDir& storage_dir,
bool captured)
: name{name},
comment{comment},
parent{std::move(parent)},
cloud_init_instance_id{cloud_init_instance_id},
index{index},
id{snapshot_template.arg(index)},
creation_timestamp{std::move(creation_timestamp)},
num_cores{num_cores},
mem_size{mem_size},
disk_space{disk_space},
extra_interfaces{extra_interfaces},
state{state},
mounts{std::move(mounts)},
metadata{std::move(metadata)},
storage_dir{storage_dir},
captured{captured}
{
using St = VirtualMachine::State;
if (state != St::off && state != St::stopped)
throw std::runtime_error{fmt::format("Unsupported VM state in snapshot: {}", static_cast<int>(state))};
if (index < 1)
throw std::runtime_error{fmt::format("Snapshot index not positive: {}", index)};
if (index > max_snapshots)
throw std::runtime_error{fmt::format("Maximum number of snapshots exceeded: {}", index)};
if (name.empty())
throw std::runtime_error{"Snapshot names cannot be empty"};
if (num_cores < 1)
throw std::runtime_error{fmt::format("Invalid number of cores for snapshot: {}", num_cores)};
if (auto mem_bytes = mem_size.in_bytes(); mem_bytes < 1)
throw std::runtime_error{fmt::format("Invalid memory size for snapshot: {}", mem_bytes)};
if (auto disk_bytes = disk_space.in_bytes(); disk_bytes < 1)
throw std::runtime_error{fmt::format("Invalid disk size for snapshot: {}", disk_bytes)};
}
mp::BaseSnapshot::BaseSnapshot(const std::string& name,
const std::string& comment,
const std::string& cloud_init_instance_id,
std::shared_ptr<Snapshot> parent,
const VMSpecs& specs,
const VirtualMachine& vm)
: BaseSnapshot{name,
comment,
cloud_init_instance_id,
std::move(parent),
vm.get_snapshot_count() + 1,
QDateTime::currentDateTimeUtc(),
specs.num_cores,
specs.mem_size,
specs.disk_space,
specs.extra_interfaces,
specs.state,
specs.mounts,
specs.metadata,
vm.instance_directory(),
/*captured=*/false}
{
assert(index > 0 && "snapshot indices need to start at 1");
}
mp::BaseSnapshot::BaseSnapshot(const QString& filename, VirtualMachine& vm, const VirtualMachineDescription& desc)
: BaseSnapshot{read_snapshot_json(filename), vm, desc}
{
}
mp::BaseSnapshot::BaseSnapshot(const QJsonObject& json, VirtualMachine& vm, const VirtualMachineDescription& desc)
: BaseSnapshot{
json["name"].toString().toStdString(), // name
json["comment"].toString().toStdString(), // comment
choose_cloud_init_instance_id(json,
std::filesystem::path{vm.instance_directory().absolutePath().toStdString()} /
cloud_init_file_name), // instance id from cloud init
find_parent(json, vm), // parent
json["index"].toInt(), // index
QDateTime::fromString(json["creation_timestamp"].toString(), Qt::ISODateWithMs), // creation_timestamp
json["num_cores"].toInt(), // num_cores
MemorySize{json["mem_size"].toString().toStdString()}, // mem_size
MemorySize{json["disk_space"].toString().toStdString()}, // disk_space
MP_JSONUTILS.read_extra_interfaces(json).value_or(desc.extra_interfaces), // extra_interfaces
static_cast<mp::VirtualMachine::State>(json["state"].toInt()), // state
load_mounts(json["mounts"].toArray()), // mounts
json["metadata"].toObject(), // metadata
vm.instance_directory(), // storage_dir
true} // captured
{
if (!(json.contains("extra_interfaces") && json.contains("cloud_init_instance_id")))
{
persist();
}
}
QJsonObject mp::BaseSnapshot::serialize() const
{
assert(captured && "precondition: only captured snapshots can be serialized");
QJsonObject ret, snapshot{};
const std::unique_lock lock{mutex};
snapshot.insert("name", QString::fromStdString(name));
snapshot.insert("comment", QString::fromStdString(comment));
snapshot.insert("cloud_init_instance_id", QString::fromStdString(cloud_init_instance_id));
snapshot.insert("parent", get_parents_index());
snapshot.insert("index", index);
snapshot.insert("creation_timestamp", creation_timestamp.toString(Qt::ISODateWithMs));
snapshot.insert("num_cores", num_cores);
snapshot.insert("mem_size", QString::number(mem_size.in_bytes()));
snapshot.insert("disk_space", QString::number(disk_space.in_bytes()));
snapshot.insert("extra_interfaces", MP_JSONUTILS.extra_interfaces_to_json_array(extra_interfaces));
snapshot.insert("state", static_cast<int>(state));
snapshot.insert("metadata", metadata);
// Extract mount serialization
QJsonArray json_mounts;
for (const auto& mount : mounts)
{
auto entry = mount.second.serialize();
entry.insert("target_path", QString::fromStdString(mount.first));
json_mounts.append(entry);
}
snapshot.insert("mounts", json_mounts);
ret.insert("snapshot", snapshot);
return ret;
}
void mp::BaseSnapshot::persist() const
{
const std::unique_lock lock{mutex};
auto snapshot_filepath = storage_dir.filePath(derive_snapshot_filename());
MP_JSONUTILS.write_json(serialize(), snapshot_filepath);
}
auto mp::BaseSnapshot::erase_helper()
{
// Remove snapshot file
auto tmp_dir = std::make_unique<QTemporaryDir>(); // work around no move ctor
if (!tmp_dir->isValid())
throw std::runtime_error{"Could not create temporary directory"};
const auto snapshot_filename = derive_snapshot_filename();
auto snapshot_filepath = storage_dir.filePath(snapshot_filename);
auto deleting_filepath = tmp_dir->filePath(snapshot_filename);
QFile snapshot_file{snapshot_filepath};
if (!MP_FILEOPS.rename(snapshot_file, deleting_filepath) && snapshot_file.exists())
throw std::runtime_error{
fmt::format("Failed to move snapshot file to temporary destination: {}", deleting_filepath)};
return sg::make_scope_guard([tmp_dir = std::move(tmp_dir),
deleting_filepath = std::move(deleting_filepath),
snapshot_filepath = std::move(snapshot_filepath)]() noexcept {
QFile temp_file{deleting_filepath};
MP_FILEOPS.rename(temp_file, snapshot_filepath); // best effort, ignore return
});
}
void mp::BaseSnapshot::erase()
{
const std::unique_lock lock{mutex};
assert(captured && "precondition: only captured snapshots can be erased");
auto rollback_snapshot_file = erase_helper();
erase_impl();
rollback_snapshot_file.dismiss();
}
QString mp::BaseSnapshot::derive_snapshot_filename() const
{
return QString{"%1.%2"}.arg(derive_index_string(index), snapshot_extension);
}
| 12,732
|
C++
|
.cpp
| 263
| 39.311787
| 119
| 0.609552
|
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,726
|
sshfs_server_process_spec.cpp
|
canonical_multipass/src/platform/backends/shared/sshfs_server_process_spec.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 "sshfs_server_process_spec.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/id_mappings.h>
#include <multipass/logging/log.h>
#include <multipass/snap_utils.h>
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDir>
namespace mp = multipass;
namespace mpu = multipass::utils;
namespace
{
QString serialise_id_mappings(const mp::id_mappings& xid_mappings)
{
QString out;
for (auto ids : xid_mappings)
{
out += QString("%1:%2,").arg(ids.first).arg(ids.second);
}
return out;
}
QByteArray gen_hash(const std::string& path)
{
// need to return unique name for each mount. The target directory string will be unique,
// so hash it and return first 8 hex chars.
return QCryptographicHash::hash(QByteArray::fromStdString(path), QCryptographicHash::Sha256).toHex().left(8);
}
} // namespace
mp::SSHFSServerProcessSpec::SSHFSServerProcessSpec(const SSHFSServerConfig& config)
: config(config), target_hash(gen_hash(config.source_path))
{
}
QString mp::SSHFSServerProcessSpec::program() const
{
return QCoreApplication::applicationDirPath() + "/sshfs_server";
}
QStringList mp::SSHFSServerProcessSpec::arguments() const
{
return QStringList() << QString::fromStdString(config.host) << QString::number(config.port)
<< QString::fromStdString(config.username) << QString::fromStdString(config.source_path)
<< QString::fromStdString(config.target_path) << serialise_id_mappings(config.uid_mappings)
<< serialise_id_mappings(config.gid_mappings)
<< QString::number(static_cast<int>(mp::logging::get_logging_level()));
}
QProcessEnvironment mp::SSHFSServerProcessSpec::environment() const
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("KEY", QString::fromStdString(config.private_key));
return env;
}
mp::logging::Level mp::SSHFSServerProcessSpec::error_log_level() const
{
return mp::logging::Level::debug;
}
QString mp::SSHFSServerProcessSpec::apparmor_profile() const
{
QString profile_template(R"END(
#include <tunables/global>
profile %1 flags=(attach_disconnected) {
#include <abstractions/base>
#include <abstractions/nameservice>
# Sshfs_server requires broad filesystem altering permissions, but only for the
# host directory the user has specified to be shared with the VM.
# Required for reading and searching host directories
capability dac_override,
capability dac_read_search,
# Enables modifying of file ownership and permissions
capability chown,
capability fsetid,
capability fowner,
# Multipass allows user to specify arbitrary uid/gid mappings
capability setuid,
capability setgid,
# Allow multipassd send sshfs_server signals
signal (receive) peer=%2,
# sshfs gathers some info about system resources
/sys/devices/system/node/ r,
/sys/devices/system/node/node[0-9]*/meminfo r,
# binary and its libs
%3/bin/sshfs_server ixr,
%3/{usr/,}lib/** rm,
# CLASSIC ONLY: need to specify required libs from core snap
/{,var/lib/snapd/}snap/core18/*/{,usr/}lib/@{multiarch}/{,**/}*.so* rm,
# allow full access just to this user-specified source directory on the host
%4/ rw,
%4/** rwlk,
}
)END");
/* Customisations depending on if running inside snap or not */
QString root_dir; // sshfs_server is a multipass utility, is located relative to the multipassd binary if not in a
// snap. If snapped, is located relative to $SNAP
QString signal_peer; // if snap confined, specify only multipassd can kill dnsmasq
try
{
root_dir = mpu::snap_dir();
signal_peer = "snap.multipass.multipassd";
}
catch (const mp::SnapEnvironmentException&)
{
QDir application_dir(QCoreApplication::applicationDirPath());
application_dir.cdUp();
root_dir = application_dir.absolutePath();
signal_peer = "unconfined";
}
return profile_template.arg(apparmor_profile_name(), signal_peer, root_dir,
QString::fromStdString(config.source_path));
}
QString mp::SSHFSServerProcessSpec::identifier() const
{
return QString::fromStdString(config.instance) + "." + target_hash;
}
| 5,014
|
C++
|
.cpp
| 127
| 34.795276
| 118
| 0.714638
|
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,727
|
base_virtual_machine.cpp
|
canonical_multipass/src/platform/backends/shared/base_virtual_machine.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 "base_virtual_machine.h"
#include <multipass/cloud_init_iso.h>
#include <multipass/constants.h>
#include <multipass/exceptions/file_open_failed_exception.h>
#include <multipass/exceptions/internal_timeout_exception.h>
#include <multipass/exceptions/ip_unavailable_exception.h>
#include <multipass/exceptions/snapshot_exceptions.h>
#include <multipass/exceptions/ssh_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/snapshot.h>
#include <multipass/ssh/ssh_key_provider.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/top_catch_all.h>
#include <multipass/vm_specs.h>
#include <scope_guard.hpp>
#include <QDir>
#include <chrono>
#include <functional>
#include <mutex>
#include <stdexcept>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
using namespace std::chrono_literals;
namespace
{
using St = mp::VirtualMachine::State;
constexpr auto snapshot_extension = "snapshot.json";
constexpr auto head_filename = "snapshot-head";
constexpr auto count_filename = "snapshot-count";
constexpr auto yes_overwrite = true;
void assert_vm_stopped(St state)
{
assert(state == St::off || state == St::stopped);
}
mp::Path derive_head_path(const QDir& snapshot_dir)
{
return snapshot_dir.filePath(head_filename);
}
void update_parents_rollback_helper(const std::shared_ptr<mp::Snapshot>& deleted_parent,
std::vector<mp::Snapshot*>& updated_parents)
{
for (auto snapshot : updated_parents)
snapshot->set_parent(deleted_parent);
}
std::string trimmed_contents_of(const QString& file_path)
{
return mpu::trim(mpu::contents_of(file_path));
}
template <typename ExceptionT>
mp::utils::TimeoutAction log_and_retry(const ExceptionT& e,
const mp::VirtualMachine* vm,
mpl::Level log_level = mpl::Level::trace)
{
assert(vm);
mpl::log(log_level, vm->vm_name, e.what());
return mp::utils::TimeoutAction::retry;
};
std::optional<mp::SSHSession> wait_until_ssh_up_helper(mp::VirtualMachine* virtual_machine,
std::chrono::milliseconds timeout,
const mp::SSHKeyProvider& key_provider)
{
static constexpr auto wait_step = 1s;
mpl::log(mpl::Level::debug, virtual_machine->vm_name, "Waiting for SSH to be up");
std::optional<mp::SSHSession> session = std::nullopt;
auto action = [virtual_machine, &key_provider, &session] {
virtual_machine->ensure_vm_is_running();
try
{
session.emplace(virtual_machine->ssh_hostname(wait_step),
virtual_machine->ssh_port(),
virtual_machine->ssh_username(),
key_provider);
std::lock_guard<decltype(virtual_machine->state_mutex)> lock{virtual_machine->state_mutex};
virtual_machine->state = mp::VirtualMachine::State::running;
virtual_machine->update_state();
return mp::utils::TimeoutAction::done;
}
catch (const mp::InternalTimeoutException& e)
{
return log_and_retry(e, virtual_machine);
}
catch (const mp::SSHException& e)
{
return log_and_retry(e, virtual_machine);
}
catch (const mp::IPUnavailableException& e)
{
return log_and_retry(e, virtual_machine);
}
catch (const std::runtime_error& e) // transitioning away from catching generic runtime errors
{ // TODO remove once we're confident this is an anomaly
return log_and_retry(e, virtual_machine, mpl::Level::warning);
}
};
auto on_timeout = [virtual_machine] {
std::lock_guard<decltype(virtual_machine->state_mutex)> lock{virtual_machine->state_mutex};
virtual_machine->state = mp::VirtualMachine::State::unknown;
virtual_machine->update_state();
throw std::runtime_error(fmt::format("{}: timed out waiting for response", virtual_machine->vm_name));
};
mp::utils::try_action_for(on_timeout, timeout, action);
return session;
}
} // namespace
mp::BaseVirtualMachine::BaseVirtualMachine(VirtualMachine::State state,
const std::string& vm_name,
const SSHKeyProvider& key_provider,
const Path& instance_dir)
: VirtualMachine{state, vm_name, instance_dir}, key_provider{key_provider}
{
}
mp::BaseVirtualMachine::BaseVirtualMachine(const std::string& vm_name,
const SSHKeyProvider& key_provider,
const Path& instance_dir)
: VirtualMachine{vm_name, instance_dir}, key_provider{key_provider}
{
}
void mp::BaseVirtualMachine::apply_extra_interfaces_and_instance_id_to_cloud_init(
const std::string& default_mac_addr,
const std::vector<NetworkInterface>& extra_interfaces,
const std::string& new_instance_id) const
{
const std::filesystem::path cloud_init_config_iso_file_path =
std::filesystem::path{instance_dir.absolutePath().toStdString()} / cloud_init_file_name;
MP_CLOUD_INIT_FILE_OPS.update_cloud_init_with_new_extra_interfaces_and_new_id(default_mac_addr,
extra_interfaces,
new_instance_id,
cloud_init_config_iso_file_path);
}
void mp::BaseVirtualMachine::add_extra_interface_to_instance_cloud_init(const std::string& default_mac_addr,
const NetworkInterface& extra_interface) const
{
const std::filesystem::path cloud_init_config_iso_file_path =
std::filesystem::path{instance_dir.absolutePath().toStdString()} / cloud_init_file_name;
MP_CLOUD_INIT_FILE_OPS.add_extra_interface_to_cloud_init(default_mac_addr,
extra_interface,
cloud_init_config_iso_file_path);
}
std::string mp::BaseVirtualMachine::get_instance_id_from_the_cloud_init() const
{
const std::filesystem::path cloud_init_config_iso_file_path =
std::filesystem::path{instance_dir.absolutePath().toStdString()} / cloud_init_file_name;
return MP_CLOUD_INIT_FILE_OPS.get_instance_id_from_cloud_init(cloud_init_config_iso_file_path);
}
void mp::BaseVirtualMachine::check_state_for_shutdown(ShutdownPolicy shutdown_policy)
{
// A mutex should already be locked by the caller here
if (state == State::off || state == State::stopped)
{
throw VMStateIdempotentException{"Ignoring shutdown since instance is already stopped."};
}
if (shutdown_policy == ShutdownPolicy::Poweroff)
{
return;
}
if (state == State::suspended)
{
if (shutdown_policy == ShutdownPolicy::Halt)
{
throw VMStateIdempotentException{"Ignoring shutdown since instance is already suspended."};
}
else // else only can be ShutdownPolicy::Powerdown since ShutdownPolicy::Poweroff check was preemptively done.
{
throw VMStateInvalidException{fmt::format("Cannot shut down suspended instance {}.", vm_name)};
}
}
if (state == State::suspending)
{
throw VMStateInvalidException{fmt::format("Cannot shut down instance {} while suspending.", vm_name)};
}
if (state == State::starting || state == State::restarting)
{
throw VMStateInvalidException{fmt::format("Cannot shut down instance {} while starting.", vm_name)};
}
}
std::string mp::BaseVirtualMachine::ssh_exec(const std::string& cmd, bool whisper)
{
std::unique_lock lock{state_mutex};
std::optional<std::string> log_details = std::nullopt;
bool reconnect = true;
while (true)
{
assert(reconnect && "we should have thrown otherwise");
if ((!ssh_session || !ssh_session->is_connected()) && reconnect)
{
const auto msg =
fmt::format("SSH session disconnected{}", log_details ? fmt::format(": {}", *log_details) : "");
mpl::log(logging::Level::info, vm_name, msg);
reconnect = false; // once only
lock.unlock();
renew_ssh_session();
lock.lock();
}
try
{
return MP_UTILS.run_in_ssh_session(*ssh_session, cmd, whisper);
}
catch (const SSHException& e)
{
assert(ssh_session);
if (ssh_session->is_connected() || !reconnect)
throw;
log_details = e.what();
continue; // disconnections are often only detected after attempted use
}
}
assert(false && "we should never reach here");
}
void mp::BaseVirtualMachine::renew_ssh_session()
{
{
const std::unique_lock lock{state_mutex};
if (!MP_UTILS.is_running(current_state())) // spend time updating state only if we need a new session
throw SSHException{fmt::format("SSH unavailable on instance {}: not running", vm_name)};
}
mpl::log(logging::Level::debug,
vm_name,
fmt::format("{} SSH session", ssh_session ? "Renewing cached" : "Caching new"));
ssh_session.emplace(ssh_hostname(), ssh_port(), ssh_username(), key_provider);
}
void mp::BaseVirtualMachine::wait_until_ssh_up(std::chrono::milliseconds timeout)
{
drop_ssh_session();
ssh_session = wait_until_ssh_up_helper(this, timeout, key_provider);
mpl::log(logging::Level::debug, vm_name, "Caching initial SSH session");
}
void mp::BaseVirtualMachine::wait_for_cloud_init(std::chrono::milliseconds timeout)
{
auto action = [this] {
ensure_vm_is_running();
try
{
ssh_exec("[ -e /var/lib/cloud/instance/boot-finished ]");
return mp::utils::TimeoutAction::done;
}
catch (const SSHExecFailure& e)
{
return mp::utils::TimeoutAction::retry;
}
catch (const std::exception& e) // transitioning away from catching generic runtime errors
{ // TODO remove once we're confident this is an anomaly
mpl::log(mpl::Level::warning, vm_name, e.what());
return mp::utils::TimeoutAction::retry;
}
};
auto on_timeout = [] { throw std::runtime_error("timed out waiting for initialization to complete"); };
mp::utils::try_action_for(on_timeout, timeout, action);
}
std::vector<std::string> mp::BaseVirtualMachine::get_all_ipv4()
{
std::vector<std::string> all_ipv4;
if (MP_UTILS.is_running(current_state()))
{
try
{
auto ip_a_output = QString::fromStdString(
ssh_exec("ip -brief -family inet address show scope global", /* whisper = */ true));
QRegularExpression ipv4_re{QStringLiteral("([\\d\\.]+)\\/\\d+\\s*(metric \\d+)?\\s*$"),
QRegularExpression::MultilineOption};
QRegularExpressionMatchIterator ip_it = ipv4_re.globalMatch(ip_a_output);
while (ip_it.hasNext())
{
auto ip_match = ip_it.next();
auto ip = ip_match.captured(1).toStdString();
all_ipv4.push_back(ip);
}
}
catch (const SSHException& e)
{
mpl::log(mpl::Level::debug, vm_name, fmt::format("Error getting extra IP addresses: {}", e.what()));
}
}
return all_ipv4;
}
auto mp::BaseVirtualMachine::view_snapshots() const -> SnapshotVista
{
require_snapshots_support();
SnapshotVista ret;
const std::unique_lock lock{snapshot_mutex};
ret.reserve(snapshots.size());
std::transform(std::cbegin(snapshots), std::cend(snapshots), std::back_inserter(ret), [](const auto& pair) {
return pair.second;
});
return ret;
}
std::shared_ptr<const mp::Snapshot> mp::BaseVirtualMachine::get_snapshot(const std::string& name) const
{
require_snapshots_support();
const std::unique_lock lock{snapshot_mutex};
try
{
return snapshots.at(name);
}
catch (const std::out_of_range&)
{
throw NoSuchSnapshotException{vm_name, name};
}
}
std::shared_ptr<const mp::Snapshot> mp::BaseVirtualMachine::get_snapshot(int index) const
{
require_snapshots_support();
const std::unique_lock lock{snapshot_mutex};
auto index_matcher = [index](const auto& elem) { return elem.second->get_index() == index; };
if (auto it = std::find_if(snapshots.begin(), snapshots.end(), index_matcher); it != snapshots.end())
return it->second;
throw std::runtime_error{
fmt::format("No snapshot with given index in instance; instance name: {}; snapshot index: {}", vm_name, index)};
}
std::shared_ptr<mp::Snapshot> mp::BaseVirtualMachine::get_snapshot(const std::string& name)
{
return std::const_pointer_cast<Snapshot>(std::as_const(*this).get_snapshot(name));
}
std::shared_ptr<mp::Snapshot> mp::BaseVirtualMachine::get_snapshot(int index)
{
return std::const_pointer_cast<Snapshot>(std::as_const(*this).get_snapshot(index));
}
void mp::BaseVirtualMachine::take_snapshot_rollback_helper(SnapshotMap::iterator it,
std::shared_ptr<Snapshot>& old_head,
int old_count)
{
if (old_head != head_snapshot)
{
assert(it->second && "snapshot not created despite modified head");
if (snapshot_count > old_count) // snapshot was captured
{
assert(snapshot_count - old_count == 1);
--snapshot_count;
mp::top_catch_all(vm_name, [it] { it->second->erase(); });
}
head_snapshot = std::move(old_head);
}
snapshots.erase(it);
}
auto mp::BaseVirtualMachine::make_take_snapshot_rollback(SnapshotMap::iterator it)
{
return sg::make_scope_guard( // best effort to rollback
[this, it = it, old_head = head_snapshot, old_count = snapshot_count]() mutable noexcept {
take_snapshot_rollback_helper(it, old_head, old_count);
});
}
std::shared_ptr<const mp::Snapshot> mp::BaseVirtualMachine::take_snapshot(const VMSpecs& specs,
const std::string& snapshot_name,
const std::string& comment)
{
require_snapshots_support();
std::unique_lock lock{snapshot_mutex};
assert_vm_stopped(state); // precondition
auto sname = snapshot_name.empty() ? generate_snapshot_name() : snapshot_name;
const auto [it, success] = snapshots.try_emplace(sname, nullptr);
if (!success)
{
mpl::log(mpl::Level::warning, vm_name, fmt::format("Snapshot name taken: {}", sname));
throw SnapshotNameTakenException{vm_name, sname};
}
auto rollback_on_failure = make_take_snapshot_rollback(it);
// get instance id from cloud-init file or lxd cloud init config and pass to make_specific_snapshot
auto ret = head_snapshot = it->second =
make_specific_snapshot(sname, comment, get_instance_id_from_the_cloud_init(), specs, head_snapshot);
ret->capture();
++snapshot_count;
persist_generic_snapshot_info();
rollback_on_failure.dismiss();
log_latest_snapshot(std::move(lock));
return ret;
}
bool mp::BaseVirtualMachine::updated_deleted_head(std::shared_ptr<Snapshot>& snapshot, const Path& head_path)
{
if (head_snapshot == snapshot)
{
head_snapshot = snapshot->get_parent();
persist_head_snapshot_index(head_path);
return true;
}
return false;
}
auto mp::BaseVirtualMachine::make_deleted_head_rollback(const Path& head_path, const bool& wrote_head)
{
return sg::make_scope_guard([this, old_head = head_snapshot, &head_path, &wrote_head]() mutable noexcept {
deleted_head_rollback_helper(head_path, wrote_head, old_head);
});
}
void mp::BaseVirtualMachine::deleted_head_rollback_helper(const Path& head_path,
const bool& wrote_head,
std::shared_ptr<Snapshot>& old_head)
{
if (head_snapshot != old_head)
{
head_snapshot = std::move(old_head);
if (wrote_head)
top_catch_all(vm_name, [this, &head_path] {
MP_UTILS.make_file_with_content(head_path.toStdString(),
std::to_string(head_snapshot->get_index()) + "\n",
yes_overwrite);
});
}
}
auto mp::BaseVirtualMachine::make_parent_update_rollback(const std::shared_ptr<Snapshot>& deleted_parent,
std::vector<Snapshot*>& updated_parents) const
{
return sg::make_scope_guard([this, &updated_parents, deleted_parent]() noexcept {
top_catch_all(vm_name, &update_parents_rollback_helper, deleted_parent, updated_parents);
});
}
void mp::BaseVirtualMachine::delete_snapshot_helper(std::shared_ptr<Snapshot>& snapshot)
{
// Update head if deleted
auto wrote_head = false;
auto head_path = derive_head_path(instance_dir);
auto rollback_head = make_deleted_head_rollback(head_path, wrote_head);
wrote_head = updated_deleted_head(snapshot, head_path);
// Update children of deleted snapshot
std::vector<Snapshot*> updated_parents{};
updated_parents.reserve(snapshots.size());
auto rollback_parent_updates = make_parent_update_rollback(snapshot, updated_parents);
update_parents(snapshot, updated_parents);
// Erase the snapshot with the backend and dismiss rollbacks on success
snapshot->erase();
rollback_parent_updates.dismiss();
rollback_head.dismiss();
}
void mp::BaseVirtualMachine::update_parents(std::shared_ptr<Snapshot>& deleted_parent,
std::vector<Snapshot*>& updated_parents)
{
auto new_parent = deleted_parent->get_parent();
for (auto& [ignore, other] : snapshots)
{
if (other->get_parent() == deleted_parent)
{
other->set_parent(new_parent);
updated_parents.push_back(other.get());
}
}
}
template <typename NodeT>
auto mp::BaseVirtualMachine::make_reinsert_guard(NodeT& snapshot_node)
{
return sg::make_scope_guard([this, &snapshot_node]() noexcept {
top_catch_all(vm_name, [this, &snapshot_node] {
const auto& current_name = snapshot_node.mapped()->get_name();
if (auto& key = snapshot_node.key(); key != current_name)
key = current_name; // best-effort rollback (this is very unlikely to fail)
snapshots.insert(std::move(snapshot_node));
});
});
;
}
void mp::BaseVirtualMachine::rename_snapshot(const std::string& old_name, const std::string& new_name)
{
if (old_name == new_name)
return;
const std::unique_lock lock{snapshot_mutex};
auto old_it = snapshots.find(old_name);
if (old_it == snapshots.end())
throw NoSuchSnapshotException{vm_name, old_name};
if (snapshots.find(new_name) != snapshots.end())
throw SnapshotNameTakenException{vm_name, new_name};
auto snapshot_node = snapshots.extract(old_it);
const auto reinsert_guard = make_reinsert_guard(snapshot_node); // we want this to execute both on failure & success
snapshot_node.key() = new_name;
snapshot_node.mapped()->set_name(new_name);
}
void mp::BaseVirtualMachine::delete_snapshot(const std::string& name)
{
const std::unique_lock lock{snapshot_mutex};
auto it = snapshots.find(name);
if (it == snapshots.end())
throw NoSuchSnapshotException{vm_name, name};
auto snapshot = it->second;
delete_snapshot_helper(snapshot);
snapshots.erase(it); // doesn't throw
mpl::log(mpl::Level::debug, vm_name, fmt::format("Snapshot deleted: {}", name));
}
void mp::BaseVirtualMachine::load_snapshots()
{
const std::unique_lock lock{snapshot_mutex};
auto snapshot_files = MP_FILEOPS.entryInfoList(instance_dir,
{QString{"*.%1"}.arg(snapshot_extension)},
QDir::Filter::Files | QDir::Filter::Readable,
QDir::SortFlag::Name);
for (const auto& finfo : snapshot_files)
load_snapshot(finfo.filePath());
load_generic_snapshot_info();
}
std::vector<std::string> mp::BaseVirtualMachine::get_childrens_names(const Snapshot* parent) const
{
require_snapshots_support();
std::vector<std::string> children;
for (const auto& snapshot : view_snapshots())
if (snapshot->get_parent().get() == parent)
children.push_back(snapshot->get_name());
return children;
}
void mp::BaseVirtualMachine::load_generic_snapshot_info()
{
try
{
snapshot_count = std::stoi(trimmed_contents_of(instance_dir.filePath(count_filename)));
auto head_index = std::stoi(trimmed_contents_of(instance_dir.filePath(head_filename)));
head_snapshot = head_index ? get_snapshot(head_index) : nullptr;
}
catch (FileOpenFailedException&)
{
if (!snapshots.empty())
throw;
}
}
template <typename LockT>
void mp::BaseVirtualMachine::log_latest_snapshot(LockT lock) const
{
auto num_snapshots = static_cast<int>(snapshots.size());
auto parent_name = head_snapshot->get_parents_name();
assert(num_snapshots <= snapshot_count && "can't have more snapshots than were ever taken");
if (auto log_detail_lvl = mpl::Level::debug; log_detail_lvl <= mpl::get_logging_level())
{
auto name = head_snapshot->get_name();
lock.unlock(); // unlock earlier
mpl::log(log_detail_lvl,
vm_name,
fmt::format(R"(New snapshot: "{}"; Descendant of: "{}"; Total snapshots: {})",
name,
parent_name,
num_snapshots));
}
}
void mp::BaseVirtualMachine::load_snapshot(const QString& filename)
{
const auto snapshot = make_specific_snapshot(filename);
const auto& name = snapshot->get_name();
const auto [_, success] = snapshots.try_emplace(name, snapshot);
if (!success)
{
mpl::log(mpl::Level::warning, vm_name, fmt::format("Snapshot name taken: {}", name));
throw SnapshotNameTakenException{vm_name, name};
}
}
auto mp::BaseVirtualMachine::make_common_file_rollback(const Path& file_path,
QFile& file,
const std::string& old_contents) const
{
return sg::make_scope_guard([this, &file_path, &file, old_contents, existed = file.exists()]() noexcept {
common_file_rollback_helper(file_path, file, old_contents, existed);
});
}
void mp::BaseVirtualMachine::common_file_rollback_helper(const Path& file_path,
QFile& file,
const std::string& old_contents,
bool existed) const
{
// best effort, ignore returns
if (!existed)
file.remove();
else
top_catch_all(vm_name, [&file_path, &old_contents] {
MP_UTILS.make_file_with_content(file_path.toStdString(), old_contents, yes_overwrite);
});
}
void mp::BaseVirtualMachine::persist_generic_snapshot_info() const
{
assert(head_snapshot);
auto head_path = derive_head_path(instance_dir);
auto count_path = instance_dir.filePath(count_filename);
QFile head_file{head_path};
auto head_file_rollback =
make_common_file_rollback(head_path, head_file, std::to_string(head_snapshot->get_parents_index()) + "\n");
persist_head_snapshot_index(head_path);
QFile count_file{count_path};
auto count_file_rollback =
make_common_file_rollback(count_path, count_file, std::to_string(snapshot_count - 1) + "\n");
MP_UTILS.make_file_with_content(count_path.toStdString(), std::to_string(snapshot_count) + "\n", yes_overwrite);
count_file_rollback.dismiss();
head_file_rollback.dismiss();
}
void mp::BaseVirtualMachine::persist_head_snapshot_index(const Path& head_path) const
{
auto head_index = head_snapshot ? head_snapshot->get_index() : 0;
MP_UTILS.make_file_with_content(head_path.toStdString(), std::to_string(head_index) + "\n", yes_overwrite);
}
std::string mp::BaseVirtualMachine::generate_snapshot_name() const
{
return fmt::format("snapshot{}", snapshot_count + 1);
}
auto mp::BaseVirtualMachine::make_restore_rollback(const Path& head_path, VMSpecs& specs)
{
return sg::make_scope_guard([this, &head_path, old_head = head_snapshot, old_specs = specs, &specs]() noexcept {
top_catch_all(vm_name,
&BaseVirtualMachine::restore_rollback_helper,
this,
head_path,
old_head,
old_specs,
specs);
});
}
void mp::BaseVirtualMachine::restore_rollback_helper(const Path& head_path,
const std::shared_ptr<Snapshot>& old_head,
const VMSpecs& old_specs,
VMSpecs& specs)
{
// best effort only
specs = old_specs;
if (old_head != head_snapshot)
{
head_snapshot = old_head;
persist_head_snapshot_index(head_path);
}
}
void mp::BaseVirtualMachine::restore_snapshot(const std::string& name, VMSpecs& specs)
{
const std::unique_lock lock{snapshot_mutex};
auto snapshot = get_snapshot(name);
assert_vm_stopped(state); // precondition
assert_vm_stopped(snapshot->get_state()); // precondition
const auto head_path = derive_head_path(instance_dir);
auto rollback = make_restore_rollback(head_path, specs);
specs.state = snapshot->get_state();
specs.num_cores = snapshot->get_num_cores();
specs.mem_size = snapshot->get_mem_size();
specs.disk_space = snapshot->get_disk_space();
const bool are_extra_interfaces_different = specs.extra_interfaces != snapshot->get_extra_interfaces();
specs.extra_interfaces = snapshot->get_extra_interfaces();
specs.mounts = snapshot->get_mounts();
specs.metadata = snapshot->get_metadata();
if (head_snapshot != snapshot)
{
head_snapshot = snapshot;
persist_head_snapshot_index(head_path);
}
snapshot->apply();
if (are_extra_interfaces_different)
{
// here we can use default_mac_address of the current state because it is an immutable variable.
apply_extra_interfaces_and_instance_id_to_cloud_init(specs.default_mac_address,
snapshot->get_extra_interfaces(),
snapshot->get_cloud_init_instance_id());
}
rollback.dismiss();
}
std::shared_ptr<mp::Snapshot> mp::BaseVirtualMachine::make_specific_snapshot(const std::string& /*snapshot_name*/,
const std::string& /*comment*/,
const std::string& /*instance_id*/,
const VMSpecs& /*specs*/,
std::shared_ptr<Snapshot> /*parent*/)
{
throw NotImplementedOnThisBackendException{"snapshots"};
}
std::shared_ptr<mp::Snapshot> mp::BaseVirtualMachine::make_specific_snapshot(const QString& /*filename*/)
{
throw NotImplementedOnThisBackendException{"snapshots"};
}
void mp::BaseVirtualMachine::drop_ssh_session()
{
if (ssh_session)
{
mpl::log(mpl::Level::debug, vm_name, "Dropping cached SSH session");
ssh_session.reset();
}
}
| 29,507
|
C++
|
.cpp
| 677
| 34.246677
| 120
| 0.61469
|
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,728
|
apparmor.cpp
|
canonical_multipass/src/platform/backends/shared/linux/apparmor.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/>.
*
*/
// Note: Do not use ProcessFactory here, as can introduce dependency loop.
#include "apparmor.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/snap_utils.h>
#include <sys/apparmor.h>
#include <QDir>
#include <QProcess>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
static const auto apparmor_parser = "apparmor_parser";
void throw_if_binary_fails(const char* binary_name, const QStringList& arguments = QStringList())
{
QProcess process;
process.start(binary_name, arguments);
if (!process.waitForFinished() || process.exitCode() != 0)
{
throw mp::AppArmorException(
fmt::format("AppArmor cannot be configured, the '{}' utility failed to launch with error: {}", binary_name,
process.errorString()));
}
}
QStringList generate_extra_apparmor_args()
{
try
{
QString apparmor_cache_dir = mp::utils::snap_common_dir() + "/apparmor.d/cache/multipass";
QDir cache_dir;
if (cache_dir.mkpath(apparmor_cache_dir))
{
return {"-WL", apparmor_cache_dir}; // write profiles to local cache
}
else
{
mpl::log(mpl::Level::debug, "daemon", "Failed to create cache directory for AppArmor - disabling caching");
}
}
catch (const mp::SnapEnvironmentException&)
{
// Ignore
}
return {"-W"};
}
} // namespace
mp::AppArmor::AppArmor() : apparmor_args{generate_extra_apparmor_args()}
{
int ret = aa_is_enabled();
if (ret <= 0)
{
throw mp::AppArmorException("AppArmor is not enabled");
}
// libapparmor's profile management API is not easy to use, it is handier to use apparmor_profile CLI tool
// Ensure it is available
throw_if_binary_fails(apparmor_parser, {"-V"});
}
void mp::AppArmor::load_policy(const QByteArray& aa_policy) const
{
QProcess process;
process.start(apparmor_parser,
apparmor_args + QStringList({"--abort-on-error", "-r"})); // inserts new or replaces existing
process.waitForStarted();
process.write(aa_policy);
process.closeWriteChannel();
process.waitForFinished();
mpl::log(mpl::Level::trace, "daemon", fmt::format("Loading AppArmor policy:\n{}", aa_policy));
if (process.exitCode() != 0)
{
throw mp::AppArmorException(fmt::format("Failed to load AppArmor policy {}: errno={} ({})", aa_policy,
process.exitCode(), process.readAll()));
}
}
void mp::AppArmor::remove_policy(const QByteArray& aa_policy) const
{
QProcess process;
process.start(apparmor_parser, apparmor_args + QStringList("-R"));
process.waitForStarted();
process.write(aa_policy);
process.closeWriteChannel();
process.waitForFinished();
mpl::log(mpl::Level::trace, "daemon", fmt::format("Removing AppArmor policy:\n{}", aa_policy));
if (process.exitCode() != 0)
{
throw mp::AppArmorException(fmt::format("Failed to remove AppArmor policy {}: errno={} ({})", aa_policy,
process.exitCode(), process.readAll()));
}
}
void mp::AppArmor::next_exec_under_policy(const QByteArray& aa_policy_name) const
{
int ret = aa_change_onexec(aa_policy_name.constData());
if (ret < 0)
{
throw mp::AppArmorException(
fmt::format("Failed to apply AppArmor policy {}: errno={} ({})", aa_policy_name, errno, strerror(errno)));
}
}
| 4,219
|
C++
|
.cpp
| 114
| 31.578947
| 119
| 0.664382
|
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,729
|
backend_utils.cpp
|
canonical_multipass/src/platform/backends/shared/linux/backend_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 "backend_utils.h"
#include "dbus_wrappers.h"
#include "process_factory.h"
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/process/basic_process.h>
#include <multipass/top_catch_all.h>
#include <multipass/utils.h>
#include <scope_guard.hpp>
#include <QCoreApplication>
#include <QDBusMetaType>
#include <QString>
#include <QtDBus/QtDBus>
#include <cassert>
#include <chrono>
#include <exception>
#include <mutex>
#include <random>
#include <type_traits>
#include <errno.h>
#include <fcntl.h>
#include <linux/kvm.h>
#include <sys/ioctl.h>
#include <unistd.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpdbus = multipass::backend::dbus;
typedef QMap<QString, QVariantMap> VariantMapMap;
Q_DECLARE_METATYPE(VariantMapMap) // for DBus
namespace
{
std::default_random_engine gen;
std::uniform_int_distribution<int> dist{0, 255};
const auto nm_bus_name = QStringLiteral("org.freedesktop.NetworkManager");
const auto nm_root_obj = QStringLiteral("/org/freedesktop/NetworkManager");
const auto nm_root_ifc = QStringLiteral("org.freedesktop.NetworkManager");
const auto nm_settings_obj = QStringLiteral("/org/freedesktop/NetworkManager/Settings");
const auto nm_settings_ifc = QStringLiteral("org.freedesktop.NetworkManager.Settings");
const auto nm_connection_ifc = QStringLiteral("org.freedesktop.NetworkManager.Settings.Connection");
constexpr auto max_bridge_name_len = 15; // maximum number of characters in a bridge name
bool subnet_used_locally(const std::string& subnet)
{
// CLI equivalent: ip -4 route show | grep -q ${SUBNET}
const auto output = QString::fromStdString(MP_UTILS.run_cmd_for_output("ip", {"-4", "route", "show"}));
return output.contains(QString::fromStdString(subnet));
}
bool can_reach_gateway(const std::string& ip)
{
return MP_UTILS.run_cmd_for_status("ping", {"-n", "-q", ip.c_str(), "-c", "-1", "-W", "1"});
}
auto virtual_switch_subnet(const QString& bridge_name)
{
// CLI equivalent: ip -4 route show | grep ${BRIDGE_NAME} | cut -d ' ' -f1 | cut -d '.' -f1-3
QString subnet;
const auto output = QString::fromStdString(MP_UTILS.run_cmd_for_output("ip", {"-4", "route", "show"})).split('\n');
for (const auto& line : output)
{
if (line.contains(bridge_name))
{
subnet = line.section('.', 0, 2);
break;
}
}
if (subnet.isNull())
{
mpl::log(mpl::Level::info, "daemon",
fmt::format("Unable to determine subnet for the {} subnet", qUtf8Printable(bridge_name)));
}
return subnet.toStdString();
}
const mpdbus::DBusConnection& get_checked_system_bus()
{
const auto& system_bus = mpdbus::DBusProvider::instance().get_system_bus();
if (!system_bus.is_connected())
throw mp::backend::CreateBridgeException{"Failed to connect to D-Bus system bus", system_bus.last_error()};
return system_bus;
}
std::unique_ptr<mpdbus::DBusInterface> get_checked_interface(const mpdbus::DBusConnection& bus, const QString& service,
const QString& path, const QString& interface)
{
auto ret = bus.get_interface(service, path, interface);
assert(ret);
if (!ret->is_valid())
throw mp::backend::CreateBridgeException{"Could not reach remote D-Bus object", ret->last_error()};
return ret;
}
template <typename T, bool RollingBack = false, typename... Ts>
T checked_dbus_call(mpdbus::DBusInterface& interface, const QString& method_name, Ts&&... params)
{
static constexpr auto error_template = "Failed DBus call. (Service: {}; Object: {}; Interface: {}; Method: {})";
auto reply_msg = interface.call(QDBus::Block, method_name, QVariant::fromValue(std::forward<Ts>(params))...);
QDBusReply<T> reply = reply_msg;
if (!reply.isValid())
throw mp::backend::CreateBridgeException{
fmt::format(error_template, interface.service(), interface.path(), interface.interface(), method_name),
reply.error(), RollingBack};
if constexpr (!std::is_void_v<T>)
return reply.value();
}
auto make_connection_settings(const QString& parent_name, const QString& child_name, const QString& interface_name)
{
VariantMapMap arg1{{"connection", {{"type", "bridge"}, {"id", parent_name}, {"autoconnect-slaves", 1}}},
{"bridge", {{"interface-name", parent_name}}}};
VariantMapMap arg2{{"connection",
{{"id", child_name},
{"type", "802-3-ethernet"},
{"slave-type", "bridge"},
{"master", parent_name},
{"interface-name", interface_name},
{"autoconnect-priority", 10}}}};
return std::make_pair(arg1, arg2);
}
auto make_bridge_rollback_guard(const mpl::CString& log_category, const mpdbus::DBusConnection& system_bus,
const QDBusObjectPath& parent_path, const QDBusObjectPath& child_path)
{
auto rollback = [&system_bus, &parent_path, &child_path] {
for (const auto* obj_path : {&child_path, &parent_path})
{
if (auto path = obj_path->path(); !path.isNull())
{
auto connection = system_bus.get_interface(nm_bus_name, path, nm_connection_ifc);
checked_dbus_call<void, /* RollingBack = */ true>(*connection, "Delete");
}
}
};
return sg::make_scope_guard([rollback, log_category]() noexcept {
mpl::log(mpl::Level::info, log_category, "Rolling back bridge");
mp::top_catch_all(log_category, rollback);
});
}
} // namespace
std::string mp::backend::generate_random_subnet()
{
gen.seed(std::chrono::system_clock::now().time_since_epoch().count());
for (auto i = 0; i < 100; ++i)
{
auto subnet = fmt::format("10.{}.{}", dist(gen), dist(gen));
if (subnet_used_locally(subnet))
continue;
if (can_reach_gateway(fmt::format("{}.1", subnet)))
continue;
if (can_reach_gateway(fmt::format("{}.254", subnet)))
continue;
return subnet;
}
throw std::runtime_error("Could not determine a subnet for networking.");
}
// @precondition no bridge exists for this interface
// @precondition interface identifies an ethernet device
std::string mp::Backend::create_bridge_with(const std::string& interface)
{
static constexpr auto log_category_create = "create bridge";
static constexpr auto log_category_rollback = "rollback bridge";
static const auto root_path = QDBusObjectPath{"/"};
static const auto base_name = QStringLiteral("br-");
static std::once_flag once;
std::call_once(once, [] { qDBusRegisterMetaType<VariantMapMap>(); });
const auto& system_bus = get_checked_system_bus();
auto nm_root = get_checked_interface(system_bus, nm_bus_name, nm_root_obj, nm_root_ifc);
auto nm_settings = get_checked_interface(system_bus, nm_bus_name, nm_settings_obj, nm_settings_ifc);
auto parent_name = (base_name + interface.c_str()).left(max_bridge_name_len);
auto child_name = parent_name + "-child";
mpl::log(mpl::Level::debug, log_category_create, fmt::format("Creating bridge: {}", parent_name));
// AddConnection expects the following DBus argument type: a{sa{sv}}
const auto& [arg1, arg2] = make_connection_settings(parent_name, child_name, QString::fromStdString(interface));
// The rollbacks could be achieved with
// `nmcli connection delete <parent_connection> <child_connection>
QDBusObjectPath parent_path{}, child_path{};
auto rollback_guard = // rollback unless we succeed
make_bridge_rollback_guard(log_category_rollback, system_bus, parent_path, child_path);
// The following DBus calls are roughly equivalent to:
// `nmcli connection add type bridge ifname <br> connection.autoconnect-slaves 1`
// `nmcli connection add type bridge-slave ifname <if> master <br> connection.autoconnect-priority 10`
// `nmcli connection up <child_connection>`
parent_path = checked_dbus_call<QDBusObjectPath>(*nm_settings, "AddConnection", arg1);
child_path = checked_dbus_call<QDBusObjectPath>(*nm_settings, "AddConnection", arg2);
checked_dbus_call<QDBusObjectPath>(*nm_root, "ActivateConnection", child_path, root_path, root_path); /* Inspiration
for '/' to signal null `device` and `specific-object` derived from nmcli and libnm. See https://bit.ly/3dMA3QB */
rollback_guard.dismiss(); // we succeeded!
auto ret = parent_name.toStdString();
mpl::log(mpl::Level::info, log_category_create, fmt::format("Created bridge: {}", ret));
return ret;
}
std::string mp::Backend::get_subnet(const mp::Path& network_dir, const QString& bridge_name) const
{
auto subnet = virtual_switch_subnet(bridge_name);
if (!subnet.empty())
return subnet;
QFile subnet_file{network_dir + "/multipass_subnet"};
MP_FILEOPS.open(subnet_file, QIODevice::ReadWrite | QIODevice::Text);
if (MP_FILEOPS.size(subnet_file) > 0)
return MP_FILEOPS.read_all(subnet_file).trimmed().toStdString();
auto new_subnet = mp::backend::generate_random_subnet();
MP_FILEOPS.write(subnet_file, new_subnet.data(), new_subnet.length());
return new_subnet;
}
void mp::Backend::check_for_kvm_support()
{
QFile kvm_device{"/dev/kvm"};
if (!MP_FILEOPS.exists(kvm_device))
{
throw std::runtime_error("KVM support is not enabled on this machine.\n"
"Please ensure the following:\n"
"1. The system's CPU supports virtualization.\n"
"2. Virtualization is enabled in the system BIOS.\n"
"3. The KVM kernel modules are loaded.");
}
if (!MP_FILEOPS.open(kvm_device, QIODevice::ReadWrite))
{
throw std::runtime_error("The KVM device cannot be opened for reading and writing.\n"
"Please ensure the Snap KVM interface is connected by issuing:\n"
"$ snap connect multipass:kvm");
}
}
void mp::Backend::check_if_kvm_is_in_use()
{
auto kvm_fd = MP_LINUX_SYSCALLS.open("/dev/kvm", O_RDWR | O_CLOEXEC);
auto ret = MP_LINUX_SYSCALLS.ioctl(kvm_fd, KVM_CREATE_VM, (unsigned long)0);
MP_LINUX_SYSCALLS.close(kvm_fd);
if (ret == -1 && errno == EBUSY)
throw std::runtime_error("Another virtual machine manager is currently running. Please shut it down before "
"starting a Multipass instance.");
MP_LINUX_SYSCALLS.close(ret);
}
mp::backend::CreateBridgeException::CreateBridgeException(const std::string& detail, const QDBusError& dbus_error,
bool rollback)
: std::runtime_error(fmt::format("{}. {}: {}", rollback ? "Could not rollback bridge" : "Could not create bridge",
detail, dbus_error.isValid() ? dbus_error.message() : "unknown cause"))
{
}
int mp::LinuxSysCalls::close(int fd) const
{
return ::close(fd);
}
int mp::LinuxSysCalls::ioctl(int fd, unsigned long request, unsigned long parameter) const
{
return ::ioctl(fd, request, parameter);
}
int mp::LinuxSysCalls::open(const char* path, mode_t mode) const
{
return ::open(path, mode);
}
| 12,123
|
C++
|
.cpp
| 259
| 40.432432
| 120
| 0.662827
|
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,730
|
process_factory.cpp
|
canonical_multipass/src/platform/backends/shared/linux/process_factory.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 "process_factory.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/process/basic_process.h>
#include <multipass/process/process_spec.h>
#include <multipass/process/simple_process_spec.h>
#include <multipass/snap_utils.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
class AppArmoredProcess : public mp::BasicProcess
{
public:
AppArmoredProcess(const mp::AppArmor& aa, std::shared_ptr<mp::ProcessSpec> spec)
: mp::BasicProcess{spec}, apparmor{aa}
{
apparmor.load_policy(process_spec->apparmor_profile().toLatin1());
connect(this, &AppArmoredProcess::state_changed, [this](QProcess::ProcessState state) {
if (state == QProcess::Starting)
{
mpl::log(mpl::Level::debug, "daemon",
fmt::format("Applied AppArmor policy: {}", process_spec->apparmor_profile_name()));
}
});
}
void setup_child_process() final
{
mp::BasicProcess::setup_child_process();
apparmor.next_exec_under_policy(process_spec->apparmor_profile_name().toLatin1());
}
~AppArmoredProcess()
{
try
{
apparmor.remove_policy(process_spec->apparmor_profile().toLatin1());
}
catch (const std::exception& e)
{
// It's not considered an error when an apparmor cannot be removed
mpl::log(mpl::Level::info, "apparmor", e.what());
}
}
private:
const mp::AppArmor& apparmor;
};
std::optional<mp::AppArmor> create_apparmor()
{
try
{
mp::utils::snap_dir();
}
catch (const mp::SnapEnvironmentException&)
{
if (qEnvironmentVariableIsSet("DISABLE_APPARMOR"))
{
mpl::log(mpl::Level::warning, "apparmor", "AppArmor disabled by environment variable");
return std::nullopt;
}
}
try
{
mpl::log(mpl::Level::info, "apparmor", "Using AppArmor support");
return mp::AppArmor{};
}
catch (mp::AppArmorException& e)
{
mpl::log(mpl::Level::warning, "apparmor", fmt::format("Failed to enable AppArmor: {}", e.what()));
return std::nullopt;
}
}
} // namespace
mp::ProcessFactory::ProcessFactory(const Singleton<ProcessFactory>::PrivatePass& pass)
: Singleton<ProcessFactory>::Singleton{pass}, apparmor{create_apparmor()}
{
}
// This is the default ProcessFactory that creates a Process with no security mechanisms enabled
std::unique_ptr<mp::Process> mp::ProcessFactory::create_process(std::unique_ptr<mp::ProcessSpec>&& process_spec) const
{
if (apparmor && !process_spec->apparmor_profile().isNull())
{
std::shared_ptr<ProcessSpec> spec = std::move(process_spec);
try
{
return std::make_unique<AppArmoredProcess>(apparmor.value(), spec);
}
catch (const mp::AppArmorException& e)
{
// TODO: This won't fly in strict mode (#1074), since we'll be confined by snapd
mpl::log(mpl::Level::warning, "apparmor", e.what());
return std::make_unique<BasicProcess>(spec);
}
}
else
{
return std::make_unique<BasicProcess>(std::move(process_spec));
}
}
std::unique_ptr<mp::Process> mp::ProcessFactory::create_process(const QString& command,
const QStringList& arguments) const
{
return create_process(simple_process_spec(command, arguments));
}
| 4,233
|
C++
|
.cpp
| 120
| 29.091667
| 118
| 0.652842
|
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,731
|
qemu_img_utils.cpp
|
canonical_multipass/src/platform/backends/shared/qemu_img_utils/qemu_img_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 "qemu_img_utils.h"
#include <multipass/constants.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <multipass/platform.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <QJsonDocument>
#include <QJsonObject>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
namespace mp = multipass;
namespace mpp = multipass::platform;
auto mp::backend::checked_exec_qemu_img(std::unique_ptr<mp::QemuImgProcessSpec> spec,
const std::string& custom_error_prefix,
std::optional<int> timeout) -> Process::UPtr
{
auto process = mpp::make_process(std::move(spec));
auto process_state = timeout ? process->execute(*timeout) : process->execute();
if (!process_state.completed_successfully())
{
throw QemuImgException{fmt::format("{}: qemu-img failed ({}) with output:\n{}",
custom_error_prefix,
process_state.failure_message(),
process->read_all_standard_error())};
}
return process;
}
void mp::backend::resize_instance_image(const MemorySize& disk_space, const mp::Path& image_path)
{
auto disk_size = QString::number(disk_space.in_bytes()); // format documented in `man qemu-img` (look for "size")
QStringList qemuimg_parameters{{"resize", image_path, disk_size}};
checked_exec_qemu_img(std::make_unique<mp::QemuImgProcessSpec>(qemuimg_parameters, "", image_path),
"Cannot resize instance image",
mp::image_resize_timeout);
}
mp::Path mp::backend::convert_to_qcow_if_necessary(const mp::Path& image_path)
{
// Check if raw image file, and if so, convert to qcow2 format.
// TODO: we could support converting from other the image formats that qemu-img can deal with
const auto qcow2_path{image_path + ".qcow2"};
auto qemuimg_info_process = checked_exec_qemu_img(
std::make_unique<mp::QemuImgProcessSpec>(QStringList{"info", "--output=json", image_path}, image_path),
"Cannot read image format");
auto image_info = qemuimg_info_process->read_all_standard_output();
auto image_record = QJsonDocument::fromJson(QString(image_info).toUtf8(), nullptr).object();
if (image_record["format"].toString() == "raw")
{
auto qemuimg_convert_spec = std::make_unique<mp::QemuImgProcessSpec>(
QStringList{"convert", "-p", "-O", "qcow2", image_path, qcow2_path}, image_path, qcow2_path);
auto qemuimg_convert_process =
checked_exec_qemu_img(std::move(qemuimg_convert_spec), "Failed to convert image format");
return qcow2_path;
}
else
{
return image_path;
}
}
void mp::backend::amend_to_qcow2_v3(const mp::Path& image_path)
{
checked_exec_qemu_img(
std::make_unique<mp::QemuImgProcessSpec>(QStringList{"amend", "-o", "compat=1.1", image_path}, image_path),
"Failed to amend image to QCOW2 v3");
}
bool mp::backend::instance_image_has_snapshot(const mp::Path& image_path, QString snapshot_tag)
{
auto process = checked_exec_qemu_img(
std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-l", image_path}, image_path));
QRegularExpression regex{snapshot_tag.append(R"(\s)")};
return QString{process->read_all_standard_output()}.contains(regex);
}
QByteArray mp::backend::snapshot_list_output(const Path& image_path)
{
auto qemuimg_info_process = checked_exec_qemu_img(
std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-l", image_path}, image_path),
"Cannot list snapshots from the image");
return qemuimg_info_process->read_all_standard_output();
}
void mp::backend::delete_snapshot_from_image(const Path& image_path, const QString& snapshot_tag)
{
checked_exec_qemu_img(
std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-d", snapshot_tag, image_path}, image_path),
"Cannot delete snapshot from the image");
}
| 4,744
|
C++
|
.cpp
| 101
| 40.60396
| 118
| 0.676324
|
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,732
|
qemu_base_process_spec.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_base_process_spec.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 "qemu_base_process_spec.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/snap_utils.h>
namespace mp = multipass;
namespace mpu = multipass::utils;
QString mp::QemuBaseProcessSpec::program() const
{
return QString("qemu-system-%1").arg(HOST_ARCH);
}
QString mp::QemuBaseProcessSpec::working_directory() const
{
try
{
return mpu::snap_dir().append("/qemu");
}
catch (const mp::SnapEnvironmentException&)
{
return QString();
}
}
QString mp::QemuBaseProcessSpec::apparmor_profile() const
{
return QString();
}
| 1,232
|
C++
|
.cpp
| 40
| 28.075
| 72
| 0.736931
|
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,733
|
qemu_virtual_machine_factory.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_virtual_machine_factory.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 "qemu_virtual_machine_factory.h"
#include "qemu_virtual_machine.h"
#include <multipass/cloud_init_iso.h>
#include <multipass/constants.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/process/simple_process_spec.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_specs.h>
#include <multipass/yaml_node_utils.h>
#include <shared/qemu_img_utils/qemu_img_utils.h>
#include <QRegularExpression>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "qemu factory";
} // namespace
mp::QemuVirtualMachineFactory::QemuVirtualMachineFactory(const mp::Path& data_dir)
: QemuVirtualMachineFactory{MP_QEMU_PLATFORM_FACTORY.make_qemu_platform(data_dir), data_dir}
{
}
mp::QemuVirtualMachineFactory::QemuVirtualMachineFactory(QemuPlatform::UPtr qemu_platform, const mp::Path& data_dir)
: BaseVirtualMachineFactory(
MP_UTILS.derive_instances_dir(data_dir, qemu_platform->get_directory_name(), instances_subdir)),
qemu_platform{std::move(qemu_platform)}
{
}
mp::VirtualMachine::UPtr mp::QemuVirtualMachineFactory::create_virtual_machine(const VirtualMachineDescription& desc,
const SSHKeyProvider& key_provider,
VMStatusMonitor& monitor)
{
return std::make_unique<mp::QemuVirtualMachine>(desc,
qemu_platform.get(),
monitor,
key_provider,
get_instance_directory(desc.vm_name));
}
mp::VirtualMachine::UPtr mp::QemuVirtualMachineFactory::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)
{
const std::filesystem::path source_instance_data_directory{get_instance_directory(source_name).toStdString()};
const std::filesystem::path dest_instance_data_directory{get_instance_directory(destination_name).toStdString()};
copy_instance_dir_with_essential_files(source_instance_data_directory, dest_instance_data_directory);
const fs::path cloud_init_config_iso_file_path = dest_instance_data_directory / cloud_init_file_name;
MP_CLOUD_INIT_FILE_OPS.update_cloned_cloud_init_unique_identifiers(dest_vm_spec.default_mac_address,
dest_vm_spec.extra_interfaces,
destination_name,
cloud_init_config_iso_file_path);
// start to construct VirtualMachineDescription
mp::VirtualMachineDescription dest_vm_desc{dest_vm_spec.num_cores,
dest_vm_spec.mem_size,
dest_vm_spec.disk_space,
destination_name,
dest_vm_spec.default_mac_address,
dest_vm_spec.extra_interfaces,
dest_vm_spec.ssh_username,
dest_vm_image,
cloud_init_config_iso_file_path.string().c_str(),
{},
{},
{},
{}};
mp::VirtualMachine::UPtr cloned_instance =
std::make_unique<mp::QemuVirtualMachine>(dest_vm_desc,
qemu_platform.get(),
monitor,
key_provider,
get_instance_directory(dest_vm_desc.vm_name));
cloned_instance->remove_snapshots_from_image();
return cloned_instance;
}
void mp::QemuVirtualMachineFactory::remove_resources_for_impl(const std::string& name)
{
qemu_platform->remove_resources_for(name);
}
mp::VMImage mp::QemuVirtualMachineFactory::prepare_source_image(const mp::VMImage& source_image)
{
VMImage image{source_image};
image.image_path = mp::backend::convert_to_qcow_if_necessary(source_image.image_path);
mp::backend::amend_to_qcow2_v3(image.image_path);
return image;
}
void mp::QemuVirtualMachineFactory::prepare_instance_image(const mp::VMImage& instance_image,
const VirtualMachineDescription& desc)
{
mp::backend::resize_instance_image(desc.disk_space, instance_image.image_path);
}
void mp::QemuVirtualMachineFactory::hypervisor_health_check()
{
qemu_platform->platform_health_check();
}
QString mp::QemuVirtualMachineFactory::get_backend_version_string() const
{
auto process =
mp::platform::make_process(simple_process_spec(QString("qemu-system-%1").arg(HOST_ARCH), {"--version"}));
auto version_re = QRegularExpression("^QEMU emulator version ([\\d\\.]+)");
auto exit_state = process->execute();
if (exit_state.completed_successfully())
{
auto match = version_re.match(process->read_all_standard_output());
if (match.hasMatch())
return QString("qemu-%1").arg(match.captured(1));
else
{
mpl::log(mpl::Level::error, category,
fmt::format("Failed to parse QEMU version out: '{}'", process->read_all_standard_output()));
return QString("qemu-unknown");
}
}
else
{
if (exit_state.error)
{
mpl::log(mpl::Level::error, category,
fmt::format("Qemu failed to start: {}", exit_state.failure_message()));
}
else if (exit_state.exit_code)
{
mpl::log(mpl::Level::error, category,
fmt::format("Qemu fail: '{}' with outputs:\n{}\n{}", exit_state.failure_message(),
process->read_all_standard_output(), process->read_all_standard_error()));
}
}
return QString("qemu-unknown");
}
QString mp::QemuVirtualMachineFactory::get_backend_directory_name() const
{
return qemu_platform->get_directory_name();
}
auto mp::QemuVirtualMachineFactory::networks() const -> std::vector<NetworkInterfaceInfo>
{
auto platform_ifs_info = MP_PLATFORM.get_network_interfaces_info();
std::vector<NetworkInterfaceInfo> ret;
for (const auto& ifs_info : platform_ifs_info)
{
const auto& info = ifs_info.second;
const auto& type = info.type;
if (qemu_platform->is_network_supported(type))
ret.push_back(info);
}
qemu_platform->set_authorization(ret);
return ret;
}
void mp::QemuVirtualMachineFactory::prepare_networking(std::vector<NetworkInterface>& extra_interfaces)
{
if (qemu_platform->needs_network_prep())
mp::BaseVirtualMachineFactory::prepare_networking(extra_interfaces);
}
std::string mp::QemuVirtualMachineFactory::create_bridge_with(const NetworkInterfaceInfo& interface)
{
return qemu_platform->create_bridge_with(interface);
}
| 8,317
|
C++
|
.cpp
| 177
| 34.954802
| 117
| 0.603231
|
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,734
|
qemu_virtual_machine.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_virtual_machine.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 "qemu_virtual_machine.h"
#include "qemu_mount_handler.h"
#include "qemu_snapshot.h"
#include "qemu_vm_process_spec.h"
#include "qemu_vmstate_process_spec.h"
#include <shared/qemu_img_utils/qemu_img_utils.h>
#include <shared/shared_backend_utils.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/memory_size.h>
#include <multipass/platform.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <multipass/top_catch_all.h>
#include <multipass/utils.h>
#include <multipass/vm_mount.h>
#include <multipass/vm_status_monitor.h>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QProcess>
#include <QString>
#include <QTemporaryFile>
#include <cassert>
namespace mp = multipass;
namespace mpl = multipass::logging;
using namespace std::chrono_literals;
namespace
{
constexpr auto suspend_tag = "suspend";
constexpr auto machine_type_key = "machine_type";
constexpr auto arguments_key = "arguments";
constexpr auto mount_data_key = "mount_data";
constexpr auto mount_source_key = "source";
constexpr auto mount_arguments_key = "arguments";
constexpr int shutdown_timeout = 300000; // unit: ms, 5 minute timeout for shutdown/suspend
constexpr int kill_process_timeout = 5000; // unit: ms, 5 seconds timeout for killing the process
bool use_cdrom_set(const QJsonObject& metadata)
{
return metadata.contains("use_cdrom") && metadata["use_cdrom"].toBool();
}
QString get_vm_machine(const QJsonObject& metadata)
{
QString machine;
if (metadata.contains(machine_type_key))
{
machine = metadata[machine_type_key].toString();
}
return machine;
}
QStringList get_arguments(const QJsonObject& metadata)
{
QStringList args;
if (metadata.contains(arguments_key) && metadata[arguments_key].type() == QJsonValue::Array)
{
auto array = metadata[arguments_key].toArray();
for (const QJsonValueRef val : array)
{
args.push_back(val.toString());
}
}
return args;
}
auto mount_args_from_json(const QJsonObject& object)
{
mp::QemuVirtualMachine::MountArgs mount_args;
auto mount_data_map = object[mount_data_key].toObject();
for (const auto& tag : mount_data_map.keys())
{
const auto mount_data = mount_data_map[tag].toObject();
const auto source = mount_data[mount_source_key];
auto args = mount_data[mount_arguments_key].toArray();
if (!source.isString() || !std::all_of(args.begin(), args.end(), std::mem_fn(&QJsonValueRef::isString)))
continue;
mount_args[tag.toStdString()] = {source.toString().toStdString(),
QVariant{args.toVariantList()}.toStringList()};
}
return mount_args;
}
auto make_qemu_process(const mp::VirtualMachineDescription& desc, const std::optional<QJsonObject>& resume_metadata,
const mp::QemuVirtualMachine::MountArgs& mount_args, const QStringList& platform_args)
{
if (!QFile::exists(desc.image.image_path) || !QFile::exists(desc.cloud_init_iso))
{
throw std::runtime_error("cannot start VM without an image");
}
std::optional<mp::QemuVMProcessSpec::ResumeData> resume_data;
if (resume_metadata)
{
const auto& data = resume_metadata.value();
resume_data = mp::QemuVMProcessSpec::ResumeData{suspend_tag, get_vm_machine(data), use_cdrom_set(data),
get_arguments(data)};
}
auto process_spec = std::make_unique<mp::QemuVMProcessSpec>(desc, platform_args, mount_args, resume_data);
auto process = mp::platform::make_process(std::move(process_spec));
mpl::log(mpl::Level::debug, desc.vm_name, fmt::format("process working dir '{}'", process->working_directory()));
mpl::log(mpl::Level::info, desc.vm_name, fmt::format("process program '{}'", process->program()));
mpl::log(mpl::Level::info, desc.vm_name, fmt::format("process arguments '{}'", process->arguments().join(", ")));
return process;
}
auto qmp_execute_json(const QString& cmd)
{
QJsonObject qmp;
qmp.insert("execute", cmd);
return QJsonDocument(qmp).toJson();
}
auto hmc_to_qmp_json(const QString& command_line)
{
auto qmp = QJsonDocument::fromJson(qmp_execute_json("human-monitor-command")).object();
QJsonObject cmd_line;
cmd_line.insert("command-line", command_line);
qmp.insert("arguments", cmd_line);
return QJsonDocument(qmp).toJson();
}
auto get_qemu_machine_type(const QStringList& platform_args)
{
QTemporaryFile dump_file;
if (!dump_file.open())
{
return QString();
}
auto process_spec = std::make_unique<mp::QemuVmStateProcessSpec>(dump_file.fileName(), platform_args);
auto process = mp::platform::make_process(std::move(process_spec));
auto process_state = process->execute();
if (!process_state.completed_successfully())
{
throw std::runtime_error(
fmt::format("Internal error: qemu-system-{} failed getting vmstate ({}) with output:\n{}", HOST_ARCH,
process_state.failure_message(), process->read_all_standard_error()));
}
auto vmstate = QJsonDocument::fromJson(dump_file.readAll()).object();
auto machine_type = vmstate["vmschkmachine"].toObject()["Name"].toString();
return machine_type;
}
auto mount_args_to_json(const mp::QemuVirtualMachine::MountArgs& mount_args)
{
QJsonObject object;
for (const auto& [tag, mount_data] : mount_args)
{
const auto& [source, args] = mount_data;
object[QString::fromStdString(tag)] = QJsonObject{{mount_source_key, QString::fromStdString(source)},
{mount_arguments_key, QJsonArray::fromStringList(args)}};
}
return object;
}
auto generate_metadata(const QStringList& platform_args, const QStringList& proc_args,
const mp::QemuVirtualMachine::MountArgs& mount_args)
{
QJsonObject metadata;
metadata[machine_type_key] = get_qemu_machine_type(platform_args);
metadata[arguments_key] = QJsonArray::fromStringList(proc_args);
metadata[mount_data_key] = mount_args_to_json(mount_args);
return metadata;
}
void convert_to_qcow2_v3_if_necessary(const mp::Path& image_path, const std::string& vm_name)
{
try
{
// convert existing VMs to v3 too (doesn't affect images that are already v3)
mp::backend::amend_to_qcow2_v3(image_path);
}
catch (const mp::backend::QemuImgException& e)
{
mpl::log(mpl::Level::error, vm_name, e.what());
}
}
QStringList extract_snapshot_tags(const QByteArray& snapshot_list_output_stream)
{
QStringList lines = QString{snapshot_list_output_stream}.split('\n');
QStringList snapshot_tags;
// Snapshot list:
// ID TAG VM SIZE DATE VM CLOCK ICOUNT
// 2 @s2 0 B 2024-06-11 23:22:59 00:00:00.000 0
// 3 @s3 0 B 2024-06-12 12:30:37 00:00:00.000 0
// The first two lines are headers
for (int i = 2; i < lines.size(); ++i)
{
// Qt::SkipEmptyParts improve the robustness of the code, it can keep the result correct in the case of leading
// and trailing spaces.
QStringList entries = lines[i].split(QRegularExpression{R"(\s+)"}, Qt::SkipEmptyParts);
if (entries.count() >= 2)
{
snapshot_tags.append(entries[1]);
}
}
return snapshot_tags;
}
} // namespace
mp::QemuVirtualMachine::QemuVirtualMachine(const VirtualMachineDescription& desc,
QemuPlatform* qemu_platform,
VMStatusMonitor& monitor,
const SSHKeyProvider& key_provider,
const Path& instance_dir)
: BaseVirtualMachine{mp::backend::instance_image_has_snapshot(desc.image.image_path, suspend_tag) ? State::suspended
: State::off,
desc.vm_name,
key_provider,
instance_dir},
desc{desc},
qemu_platform{qemu_platform},
monitor{&monitor},
mount_args{mount_args_from_json(monitor.retrieve_metadata_for(vm_name))}
{
convert_to_qcow2_v3_if_necessary(desc.image.image_path,
vm_name); // TODO drop in a couple of releases (went in on v1.13)
connect_vm_signals();
}
mp::QemuVirtualMachine::~QemuVirtualMachine()
{
if (vm_process)
{
update_shutdown_status = false;
mp::top_catch_all(vm_name, [this]() {
if (state == State::running)
{
suspend();
}
else
{
shutdown();
}
});
}
}
void mp::QemuVirtualMachine::start()
{
initialize_vm_process();
if (state == State::suspended)
{
mpl::log(mpl::Level::info, vm_name, fmt::format("Resuming from a suspended state"));
update_shutdown_status = true;
is_starting_from_suspend = true;
network_deadline = std::chrono::steady_clock::now() + 5s;
}
else
{
// remove the mount arguments from the rest of the arguments, as they are stored separately for easier retrieval
auto proc_args = vm_process->arguments();
for (const auto& [_, mount_data] : mount_args)
for (const auto& arg : mount_data.second)
proc_args.removeOne(arg);
monitor->update_metadata_for(vm_name,
generate_metadata(qemu_platform->vmstate_platform_args(), proc_args, mount_args));
}
vm_process->start();
connect_vm_signals();
if (!vm_process->wait_for_started())
{
auto process_state = vm_process->process_state();
if (process_state.error)
{
mpl::log(mpl::Level::error, vm_name, fmt::format("Qemu failed to start: {}", process_state.error->message));
throw std::runtime_error(fmt::format("failed to start qemu instance: {}", process_state.error->message));
}
else if (process_state.exit_code)
{
mpl::log(mpl::Level::error, vm_name,
fmt::format("Qemu quit unexpectedly with exit code {} and with output:\n{}",
process_state.exit_code.value(), vm_process->read_all_standard_error()));
throw std::runtime_error(
fmt::format("qemu quit unexpectedly with exit code {}, check logs for more details",
process_state.exit_code.value()));
}
}
vm_process->write(qmp_execute_json("qmp_capabilities"));
}
void mp::QemuVirtualMachine::shutdown(ShutdownPolicy shutdown_policy)
{
std::unique_lock<std::mutex> lock{state_mutex};
disconnect_vm_signals();
try
{
check_state_for_shutdown(shutdown_policy);
}
catch (const VMStateIdempotentException& e)
{
mpl::log(mpl::Level::info, vm_name, e.what());
return;
}
if (shutdown_policy == ShutdownPolicy::Poweroff)
{
mpl::log(mpl::Level::info, vm_name, "Forcing shutdown");
if (vm_process)
{
mpl::log(mpl::Level::info, vm_name, "Killing process");
force_shutdown = true;
lock.unlock();
vm_process->kill();
if (vm_process != nullptr && !vm_process->wait_for_finished(kill_process_timeout))
{
throw std::runtime_error{
fmt::format("The QEMU process did not finish within {} milliseconds after being killed",
kill_process_timeout)};
}
}
else
{
mpl::log(mpl::Level::debug, vm_name, "No process to kill");
}
const auto has_suspend_snapshot = mp::backend::instance_image_has_snapshot(desc.image.image_path, suspend_tag);
if (has_suspend_snapshot != (state == State::suspended)) // clang-format off
mpl::log(mpl::Level::warning, vm_name, fmt::format("Image has {} suspension snapshot, but the state is {}",
has_suspend_snapshot ? "a" : "no",
static_cast<short>(state))); // clang-format on
if (has_suspend_snapshot)
{
mpl::log(mpl::Level::info, vm_name, "Deleting suspend image");
mp::backend::delete_snapshot_from_image(desc.image.image_path, suspend_tag);
}
state = State::off;
}
else
{
lock.unlock();
drop_ssh_session();
if (vm_process && vm_process->running())
{
vm_process->write(qmp_execute_json("system_powerdown"));
if (vm_process->wait_for_finished(shutdown_timeout))
{
lock.lock();
state = State::off;
}
else
{
throw std::runtime_error{
fmt::format("The QEMU process did not finish within {} milliseconds after being shutdown",
shutdown_timeout)};
}
}
}
}
void mp::QemuVirtualMachine::suspend()
{
if ((state == State::running || state == State::delayed_shutdown) && vm_process->running())
{
if (update_shutdown_status)
{
state = State::suspending;
update_state();
update_shutdown_status = false;
}
drop_ssh_session();
vm_process->write(hmc_to_qmp_json(QString{"savevm "} + suspend_tag));
vm_process->wait_for_finished(shutdown_timeout);
vm_process.reset(nullptr);
}
else if (state == State::off || state == State::suspended)
{
mpl::log(mpl::Level::info, vm_name, fmt::format("Ignoring suspend issued while stopped/suspended"));
monitor->on_suspend();
}
}
mp::VirtualMachine::State mp::QemuVirtualMachine::current_state()
{
return state;
}
int mp::QemuVirtualMachine::ssh_port()
{
return 22;
}
void mp::QemuVirtualMachine::update_state()
{
monitor->persist_state_for(vm_name, state);
}
void mp::QemuVirtualMachine::on_started()
{
state = VirtualMachine::State::starting;
update_state();
monitor->on_resume();
}
void mp::QemuVirtualMachine::on_error()
{
state = State::off;
update_state();
}
void mp::QemuVirtualMachine::on_shutdown()
{
{
std::unique_lock<decltype(state_mutex)> lock{state_mutex};
auto current_state = state;
state = State::off;
if (current_state == State::starting)
{
if (!saved_error_msg.empty() && saved_error_msg.back() != '\n')
saved_error_msg.append("\n");
saved_error_msg.append(fmt::format("{}: shutdown called while starting", vm_name));
state_wait.wait(lock, [this] { return shutdown_while_starting; });
}
management_ip = std::nullopt;
drop_ssh_session();
update_state();
vm_process.reset(nullptr);
}
monitor->on_shutdown();
}
void mp::QemuVirtualMachine::on_suspend()
{
drop_ssh_session();
state = State::suspended;
monitor->on_suspend();
}
void mp::QemuVirtualMachine::on_restart()
{
drop_ssh_session();
state = State::restarting;
update_state();
management_ip = std::nullopt;
monitor->on_restart(vm_name);
}
void mp::QemuVirtualMachine::ensure_vm_is_running()
{
if (is_starting_from_suspend)
{
// Due to https://github.com/canonical/multipass/issues/2374, the DHCP address is removed from
// the dnsmasq leases file, so if the daemon restarts while an instance is suspended and then
// starts the instance, the daemon won't be able to reach the instance since the instance
// won't refresh it's IP address. The following will force the instance to refresh by resetting
// the network at 5 seconds and then every 30 seconds until the start timeout is reached.
if (std::chrono::steady_clock::now() > network_deadline)
{
network_deadline = std::chrono::steady_clock::now() + 30s;
emit on_reset_network();
}
}
auto is_vm_running = [this] { return (vm_process && vm_process->running()); };
mp::backend::ensure_vm_is_running_for(this, is_vm_running, saved_error_msg);
}
std::string mp::QemuVirtualMachine::ssh_hostname(std::chrono::milliseconds timeout)
{
auto get_ip = [this]() -> std::optional<IPAddress> { return qemu_platform->get_ip_for(desc.default_mac_address); };
return mp::backend::ip_address_for(this, get_ip, timeout);
}
std::string mp::QemuVirtualMachine::ssh_username()
{
return desc.ssh_username;
}
std::string mp::QemuVirtualMachine::management_ipv4()
{
if (!management_ip)
{
auto result = qemu_platform->get_ip_for(desc.default_mac_address);
if (result)
management_ip.emplace(result.value());
else
return "UNKNOWN";
}
return management_ip.value().as_string();
}
std::string mp::QemuVirtualMachine::ipv6()
{
return {};
}
void mp::QemuVirtualMachine::wait_until_ssh_up(std::chrono::milliseconds timeout)
{
BaseVirtualMachine::wait_until_ssh_up(timeout);
if (is_starting_from_suspend)
{
emit on_delete_memory_snapshot();
emit on_synchronize_clock();
}
}
void mp::QemuVirtualMachine::initialize_vm_process()
{
vm_process = make_qemu_process(
desc,
((state == State::suspended) ? std::make_optional(monitor->retrieve_metadata_for(vm_name)) : std::nullopt),
mount_args, qemu_platform->vm_platform_args(desc));
QObject::connect(vm_process.get(), &Process::started, [this]() {
mpl::log(mpl::Level::info, vm_name, "process started");
on_started();
});
QObject::connect(vm_process.get(), &Process::ready_read_standard_output, [this]() {
auto qmp_output = vm_process->read_all_standard_output();
mpl::log(mpl::Level::debug, vm_name, fmt::format("QMP: {}", qmp_output));
auto qmp_object = QJsonDocument::fromJson(qmp_output.split('\n').first()).object();
auto event = qmp_object["event"];
if (!event.isNull())
{
if (event.toString() == "RESET" && state != State::restarting)
{
mpl::log(mpl::Level::info, vm_name, "VM restarting");
on_restart();
}
else if (event.toString() == "POWERDOWN")
{
mpl::log(mpl::Level::info, vm_name, "VM powering down");
}
else if (event.toString() == "SHUTDOWN")
{
mpl::log(mpl::Level::info, vm_name, "VM shut down");
}
else if (event.toString() == "STOP")
{
mpl::log(mpl::Level::info, vm_name, "VM suspending");
}
else if (event.toString() == "RESUME")
{
mpl::log(mpl::Level::info, vm_name, "VM suspended");
if (state == State::suspending || state == State::running)
{
vm_process->kill();
on_suspend();
}
}
}
});
QObject::connect(vm_process.get(), &Process::ready_read_standard_error, [this]() {
saved_error_msg = vm_process->read_all_standard_error().data();
mpl::log(mpl::Level::warning, vm_name, saved_error_msg);
});
QObject::connect(vm_process.get(), &Process::state_changed, [this](QProcess::ProcessState newState) {
mpl::log(mpl::Level::info, vm_name,
fmt::format("process state changed to {}", utils::qenum_to_string(newState)));
});
QObject::connect(
vm_process.get(), &Process::error_occurred, [this](QProcess::ProcessError error, QString error_string) {
// We just kill the process when suspending, so we don't want to print
// out any scary error messages for this state
if (update_shutdown_status)
{
const auto log_level = force_shutdown ? mpl::Level::info : mpl::Level::error;
mpl::log(log_level,
vm_name,
fmt::format("process error occurred {} {}", utils::qenum_to_string(error), error_string));
on_error();
}
});
QObject::connect(vm_process.get(), &Process::finished, [this](ProcessState process_state) {
if (process_state.exit_code)
{
mpl::log(mpl::Level::info, vm_name,
fmt::format("process finished with exit code {}", process_state.exit_code.value()));
}
if (process_state.error)
{
if (process_state.error->state == QProcess::Crashed &&
(state == State::suspending || state == State::suspended))
{
// when suspending, we ask Qemu to savevm. Once it confirms that's done, we kill it. Catch the "crash"
mpl::log(mpl::Level::debug, vm_name, "Suspended VM successfully stopped");
}
else
{
const auto log_level = force_shutdown ? mpl::Level::info : mpl::Level::error;
mpl::log(log_level, vm_name, fmt::format("error: {}", process_state.error->message));
// reset force_shutdown so that subsequent errors can be accurately reported
force_shutdown = false;
}
}
if (update_shutdown_status || state == State::starting)
{
on_shutdown();
}
});
}
void mp::QemuVirtualMachine::connect_vm_signals()
{
std::unique_lock lock{vm_signal_mutex};
if (vm_signals_connected)
return;
QObject::connect(
this,
&QemuVirtualMachine::on_delete_memory_snapshot,
this,
[this] {
mpl::log(mpl::Level::debug, vm_name, fmt::format("Deleted memory snapshot"));
vm_process->write(hmc_to_qmp_json(QString("delvm ") + suspend_tag));
is_starting_from_suspend = false;
},
Qt::QueuedConnection);
// The following is the actual code to reset the network via QMP if an IP address is not obtained after
// starting from suspend. This will probably be deprecated in the future.
QObject::connect(
this,
&QemuVirtualMachine::on_reset_network,
this,
[this] {
mpl::log(mpl::Level::debug, vm_name, fmt::format("Resetting the network"));
auto qmp = QJsonDocument::fromJson(qmp_execute_json("set_link")).object();
QJsonObject args;
args.insert("name", "virtio-net-pci.0");
args.insert("up", false);
qmp.insert("arguments", args);
vm_process->write(QJsonDocument(qmp).toJson());
args["up"] = true;
qmp["arguments"] = args;
vm_process->write(QJsonDocument(qmp).toJson());
},
Qt::QueuedConnection);
QObject::connect(
this,
&QemuVirtualMachine::on_synchronize_clock,
this,
[this]() {
try
{
mpl::log(mpl::Level::debug, vm_name, fmt::format("Syncing RTC clock"));
ssh_exec("sudo timedatectl set-local-rtc 0 --adjust-system-clock");
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, vm_name, fmt::format("Failed to sync clock: {}", e.what()));
}
},
Qt::QueuedConnection);
vm_signals_connected = true;
}
void mp::QemuVirtualMachine::disconnect_vm_signals()
{
std::unique_lock lock{vm_signal_mutex};
disconnect(this, &QemuVirtualMachine::on_delete_memory_snapshot, nullptr, nullptr);
disconnect(this, &QemuVirtualMachine::on_reset_network, nullptr, nullptr);
disconnect(this, &QemuVirtualMachine::on_synchronize_clock, nullptr, nullptr);
vm_signals_connected = false;
}
void mp::QemuVirtualMachine::update_cpus(int num_cores)
{
assert(num_cores > 0);
desc.num_cores = num_cores;
}
void mp::QemuVirtualMachine::resize_memory(const MemorySize& new_size)
{
desc.mem_size = new_size;
}
void mp::QemuVirtualMachine::resize_disk(const MemorySize& new_size)
{
assert(new_size > desc.disk_space);
mp::backend::resize_instance_image(new_size, desc.image.image_path);
desc.disk_space = new_size;
}
void mp::QemuVirtualMachine::add_network_interface(int /* not used on this backend */,
const std::string& default_mac_addr,
const NetworkInterface& extra_interface)
{
desc.extra_interfaces.push_back(extra_interface);
add_extra_interface_to_instance_cloud_init(default_mac_addr, extra_interface);
}
mp::MountHandler::UPtr mp::QemuVirtualMachine::make_native_mount_handler(const std::string& target,
const VMMount& mount)
{
return std::make_unique<QemuMountHandler>(this, &key_provider, target, mount);
}
void mp::QemuVirtualMachine::remove_snapshots_from_image() const
{
const QStringList snapshot_tag_list = extract_snapshot_tags(backend::snapshot_list_output(desc.image.image_path));
for (const auto& snapshot_tag : snapshot_tag_list)
{
backend::delete_snapshot_from_image(desc.image.image_path, snapshot_tag);
}
}
mp::QemuVirtualMachine::MountArgs& mp::QemuVirtualMachine::modifiable_mount_args()
{
return mount_args;
}
auto mp::QemuVirtualMachine::make_specific_snapshot(const std::string& snapshot_name,
const std::string& comment,
const std::string& instance_id,
const VMSpecs& specs,
std::shared_ptr<Snapshot> parent) -> std::shared_ptr<Snapshot>
{
assert(state == VirtualMachine::State::off || state == VirtualMachine::State::stopped); // would need QMP otherwise
return std::make_shared<QemuSnapshot>(snapshot_name, comment, instance_id, std::move(parent), specs, *this, desc);
}
auto mp::QemuVirtualMachine::make_specific_snapshot(const QString& filename) -> std::shared_ptr<Snapshot>
{
return std::make_shared<QemuSnapshot>(filename, *this, desc);
}
| 27,494
|
C++
|
.cpp
| 685
| 31.652555
| 120
| 0.60786
|
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,735
|
qemu_vm_process_spec.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_vm_process_spec.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 "qemu_vm_process_spec.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/snap_utils.h>
#include <shared/linux/backend_utils.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
mp::QemuVMProcessSpec::QemuVMProcessSpec(const mp::VirtualMachineDescription& desc, const QStringList& platform_args,
const mp::QemuVirtualMachine::MountArgs& mount_args,
const std::optional<ResumeData>& resume_data)
: desc{desc}, platform_args{platform_args}, mount_args{mount_args}, resume_data{resume_data}
{
}
QStringList mp::QemuVMProcessSpec::arguments() const
{
QStringList args;
if (resume_data)
{
args = resume_data->arguments;
// need to append extra arguments for resume
args << "-loadvm" << resume_data->suspend_tag;
QString machine_type = resume_data->machine_type;
if (!machine_type.isEmpty())
{
args << "-machine" << machine_type;
}
else
{
mpl::log(mpl::Level::info, desc.vm_name,
fmt::format("Cannot determine QEMU machine type. Falling back to system default."));
}
// need to fix old-style vmnet arguments
// TODO: remove in due time
args.replaceInStrings("vmnet-macos,mode=shared,", "vmnet-shared,");
}
else
{
auto mem_size = QString::number(desc.mem_size.in_megabytes()) + 'M'; /* flooring here; format documented in
`man qemu-system`, under `-m` option; including suffix to avoid relying on default unit */
args << platform_args;
// The VM image itself
args << "-device"
<< "virtio-scsi-pci,id=scsi0"
<< "-drive" << QString("file=%1,if=none,format=qcow2,discard=unmap,id=hda").arg(desc.image.image_path)
<< "-device"
<< "scsi-hd,drive=hda,bus=scsi0.0";
// Number of cpu cores
args << "-smp" << QString::number(desc.num_cores);
// Memory to use for VM
args << "-m" << mem_size;
// Control interface
args << "-qmp"
<< "stdio";
// No console
args << "-chardev"
// TODO Read and log machine output when verbose
<< "null,id=char0"
<< "-serial"
<< "chardev:char0"
// TODO Add a debugging mode with access to console
<< "-nographic";
// Cloud-init disk
args << "-cdrom" << desc.cloud_init_iso;
}
for (const auto& [_, mount_data] : mount_args)
{
const auto& [__, mount_args] = mount_data;
args << mount_args;
}
return args;
}
QString mp::QemuVMProcessSpec::apparmor_profile() const
{
// Following profile is based on /etc/apparmor.d/abstractions/libvirt-qemu
QString profile_template(R"END(
#include <tunables/global>
profile %1 flags=(attach_disconnected) {
#include <abstractions/base>
#include <abstractions/consoles>
#include <abstractions/nameservice>
# required for reading disk images
capability dac_override,
capability dac_read_search,
capability chown,
# Enables modifying of file ownership and permissions
capability fsetid,
capability fowner,
# needed to drop privileges
capability setgid,
capability setuid,
network inet stream,
network inet6 stream,
# Allow multipassd send qemu signals
signal (receive) peer=%2,
/dev/net/tun rw,
/dev/kvm rw,
/dev/ptmx rw,
/dev/kqemu rw,
@{PROC}/*/status r,
# When qemu is signaled to terminate, it will read cmdline of signaling
# process for reporting purposes. Allowing read access to a process
# cmdline may leak sensitive information embedded in the cmdline.
@{PROC}/@{pid}/cmdline r,
# Per man(5) proc, the kernel enforces that a thread may
# only modify its comm value or those in its thread group.
owner @{PROC}/@{pid}/task/@{tid}/comm rw,
@{PROC}/sys/kernel/cap_last_cap r,
owner @{PROC}/*/auxv r,
@{PROC}/sys/vm/overcommit_memory r,
# access to firmware's etc (selectively chosen for multipass' usage)
%3 r,
# for save and resume
/{usr/,}bin/dash rmix,
/{usr/,}bin/dd rmix,
/{usr/,}bin/cat rmix,
# to execute bridge helper
%4/bin/bridge_helper,
# for restore
/{usr/,}bin/bash rmix,
# for file-posix getting limits since 9103f1ce
/sys/devices/**/block/*/queue/max_segments r,
# for gathering information about available host resources
/sys/devices/system/cpu/ r,
/sys/devices/system/node/ r,
/sys/devices/system/node/node[0-9]*/meminfo r,
/sys/module/vhost/parameters/max_mem_regions r,
# binary and its libs
%4/usr/bin/%5 ixr,
%4/{,usr/}lib/{,@{multiarch}/}{,**/}*.so* rm,
# CLASSIC ONLY: need to specify required libs from core snap
/{,var/lib/snapd/}snap/core18/*/{,usr/}lib/@{multiarch}/{,**/}*.so* rm,
# Disk images
%6 rwk, # QCow2 filesystem image
%7 rk, # cloud-init ISO
# allow full access just to user-specified mount directories on the host
%8
}
)END");
/* Customisations depending on if running inside snap or not */
QString root_dir; // root directory: either "" or $SNAP
QString signal_peer; // who can send kill signal to qemu
QString firmware; // location of bootloader firmware needed by qemu
QString mount_dirs; // directories on host that are mounted
for (const auto& [_, mount_data] : mount_args)
{
const auto& [source_path, __] = mount_data;
mount_dirs += QString::fromStdString(source_path) + "/ rw,\n ";
mount_dirs += QString::fromStdString(source_path) + "/** rwlk,\n ";
}
try
{
root_dir = mpu::snap_dir();
signal_peer = "snap.multipass.multipassd"; // only multipassd can send qemu signals
firmware = root_dir + "/qemu/*"; // if snap confined, firmware in $SNAP/qemu
}
catch (const mp::SnapEnvironmentException&)
{
signal_peer = "unconfined";
firmware = "/usr{,/local}/share/{seabios,ovmf,qemu,qemu-efi}/*";
}
return profile_template.arg(apparmor_profile_name(), signal_peer, firmware, root_dir, program(),
desc.image.image_path, desc.cloud_init_iso, mount_dirs);
}
QString mp::QemuVMProcessSpec::identifier() const
{
return QString::fromStdString(desc.vm_name);
}
| 7,117
|
C++
|
.cpp
| 185
| 32.643243
| 117
| 0.652943
|
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,736
|
qemu_snapshot.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_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 "qemu_snapshot.h"
#include "qemu_virtual_machine.h"
#include "shared/qemu_img_utils/qemu_img_utils.h"
#include <multipass/logging/log.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <multipass/top_catch_all.h>
#include <multipass/virtual_machine_description.h>
#include <scope_guard.hpp>
#include <memory>
namespace mp = multipass;
namespace
{
std::unique_ptr<mp::QemuImgProcessSpec> make_capture_spec(const QString& tag, const mp::Path& image_path)
{
return std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-c", tag, image_path},
/* src_img = */ "",
image_path);
}
std::unique_ptr<mp::QemuImgProcessSpec> make_restore_spec(const QString& tag, const mp::Path& image_path)
{
return std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-a", tag, image_path},
/* src_img = */ "",
image_path);
}
std::unique_ptr<mp::QemuImgProcessSpec> make_delete_spec(const QString& tag, const mp::Path& image_path)
{
return std::make_unique<mp::QemuImgProcessSpec>(QStringList{"snapshot", "-d", tag, image_path},
/* src_img = */ "",
image_path);
}
} // namespace
mp::QemuSnapshot::QemuSnapshot(const std::string& name,
const std::string& comment,
const std::string& cloud_init_instance_id,
std::shared_ptr<Snapshot> parent,
const VMSpecs& specs,
QemuVirtualMachine& vm,
VirtualMachineDescription& desc)
: BaseSnapshot{name, comment, cloud_init_instance_id, std::move(parent), specs, vm},
desc{desc},
image_path{desc.image.image_path}
{
}
mp::QemuSnapshot::QemuSnapshot(const QString& filename, QemuVirtualMachine& vm, VirtualMachineDescription& desc)
: BaseSnapshot{filename, vm, desc}, desc{desc}, image_path{desc.image.image_path}
{
}
void mp::QemuSnapshot::capture_impl()
{
const auto& tag = get_id();
// Avoid creating more than one snapshot with the same tag (creation would succeed, but we'd then be unable to
// identify the snapshot by tag)
if (backend::instance_image_has_snapshot(image_path, tag))
throw std::runtime_error{
fmt::format("A snapshot with the same tag already exists in the image. Image: {}; tag: {})",
image_path,
tag)};
mp::backend::checked_exec_qemu_img(make_capture_spec(tag, image_path));
}
void mp::QemuSnapshot::erase_impl()
{
const auto& tag = get_id();
if (backend::instance_image_has_snapshot(image_path, tag))
mp::backend::checked_exec_qemu_img(make_delete_spec(tag, image_path));
else
mpl::log(
mpl::Level::warning,
BaseSnapshot::get_name(),
fmt::format("Could not find the underlying QEMU snapshot. Assuming it is already gone. Image: {}; tag: {}",
image_path,
tag));
}
void mp::QemuSnapshot::apply_impl()
{
auto rollback = sg::make_scope_guard(
[this, old_desc = desc]() noexcept { top_catch_all(get_name(), [this, &old_desc]() { desc = old_desc; }); });
desc.num_cores = get_num_cores();
desc.mem_size = get_mem_size();
desc.disk_space = get_disk_space();
desc.extra_interfaces = get_extra_interfaces();
mp::backend::checked_exec_qemu_img(make_restore_spec(get_id(), image_path));
rollback.dismiss();
}
| 4,390
|
C++
|
.cpp
| 99
| 35.282828
| 119
| 0.613243
|
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,737
|
qemu_vmstate_process_spec.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_vmstate_process_spec.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 "qemu_vmstate_process_spec.h"
namespace mp = multipass;
mp::QemuVmStateProcessSpec::QemuVmStateProcessSpec(const QString& file_name, const QStringList& platform_args)
: file_name{file_name}, platform_args{platform_args}
{
}
QStringList mp::QemuVmStateProcessSpec::arguments() const
{
QStringList args;
args << platform_args;
args << "-nographic"
<< "-dump-vmstate" << file_name;
return args;
}
| 1,067
|
C++
|
.cpp
| 30
| 32.866667
| 110
| 0.74466
|
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,738
|
qemu_mount_handler.cpp
|
canonical_multipass/src/platform/backends/qemu/qemu_mount_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 "qemu_mount_handler.h"
#include <multipass/utils.h>
#include <QUuid>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "qemu-mount-handler";
} // namespace
namespace multipass
{
QemuMountHandler::QemuMountHandler(QemuVirtualMachine* vm,
const SSHKeyProvider* ssh_key_provider,
const std::string& target,
VMMount mount_spec)
: MountHandler{vm, ssh_key_provider, std::move(mount_spec), target},
vm_mount_args{vm->modifiable_mount_args()},
// Create a reproducible unique mount tag for each mount. The cmd arg can only be 31 bytes long so part of the
// uuid must be truncated. First character of tag must also be alphabetical.
tag{mp::utils::make_uuid(target).remove("-").left(30).prepend('m').toStdString()}
{
auto state = vm->current_state();
if (state == VirtualMachine::State::suspended && vm_mount_args.find(tag) != vm_mount_args.end())
{
mpl::log(mpl::Level::info, category,
fmt::format("Found native mount {} => {} in '{}' while suspended", source, target, vm->vm_name));
return;
}
if (state != VirtualMachine::State::off && state != VirtualMachine::State::stopped)
{
throw mp::NativeMountNeedsStoppedVMException(vm->vm_name);
}
// Need to ensure no more than one uid/gid map is passed in here.
if (this->mount_spec.get_uid_mappings().size() > 1 || this->mount_spec.get_gid_mappings().size() > 1)
throw std::runtime_error("Only one mapping per native mount allowed.");
mpl::log(mpl::Level::info, category,
fmt::format("initializing native mount {} => {} in '{}'", source, target, vm->vm_name));
const auto uid_map = this->mount_spec.get_uid_mappings().empty() ? std::make_pair(1000, 1000)
: this->mount_spec.get_uid_mappings()[0];
const auto gid_map = this->mount_spec.get_gid_mappings().empty() ? std::make_pair(1000, 1000)
: this->mount_spec.get_gid_mappings()[0];
const auto uid_arg = QString("uid_map=%1:%2,").arg(uid_map.first).arg(uid_map.second == -1 ? 1000 : uid_map.second);
const auto gid_arg = QString{"gid_map=%1:%2,"}.arg(gid_map.first).arg(gid_map.second == -1 ? 1000 : gid_map.second);
vm_mount_args[tag] = {
source,
{"-virtfs", QString::fromStdString(fmt::format("local,security_model=passthrough,{}{}path={},mount_tag={}",
uid_arg, gid_arg, source, tag))}};
}
bool QemuMountHandler::is_active()
try
{
return active && !SSHSession{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider}
.exec(fmt::format("findmnt --type 9p | grep '{} {}'", target, tag))
.exit_code();
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Failed checking 9p mount \"{}\" in instance '{}': {}", target, vm->vm_name, e.what()));
return false;
}
void QemuMountHandler::activate_impl(ServerVariant, std::chrono::milliseconds)
{
SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider};
// Split the path in existing and missing parts
// We need to create the part of the path which does not still exist, and set then the correct ownership.
if (const auto& [leading, missing] = mpu::get_path_split(session, target); missing != ".")
{
const auto default_uid = std::stoi(MP_UTILS.run_in_ssh_session(session, "id -u"));
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): `id -u` = {}", __FILE__, __LINE__, __FUNCTION__, default_uid));
const auto default_gid = std::stoi(MP_UTILS.run_in_ssh_session(session, "id -g"));
mpl::log(mpl::Level::debug, category,
fmt::format("{}:{} {}(): `id -g` = {}", __FILE__, __LINE__, __FUNCTION__, default_gid));
mpu::make_target_dir(session, leading, missing);
mpu::set_owner_for(session, leading, missing, default_uid, default_gid);
}
MP_UTILS.run_in_ssh_session(
session,
fmt::format("sudo mount -t 9p {} {} -o trans=virtio,version=9p2000.L,msize=536870912", tag, target));
}
void QemuMountHandler::deactivate_impl(bool force)
try
{
mpl::log(mpl::Level::info, category,
fmt::format("Stopping native mount \"{}\" in instance '{}'", target, vm->vm_name));
SSHSession session{vm->ssh_hostname(), vm->ssh_port(), vm->ssh_username(), *ssh_key_provider};
MP_UTILS.run_in_ssh_session(session,
fmt::format("if mountpoint -q {0}; then sudo umount {0}; else true; fi", target));
}
catch (const std::exception& e)
{
if (!force)
throw;
mpl::log(mpl::Level::warning, category,
fmt::format("Failed to gracefully stop mount \"{}\" in instance '{}': {}", target, vm->vm_name, e.what()));
}
QemuMountHandler::~QemuMountHandler()
{
deactivate(/*force=*/true);
vm_mount_args.erase(tag);
}
} // namespace multipass
| 5,929
|
C++
|
.cpp
| 120
| 41.8
| 120
| 0.617231
|
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,739
|
dnsmasq_server.cpp
|
canonical_multipass/src/platform/backends/qemu/linux/dnsmasq_server.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 "dnsmasq_server.h"
#include "dnsmasq_process_spec.h"
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/process/process.h>
#include <multipass/utils.h>
#include <shared/linux/process_factory.h>
#include <QDir>
#include <fstream>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto immediate_wait = 100; // period to wait for immediate dnsmasq failures, in ms
auto make_dnsmasq_process(const mp::Path& data_dir, const QString& bridge_name, const std::string& subnet,
const QString& conf_file_path)
{
auto process_spec = std::make_unique<mp::DNSMasqProcessSpec>(data_dir, bridge_name, subnet, conf_file_path);
return MP_PROCFACTORY.create_process(std::move(process_spec));
}
} // namespace
mp::DNSMasqServer::DNSMasqServer(const Path& data_dir, const QString& bridge_name, const std::string& subnet)
: data_dir{data_dir},
bridge_name{bridge_name},
subnet{subnet},
conf_file{QDir(data_dir).absoluteFilePath("dnsmasq-XXXXXX.conf")}
{
conf_file.open();
conf_file.close();
QFile dnsmasq_hosts(QDir(data_dir).filePath("dnsmasq.hosts"));
if (!dnsmasq_hosts.exists())
{
dnsmasq_hosts.open(QIODevice::WriteOnly);
}
dnsmasq_cmd = make_dnsmasq_process(data_dir, bridge_name, subnet, conf_file.fileName());
start_dnsmasq();
}
mp::DNSMasqServer::~DNSMasqServer()
{
if (dnsmasq_cmd && dnsmasq_cmd->running())
{
QObject::disconnect(finish_connection);
mpl::log(mpl::Level::debug, "dnsmasq", "terminating");
dnsmasq_cmd->terminate();
if (!dnsmasq_cmd->wait_for_finished(1000))
{
mpl::log(mpl::Level::info, "dnsmasq", "failed to terminate nicely, killing");
dnsmasq_cmd->kill();
if (!dnsmasq_cmd->wait_for_finished(100))
mpl::log(mpl::Level::warning, "dnsmasq", "failed to kill");
}
}
}
std::optional<mp::IPAddress> mp::DNSMasqServer::get_ip_for(const std::string& hw_addr)
{
// DNSMasq leases entries consist of:
// <lease expiration> <mac addr> <ipv4> <name> * * *
const auto path = QDir(data_dir).filePath("dnsmasq.leases").toStdString();
const std::string delimiter{" "};
const int hw_addr_idx{1};
const int ipv4_idx{2};
std::ifstream leases_file{path};
std::string line;
while (getline(leases_file, line))
{
const auto fields = mp::utils::split(line, delimiter);
if (fields.size() > 2 && fields[hw_addr_idx] == hw_addr)
return fields[ipv4_idx];
}
return std::nullopt;
}
void mp::DNSMasqServer::release_mac(const std::string& hw_addr)
{
auto ip = get_ip_for(hw_addr);
if (!ip)
{
mpl::log(mpl::Level::warning, "dnsmasq", fmt::format("attempting to release non-existent addr: {}", hw_addr));
return;
}
QProcess dhcp_release;
QObject::connect(&dhcp_release, &QProcess::errorOccurred, [&ip, &hw_addr](QProcess::ProcessError error) {
mpl::log(mpl::Level::warning, "dnsmasq",
fmt::format("failed to release ip addr {} with mac {}: {}", ip.value().as_string(), hw_addr,
utils::qenum_to_string(error)));
});
auto log_exit_status = [&ip, &hw_addr](int exit_code, QProcess::ExitStatus exit_status) {
if (exit_code == 0 && exit_status == QProcess::NormalExit)
return;
auto msg = fmt::format("failed to release ip addr {} with mac {}, exit_code: {}", ip.value().as_string(),
hw_addr, exit_code);
mpl::log(mpl::Level::warning, "dnsmasq", msg);
};
QObject::connect(&dhcp_release, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
log_exit_status);
dhcp_release.start("dhcp_release", QStringList() << bridge_name << QString::fromStdString(ip.value().as_string())
<< QString::fromStdString(hw_addr));
dhcp_release.waitForFinished();
}
void mp::DNSMasqServer::check_dnsmasq_running()
{
if (!dnsmasq_cmd->running())
{
mpl::log(mpl::Level::warning, "dnsmasq", "Not running");
start_dnsmasq();
}
}
namespace
{
std::string dnsmasq_failure_msg(std::string err_base, const mp::ProcessState& state)
{
if (auto err_detail = state.failure_message(); !err_detail.isEmpty())
err_base += fmt::format(": {}", err_detail);
return err_base;
}
std::string dnsmasq_failure_msg(const mp::ProcessState& state)
{
auto err_msg = dnsmasq_failure_msg("dnsmasq died", state);
if (state.exit_code == 2)
err_msg += ". Ensure nothing is using port 53.";
return err_msg;
}
} // namespace
void mp::DNSMasqServer::start_dnsmasq()
{
mpl::log(mpl::Level::debug, "dnsmasq", "Starting dnsmasq");
finish_connection = QObject::connect(dnsmasq_cmd.get(), &mp::Process::finished, [](const ProcessState& state) {
mpl::log(mpl::Level::error, "dnsmasq", dnsmasq_failure_msg(state));
});
dnsmasq_cmd->start();
if (!dnsmasq_cmd->wait_for_started())
{
auto err_msg = dnsmasq_failure_msg("Multipass dnsmasq failed to start", dnsmasq_cmd->process_state());
dnsmasq_cmd->kill();
throw std::runtime_error(err_msg);
}
if (dnsmasq_cmd->wait_for_finished(immediate_wait)) // detect immediate failures (in the first few milliseconds)
throw std::runtime_error{dnsmasq_failure_msg(dnsmasq_cmd->process_state())};
}
mp::DNSMasqServer::UPtr mp::DNSMasqServerFactory::make_dnsmasq_server(const mp::Path& network_dir,
const QString& bridge_name,
const std::string& subnet) const
{
return std::make_unique<mp::DNSMasqServer>(network_dir, bridge_name, subnet);
}
| 6,566
|
C++
|
.cpp
| 160
| 34.6
| 118
| 0.643866
|
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,740
|
firewall_config.cpp
|
canonical_multipass/src/platform/backends/qemu/linux/firewall_config.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 "firewall_config.h"
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/process/process.h>
#include <multipass/top_catch_all.h>
#include <multipass/utils.h>
#include <shared/linux/process_factory.h>
#include <semver200.h>
#include <stdexcept>
#include <QRegularExpression>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "firewall";
// QString constants for all of the different firewall calls
const QString iptables{QStringLiteral("iptables-legacy")};
const QString nftables{QStringLiteral("iptables-nft")};
const QString negate{QStringLiteral("!")};
// Different tables to use
const QString filter{QStringLiteral("filter")};
const QString nat{QStringLiteral("nat")};
const QString mangle{QStringLiteral("mangle")};
const QString raw{QStringLiteral("raw")};
// List of all tables
const QStringList firewall_tables{filter, nat, mangle, raw};
// Chain constants
const QString INPUT{QStringLiteral("INPUT")};
const QString OUTPUT{QStringLiteral("OUTPUT")};
const QString POSTROUTING{QStringLiteral("POSTROUTING")};
const QString FORWARD{QStringLiteral("FORWARD")};
// option constants
const QString destination{QStringLiteral("--destination")};
const QString delete_rule{QStringLiteral("--delete")};
const QString in_interface{QStringLiteral("--in-interface")};
const QString append_rule{QStringLiteral("--append")};
const QString insert_rule{QStringLiteral("--insert")};
const QString jump{QStringLiteral("--jump")};
const QString match{QStringLiteral("--match")};
const QString out_interface{QStringLiteral("--out-interface")};
const QString protocol{QStringLiteral("--protocol")};
const QString source{QStringLiteral("--source")};
const QString list_rules{QStringLiteral("--list-rules")};
const QString dash_t{QStringLiteral("-t")}; // Use short option for specifying table to avoid var conflicts
const QString wait{QStringLiteral("--wait")};
// protocol constants
const QString udp{QStringLiteral("udp")};
const QString tcp{QStringLiteral("tcp")};
// port options and constants
const QString dport{QStringLiteral("--dport")};
const QString sport{QStringLiteral("--sport")};
const QString to_ports{QStringLiteral("--to-ports")};
const QString port_53{QStringLiteral("53")};
const QString port_67{QStringLiteral("67")};
const QString port_68{QStringLiteral("68")};
const QString port_range{QStringLiteral("1024-65535")};
// rule target constants
const QString ACCEPT{QStringLiteral("ACCEPT")};
const QString MASQUERADE{QStringLiteral("MASQUERADE")};
const QString REJECT{QStringLiteral("REJECT")};
const QString RETURN{QStringLiteral("RETURN")};
// reject rule constants
const QString reject_with{QStringLiteral("--reject-with")};
const QString icmp_port_unreachable{QStringLiteral("icmp-port-unreachable")};
class FirewallException : public std::runtime_error
{
public:
FirewallException(const QString& issue, const QString& table, const QString& failure, const QString& output)
: runtime_error{fmt::format("{}; Table: {}; Failure: {}; Output: {}", issue, table, failure, output)} {};
};
auto multipass_firewall_comment(const QString& bridge_name)
{
return QString("generated for Multipass network %1").arg(bridge_name);
}
void add_firewall_rule(const QString& firewall, const QString& table, const QString& chain, const QStringList& rule,
bool append = false)
{
auto process = MP_PROCFACTORY.create_process(
firewall, QStringList() << wait << dash_t << table << (append ? append_rule : insert_rule) << chain << rule);
auto exit_state = process->execute();
if (!exit_state.completed_successfully())
throw FirewallException("Failed to set firewall rule", table, exit_state.failure_message(),
process->read_all_standard_error());
}
void delete_firewall_rule(const QString& firewall, const QString& table, const QStringList& chain_and_rule)
{
auto args = QStringList() << firewall << wait << dash_t << table << delete_rule << chain_and_rule;
auto process =
MP_PROCFACTORY.create_process(QStringLiteral("sh"), QStringList() << QStringLiteral("-c") << args.join(" "));
auto exit_state = process->execute();
if (!exit_state.completed_successfully())
throw FirewallException("Failed to delete firewall rule", table, exit_state.failure_message(),
process->read_all_standard_error());
}
auto get_firewall_rules(const QString& firewall, const QString& table)
{
// TODO: Parse out stderr so as not to log noisy warnings from iptables-nft when legacy iptables are in use
auto process = MP_PROCFACTORY.create_process(firewall, QStringList() << wait << dash_t << table << list_rules);
auto exit_state = process->execute();
if (!exit_state.completed_successfully())
throw FirewallException("Failed to get firewall list", table, exit_state.failure_message(),
process->read_all_standard_error());
return process->read_all_standard_output();
}
void set_firewall_rules(const QString& firewall, const QString& bridge_name, const QString& cidr,
const QString& comment)
{
const QStringList comment_option{match, QStringLiteral("comment"), QStringLiteral("--comment"), comment};
// Setup basic firewall overrides for DHCP/DNS
add_firewall_rule(firewall, filter, INPUT,
QStringList() << in_interface << bridge_name << protocol << udp << dport << port_67 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, filter, INPUT,
QStringList() << in_interface << bridge_name << protocol << udp << dport << port_53 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, filter, INPUT,
QStringList() << in_interface << bridge_name << protocol << tcp << dport << port_53 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, filter, OUTPUT,
QStringList() << out_interface << bridge_name << protocol << udp << sport << port_67 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, filter, OUTPUT,
QStringList() << out_interface << bridge_name << protocol << udp << sport << port_53 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, filter, OUTPUT,
QStringList() << out_interface << bridge_name << protocol << tcp << sport << port_53 << jump
<< ACCEPT << comment_option);
add_firewall_rule(firewall, mangle, POSTROUTING,
QStringList() << out_interface << bridge_name << protocol << udp << dport << port_68 << jump
<< QStringLiteral("CHECKSUM") << QStringLiteral("--checksum-fill")
<< comment_option);
// Do not masquerade to these reserved address blocks.
add_firewall_rule(firewall, nat, POSTROUTING,
QStringList() << source << cidr << destination << QStringLiteral("224.0.0.0/24") << jump << RETURN
<< comment_option);
add_firewall_rule(firewall, nat, POSTROUTING,
QStringList() << source << cidr << destination << QStringLiteral("255.255.255.255/32") << jump
<< RETURN << comment_option);
// Masquerade all packets going from VMs to the LAN/Internet
add_firewall_rule(firewall, nat, POSTROUTING,
QStringList() << source << cidr << negate << destination << cidr << protocol << tcp << jump
<< MASQUERADE << to_ports << port_range << comment_option);
add_firewall_rule(firewall, nat, POSTROUTING,
QStringList() << source << cidr << negate << destination << cidr << protocol << udp << jump
<< MASQUERADE << to_ports << port_range << comment_option);
add_firewall_rule(firewall, nat, POSTROUTING,
QStringList() << source << cidr << negate << destination << cidr << jump << MASQUERADE
<< comment_option);
// Allow established traffic to the private subnet
add_firewall_rule(firewall, filter, FORWARD,
QStringList() << destination << cidr << out_interface << bridge_name << match
<< QStringLiteral("conntrack") << QStringLiteral("--ctstate")
<< QStringLiteral("RELATED,ESTABLISHED") << jump << ACCEPT << comment_option);
// Allow outbound traffic from the private subnet
add_firewall_rule(firewall, filter, FORWARD,
QStringList() << source << cidr << in_interface << bridge_name << jump << ACCEPT
<< comment_option);
// Allow traffic between virtual machines
add_firewall_rule(firewall, filter, FORWARD,
QStringList() << in_interface << bridge_name << out_interface << bridge_name << jump << ACCEPT
<< comment_option);
// Reject everything else
add_firewall_rule(firewall, filter, FORWARD,
QStringList() << in_interface << bridge_name << jump << REJECT << reject_with
<< icmp_port_unreachable << comment_option,
/*append=*/true);
add_firewall_rule(firewall, filter, FORWARD,
QStringList() << out_interface << bridge_name << jump << REJECT << reject_with
<< icmp_port_unreachable << comment_option,
/*append=*/true);
}
void clear_firewall_rules_for(const QString& firewall, const QString& table, const QString& bridge_name,
const QString& cidr, const QString& comment)
{
auto rules = QString::fromUtf8(get_firewall_rules(firewall, table));
for (auto& rule : rules.split('\n'))
{
if (rule.contains(comment) || rule.contains(bridge_name) || rule.contains(cidr))
{
// Remove the policy type since delete doesn't use that
rule.remove(0, 3);
try
{
// Pass the chain and rule wholesale since we capture the whole line
delete_firewall_rule(firewall, table, QStringList() << rule);
}
catch (const FirewallException& e)
{
mpl::log(mpl::Level::error, category,
fmt::format("Error deleting firewall rule '{}': {}", rule, e.what()));
}
}
}
}
bool is_firewall_in_use(const QString& firewall)
{
return std::any_of(firewall_tables.cbegin(), firewall_tables.cend(), [&firewall](const QString& table) {
QRegularExpression re{"^-[ARIN]"};
auto rule_lines = get_firewall_rules(firewall, table).split('\n');
return std::any_of(rule_lines.cbegin(), rule_lines.cend(),
[&re](const QString& line) { return re.match(line).hasMatch(); });
});
}
// We require a >= 5.2 kernel to avoid weird conflicts with xtables and support for inet table NAT rules.
// Taken from LXD :)
bool kernel_supports_nftables()
{
const auto kernel_version{MP_UTILS.get_kernel_version()};
try
{
auto kernel_supported{version::Semver200_version(kernel_version) >= version::Semver200_version("5.2.0")};
if (!kernel_supported)
{
mpl::log(mpl::Level::warning, category, "Kernel version does not meet minimum requirement of 5.2");
}
return kernel_supported;
}
catch (version::Parse_error&)
{
mpl::log(mpl::Level::warning, category, fmt::format("Cannot parse kernel version \'{}\'", kernel_version));
return false;
}
}
QString detect_firewall()
{
QString firewall_exec;
try
{
firewall_exec = kernel_supports_nftables() && (is_firewall_in_use(nftables) || !is_firewall_in_use(iptables))
? nftables
: iptables;
}
catch (const FirewallException& e)
{
firewall_exec = iptables;
mpl::log(mpl::Level::warning, category, e.what());
}
mpl::log(mpl::Level::info, category, fmt::format("Using {} for firewall rules.", firewall_exec));
return firewall_exec;
}
} // namespace
mp::FirewallConfig::FirewallConfig(const QString& bridge_name, const std::string& subnet)
: firewall{detect_firewall()},
bridge_name{bridge_name},
cidr{QString("%1.0/24").arg(QString::fromStdString(subnet))},
comment{multipass_firewall_comment(bridge_name)}
{
try
{
clear_all_firewall_rules();
set_firewall_rules(firewall, bridge_name, cidr, comment);
}
catch (const FirewallException& e)
{
mpl::log(mpl::Level::warning, category, e.what());
firewall_error = true;
error_string = e.what();
}
}
mp::FirewallConfig::~FirewallConfig()
{
if (!firewall.isEmpty())
{
mp::top_catch_all(category, [this] { clear_all_firewall_rules(); });
}
}
void mp::FirewallConfig::verify_firewall_rules()
{
if (firewall_error)
{
throw std::runtime_error(error_string);
}
}
void mp::FirewallConfig::clear_all_firewall_rules()
{
for (const auto& table : firewall_tables)
{
clear_firewall_rules_for(firewall, table, bridge_name, cidr, comment);
}
}
mp::FirewallConfig::UPtr mp::FirewallConfigFactory::make_firewall_config(const QString& bridge_name,
const std::string& subnet) const
{
return std::make_unique<mp::FirewallConfig>(bridge_name, subnet);
}
| 14,643
|
C++
|
.cpp
| 301
| 40.136213
| 120
| 0.634333
|
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,741
|
dnsmasq_process_spec.cpp
|
canonical_multipass/src/platform/backends/qemu/linux/dnsmasq_process_spec.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 "dnsmasq_process_spec.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/format.h>
#include <multipass/snap_utils.h>
namespace mp = multipass;
namespace mpu = multipass::utils;
mp::DNSMasqProcessSpec::DNSMasqProcessSpec(const mp::Path& data_dir, const QString& bridge_name,
const std::string& subnet, const QString& conf_file_path)
: data_dir(data_dir), bridge_name(bridge_name), subnet{subnet}, conf_file_path{conf_file_path}
{
}
QString mp::DNSMasqProcessSpec::program() const
{
return "dnsmasq"; // depend on desired binary being in $PATH
}
QStringList mp::DNSMasqProcessSpec::arguments() const
{
const auto bridge_addr = mp::IPAddress{fmt::format("{}.1", subnet)};
const auto start_ip = mp::IPAddress{fmt::format("{}.2", subnet)};
const auto end_ip = mp::IPAddress{fmt::format("{}.254", subnet)};
return QStringList() << "--keep-in-foreground"
<< "--strict-order"
<< "--bind-interfaces" << QString("--pid-file") << "--domain=multipass"
<< "--local=/multipass/"
<< "--except-interface=lo" << QString("--interface=%1").arg(bridge_name)
<< QString("--listen-address=%1").arg(QString::fromStdString(bridge_addr.as_string()))
<< "--dhcp-no-override"
<< "--dhcp-ignore-clid"
<< "--dhcp-authoritative" << QString("--dhcp-leasefile=%1/dnsmasq.leases").arg(data_dir)
<< QString("--dhcp-hostsfile=%1/dnsmasq.hosts").arg(data_dir) << "--dhcp-range"
<< QString("%1,%2,infinite")
.arg(QString::fromStdString(start_ip.as_string()))
.arg(QString::fromStdString(end_ip.as_string()))
// This is to prevent it trying to read /etc/dnsmasq.conf
<< QString("--conf-file=%1").arg(conf_file_path);
}
mp::logging::Level mp::DNSMasqProcessSpec::error_log_level() const
{
// dnsmasq only complains if something really wrong
return mp::logging::Level::error;
}
QString mp::DNSMasqProcessSpec::apparmor_profile() const
{
// Profile based on https://github.com/Rafiot/apparmor-profiles/blob/master/profiles/usr.sbin.dnsmasq
QString profile_template(R"END(
#include <tunables/global>
profile %1 flags=(attach_disconnected) {
#include <abstractions/base>
#include <abstractions/nameservice>
capability chown,
capability net_bind_service,
capability setgid,
capability setuid,
capability dac_override,
capability dac_read_search,
capability net_admin, # for DHCP server
capability net_raw, # for DHCP server ping checks
network inet raw,
network inet6 raw,
# Allow multipassd send dnsmasq signals
signal (receive) peer=%2,
# access to iface mtu needed for Router Advertisement messages in IPv6
# Neighbor Discovery protocol (RFC 2461)
@{PROC}/sys/net/ipv6/conf/*/mtu r,
# binary and its libs
%3/usr/sbin/%4 ixr,
%3/{usr/,}lib/@{multiarch}/{,**/}*.so* rm,
# CLASSIC ONLY: need to specify required libs from core snap
/{,var/lib/snapd/}snap/core18/*/{,usr/}lib/@{multiarch}/{,**/}*.so* rm,
%5/dnsmasq.leases rw, # Leases file
%5/dnsmasq.hosts r, # Hosts file
%6 r, # conf file
}
)END");
/* Customisations depending on if running inside snap or not */
QString root_dir; // root directory: either "" or $SNAP
QString signal_peer; // who can send kill signal to dnsmasq
try
{
// if snap confined, specify only multipassd can kill dnsmasq
root_dir = mpu::snap_dir();
signal_peer = "snap.multipass.multipassd";
}
catch (const mp::SnapEnvironmentException&)
{
signal_peer = "unconfined";
}
return profile_template.arg(apparmor_profile_name(), signal_peer, root_dir, program(), data_dir, conf_file_path);
}
| 4,679
|
C++
|
.cpp
| 105
| 37.780952
| 117
| 0.644127
|
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,742
|
qemu_platform_detail_linux.cpp
|
canonical_multipass/src/platform/backends/qemu/linux/qemu_platform_detail_linux.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 "qemu_platform_detail.h"
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/utils.h>
#include <shared/linux/backend_utils.h>
#include <QCoreApplication>
#include <QFile>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "qemu platform";
const QString multipass_bridge_name{"mpqemubr0"};
// An interface name can only be 15 characters, so this generates a hash of the
// VM instance name with a "tap-" prefix and then truncates it.
auto generate_tap_device_name(const std::string& vm_name)
{
const auto name_hash = std::hash<std::string>{}(vm_name);
auto tap_name = fmt::format("tap-{:x}", name_hash);
tap_name.resize(15);
return QString::fromStdString(tap_name);
}
void create_tap_device(const QString& tap_name, const QString& bridge_name)
{
if (!MP_UTILS.run_cmd_for_status("ip", {"addr", "show", tap_name}))
{
MP_UTILS.run_cmd_for_status("ip", {"tuntap", "add", tap_name, "mode", "tap"});
MP_UTILS.run_cmd_for_status("ip", {"link", "set", tap_name, "master", bridge_name});
MP_UTILS.run_cmd_for_status("ip", {"link", "set", tap_name, "up"});
}
}
void remove_tap_device(const QString& tap_device_name)
{
if (MP_UTILS.run_cmd_for_status("ip", {"addr", "show", tap_device_name}))
{
MP_UTILS.run_cmd_for_status("ip", {"link", "delete", tap_device_name});
}
}
void create_virtual_switch(const std::string& subnet, const QString& bridge_name)
{
if (!MP_UTILS.run_cmd_for_status("ip", {"addr", "show", bridge_name}))
{
const auto mac_address = mp::utils::generate_mac_address();
const auto cidr = fmt::format("{}.1/24", subnet);
const auto broadcast = fmt::format("{}.255", subnet);
MP_UTILS.run_cmd_for_status("ip",
{"link", "add", bridge_name, "address", mac_address.c_str(), "type", "bridge"});
MP_UTILS.run_cmd_for_status(
"ip", {"address", "add", cidr.c_str(), "dev", bridge_name, "broadcast", broadcast.c_str()});
MP_UTILS.run_cmd_for_status("ip", {"link", "set", bridge_name, "up"});
}
}
void set_ip_forward()
{
// Command line equivalent: "sysctl -w net.ipv4.ip_forward=1"
QFile ip_forward("/proc/sys/net/ipv4/ip_forward");
if (!MP_FILEOPS.open(ip_forward, QFile::ReadWrite))
{
mpl::log(mpl::Level::warning, category,
fmt::format("Unable to open {}", qUtf8Printable(ip_forward.fileName())));
return;
}
if (MP_FILEOPS.write(ip_forward, "1") < 0)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Failed to write to {}", qUtf8Printable(ip_forward.fileName())));
}
}
mp::DNSMasqServer::UPtr init_nat_network(const mp::Path& network_dir, const QString& bridge_name,
const std::string& subnet)
{
create_virtual_switch(subnet, bridge_name);
set_ip_forward();
return MP_DNSMASQ_SERVER_FACTORY.make_dnsmasq_server(network_dir, bridge_name, subnet);
}
void delete_virtual_switch(const QString& bridge_name)
{
if (MP_UTILS.run_cmd_for_status("ip", {"addr", "show", bridge_name}))
{
MP_UTILS.run_cmd_for_status("ip", {"link", "delete", bridge_name});
}
}
} // namespace
mp::QemuPlatformDetail::QemuPlatformDetail(const mp::Path& data_dir)
: bridge_name{multipass_bridge_name},
network_dir{MP_UTILS.make_dir(QDir(data_dir), "network")},
subnet{MP_BACKEND.get_subnet(network_dir, bridge_name)},
dnsmasq_server{init_nat_network(network_dir, bridge_name, subnet)},
firewall_config{MP_FIREWALL_CONFIG_FACTORY.make_firewall_config(bridge_name, subnet)}
{
}
mp::QemuPlatformDetail::~QemuPlatformDetail()
{
for (const auto& it : name_to_net_device_map)
{
const auto& [tap_device_name, hw_addr] = it.second;
remove_tap_device(tap_device_name);
}
delete_virtual_switch(bridge_name);
}
std::optional<mp::IPAddress> mp::QemuPlatformDetail::get_ip_for(const std::string& hw_addr)
{
return dnsmasq_server->get_ip_for(hw_addr);
}
void mp::QemuPlatformDetail::remove_resources_for(const std::string& name)
{
auto it = name_to_net_device_map.find(name);
if (it != name_to_net_device_map.end())
{
const auto& [tap_device_name, hw_addr] = it->second;
dnsmasq_server->release_mac(hw_addr);
remove_tap_device(tap_device_name);
name_to_net_device_map.erase(name);
}
}
void mp::QemuPlatformDetail::platform_health_check()
{
MP_BACKEND.check_for_kvm_support();
MP_BACKEND.check_if_kvm_is_in_use();
dnsmasq_server->check_dnsmasq_running();
firewall_config->verify_firewall_rules();
}
QStringList mp::QemuPlatformDetail::vm_platform_args(const VirtualMachineDescription& vm_desc)
{
// Configure and generate the args for the default network interface
auto tap_device_name = generate_tap_device_name(vm_desc.vm_name);
create_tap_device(tap_device_name, bridge_name);
name_to_net_device_map.emplace(vm_desc.vm_name, std::make_pair(tap_device_name, vm_desc.default_mac_address));
QStringList opts;
// Work around for Xenial where UEFI images are not one and the same
if (!(vm_desc.image.original_release == "16.04 LTS" && vm_desc.image.image_path.contains("disk1.img")))
{
#if defined Q_PROCESSOR_X86
opts << "-bios"
<< "OVMF.fd";
#elif defined Q_PROCESSOR_ARM
opts << "-bios"
<< "QEMU_EFI.fd";
#endif
}
opts << "--enable-kvm"
// Pass host CPU flags to VM
<< "-cpu"
<< "host"
// Set up the network related args
<< "-nic"
<< QString::fromStdString(fmt::format("tap,ifname={},script=no,downscript=no,model=virtio-net-pci,mac={}",
tap_device_name, vm_desc.default_mac_address));
const auto bridge_helper_exec_path =
QDir(QCoreApplication::applicationDirPath()).filePath(BRIDGE_HELPER_EXEC_NAME_CPP);
for (const auto& extra_interface : vm_desc.extra_interfaces)
{
opts << "-nic"
<< QString::fromStdString(fmt::format("bridge,br={},model=virtio-net-pci,mac={},helper={}",
extra_interface.id,
extra_interface.mac_address,
bridge_helper_exec_path));
}
return opts;
}
mp::QemuPlatform::UPtr mp::QemuPlatformFactory::make_qemu_platform(const Path& data_dir) const
{
return std::make_unique<mp::QemuPlatformDetail>(data_dir);
}
bool mp::QemuPlatformDetail::is_network_supported(const std::string& network_type) const
{
return network_type == "bridge" || network_type == "ethernet";
}
bool mp::QemuPlatformDetail::needs_network_prep() const
{
return true;
}
void mp::QemuPlatformDetail::set_authorization(std::vector<NetworkInterfaceInfo>& networks)
{
const auto& br_nomenclature = MP_PLATFORM.bridge_nomenclature();
for (auto& net : networks)
if (net.type == "ethernet" && !mpu::find_bridge_with(networks, net.id, br_nomenclature))
net.needs_authorization = true;
}
std::string mp::QemuPlatformDetail::create_bridge_with(const NetworkInterfaceInfo& interface) const
{
assert(interface.type == "ethernet");
return MP_BACKEND.create_bridge_with(interface.id);
}
| 8,180
|
C++
|
.cpp
| 203
| 34.581281
| 116
| 0.65701
|
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,743
|
lxd_virtual_machine_factory.cpp
|
canonical_multipass/src/platform/backends/lxd/lxd_virtual_machine_factory.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 "lxd_virtual_machine_factory.h"
#include "lxd_virtual_machine.h"
#include "lxd_vm_image_vault.h"
#include <shared/linux/backend_utils.h>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/network_interface.h>
#include <multipass/network_interface_info.h>
#include <multipass/platform.h>
#include <multipass/snap_utils.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine_description.h>
#include <QJsonDocument>
#include <QJsonObject>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
constexpr auto category = "lxd factory";
const QString multipass_bridge_name = "mpbr0";
mp::NetworkInterfaceInfo munch_network(std::map<std::string, mp::NetworkInterfaceInfo>& platform_networks,
const QJsonObject& network)
{
using namespace std::string_literals;
static const std::array supported_types{"bridge"s, "ethernet"s};
mp::NetworkInterfaceInfo ret;
if (auto qid = network["name"].toString(); !qid.isEmpty())
{
auto id = qid.toStdString();
if (auto platform_it = platform_networks.find(id); platform_it != platform_networks.cend())
{
if (auto& type = platform_it->second.type;
std::find(supported_types.cbegin(), supported_types.cend(), type) != supported_types.cend())
{
auto lxd_description = network["description"].toString();
auto description = lxd_description.isEmpty() ? std::move(platform_it->second.description)
: lxd_description.toStdString();
auto require_authorization = type != "bridge";
ret = {std::move(id), std::move(type), std::move(description), std::move(platform_it->second.links),
require_authorization};
platform_networks.erase(platform_it); // prevent matching with this network again
}
}
}
return ret;
}
} // namespace
mp::LXDVirtualMachineFactory::LXDVirtualMachineFactory(NetworkAccessManager::UPtr manager,
const mp::Path& data_dir,
const QUrl& base_url)
: BaseVirtualMachineFactory(
MP_UTILS.derive_instances_dir(data_dir, get_backend_directory_name(), instances_subdir)),
manager{std::move(manager)},
base_url{base_url}
{
}
mp::LXDVirtualMachineFactory::LXDVirtualMachineFactory(const mp::Path& data_dir, const QUrl& base_url)
: LXDVirtualMachineFactory(std::make_unique<NetworkAccessManager>(), data_dir, base_url)
{
}
mp::VirtualMachine::UPtr mp::LXDVirtualMachineFactory::create_virtual_machine(const VirtualMachineDescription& desc,
const SSHKeyProvider& key_provider,
VMStatusMonitor& monitor)
{
return std::make_unique<mp::LXDVirtualMachine>(desc,
monitor,
manager.get(),
base_url,
multipass_bridge_name,
storage_pool,
key_provider,
MP_UTILS.make_dir(get_instance_directory(desc.vm_name)));
}
void mp::LXDVirtualMachineFactory::remove_resources_for_impl(const std::string& name)
{
mpl::log(mpl::Level::trace, category, fmt::format("No further resources to remove for \"{}\"", name));
}
auto mp::LXDVirtualMachineFactory::prepare_source_image(const VMImage& source_image) -> VMImage
{
mpl::log(mpl::Level::trace, category, "No driver preparation required for source image");
return source_image;
}
void mp::LXDVirtualMachineFactory::prepare_instance_image(const mp::VMImage& /* instance_image */,
const VirtualMachineDescription& /* desc */)
{
mpl::log(mpl::Level::trace, category, "No driver preparation for instance image");
}
void mp::LXDVirtualMachineFactory::configure(VirtualMachineDescription& /*vm_desc*/)
{
mpl::log(mpl::Level::trace, category, "No preliminary configure step in LXD driver");
}
void mp::LXDVirtualMachineFactory::hypervisor_health_check()
{
QJsonObject reply;
try
{
reply = lxd_request(manager.get(), "GET", base_url);
}
catch (const LocalSocketConnectionException& e)
{
std::string snap_msg;
if (mpu::in_multipass_snap())
snap_msg = " Also make sure\n the LXD interface is connected via `snap connect multipass:lxd lxd`.";
throw std::runtime_error(
fmt::format("{}\n\nPlease ensure the LXD snap is installed and enabled.{}", e.what(), snap_msg));
}
if (reply["metadata"].toObject()["auth"] != QStringLiteral("trusted"))
{
mpl::log(mpl::Level::debug, category, "Failed to authenticate to LXD:");
mpl::log(mpl::Level::debug, category,
fmt::format("{}: {}", base_url.toString(), QJsonDocument(reply).toJson(QJsonDocument::Compact)));
throw std::runtime_error("Failed to authenticate to LXD.");
}
try
{
lxd_request(manager.get(), "GET",
QUrl(QString("%1/projects/%2").arg(base_url.toString()).arg(lxd_project_name)));
}
catch (const LXDNotFoundException&)
{
QJsonObject project{{"name", lxd_project_name}, {"description", "Project for Multipass instances"}};
lxd_request(manager.get(), "POST", QUrl(QString("%1/projects").arg(base_url.toString())), project);
}
const QStringList pools_to_try{{"multipass", "default"}};
for (const auto& pool : pools_to_try)
{
try
{
lxd_request(manager.get(), "GET", QUrl(QString("%1/storage-pools/%2").arg(base_url.toString()).arg(pool)));
storage_pool = pool;
mpl::log(mpl::Level::debug, category, fmt::format("Using the \'{}\' storage pool.", pool));
break;
}
catch (const LXDNotFoundException&)
{
// Keep going
}
}
// No storage pool to use, so create a multipass dir-based pool
if (storage_pool.isEmpty())
{
storage_pool = "multipass";
mpl::log(mpl::Level::info, category, "No storage pool found for multpass: creating…");
QJsonObject pool_config{
{"description", "Storage pool for Multipass"}, {"name", storage_pool}, {"driver", "dir"}};
lxd_request(manager.get(), "POST", QUrl(QString("%1/storage-pools").arg(base_url.toString())), pool_config);
}
try
{
lxd_request(manager.get(), "GET",
QUrl(QString("%1/networks/%2").arg(base_url.toString()).arg(multipass_bridge_name)));
}
catch (const LXDNotFoundException&)
{
QJsonObject network{{"name", multipass_bridge_name}, {"description", "Network bridge for Multipass"}};
lxd_request(manager.get(), "POST", QUrl(QString("%1/networks").arg(base_url.toString())), network);
}
}
QString mp::LXDVirtualMachineFactory::get_backend_version_string() const
{
auto reply = lxd_request(manager.get(), "GET", base_url);
return QString("lxd-%1").arg(reply["metadata"].toObject()["environment"].toObject()["server_version"].toString());
}
mp::VMImageVault::UPtr mp::LXDVirtualMachineFactory::create_image_vault(std::vector<mp::VMImageHost*> image_hosts,
mp::URLDownloader* downloader,
const mp::Path& cache_dir_path,
const mp::Path& data_dir_path,
const mp::days& days_to_expire)
{
return std::make_unique<mp::LXDVMImageVault>(image_hosts, downloader, manager.get(), base_url, cache_dir_path,
days_to_expire);
}
auto mp::LXDVirtualMachineFactory::networks() const -> std::vector<NetworkInterfaceInfo>
{
auto url = QUrl{QString{"%1/networks?recursion=1"}.arg(base_url.toString())}; // no network filter ATTOW
auto reply = lxd_request(manager.get(), "GET", url);
auto ret = std::vector<NetworkInterfaceInfo>{};
auto networks = reply["metadata"].toArray();
if (!networks.isEmpty())
{
const auto& br_nomenclature = MP_PLATFORM.bridge_nomenclature();
auto platform_networks = MP_PLATFORM.get_network_interfaces_info();
for (const QJsonValueRef net_value : networks)
if (auto network = munch_network(platform_networks, net_value.toObject()); !network.id.empty())
ret.push_back(std::move(network));
for (auto& net : ret)
if (net.needs_authorization && mpu::find_bridge_with(ret, net.id, br_nomenclature))
net.needs_authorization = false;
}
return ret;
}
std::string mp::LXDVirtualMachineFactory::create_bridge_with(const NetworkInterfaceInfo& interface)
{
assert(interface.type == "ethernet");
return MP_BACKEND.create_bridge_with(interface.id);
}
| 10,197
|
C++
|
.cpp
| 214
| 37.126168
| 119
| 0.608508
|
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,744
|
lxd_request.cpp
|
canonical_multipass/src/platform/backends/lxd/lxd_request.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 "lxd_request.h"
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/network_access_manager.h>
#include <multipass/version.h>
#include <QEventLoop>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QTimer>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto request_category = "lxd request";
template <typename Callable>
const QJsonObject lxd_request_common(const std::string& method, QUrl& url, int timeout, Callable&& handle_request)
{
QEventLoop event_loop;
QTimer download_timeout;
download_timeout.setInterval(timeout);
if (url.host().isEmpty())
{
url.setHost(mp::lxd_project_name);
}
const QString project_query_string = QString("project=%1").arg(mp::lxd_project_name);
if (url.hasQuery())
{
url.setQuery(url.query() + "&" + project_query_string);
}
else
{
url.setQuery(project_query_string);
}
mpl::log(mpl::Level::trace, request_category, fmt::format("Requesting LXD: {} {}", method, url.toString()));
QNetworkRequest request{url};
request.setHeader(QNetworkRequest::UserAgentHeader, QString("Multipass/%1").arg(mp::version_string));
auto verb = QByteArray::fromStdString(method);
auto reply = handle_request(request, verb);
QObject::connect(reply, &QNetworkReply::finished, &event_loop, &QEventLoop::quit);
QObject::connect(&download_timeout, &QTimer::timeout, [&]() {
download_timeout.stop();
reply->abort();
});
if (!reply->isFinished())
{
download_timeout.start();
event_loop.exec();
}
if (reply->error() == QNetworkReply::ContentNotFoundError)
throw mp::LXDNotFoundException();
if (reply->error() == QNetworkReply::OperationCanceledError)
throw mp::LXDRuntimeError(
fmt::format("Timeout getting response for {} operation on {}", method, url.toString()));
auto bytearray_reply = reply->readAll();
reply->deleteLater();
if (bytearray_reply.isEmpty())
throw mp::LXDRuntimeError(fmt::format("Empty reply received for {} operation on {}", method, url.toString()));
QJsonParseError json_error;
auto json_reply = QJsonDocument::fromJson(bytearray_reply, &json_error);
if (json_error.error != QJsonParseError::NoError)
{
std::string error_string{
fmt::format("Error parsing JSON response for {}: {}", url.toString(), json_error.errorString())};
mpl::log(mpl::Level::debug, request_category, fmt::format("{}\n{}", error_string, bytearray_reply));
throw mp::LXDJsonParseError(error_string);
}
if (json_reply.isNull() || !json_reply.isObject())
{
std::string error_string{fmt::format("Invalid LXD response for {}", url.toString())};
mpl::log(mpl::Level::debug, request_category, fmt::format("{}\n{}", error_string, bytearray_reply));
throw mp::LXDJsonParseError(error_string);
}
mpl::log(mpl::Level::trace, request_category, fmt::format("Got reply: {}", QJsonDocument(json_reply).toJson()));
if (reply->error() != QNetworkReply::NoError)
throw mp::LXDNetworkError(fmt::format("Network error for {}: {} - {}",
url.toString(),
reply->errorString(),
json_reply.object()["error"].toString()));
return json_reply.object();
}
} // namespace
const QJsonObject mp::lxd_request(mp::NetworkAccessManager* manager, const std::string& method, QUrl url,
const std::optional<QJsonObject>& json_data, int timeout)
try
{
auto handle_request = [manager, &json_data](QNetworkRequest& request, const QByteArray& verb) {
QByteArray data;
if (json_data)
{
data = QJsonDocument(*json_data).toJson(QJsonDocument::Compact);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.size()));
mpl::log(mpl::Level::trace, request_category, fmt::format("Sending data: {}", data));
}
return manager->sendCustomRequest(request, verb, data);
};
return lxd_request_common(method, url, timeout, handle_request);
}
catch (const LXDNetworkError& e)
{
mpl::log(mpl::Level::warning, request_category, e.what());
throw;
}
catch (const LXDRuntimeError& e)
{
mpl::log(mpl::Level::error, request_category, e.what());
throw;
}
const QJsonObject mp::lxd_request(mp::NetworkAccessManager* manager, const std::string& method, QUrl url,
QHttpMultiPart& multi_part, int timeout)
try
{
auto handle_request = [manager, &multi_part](QNetworkRequest& request, const QByteArray& verb) {
request.setRawHeader("Transfer-Encoding", "chunked");
return manager->sendCustomRequest(request, verb, &multi_part);
};
return lxd_request_common(method, url, timeout, handle_request);
}
catch (const LXDRuntimeError& e)
{
mpl::log(mpl::Level::error, request_category, e.what());
throw;
}
const QJsonObject mp::lxd_wait(mp::NetworkAccessManager* manager, const QUrl& base_url, const QJsonObject& task_data,
int timeout)
try
{
QJsonObject task_reply;
if (task_data["metadata"].toObject()["class"] == QStringLiteral("task") &&
task_data["status_code"].toInt(-1) == 100)
{
QUrl task_url(QString("%1/operations/%2/wait")
.arg(base_url.toString())
.arg(task_data["metadata"].toObject()["id"].toString()));
task_reply = lxd_request(manager, "GET", task_url, std::nullopt, timeout);
if (task_reply["error_code"].toInt() >= 400)
{
throw mp::LXDRuntimeError(fmt::format("Error waiting on operation: ({}) {}",
task_reply["error_code"].toInt(), task_reply["error"].toString()));
}
else if (task_reply["status_code"].toInt() >= 400)
{
throw mp::LXDRuntimeError(fmt::format("Failure waiting on operation: ({}) {}",
task_reply["status_code"].toInt(), task_reply["status"].toString()));
}
else if (task_reply["metadata"].toObject()["status_code"].toInt() >= 400)
{
throw mp::LXDRuntimeError(fmt::format("Operation completed with error: ({}) {}",
task_reply["metadata"].toObject()["status_code"].toInt(),
task_reply["metadata"].toObject()["err"].toString()));
}
}
return task_reply;
}
catch (const LXDRuntimeError& e)
{
mpl::log(mpl::Level::error, request_category, e.what());
throw;
}
| 7,584
|
C++
|
.cpp
| 175
| 35.6
| 119
| 0.633044
|
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,745
|
lxd_vm_image_vault.cpp
|
canonical_multipass/src/platform/backends/lxd/lxd_vm_image_vault.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 "lxd_vm_image_vault.h"
#include "lxd_request.h"
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/image_vault_exceptions.h>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/network_access_manager.h>
#include <multipass/platform.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <multipass/vm_image.h>
#include <multipass/vm_image_host.h>
#include <shared/linux/process_factory.h>
#include <shared/qemu_img_utils/qemu_img_utils.h>
#include <yaml-cpp/yaml.h>
#include <QCoreApplication>
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QHttpMultiPart>
#include <QJsonArray>
#include <QRegularExpression>
#include <QSysInfo>
#include <QTemporaryDir>
#include <chrono>
#include <thread>
namespace mp = multipass;
namespace mpl = multipass::logging;
using namespace std::literals::chrono_literals;
namespace
{
constexpr auto category = "lxd image vault";
const QHash<QString, QString> host_to_lxd_arch{{"x86_64", "x86_64"}, {"arm", "armv7l"}, {"arm64", "aarch64"},
{"i386", "i686"}, {"power", "ppc"}, {"power64", "ppc64"},
{"s390x", "s390x"}};
auto parse_percent_as_int(const QString& progress_string)
{
QRegularExpression re{"rootfs:\\s(\\d{1,3})%"};
QRegularExpressionMatch match = re.match(progress_string);
if (match.hasMatch())
{
return match.captured(1).toInt();
}
return -1;
}
QString post_process_downloaded_image(const QString& image_path, const mp::ProgressMonitor& monitor)
{
QString new_image_path{image_path};
if (image_path.endsWith(".xz"))
{
new_image_path = mp::vault::extract_image(image_path, monitor, true);
}
QString original_image_path{new_image_path};
new_image_path = mp::backend::convert_to_qcow_if_necessary(new_image_path);
if (original_image_path != new_image_path)
{
mp::vault::delete_file(original_image_path);
}
return new_image_path;
}
QString create_metadata_tarball(const mp::VMImageInfo& info, const QTemporaryDir& lxd_import_dir)
{
QFile metadata_yaml_file{lxd_import_dir.filePath("metadata.yaml")};
YAML::Node metadata_node;
metadata_node["architecture"] = host_to_lxd_arch.value(QSysInfo::currentCpuArchitecture()).toStdString();
metadata_node["creation_date"] = QDateTime::currentSecsSinceEpoch();
metadata_node["properties"]["description"] = info.release_title.toStdString();
metadata_node["properties"]["os"] = info.os.toStdString();
metadata_node["properties"]["release"] = info.release.toStdString();
metadata_node["properties"]["version"] = info.version.toStdString();
metadata_node["properties"]["original_hash"] = info.id.toStdString();
YAML::Emitter emitter;
emitter << metadata_node << YAML::Newline;
metadata_yaml_file.open(QIODevice::WriteOnly);
metadata_yaml_file.write(emitter.c_str());
metadata_yaml_file.close();
const auto metadata_tarball_path = lxd_import_dir.filePath("metadata.tar");
auto process = MP_PROCFACTORY.create_process(
"tar", QStringList() << "-cf" << metadata_tarball_path << "-C" << lxd_import_dir.path()
<< QFileInfo(metadata_yaml_file.fileName()).fileName());
auto exit_state = process->execute();
if (!exit_state.completed_successfully())
{
throw std::runtime_error(
fmt::format("Failed to create LXD image import metadata tarball: {}", process->read_all_standard_error()));
}
return metadata_tarball_path;
}
std::vector<std::string> copy_aliases(const QStringList& aliases)
{
std::vector<std::string> copied_aliases;
for (const auto& alias : aliases)
{
copied_aliases.push_back(alias.toStdString());
}
return copied_aliases;
}
} // namespace
mp::LXDVMImageVault::LXDVMImageVault(std::vector<VMImageHost*> image_hosts, URLDownloader* downloader,
NetworkAccessManager* manager, const QUrl& base_url, const QString& cache_dir_path,
const days& days_to_expire)
: BaseVMImageVault{image_hosts},
url_downloader{downloader},
manager{manager},
base_url{base_url},
template_path{QString("%1/%2-").arg(cache_dir_path).arg(QCoreApplication::applicationName())},
days_to_expire{days_to_expire}
{
}
mp::VMImage mp::LXDVMImageVault::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 mp::Path& /* save_dir */)
{
// Look for an already existing instance and get its image info
try
{
VMImage source_image;
auto instance_info = lxd_request(
manager, "GET",
QUrl(QString("%1/virtual-machines/%2").arg(base_url.toString()).arg(QString::fromStdString(query.name))));
auto config = instance_info["metadata"].toObject()["config"].toObject();
if (config.contains("image.original_hash"))
{
source_image.id = config["image.original_hash"].toString().toStdString();
source_image.original_release = config["image.description"].toString().toStdString();
source_image.release_date = config["image.version"].toString().toStdString();
return source_image;
}
source_image.id = config["volatile.base_image"].toString().toStdString();
if (config.contains("image.release_title"))
{
source_image.original_release = config["image.release_title"].toString().toStdString();
}
else
{
Query image_query;
image_query.release = config["image.release"].toString().toStdString();
try
{
const auto info = info_for(image_query);
source_image.original_release = info->release_title.toStdString();
}
catch (const std::exception&)
{
// do nothing
}
}
return source_image;
}
catch (const LXDNotFoundException&)
{
// Instance doesn't exist, so move on
}
catch (const LocalSocketConnectionException& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("{} - returning blank image info", e.what()));
return VMImage{};
}
catch (const std::exception&)
{
// Image doesn't exist, so move on
}
VMImage source_image;
VMImageInfo info;
QString id;
if (query.query_type == Query::Type::Alias)
{
if (auto image_info = info_for(query); image_info)
info = *image_info;
else
throw mp::ImageNotFoundException(query.release, query.remote_name);
id = info.id;
source_image.id = id.toStdString();
source_image.original_release = info.release_title.toStdString();
source_image.release_date = info.version.toStdString();
source_image.aliases = copy_aliases(info.aliases);
}
else
{
QUrl image_url(QString::fromStdString(query.release));
QDateTime last_modified;
if (query.query_type == Query::Type::HttpDownload)
{
// If no checksum given, generate a sha256 hash based on the URL and use that for the id
id = checksum
? QString::fromStdString(*checksum)
: QString(QCryptographicHash::hash(query.release.c_str(), QCryptographicHash::Sha256).toHex());
last_modified = url_downloader->last_modified(image_url);
}
else
{
if (!QFile::exists(image_url.path()))
throw std::runtime_error(fmt::format("Custom image `{}` does not exist.", image_url.path()));
source_image.image_path = image_url.path();
id = mp::vault::compute_image_hash(source_image.image_path);
last_modified = QDateTime::currentDateTime();
}
info = VMImageInfo{{},
{},
{},
{},
{},
true,
image_url.url(),
id,
{},
last_modified.toString(),
0,
checksum.has_value()};
source_image.id = id.toStdString();
source_image.release_date = last_modified.toString(Qt::ISODateWithMs).toStdString();
}
try
{
auto json_reply = lxd_request(manager, "GET", QUrl(QString("%1/images/%2").arg(base_url.toString()).arg(id)));
}
catch (const LXDNotFoundException&)
{
auto lxd_image_hash = get_lxd_image_hash_for(id);
if (!lxd_image_hash.empty())
{
source_image.id = lxd_image_hash;
}
else if (!info.stream_location.isEmpty())
{
lxd_download_image(info, query, monitor);
}
else if (!info.image_location.isEmpty())
{
QString image_path;
QTemporaryDir lxd_import_dir{template_path};
if (query.query_type != Query::Type::LocalFile)
{
// TODO: Need to make this async like in DefaultVMImageVault
image_path = lxd_import_dir.filePath(mp::vault::filename_for(info.image_location));
url_download_image(info, image_path, monitor);
}
else
{
image_path = mp::vault::copy(source_image.image_path, lxd_import_dir.path());
}
image_path = post_process_downloaded_image(image_path, monitor);
monitor(LaunchProgress::WAITING, -1);
auto metadata_tarball_path = create_metadata_tarball(info, lxd_import_dir);
source_image.id = lxd_import_metadata_and_image(metadata_tarball_path, image_path);
}
else
{
throw std::runtime_error(fmt::format("Unable to fetch image with hash \'{}\'", id));
}
}
return source_image;
}
void mp::LXDVMImageVault::remove(const std::string& name)
{
try
{
auto task_reply = lxd_request(
manager, "DELETE", QUrl(QString("%1/virtual-machines/%2").arg(base_url.toString()).arg(name.c_str())));
lxd_wait(manager, base_url, task_reply, 120000);
}
catch (const LXDNotFoundException&)
{
mpl::log(mpl::Level::warning, category, fmt::format("Instance \'{}\' does not exist: not removing", name));
}
}
bool mp::LXDVMImageVault::has_record_for(const std::string& name)
{
try
{
lxd_request(manager, "GET", QUrl(QString("%1/virtual-machines/%2").arg(base_url.toString()).arg(name.c_str())));
return true;
}
catch (const LXDNotFoundException&)
{
return false;
}
catch (const LocalSocketConnectionException& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("{} - Unable to determine if \'{}\' exists", e.what(), name));
// Assume instance exists until it knows for sure
return true;
}
}
void mp::LXDVMImageVault::prune_expired_images()
{
auto images = retrieve_image_list();
for (const auto image : images)
{
auto image_info = image.toObject();
auto properties = image_info["properties"].toObject();
auto last_used = std::chrono::system_clock::time_point(std::chrono::milliseconds(
QDateTime::fromString(image_info["last_used_at"].toString(), Qt::ISODateWithMs).toMSecsSinceEpoch()));
// If the image has been downloaded but never used, then check if we added a "last_used_at" property during
// update
if (last_used < std::chrono::system_clock::time_point(0ms) && properties.contains("last_used_at"))
{
last_used = std::chrono::system_clock::time_point(std::chrono::milliseconds(
QDateTime::fromString(properties["last_used_at"].toString(), Qt::ISODateWithMs).toMSecsSinceEpoch()));
}
if (last_used + days_to_expire <= std::chrono::system_clock::now())
{
mpl::log(mpl::Level::info, category,
fmt::format("Source image \'{}\' is expired. Removing it…",
image_info["properties"].toObject()["release"].toString()));
try
{
lxd_request(
manager, "DELETE",
QUrl(QString("%1/images/%2").arg(base_url.toString()).arg(image_info["fingerprint"].toString())));
}
catch (const LXDNotFoundException&)
{
continue;
}
}
}
}
void mp::LXDVMImageVault::update_images(const FetchType& fetch_type, const PrepareAction& prepare,
const ProgressMonitor& monitor)
{
mpl::log(mpl::Level::debug, category, "Checking for images to update…");
auto images = retrieve_image_list();
for (const auto image : images)
{
auto image_info = image.toObject();
auto image_properties = image_info["properties"].toObject();
if (image_properties.contains("query.release"))
{
auto id = image_info["fingerprint"].toString();
Query query;
query.release = image_properties["query.release"].toString().toStdString();
query.remote_name = image_properties["query.remote"].toString().toStdString();
try
{
auto info = info_for(query);
if (!info)
throw mp::ImageNotFoundException(query.release, query.remote_name);
if (info->id != id)
{
mpl::log(mpl::Level::info, category,
fmt::format("Updating {} source image to latest", query.release));
lxd_download_image(*info, query, monitor, image_info["last_used_at"].toString());
lxd_request(manager, "DELETE", QUrl(QString("%1/images/%2").arg(base_url.toString()).arg(id)));
}
}
catch (const LXDNotFoundException&)
{
continue;
}
}
}
}
mp::MemorySize mp::LXDVMImageVault::minimum_image_size_for(const std::string& id)
{
MemorySize lxd_image_size{"10G"};
try
{
auto json_reply = lxd_request(
manager, "GET", QUrl(QString("%1/images/%2").arg(base_url.toString()).arg(QString::fromStdString(id))));
const long image_size_bytes = json_reply["metadata"].toObject()["size"].toDouble();
const MemorySize image_size{std::to_string(image_size_bytes)};
if (image_size > lxd_image_size)
{
lxd_image_size = image_size;
}
}
catch (const std::exception& e)
{
throw std::runtime_error(fmt::format("Cannot retrieve info for image with id \'{}\': {}", id, e.what()));
}
return lxd_image_size;
}
void mp::LXDVMImageVault::lxd_download_image(const VMImageInfo& info, const Query& query,
const ProgressMonitor& monitor, const QString& last_used)
{
const auto id = info.id;
QJsonObject source_object;
source_object.insert("type", "image");
source_object.insert("mode", "pull");
source_object.insert("server", info.stream_location);
source_object.insert("protocol", "simplestreams");
source_object.insert("image_type", "virtual-machine");
source_object.insert("fingerprint", id);
QJsonObject image_object{{"source", source_object}};
auto release = QString::fromStdString(query.release);
if (!id.startsWith(release))
{
QJsonObject properties_object{{"query.release", release},
{"query.remote", QString::fromStdString(query.remote_name)},
{"release_title", info.release_title}};
// Need to save the original image's last_used_at as a property since there is no way to modify the
// new image's last_used_at field.
if (!last_used.isEmpty())
{
properties_object.insert("last_used_at", last_used);
}
image_object.insert("properties", properties_object);
}
auto json_reply = lxd_request(manager, "POST", QUrl(QString("%1/images").arg(base_url.toString())), image_object);
poll_download_operation(json_reply, monitor);
}
void mp::LXDVMImageVault::url_download_image(const VMImageInfo& info, const QString& image_path,
const ProgressMonitor& monitor)
{
mp::vault::DeleteOnException image_file{image_path};
url_downloader->download_to(info.image_location, image_path, info.size, LaunchProgress::IMAGE, monitor);
if (info.verify)
{
monitor(LaunchProgress::VERIFY, -1);
mp::vault::verify_image_download(image_path, info.id);
}
}
void mp::LXDVMImageVault::poll_download_operation(const QJsonObject& json_reply, const ProgressMonitor& monitor)
{
if (json_reply["metadata"].toObject()["class"] == QStringLiteral("task") &&
json_reply["status_code"].toInt(-1) == 100)
{
QUrl task_url(QString("%1/operations/%2")
.arg(base_url.toString())
.arg(json_reply["metadata"].toObject()["id"].toString()));
// Instead of polling, need to use websockets to get events
auto last_download_progress = -2;
while (true)
{
try
{
auto task_reply = mp::lxd_request(manager, "GET", task_url);
if (task_reply["error_code"].toInt(-1) != 0)
{
mpl::log(mpl::Level::error, category, task_reply["error"].toString().toStdString());
break;
}
auto status_code = task_reply["metadata"].toObject()["status_code"].toInt(-1);
if (status_code == 200)
{
break;
}
else
{
auto download_progress = parse_percent_as_int(
task_reply["metadata"].toObject()["metadata"].toObject()["download_progress"].toString());
if (last_download_progress != download_progress &&
!monitor(LaunchProgress::IMAGE, download_progress))
{
mp::lxd_request(manager, "DELETE", task_url);
throw mp::AbortedDownloadException{"Download aborted"};
}
last_download_progress = download_progress;
std::this_thread::sleep_for(1s);
}
}
// Implies the task is finished
catch (const LXDNotFoundException&)
{
break;
}
}
}
}
std::string mp::LXDVMImageVault::lxd_import_metadata_and_image(const QString& metadata_path, const QString& image_path)
{
QHttpMultiPart lxd_multipart{QHttpMultiPart::FormDataType};
QFileInfo metadata_info{metadata_path}, image_info{image_path};
QHttpPart metadata_part;
metadata_part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
metadata_part.setHeader(
QNetworkRequest::ContentDispositionHeader,
QVariant(QString("form-data; name=\"metadata\"; filename=\"%1\"").arg(metadata_info.fileName())));
QFile* metadata_file = new QFile(metadata_path);
metadata_file->open(QIODevice::ReadOnly);
metadata_part.setBodyDevice(metadata_file);
metadata_file->setParent(&lxd_multipart);
QHttpPart image_part;
image_part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
image_part.setHeader(
QNetworkRequest::ContentDispositionHeader,
QVariant(QString("form-data; name=\"rootfs.img\"; filename=\"%1\"").arg(image_info.fileName())));
QFile* image_file = new QFile(image_path);
image_file->open(QIODevice::ReadOnly);
image_part.setBodyDevice(image_file);
image_file->setParent(&lxd_multipart);
lxd_multipart.append(metadata_part);
lxd_multipart.append(image_part);
auto json_reply = lxd_request(manager, "POST", QUrl(QString("%1/images").arg(base_url.toString())), lxd_multipart);
auto task_reply = lxd_wait(manager, base_url, json_reply, 300000);
return task_reply["metadata"].toObject()["metadata"].toObject()["fingerprint"].toString().toStdString();
}
std::string mp::LXDVMImageVault::get_lxd_image_hash_for(const QString& id)
{
auto images = retrieve_image_list();
for (const auto image : images)
{
auto image_info = image.toObject();
auto properties = image_info["properties"].toObject();
if (properties.contains("original_hash"))
{
auto original_hash = properties["original_hash"].toString();
if (original_hash == id)
{
return image_info["fingerprint"].toString().toStdString();
}
}
}
return {};
}
QJsonArray mp::LXDVMImageVault::retrieve_image_list()
{
QJsonArray image_list;
try
{
auto json_reply = lxd_request(manager, "GET", QUrl(QString("%1/images?recursion=1").arg(base_url.toString())));
image_list = json_reply["metadata"].toArray();
}
catch (const LXDNotFoundException&)
{
// ignore exception
}
catch (const LocalSocketConnectionException& e)
{
mpl::log(mpl::Level::warning, category, e.what());
}
return image_list;
}
| 22,923
|
C++
|
.cpp
| 547
| 32.347349
| 120
| 0.602228
|
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,746
|
lxd_virtual_machine.cpp
|
canonical_multipass/src/platform/backends/lxd/lxd_virtual_machine.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 "lxd_virtual_machine.h"
#include "lxd_mount_handler.h"
#include "lxd_request.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/exceptions/start_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/memory_size.h>
#include <multipass/network_access_manager.h>
#include <multipass/snap_utils.h>
#include <multipass/top_catch_all.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_status_monitor.h>
#include <multipass/yaml_node_utils.h>
#include <shared/shared_backend_utils.h>
#include <chrono>
#include <thread>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
using namespace std::literals::chrono_literals;
namespace
{
constexpr int timeout_milliseconds = 30000;
auto instance_state_for(const QString& name, mp::NetworkAccessManager* manager, const QUrl& url)
{
auto json_reply = lxd_request(manager, "GET", url);
auto metadata = json_reply["metadata"].toObject();
mpl::log(mpl::Level::trace, name.toStdString(),
fmt::format("Got LXD container state: {} is {}", name, metadata["status"].toString()));
switch (metadata["status_code"].toInt(-1))
{
case 101: // Started
case 103: // Running
case 107: // Stopping
case 111: // Thawed
return mp::VirtualMachine::State::running;
case 102: // Stopped
return mp::VirtualMachine::State::stopped;
case 106: // Starting
return mp::VirtualMachine::State::starting;
case 109: // Freezing
return mp::VirtualMachine::State::suspending;
case 110: // Frozen
return mp::VirtualMachine::State::suspended;
case 104: // Cancelling
case 108: // Aborting
case 112: // Error
return mp::VirtualMachine::State::unknown;
default:
mpl::log(mpl::Level::error, name.toStdString(),
fmt::format("Got unexpected LXD state: {} ({})", metadata["status"].toString(),
metadata["status_code"].toInt()));
return mp::VirtualMachine::State::unknown;
}
}
std::optional<mp::IPAddress> get_ip_for(const QString& mac_addr, mp::NetworkAccessManager* manager, const QUrl& url)
{
const auto json_leases = lxd_request(manager, "GET", url);
const auto leases = json_leases["metadata"].toArray();
for (const auto lease : leases)
{
if (lease.toObject()["hwaddr"].toString() == mac_addr)
{
try
{
return std::optional<mp::IPAddress>{lease.toObject()["address"].toString().toStdString()};
}
catch (const std::invalid_argument&)
{
continue;
}
}
}
return std::nullopt;
}
QJsonObject generate_base_vm_config(const multipass::VirtualMachineDescription& desc)
{
QJsonObject config{{"limits.cpu", QString::number(desc.num_cores)},
{"limits.memory", QString::number(desc.mem_size.in_bytes())},
{"security.secureboot", "false"}};
if (!desc.meta_data_config.IsNull())
config["user.meta-data"] = QString::fromStdString(mpu::emit_cloud_config(desc.meta_data_config));
if (!desc.vendor_data_config.IsNull())
config["user.vendor-data"] = QString::fromStdString(mpu::emit_cloud_config(desc.vendor_data_config));
if (!desc.user_data_config.IsNull())
config["user.user-data"] = QString::fromStdString(mpu::emit_cloud_config(desc.user_data_config));
if (!desc.network_data_config.IsNull())
config["user.network-config"] = QString::fromStdString(mpu::emit_cloud_config(desc.network_data_config));
return config;
}
QJsonObject create_bridged_interface_json(const QString& name, const QString& parent, const QString& mac)
{
return QJsonObject{{"name", name}, {"nictype", "bridged"}, {"parent", parent}, {"type", "nic"}, {"hwaddr", mac}};
}
QJsonObject generate_devices_config(const multipass::VirtualMachineDescription& desc, const QString& default_mac_addr,
const QString& storage_pool)
{
QJsonObject devices{{"config", QJsonObject{{"source", "cloud-init:config"}, {"type", "disk"}}},
{"root",
QJsonObject{{"path", "/"},
{"pool", storage_pool},
{"size", QString::number(desc.disk_space.in_bytes())},
{"type", "disk"}}},
{"eth0", create_bridged_interface_json("eth0", "mpbr0", default_mac_addr)}};
for (auto i = 0u; i < desc.extra_interfaces.size();)
{
const auto& net = desc.extra_interfaces[i];
auto net_name = QStringLiteral("eth%1").arg(++i);
devices.insert(net_name,
create_bridged_interface_json(net_name,
QString::fromStdString(net.id),
QString::fromStdString(net.mac_address)));
}
return devices;
}
bool uses_default_id_mappings(const multipass::VMMount& mount)
{
const auto& gid_mappings = mount.get_gid_mappings();
const auto& uid_mappings = mount.get_uid_mappings();
// -1 is the default value for gid and uid
return gid_mappings.size() == 1 && gid_mappings.front().second == -1 && uid_mappings.size() == 1 &&
uid_mappings.front().second == -1;
}
} // namespace
mp::LXDVirtualMachine::LXDVirtualMachine(const VirtualMachineDescription& desc,
VMStatusMonitor& monitor,
NetworkAccessManager* manager,
const QUrl& base_url,
const QString& bridge_name,
const QString& storage_pool,
const SSHKeyProvider& key_provider,
const mp::Path& instance_dir)
: BaseVirtualMachine{desc.vm_name, key_provider, instance_dir},
name{QString::fromStdString(desc.vm_name)},
username{desc.ssh_username},
monitor{&monitor},
manager{manager},
base_url{base_url},
bridge_name{bridge_name},
mac_addr{QString::fromStdString(desc.default_mac_address)},
storage_pool{storage_pool}
{
try
{
current_state();
}
catch (const LXDNotFoundException& e)
{
mpl::log(mpl::Level::debug, name.toStdString(),
fmt::format("Creating instance with image id: {}", desc.image.id));
QJsonObject virtual_machine{
{"name", name},
{"config", generate_base_vm_config(desc)},
{"devices", generate_devices_config(desc, mac_addr, storage_pool)},
{"source", QJsonObject{{"type", "image"}, {"fingerprint", QString::fromStdString(desc.image.id)}}}};
auto json_reply = lxd_request(manager, "POST", QUrl(QString("%1/virtual-machines").arg(base_url.toString())),
virtual_machine);
// TODO: Need a way to pass in the daemon timeout and make in general for all back ends
lxd_wait(manager, base_url, json_reply, 600000);
current_state();
}
}
mp::LXDVirtualMachine::~LXDVirtualMachine()
{
update_shutdown_status = false;
mp::top_catch_all(vm_name, [this]() {
try
{
current_state();
if (state == State::running)
{
try
{
if (!QFileInfo::exists(mp::utils::snap_common_dir() + "/snap_refresh"))
shutdown();
}
catch (const mp::SnapEnvironmentException&)
{
shutdown();
}
}
else
{
update_state();
}
}
catch (const LXDNotFoundException& e)
{
mpl::log(mpl::Level::debug, vm_name, fmt::format("LXD object not found"));
}
});
}
void mp::LXDVirtualMachine::start()
{
if (state == State::suspended)
{
mpl::log(mpl::Level::info, vm_name, fmt::format("Resuming from a suspended state"));
request_state("unfreeze");
}
else
{
request_state("start");
}
state = State::starting;
update_state();
}
void mp::LXDVirtualMachine::shutdown(ShutdownPolicy shutdown_policy)
{
std::unique_lock<std::mutex> lock{state_mutex};
const auto present_state = current_state();
try
{
check_state_for_shutdown(shutdown_policy);
}
catch (const VMStateIdempotentException& e)
{
mpl::log(mpl::Level::info, vm_name, e.what());
return;
}
// ShutdownPolicy::Poweroff is force and the other two values are non-force
request_state("stop", {{"force", shutdown_policy == ShutdownPolicy::Poweroff}});
state = State::off;
if (present_state == State::starting)
{
state_wait.wait(lock, [this] { return shutdown_while_starting; });
}
drop_ssh_session();
port = std::nullopt;
if (update_shutdown_status)
update_state();
}
void mp::LXDVirtualMachine::suspend()
{
throw NotImplementedOnThisBackendException{"suspend"};
}
mp::VirtualMachine::State mp::LXDVirtualMachine::current_state()
{
try
{
auto present_state = instance_state_for(name, manager, state_url());
if ((state == State::delayed_shutdown || state == State::starting) && present_state == State::running)
return state;
state = present_state;
if (state == State::suspended || state == State::suspending || state == State::restarting)
drop_ssh_session();
}
catch (const LocalSocketConnectionException& e)
{
mpl::log(mpl::Level::warning, vm_name, e.what());
state = State::unknown;
}
return state;
}
int mp::LXDVirtualMachine::ssh_port()
{
return 22;
}
void mp::LXDVirtualMachine::ensure_vm_is_running()
{
ensure_vm_is_running(20s);
}
void mp::LXDVirtualMachine::ensure_vm_is_running(const std::chrono::milliseconds& timeout)
{
auto is_vm_running = [this, timeout] {
if (current_state() != State::stopped)
{
return true;
}
// Sleep to see if LXD is just rebooting the instance
std::this_thread::sleep_for(timeout);
if (current_state() != State::stopped)
{
state = State::starting;
update_state();
return true;
}
return false;
};
mp::backend::ensure_vm_is_running_for(this, is_vm_running, "Instance shutdown during start");
}
void mp::LXDVirtualMachine::update_state()
{
monitor->persist_state_for(vm_name, state);
}
std::string mp::LXDVirtualMachine::ssh_hostname(std::chrono::milliseconds timeout)
{
auto get_ip = [this]() -> std::optional<IPAddress> { return get_ip_for(mac_addr, manager, network_leases_url()); };
return mp::backend::ip_address_for(this, get_ip, timeout);
}
std::string mp::LXDVirtualMachine::ssh_username()
{
return username;
}
std::string mp::LXDVirtualMachine::management_ipv4()
{
if (!management_ip)
{
management_ip = get_ip_for(mac_addr, manager, network_leases_url());
if (!management_ip)
{
mpl::log(mpl::Level::trace, name.toStdString(), "IP address not found.");
return "UNKNOWN";
}
}
return management_ip.value().as_string();
}
std::string mp::LXDVirtualMachine::ipv6()
{
return {};
}
const QUrl mp::LXDVirtualMachine::url() const
{
return QString("%1/virtual-machines/%2").arg(base_url.toString()).arg(name);
}
const QUrl mp::LXDVirtualMachine::state_url()
{
return url().toString() + "/state";
}
const QUrl mp::LXDVirtualMachine::network_leases_url()
{
return base_url.toString() + "/networks/" + bridge_name + "/leases";
}
void mp::LXDVirtualMachine::request_state(const QString& new_state, const QJsonObject& args)
{
QJsonObject state_json{{"action", new_state}};
for (auto it = args.constBegin(); it != args.constEnd(); it++)
{
state_json.insert(it.key(), it.value());
}
auto state_task = lxd_request(manager, "PUT", state_url(), state_json, 5000);
try
{
lxd_wait(manager, base_url, state_task, 60000);
}
catch (const LXDNotFoundException&)
{
// Implies the task doesn't exist, move on...
}
}
void mp::LXDVirtualMachine::update_cpus(int num_cores)
{
assert(num_cores > 0);
assert(manager);
/*
* similar to:
* $ curl -s -w "%{http_code}" -X PATCH -H "Content-Type: application/json" \
* -d '{"config": {"limits.cpu": "3"}}' \
* --unix-socket /var/snap/lxd/common/lxd/unix.socket \
* lxd/1.0/virtual-machines/asdf?project=multipass
*/
QJsonObject patch_json{{"config", QJsonObject{{"limits.cpu", QString::number(num_cores)}}}};
auto reply = lxd_request(manager, "PATCH", url(), patch_json);
}
void mp::LXDVirtualMachine::resize_memory(const MemorySize& new_size)
{
assert(new_size.in_bytes() > 0);
assert(manager);
/*
* similar to:
* $ curl -s -w "%{http_code}" -X PATCH -H "Content-Type: application/json" \
* -d '{"config": {"limits.memory": "1572864000"}}' \
* --unix-socket /var/snap/lxd/common/lxd/unix.socket \
* lxd/1.0/virtual-machines/asdf?project=multipass
*/
QJsonObject patch_json{{"config", QJsonObject{{"limits.memory", QString::number(new_size.in_bytes())}}}};
auto reply = lxd_request(manager, "PATCH", url(), patch_json);
}
void mp::LXDVirtualMachine::resize_disk(const MemorySize& new_size)
{
assert(new_size.in_bytes() > 0);
assert(manager);
/*
* similar to:
* $ curl -s -w "%{http_code}\n" -X PATCH -H "Content-Type: application/json" \
* -d '{"devices": {"root": {"size": "10737418245B"}}}' \
* --unix-socket /var/snap/lxd/common/lxd/unix.socket \
* lxd/1.0/virtual-machines/asdf?project=multipass
*/
QJsonObject root_json{
{"path", "/"}, {"pool", storage_pool}, {"size", QString::number(new_size.in_bytes())}, {"type", "disk"}};
QJsonObject patch_json{{"devices", QJsonObject{{"root", root_json}}}};
lxd_request(manager, "PATCH", url(), patch_json);
}
void mp::LXDVirtualMachine::add_network_interface(int index,
const std::string& default_mac_addr,
const mp::NetworkInterface& extra_interface)
{
assert(manager);
auto net_name = QStringLiteral("eth%1").arg(index + 1);
auto net_config = create_bridged_interface_json(net_name,
QString::fromStdString(extra_interface.id),
QString::fromStdString(extra_interface.mac_address));
QJsonObject patch_json{{"devices", QJsonObject{{net_name, net_config}}}};
lxd_request(manager, "PATCH", url(), patch_json);
add_extra_interface_to_instance_cloud_init(default_mac_addr, extra_interface);
}
std::unique_ptr<mp::MountHandler> mp::LXDVirtualMachine::make_native_mount_handler(const std::string& target,
const VMMount& mount)
{
if (!uses_default_id_mappings(mount))
{
throw std::runtime_error("LXD native mount does not accept custom ID mappings.");
}
return std::make_unique<LXDMountHandler>(manager, this, &key_provider, target, mount);
}
void mp::LXDVirtualMachine::add_extra_interface_to_instance_cloud_init(const std::string& default_mac_addr,
const NetworkInterface& extra_interface) const
{
const QJsonObject instance_info = lxd_request(manager, "GET", url());
QJsonObject instance_info_metadata = instance_info["metadata"].toObject();
QJsonObject config_section = instance_info_metadata["config"].toObject();
QJsonValueRef meta_data = config_section["user.meta-data"];
assert(!meta_data.isNull());
meta_data = QString::fromStdString(
mpu::emit_cloud_config(mpu::make_cloud_init_meta_config_with_id_tweak(meta_data.toString().toStdString())));
QJsonValueRef network_config_data = config_section["user.network-config"];
network_config_data = QString::fromStdString(mpu::emit_cloud_config(
mpu::add_extra_interface_to_network_config(default_mac_addr,
extra_interface,
network_config_data.toString().toStdString())));
instance_info_metadata["config"] = config_section;
const QJsonObject json_reply = lxd_request(manager, "PUT", url(), instance_info_metadata);
lxd_wait(manager, base_url, json_reply, timeout_milliseconds);
}
| 17,901
|
C++
|
.cpp
| 445
| 32.173034
| 119
| 0.613277
|
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,747
|
lxd_mount_handler.cpp
|
canonical_multipass/src/platform/backends/lxd/lxd_mount_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 "lxd_mount_handler.h"
#include "lxd_request.h"
namespace mp = multipass;
namespace
{
constexpr std::string_view category = "lxd-mount-handler";
constexpr int length_of_unique_id_without_prefix = 25;
constexpr int timeout_milliseconds = 30000;
} // namespace
namespace multipass
{
LXDMountHandler::LXDMountHandler(mp::NetworkAccessManager* network_manager,
LXDVirtualMachine* lxd_virtual_machine,
const SSHKeyProvider* ssh_key_provider,
const std::string& target_path,
VMMount mount_spec)
: MountHandler{lxd_virtual_machine, ssh_key_provider, std::move(mount_spec), target_path},
network_manager{network_manager},
lxd_instance_endpoint{
QString("%1/instances/%2").arg(lxd_socket_url.toString(), lxd_virtual_machine->vm_name.c_str())},
// make_uuid is a seed based unique id generator, that makes the device_name reproducible if the seed
// (target_path) is the same. If the seeds are different, then the generated ids are likely to be different as
// well. 27 (25 + 2(d_)) letters is the maximum device name length that LXD can accept and d_ stands for device
// name.
device_name{mp::utils::make_uuid(target_path)
.remove("-")
.left(length_of_unique_id_without_prefix)
.prepend("d_")
.toStdString()}
{
}
void LXDMountHandler::activate_impl(ServerVariant /**/, std::chrono::milliseconds /**/)
{
const VirtualMachine::State state = vm->current_state();
if (state != VirtualMachine::State::off && state != VirtualMachine::State::stopped)
{
throw mp::NativeMountNeedsStoppedVMException(vm->vm_name);
}
mpl::log(mpl::Level::info, std::string(category),
fmt::format("initializing native mount {} => {} in '{}'", source, target, vm->vm_name));
lxd_device_add();
}
void LXDMountHandler::deactivate_impl(bool /*force*/)
{
// TODO: remove the throwing and adjust the unit tests once lxd fix the hot-unmount bug
const VirtualMachine::State state = vm->current_state();
if (state != VirtualMachine::State::off && state != VirtualMachine::State::stopped)
{
throw std::runtime_error("Please stop the instance " + vm->vm_name + " before unmount it natively.");
}
mpl::log(mpl::Level::info, std::string(category),
fmt::format("Stopping native mount \"{}\" in instance '{}'", target, vm->vm_name));
lxd_device_remove();
}
LXDMountHandler::~LXDMountHandler() = default;
void LXDMountHandler::lxd_device_remove()
{
const QJsonObject instance_info = lxd_request(network_manager, "GET", lxd_instance_endpoint);
QJsonObject instance_info_metadata = instance_info["metadata"].toObject();
QJsonObject device_list = instance_info_metadata["devices"].toObject();
device_list.remove(device_name.c_str());
instance_info_metadata["devices"] = device_list;
// TODO: make this put method If-Match pattern
const QJsonObject json_reply = lxd_request(network_manager, "PUT", lxd_instance_endpoint, instance_info_metadata);
lxd_wait(network_manager, multipass::lxd_socket_url, json_reply, timeout_milliseconds);
}
void LXDMountHandler::lxd_device_add()
{
const QJsonObject instance_info = lxd_request(network_manager, "GET", lxd_instance_endpoint);
QJsonObject instance_info_metadata = instance_info["metadata"].toObject();
QJsonObject device_list = instance_info_metadata["devices"].toObject();
const std::string abs_target_path =
std::filesystem::path{target}.is_relative() ? fmt::format("/home/{}/{}", vm->ssh_username(), target) : target;
const QJsonObject new_device_object{
{"path", abs_target_path.c_str()}, {"source", source.c_str()}, {"type", "disk"}};
device_list.insert(device_name.c_str(), new_device_object);
instance_info_metadata["devices"] = device_list;
// TODO: make this put method If-Match pattern
const QJsonObject json_reply = lxd_request(network_manager, "PUT", lxd_instance_endpoint, instance_info_metadata);
lxd_wait(network_manager, multipass::lxd_socket_url, json_reply, timeout_milliseconds);
}
} // namespace multipass
| 4,924
|
C++
|
.cpp
| 98
| 44.255102
| 118
| 0.685655
|
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,748
|
journald_logger.cpp
|
canonical_multipass/src/platform/logger/journald_logger.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 "journald_logger.h"
#define SD_JOURNAL_SUPPRESS_LOCATION
#include <systemd/sd-journal.h>
namespace mpl = multipass::logging;
mpl::JournaldLogger::JournaldLogger(mpl::Level level) : LinuxLogger{level}
{
}
void mpl::JournaldLogger::log(mpl::Level level, CString category, CString message) const
{
if (level <= logging_level)
{
sd_journal_send("MESSAGE=%s", message.c_str(), "PRIORITY=%i", to_syslog_priority(level), "CATEGORY=%s",
category.c_str(), nullptr);
}
}
| 1,147
|
C++
|
.cpp
| 31
| 33.935484
| 111
| 0.725473
|
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,749
|
linux_logger.cpp
|
canonical_multipass/src/platform/logger/linux_logger.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 "linux_logger.h"
#include <multipass/logging/logger.h>
#include <syslog.h>
namespace mpl = multipass::logging;
mpl::LinuxLogger::LinuxLogger(mpl::Level level) : Logger{level}
{
}
| 819
|
C++
|
.cpp
| 23
| 33.826087
| 72
| 0.757881
|
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,750
|
syslog_logger.cpp
|
canonical_multipass/src/platform/logger/syslog_logger.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 "syslog_logger.h"
#include <syslog.h>
namespace mpl = multipass::logging;
mpl::SyslogLogger::SyslogLogger(mpl::Level level) : LinuxLogger{level}
{
openlog("multipass", LOG_CONS | LOG_PID, LOG_USER);
}
void mpl::SyslogLogger::log(mpl::Level level, CString category, CString message) const
{
if (level <= logging_level)
{
syslog(to_syslog_priority(level), "[%s] %s", category.c_str(), message.c_str());
}
}
| 1,070
|
C++
|
.cpp
| 30
| 33.233333
| 88
| 0.728764
|
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,751
|
new_release_monitor.cpp
|
canonical_multipass/src/platform/update/new_release_monitor.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 "new_release_monitor.h"
#include <multipass/exceptions/download_exception.h>
#include <multipass/logging/log.h>
#include <multipass/url_downloader.h>
#include <semver200.h>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto timeout = std::chrono::minutes(1);
constexpr auto json_tag_name = "version";
constexpr auto json_html_url = "release_url";
constexpr auto json_title = "title";
constexpr auto json_description = "description";
QJsonObject parse_manifest(const QByteArray& json)
{
QJsonParseError parse_error;
const auto doc = QJsonDocument::fromJson(json, &parse_error);
if (doc.isNull())
throw std::runtime_error(parse_error.errorString().toStdString());
if (!doc.isObject())
throw std::runtime_error("invalid JSON object");
return doc.object();
}
} // namespace
class mp::LatestReleaseChecker : public QThread
{
Q_OBJECT
public:
LatestReleaseChecker(QString update_url) : update_url(update_url)
{
}
void run() override
{
QUrl url(update_url);
try
{
mp::URLDownloader downloader(::timeout);
QByteArray json = downloader.download(url);
const auto manifest = ::parse_manifest(json);
if (!manifest.contains(::json_tag_name) || !manifest.contains(::json_html_url))
throw std::runtime_error("Update JSON missing required fields");
mp::NewReleaseInfo release;
release.version = manifest[::json_tag_name].toString();
release.url = manifest[::json_html_url].toString();
release.title = manifest[::json_title].toString();
release.description = manifest[::json_description].toString();
mpl::log(mpl::Level::debug, "update",
fmt::format("Latest Multipass release available is version {}", qUtf8Printable(release.version)));
emit latest_release_found(release);
}
catch (const mp::DownloadException& e)
{
mpl::log(mpl::Level::info, "update",
fmt::format("Failed to fetch update info: {}", qUtf8Printable(e.what())));
}
catch (const std::runtime_error& e)
{
mpl::log(mpl::Level::info, "update",
fmt::format("Failed to parse update info: {}", qUtf8Printable(e.what())));
}
}
signals:
void latest_release_found(const multipass::NewReleaseInfo& release);
private:
const QString update_url;
};
mp::NewReleaseMonitor::NewReleaseMonitor(const QString& current_version,
std::chrono::steady_clock::duration refresh_rate, const QString& update_url)
: current_version(current_version), update_url(update_url)
{
qRegisterMetaType<multipass::NewReleaseInfo>(); // necessary to allow custom type be passed in signal/slot
check_for_new_release();
refresh_timer.setInterval(std::chrono::duration_cast<std::chrono::milliseconds>(refresh_rate));
connect(&refresh_timer, &QTimer::timeout, this, &mp::NewReleaseMonitor::check_for_new_release);
refresh_timer.start();
}
mp::NewReleaseMonitor::~NewReleaseMonitor() = default;
std::optional<mp::NewReleaseInfo> mp::NewReleaseMonitor::get_new_release() const
{
return new_release;
}
void mp::NewReleaseMonitor::latest_release_found(const NewReleaseInfo& latest_release)
{
try
{
// Deliberately keeping all version string parsing here. If any version string
// not of correct form, throw.
if (version::Semver200_version(current_version.toStdString()) <
version::Semver200_version(latest_release.version.toStdString()))
{
new_release = latest_release;
mpl::log(mpl::Level::info, "update",
fmt::format("A New Multipass release is available: {}", qUtf8Printable(new_release->version)));
}
}
catch (const version::Parse_error& e)
{
mpl::log(mpl::Level::warning, "update",
fmt::format("Version strings {} and {} not comparable: {}", qUtf8Printable(current_version),
qUtf8Printable(latest_release.version), e.what()));
}
}
void mp::NewReleaseMonitor::check_for_new_release()
{
if (!worker_thread)
{
worker_thread.reset(new mp::LatestReleaseChecker(update_url));
connect(worker_thread.get(), &mp::LatestReleaseChecker::latest_release_found, this,
&mp::NewReleaseMonitor::latest_release_found);
connect(worker_thread.get(), &QThread::finished, this, [this]() { worker_thread.reset(); });
worker_thread->start();
}
}
#include "new_release_monitor.moc"
| 5,418
|
C++
|
.cpp
| 134
| 33.992537
| 119
| 0.668694
|
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,752
|
default_update_prompt.cpp
|
canonical_multipass/src/platform/update/default_update_prompt.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 "default_update_prompt.h"
#include "new_release_monitor.h"
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/version.h>
namespace mp = multipass;
namespace
{
constexpr auto new_release_check_frequency = std::chrono::hours(24);
constexpr auto notify_user_frequency = std::chrono::hours(6);
} // namespace
mp::DefaultUpdatePrompt::DefaultUpdatePrompt()
: monitor{std::make_unique<NewReleaseMonitor>(mp::version_string, ::new_release_check_frequency)},
last_shown{std::chrono::system_clock::now() - notify_user_frequency} // so we show update message soon after start
{
}
mp::DefaultUpdatePrompt::~DefaultUpdatePrompt() = default;
bool mp::DefaultUpdatePrompt::is_time_to_show()
{
return monitor->get_new_release() && last_shown + ::notify_user_frequency < std::chrono::system_clock::now();
}
void mp::DefaultUpdatePrompt::populate(mp::UpdateInfo* update_info)
{
auto new_release = monitor->get_new_release();
if (new_release)
{
update_info->set_version(new_release->version.toStdString());
update_info->set_url(new_release->url.toEncoded());
update_info->set_title(new_release->title.toStdString());
update_info->set_description(new_release->description.toStdString());
last_shown = std::chrono::system_clock::now();
}
}
void mp::DefaultUpdatePrompt::populate_if_time_to_show(mp::UpdateInfo* update_info)
{
if (is_time_to_show())
populate(update_info);
}
| 2,096
|
C++
|
.cpp
| 53
| 36.54717
| 120
| 0.733038
|
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,753
|
client_platform.cpp
|
canonical_multipass/src/platform/client/client_platform.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_platform.h>
#include <QFileInfo>
#include <unistd.h>
namespace mp = multipass;
namespace mcp = multipass::cli::platform;
void mcp::parse_transfer_entry(const QString& entry, QString& path, QString& instance_name)
{
auto colon_count = entry.count(":");
switch (colon_count)
{
case 0:
path = entry;
break;
case 1:
if (!QFileInfo::exists(entry))
{
instance_name = entry.section(":", 0, 0);
path = entry.section(":", 1);
}
else
{
path = entry;
}
break;
}
}
int mcp::getuid()
{
return ::getuid();
}
int mcp::getgid()
{
return ::getgid();
}
std::string mcp::Platform::get_password(mp::Terminal*) const
{
return {};
}
void mcp::Platform::enable_ansi_escape_chars() const
{
return;
}
| 1,493
|
C++
|
.cpp
| 58
| 21.758621
| 91
| 0.661754
|
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,754
|
simple_streams_index.cpp
|
canonical_multipass/src/simplestreams/simple_streams_index.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: Chris Townsend <christopher.townsend@canonical.com>
* Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include <multipass/simple_streams_index.h>
#include <QJsonDocument>
#include <QJsonObject>
namespace mp = multipass;
namespace
{
QJsonObject parse_index(const QByteArray& json)
{
QJsonParseError parse_error;
auto doc = QJsonDocument::fromJson(json, &parse_error);
if (doc.isNull())
throw std::runtime_error(parse_error.errorString().toStdString());
if (!doc.isObject())
throw std::runtime_error("invalid index object");
auto index = doc.object()["index"].toObject();
if (index.isEmpty())
throw std::runtime_error("No index found");
return index;
}
}
mp::SimpleStreamsIndex mp::SimpleStreamsIndex::fromJson(const QByteArray& json)
{
auto index = parse_index(json);
for (QJsonValueRef value : index)
{
auto entry = value.toObject();
if (entry["datatype"] == "image-downloads")
{
auto path_entry = entry["path"];
auto date_entry = entry["updated"];
return {path_entry.toString(), date_entry.toString()};
}
}
throw std::runtime_error("no image-downloads entry found");
}
| 1,881
|
C++
|
.cpp
| 54
| 30.722222
| 79
| 0.696753
|
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,755
|
simple_streams_manifest.cpp
|
canonical_multipass/src/simplestreams/simple_streams_manifest.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/simple_streams_manifest.h>
#include <QFileInfo>
#include <QHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSysInfo>
#include <multipass/constants.h>
#include <multipass/exceptions/manifest_exceptions.h>
#include <multipass/settings/settings.h>
#include <multipass/utils.h>
namespace mp = multipass;
namespace
{
const QHash<QString, QString> arch_to_manifest{{"x86_64", "amd64"}, {"arm", "armhf"}, {"arm64", "arm64"},
{"i386", "i386"}, {"power", "powerpc"}, {"power64", "ppc64el"},
{"s390x", "s390x"}};
QJsonObject parse_manifest(const QByteArray& json)
{
QJsonParseError parse_error;
const auto doc = QJsonDocument::fromJson(json, &parse_error);
if (doc.isNull())
throw mp::GenericManifestException(parse_error.errorString().toStdString());
if (!doc.isObject())
throw mp::GenericManifestException("invalid manifest object");
return doc.object();
}
QString latest_version_in(const QJsonObject& versions)
{
QString max_version;
for (auto it = versions.constBegin(); it != versions.constEnd(); ++it)
{
const auto version = it.key();
if (version < max_version)
continue;
max_version = version;
}
return max_version;
}
QMap<QString, const mp::VMImageInfo*> qmap_aliases_to_vm_info_for(const std::vector<mp::VMImageInfo>& images)
{
QMap<QString, const mp::VMImageInfo*> map;
for (const auto& image : images)
{
map[image.id] = ℑ
for (const auto& alias : image.aliases)
{
map[alias] = ℑ
}
}
return map;
}
} // namespace
mp::SimpleStreamsManifest::SimpleStreamsManifest(const QString& updated_at, std::vector<VMImageInfo>&& images)
: updated_at{updated_at}, products{std::move(images)}, image_records{qmap_aliases_to_vm_info_for(products)}
{
}
std::unique_ptr<mp::SimpleStreamsManifest>
mp::SimpleStreamsManifest::fromJson(const QByteArray& json_from_official,
const std::optional<QByteArray>& json_from_mirror, const QString& host_url)
{
const auto manifest_from_official = parse_manifest(json_from_official);
const auto updated = manifest_from_official["updated"].toString();
const auto manifest_products_from_official = manifest_from_official["products"].toObject();
if (manifest_products_from_official.isEmpty())
throw mp::GenericManifestException("No products found");
auto arch = arch_to_manifest.value(QSysInfo::currentCpuArchitecture());
if (arch.isEmpty())
throw mp::GenericManifestException("Unsupported cloud image architecture");
std::optional<QJsonObject> manifest_products_from_mirror = std::nullopt;
if (json_from_mirror)
{
const auto manifest_from_mirror = parse_manifest(json_from_mirror.value());
const auto products_from_mirror = manifest_from_mirror["products"].toObject();
manifest_products_from_mirror = std::make_optional(products_from_mirror);
}
const QJsonObject manifest_products = manifest_products_from_mirror.value_or(manifest_products_from_official);
std::vector<VMImageInfo> products;
for (auto it = manifest_products.constBegin(); it != manifest_products.constEnd(); ++it)
{
const auto product_key = it.key();
const QJsonValue product = it.value();
if (product["arch"].toString() != arch)
continue;
const auto product_aliases = product["aliases"].toString().split(",");
const auto release = product["release"].toString();
const auto release_title = product["release_title"].toString();
const auto release_codename = product["release_codename"].toString();
const auto supported = product["supported"].toBool() || product_aliases.contains("devel");
const auto versions = product["versions"].toObject();
if (versions.isEmpty())
continue;
const auto latest_version = latest_version_in(versions);
for (auto it = versions.constBegin(); it != versions.constEnd(); ++it)
{
const auto version_string = it.key();
const auto version = versions[version_string].toObject();
const auto version_from_official = manifest_products_from_official[product_key]
.toObject()["versions"]
.toObject()[version_string]
.toObject();
if (version != version_from_official)
continue;
const auto items = version["items"].toObject();
if (items.isEmpty())
continue;
const auto& driver = MP_SETTINGS.get(mp::driver_key);
QJsonObject image;
QString sha256, image_location;
int size = -1;
// TODO: make this a VM factory call with a preference list
if (driver == "lxd")
{
image = items["lxd.tar.xz"].toObject();
// Avoid kvm image due to canonical/multipass#2491
if (image.contains("combined_disk1-img_sha256"))
{
sha256 = image["combined_disk1-img_sha256"].toString();
}
else
continue;
}
else
{
const auto image_key = items.contains("uefi1.img") ? "uefi1.img" : "disk1.img";
image = items[image_key].toObject();
image_location = image["path"].toString();
sha256 = image["sha256"].toString();
size = image["size"].toInt(-1);
}
// Aliases always alias to the latest version
const QStringList& aliases = version_string == latest_version ? product_aliases : QStringList();
products.push_back({aliases,
"Ubuntu",
release,
release_title,
release_codename,
supported,
image_location,
sha256,
host_url,
version_string,
size,
true});
}
}
if (products.empty())
throw mp::EmptyManifestException("No supported products found.");
return std::make_unique<SimpleStreamsManifest>(updated, std::move(products));
}
| 7,339
|
C++
|
.cpp
| 165
| 33.872727
| 114
| 0.598963
|
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,756
|
local_socket_reply.cpp
|
canonical_multipass/src/network/local_socket_reply.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 "local_socket_reply.h"
#include <multipass/exceptions/http_local_socket_exception.h>
#include <multipass/format.h>
#include <vector>
#include <QRegularExpression>
namespace mp = multipass;
namespace
{
constexpr int len = 65536;
constexpr int max_bytes = 32768;
// Status code mapping based on
// https://github.com/qt/qtbase/blob/dev/src/network/access/qhttpthreaddelegate.cpp
QNetworkReply::NetworkError statusCodeFromHttp(int httpStatusCode)
{
QNetworkReply::NetworkError code;
// Only switch on the LXD HTTP errors:
// https://lxd.readthedocs.io/en/latest/rest-api/#error
switch (httpStatusCode)
{
case 400: // Bad Request
code = QNetworkReply::ProtocolInvalidOperationError;
break;
case 401: // Authorization required
code = QNetworkReply::AuthenticationRequiredError;
break;
case 403: // Access denied
code = QNetworkReply::ContentAccessDenied;
break;
case 404: // Not Found
code = QNetworkReply::ContentNotFoundError;
break;
case 409: // Resource Conflict
code = QNetworkReply::ContentConflictError;
break;
case 500: // Internal Server Error
code = QNetworkReply::InternalServerError;
break;
default:
if (httpStatusCode > 500)
{
// some kind of server error
code = QNetworkReply::UnknownServerError;
}
else
{
// content error we did not handle above
code = QNetworkReply::UnknownContentError;
}
}
return code;
}
} // namespace
mp::LocalSocketReply::LocalSocketReply(LocalSocketUPtr local_socket, const QNetworkRequest& request,
QIODevice* outgoingData)
: QNetworkReply(), local_socket{std::move(local_socket)}, reply_data{QByteArray(len, '\0')}
{
open(QIODevice::ReadOnly);
QObject::connect(this->local_socket.get(), &QLocalSocket::readyRead, this, &LocalSocketReply::read_reply);
QObject::connect(this->local_socket.get(), &QLocalSocket::readChannelFinished, this,
&LocalSocketReply::read_finish);
send_request(request, outgoingData);
}
// Mainly for testing
mp::LocalSocketReply::LocalSocketReply()
{
open(QIODevice::ReadOnly);
setFinished(true);
emit finished();
}
mp::LocalSocketReply::~LocalSocketReply()
{
if (local_socket)
{
local_socket->disconnectFromServer();
}
}
void mp::LocalSocketReply::abort()
{
close();
setError(OperationCanceledError, "Operation canceled");
emit errorOccurred(OperationCanceledError);
setFinished(true);
emit finished();
}
qint64 mp::LocalSocketReply::readData(char* data, qint64 maxSize)
{
if (offset < content_data.size())
{
qint64 number = qMin(maxSize, content_data.size() - offset);
memcpy(data, content_data.constData() + offset, number);
offset += number;
return number;
}
return -1;
}
void mp::LocalSocketReply::send_request(const QNetworkRequest& request, QIODevice* outgoingData)
{
QByteArray http_data;
http_data.reserve(1024);
auto op = request.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray();
// Build the HTTP method part
http_data += op + ' ' + request.url().path().toLatin1();
if (request.url().hasQuery())
{
http_data += "?" + request.url().query().toLatin1();
}
http_data += " HTTP/1.1\r\n";
// Build the HTTP Host header
auto host = request.url().host().toLatin1();
if (!host.isEmpty())
{
http_data += "Host: " + host + "\r\n";
}
else
{
throw mp::HttpLocalSocketException("Host is required in URL");
}
// Build the HTTP User-Agent header
auto user_agent = request.header(QNetworkRequest::UserAgentHeader).toByteArray();
if (!user_agent.isEmpty())
{
http_data += "User-Agent: " + user_agent + "\r\n";
}
// Workaround weird issue in LXD's use of Go where Go's HTTP handler thinks there is more
// data and "sees" and "empty" query and reponds with an unexpected 400 error
http_data += "Connection: close\r\n";
if (!local_socket_write(http_data))
return;
if (op == "POST" || op == "PUT" || op == "PATCH")
{
http_data = "Content-Type: " + request.header(QNetworkRequest::ContentTypeHeader).toByteArray() + "\r\n";
if (outgoingData && outgoingData->size() > 0)
{
auto content_length = request.header(QNetworkRequest::ContentLengthHeader).toByteArray();
auto transfer_encoding = request.rawHeader("Transfer-Encoding").toLower();
bool is_chunked = transfer_encoding.contains("chunked") ? true : false;
if (!content_length.isEmpty())
{
if (is_chunked)
{
throw mp::HttpLocalSocketException("Both the \'Content-Length\' header and \'chunked\' transfer "
"encoding cannot be set at the same time");
}
http_data += "Content-Length: " + content_length + "\r\n";
}
else if (content_length.isEmpty() && !is_chunked)
{
throw mp::HttpLocalSocketException(
"Either the \'Content-Length\' header or \'chunked\' transfer encoding must be set");
}
if (!transfer_encoding.isEmpty())
{
http_data += "Transfer-Encoding: " + transfer_encoding + "\r\n";
}
if (!local_socket_write(http_data + "\r\n"))
return;
local_socket->flush();
outgoingData->open(QIODevice::ReadOnly);
std::vector<char> data_buffer;
data_buffer.reserve(max_bytes);
int bytes_read{0};
while ((bytes_read = outgoingData->read(data_buffer.data(), max_bytes)) > 0)
{
if (is_chunked && !local_socket_write(QByteArray::number(bytes_read, 16) + "\r\n"))
return;
if (!local_socket_write(QByteArray::fromRawData(data_buffer.data(), bytes_read)))
return;
if (is_chunked && !local_socket_write("\r\n"))
return;
local_socket->waitForBytesWritten();
}
if (bytes_read < 0)
{
throw mp::HttpLocalSocketException(
fmt::format("Cannot read data to send to socket: {}", outgoingData->errorString()));
}
// Trailer part for chunked data
if (is_chunked && !local_socket_write("0\r\n"))
return;
}
}
if (!local_socket_write("\r\n"))
return;
local_socket->flush();
}
void mp::LocalSocketReply::read_reply()
{
auto data_ptr = reply_data.data() + reply_offset;
int bytes_read{0};
do
{
if (reply_offset + local_socket->bytesAvailable() > reply_data.length())
{
reply_data.append(len, '\0');
data_ptr = reply_data.data() + reply_offset;
}
bytes_read = local_socket->read(data_ptr, len);
reply_offset += bytes_read;
data_ptr += bytes_read;
} while (bytes_read > 0);
}
void mp::LocalSocketReply::read_finish()
{
if (local_socket->bytesAvailable())
read_reply();
if (reply_offset)
parse_reply();
setFinished(true);
emit finished();
}
void mp::LocalSocketReply::parse_reply()
{
auto reply_lines = reply_data.split('\n');
auto it = reply_lines.constBegin();
parse_status(*it);
for (++it; it != reply_lines.constEnd(); ++it)
{
if ((*it).contains("Transfer-Encoding") && (*it).contains("chunked"))
chunked_transfer_encoding = true;
if ((*it).isEmpty() || (*it).startsWith('\r'))
{
// Advance to the body
// Chunked transfer encoding also includes a line with the amount of
// bytes (in hex) in the chunk. We just skip it for now.
it = chunked_transfer_encoding ? it + 2 : it + 1;
content_data = (*it).trimmed();
break;
}
}
}
void mp::LocalSocketReply::parse_status(const QByteArray& status)
{
QRegularExpression http_status_regex{"^HTTP/\\d\\.\\d (?P<status>\\d{3})\\ (?P<message>.*)$"};
QRegularExpressionMatch http_status_match = http_status_regex.match(QString::fromLatin1(status));
if (!http_status_match.hasMatch())
{
setError(QNetworkReply::ProtocolFailure, "Malformed HTTP response from server");
emit errorOccurred(QNetworkReply::ProtocolFailure);
return;
}
bool ok;
auto statusCode = http_status_match.captured("status").toInt(&ok);
if (statusCode >= 400)
{
auto error_code = statusCodeFromHttp(statusCode);
setError(error_code, http_status_match.captured("message"));
emit errorOccurred(error_code);
}
}
bool mp::LocalSocketReply::local_socket_write(const QByteArray& data)
{
auto bytes_written = local_socket->write(data);
if (bytes_written < 0)
{
setError(QNetworkReply::InternalServerError, local_socket->errorString());
emit errorOccurred(QNetworkReply::InternalServerError);
return false;
}
return true;
}
| 10,039
|
C++
|
.cpp
| 276
| 28.807971
| 117
| 0.619672
|
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,757
|
ip_address.cpp
|
canonical_multipass/src/network/ip_address.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/ip_address.h>
#include <sstream>
namespace mp = multipass;
namespace
{
uint8_t as_octet(uint32_t value)
{
return static_cast<uint8_t>(value);
}
void check_range(int value)
{
if (value < 0 || value > 255)
throw std::invalid_argument("invalid IP octet");
}
std::array<uint8_t, 4> parse(const std::string& ip)
{
char ch;
int a = -1;
int b = -1;
int c = -1;
int d = -1;
std::stringstream s(ip);
s >> a >> ch >> b >> ch >> c >> ch >> d;
check_range(a);
check_range(b);
check_range(c);
check_range(d);
return {{as_octet(a), as_octet(b), as_octet(c), as_octet(d)}};
}
std::array<uint8_t, 4> to_octets(uint32_t value)
{
return {{as_octet(value >> 24u), as_octet(value >> 16u), as_octet(value >> 8u), as_octet(value)}};
}
}
mp::IPAddress::IPAddress(std::array<uint8_t, 4> octets) : octets{octets}
{
}
mp::IPAddress::IPAddress(const std::string& ip) : IPAddress(parse(ip))
{
}
mp::IPAddress::IPAddress(uint32_t value) : IPAddress(to_octets(value))
{
}
std::string mp::IPAddress::as_string() const
{
std::stringstream ip;
ip << static_cast<int>(octets[0]) << "." << static_cast<int>(octets[1]) << "." << static_cast<int>(octets[2]) << "."
<< static_cast<int>(octets[3]);
return ip.str();
}
uint32_t mp::IPAddress::as_uint32() const
{
uint32_t value = octets[0] << 24u;
value |= octets[1] << 16u;
value |= octets[2] << 8u;
value |= octets[3];
return value;
}
bool mp::IPAddress::operator==(const IPAddress& other) const
{
return octets == other.octets;
}
bool mp::IPAddress::operator!=(const IPAddress& other) const
{
return octets != other.octets;
}
bool mp::IPAddress::operator<(const IPAddress& other) const
{
return as_uint32() < other.as_uint32();
}
bool mp::IPAddress::operator<=(const IPAddress& other) const
{
return as_uint32() <= other.as_uint32();
}
bool mp::IPAddress::operator>(const IPAddress& other) const
{
return as_uint32() > other.as_uint32();
}
bool mp::IPAddress::operator>=(const IPAddress& other) const
{
return as_uint32() >= other.as_uint32();
}
mp::IPAddress mp::IPAddress::operator+(int value) const
{
return mp::IPAddress(as_uint32() + value);
}
| 2,866
|
C++
|
.cpp
| 102
| 25.421569
| 120
| 0.671892
|
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,758
|
network_access_manager.cpp
|
canonical_multipass/src/network/network_access_manager.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 "local_socket_reply.h"
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/format.h>
#include <multipass/network_access_manager.h>
namespace mp = multipass;
mp::NetworkAccessManager::NetworkAccessManager(QObject* parent) : QNetworkAccessManager(parent)
{
}
QNetworkReply* mp::NetworkAccessManager::createRequest(QNetworkAccessManager::Operation operation,
const QNetworkRequest& orig_request, QIODevice* device)
{
auto scheme = orig_request.url().scheme();
// To support http requests over Unix sockets, the initial URL needs to be in the form of:
// unix:///path/to/unix_socket@path/in/server (or 'local' instead of 'unix')
//
// For example, to get the general LXD configuration when LXD is installed as a snap:
// unix:////var/snap/lxd/common/lxd/unix.socket@1.0
if (scheme == "unix" || scheme == "local")
{
const auto url_parts = orig_request.url().toString().split('@');
if (url_parts.count() != 2)
{
throw LocalSocketConnectionException("The local socket scheme is malformed.");
}
const auto socket_path = QUrl(url_parts[0]).path();
LocalSocketUPtr local_socket = std::make_unique<QLocalSocket>();
local_socket->connectToServer(socket_path);
if (!local_socket->waitForConnected(5000))
{
throw LocalSocketConnectionException(
fmt::format("Cannot connect to {}: {}", socket_path, local_socket->errorString()));
}
const auto server_path = url_parts[1];
QNetworkRequest request{orig_request};
QUrl url(QString("/%1").arg(server_path));
url.setHost(orig_request.url().host());
request.setUrl(url);
// The caller needs to be responsible for freeing the allocated memory
return new LocalSocketReply(std::move(local_socket), request, device);
}
else
{
return QNetworkAccessManager::createRequest(operation, orig_request, device);
}
}
| 2,705
|
C++
|
.cpp
| 61
| 38.180328
| 110
| 0.684531
|
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,759
|
url_downloader.cpp
|
canonical_multipass/src/network/url_downloader.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/url_downloader.h>
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/file_ops.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/version.h>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QNetworkDiskCache>
#include <QNetworkReply>
#include <QTimer>
#include <QUrl>
#include <memory>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "url downloader";
using NetworkReplyUPtr = std::unique_ptr<QNetworkReply>;
auto make_network_manager(const mp::Path& cache_dir_path)
{
auto manager = std::make_unique<QNetworkAccessManager>();
if (!cache_dir_path.isEmpty())
{
auto network_cache = new QNetworkDiskCache;
network_cache->setCacheDirectory(cache_dir_path);
// Manager now owns network_cache and so it will delete it in its dtor
manager->setCache(network_cache);
}
return manager;
}
void wait_for_reply(QNetworkReply* reply, QTimer& download_timeout)
{
QEventLoop event_loop;
QObject::connect(reply, &QNetworkReply::finished, &event_loop, &QEventLoop::quit);
QObject::connect(&download_timeout, &QTimer::timeout, [reply, &download_timeout]() {
download_timeout.stop();
reply->abort();
});
download_timeout.start();
event_loop.exec();
}
template <typename ProgressAction, typename DownloadAction, typename ErrorAction, typename Time>
QByteArray
download(QNetworkAccessManager* manager, const Time& timeout, QUrl const& url, ProgressAction&& on_progress,
DownloadAction&& on_download, ErrorAction&& on_error, const std::atomic_bool& abort_download,
const QNetworkRequest::CacheLoadControl cache_load_control = QNetworkRequest::CacheLoadControl::PreferNetwork)
{
QTimer download_timeout;
download_timeout.setInterval(timeout);
QNetworkRequest request{url};
request.setRawHeader("Connection", "Keep-Alive");
request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, cache_load_control);
request.setHeader(
QNetworkRequest::UserAgentHeader,
QString::fromStdString(fmt::format("Multipass/{} ({}; {})", multipass::version_string,
mp::platform::host_version(), QSysInfo::currentCpuArchitecture())));
NetworkReplyUPtr reply{manager->get(request)};
QObject::connect(reply.get(), &QNetworkReply::downloadProgress, [&](qint64 bytes_received, qint64 bytes_total) {
on_progress(reply.get(), bytes_received, bytes_total);
});
QObject::connect(reply.get(), &QNetworkReply::readyRead, [&]() { on_download(reply.get(), download_timeout); });
wait_for_reply(reply.get(), download_timeout);
if (reply->error() != QNetworkReply::NoError)
{
const auto msg = download_timeout.isActive() ? reply->errorString().toStdString() : "Network timeout";
if (reply->error() == QNetworkReply::ProxyAuthenticationRequiredError || abort_download)
{
on_error();
throw mp::AbortedDownloadException{msg};
}
if (cache_load_control == QNetworkRequest::CacheLoadControl::AlwaysCache)
{
on_error();
throw mp::DownloadException{url.toString().toStdString(), msg};
}
mpl::log(mpl::Level::warning, category,
fmt::format("Error getting {}: {} - trying cache.", url.toString(), msg));
return ::download(manager, timeout, url, on_progress, on_download, on_error, abort_download,
QNetworkRequest::CacheLoadControl::AlwaysCache);
}
mpl::log(mpl::Level::trace, category,
fmt::format("Found {} in cache: {}", url.toString(),
reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool()));
return reply->readAll();
}
template <typename Time>
auto get_header(QNetworkAccessManager* manager, const QUrl& url, const QNetworkRequest::KnownHeaders header,
const Time& timeout)
{
QTimer download_timeout;
download_timeout.setInterval(timeout);
QNetworkRequest request{url};
NetworkReplyUPtr reply{manager->head(request)};
wait_for_reply(reply.get(), download_timeout);
if (reply->error() != QNetworkReply::NoError)
{
const auto msg = download_timeout.isActive() ? reply->errorString().toStdString() : "Network timeout";
mpl::log(mpl::Level::warning, category, fmt::format("Cannot retrieve headers for {}: {}", url.toString(), msg));
throw mp::DownloadException{url.toString().toStdString(), reply->errorString().toStdString()};
}
return reply->header(header);
}
} // namespace
mp::NetworkManagerFactory::NetworkManagerFactory(const Singleton<NetworkManagerFactory>::PrivatePass& pass) noexcept
: Singleton<NetworkManagerFactory>::Singleton{pass}
{
}
std::unique_ptr<QNetworkAccessManager>
mp::NetworkManagerFactory::make_network_manager(const mp::Path& cache_dir_path) const
{
return ::make_network_manager(cache_dir_path);
}
mp::URLDownloader::URLDownloader(std::chrono::milliseconds timeout) : URLDownloader{Path(), timeout}
{
}
mp::URLDownloader::URLDownloader(const mp::Path& cache_dir, std::chrono::milliseconds timeout)
: cache_dir_path{QDir(cache_dir).filePath("network-cache")}, timeout{timeout}
{
}
void mp::URLDownloader::download_to(const QUrl& url, const QString& file_name, int64_t size, const int download_type,
const mp::ProgressMonitor& monitor)
{
std::atomic_bool abort_download{false};
auto manager{MP_NETMGRFACTORY.make_network_manager(cache_dir_path)};
QFile file{file_name};
file.open(QIODevice::ReadWrite | QIODevice::Truncate);
auto progress_monitor = [this, &abort_download, &monitor, download_type,
size](QNetworkReply* reply, qint64 bytes_received, qint64 bytes_total) {
static int last_progress_printed = -1;
if (bytes_received == 0)
return;
if (bytes_total == -1 && size > 0)
bytes_total = size;
auto progress = (size < 0) ? size : (100 * bytes_received + bytes_total / 2) / bytes_total;
abort_download = abort_downloads || (last_progress_printed != progress && !monitor(download_type, progress));
last_progress_printed = progress;
if (abort_download)
{
reply->abort();
}
};
auto on_download = [this, &abort_download, &file](QNetworkReply* reply, QTimer& download_timeout) {
abort_download = abort_download || abort_downloads;
if (abort_download)
{
reply->abort();
return;
}
if (download_timeout.isActive())
download_timeout.stop();
else
return;
if (MP_FILEOPS.write(file, reply->readAll()) < 0)
{
mpl::log(mpl::Level::error, category, fmt::format("error writing image: {}", file.errorString()));
abort_download = true;
reply->abort();
}
download_timeout.start();
};
auto on_error = [&file]() { file.remove(); };
::download(manager.get(), timeout, url, progress_monitor, on_download, on_error, abort_download);
}
QByteArray mp::URLDownloader::download(const QUrl& url)
{
return download(url, false);
}
QByteArray mp::URLDownloader::download(const QUrl& url, const bool is_force_update_from_network)
{
auto manager{MP_NETMGRFACTORY.make_network_manager(cache_dir_path)};
// This will connect to the QNetworkReply::readReady signal and when emitted,
// reset the timer.
auto on_download = [this](QNetworkReply* reply, QTimer& download_timeout) {
if (abort_downloads)
{
reply->abort();
return;
}
download_timeout.start();
};
const QNetworkRequest::CacheLoadControl cache_load_control = is_force_update_from_network
? QNetworkRequest::CacheLoadControl::AlwaysNetwork
: QNetworkRequest::CacheLoadControl::PreferNetwork;
return ::download(
manager.get(), timeout, url, [](QNetworkReply*, qint64, qint64) {}, on_download, [] {}, abort_downloads,
cache_load_control);
}
QDateTime mp::URLDownloader::last_modified(const QUrl& url)
{
auto manager{MP_NETMGRFACTORY.make_network_manager(cache_dir_path)};
return get_header(manager.get(), url, QNetworkRequest::LastModifiedHeader, timeout).toDateTime();
}
void mp::URLDownloader::abort_all_downloads()
{
abort_downloads = true;
}
| 9,513
|
C++
|
.cpp
| 217
| 37.142857
| 120
| 0.677706
|
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,760
|
log.cpp
|
canonical_multipass/src/logging/log.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/logging/log.h>
#include <multipass/format.h>
#include <QString>
#include <QtGlobal>
#include <shared_mutex>
#include <stdexcept>
namespace mpl = multipass::logging;
namespace
{
std::shared_timed_mutex mutex;
std::shared_ptr<multipass::logging::Logger> global_logger;
mpl::Level to_level(QtMsgType type)
{
switch (type)
{
case QtDebugMsg:
return mpl::Level::debug;
case QtInfoMsg:
return mpl::Level::info;
case QtWarningMsg:
return mpl::Level::warning;
case QtCriticalMsg:
case QtFatalMsg:
return mpl::Level::error;
}
throw std::invalid_argument("Unknown Qt log message type");
}
void qt_message_handler(QtMsgType type, const QMessageLogContext&, const QString& message)
{
auto msg = message.toLocal8Bit();
mpl::log(to_level(type), "Qt", msg.constData());
}
} // namespace
void mpl::log(Level level, CString category, CString message)
{
std::shared_lock<decltype(mutex)> lock{mutex};
if (global_logger)
global_logger->log(level, category, message);
else
fmt::print(stderr, "[{}] [{}] {}\n", as_string(level).c_str(), category.c_str(), message.c_str());
}
mpl::Level mpl::get_logging_level()
{
if (global_logger)
{
return global_logger->get_logging_level();
}
return Level::error;
}
void mpl::set_logger(std::shared_ptr<Logger> logger)
{
std::lock_guard<decltype(mutex)> lock{mutex};
global_logger = std::move(logger);
qInstallMessageHandler(qt_message_handler);
}
auto mpl::get_logger() -> Logger* // for tests, don't rely on it lasting
{
return global_logger.get();
}
| 2,273
|
C++
|
.cpp
| 75
| 27.013333
| 106
| 0.706636
|
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,761
|
multiplexing_logger.cpp
|
canonical_multipass/src/logging/multiplexing_logger.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/logging/multiplexing_logger.h>
#include <algorithm>
namespace mpl = multipass::logging;
multipass::logging::MultiplexingLogger::MultiplexingLogger(UPtr system_logger)
: Logger{system_logger->get_logging_level()}, system_logger{std::move(system_logger)}
{
}
void mpl::MultiplexingLogger::log(mpl::Level level, CString category, CString message) const
{
std::shared_lock<decltype(mutex)> lock{mutex};
system_logger->log(level, category, message);
for (auto logger : loggers)
logger->log(level, category, message);
}
void mpl::MultiplexingLogger::add_logger(const Logger* logger)
{
std::lock_guard<decltype(mutex)> lock{mutex};
loggers.push_back(logger);
}
void mpl::MultiplexingLogger::remove_logger(const Logger* logger)
{
std::lock_guard<decltype(mutex)> lock{mutex};
loggers.erase(std::remove(loggers.begin(), loggers.end(), logger), loggers.end());
}
| 1,548
|
C++
|
.cpp
| 40
| 36.15
| 92
| 0.750167
|
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,762
|
standard_logger.cpp
|
canonical_multipass/src/logging/standard_logger.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/logging/standard_logger.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
mpl::StandardLogger::StandardLogger(mpl::Level level) : Logger{level}
{
}
void mpl::StandardLogger::log(mpl::Level level, CString category, CString message) const
{
if (level <= logging_level)
{
fmt::print(stderr, "[{}] [{}] [{}] {}\n", timestamp(), as_string(level).c_str(), category.c_str(),
message.c_str());
}
}
| 1,127
|
C++
|
.cpp
| 31
| 33.451613
| 106
| 0.714024
|
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,763
|
petname.cpp
|
canonical_multipass/src/petname/petname.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 "petname.h"
#include "multipass/petname/names.h"
#include <iostream>
namespace mp = multipass;
namespace
{
constexpr auto num_names = std::extent<decltype(mp::petname::names)>::value;
constexpr auto num_adverbs = std::extent<decltype(mp::petname::adverbs)>::value;
constexpr auto num_adjectives = std::extent<decltype(mp::petname::adjectives)>::value;
// Arbitrary but arrays should have at least 100 entries each
static_assert(num_names >= 100, "");
static_assert(num_adverbs >= 100, "");
static_assert(num_adjectives >= 100, "");
std::mt19937 make_engine()
{
std::random_device device;
return std::mt19937(device());
}
}
mp::Petname::Petname(std::string separator)
: Petname(NumWords::TWO, separator)
{
}
mp::Petname::Petname(NumWords num_words)
: Petname(num_words, "-")
{
}
mp::Petname::Petname(NumWords num_words, std::string separator)
: separator{separator},
num_words{num_words},
engine{make_engine()},
name_dist{1, num_names - 1},
adjective_dist{0, num_adjectives - 1},
adverb_dist{0, num_adverbs - 1}
{
}
std::string mp::Petname::make_name()
{
std::string name = multipass::petname::names[name_dist(engine)];
std::string adjective = multipass::petname::adjectives[adjective_dist(engine)];
std::string adverb = multipass::petname::adverbs[adverb_dist(engine)];
switch(num_words)
{
case NumWords::ONE:
return name;
case NumWords::TWO:
return adjective + separator + name;
case NumWords::THREE:
return adverb + separator + adjective + separator + name;
default:
throw std::invalid_argument("Invalid number of words chosen");
}
}
| 2,372
|
C++
|
.cpp
| 71
| 30.309859
| 86
| 0.714535
|
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,764
|
make_name_generator.cpp
|
canonical_multipass/src/petname/make_name_generator.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 "petname.h"
#include <multipass/name_generator.h>
namespace mp = multipass;
mp::NameGenerator::UPtr mp::make_default_name_generator()
{
return std::make_unique<mp::Petname>(mp::Petname::NumWords::TWO, "-");
}
| 920
|
C++
|
.cpp
| 25
| 34.84
| 74
| 0.75
|
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,765
|
text_to_string_array.cpp
|
canonical_multipass/src/petname/text_to_string_array.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 <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace
{
void usage(char* argv[])
{
std::cout << "Usage:\n ";
std::cout << argv[0] << " <adjectives> <adverbs> <names> <output>\n";
}
std::vector<std::string> words_in(const std::string& filename)
{
std::ifstream input_stream(filename);
std::string word;
std::vector<std::string> words;
while (std::getline(input_stream, word))
{
words.push_back(word);
}
return words;
}
class Words
{
public:
Words(const std::string& filename, std::string var_name) : var_name{std::move(var_name)}, words{words_in(filename)}
{
}
void print_to(std::ostream& out)
{
out << "const char* " << var_name << "[] =\n{\n";
for (auto const& w: words)
{
out << " \"" << w << "\",\n";
}
out << "};\n\n";
}
private:
std::string var_name;
std::vector<std::string> words;
};
}
int main(int argc, char* argv[])
try
{
if (argc != 5)
{
usage(argv);
return EXIT_FAILURE;
}
Words adjectives{argv[1], "adjectives"};
Words adverbs{argv[2], "adverbs"};
Words names{argv[3], "names"};
std::ofstream out(argv[4]);
out << "//Auto Generated, any edits will be lost\n\n";
out << "namespace multipass\n{\n";
out << "namespace petname\n{\n";
adjectives.print_to(out);
adverbs.print_to(out);
names.print_to(out);
out << "}\n}";
return EXIT_SUCCESS;
}
catch(const std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
}
| 2,280
|
C++
|
.cpp
| 85
| 23.035294
| 119
| 0.632616
|
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,766
|
daemon_config.cpp
|
canonical_multipass/src/daemon/daemon_config.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_config.h"
#include "custom_image_host.h"
#include "ubuntu_image_host.h"
#include <multipass/client_cert_store.h>
#include <multipass/constants.h>
#include <multipass/default_vm_blueprint_provider.h>
#include <multipass/logging/log.h>
#include <multipass/logging/standard_logger.h>
#include <multipass/name_generator.h>
#include <multipass/platform.h>
#include <multipass/ssh/openssh_key_provider.h>
#include <multipass/ssl_cert_provider.h>
#include <multipass/standard_paths.h>
#include <multipass/utils.h>
#include <QString>
#include <QSysInfo>
#include <QUrl>
#include <chrono>
#include <memory>
#include <optional>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto manifest_ttl = std::chrono::minutes{5};
std::string server_name_from(const std::string& server_address)
{
auto tokens = mp::utils::split(server_address, ":");
const auto server_name = tokens[0];
if (server_name == "unix")
return "localhost";
return server_name;
}
std::unique_ptr<QNetworkProxy> discover_http_proxy()
{
std::unique_ptr<QNetworkProxy> proxy_ptr{nullptr};
QString http_proxy{qgetenv("http_proxy")};
if (http_proxy.isEmpty())
{
// Some OS's are case sensitive
http_proxy = qgetenv("HTTP_PROXY");
}
if (!http_proxy.isEmpty())
{
if (!http_proxy.contains("://"))
{
http_proxy.prepend("http://");
}
QUrl proxy_url{http_proxy};
const auto host = proxy_url.host();
const auto port = proxy_url.port();
auto network_proxy = QNetworkProxy(QNetworkProxy::HttpProxy, host, static_cast<quint16>(port),
proxy_url.userName(), proxy_url.password());
QNetworkProxy::setApplicationProxy(network_proxy);
proxy_ptr = std::make_unique<QNetworkProxy>(network_proxy);
}
return proxy_ptr;
}
} // namespace
mp::DaemonConfig::~DaemonConfig()
{
mpl::set_logger(nullptr);
}
std::unique_ptr<const mp::DaemonConfig> mp::DaemonConfigBuilder::build()
{
// Install logger as early as possible
if (logger == nullptr)
logger = platform::make_logger(verbosity_level);
// Fallback when platform does not have a logger
if (logger == nullptr)
logger = std::make_unique<mpl::StandardLogger>(verbosity_level);
auto multiplexing_logger = std::make_shared<mpl::MultiplexingLogger>(std::move(logger));
mpl::set_logger(multiplexing_logger);
auto storage_path = MP_PLATFORM.multipass_storage_location();
if (!storage_path.isEmpty())
MP_UTILS.make_dir(storage_path, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
if (cache_directory.isEmpty())
{
if (!storage_path.isEmpty())
cache_directory = MP_UTILS.make_dir(storage_path, "cache");
else
cache_directory = MP_STDPATHS.writableLocation(StandardPaths::CacheLocation);
}
if (data_directory.isEmpty())
{
if (!storage_path.isEmpty())
data_directory = MP_UTILS.make_dir(storage_path, "data");
else
data_directory = MP_STDPATHS.writableLocation(StandardPaths::AppDataLocation);
}
if (url_downloader == nullptr)
url_downloader = std::make_unique<URLDownloader>(cache_directory, std::chrono::seconds{10});
if (factory == nullptr)
factory = platform::vm_backend(data_directory);
if (update_prompt == nullptr)
update_prompt = platform::make_update_prompt();
if (image_hosts.empty())
{
image_hosts.push_back(
std::make_unique<mp::CustomVMImageHost>(QSysInfo::currentCpuArchitecture(), url_downloader.get()));
image_hosts.push_back(std::make_unique<mp::UbuntuVMImageHost>(
std::vector<std::pair<std::string, UbuntuVMImageRemote>>{
{mp::release_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "releases/",
std::make_optional<QString>(mp::mirror_key)}},
{mp::daily_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "daily/",
std::make_optional<QString>(mp::mirror_key)}},
{mp::snapcraft_remote, UbuntuVMImageRemote{"https://cloud-images.ubuntu.com/", "buildd/daily/",
std::make_optional<QString>(mp::mirror_key)}},
{mp::appliance_remote, UbuntuVMImageRemote{"https://cdimage.ubuntu.com/", "ubuntu-core/appliances/"}}},
url_downloader.get()));
}
if (vault == nullptr)
{
std::vector<VMImageHost*> hosts;
for (const auto& image : image_hosts)
{
hosts.push_back(image.get());
}
vault = factory->create_image_vault(
hosts, url_downloader.get(), MP_UTILS.make_dir(cache_directory, factory->get_backend_directory_name()),
mp::utils::backend_directory_path(data_directory, factory->get_backend_directory_name()), days_to_expire);
}
if (name_generator == nullptr)
name_generator = mp::make_default_name_generator();
if (server_address.empty())
server_address = platform::default_server_address();
if (ssh_key_provider == nullptr)
ssh_key_provider = std::make_unique<OpenSSHKeyProvider>(data_directory);
if (cert_provider == nullptr)
cert_provider = std::make_unique<mp::SSLCertProvider>(MP_UTILS.make_dir(data_directory, "certificates"),
server_name_from(server_address));
if (client_cert_store == nullptr)
client_cert_store = std::make_unique<mp::ClientCertStore>(data_directory);
if (ssh_username.empty())
ssh_username = "ubuntu";
if (network_proxy == nullptr)
network_proxy = discover_http_proxy();
if (blueprint_provider == nullptr)
{
auto blueprint_provider_url = MP_PLATFORM.get_blueprints_url_override();
if (!blueprint_provider_url.isEmpty())
blueprint_provider = std::make_unique<DefaultVMBlueprintProvider>(
QUrl(blueprint_provider_url), url_downloader.get(), cache_directory, manifest_ttl);
else
blueprint_provider =
std::make_unique<DefaultVMBlueprintProvider>(url_downloader.get(), cache_directory, manifest_ttl);
}
return std::unique_ptr<const DaemonConfig>(new DaemonConfig{
std::move(url_downloader), std::move(factory), std::move(image_hosts), std::move(vault),
std::move(name_generator), std::move(ssh_key_provider), std::move(cert_provider), std::move(client_cert_store),
std::move(update_prompt), multiplexing_logger, std::move(network_proxy), std::move(blueprint_provider),
cache_directory, data_directory, server_address, ssh_username, image_refresh_timer});
}
| 7,580
|
C++
|
.cpp
| 169
| 37.301775
| 119
| 0.656237
|
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,767
|
daemon.cpp
|
canonical_multipass/src/daemon/daemon.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.h"
#include "base_cloud_init_config.h"
#include "instance_settings_handler.h"
#include "runtime_instance_info_helper.h"
#include "snapshot_settings_handler.h"
#include <multipass/alias_definition.h>
#include <multipass/cloud_init_iso.h>
#include <multipass/constants.h>
#include <multipass/exceptions/blueprint_exceptions.h>
#include <multipass/exceptions/clone_exceptions.h>
#include <multipass/exceptions/create_image_exception.h>
#include <multipass/exceptions/exitless_sshprocess_exceptions.h>
#include <multipass/exceptions/image_vault_exceptions.h>
#include <multipass/exceptions/invalid_memory_size_exception.h>
#include <multipass/exceptions/not_implemented_on_this_backend_exception.h>
#include <multipass/exceptions/snapshot_exceptions.h>
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/exceptions/start_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/ip_address.h>
#include <multipass/json_utils.h>
#include <multipass/logging/client_logger.h>
#include <multipass/logging/log.h>
#include <multipass/name_generator.h>
#include <multipass/network_interface.h>
#include <multipass/platform.h>
#include <multipass/query.h>
#include <multipass/settings/bool_setting_spec.h>
#include <multipass/settings/settings.h>
#include <multipass/snapshot.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/sshfs_mount/sshfs_mount_handler.h>
#include <multipass/top_catch_all.h>
#include <multipass/version.h>
#include <multipass/virtual_machine.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/virtual_machine_factory.h>
#include <multipass/vm_image.h>
#include <multipass/vm_image_host.h>
#include <multipass/vm_image_vault.h>
#include <multipass/yaml_node_utils.h>
#include <scope_guard.hpp>
#include <yaml-cpp/yaml.h>
#include <QDir>
#include <QEventLoop>
#include <QFutureSynchronizer>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonParseError>
#include <QStorageInfo>
#include <QString>
#include <QSysInfo>
#include <QtConcurrent/QtConcurrent>
#include <algorithm>
#include <cassert>
#include <functional>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpu = multipass::utils;
namespace
{
using namespace std::chrono_literals;
using error_string = std::string;
constexpr auto category = "daemon";
constexpr auto instance_db_name = "multipassd-vm-instances.json";
constexpr auto reboot_cmd = "sudo reboot";
constexpr auto stop_ssh_cmd = "sudo systemctl stop ssh";
const std::string sshfs_error_template = "Error enabling mount support in '{}'"
"\n\nPlease install the 'multipass-sshfs' snap manually inside the instance.";
const std::string invalid_network_template = "Invalid network '{}' set as bridged interface, use `multipass set "
"{}=<name>` to correct. See `multipass networks` for valid names.";
// Images which cannot be bridged with --network.
const std::unordered_set<std::string> no_bridging_release = { // images to check from release and daily remotes
"10.04", "lucid", "11.10", "oneiric", "12.04", "precise", "12.10", "quantal", "13.04",
"raring", "13.10", "saucy", "14.04", "trusty", "14.10", "utopic", "15.04", "vivid",
"15.10", "wily", "16.04", "xenial", "16.10", "yakkety", "17.04", "zesty"};
const std::unordered_set<std::string> no_bridging_remote = {}; // images with other remote specified
const std::unordered_set<std::string> no_bridging_remoteless = {"core", "core16"}; // images which do not use remote
mp::Query query_from(const mp::LaunchRequest* request, const std::string& name)
{
if (!request->remote_name().empty() && request->image().empty())
throw std::runtime_error("Must specify an image when specifying a remote");
std::string image = request->image().empty() ? "default" : request->image();
// TODO: persistence should be specified by the rpc as well
mp::Query::Type query_type{mp::Query::Type::Alias};
if (QString::fromStdString(image).startsWith("file"))
query_type = mp::Query::Type::LocalFile;
else if (QString::fromStdString(image).startsWith("http"))
query_type = mp::Query::Type::HttpDownload;
return {name, image, false, request->remote_name(), query_type, true};
}
auto make_cloud_init_vendor_config(const mp::SSHKeyProvider& key_provider, const std::string& username,
const std::string& backend_version_string, const mp::CreateRequest* request)
{
auto ssh_key_line = fmt::format("ssh-rsa {} {}@localhost", key_provider.public_key_as_base64(), username);
QString pollinate_alias = QString::fromStdString(request->image());
if (pollinate_alias.isEmpty())
{
pollinate_alias = "default";
}
else if (pollinate_alias.startsWith("http"))
{
pollinate_alias = "http";
}
else if (pollinate_alias.startsWith("file"))
{
pollinate_alias = "file";
}
auto remote_name = request->remote_name();
auto config = YAML::Load(mp::base_cloud_init_config);
config["ssh_authorized_keys"].push_back(ssh_key_line);
config["timezone"] = request->time_zone();
config["system_info"]["default_user"]["name"] = username;
config["packages"].push_back("pollinate");
auto pollinate_user_agent_string =
fmt::format("multipass/version/{} # written by Multipass\n", multipass::version_string);
pollinate_user_agent_string += fmt::format("multipass/driver/{} # written by Multipass\n", backend_version_string);
pollinate_user_agent_string +=
fmt::format("multipass/host/{} # written by Multipass\n", multipass::platform::host_version());
pollinate_user_agent_string += fmt::format("multipass/alias/{}{} # written by Multipass\n",
!remote_name.empty() ? remote_name + ":" : "", pollinate_alias);
YAML::Node pollinate_user_agent_node;
pollinate_user_agent_node["path"] = "/etc/pollinate/add-user-agent";
pollinate_user_agent_node["content"] = pollinate_user_agent_string;
config["write_files"].push_back(pollinate_user_agent_node);
return config;
}
void prepare_user_data(YAML::Node& user_data_config, YAML::Node& vendor_config)
{
auto users = user_data_config["users"];
if (users.IsSequence())
users.push_back("default");
auto keys = user_data_config["ssh_authorized_keys"];
if (keys.IsSequence())
keys.push_back(vendor_config["ssh_authorized_keys"][0]);
auto packages = user_data_config["packages"];
if (packages.IsSequence())
{
for (const auto& package : vendor_config["packages"])
{
packages.push_back(package);
}
}
}
template <typename T>
auto name_from(const std::string& requested_name, const std::string& blueprint_name, mp::NameGenerator& name_gen,
const T& currently_used_names)
{
if (!requested_name.empty())
{
return requested_name;
}
else if (!blueprint_name.empty())
{
return blueprint_name;
}
else
{
auto name = name_gen.make_name();
constexpr int num_retries = 100;
for (int i = 0; i < num_retries; i++)
{
if (currently_used_names.find(name) != currently_used_names.end())
continue;
return name;
}
throw std::runtime_error("unable to generate a unique name");
}
}
std::unordered_map<std::string, mp::VMSpecs> load_db(const mp::Path& data_path, const mp::Path& cache_path)
{
QDir data_dir{data_path};
QDir cache_dir{cache_path};
QFile db_file{data_dir.filePath(instance_db_name)};
if (!db_file.open(QIODevice::ReadOnly))
{
// Try to open the old location
db_file.setFileName(cache_dir.filePath(instance_db_name));
if (!db_file.open(QIODevice::ReadOnly))
return {};
}
QJsonParseError parse_error;
auto doc = QJsonDocument::fromJson(db_file.readAll(), &parse_error);
if (doc.isNull())
return {};
auto records = doc.object();
if (records.isEmpty())
return {};
std::unordered_map<std::string, mp::VMSpecs> reconstructed_records;
for (auto it = records.constBegin(); it != records.constEnd(); ++it)
{
auto key = it.key().toStdString();
auto record = it.value().toObject();
if (record.isEmpty())
return {};
auto num_cores = record["num_cores"].toInt();
auto mem_size = record["mem_size"].toString().toStdString();
auto disk_space = record["disk_space"].toString().toStdString();
auto ssh_username = record["ssh_username"].toString().toStdString();
auto state = record["state"].toInt();
auto deleted = record["deleted"].toBool();
auto metadata = record["metadata"].toObject();
auto clone_count = record["clone_count"].toInt();
if (!num_cores && !deleted && ssh_username.empty() && metadata.isEmpty() &&
!mp::MemorySize{mem_size}.in_bytes() && !mp::MemorySize{disk_space}.in_bytes())
{
mpl::log(mpl::Level::warning, category, fmt::format("Ignoring ghost instance in database: {}", key));
continue;
}
if (ssh_username.empty())
ssh_username = "ubuntu";
// Read the default network interface, constructed from the "mac_addr" field.
auto default_mac_address = record["mac_addr"].toString().toStdString();
if (!mpu::valid_mac_address(default_mac_address))
{
throw std::runtime_error(fmt::format("Invalid MAC address {}", default_mac_address));
}
std::unordered_map<std::string, mp::VMMount> mounts;
for (QJsonValueRef entry : record["mounts"].toArray())
{
const auto& json = entry.toObject();
mounts[json["target_path"].toString().toStdString()] = mp::VMMount{json};
}
reconstructed_records[key] = {
num_cores,
mp::MemorySize{mem_size.empty() ? mp::default_memory_size : mem_size},
mp::MemorySize{disk_space.empty() ? mp::default_disk_size : disk_space},
default_mac_address,
MP_JSONUTILS.read_extra_interfaces(record).value_or(std::vector<mp::NetworkInterface>{}),
ssh_username,
static_cast<mp::VirtualMachine::State>(state),
mounts,
deleted,
metadata,
clone_count};
}
return reconstructed_records;
}
QJsonObject vm_spec_to_json(const mp::VMSpecs& specs)
{
QJsonObject json;
json.insert("num_cores", specs.num_cores);
json.insert("mem_size", QString::number(specs.mem_size.in_bytes()));
json.insert("disk_space", QString::number(specs.disk_space.in_bytes()));
json.insert("ssh_username", QString::fromStdString(specs.ssh_username));
json.insert("state", static_cast<int>(specs.state));
json.insert("deleted", specs.deleted);
json.insert("metadata", specs.metadata);
// Write the networking information. Write first a field "mac_addr" containing the MAC address of the
// default network interface. Then, write all the information about the rest of the interfaces.
json.insert("mac_addr", QString::fromStdString(specs.default_mac_address));
json.insert("extra_interfaces", MP_JSONUTILS.extra_interfaces_to_json_array(specs.extra_interfaces));
QJsonArray json_mounts;
for (const auto& mount : specs.mounts)
{
auto entry = mount.second.serialize();
entry.insert("target_path", QString::fromStdString(mount.first));
json_mounts.append(entry);
}
json.insert("mounts", json_mounts);
json.insert("clone_count", specs.clone_count);
return json;
}
std::string generate_next_clone_name(int clone_count, const std::string& source_name)
{
return fmt::format("{}-clone{}", source_name, clone_count + 1);
}
auto fetch_image_for(const std::string& name, mp::VirtualMachineFactory& factory, mp::VMImageVault& vault)
{
auto stub_prepare = [](const mp::VMImage&) -> mp::VMImage { return {}; };
auto stub_progress = [](int download_type, int progress) { return true; };
mp::Query query{name, "", false, "", mp::Query::Type::Alias, false};
return vault.fetch_image(factory.fetch_type(),
query,
stub_prepare,
stub_progress,
false,
std::nullopt,
factory.get_instance_directory(name));
}
auto try_mem_size(const std::string& val) -> std::optional<mp::MemorySize>
{
try
{
return mp::MemorySize{val};
}
catch (mp::InvalidMemorySizeException& /*unused*/)
{
return std::nullopt;
}
}
std::string get_bridged_interface_name()
{
const auto bridged_id = MP_SETTINGS.get(mp::bridged_interface_key);
if (bridged_id == "")
{
throw std::runtime_error(fmt::format("You have to `multipass set {}=<name>` to use the \"bridged\" shortcut.",
mp::bridged_interface_key));
}
return bridged_id.toStdString();
}
bool is_bridged_impl(const mp::VMSpecs& specs,
const std::vector<mp::NetworkInterfaceInfo>& host_nets,
const std::string& preferred_net)
{
const auto& matching_bridge = mpu::find_bridge_with(host_nets, preferred_net, MP_PLATFORM.bridge_nomenclature());
return std::any_of(specs.extra_interfaces.cbegin(),
specs.extra_interfaces.cend(),
[&preferred_net, &matching_bridge](const auto& network) -> bool {
return network.id == preferred_net || (matching_bridge && network.id == matching_bridge->id);
});
}
std::vector<mp::NetworkInterface> validate_extra_interfaces(const mp::LaunchRequest* request,
const mp::VirtualMachineFactory& factory,
std::vector<std::string>& nets_need_bridging,
mp::LaunchError& option_errors)
{
std::vector<mp::NetworkInterface> interfaces;
std::optional<std::vector<mp::NetworkInterfaceInfo>> factory_networks = std::nullopt;
bool dont_allow_auto = false;
std::string specified_image;
auto remote = request->remote_name();
auto image = request->image();
if (request->remote_name().empty())
{
specified_image = image;
dont_allow_auto = (no_bridging_remoteless.find(image) != no_bridging_remoteless.end()) ||
(no_bridging_release.find(image) != no_bridging_release.end());
}
else
{
specified_image = remote + ":" + image;
dont_allow_auto = no_bridging_remote.find(specified_image) != no_bridging_remote.end();
if (!dont_allow_auto && (remote == "release" || remote == "daily"))
dont_allow_auto = no_bridging_release.find(image) != no_bridging_release.end();
}
for (const auto& net : request->network_options())
{
auto net_id = net.id();
if (net_id == mp::bridged_network_name)
{
net_id = get_bridged_interface_name();
}
if (!factory_networks)
{
try
{
factory_networks = factory.networks();
}
catch (const mp::NotImplementedOnThisBackendException&)
{
throw mp::NotImplementedOnThisBackendException("networks");
}
}
if (dont_allow_auto && net.mode() == multipass::LaunchRequest_NetworkOptions_Mode_AUTO)
{
throw std::runtime_error(fmt::format(
"Automatic network configuration not available for {}. Consider using manual mode.", specified_image));
}
// Check that the id the user specified is valid.
auto pred = [net_id](const mp::NetworkInterfaceInfo& info) { return info.id == net_id; };
auto host_net_it = std::find_if(factory_networks->cbegin(), factory_networks->cend(), pred);
if (host_net_it == factory_networks->cend())
{
if (net.id() == mp::bridged_network_name)
throw std::runtime_error(fmt::format(invalid_network_template, net_id, mp::bridged_interface_key));
mpl::log(mpl::Level::warning, category, fmt::format("Invalid network name \"{}\"", net_id));
option_errors.add_error_codes(mp::LaunchError::INVALID_NETWORK);
}
else if (host_net_it->needs_authorization)
nets_need_bridging.push_back(host_net_it->id);
// In case the user specified a MAC address, check it is valid.
if (const auto& mac = QString::fromStdString(net.mac_address()).toLower().toStdString();
mac.empty() || mpu::valid_mac_address(mac))
interfaces.push_back(
mp::NetworkInterface{net_id, mac, net.mode() != multipass::LaunchRequest_NetworkOptions_Mode_MANUAL});
else
{
mpl::log(mpl::Level::warning, category, fmt::format("Invalid MAC address \"{}\"", mac));
option_errors.add_error_codes(mp::LaunchError::INVALID_NETWORK);
}
}
return interfaces;
}
void validate_image(const mp::LaunchRequest* request, const mp::VMImageVault& vault,
mp::VMBlueprintProvider& blueprint_provider)
{
// TODO: Refactor this in such a way that we can use info returned here instead of ignoring it to avoid calls
// later that accomplish the same thing.
try
{
if (!blueprint_provider.info_for(request->image()))
{
auto image_query = query_from(request, "");
if (image_query.query_type == mp::Query::Type::Alias && vault.all_info_for(image_query).empty())
throw mp::ImageNotFoundException(request->image(), request->remote_name());
}
}
catch (const mp::IncompatibleBlueprintException&)
{
throw std::runtime_error(
fmt::format("The \"{}\" Blueprint is not compatible with this host.", request->image()));
}
}
auto validate_create_arguments(const mp::LaunchRequest* request, const mp::DaemonConfig* config)
{
assert(config && config->factory && config->blueprint_provider && config->vault && "null ptr somewhere...");
validate_image(request, *config->vault, *config->blueprint_provider);
static const auto min_mem = try_mem_size(mp::min_memory_size);
static const auto min_disk = try_mem_size(mp::min_disk_size);
assert(min_mem && min_disk);
auto mem_size_str = request->mem_size();
auto disk_space_str = request->disk_space();
auto instance_name = request->instance_name();
auto option_errors = mp::LaunchError{};
const auto opt_mem_size = try_mem_size(mem_size_str.empty() ? mp::default_memory_size : mem_size_str);
mp::MemorySize mem_size{};
if (opt_mem_size && *opt_mem_size >= min_mem)
mem_size = *opt_mem_size;
else
option_errors.add_error_codes(mp::LaunchError::INVALID_MEM_SIZE);
// If the user did not specify a disk size, then std::nullopt be passed down. Otherwise, the specified size will be
// checked.
std::optional<mp::MemorySize> disk_space{}; // std::nullopt by default.
if (!disk_space_str.empty())
{
auto opt_disk_space = try_mem_size(disk_space_str);
if (opt_disk_space && *opt_disk_space >= min_disk)
{
disk_space = opt_disk_space;
}
else
{
option_errors.add_error_codes(mp::LaunchError::INVALID_DISK_SIZE);
}
}
if (!instance_name.empty() && !mp::utils::valid_hostname(instance_name))
option_errors.add_error_codes(mp::LaunchError::INVALID_HOSTNAME);
std::vector<std::string> nets_need_bridging;
auto extra_interfaces = validate_extra_interfaces(request, *config->factory, nets_need_bridging, option_errors);
struct CheckedArguments
{
mp::MemorySize mem_size;
std::optional<mp::MemorySize> disk_space;
std::string instance_name;
std::vector<mp::NetworkInterface> extra_interfaces;
std::vector<std::string> nets_need_bridging;
mp::LaunchError option_errors;
} ret{std::move(mem_size), std::move(disk_space), std::move(instance_name),
std::move(extra_interfaces), std::move(nets_need_bridging), std::move(option_errors)};
return ret;
}
auto connect_rpc(mp::DaemonRpc& rpc, mp::Daemon& daemon)
{
QObject::connect(&rpc, &mp::DaemonRpc::on_create, &daemon, &mp::Daemon::create);
QObject::connect(&rpc, &mp::DaemonRpc::on_launch, &daemon, &mp::Daemon::launch);
QObject::connect(&rpc, &mp::DaemonRpc::on_purge, &daemon, &mp::Daemon::purge);
QObject::connect(&rpc, &mp::DaemonRpc::on_find, &daemon, &mp::Daemon::find);
QObject::connect(&rpc, &mp::DaemonRpc::on_info, &daemon, &mp::Daemon::info);
QObject::connect(&rpc, &mp::DaemonRpc::on_list, &daemon, &mp::Daemon::list);
QObject::connect(&rpc, &mp::DaemonRpc::on_clone, &daemon, &mp::Daemon::clone);
QObject::connect(&rpc, &mp::DaemonRpc::on_networks, &daemon, &mp::Daemon::networks);
QObject::connect(&rpc, &mp::DaemonRpc::on_mount, &daemon, &mp::Daemon::mount);
QObject::connect(&rpc, &mp::DaemonRpc::on_recover, &daemon, &mp::Daemon::recover);
QObject::connect(&rpc, &mp::DaemonRpc::on_ssh_info, &daemon, &mp::Daemon::ssh_info);
QObject::connect(&rpc, &mp::DaemonRpc::on_start, &daemon, &mp::Daemon::start);
QObject::connect(&rpc, &mp::DaemonRpc::on_stop, &daemon, &mp::Daemon::stop);
QObject::connect(&rpc, &mp::DaemonRpc::on_suspend, &daemon, &mp::Daemon::suspend);
QObject::connect(&rpc, &mp::DaemonRpc::on_restart, &daemon, &mp::Daemon::restart);
QObject::connect(&rpc, &mp::DaemonRpc::on_delete, &daemon, &mp::Daemon::delet);
QObject::connect(&rpc, &mp::DaemonRpc::on_umount, &daemon, &mp::Daemon::umount);
QObject::connect(&rpc, &mp::DaemonRpc::on_version, &daemon, &mp::Daemon::version);
QObject::connect(&rpc, &mp::DaemonRpc::on_get, &daemon, &mp::Daemon::get);
QObject::connect(&rpc, &mp::DaemonRpc::on_set, &daemon, &mp::Daemon::set);
QObject::connect(&rpc, &mp::DaemonRpc::on_keys, &daemon, &mp::Daemon::keys);
QObject::connect(&rpc, &mp::DaemonRpc::on_authenticate, &daemon, &mp::Daemon::authenticate);
QObject::connect(&rpc, &mp::DaemonRpc::on_snapshot, &daemon, &mp::Daemon::snapshot);
QObject::connect(&rpc, &mp::DaemonRpc::on_restore, &daemon, &mp::Daemon::restore);
QObject::connect(&rpc, &mp::DaemonRpc::on_daemon_info, &daemon, &mp::Daemon::daemon_info);
}
enum class InstanceGroup
{
None,
Operative,
Deleted,
All
};
// Hack to import typedef here, without making it part of the Daemon's public interface
// clang-format off
struct TapDaemon : private mp::Daemon { using Daemon::InstanceTable; }; // clang-format on
using InstanceTable = TapDaemon::InstanceTable;
using InstanceTrail = std::variant<InstanceTable::iterator, // operative instances
InstanceTable::iterator, // deleted instances
std::reference_wrapper<const std::string>>; // missing instances
// careful to keep the original `name` around while the returned trail is in use!
InstanceTrail find_instance(InstanceTable& operative_instances, InstanceTable& deleted_instances,
const std::string& name)
{
if (auto it = operative_instances.find(name); it != std::end(operative_instances))
return InstanceTrail{std::in_place_index<0>, it};
else if (it = deleted_instances.find(name); it != std::end(deleted_instances))
return InstanceTrail{std::in_place_index<1>, it};
else
return {name};
}
using LinearInstanceSelection = std::vector<InstanceTable::iterator>;
using MissingInstanceList = std::vector<std::reference_wrapper<const std::string>>;
struct InstanceSelectionReport
{
LinearInstanceSelection operative_selection;
LinearInstanceSelection deleted_selection;
MissingInstanceList missing_instances;
};
LinearInstanceSelection select_all(InstanceTable& instances)
{
LinearInstanceSelection selection;
selection.reserve(instances.size());
for (auto it = instances.begin(); it != instances.end(); ++it)
selection.push_back(it);
return selection;
}
// careful to keep the original `name` around while the provided `selection` is in use!
void rank_instance(const std::string& name, const InstanceTrail& trail, InstanceSelectionReport& selection)
{
switch (trail.index())
{
case 0:
selection.operative_selection.push_back(std::get<0>(trail));
break;
case 1:
selection.deleted_selection.push_back(std::get<1>(trail));
break;
case 2:
selection.missing_instances.push_back(std::get<2>(trail));
break;
}
}
// careful to keep the original `names` around while the returned selection is in use!
template <typename InstanceNames>
InstanceSelectionReport select_instances(InstanceTable& operative_instances, InstanceTable& deleted_instances,
const InstanceNames& names, InstanceGroup no_name_means)
{
InstanceSelectionReport ret{};
if (names.empty() && no_name_means != InstanceGroup::None)
{
if (no_name_means == InstanceGroup::Operative || no_name_means == InstanceGroup::All)
ret.operative_selection = select_all(operative_instances);
if (no_name_means == InstanceGroup::Deleted || no_name_means == InstanceGroup::All)
ret.deleted_selection = select_all(deleted_instances);
}
else
{
std::unordered_set<std::string> seen_instances;
for (const auto& name : names)
{
using T = std::decay_t<decltype(name)>;
const std::string* vm_name;
if constexpr (std::is_same_v<T, std::string>)
vm_name = &name;
else
vm_name = &name.instance_name();
if (seen_instances.insert(*vm_name).second)
{
auto trail = find_instance(operative_instances, deleted_instances, *vm_name);
rank_instance(*vm_name, trail, ret);
}
}
}
return ret;
}
struct SelectionReaction
{
struct ReactionComponent
{
grpc::StatusCode status_code;
std::optional<std::string> message_template = std::nullopt;
} operative_reaction, deleted_reaction, missing_reaction;
};
const SelectionReaction require_operative_instances_reaction{
{grpc::StatusCode::OK},
{grpc::StatusCode::INVALID_ARGUMENT, "instance \"{}\" is deleted"},
{grpc::StatusCode::NOT_FOUND, "instance \"{}\" does not exist"}};
const SelectionReaction require_existing_instances_reaction{
{grpc::StatusCode::OK}, // hands off clang-format
{grpc::StatusCode::OK},
{grpc::StatusCode::NOT_FOUND, "instance \"{}\" does not exist"}};
const SelectionReaction require_missing_instances_reaction{
{grpc::StatusCode::INVALID_ARGUMENT, "instance \"{}\" already exists"},
{grpc::StatusCode::INVALID_ARGUMENT, "instance \"{}\" already exists"},
{grpc::StatusCode::OK}};
template <typename InstanceElem> // call only with InstanceTable::iterator or std::reference_wrapper<std::string>
const std::string& get_instance_name(InstanceElem instance_element)
{
using T = std::decay_t<decltype(instance_element)>;
if constexpr (std::is_same_v<T, LinearInstanceSelection::value_type>)
return instance_element->first;
else
{
static_assert(std::is_same_v<T, MissingInstanceList::value_type>);
return instance_element.get();
}
}
template <typename... Ts>
auto add_fmt_to(fmt::memory_buffer& buffer, Ts&&... fmt_params) -> std::back_insert_iterator<fmt::memory_buffer>
{
if (buffer.size())
buffer.push_back('\n');
return fmt::format_to(std::back_inserter(buffer), std::forward<Ts>(fmt_params)...);
}
using SelectionComponent = std::variant<LinearInstanceSelection, MissingInstanceList>;
grpc::StatusCode react_to_component(const SelectionComponent& selection_component,
const SelectionReaction::ReactionComponent& reaction_component,
fmt::memory_buffer& errors)
{
auto visitor = [&reaction_component, &errors](const auto& component) {
auto status_code = grpc::StatusCode::OK;
if (!component.empty())
{
const auto& msg_opt = reaction_component.message_template;
status_code = reaction_component.status_code;
if (msg_opt)
{
const auto& msg = *msg_opt;
for (const auto& instance_element : component) // can be an iterator into an InstanceTable or a name
{
const auto& instance_name = get_instance_name(instance_element);
if (status_code)
add_fmt_to(errors, msg, instance_name);
else
mpl::log(mpl::Level::debug, category, fmt::format(msg, instance_name));
}
}
}
return status_code;
};
return std::visit(visitor, selection_component);
}
auto grpc_status_for_mount_error(const std::string& instance_name)
{
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, fmt::format(sshfs_error_template, instance_name));
}
auto grpc_status_for(fmt::memory_buffer& errors, grpc::StatusCode status_code = grpc::StatusCode::OK)
{
if (errors.size() && !status_code)
status_code = grpc::StatusCode::INVALID_ARGUMENT;
return status_code ? grpc::Status(status_code,
fmt::format("The following errors occurred:\n{}", fmt::to_string(errors)), "")
: grpc::Status::OK;
}
// Only the last bad status code is used
grpc::Status grpc_status_for_selection(const InstanceSelectionReport& selection, const SelectionReaction& reaction)
{
fmt::memory_buffer errors;
auto status_code = grpc::StatusCode::OK;
if (auto code = react_to_component(selection.operative_selection, reaction.operative_reaction, errors); code)
status_code = code;
if (auto code = react_to_component(selection.deleted_selection, reaction.deleted_reaction, errors); code)
status_code = code;
if (auto code = react_to_component(selection.missing_instances, reaction.missing_reaction, errors); code)
status_code = code;
return grpc_status_for(errors, status_code);
}
grpc::Status grpc_status_for_instance_trail(const InstanceTrail& trail, const SelectionReaction& reaction)
{
const std::string* instance_name = nullptr;
const SelectionReaction::ReactionComponent* relevant_reaction_component = nullptr;
switch (trail.index())
{
case 0:
instance_name = &std::get<0>(trail)->first;
relevant_reaction_component = &reaction.operative_reaction;
break;
case 1:
instance_name = &std::get<1>(trail)->first;
relevant_reaction_component = &reaction.deleted_reaction;
break;
case 2:
instance_name = &std::get<2>(trail).get();
relevant_reaction_component = &reaction.missing_reaction;
break;
default:
assert(trail.index() && false && "shouldn't be here");
}
assert(relevant_reaction_component && instance_name);
const auto& status_code = relevant_reaction_component->status_code;
if (const auto& msg_opt = relevant_reaction_component->message_template; msg_opt)
{
const auto& msg = fmt::format(*msg_opt, *instance_name);
if (status_code)
return grpc::Status{status_code, msg, ""};
mpl::log(mpl::Level::debug, category, msg);
}
return grpc::Status{status_code, "", ""};
}
std::pair<InstanceTrail, grpc::Status> find_instance_and_react(InstanceTable& operative_instances,
InstanceTable& deleted_instances,
const std::string& name,
const SelectionReaction& reaction)
{
auto trail = find_instance(operative_instances, deleted_instances, name);
auto status = grpc_status_for_instance_trail(trail, reaction);
return {std::move(trail), status};
}
// careful to keep the original `names` around while the returned selection is in use!
template <typename InstanceNames>
std::pair<InstanceSelectionReport, grpc::Status>
select_instances_and_react(InstanceTable& operative_instances, InstanceTable& deleted_instances,
const InstanceNames& names, InstanceGroup no_name_means, const SelectionReaction& reaction)
{
auto instance_selection = select_instances(operative_instances, deleted_instances, names, no_name_means);
return {instance_selection, grpc_status_for_selection(instance_selection, reaction)};
}
std::string make_start_error_details(const InstanceSelectionReport& instance_selection)
{
mp::StartError start_error;
auto* errors = start_error.mutable_instance_errors();
for (const auto& vm_it : instance_selection.deleted_selection)
errors->insert({vm_it->first, mp::StartError::INSTANCE_DELETED});
for (const auto& name : instance_selection.missing_instances)
errors->insert({name, mp::StartError::DOES_NOT_EXIST});
return start_error.SerializeAsString();
}
using VMCommand = std::function<grpc::Status(mp::VirtualMachine&)>;
grpc::Status cmd_vms(const LinearInstanceSelection& tgts, const VMCommand& cmd)
{
// std::function involves some overhead, but it should be negligible here and
// it gives clear error messages on type mismatch (!= templated callable).
for (const auto& tgt : tgts)
{
auto vm_ptr = tgt->second;
assert(vm_ptr && "no nulls please");
if (auto st = cmd(*vm_ptr); !st.ok())
return st; // Fail early
}
return grpc::Status::OK;
}
std::vector<std::string> names_from(const LinearInstanceSelection& instances)
{
std::vector<std::string> ret;
ret.reserve(instances.size());
std::transform(std::cbegin(instances), std::cend(instances), std::back_inserter(ret),
[](const auto& item) { return item->first; });
return ret;
}
template <typename Instances>
auto instances_running(const Instances& instances)
{
for (const auto& instance : instances)
{
if (MP_UTILS.is_running(instance.second->current_state()))
return true;
}
return false;
}
grpc::Status stop_accepting_ssh_connections(mp::VirtualMachine& vm)
{
try
{
vm.ssh_exec(stop_ssh_cmd);
}
catch (const mp::SSHExecFailure& e)
{
return grpc::Status{grpc::StatusCode::FAILED_PRECONDITION,
fmt::format("Could not stop sshd. '{}' exited with code {}.", stop_ssh_cmd, e.exit_code()),
e.what()};
}
return grpc::Status::OK;
}
grpc::Status ssh_reboot(mp::VirtualMachine& vm)
{
// This allows us to later detect when the machine has finished restarting by waiting for SSH to be back up.
// Otherwise, there would be a race condition, and we would be unable to distinguish whether it had ever been down.
stop_accepting_ssh_connections(vm);
try
{
vm.ssh_exec(reboot_cmd);
}
catch (const mp::SSHExecFailure& e)
{
return grpc::Status{grpc::StatusCode::FAILED_PRECONDITION,
fmt::format("Reboot command exited with code {}", e.exit_code()),
e.what()};
}
catch (const mp::SSHProcessTimeoutException&)
{
// this is the expected path
}
return grpc::Status::OK;
}
mp::InstanceStatus::Status grpc_instance_status_for(const mp::VirtualMachine::State& state)
{
switch (state)
{
case mp::VirtualMachine::State::off:
case mp::VirtualMachine::State::stopped:
return mp::InstanceStatus::STOPPED;
case mp::VirtualMachine::State::starting:
return mp::InstanceStatus::STARTING;
case mp::VirtualMachine::State::restarting:
return mp::InstanceStatus::RESTARTING;
case mp::VirtualMachine::State::running:
return mp::InstanceStatus::RUNNING;
case mp::VirtualMachine::State::delayed_shutdown:
return mp::InstanceStatus::DELAYED_SHUTDOWN;
case mp::VirtualMachine::State::suspending:
return mp::InstanceStatus::SUSPENDING;
case mp::VirtualMachine::State::suspended:
return mp::InstanceStatus::SUSPENDED;
case mp::VirtualMachine::State::unknown:
default:
return mp::InstanceStatus::UNKNOWN;
}
}
// Computes the final size of an image, but also checks if the value given by the user is bigger than or equal than
// the size of the image.
mp::MemorySize compute_final_image_size(const mp::MemorySize image_size,
std::optional<mp::MemorySize> command_line_value, mp::Path data_directory)
{
mp::MemorySize disk_space{};
if (!command_line_value)
{
auto default_disk_size_as_struct = mp::MemorySize(mp::default_disk_size);
disk_space = image_size < default_disk_size_as_struct ? default_disk_size_as_struct : image_size;
}
else if (*command_line_value < image_size)
{
throw std::runtime_error(fmt::format("Requested disk ({} bytes) below minimum for this image ({} bytes)",
command_line_value->in_bytes(), image_size.in_bytes()));
}
else
{
disk_space = *command_line_value;
}
auto available_bytes = MP_UTILS.filesystem_bytes_available(data_directory);
if (available_bytes == -1)
{
throw std::runtime_error(fmt::format("Failed to determine information about the volume containing {}",
data_directory.toStdString()));
}
std::string available_bytes_str = QString::number(available_bytes).toStdString();
auto available_disk_space = mp::MemorySize(available_bytes_str + "B");
if (available_disk_space < image_size)
{
throw std::runtime_error(fmt::format("Available disk ({} bytes) below minimum for this image ({} bytes)",
available_disk_space.in_bytes(), image_size.in_bytes()));
}
if (available_disk_space < disk_space)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Reserving more disk space ({} bytes) than available ({} bytes)", disk_space.in_bytes(),
available_disk_space.in_bytes()));
}
return disk_space;
}
std::unordered_set<std::string> mac_set_from(const mp::VMSpecs& spec)
{
std::unordered_set<std::string> macs{};
macs.insert(spec.default_mac_address);
for (const auto& extra_iface : spec.extra_interfaces)
if (!extra_iface.mac_address.empty())
macs.insert(extra_iface.mac_address);
return macs;
}
// Merge the contents of t into s, iff the sets are disjoint (i.e. make s = sUt). Return whether s and t were disjoint.
bool merge_if_disjoint(std::unordered_set<std::string>& s, const std::unordered_set<std::string>& t)
{
if (any_of(cbegin(s), cend(s), [&t](const auto& mac) { return t.find(mac) != cend(t); }))
return false;
s.insert(cbegin(t), cend(t));
return true;
}
// Generate a MAC address which does not exist in the set s. Then add the address to s.
std::string generate_unused_mac_address(std::unordered_set<std::string>& s)
{
// TODO: Checking in our list of MAC addresses does not suffice to conclude the generated MAC is unique. We
// should also check in the ARP table.
static constexpr auto max_tries = 5;
for (auto i = 0; i < max_tries; ++i)
if (auto [it, success] = s.insert(mp::utils::generate_mac_address()); success)
return *it;
throw std::runtime_error{
fmt::format("Failed to generate an unique mac address after {} attempts. Number of mac addresses in use: {}",
max_tries, s.size())};
}
struct SnapshotPick
{
std::unordered_set<std::string> pick;
bool all_or_none;
};
using InstanceSnapshotPairs = google::protobuf::RepeatedPtrField<mp::InstanceSnapshotPair>;
using InstanceSnapshotsMap = std::unordered_map<std::string, SnapshotPick>;
InstanceSnapshotsMap map_snapshots_to_instances(const InstanceSnapshotPairs& instances_snapshots)
{
InstanceSnapshotsMap instance_snapshots_map;
for (const auto& it : instances_snapshots)
{
const auto& instance = it.instance_name();
auto& snapshot_pick = instance_snapshots_map[instance];
if (!it.has_snapshot_name())
snapshot_pick.all_or_none = true;
else
snapshot_pick.pick.insert(it.snapshot_name());
}
return instance_snapshots_map;
}
bool verify_snapshot_picks(const InstanceSelectionReport& report,
const std::unordered_map<std::string, SnapshotPick>& snapshot_picks,
bool purge)
{
auto any_snapshot = false;
std::vector<std::string> snapshots_of_deleted_instances{};
for (const auto* selection : {&report.deleted_selection, &report.operative_selection})
{
for (const auto& vm_it : *selection)
{
if (auto pick_it = snapshot_picks.find(vm_it->first); pick_it != snapshot_picks.end())
{
for (const auto& snapshot_name : pick_it->second.pick)
{
if (selection == &report.deleted_selection && !(pick_it->second.all_or_none && purge))
snapshots_of_deleted_instances.push_back(fmt::format("{}.{}", vm_it->first, snapshot_name));
vm_it->second->get_snapshot(snapshot_name); // throws if missing
any_snapshot = true;
}
}
}
if (!snapshots_of_deleted_instances.empty())
throw std::runtime_error{fmt::format(
"Cannot delete snapshots of deleted instances: {}",
fmt::join(snapshots_of_deleted_instances.begin(), snapshots_of_deleted_instances.end(), ", "))};
}
return any_snapshot;
}
void add_aliases(google::protobuf::RepeatedPtrField<mp::FindReply_ImageInfo>* container, const std::string& remote_name,
const mp::VMImageInfo& info, const std::string& default_remote)
{
if (!info.aliases.empty())
{
auto entry = container->Add();
for (const auto& alias : info.aliases)
{
auto alias_entry = entry->add_aliases_info();
if (remote_name != default_remote)
{
alias_entry->set_remote_name(remote_name);
}
alias_entry->set_alias(alias.toStdString());
}
entry->set_os(info.os.toStdString());
entry->set_release(info.release_title.toStdString());
entry->set_version(info.version.toStdString());
entry->set_codename(info.release_codename.toStdString());
}
}
auto timeout_for(const int requested_timeout, const int blueprint_timeout)
{
if (requested_timeout > 0)
return std::chrono::seconds(requested_timeout);
if (blueprint_timeout > 0)
return std::chrono::seconds(blueprint_timeout);
return mp::default_timeout;
}
mp::SettingsHandler* register_instance_mod(std::unordered_map<std::string, mp::VMSpecs>& vm_instance_specs,
InstanceTable& operative_instances,
const InstanceTable& 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)
{
return MP_SETTINGS.register_handler(std::make_unique<mp::InstanceSettingsHandler>(vm_instance_specs,
operative_instances,
deleted_instances,
preparing_instances,
std::move(instance_persister),
is_bridged,
add_interface));
}
mp::SettingsHandler* register_snapshot_mod(
std::unordered_map<std::string, mp::VirtualMachine::ShPtr>& operative_instances,
const std::unordered_map<std::string, mp::VirtualMachine::ShPtr>& deleted_instances,
const std::unordered_set<std::string>& preparing_instances,
const mp::VirtualMachineFactory& vm_factory)
{
try
{
vm_factory.require_snapshots_support();
return MP_SETTINGS.register_handler(
std::make_unique<mp::SnapshotSettingsHandler>(operative_instances, deleted_instances, preparing_instances));
}
catch (const mp::NotImplementedOnThisBackendException& e)
{
assert(std::string{e.what()}.find("snapshots") != std::string::npos);
}
return nullptr;
}
// Erase any outdated mount handlers for a given VM
bool prune_obsolete_mounts(const std::unordered_map<std::string, mp::VMMount>& mount_specs,
std::unordered_map<std::string, mp::MountHandler::UPtr>& vm_mounts)
{
auto removed = false;
auto handlers_it = vm_mounts.begin();
while (handlers_it != vm_mounts.end())
{
const auto& [target, handler] = *handlers_it;
if (auto specs_it = mount_specs.find(target);
specs_it == mount_specs.end() || handler->get_mount_spec() != specs_it->second)
{
if (handler->is_mount_managed_by_backend())
{
assert(handler->is_active());
handler->deactivate();
}
handlers_it = vm_mounts.erase(handlers_it);
removed = true;
}
else
++handlers_it;
}
return removed;
}
void populate_snapshot_fundamentals(std::shared_ptr<const mp::Snapshot> snapshot,
mp::SnapshotFundamentals* fundamentals)
{
fundamentals->set_snapshot_name(snapshot->get_name());
fundamentals->set_parent(snapshot->get_parents_name());
fundamentals->set_comment(snapshot->get_comment());
auto timestamp = fundamentals->mutable_creation_timestamp();
timestamp->set_seconds(snapshot->get_creation_timestamp().toSecsSinceEpoch());
timestamp->set_nanos(snapshot->get_creation_timestamp().time().msec() * 1'000'000);
}
void populate_mount_info(const std::unordered_map<std::string, mp::VMMount>& mounts,
mp::MountInfo* mount_info,
bool& have_mounts)
{
mount_info->set_longest_path_len(0);
if (!mounts.empty())
have_mounts = true;
if (MP_SETTINGS.get_as<bool>(mp::mounts_key))
{
for (const auto& mount : mounts)
{
if (mount.second.get_source_path().size() > mount_info->longest_path_len())
mount_info->set_longest_path_len(mount.second.get_source_path().size());
auto entry = mount_info->add_mount_paths();
entry->set_source_path(mount.second.get_source_path());
entry->set_target_path(mount.first);
for (const auto& uid_mapping : mount.second.get_uid_mappings())
{
auto uid_pair = entry->mutable_mount_maps()->add_uid_mappings();
uid_pair->set_host_id(uid_mapping.first);
uid_pair->set_instance_id(uid_mapping.second);
}
for (const auto& gid_mapping : mount.second.get_gid_mappings())
{
auto gid_pair = entry->mutable_mount_maps()->add_gid_mappings();
gid_pair->set_host_id(gid_mapping.first);
gid_pair->set_instance_id(gid_mapping.second);
}
}
}
}
void populate_snapshot_info(mp::VirtualMachine& vm,
std::shared_ptr<const mp::Snapshot> snapshot,
mp::InfoReply& response,
bool& have_mounts)
{
auto* info = response.add_details();
auto snapshot_info = info->mutable_snapshot_info();
auto fundamentals = snapshot_info->mutable_fundamentals();
info->set_name(vm.vm_name);
info->mutable_instance_status()->set_status(grpc_instance_status_for(snapshot->get_state()));
info->set_memory_total(snapshot->get_mem_size().human_readable());
info->set_disk_total(snapshot->get_disk_space().human_readable());
info->set_cpu_count(std::to_string(snapshot->get_num_cores()));
auto mount_info = info->mutable_mount_info();
populate_mount_info(snapshot->get_mounts(), mount_info, have_mounts);
// TODO@snapshots get snapshot size once available
for (const auto& child : vm.get_childrens_names(snapshot.get()))
snapshot_info->add_children(child);
populate_snapshot_fundamentals(snapshot, fundamentals);
}
} // namespace
mp::Daemon::Daemon(std::unique_ptr<const DaemonConfig> the_config)
: config{std::move(the_config)},
vm_instance_specs{load_db(
mp::utils::backend_directory_path(config->data_directory, config->factory->get_backend_directory_name()),
mp::utils::backend_directory_path(config->cache_directory, config->factory->get_backend_directory_name()))},
daemon_rpc{config->server_address, *config->cert_provider, config->client_cert_store.get()},
instance_mod_handler{register_instance_mod(
vm_instance_specs,
operative_instances,
deleted_instances,
preparing_instances,
[this] { persist_instances(); },
[this](const std::string& n) { return is_bridged(n); },
[this](const std::string& n) { return add_bridged_interface(n); })},
snapshot_mod_handler{
register_snapshot_mod(operative_instances, deleted_instances, preparing_instances, *config->factory)}
{
connect_rpc(daemon_rpc, *this);
std::vector<std::string> invalid_specs;
try
{
config->factory->hypervisor_health_check();
}
catch (const std::runtime_error& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("Hypervisor health check failed: {}", e.what()));
}
for (auto& entry : vm_instance_specs)
{
const auto& name = entry.first;
auto& spec = entry.second;
if (!config->vault->has_record_for(name))
{
invalid_specs.push_back(name);
continue;
}
// Check that all the interfaces in the instance have different MAC address, and that they were not used in
// the other instances. String validity was already checked in load_db(). Add these MAC's to the daemon's set
// only if this instance is not invalid.
auto new_macs = mac_set_from(spec);
if (new_macs.size() <= spec.extra_interfaces.size() || !merge_if_disjoint(new_macs, allocated_mac_addrs))
{
// There is at least one repeated address in new_macs.
mpl::log(mpl::Level::warning, category, fmt::format("{} has repeated MAC addresses", name));
invalid_specs.push_back(name);
continue;
}
auto vm_image = fetch_image_for(name, *config->factory, *config->vault);
if (!vm_image.image_path.isEmpty() && !QFile::exists(vm_image.image_path))
{
mpl::log(mpl::Level::warning, category,
fmt::format("Could not find image for '{}'. Expected location: {}", name, vm_image.image_path));
invalid_specs.push_back(name);
continue;
}
const auto instance_dir = mp::utils::base_dir(vm_image.image_path);
const auto cloud_init_iso = instance_dir.filePath(cloud_init_file_name);
mp::VirtualMachineDescription vm_desc{spec.num_cores,
spec.mem_size,
spec.disk_space,
name,
spec.default_mac_address,
spec.extra_interfaces,
spec.ssh_username,
vm_image,
cloud_init_iso,
{},
{},
{},
{}};
auto& instance_record = spec.deleted ? deleted_instances : operative_instances;
auto instance = instance_record[name] =
config->factory->create_virtual_machine(vm_desc, *config->ssh_key_provider, *this);
instance->load_snapshots();
allocated_mac_addrs = std::move(new_macs); // Add the new macs to the daemon's list only if we got this far
// FIXME: somehow we're writing contradictory state to disk.
if (spec.deleted && spec.state != VirtualMachine::State::stopped && spec.state != VirtualMachine::State::off)
{
mpl::log(mpl::Level::warning,
category,
fmt::format("{} is deleted but has incompatible state {}, resetting state to {} (stopped)",
name,
static_cast<int>(spec.state),
static_cast<int>(VirtualMachine::State::stopped)));
spec.state = VirtualMachine::State::stopped;
}
if (!spec.deleted)
init_mounts(name);
std::unique_lock lock{start_mutex};
if (spec.state == VirtualMachine::State::running &&
operative_instances[name]->current_state() != VirtualMachine::State::running &&
operative_instances[name]->current_state() != VirtualMachine::State::starting)
{
assert(!spec.deleted);
mpl::log(mpl::Level::info, category, fmt::format("{} needs starting. Starting now...", name));
multipass::top_catch_all(name, [this, &name, &lock]() {
operative_instances[name]->start();
lock.unlock();
on_restart(name);
});
}
}
for (const auto& bad_spec : invalid_specs)
{
mpl::log(mpl::Level::warning, category, fmt::format("Removing invalid instance: {}", bad_spec));
vm_instance_specs.erase(bad_spec);
config->vault->remove(bad_spec);
}
if (!invalid_specs.empty())
persist_instances();
config->vault->prune_expired_images();
// Fire timer every six hours to perform maintenance on source images such as
// pruning expired images and updating to newly released images.
connect(&source_images_maintenance_task, &QTimer::timeout, [this]() {
if (image_update_future.isRunning())
{
mpl::log(mpl::Level::info, category, "Image updater already running. Skipping…");
}
else
{
image_update_future = QtConcurrent::run([this] {
config->vault->prune_expired_images();
auto prepare_action = [this](const VMImage& source_image) -> VMImage {
return config->factory->prepare_source_image(source_image);
};
auto download_monitor = [](int download_type, int percentage) {
static int last_percentage_logged = -1;
if (percentage % 10 == 0)
{
// Note: The progress callback may be called repeatedly with the same percentage,
// so this logic is to only log it once
if (last_percentage_logged != percentage)
{
mpl::log(mpl::Level::info, category, fmt::format(" {}%", percentage));
last_percentage_logged = percentage;
}
}
return true;
};
try
{
config->vault->update_images(config->factory->fetch_type(), prepare_action, download_monitor);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::error, category, fmt::format("Error updating images: {}", e.what()));
}
});
}
});
source_images_maintenance_task.start(config->image_refresh_timer);
}
mp::Daemon::~Daemon()
{
mp::top_catch_all(category, [this] {
MP_SETTINGS.unregister_handler(instance_mod_handler);
MP_SETTINGS.unregister_handler(snapshot_mod_handler);
});
}
void mp::Daemon::shutdown_grpc_server()
{
daemon_rpc.shutdown_and_wait();
}
void mp::Daemon::create(const CreateRequest* request,
grpc::ServerReaderWriterInterface<CreateReply, CreateRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<CreateReply, CreateRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
return create_vm(request, server, status_promise, /*start=*/false);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::launch(const LaunchRequest* request,
grpc::ServerReaderWriterInterface<LaunchReply, LaunchRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<LaunchReply, LaunchRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
return create_vm(request, server, status_promise, /*start=*/true);
}
catch (const mp::StartException& e)
{
auto name = e.name();
release_resources(name);
operative_instances.erase(name);
persist_instances();
status_promise->set_value(grpc::Status(grpc::StatusCode::ABORTED, e.what(), ""));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::purge(const PurgeRequest* request, grpc::ServerReaderWriterInterface<PurgeReply, PurgeRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
PurgeReply response;
for (const auto& del : deleted_instances)
{
const auto& name = del.first;
release_resources(name);
response.add_purged_instances(name);
mpl::log(mpl::Level::debug, category, fmt::format("Instance purged: {}", name));
}
deleted_instances.clear();
persist_instances();
server->Write(response);
status_promise->set_value(grpc::Status::OK);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::find(const FindRequest* request, grpc::ServerReaderWriterInterface<FindReply, FindRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<FindReply, FindRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
FindReply response;
response.set_show_images(request->show_images());
response.set_show_blueprints(request->show_blueprints());
const auto default_remote{"release"};
if (!request->search_string().empty())
{
if (!request->remote_name().empty())
{
// This is a compromised solution for now, it throws if remote_name is invalid.
// In principle, it should catch the returned VMImageHost in the valid remote_name case and
// get the found VMImageHost reused in the follow-up code. However, because of the current framework,
// That would involve more changes because the query carries the remote name and there is
// another dispatch in the all_info_for function.
const auto& remote_name = request->remote_name();
config->vault->image_host_for(remote_name);
}
if (request->show_images())
{
wait_update_manifests_all_and_optionally_applied_force(request->force_manifest_network_download());
std::vector<std::pair<std::string, VMImageInfo>> vm_images_info;
try
{
vm_images_info =
config->vault->all_info_for({"", request->search_string(), false, request->remote_name(),
Query::Type::Alias, request->allow_unsupported()});
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("An unexpected error occurred while fetching images matching \"{}\": {}",
request->search_string(), e.what()));
}
for (auto& [remote, info] : vm_images_info)
{
if (info.aliases.contains(QString::fromStdString(request->search_string())))
info.aliases = QStringList({QString::fromStdString(request->search_string())});
else
info.aliases = QStringList({info.id.left(12)});
auto remote_name =
(!request->remote_name().empty() ||
(request->remote_name().empty() && vm_images_info.size() > 1 && remote != default_remote))
? remote
: "";
add_aliases(response.mutable_images_info(), remote_name, info, "");
}
}
if (request->show_blueprints())
{
std::optional<VMImageInfo> info;
try
{
info = config->blueprint_provider->info_for(request->search_string());
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("An unexpected error occurred while fetching blueprints matching \"{}\": {}",
request->search_string(), e.what()));
}
if (info)
{
if ((*info).aliases.contains(QString::fromStdString(request->search_string())))
(*info).aliases = QStringList({QString::fromStdString(request->search_string())});
else
(*info).aliases = QStringList({(*info).id.left(12)});
add_aliases(response.mutable_blueprints_info(), "", *info, "");
}
}
}
else if (request->remote_name().empty())
{
if (request->show_images())
{
wait_update_manifests_all_and_optionally_applied_force(request->force_manifest_network_download());
for (const auto& image_host : config->image_hosts)
{
std::unordered_set<std::string> images_found;
auto action = [&images_found, &default_remote, request, &response](const std::string& remote,
const mp::VMImageInfo& info) {
if (remote != mp::snapcraft_remote && (info.supported || request->allow_unsupported()) &&
!info.aliases.empty() &&
images_found.find(info.release_title.toStdString()) == images_found.end())
{
add_aliases(response.mutable_images_info(), remote, info, default_remote);
images_found.insert(info.release_title.toStdString());
}
};
image_host->for_each_entry_do(action);
}
}
if (request->show_blueprints())
{
auto vm_blueprints_info = config->blueprint_provider->all_blueprints();
for (const auto& info : vm_blueprints_info)
add_aliases(response.mutable_blueprints_info(), "", info, "");
}
}
else
{
wait_update_manifests_all_and_optionally_applied_force(request->force_manifest_network_download());
const auto& remote = request->remote_name();
auto image_host = config->vault->image_host_for(remote);
auto vm_images_info = image_host->all_images_for(remote, request->allow_unsupported());
for (const auto& info : vm_images_info)
add_aliases(response.mutable_images_info(), remote, info, "");
}
server->Write(response);
status_promise->set_value(grpc::Status::OK);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::info(const InfoRequest* request, grpc::ServerReaderWriterInterface<InfoReply, InfoRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<InfoReply, InfoRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
InfoReply response;
config->update_prompt->populate_if_time_to_show(response.mutable_update_info());
InstanceSnapshotsMap instance_snapshots_map;
bool have_mounts = false;
bool deleted = false;
bool snapshots_only = request->snapshots();
response.set_snapshots(snapshots_only);
if (snapshots_only)
config->factory->require_snapshots_support();
auto process_snapshot_pick = [&response, &have_mounts, snapshots_only](VirtualMachine& vm,
const SnapshotPick& snapshot_pick) {
for (const auto& snapshot_name : snapshot_pick.pick)
{
const auto snapshot = vm.get_snapshot(snapshot_name); // verify validity even if unused
if (!snapshot_pick.all_or_none || !snapshots_only)
populate_snapshot_info(vm, snapshot, response, have_mounts);
}
};
auto fetch_detailed_report = [this,
&instance_snapshots_map,
process_snapshot_pick,
snapshots_only,
request,
&response,
&have_mounts,
&deleted](VirtualMachine& vm) {
fmt::memory_buffer errors;
const auto& name = vm.vm_name;
const auto& it = instance_snapshots_map.find(name);
const auto& snapshot_pick = it == instance_snapshots_map.end() ? SnapshotPick{{}, true} : it->second;
try
{
process_snapshot_pick(vm, snapshot_pick);
if (snapshot_pick.all_or_none)
{
if (snapshots_only)
for (const auto& snapshot : vm.view_snapshots())
populate_snapshot_info(vm, snapshot, response, have_mounts);
else
populate_instance_info(vm, response, request->no_runtime_information(), deleted, have_mounts);
}
}
catch (const NoSuchSnapshotException& e)
{
add_fmt_to(errors, e.what());
}
return grpc_status_for(errors);
};
auto [instance_selection, status] = select_instances_and_react(operative_instances,
deleted_instances,
request->instance_snapshot_pairs(),
InstanceGroup::All,
require_existing_instances_reaction);
if (status.ok())
{
instance_snapshots_map = map_snapshots_to_instances(request->instance_snapshot_pairs());
if ((status = cmd_vms(instance_selection.operative_selection, fetch_detailed_report)).ok())
{
deleted = true;
status = cmd_vms(instance_selection.deleted_selection, fetch_detailed_report);
}
if (have_mounts && !MP_SETTINGS.get_as<bool>(mp::mounts_key))
mpl::log(mpl::Level::error, category, "Mounts have been disabled on this instance of Multipass");
server->Write(response);
}
status_promise->set_value(status);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::list(const ListRequest* request, grpc::ServerReaderWriterInterface<ListReply, ListRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<ListReply, ListRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
ListReply response;
config->update_prompt->populate_if_time_to_show(response.mutable_update_info());
// Need to 'touch' a report in the response so formatters know what to do with an otherwise empty response
if (request->snapshots())
{
config->factory->require_snapshots_support();
response.mutable_snapshot_list();
}
else
response.mutable_instance_list();
bool deleted = false;
auto fetch_instance = [this, request, &response, &deleted](VirtualMachine& vm) {
const auto& name = vm.vm_name;
auto present_state = vm.current_state();
auto entry = response.mutable_instance_list()->add_instances();
entry->set_name(name);
if (deleted)
entry->mutable_instance_status()->set_status(mp::InstanceStatus::DELETED);
else
entry->mutable_instance_status()->set_status(grpc_instance_status_for(present_state));
// FIXME: Set the release to the cached current version when supported
auto vm_image = fetch_image_for(name, *config->factory, *config->vault);
auto current_release = vm_image.original_release;
if (!vm_image.id.empty() && current_release.empty())
{
try
{
auto vm_image_info = config->image_hosts.back()->info_for_full_hash(vm_image.id);
current_release = vm_image_info.release_title.toStdString();
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("Cannot fetch image information: {}", e.what()));
}
}
entry->set_current_release(current_release);
if (request->request_ipv4() && MP_UTILS.is_running(present_state))
{
std::string management_ip = vm.management_ipv4();
auto all_ipv4 = vm.get_all_ipv4();
if (MP_UTILS.is_ipv4_valid(management_ip))
entry->add_ipv4(management_ip);
else if (all_ipv4.empty())
entry->add_ipv4("N/A");
for (const auto& extra_ipv4 : all_ipv4)
if (extra_ipv4 != management_ip)
entry->add_ipv4(extra_ipv4);
}
return grpc::Status::OK;
};
auto fetch_snapshot = [&response](VirtualMachine& vm) {
fmt::memory_buffer errors;
const auto& name = vm.vm_name;
try
{
for (const auto& snapshot : vm.view_snapshots())
{
auto entry = response.mutable_snapshot_list()->add_snapshots();
auto fundamentals = entry->mutable_fundamentals();
entry->set_name(name);
populate_snapshot_fundamentals(snapshot, fundamentals);
}
}
catch (const NoSuchSnapshotException& e)
{
add_fmt_to(errors, e.what());
}
return grpc_status_for(errors);
};
auto cmd = request->snapshots() ? std::function(fetch_snapshot) : std::function(fetch_instance);
auto status = cmd_vms(select_all(operative_instances), cmd);
if (status.ok())
{
deleted = true;
status = cmd_vms(select_all(deleted_instances), cmd);
}
server->Write(response);
status_promise->set_value(status);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::networks(const NetworksRequest* request,
grpc::ServerReaderWriterInterface<NetworksReply, NetworksRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<NetworksReply, NetworksRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger, server};
NetworksReply response;
config->update_prompt->populate_if_time_to_show(response.mutable_update_info());
if (!instances_running(operative_instances))
config->factory->hypervisor_health_check();
const auto& iface_list = config->factory->networks();
for (const auto& iface : iface_list)
{
auto entry = response.add_interfaces();
entry->set_name(iface.id);
entry->set_type(iface.type);
entry->set_description(iface.description);
}
server->Write(response);
status_promise->set_value(grpc::Status::OK);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::mount(const MountRequest* request, grpc::ServerReaderWriterInterface<MountReply, MountRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<MountReply, MountRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
if (!MP_SETTINGS.get_as<bool>(mp::mounts_key))
return status_promise->set_value(
grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
"Mounts are disabled on this installation of Multipass.\n\n"
"See https://multipass.run/docs/set-command#local.privileged-mounts for information\n"
"on how to enable them."));
mp::id_mappings uid_mappings, gid_mappings;
for (const auto& map : request->mount_maps().uid_mappings())
uid_mappings.push_back({map.host_id(), map.instance_id()});
for (const auto& map : request->mount_maps().gid_mappings())
gid_mappings.push_back({map.host_id(), map.instance_id()});
fmt::memory_buffer errors;
for (const auto& path_entry : request->target_paths())
{
const auto& name = path_entry.instance_name();
const auto q_target_path = path_entry.target_path().empty()
? MP_UTILS.default_mount_target(QString::fromStdString(request->source_path()))
: QDir::cleanPath(QString::fromStdString(path_entry.target_path()));
const auto target_path = q_target_path.toStdString();
auto it = operative_instances.find(name);
if (it == operative_instances.end())
{
add_fmt_to(errors, "instance '{}' does not exist", name);
continue;
}
auto& vm = it->second;
if (mp::utils::invalid_target_path(q_target_path))
{
add_fmt_to(errors, "unable to mount to \"{}\"", target_path);
continue;
}
auto& vm_mounts = mounts[name];
if (vm_mounts.find(target_path) != vm_mounts.end())
{
add_fmt_to(errors, "\"{}\" is already mounted in '{}'", target_path, name);
continue;
}
const auto mount_type = request->mount_type() == MountRequest_MountType_CLASSIC ? VMMount::MountType::Classic
: VMMount::MountType::Native;
VMMount vm_mount{request->source_path(), gid_mappings, uid_mappings, mount_type};
vm_mounts[target_path] = make_mount(vm.get(), target_path, vm_mount);
if (vm->current_state() == mp::VirtualMachine::State::running ||
vm_mounts[target_path]->is_mount_managed_by_backend())
{
try
{
vm_mounts[target_path]->activate(server);
}
catch (const mp::SSHFSMissingError&)
{
return status_promise->set_value(grpc_status_for_mount_error(name));
}
catch (const std::exception& e)
{
add_fmt_to(errors, "error mounting \"{}\": {}", target_path, e.what());
vm_mounts.erase(target_path);
continue;
}
}
vm_instance_specs[name].mounts[target_path] = vm_mount;
}
persist_instances();
status_promise->set_value(grpc_status_for(errors));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::recover(const RecoverRequest* request,
grpc::ServerReaderWriterInterface<RecoverReply, RecoverRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<RecoverReply, RecoverRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto recover_reaction = require_existing_instances_reaction;
recover_reaction.operative_reaction.message_template = "instance \"{}\" does not need to be recovered";
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_names().instance_name(),
InstanceGroup::Deleted, recover_reaction);
if (status.ok())
{
for (const auto& vm_it : instance_selection.deleted_selection)
{
const auto name = vm_it->first;
assert(vm_instance_specs[name].deleted);
vm_instance_specs[name].deleted = false;
operative_instances[name] = std::move(vm_it->second);
deleted_instances.erase(vm_it);
init_mounts(name);
mpl::log(mpl::Level::debug, category, fmt::format("Instance recovered: {}", name));
}
persist_instances();
}
status_promise->set_value(status);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::ssh_info(const SSHInfoRequest* request,
grpc::ServerReaderWriterInterface<SSHInfoReply, SSHInfoRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<SSHInfoReply, SSHInfoRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_name(),
InstanceGroup::None, require_operative_instances_reaction);
if (status.ok())
{
SSHInfoReply response;
auto operation = std::bind(&Daemon::get_ssh_info_for_vm, this, std::placeholders::_1, std::ref(response));
if ((status = cmd_vms(instance_selection.operative_selection, operation)).ok())
server->Write(response);
}
status_promise->set_value(status);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::start(const StartRequest* request, grpc::ServerReaderWriterInterface<StartReply, StartRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<StartReply, StartRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto timeout = request->timeout() > 0 ? std::chrono::seconds(request->timeout()) : mp::default_timeout;
if (!instances_running(operative_instances))
config->factory->hypervisor_health_check();
const SelectionReaction custom_reaction{
{grpc::StatusCode::OK}, {grpc::StatusCode::ABORTED}, {grpc::StatusCode::ABORTED}};
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_names().instance_name(),
InstanceGroup::Operative, custom_reaction);
if (!status.ok())
return status_promise->set_value(
{status.error_code(), "instance(s) missing", make_start_error_details(instance_selection)});
bool complain_disabled_mounts = !MP_SETTINGS.get_as<bool>(mp::mounts_key);
std::vector<std::string> starting_vms{};
starting_vms.reserve(instance_selection.operative_selection.size());
fmt::memory_buffer start_errors, start_warnings;
for (auto& vm_it : instance_selection.operative_selection)
{
std::lock_guard lock{start_mutex};
const auto& name = vm_it->first;
auto& vm = *vm_it->second;
switch (vm.current_state())
{
case VirtualMachine::State::unknown:
{
auto error_string = fmt::format("Instance '{0}' is already running, but in an unknown state.\n"
"Try to stop it first.",
name);
mpl::log(mpl::Level::warning, category, error_string);
fmt::format_to(std::back_inserter(start_errors), error_string);
continue;
}
case VirtualMachine::State::suspending:
fmt::format_to(std::back_inserter(start_errors), "Cannot start the instance '{}' while suspending.", name);
continue;
case VirtualMachine::State::delayed_shutdown:
delayed_shutdown_instances.erase(name);
continue;
case VirtualMachine::State::running:
continue;
case VirtualMachine::State::starting:
case VirtualMachine::State::restarting:
break;
default:
if (complain_disabled_mounts && !vm_instance_specs[name].mounts.empty())
{
complain_disabled_mounts = false; // I shall say zis only once
mpl::log(mpl::Level::error, category, "Mounts have been disabled on this instance of Multipass");
}
vm.start();
}
starting_vms.push_back(vm_it->first);
}
auto future_watcher = create_future_watcher();
future_watcher->setFuture(QtConcurrent::run(&Daemon::async_wait_for_ready_all<StartReply, StartRequest>,
this,
server,
starting_vms,
timeout,
status_promise,
fmt::to_string(start_errors),
fmt::to_string(start_warnings)));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::stop(const StopRequest* request, grpc::ServerReaderWriterInterface<StopReply, StopRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<StopReply, StopRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_names().instance_name(),
InstanceGroup::Operative, require_operative_instances_reaction);
if (status.ok())
{
assert(instance_selection.deleted_selection.empty());
assert(instance_selection.missing_instances.empty());
std::function<grpc::Status(VirtualMachine&)> operation;
if (request->cancel_shutdown())
operation = [this](const VirtualMachine& vm) { return this->cancel_vm_shutdown(vm); };
else if (request->force_stop())
operation = [this](VirtualMachine& vm) { return this->switch_off_vm(vm); };
else
operation = [this, delay_minutes = std::chrono::minutes(request->time_minutes())](VirtualMachine& vm) {
return this->shutdown_vm(vm, delay_minutes);
};
status = cmd_vms(instance_selection.operative_selection, operation);
}
status_promise->set_value(status);
}
catch (const mp::VMStateInvalidException& e)
{
status_promise->set_value(grpc::Status{grpc::StatusCode::FAILED_PRECONDITION, e.what()});
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what()));
}
void mp::Daemon::suspend(const SuspendRequest* request,
grpc::ServerReaderWriterInterface<SuspendReply, SuspendRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<SuspendReply, SuspendRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_names().instance_name(),
InstanceGroup::Operative, require_operative_instances_reaction);
if (status.ok())
{
config->factory->require_suspend_support();
status = cmd_vms(instance_selection.operative_selection, [this](auto& vm) {
stop_mounts(vm.vm_name);
vm.suspend();
return grpc::Status::OK;
});
}
status_promise->set_value(status);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::restart(const RestartRequest* request,
grpc::ServerReaderWriterInterface<RestartReply, RestartRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<RestartReply, RestartRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto timeout = request->timeout() > 0 ? std::chrono::seconds(request->timeout()) : mp::default_timeout;
auto [instance_selection, status] =
select_instances_and_react(operative_instances, deleted_instances, request->instance_names().instance_name(),
InstanceGroup::Operative, require_operative_instances_reaction);
if (!status.ok())
{
return status_promise->set_value(status);
}
const auto& instance_targets = instance_selection.operative_selection;
status = cmd_vms(instance_targets, [this](auto& vm) {
stop_mounts(vm.vm_name);
return reboot_vm(vm);
}); // 1st pass to reboot all targets
if (!status.ok())
{
return status_promise->set_value(status);
}
auto future_watcher = create_future_watcher();
future_watcher->setFuture(QtConcurrent::run(&Daemon::async_wait_for_ready_all<RestartReply, RestartRequest>,
this,
server,
names_from(instance_targets),
timeout,
status_promise,
std::string(),
std::string()));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::delet(const DeleteRequest* request,
grpc::ServerReaderWriterInterface<DeleteReply, DeleteRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<DeleteReply, DeleteRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
DeleteReply response;
auto [instance_selection, status] = select_instances_and_react(operative_instances,
deleted_instances,
request->instance_snapshot_pairs(),
InstanceGroup::All,
require_existing_instances_reaction);
if (status.ok())
{
const bool purge = request->purge();
bool purge_snapshots = request->purge_snapshots();
auto instances_dirty = false;
auto instance_snapshots_map = map_snapshots_to_instances(request->instance_snapshot_pairs());
// avoid deleting if any snapshot is missing or if we don't get confirmation
auto any_snapshot_args = verify_snapshot_picks(instance_selection, instance_snapshots_map, purge);
if (any_snapshot_args && !purge && !purge_snapshots)
{
DeleteReply confirm_action{};
confirm_action.set_confirm_snapshot_purging(true);
// TODO refactor with bridging and restore prompts
if (!server->Write(confirm_action))
throw std::runtime_error("Cannot request confirmation from client. Aborting...");
DeleteRequest client_response;
if (!server->Read(&client_response))
throw std::runtime_error("Cannot get confirmation from client. Aborting...");
if (!(purge_snapshots = client_response.purge_snapshots()))
return status_promise->set_value(grpc::Status{grpc::CANCELLED, "Cancelled."});
}
// start with deleted instances, to avoid iterator invalidation when moving instances there
for (const auto* selection : {&instance_selection.deleted_selection, &instance_selection.operative_selection})
{
for (const auto& vm_it : *selection)
{
const auto& instance_name = vm_it->first;
auto snapshot_pick_it = instance_snapshots_map.find(instance_name);
const auto& [pick, all] = snapshot_pick_it == instance_snapshots_map.end() ? SnapshotPick{{}, true}
: snapshot_pick_it->second;
if (!all || !purge) // if we're not purging the instance, we need to delete specified snapshots
for (const auto& snapshot_name : pick)
vm_it->second->delete_snapshot(snapshot_name);
if (all) // we're asked to delete the VM
instances_dirty |= delete_vm(vm_it, purge, response);
}
}
if (instances_dirty)
persist_instances();
}
server->Write(response);
status_promise->set_value(status);
}
catch (const mp::VMStateInvalidException& e)
{
status_promise->set_value(grpc::Status{grpc::StatusCode::FAILED_PRECONDITION, e.what()});
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what()));
}
void mp::Daemon::umount(const UmountRequest* request,
grpc::ServerReaderWriterInterface<UmountReply, UmountRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<UmountReply, UmountRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
fmt::memory_buffer errors;
for (const auto& path_entry : request->target_paths())
{
const auto& name = path_entry.instance_name();
const auto target_path = QDir::cleanPath(QString::fromStdString(path_entry.target_path())).toStdString();
if (operative_instances.find(name) == operative_instances.end())
{
add_fmt_to(errors, "instance '{}' does not exist", name);
continue;
}
auto& vm_spec_mounts = vm_instance_specs[name].mounts;
auto& vm_mounts = mounts[name];
auto do_unmount = [&](auto expiring_it) {
const auto& [target, mount] = *expiring_it;
try
{
mount->deactivate();
vm_spec_mounts.erase(target);
vm_mounts.erase(expiring_it);
}
catch (const std::runtime_error& e)
{
add_fmt_to(errors, "failed to unmount \"{}\" from '{}': {}", target, name, e.what());
}
};
// Empty target path indicates removing all mounts for the VM instance
if (target_path.empty())
for (auto expiring_it = vm_mounts.begin(); expiring_it != vm_mounts.end();)
{
// iterator must be advanced before used in order to prevent iterator invalidation caused by deleting
// from the iterated map
// expiring_it will be invalidated by do_unmount, so it must not be used after this point
do_unmount(expiring_it++);
}
else if (auto it = vm_mounts.find(target_path); it != vm_mounts.end())
do_unmount(it);
else
add_fmt_to(errors, "path \"{}\" is not mounted in '{}'", target_path, name);
}
persist_instances();
status_promise->set_value(grpc_status_for(errors));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::version(const VersionRequest* request,
grpc::ServerReaderWriterInterface<VersionReply, VersionRequest>* server,
std::promise<grpc::Status>* status_promise)
{
mpl::ClientLogger<VersionReply, VersionRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
VersionReply reply;
reply.set_version(multipass::version_string);
config->update_prompt->populate(reply.mutable_update_info());
server->Write(reply);
status_promise->set_value(grpc::Status::OK);
}
void mp::Daemon::get(const GetRequest* request, grpc::ServerReaderWriterInterface<GetReply, GetRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<GetReply, GetRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
GetReply reply;
auto key = request->key();
auto val = MP_SETTINGS.get(QString::fromStdString(key)).toStdString();
mpl::log(mpl::Level::debug, category, fmt::format("Returning setting {}={}", key, val));
reply.set_value(val);
server->Write(reply);
status_promise->set_value(grpc::Status::OK);
}
catch (const mp::UnrecognizedSettingException& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what(), ""));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::set(const SetRequest* request, grpc::ServerReaderWriterInterface<SetReply, SetRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<SetReply, SetRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
auto key = request->key();
auto val = request->val();
std::string bridge_name;
if (request->authorized() && !(bridge_name = MP_SETTINGS.get(mp::bridged_interface_key).toStdString()).empty())
{
user_authorized_bridges.insert(bridge_name);
}
auto auth_guard = sg::make_scope_guard([this, &bridge_name]() noexcept {
mp::top_catch_all(category, [this, &bridge_name]() {
if (!bridge_name.empty())
user_authorized_bridges.erase(bridge_name);
});
});
mpl::log(mpl::Level::trace, category, fmt::format("Trying to set {}={}", key, val));
MP_SETTINGS.set(QString::fromStdString(key), QString::fromStdString(val));
mpl::log(mpl::Level::debug, category, fmt::format("Succeeded setting {}={}", key, val));
status_promise->set_value(grpc::Status::OK);
}
catch (const mp::NonAuthorizedBridgeSettingsException& e)
{
auto key = request->key();
auto val = request->val();
mpl::log(mpl::Level::debug, category, fmt::format("Asking for user authorization to set {}={}", key, val));
auto reply = SetReply{};
reply.set_needs_authorization(true);
reply.set_reply_message(get_bridged_interface_name());
server->Write(reply);
auto callback_request = SetRequest{};
server->Read(&callback_request);
if (callback_request.authorized())
{
user_authorized_bridges.insert(get_bridged_interface_name());
MP_SETTINGS.set(QString::fromStdString(key), QString::fromStdString(val));
user_authorized_bridges.erase(get_bridged_interface_name());
mpl::log(mpl::Level::debug, category, fmt::format("Succeeded setting {}={}", key, val));
status_promise->set_value(grpc::Status::OK);
}
else
{
mpl::log(mpl::Level::debug, category, "User did not authorize, cancelling");
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
}
catch (const mp::BridgeFailureException& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what(), ""));
}
catch (const mp::UnrecognizedSettingException& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what(), ""));
}
catch (const mp::InvalidSettingException& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what(), ""));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::keys(const mp::KeysRequest* request, grpc::ServerReaderWriterInterface<KeysReply, KeysRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<KeysReply, KeysRequest> logger{mpl::level_from(request->verbosity_level()), *config->logger,
server};
KeysReply reply;
for (const auto& key : MP_SETTINGS.keys())
reply.add_settings_keys(key.toStdString());
mpl::log(mpl::Level::debug, category, fmt::format("Returning {} settings keys", reply.settings_keys_size()));
server->Write(reply);
status_promise->set_value(grpc::Status::OK);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::authenticate(const AuthenticateRequest* request,
grpc::ServerReaderWriterInterface<AuthenticateReply, AuthenticateRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<AuthenticateReply, AuthenticateRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger, server};
auto stored_hash = MP_SETTINGS.get(mp::passphrase_key);
if (stored_hash.isNull() || stored_hash.isEmpty())
{
return status_promise->set_value(
grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
"Passphrase is not set. Please `multipass set local.passphrase` with a trusted client."));
}
auto hashed_passphrase = MP_UTILS.generate_scrypt_hash_for(QString::fromStdString(request->passphrase()));
if (stored_hash != hashed_passphrase)
{
return status_promise->set_value(
grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Passphrase is not correct. Please try again."));
}
status_promise->set_value(grpc::Status::OK);
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::snapshot(const mp::SnapshotRequest* request,
grpc::ServerReaderWriterInterface<SnapshotReply, SnapshotRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<SnapshotReply, SnapshotRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger,
server};
config->factory->require_snapshots_support();
const auto& instance_name = request->instance();
auto [instance_trail, status] = find_instance_and_react(operative_instances,
deleted_instances,
instance_name,
require_operative_instances_reaction);
if (status.ok())
{
assert(instance_trail.index() == 0);
auto* vm_ptr = std::get<0>(instance_trail)->second.get();
assert(vm_ptr);
using St = VirtualMachine::State;
if (auto state = vm_ptr->current_state(); state != St::off && state != St::stopped)
return status_promise->set_value(
grpc::Status{grpc::INVALID_ARGUMENT, "Multipass can only take snapshots of stopped instances."});
auto snapshot_name = request->snapshot();
if (!snapshot_name.empty() && !mp::utils::valid_hostname(snapshot_name))
return status_promise->set_value(
grpc::Status{grpc::INVALID_ARGUMENT, fmt::format(R"(Invalid snapshot name: "{}".)", snapshot_name)});
const auto spec_it = vm_instance_specs.find(instance_name);
assert(spec_it != vm_instance_specs.end() && "missing instance specs");
SnapshotReply reply;
reply.set_snapshot(vm_ptr->take_snapshot(spec_it->second, snapshot_name, request->comment())->get_name());
server->Write(reply);
}
status_promise->set_value(status);
}
catch (const SnapshotNameTakenException& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what(), ""));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::restore(const mp::RestoreRequest* request,
grpc::ServerReaderWriterInterface<RestoreReply, RestoreRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
mpl::ClientLogger<RestoreReply, RestoreRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger,
server};
RestoreReply reply;
const auto& instance_name = request->instance();
auto [instance_trail, status] = find_instance_and_react(operative_instances,
deleted_instances,
instance_name,
require_operative_instances_reaction);
if (status.ok())
{
assert(instance_trail.index() == 0);
auto* vm_ptr = std::get<0>(instance_trail)->second.get();
assert(vm_ptr);
// Only need to check if snapshots are supported and if the snapshot exists, so the result is discarded
vm_ptr->get_snapshot(request->snapshot());
using St = VirtualMachine::State;
if (auto state = vm_ptr->current_state(); state != St::off && state != St::stopped)
return status_promise->set_value(
grpc::Status{grpc::INVALID_ARGUMENT, "Multipass can only restore snapshots of stopped instances."});
auto spec_it = vm_instance_specs.find(instance_name);
assert(spec_it != vm_instance_specs.end() && "missing instance specs");
auto& vm_specs = spec_it->second;
if (!request->destructive())
{
RestoreReply confirm_action{};
confirm_action.set_confirm_destructive(true);
if (!server->Write(confirm_action))
throw std::runtime_error("Cannot request confirmation from client. Aborting...");
RestoreRequest client_response;
if (!server->Read(&client_response))
throw std::runtime_error("Cannot get confirmation from client. Aborting...");
if (!client_response.destructive())
{
reply_msg(server, fmt::format("Taking snapshot before restoring {}", instance_name));
const auto snapshot =
vm_ptr->take_snapshot(vm_specs, "", fmt::format("Before restoring {}", request->snapshot()));
reply_msg(server,
fmt::format("Snapshot taken: {}.{}", instance_name, snapshot->get_name()),
/* sticky = */ true);
}
}
// Actually restore snapshot
reply_msg(server, "Restoring snapshot");
auto old_specs = vm_specs;
vm_ptr->restore_snapshot(request->snapshot(), vm_specs);
auto mounts_it = mounts.find(instance_name);
assert(mounts_it != mounts.end() && "uninitialized mounts");
if (update_mounts(vm_specs, mounts_it->second, vm_ptr) || vm_specs != old_specs)
persist_instances();
server->Write(reply);
}
status_promise->set_value(status);
}
catch (const mp::NoSuchSnapshotException& e)
{
status_promise->set_value(grpc::Status{grpc::StatusCode::NOT_FOUND, e.what(), ""});
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what(), ""));
}
void mp::Daemon::clone(const CloneRequest* request,
grpc::ServerReaderWriterInterface<CloneReply, CloneRequest>* server,
std::promise<grpc::Status>* status_promise)
try
{
config->factory->require_clone_support();
mpl::ClientLogger<CloneReply, CloneRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger,
server};
const auto& source_name = request->source_name();
const auto [instance_trail, status] = find_instance_and_react(operative_instances,
deleted_instances,
source_name,
require_operative_instances_reaction);
if (status.ok())
{
assert(instance_trail.index() == 0);
const auto source_vm_ptr = std::get<0>(instance_trail)->second;
assert(source_vm_ptr);
const VirtualMachine::State source_vm_state = source_vm_ptr->current_state();
if (source_vm_state != VirtualMachine::State::stopped && source_vm_state != VirtualMachine::State::off)
{
return status_promise->set_value(
grpc::Status{grpc::FAILED_PRECONDITION,
"Please stop instance " + source_name + " before you clone it."});
}
const std::string destination_name = generate_destination_instance_name_for_clone(*request);
auto rollback_clean_up_all_resource_of_dest_instance =
sg::make_scope_guard([this, destination_name]() noexcept -> void {
release_resources(destination_name);
preparing_instances.erase((destination_name));
});
// signal that the new instance is being cooked up
preparing_instances.insert(destination_name);
auto& src_spec = vm_instance_specs[source_name];
auto dest_spec = clone_spec(src_spec, source_name, destination_name);
config->vault->clone(source_name, destination_name);
const mp::VMImage dest_vm_image = fetch_image_for(destination_name, *config->factory, *config->vault);
// QemuVirtualMachine constructor depends on vm_instance_specs[destination_name], so the appending of the
// dest_spec has to be done before the function create_vm_and_clone_instance_dir_data
vm_instance_specs.emplace(destination_name, dest_spec);
operative_instances[destination_name] =
config->factory->create_vm_and_clone_instance_dir_data(src_spec,
dest_spec,
source_name,
destination_name,
dest_vm_image,
*config->ssh_key_provider,
*this);
++src_spec.clone_count;
// preparing instance is done
preparing_instances.erase(destination_name);
persist_instances();
init_mounts(destination_name);
CloneReply rpc_response;
rpc_response.set_reply_message(fmt::format("Cloned from {} to {}.\n", source_name, destination_name));
server->Write(rpc_response);
rollback_clean_up_all_resource_of_dest_instance.dismiss();
}
status_promise->set_value(status);
}
catch (const mp::CloneInvalidNameException& e)
{
// all CloneInvalidNameException throws in generate_destination_instance_name_for_clone
status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what()));
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::INTERNAL, e.what()));
}
void mp::Daemon::daemon_info(const DaemonInfoRequest* request,
grpc::ServerReaderWriterInterface<DaemonInfoReply, DaemonInfoRequest>* server,
std::promise<grpc::Status>* status_promise) // clang-format off
try // clang-format on
{
mpl::ClientLogger<DaemonInfoReply, DaemonInfoRequest> logger{mpl::level_from(request->verbosity_level()),
*config->logger,
server};
DaemonInfoReply response;
QStorageInfo storage_info{config->data_directory};
response.set_available_space(storage_info.bytesTotal());
server->Write(response);
status_promise->set_value(grpc::Status{});
}
catch (const std::exception& e)
{
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
void mp::Daemon::on_shutdown()
{
}
void mp::Daemon::on_resume()
{
}
void mp::Daemon::on_suspend()
{
}
void mp::Daemon::on_restart(const std::string& name)
{
stop_mounts(name);
auto future_watcher = create_future_watcher([this, &name]() {
try
{
auto virtual_machine = operative_instances.at(name);
std::lock_guard<decltype(virtual_machine->state_mutex)> lock{virtual_machine->state_mutex};
virtual_machine->state = VirtualMachine::State::running;
virtual_machine->update_state();
}
catch (const std::out_of_range&)
{
// logging is dangerous since this thread is probably in a corrupt state
}
});
future_watcher->setFuture(QtConcurrent::run(&Daemon::async_wait_for_ready_all<StartReply, StartRequest>,
this,
nullptr,
std::vector<std::string>{name},
mp::default_timeout,
nullptr,
std::string(),
std::string()));
}
void mp::Daemon::persist_state_for(const std::string& name, const VirtualMachine::State& state)
{
vm_instance_specs[name].state = state;
persist_instances();
}
void mp::Daemon::update_metadata_for(const std::string& name, const QJsonObject& metadata)
{
vm_instance_specs[name].metadata = metadata;
persist_instances();
}
QJsonObject mp::Daemon::retrieve_metadata_for(const std::string& name)
{
return vm_instance_specs[name].metadata;
}
void mp::Daemon::persist_instances()
{
QJsonObject instance_records_json;
for (const auto& record : vm_instance_specs)
{
auto key = QString::fromStdString(record.first);
instance_records_json.insert(key, vm_spec_to_json(record.second));
}
QDir data_dir{
mp::utils::backend_directory_path(config->data_directory, config->factory->get_backend_directory_name())};
MP_JSONUTILS.write_json(instance_records_json, data_dir.filePath(instance_db_name));
}
void mp::Daemon::release_resources(const std::string& instance)
{
config->vault->remove(instance);
config->factory->remove_resources_for(instance);
auto spec_it = vm_instance_specs.find(instance);
if (spec_it != cend(vm_instance_specs))
{
for (const auto& mac : mac_set_from(spec_it->second))
allocated_mac_addrs.erase(mac);
vm_instance_specs.erase(spec_it);
}
}
void mp::Daemon::create_vm(const CreateRequest* request,
grpc::ServerReaderWriterInterface<CreateReply, CreateRequest>* server,
std::promise<grpc::Status>* status_promise, bool start)
{
typedef typename std::pair<VirtualMachineDescription, ClientLaunchData> VMFullDescription;
auto checked_args = validate_create_arguments(request, config.get());
if (!checked_args.option_errors.error_codes().empty())
{
return status_promise->set_value(grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid arguments supplied",
checked_args.option_errors.SerializeAsString()));
}
else if (auto& nets = checked_args.nets_need_bridging; !nets.empty() && !request->permission_to_bridge())
{
CreateError create_error;
create_error.add_error_codes(CreateError::INVALID_NETWORK);
CreateReply reply;
*reply.mutable_nets_need_bridging() = {std::make_move_iterator(nets.begin()),
std::make_move_iterator(nets.end())}; /* this constructs a temporary
RepeatedPtrField from the range, then move-assigns that temporary in */
server->Write(reply);
return status_promise->set_value(
grpc::Status{grpc::StatusCode::FAILED_PRECONDITION, "Missing bridges", create_error.SerializeAsString()});
}
// TODO: We should only need to query the Blueprint Provider once for all info, so this (and timeout below) will
// need a refactoring to do so.
const std::string blueprint_name = config->blueprint_provider->name_from_blueprint(request->image());
auto name = name_from(checked_args.instance_name, blueprint_name, *config->name_generator, operative_instances);
auto [instance_trail, status] =
find_instance_and_react(operative_instances, deleted_instances, name, require_missing_instances_reaction);
assert(status.ok() == (instance_trail.index() == 2));
if (!status.ok())
return status_promise->set_value(status);
if (preparing_instances.find(name) != preparing_instances.end())
return status_promise->set_value(
{grpc::StatusCode::INVALID_ARGUMENT, fmt::format("instance \"{}\" is being prepared", name), ""});
if (!instances_running(operative_instances))
config->factory->hypervisor_health_check();
// TODO: We should only need to query the Blueprint Provider once for all info, so this (and name above) will
// need a refactoring to do so.
auto timeout = timeout_for(request->timeout(), config->blueprint_provider->blueprint_timeout(blueprint_name));
preparing_instances.insert(name);
auto prepare_future_watcher = new QFutureWatcher<VMFullDescription>();
auto log_level = mpl::level_from(request->verbosity_level());
QObject::connect(
prepare_future_watcher, &QFutureWatcher<VMFullDescription>::finished,
[this, server, status_promise, name, timeout, start, prepare_future_watcher, log_level] {
mpl::ClientLogger<CreateReply, CreateRequest> logger{log_level, *config->logger, server};
try
{
auto vm_desc_pair = prepare_future_watcher->future().result();
auto vm_desc = vm_desc_pair.first;
auto& vm_client_data = vm_desc_pair.second;
auto& vm_aliases = vm_client_data.aliases_to_be_created;
auto& vm_workspaces = vm_client_data.workspaces_to_be_created;
vm_instance_specs[name] = {vm_desc.num_cores,
vm_desc.mem_size,
vm_desc.disk_space,
vm_desc.default_mac_address,
vm_desc.extra_interfaces,
config->ssh_username,
VirtualMachine::State::off,
{},
false,
QJsonObject()};
operative_instances[name] =
config->factory->create_virtual_machine(vm_desc, *config->ssh_key_provider, *this);
preparing_instances.erase(name);
persist_instances();
if (start)
{
LaunchReply reply;
reply.set_create_message("Starting " + name);
server->Write(reply);
operative_instances[name]->start();
auto future_watcher = create_future_watcher([this, server, name, vm_aliases, vm_workspaces] {
LaunchReply reply;
reply.set_vm_instance_name(name);
config->update_prompt->populate_if_time_to_show(reply.mutable_update_info());
// Attach the aliases to be created by the CLI to the last message.
for (const auto& blueprint_alias : vm_aliases)
{
mpl::log(mpl::Level::debug, category,
fmt::format("Adding alias '{}' to RPC reply", blueprint_alias.first));
auto alias = reply.add_aliases_to_be_created();
alias->set_name(blueprint_alias.first);
alias->set_instance(blueprint_alias.second.instance);
alias->set_command(blueprint_alias.second.command);
alias->set_working_directory(blueprint_alias.second.working_directory);
}
// Now attach the workspaces.
for (const auto& blueprint_workspace : vm_workspaces)
{
mpl::log(mpl::Level::debug, category,
fmt::format("Adding workspace '{}' to RPC reply", blueprint_workspace));
reply.add_workspaces_to_be_created(blueprint_workspace);
}
server->Write(reply);
});
future_watcher->setFuture(
QtConcurrent::run(&Daemon::async_wait_for_ready_all<LaunchReply, LaunchRequest>,
this,
server,
std::vector<std::string>{name},
timeout,
status_promise,
std::string(),
std::string()));
}
else
{
status_promise->set_value(grpc::Status::OK);
}
}
catch (const std::exception& e)
{
preparing_instances.erase(name);
release_resources(name);
operative_instances.erase(name);
persist_instances();
status_promise->set_value(grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what(), ""));
}
delete prepare_future_watcher;
});
auto make_vm_description = [this, server, request, name, checked_args, log_level]() mutable -> VMFullDescription {
mpl::ClientLogger<CreateReply, CreateRequest> logger{log_level, *config->logger, server};
try
{
CreateReply reply;
reply.set_create_message("Creating " + name);
server->Write(reply);
Query query;
VirtualMachineDescription vm_desc{
request->num_cores(),
MemorySize{request->mem_size().empty() ? "0b" : request->mem_size()},
MemorySize{request->disk_space().empty() ? "0b" : request->disk_space()},
name,
"",
{},
config->ssh_username,
VMImage{},
"",
YAML::Node{},
YAML::Node{},
make_cloud_init_vendor_config(*config->ssh_key_provider, config->ssh_username,
config->factory->get_backend_version_string().toStdString(), request),
YAML::Node{}};
ClientLaunchData client_launch_data;
bool launch_from_blueprint{true};
try
{
auto image = request->image();
auto image_qstr = QString::fromStdString(image);
// If requesting to launch from a yaml file, we assume it contains a Blueprint.
if (image_qstr.startsWith("file://") &&
(image_qstr.toLower().endsWith(".yaml") || image_qstr.toLower().endsWith(".yml")))
{
auto file_info = QFileInfo(image_qstr.remove(0, 7));
auto file_path = file_info.absoluteFilePath();
auto chop = image_qstr.at(image_qstr.size() - 4) == '.' ? 4 : 5;
image = file_info.fileName().chopped(chop).toStdString();
query = config->blueprint_provider->blueprint_from_file(file_path.toStdString(), image, vm_desc,
client_launch_data);
}
else
{
query = config->blueprint_provider->fetch_blueprint_for(image, vm_desc, client_launch_data);
}
query.name = name;
// Aliases and default workspace are named in function of the instance name in the Blueprint. If the
// user asked for a different name, it will be necessary to change the alias definitions and the
// workspace name to reflect it.
if (name != image)
{
for (auto& alias_to_define : client_launch_data.aliases_to_be_created)
if (alias_to_define.second.instance == image)
{
mpl::log(mpl::Level::trace, category,
fmt::format("Renaming instance on alias \"{}\" from \"{}\" to \"{}\"",
alias_to_define.first, alias_to_define.second.instance, name));
alias_to_define.second.instance = name;
}
for (auto& workspace_to_create : client_launch_data.workspaces_to_be_created)
if (workspace_to_create == image)
{
mpl::log(mpl::Level::trace, category,
fmt::format("Renaming workspace \"{}\" to \"{}\"", workspace_to_create, name));
workspace_to_create = name;
}
}
}
catch (const std::out_of_range&)
{
// Blueprint not found, move on
launch_from_blueprint = false;
query = query_from(request, name);
vm_desc.mem_size = checked_args.mem_size;
}
auto progress_monitor = [server](int progress_type, int percentage) {
CreateReply create_reply;
create_reply.mutable_launch_progress()->set_percent_complete(std::to_string(percentage));
create_reply.mutable_launch_progress()->set_type((CreateProgress::ProgressTypes)progress_type);
return server->Write(create_reply);
};
auto prepare_action = [this, server, &name](const VMImage& source_image) -> VMImage {
CreateReply reply;
reply.set_create_message("Preparing image for " + name);
server->Write(reply);
return config->factory->prepare_source_image(source_image);
};
auto fetch_type = config->factory->fetch_type();
std::optional<std::string> checksum;
if (!vm_desc.image.id.empty())
checksum = vm_desc.image.id;
auto vm_image = config->vault->fetch_image(fetch_type,
query,
prepare_action,
progress_monitor,
launch_from_blueprint,
checksum,
config->factory->get_instance_directory(name));
const auto image_size = config->vault->minimum_image_size_for(vm_image.id);
vm_desc.disk_space = compute_final_image_size(
image_size, vm_desc.disk_space.in_bytes() > 0 ? vm_desc.disk_space : checked_args.disk_space,
config->data_directory);
reply.set_create_message("Configuring " + name);
server->Write(reply);
config->factory->prepare_networking(checked_args.extra_interfaces);
// This set stores the MAC's which need to be in the allocated_mac_addrs if everything goes well.
auto new_macs = allocated_mac_addrs;
// check for repetition of requested macs
for (auto& iface : checked_args.extra_interfaces)
if (!iface.mac_address.empty() && !new_macs.insert(iface.mac_address).second)
throw std::runtime_error(fmt::format("Repeated MAC address {}", iface.mac_address));
// generate missing macs in a second pass, to avoid repeating macs that the user requested
for (auto& iface : checked_args.extra_interfaces)
if (iface.mac_address.empty())
iface.mac_address = generate_unused_mac_address(new_macs);
vm_desc.default_mac_address = generate_unused_mac_address(new_macs);
vm_desc.extra_interfaces = checked_args.extra_interfaces;
vm_desc.meta_data_config = mpu::make_cloud_init_meta_config(name);
vm_desc.user_data_config = YAML::Load(request->cloud_init_user_data());
prepare_user_data(vm_desc.user_data_config, vm_desc.vendor_data_config);
if (vm_desc.num_cores < std::stoi(mp::min_cpu_cores))
vm_desc.num_cores = std::stoi(mp::default_cpu_cores);
vm_desc.network_data_config =
mpu::make_cloud_init_network_config(vm_desc.default_mac_address, checked_args.extra_interfaces);
vm_desc.image = vm_image;
config->factory->configure(vm_desc);
config->factory->prepare_instance_image(vm_image, vm_desc);
// Everything went well, add the MAC addresses used in this instance.
allocated_mac_addrs = std::move(new_macs);
return VMFullDescription{vm_desc, client_launch_data};
}
catch (const std::exception& e)
{
throw CreateImageException(e.what());
}
};
prepare_future_watcher->setFuture(QtConcurrent::run(make_vm_description));
}
bool mp::Daemon::delete_vm(InstanceTable::iterator vm_it, bool purge, DeleteReply& response)
{
auto& [name, instance] = *vm_it;
auto* erase_from = purge ? &deleted_instances : nullptr; // to begin with
auto instances_dirty = false;
if (!vm_instance_specs[name].deleted)
{
mpl::log(mpl::Level::debug, category, fmt::format("Deleting instance: {}", name));
erase_from = &operative_instances;
if (instance->current_state() == VirtualMachine::State::delayed_shutdown)
delayed_shutdown_instances.erase(name);
mounts[name].clear();
instance->shutdown(purge == true ? VirtualMachine::ShutdownPolicy::Poweroff
: VirtualMachine::ShutdownPolicy::Halt);
if (!purge)
{
vm_instance_specs[name].deleted = true;
deleted_instances[name] = std::move(instance);
instances_dirty = true;
mpl::log(mpl::Level::debug, category, fmt::format("Instance deleted: {}", name));
}
}
else
mpl::log(mpl::Level::debug, category, fmt::format("Instance is already deleted: {}", name));
if (purge)
{
response.add_purged_instances(name);
release_resources(name);
instances_dirty = true;
mpl::log(mpl::Level::debug, category, fmt::format("Instance purged: {}", name));
}
if (erase_from)
erase_from->erase(vm_it);
return instances_dirty;
}
grpc::Status mp::Daemon::reboot_vm(VirtualMachine& vm)
{
if (vm.state == VirtualMachine::State::delayed_shutdown)
delayed_shutdown_instances.erase(vm.vm_name);
if (!MP_UTILS.is_running(vm.current_state()))
return grpc::Status{grpc::StatusCode::INVALID_ARGUMENT,
fmt::format("Instance '{0}' is already running, but in an unknown state.\n"
"Try to stop and start it instead.",
vm.vm_name),
""};
mpl::log(mpl::Level::debug, category, fmt::format("Rebooting {}", vm.vm_name));
return ssh_reboot(vm);
}
grpc::Status mp::Daemon::shutdown_vm(VirtualMachine& vm, const std::chrono::milliseconds delay)
{
const auto& name = vm.vm_name;
delayed_shutdown_instances.erase(name);
auto stop_all_mounts = [this](const std::string& name) { stop_mounts(name); };
auto& shutdown_timer = delayed_shutdown_instances[name] =
std::make_unique<DelayedShutdownTimer>(&vm, stop_all_mounts);
QObject::connect(shutdown_timer.get(), &DelayedShutdownTimer::finished, [this, name]() {
delayed_shutdown_instances.erase(name);
});
shutdown_timer->start(delay);
return grpc::Status::OK;
}
grpc::Status mp::Daemon::switch_off_vm(VirtualMachine& vm)
{
const auto& name = vm.vm_name;
delayed_shutdown_instances.erase(name);
vm.shutdown(VirtualMachine::ShutdownPolicy::Poweroff);
return grpc::Status::OK;
}
grpc::Status mp::Daemon::cancel_vm_shutdown(const VirtualMachine& vm)
{
auto it = delayed_shutdown_instances.find(vm.vm_name);
if (it != delayed_shutdown_instances.end())
delayed_shutdown_instances.erase(it);
else
mpl::log(mpl::Level::debug, category,
fmt::format("no delayed shutdown to cancel on instance \"{}\"", vm.vm_name));
return grpc::Status::OK;
}
grpc::Status mp::Daemon::get_ssh_info_for_vm(VirtualMachine& vm, SSHInfoReply& response)
{
const auto& name = vm.vm_name;
if (vm.current_state() == VirtualMachine::State::unknown)
throw std::runtime_error("Cannot retrieve credentials in unknown state");
if (!MP_UTILS.is_running(vm.current_state()))
return grpc::Status{grpc::StatusCode::ABORTED, fmt::format("instance \"{}\" is not running", name)};
if (vm.state == VirtualMachine::State::delayed_shutdown &&
delayed_shutdown_instances[name]->get_time_remaining() <= std::chrono::minutes(1))
return grpc::Status{grpc::StatusCode::FAILED_PRECONDITION,
fmt::format("\"{}\" is scheduled to shut down in less than a minute, use "
"'multipass stop --cancel {}' to cancel the shutdown.",
name, name),
""};
mp::SSHInfo ssh_info;
ssh_info.set_host(vm.ssh_hostname());
ssh_info.set_port(vm.ssh_port());
ssh_info.set_priv_key_base64(config->ssh_key_provider->private_key_as_base64());
ssh_info.set_username(vm.ssh_username());
(*response.mutable_ssh_info())[name] = ssh_info;
return grpc::Status::OK;
}
void mp::Daemon::init_mounts(const std::string& name)
{
auto& vm_mounts = mounts[name];
auto& vm_spec_mounts = vm_instance_specs[name].mounts;
if (!create_missing_mounts(vm_spec_mounts, vm_mounts, operative_instances[name].get()))
persist_instances();
}
void mp::Daemon::stop_mounts(const std::string& name)
{
for (auto& [_, mount] : mounts[name])
{
if (!mount->is_mount_managed_by_backend())
{
mount->deactivate(/*force=*/true);
}
}
}
bool mp::Daemon::update_mounts(mp::VMSpecs& vm_specs,
std::unordered_map<std::string, mp::MountHandler::UPtr>& vm_mounts,
mp::VirtualMachine* vm)
{
auto& mount_specs = vm_specs.mounts;
return prune_obsolete_mounts(mount_specs, vm_mounts) || !create_missing_mounts(mount_specs, vm_mounts, vm);
}
bool mp::Daemon::create_missing_mounts(std::unordered_map<std::string, VMMount>& mount_specs,
std::unordered_map<std::string, mp::MountHandler::UPtr>& vm_mounts,
mp::VirtualMachine* vm)
{
auto initial_mount_count = mount_specs.size();
auto specs_it = mount_specs.begin();
while (specs_it != mount_specs.end()) // TODO@C++20 replace with erase_if over mount_specs
{
const auto& [target, mount_spec] = *specs_it;
if (vm_mounts.find(target) == vm_mounts.end())
{
try
{
vm_mounts[target] = make_mount(vm, target, mount_spec);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning,
category,
fmt::format(R"(Removing mount "{}" => "{}" from '{}': {})",
mount_spec.get_source_path(),
target,
vm->vm_name,
e.what()));
specs_it = mount_specs.erase(specs_it); // unordered_map so only iterators to erased element invalidated
continue;
}
}
++specs_it;
}
assert(mount_specs.size() <= initial_mount_count);
return mount_specs.size() != initial_mount_count;
}
mp::MountHandler::UPtr mp::Daemon::make_mount(VirtualMachine* vm, const std::string& target, const VMMount& mount)
{
return mount.get_mount_type() == VMMount::MountType::Classic
? std::make_unique<SSHFSMountHandler>(vm, config->ssh_key_provider.get(), target, mount)
: vm->make_native_mount_handler(target, mount);
}
QFutureWatcher<mp::Daemon::AsyncOperationStatus>*
mp::Daemon::create_future_watcher(std::function<void()> const& finished_op)
{
auto uuid = mp::utils::make_uuid().toStdString();
auto future_watcher = std::make_unique<QFutureWatcher<AsyncOperationStatus>>();
auto future_watcher_p = future_watcher.get();
async_future_watchers.insert({uuid, std::move(future_watcher)});
QObject::connect(future_watcher_p, &QFutureWatcher<AsyncOperationStatus>::finished, [this, uuid, finished_op] {
finished_op();
finish_async_operation(uuid);
});
return future_watcher_p;
}
template <typename Reply, typename Request>
error_string
mp::Daemon::async_wait_for_ssh_and_start_mounts_for(const std::string& name, const std::chrono::seconds& timeout,
grpc::ServerReaderWriterInterface<Reply, Request>* server)
{
fmt::memory_buffer errors;
try
{
auto it = operative_instances.find(name);
auto vm = it->second;
vm->wait_until_ssh_up(timeout);
if (std::is_same<Reply, LaunchReply>::value)
{
if (server)
{
Reply reply;
reply.set_reply_message("Waiting for initialization to complete");
server->Write(reply);
}
vm->wait_for_cloud_init(timeout);
}
if (MP_SETTINGS.get_as<bool>(mp::mounts_key))
{
std::vector<std::string> invalid_mounts;
fmt::memory_buffer warnings;
auto& vm_mounts = mounts[name];
for (auto& [target, mount] : vm_mounts)
try
{
if (!mount->is_mount_managed_by_backend())
{
mount->activate(server);
}
}
catch (const mp::SSHFSMissingError&)
{
add_fmt_to(errors, sshfs_error_template, name);
break;
}
catch (const std::exception& e)
{
auto msg = fmt::format("Removing mount \"{}\" from '{}': {}\n", target, name, e.what());
mpl::log(mpl::Level::warning, category, msg);
fmt::format_to(std::back_inserter(warnings), msg);
invalid_mounts.push_back(target);
}
auto& vm_spec_mounts = vm_instance_specs[name].mounts;
for (const auto& target : invalid_mounts)
{
vm_mounts.erase(target);
vm_spec_mounts.erase(target);
}
if (server && warnings.size() > 0)
{
Reply reply;
reply.set_log_line(fmt::to_string(warnings));
server->Write(reply);
}
persist_instances();
}
}
catch (const std::exception& e)
{
fmt::format_to(std::back_inserter(errors), e.what());
}
return fmt::to_string(errors);
}
template <typename Reply, typename Request>
mp::Daemon::AsyncOperationStatus
mp::Daemon::async_wait_for_ready_all(grpc::ServerReaderWriterInterface<Reply, Request>* server,
const std::vector<std::string>& vms,
const std::chrono::seconds& timeout,
std::promise<grpc::Status>* status_promise,
const std::string& start_errors,
const std::string& start_warnings)
{
QFutureSynchronizer<std::string> start_synchronizer;
{
std::lock_guard<decltype(start_mutex)> lock{start_mutex};
for (const auto& name : vms)
{
if (async_running_futures.find(name) != async_running_futures.end())
{
start_synchronizer.addFuture(async_running_futures[name]);
}
else
{
auto future = QtConcurrent::run(&Daemon::async_wait_for_ssh_and_start_mounts_for<Reply, Request>, this,
name, timeout, server);
async_running_futures[name] = future;
start_synchronizer.addFuture(future);
}
}
}
start_synchronizer.waitForFinished();
fmt::memory_buffer warnings;
fmt::format_to(std::back_inserter(warnings), "{}", start_warnings);
{
std::lock_guard<decltype(start_mutex)> lock{start_mutex};
for (const auto& name : vms)
{
async_running_futures.erase(name);
}
}
fmt::memory_buffer errors;
fmt::format_to(std::back_inserter(errors), "{}", start_errors);
for (const auto& future : start_synchronizer.futures())
if (auto error = future.result(); !error.empty())
add_fmt_to(errors, error);
if constexpr (std::is_same_v<Reply, StartReply> || std::is_same_v<Reply, RestartReply>)
{
if (server)
{
Reply reply;
config->update_prompt->populate_if_time_to_show(reply.mutable_update_info());
if (warnings.size() > 0)
{
reply.set_log_line(fmt::to_string(warnings));
}
server->Write(reply);
}
}
return {grpc_status_for(errors), status_promise};
}
void mp::Daemon::finish_async_operation(const std::string& async_future_key)
{
if (async_future_watchers.find(async_future_key) == async_future_watchers.end())
return;
auto async_op_result = async_future_watchers.at(async_future_key)->result();
async_future_watchers.erase(async_future_key);
if (!async_op_result.status.ok())
persist_instances();
if (async_op_result.status_promise)
async_op_result.status_promise->set_value(async_op_result.status);
}
void mp::Daemon::update_manifests_all(const bool is_force_update_from_network)
{
auto launch_update_manifests_from_vm_image_host =
[is_force_update_from_network](const std::unique_ptr<VMImageHost>& vm_image_host_ptr) -> void {
vm_image_host_ptr->update_manifests(is_force_update_from_network);
};
utils::parallel_for_each(config->image_hosts, launch_update_manifests_from_vm_image_host);
}
void mp::Daemon::wait_update_manifests_all_and_optionally_applied_force(const bool force_manifest_network_download)
{
update_manifests_all_task.wait_ongoing_task_finish();
if (force_manifest_network_download)
{
update_manifests_all_task.stop_timer();
mpl::log(mpl::Level::debug, "async task", "fetch manifest from the internet");
update_manifests_all(true);
update_manifests_all_task.start_timer();
}
}
template <typename Reply, typename Request>
void mp::Daemon::reply_msg(grpc::ServerReaderWriterInterface<Reply, Request>* server, std::string&& msg, bool sticky)
{
Reply reply{};
if (sticky)
reply.set_reply_message(fmt::format("{}\n", std::forward<decltype(msg)>(msg)));
else
reply.set_reply_message(std::forward<decltype(msg)>(msg));
server->Write(reply);
}
void mp::Daemon::populate_instance_info(VirtualMachine& vm,
mp::InfoReply& response,
bool no_runtime_info,
bool deleted,
bool& have_mounts)
{
auto* info = response.add_details();
auto instance_info = info->mutable_instance_info();
auto present_state = vm.current_state();
const auto& name = vm.vm_name;
info->set_name(name);
if (deleted)
info->mutable_instance_status()->set_status(mp::InstanceStatus::DELETED);
else
info->mutable_instance_status()->set_status(grpc_instance_status_for(present_state));
auto vm_image = fetch_image_for(name, *config->factory, *config->vault);
auto original_release = vm_image.original_release;
if (!vm_image.id.empty() && original_release.empty())
{
try
{
auto vm_image_info = config->image_hosts.back()->info_for_full_hash(vm_image.id);
original_release = vm_image_info.release_title.toStdString();
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("Cannot fetch image information: {}", e.what()));
}
}
try
{
instance_info->set_num_snapshots(vm.get_num_snapshots());
}
catch (const NotImplementedOnThisBackendException& e)
{
assert(std::string{e.what()}.find("snapshots") != std::string::npos); // TODO per-feature exception type instead
}
instance_info->set_image_release(original_release);
instance_info->set_id(vm_image.id);
auto vm_specs = vm_instance_specs[name];
auto mount_info = info->mutable_mount_info();
populate_mount_info(vm_specs.mounts, mount_info, have_mounts);
const auto created_time = QFileInfo{vm.instance_directory().path()}.birthTime();
auto timestamp = instance_info->mutable_creation_timestamp();
timestamp->set_seconds(created_time.toSecsSinceEpoch());
timestamp->set_nanos(created_time.time().msec() * 1'000'000);
if (!no_runtime_info && MP_UTILS.is_running(present_state))
RuntimeInstanceInfoHelper::populate_runtime_info(vm,
info,
instance_info,
original_release,
vm_specs.num_cores != 1);
}
bool mp::Daemon::is_instance_name_already_used(const std::string& instance_name)
{
return operative_instances.find(instance_name) != operative_instances.end() ||
deleted_instances.find(instance_name) != deleted_instances.end() ||
delayed_shutdown_instances.find(instance_name) != delayed_shutdown_instances.end() ||
preparing_instances.find(instance_name) != preparing_instances.end();
}
std::string mp::Daemon::generate_destination_instance_name_for_clone(const CloneRequest& request)
{
if (request.has_destination_name())
{
if (!mp::utils::valid_hostname(request.destination_name()))
{
throw mp::CloneInvalidNameException("Invalid destination instance name: " + request.destination_name());
}
if (is_instance_name_already_used(request.destination_name()))
{
throw mp::CloneInvalidNameException(request.destination_name() +
" already exists, please choose a new name.");
}
return request.destination_name();
}
else
{
const std::string& source_name = request.source_name();
const std::string destination_name =
generate_next_clone_name(vm_instance_specs[source_name].clone_count, source_name);
if (is_instance_name_already_used(destination_name))
{
throw mp::CloneInvalidNameException("auto-generated name " + destination_name +
" already exists, please specify a new name manually.");
}
return destination_name;
}
};
mp::VMSpecs mp::Daemon::clone_spec(const VMSpecs& src_vm_spec,
const std::string& src_name,
const std::string& dest_name)
{
mp::VMSpecs dest_vm_spec{src_vm_spec};
dest_vm_spec.clone_count = 0;
// update default mac addr and extra_interface mac addr
dest_vm_spec.default_mac_address = generate_unused_mac_address(allocated_mac_addrs);
for (auto& extra_interface : dest_vm_spec.extra_interfaces)
{
if (!extra_interface.mac_address.empty())
{
extra_interface.mac_address = generate_unused_mac_address(allocated_mac_addrs);
}
}
// non qemu snapshot files do not have metadata
if (!dest_vm_spec.metadata.isEmpty())
{
dest_vm_spec.metadata = MP_JSONUTILS
.update_unique_identifiers_of_metadata(QJsonValue{dest_vm_spec.metadata},
src_vm_spec,
dest_vm_spec,
src_name,
dest_name)
.toObject();
}
return dest_vm_spec;
}
bool mp::Daemon::is_bridged(const std::string& instance_name) const
{
return is_bridged_impl(vm_instance_specs.at(instance_name),
config->factory->networks(),
get_bridged_interface_name());
}
void mp::Daemon::add_bridged_interface(const std::string& instance_name)
{
mp::VMSpecs& specs = vm_instance_specs.at(instance_name);
mp::VirtualMachine::ShPtr instance = operative_instances.at(instance_name);
const auto& host_nets = config->factory->networks(); // This will throw if not implemented on this backend.
const auto& preferred_net = get_bridged_interface_name();
if (is_bridged_impl(specs, host_nets, preferred_net))
{
mpl::log(mpl::Level::warning, category, fmt::format("{} is already bridged", instance_name));
return;
}
if (const auto info = std::find_if(host_nets.cbegin(),
host_nets.cend(),
[preferred_net](const auto& i) { return i.id == preferred_net; });
info == host_nets.cend())
{
throw std::runtime_error(fmt::format(invalid_network_template, preferred_net, mp::bridged_interface_key));
}
else if (info->needs_authorization && !user_authorized_bridges.count(preferred_net))
{
throw mp::NonAuthorizedBridgeSettingsException("Cannot update instance settings", instance_name, preferred_net);
}
mp::NetworkInterface new_if{preferred_net, generate_unused_mac_address(allocated_mac_addrs), true};
mpl::log(mpl::Level::debug,
category,
fmt::format("New interface {{\"{}\", \"{}\", {}}}", new_if.id, new_if.mac_address, new_if.auto_mode));
// Add the new interface to the spec.
specs.extra_interfaces.push_back(new_if);
mpl::log(mpl::Level::trace, category, "Prepare networking");
config->factory->prepare_networking(specs.extra_interfaces);
new_if = specs.extra_interfaces.back(); // prepare_networking can modify the id of the new interface.
mpl::log(mpl::Level::trace, category, fmt::format("Done preparation, new interface id is now \"{}\"", new_if.id));
// Add the new interface to the VM.
mpl::log(mpl::Level::trace, category, "Adding new interface to instance");
try
{
instance->add_network_interface(specs.extra_interfaces.size() - 1, specs.default_mac_address, new_if);
mpl::log(mpl::Level::trace, category, "Done adding");
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::debug, category, "Failure adding interface to instance, rolling back");
specs.extra_interfaces.pop_back();
throw mp::BridgeFailureException("Cannot update instance settings", instance_name, preferred_net);
}
}
| 155,074
|
C++
|
.cpp
| 3,229
| 36.701146
| 120
| 0.594459
|
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,768
|
default_vm_image_vault.cpp
|
canonical_multipass/src/daemon/default_vm_image_vault.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 "default_vm_image_vault.h"
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/create_image_exception.h>
#include <multipass/exceptions/image_vault_exceptions.h>
#include <multipass/exceptions/unsupported_image_exception.h>
#include <multipass/json_utils.h>
#include <multipass/logging/log.h>
#include <multipass/platform.h>
#include <multipass/process/qemuimg_process_spec.h>
#include <multipass/query.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <multipass/vm_image.h>
#include <multipass/xz_image_decoder.h>
#include <multipass/format.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>
#include <QtConcurrent/QtConcurrent>
#include <exception>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "image vault";
constexpr auto instance_db_name = "multipassd-instance-image-records.json";
constexpr auto image_db_name = "multipassd-image-records.json";
auto query_to_json(const mp::Query& query)
{
QJsonObject json;
json.insert("release", QString::fromStdString(query.release));
json.insert("persistent", query.persistent);
json.insert("remote_name", QString::fromStdString(query.remote_name));
json.insert("query_type", static_cast<int>(query.query_type));
return json;
}
auto image_to_json(const mp::VMImage& image)
{
QJsonObject json;
json.insert("path", image.image_path);
json.insert("id", QString::fromStdString(image.id));
json.insert("original_release", QString::fromStdString(image.original_release));
json.insert("current_release", QString::fromStdString(image.current_release));
json.insert("release_date", QString::fromStdString(image.release_date));
QJsonArray aliases;
for (const auto& alias : image.aliases)
{
QJsonObject alias_entry;
alias_entry.insert("alias", QString::fromStdString(alias));
aliases.append(alias_entry);
}
json.insert("aliases", aliases);
return json;
}
auto record_to_json(const mp::VaultRecord& record)
{
QJsonObject json;
json.insert("image", image_to_json(record.image));
json.insert("query", query_to_json(record.query));
json.insert("last_accessed", static_cast<qint64>(record.last_accessed.time_since_epoch().count()));
return json;
}
std::unordered_map<std::string, mp::VaultRecord> load_db(const QString& db_name)
{
QFile db_file{db_name};
auto opened = db_file.open(QIODevice::ReadOnly);
if (!opened)
return {};
QJsonParseError parse_error;
auto doc = QJsonDocument::fromJson(db_file.readAll(), &parse_error);
if (doc.isNull())
return {};
auto records = doc.object();
if (records.isEmpty())
return {};
std::unordered_map<std::string, mp::VaultRecord> reconstructed_records;
for (auto it = records.constBegin(); it != records.constEnd(); ++it)
{
auto key = it.key().toStdString();
auto record = it.value().toObject();
if (record.isEmpty())
return {};
auto image = record["image"].toObject();
if (image.isEmpty())
return {};
auto image_path = image["path"].toString();
if (image_path.isNull())
return {};
auto image_id = image["id"].toString().toStdString();
auto original_release = image["original_release"].toString().toStdString();
auto current_release = image["current_release"].toString().toStdString();
auto release_date = image["release_date"].toString().toStdString();
std::vector<std::string> aliases;
for (QJsonValueRef entry : image["aliases"].toArray())
{
auto alias = entry.toObject()["alias"].toString().toStdString();
aliases.push_back(alias);
}
auto query = record["query"].toObject();
if (query.isEmpty())
return {};
auto release = query["release"].toString();
auto persistent = query["persistent"];
if (!persistent.isBool())
return {};
auto remote_name = query["remote_name"].toString();
auto query_type = static_cast<mp::Query::Type>(query["type"].toInt());
std::chrono::system_clock::time_point last_accessed;
auto last_accessed_count = static_cast<qint64>(record["last_accessed"].toDouble());
if (last_accessed_count == 0)
{
last_accessed = std::chrono::system_clock::now();
}
else
{
auto duration = std::chrono::system_clock::duration(last_accessed_count);
last_accessed = std::chrono::system_clock::time_point(duration);
}
reconstructed_records[key] = {
{image_path, image_id, original_release, current_release, release_date, aliases},
{"", release.toStdString(), persistent.toBool(), remote_name.toStdString(), query_type},
last_accessed};
}
return reconstructed_records;
}
void remove_source_images(const mp::VMImage& source_image, const mp::VMImage& prepared_image)
{
// The prepare phase may have been a no-op, check and only remove source images
if (source_image.image_path != prepared_image.image_path)
mp::vault::delete_file(source_image.image_path);
}
void delete_image_dir(const mp::Path& image_path)
{
QFileInfo image_file{image_path};
if (image_file.exists())
{
if (image_file.isDir())
QDir(image_path).removeRecursively();
else
image_file.dir().removeRecursively();
}
}
mp::MemorySize get_image_size(const mp::Path& image_path)
{
QStringList qemuimg_parameters{{"info", image_path}};
auto qemuimg_process =
mp::platform::make_process(std::make_unique<mp::QemuImgProcessSpec>(qemuimg_parameters, image_path));
auto process_state = qemuimg_process->execute();
if (!process_state.completed_successfully())
{
throw std::runtime_error(fmt::format("Cannot get image info: qemu-img failed ({}) with output:\n{}",
process_state.failure_message(),
qemuimg_process->read_all_standard_error()));
}
const auto img_info = QString{qemuimg_process->read_all_standard_output()};
const auto pattern = QStringLiteral("^virtual size: .+ \\((?<size>\\d+) bytes\\)\r?$");
const auto re = QRegularExpression{pattern, QRegularExpression::MultilineOption};
mp::MemorySize image_size{};
const auto match = re.match(img_info);
if (match.hasMatch())
{
image_size = mp::MemorySize(match.captured("size").toStdString());
}
else
{
throw std::runtime_error{"Could not obtain image's virtual size"};
}
return image_size;
}
template <typename T>
void persist_records(const T& records, const QString& path)
{
QJsonObject json_records;
for (const auto& record : records)
{
auto key = QString::fromStdString(record.first);
json_records.insert(key, record_to_json(record.second));
}
MP_JSONUTILS.write_json(json_records, path);
}
} // namespace
mp::DefaultVMImageVault::DefaultVMImageVault(std::vector<VMImageHost*> image_hosts,
URLDownloader* downloader,
const mp::Path& cache_dir_path,
const mp::Path& data_dir_path,
const mp::days& days_to_expire)
: BaseVMImageVault{image_hosts},
url_downloader{downloader},
cache_dir{QDir(cache_dir_path).filePath("vault")},
data_dir{QDir(data_dir_path).filePath("vault")},
images_dir(cache_dir.filePath("images")),
days_to_expire{days_to_expire},
prepared_image_records{load_db(cache_dir.filePath(image_db_name))},
instance_image_records{load_db(data_dir.filePath(instance_db_name))}
{
}
mp::DefaultVMImageVault::~DefaultVMImageVault()
{
url_downloader->abort_all_downloads();
}
mp::VMImage mp::DefaultVMImageVault::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 mp::Path& save_dir)
{
{
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
auto name_entry = instance_image_records.find(query.name);
if (name_entry != instance_image_records.end())
{
const auto& record = name_entry->second;
return record.image;
}
}
if (!unlock && query.query_type != Query::Type::Alias && !MP_PLATFORM.is_image_url_supported())
throw std::runtime_error(fmt::format("http and file based images are not supported"));
if (query.query_type == Query::Type::LocalFile)
{
QUrl image_url(QString::fromStdString(query.release));
VMImage source_image, vm_image;
if (!QFile::exists(image_url.path()))
throw std::runtime_error(fmt::format("Custom image `{}` does not exist.", image_url.path()));
source_image.image_path = image_url.path();
if (source_image.image_path.endsWith(".xz"))
{
source_image.image_path = extract_image_from(source_image, monitor, save_dir);
}
else
{
source_image = image_instance_from(source_image, save_dir);
}
vm_image = prepare(source_image);
vm_image.id = mp::vault::compute_image_hash(vm_image.image_path).toStdString();
remove_source_images(source_image, vm_image);
{
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
instance_image_records[query.name] = {vm_image, query, std::chrono::system_clock::now()};
persist_instance_records();
}
return vm_image;
}
else
{
std::string id;
std::optional<VMImage> source_image{std::nullopt};
QFuture<VMImage> future;
if (query.query_type == Query::Type::HttpDownload)
{
QUrl image_url(QString::fromStdString(query.release));
// If no checksum given, generate a sha256 hash based on the URL and use that for the id
id =
checksum
? *checksum
: QCryptographicHash::hash(query.release.c_str(), QCryptographicHash::Sha256).toHex().toStdString();
auto last_modified = url_downloader->last_modified(image_url);
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
auto entry = prepared_image_records.find(id);
if (entry != prepared_image_records.end())
{
auto& record = entry->second;
if (last_modified.isValid() && (last_modified.toString().toStdString() == record.image.release_date))
{
return finalize_image_records(query, record.image, id, save_dir);
}
}
auto running_future = get_image_future(id);
if (running_future)
{
monitor(LaunchProgress::WAITING, -1);
future = *running_future;
}
else
{
const VMImageInfo info{{},
{},
{},
{},
{},
true,
image_url.url(),
QString::fromStdString(id),
{},
last_modified.toString(),
0,
checksum.has_value()};
const auto image_filename = mp::vault::filename_for(image_url.path());
// Attempt to make a sane directory name based on the filename of the image
const auto image_dir_name =
QString("%1-%2").arg(image_filename.section(".", 0, image_filename.endsWith(".xz") ? -3 : -2),
QLocale::c().toString(last_modified, "yyyyMMdd"));
const auto image_dir = MP_UTILS.make_dir(images_dir, image_dir_name);
// Had to use std::bind here to workaround the 5 allowable function arguments constraint of
// QtConcurrent::run()
future = QtConcurrent::run(std::bind(&DefaultVMImageVault::download_and_prepare_source_image, this,
info, source_image, image_dir, fetch_type, prepare, monitor));
in_progress_image_fetches[id] = future;
}
}
else
{
const auto info = info_for(query);
if (!info)
throw mp::ImageNotFoundException(query.release, query.remote_name);
id = info->id.toStdString();
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
if (!query.name.empty())
{
for (auto& record : prepared_image_records)
{
if (record.second.query.remote_name != query.remote_name)
continue;
const auto aliases = record.second.image.aliases;
if (id == record.first ||
std::find(aliases.cbegin(), aliases.cend(), query.release) != aliases.cend())
{
const auto prepared_image = record.second.image;
try
{
return finalize_image_records(query, prepared_image, record.first, save_dir);
}
catch (const std::exception& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Cannot create instance image: {}", e.what()));
break;
}
}
}
}
auto running_future = get_image_future(id);
if (running_future)
{
monitor(LaunchProgress::WAITING, -1);
future = *running_future;
}
else
{
const auto image_dir =
MP_UTILS.make_dir(images_dir, QString("%1-%2").arg(info->release).arg(info->version));
// Had to use std::bind here to workaround the 5 allowable function arguments constraint of
// QtConcurrent::run()
future = QtConcurrent::run(std::bind(&DefaultVMImageVault::download_and_prepare_source_image, this,
*info, source_image, image_dir, fetch_type, prepare, monitor));
in_progress_image_fetches[id] = future;
}
}
try
{
auto prepared_image = future.result();
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
in_progress_image_fetches.erase(id);
return finalize_image_records(query, prepared_image, id, save_dir);
}
catch (const std::exception&)
{
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
in_progress_image_fetches.erase(id);
throw;
}
}
}
void mp::DefaultVMImageVault::remove(const std::string& name)
{
const auto& name_entry = instance_image_records.find(name);
if (name_entry == instance_image_records.end())
return;
instance_image_records.erase(name);
persist_instance_records();
}
bool mp::DefaultVMImageVault::has_record_for(const std::string& name)
{
return instance_image_records.find(name) != instance_image_records.end();
}
void mp::DefaultVMImageVault::prune_expired_images()
{
std::vector<decltype(prepared_image_records)::key_type> expired_keys;
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
for (const auto& record : prepared_image_records)
{
// Expire source images if they aren't persistent and haven't been accessed in 14 days
if (record.second.query.query_type == Query::Type::Alias && !record.second.query.persistent &&
record.second.last_accessed + days_to_expire <= std::chrono::system_clock::now())
{
mpl::log(
mpl::Level::info, category,
fmt::format("Source image {} is expired. Removing it from the cache.", record.second.query.release));
expired_keys.push_back(record.first);
delete_image_dir(record.second.image.image_path);
}
}
// Remove any image directories that have no corresponding database entry
for (const auto& entry : images_dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot))
{
if (std::find_if(prepared_image_records.cbegin(), prepared_image_records.cend(),
[&entry](const std::pair<std::string, VaultRecord>& record) {
return record.second.image.image_path.contains(entry.absoluteFilePath());
}) == prepared_image_records.cend())
{
mpl::log(mpl::Level::info, category,
fmt::format("Source image {} is no longer valid. Removing it from the cache.",
entry.absoluteFilePath()));
delete_image_dir(entry.absoluteFilePath());
}
}
for (const auto& key : expired_keys)
prepared_image_records.erase(key);
persist_image_records();
}
void mp::DefaultVMImageVault::update_images(const FetchType& fetch_type, const PrepareAction& prepare,
const ProgressMonitor& monitor)
{
mpl::log(mpl::Level::debug, category, "Checking for images to update…");
std::vector<decltype(prepared_image_records)::key_type> keys_to_update;
for (const auto& record : prepared_image_records)
{
if (record.second.query.query_type == Query::Type::Alias &&
record.first.compare(0, record.second.query.release.length(), record.second.query.release) != 0)
{
try
{
auto info = info_for(record.second.query);
if (!info)
throw mp::ImageNotFoundException(record.second.query.release, record.second.query.remote_name);
if (info->id.toStdString() != record.first)
{
keys_to_update.push_back(record.first);
}
}
catch (const mp::UnsupportedImageException& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("Skipping update: {}", e.what()));
}
catch (const mp::ImageNotFoundException& e)
{
mpl::log(mpl::Level::warning, category, fmt::format("Skipping update: {}", e.what()));
}
}
}
for (const auto& key : keys_to_update)
{
const auto& record = prepared_image_records[key];
mpl::log(mpl::Level::info, category, fmt::format("Updating {} source image to latest", record.query.release));
try
{
fetch_image(fetch_type,
record.query,
prepare,
monitor,
false,
std::nullopt,
QFileInfo{record.image.image_path}.absolutePath());
// Remove old image
std::lock_guard<decltype(fetch_mutex)> lock{fetch_mutex};
delete_image_dir(record.image.image_path);
prepared_image_records.erase(key);
persist_image_records();
}
catch (const CreateImageException& e)
{
mpl::log(mpl::Level::warning, category,
fmt::format("Cannot update source image {}: {}", record.query.release, e.what()));
}
}
}
mp::MemorySize mp::DefaultVMImageVault::minimum_image_size_for(const std::string& id)
{
auto prepared_image_entry = prepared_image_records.find(id);
if (prepared_image_entry != prepared_image_records.end())
{
const auto& record = prepared_image_entry->second;
return get_image_size(record.image.image_path);
}
for (const auto& instance_image_entry : instance_image_records)
{
const auto& record = instance_image_entry.second;
if (record.image.id == id)
{
return get_image_size(record.image.image_path);
}
}
throw std::runtime_error(fmt::format("Cannot determine minimum image size for id \'{}\'", id));
}
void mp::DefaultVMImageVault::clone(const std::string& source_instance_name,
const std::string& destination_instance_name)
{
const auto source_iter = instance_image_records.find(source_instance_name);
if (source_iter == instance_image_records.end())
{
throw std::runtime_error(source_instance_name + " does not exist in the image records");
}
if (instance_image_records.find(destination_instance_name) != instance_image_records.end())
{
throw std::runtime_error(destination_instance_name + " already exists in the image records");
}
auto& dest_vault_record = instance_image_records[destination_instance_name] =
instance_image_records[source_instance_name];
// string replacement is "instances/<src_name>"->"instances/<dest_name>" instead of
// "<src_name>"->"<dest_name>", because the second one might match other substrings of the metadata.
dest_vault_record.image.image_path.replace("instances/" + QString{source_instance_name.c_str()},
"instances/" + QString{destination_instance_name.c_str()});
persist_instance_records();
}
mp::VMImage mp::DefaultVMImageVault::download_and_prepare_source_image(
const VMImageInfo& info, std::optional<VMImage>& existing_source_image, const QDir& image_dir,
const FetchType& fetch_type, const PrepareAction& prepare, const ProgressMonitor& monitor)
{
VMImage source_image;
auto id = info.id;
if (existing_source_image)
{
source_image = *existing_source_image;
}
else
{
source_image.id = id.toStdString();
source_image.image_path = image_dir.filePath(mp::vault::filename_for(info.image_location));
source_image.original_release = info.release_title.toStdString();
source_image.release_date = info.version.toStdString();
for (const auto& alias : info.aliases)
{
source_image.aliases.push_back(alias.toStdString());
}
}
mp::vault::DeleteOnException image_file{source_image.image_path};
try
{
url_downloader->download_to(info.image_location, source_image.image_path, info.size, LaunchProgress::IMAGE,
monitor);
if (info.verify)
{
mpl::log(mpl::Level::debug, category, fmt::format("Verifying hash \"{}\"", id));
monitor(LaunchProgress::VERIFY, -1);
mp::vault::verify_image_download(source_image.image_path, id);
}
if (source_image.image_path.endsWith(".xz"))
{
source_image.image_path = mp::vault::extract_image(source_image.image_path, monitor, true);
}
auto prepared_image = prepare(source_image);
remove_source_images(source_image, prepared_image);
return prepared_image;
}
catch (const AbortedDownloadException&)
{
throw;
}
catch (const std::exception& e)
{
throw CreateImageException(e.what());
}
}
QString mp::DefaultVMImageVault::extract_image_from(const VMImage& source_image,
const ProgressMonitor& monitor,
const mp::Path& dest_dir)
{
MP_UTILS.make_dir(dest_dir);
QFileInfo file_info{source_image.image_path};
const auto image_name = file_info.fileName().remove(".xz");
const auto image_path = QDir(dest_dir).filePath(image_name);
return mp::vault::extract_image(image_path, monitor);
}
mp::VMImage mp::DefaultVMImageVault::image_instance_from(const VMImage& prepared_image, const mp::Path& dest_dir)
{
MP_UTILS.make_dir(dest_dir);
return {mp::vault::copy(prepared_image.image_path, dest_dir),
prepared_image.id,
prepared_image.original_release,
prepared_image.current_release,
prepared_image.release_date,
{}};
}
std::optional<QFuture<mp::VMImage>> mp::DefaultVMImageVault::get_image_future(const std::string& id)
{
auto it = in_progress_image_fetches.find(id);
if (it != in_progress_image_fetches.end())
{
return it->second;
}
return std::nullopt;
}
mp::VMImage mp::DefaultVMImageVault::finalize_image_records(const Query& query,
const VMImage& prepared_image,
const std::string& id,
const mp::Path& dest_dir)
{
VMImage vm_image;
if (!query.name.empty())
{
vm_image = image_instance_from(prepared_image, dest_dir);
instance_image_records[query.name] = {vm_image, query, std::chrono::system_clock::now()};
}
// Do not save the instance name for prepared images
Query prepared_query{query};
prepared_query.name = "";
prepared_image_records[id] = {prepared_image, prepared_query, std::chrono::system_clock::now()};
persist_instance_records();
persist_image_records();
return vm_image;
}
void mp::DefaultVMImageVault::persist_instance_records()
{
persist_records(instance_image_records, data_dir.filePath(instance_db_name));
}
void mp::DefaultVMImageVault::persist_image_records()
{
persist_records(prepared_image_records, cache_dir.filePath(image_db_name));
}
| 27,303
|
C++
|
.cpp
| 628
| 32.81051
| 120
| 0.592781
|
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,769
|
common_image_host.cpp
|
canonical_multipass/src/daemon/common_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 "common_image_host.h"
#include <multipass/logging/log.h>
#include <multipass/format.h>
#include <multipass/platform.h>
#include <multipass/exceptions/unsupported_alias_exception.h>
#include <multipass/exceptions/unsupported_remote_exception.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace
{
constexpr auto category = "VMImageHost";
}
void mp::CommonVMImageHost::for_each_entry_do(const Action& action)
{
for_each_entry_do_impl(action);
}
auto mp::CommonVMImageHost::info_for_full_hash(const std::string& full_hash) -> VMImageInfo
{
return info_for_full_hash_impl(full_hash);
}
void mp::CommonVMImageHost::update_manifests(const bool is_force_update_from_network)
{
clear();
fetch_manifests(is_force_update_from_network);
}
void mp::CommonVMImageHost::on_manifest_empty(const std::string& details)
{
mpl::log(mpl::Level::info, category, details);
}
void mp::CommonVMImageHost::on_manifest_update_failure(const std::string& details)
{
mpl::log(mpl::Level::warning, category, fmt::format("Could not update manifest: {}", details));
}
void mp::CommonVMImageHost::check_remote_is_supported(const std::string& remote_name) const
{
if (!MP_PLATFORM.is_remote_supported(remote_name))
throw mp::UnsupportedRemoteException(
fmt::format("Remote \'{}\' is not a supported remote for this platform. Please use "
"`multipass find` for supported remotes and images.",
remote_name));
}
void mp::CommonVMImageHost::check_alias_is_supported(const std::string& alias, const std::string& remote_name) const
{
if (!MP_PLATFORM.is_alias_supported(alias, remote_name))
throw mp::UnsupportedAliasException(fmt::format(
"\'{}\' is not a supported alias. Please use `multipass find` for supported image aliases.", alias));
}
bool mp::CommonVMImageHost::alias_verifies_image_is_supported(const QStringList& aliases,
const std::string& remote_name) const
{
return aliases.empty() || std::any_of(aliases.cbegin(), aliases.cend(), [&remote_name](const auto& alias) {
return MP_PLATFORM.is_alias_supported(alias.toStdString(), remote_name);
});
}
| 2,906
|
C++
|
.cpp
| 70
| 37.071429
| 116
| 0.714033
|
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,770
|
daemon_main.cpp
|
canonical_multipass/src/daemon/daemon_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 "daemon.h"
#include "daemon_config.h"
#include "daemon_init_settings.h"
#include "cli.h"
#include <multipass/auto_join_thread.h>
#include <multipass/constants.h>
#include <multipass/logging/log.h>
#include <multipass/platform_unix.h>
#include <multipass/top_catch_all.h>
#include <multipass/utils.h>
#include <multipass/version.h>
#include <multipass/format.h>
#include <QCoreApplication>
#include <csignal>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpp = multipass::platform;
namespace
{
class UnixSignalHandler
{
public:
UnixSignalHandler()
: signal_handling_thread{
[this, sigs = mpp::make_and_block_signals({SIGTERM, SIGINT, SIGUSR1})] { monitor_signals(sigs); }}
{
}
~UnixSignalHandler()
{
pthread_kill(signal_handling_thread.thread.native_handle(), SIGUSR1);
}
void monitor_signals(sigset_t sigset)
{
int sig = -1;
sigwait(&sigset, &sig);
if (sig != SIGUSR1)
mpl::log(mpl::Level::info, "daemon", fmt::format("Received signal {} ({})", sig, strsignal(sig)));
QCoreApplication::quit();
}
private:
mp::AutoJoinThread signal_handling_thread;
};
int main_impl(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName(mp::daemon_name);
QCoreApplication::setApplicationVersion(mp::version_string);
UnixSignalHandler handler;
mp::daemon::register_global_settings_handlers();
auto builder = mp::cli::parse(app);
auto config = builder.build();
auto server_address = config->server_address;
mp::daemon::monitor_and_quit_on_settings_change(); // TODO replace with async restart in relevant settings handlers
mp::Daemon daemon(std::move(config));
QObject::connect(&app,
&QCoreApplication::aboutToQuit,
&daemon,
&mp::Daemon::shutdown_grpc_server,
Qt::DirectConnection);
mpl::log(mpl::Level::info, "daemon", fmt::format("Starting Multipass {}", mp::version_string));
mpl::log(mpl::Level::info, "daemon", fmt::format("Daemon arguments: {}", app.arguments().join(" ")));
auto ret = QCoreApplication::exec();
mpl::log(mpl::Level::info, "daemon", "Goodbye!");
return ret;
}
} // namespace
int main(int argc, char* argv[])
{
return mp::top_catch_all("daemon", /* fallback_return = */ EXIT_FAILURE, main_impl, argc, argv);
}
| 3,102
|
C++
|
.cpp
| 86
| 31.581395
| 119
| 0.688021
|
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.